codesign-mcp-next 0.3.3 → 0.3.5
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/CHANGELOG.md +24 -0
- package/README.md +14 -10
- package/dist/browser/manager.js +3 -0
- package/dist/codesign/errors.js +4 -0
- package/dist/codesign/verify.js +495 -0
- package/dist/codesign/visual-diff.js +150 -0
- package/dist/mcp/result.js +40 -0
- package/dist/prompts/design-to-code.js +7 -4
- package/dist/resources/workflow.js +6 -4
- package/dist/server.js +4 -0
- package/dist/tools/slices.js +56 -3
- package/dist/tools/verify-rendering.js +175 -0
- package/dist/tools/visual-diff.js +292 -0
- package/package.json +6 -3
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
// visual_diff 的核心纯函数:图片解码、按比例对齐、像素差分、相似度分数与差异热区。
|
|
2
|
+
// 不接触浏览器和文件系统,便于单测。所有期望尺寸由调用方(MCP 工具)从 platformSpec 重建后传入。
|
|
3
|
+
import { PNG } from 'pngjs';
|
|
4
|
+
import pixelmatch from 'pixelmatch';
|
|
5
|
+
import { CodesignError } from './errors.js';
|
|
6
|
+
const DIFF_COLOR = [255, 0, 0];
|
|
7
|
+
export function decodePng(buf) {
|
|
8
|
+
const png = PNG.sync.read(buf);
|
|
9
|
+
return { width: png.width, height: png.height, data: Uint8Array.from(png.data) };
|
|
10
|
+
}
|
|
11
|
+
export function encodePng(image) {
|
|
12
|
+
const png = new PNG({ width: image.width, height: image.height });
|
|
13
|
+
png.data = Buffer.from(image.data);
|
|
14
|
+
return PNG.sync.write(png);
|
|
15
|
+
}
|
|
16
|
+
// 双线性缩放,保证 2x 预览图缩到 CSS 尺寸后仍可做逐像素比对。
|
|
17
|
+
export function resizeRgba(src, targetWidth, targetHeight) {
|
|
18
|
+
const sw = src.width;
|
|
19
|
+
const sh = src.height;
|
|
20
|
+
const out = new Uint8Array(targetWidth * targetHeight * 4);
|
|
21
|
+
for (let y = 0; y < targetHeight; y += 1) {
|
|
22
|
+
const sy = ((y + 0.5) * sh) / targetHeight - 0.5;
|
|
23
|
+
const y0 = clampIndex(Math.floor(sy), sh);
|
|
24
|
+
const y1 = clampIndex(y0 + 1, sh);
|
|
25
|
+
const fy = Math.min(1, Math.max(0, sy - y0));
|
|
26
|
+
for (let x = 0; x < targetWidth; x += 1) {
|
|
27
|
+
const sx = ((x + 0.5) * sw) / targetWidth - 0.5;
|
|
28
|
+
const x0 = clampIndex(Math.floor(sx), sw);
|
|
29
|
+
const x1 = clampIndex(x0 + 1, sw);
|
|
30
|
+
const fx = Math.min(1, Math.max(0, sx - x0));
|
|
31
|
+
for (let c = 0; c < 4; c += 1) {
|
|
32
|
+
const top = lerp(src.data[(y0 * sw + x0) * 4 + c], src.data[(y0 * sw + x1) * 4 + c], fx);
|
|
33
|
+
const bottom = lerp(src.data[(y1 * sw + x0) * 4 + c], src.data[(y1 * sw + x1) * 4 + c], fx);
|
|
34
|
+
out[(y * targetWidth + x) * 4 + c] = Math.round(lerp(top, bottom, fy));
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return { width: targetWidth, height: targetHeight, data: out };
|
|
39
|
+
}
|
|
40
|
+
function clampIndex(value, size) {
|
|
41
|
+
return Math.min(size - 1, Math.max(0, value));
|
|
42
|
+
}
|
|
43
|
+
function lerp(a, b, t) {
|
|
44
|
+
return a + (b - a) * t;
|
|
45
|
+
}
|
|
46
|
+
function aspect(width, height) {
|
|
47
|
+
return width / height;
|
|
48
|
+
}
|
|
49
|
+
// 对齐失败必须显式报错,不能用缩放后看似合理的低分误导用户。
|
|
50
|
+
function assertAligned(design, render, target, drift) {
|
|
51
|
+
const targetAr = aspect(target.width, target.height);
|
|
52
|
+
const candidates = [
|
|
53
|
+
['design preview', design],
|
|
54
|
+
['rendered screenshot', render],
|
|
55
|
+
];
|
|
56
|
+
for (const [label, image] of candidates) {
|
|
57
|
+
const actualAr = aspect(image.width, image.height);
|
|
58
|
+
const relativeDrift = Math.abs(actualAr - targetAr) / targetAr;
|
|
59
|
+
if (relativeDrift > drift) {
|
|
60
|
+
throw new CodesignError('VISUAL_DIFF_ALIGNMENT', 'image aspect ratio differs from the artboard viewport', {
|
|
61
|
+
target,
|
|
62
|
+
relativeDrift: Number(relativeDrift.toFixed(4)),
|
|
63
|
+
image: { label, width: image.width, height: image.height },
|
|
64
|
+
hint: 'Make sure the screenshot uses the artboard viewport and the correct screen is selected.',
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
export function compareImages(design, render, target, options = {}) {
|
|
70
|
+
const threshold = options.threshold ?? 0.1;
|
|
71
|
+
const drift = options.maxAspectRatioDrift ?? 0.05;
|
|
72
|
+
const gridCols = options.gridCols ?? 8;
|
|
73
|
+
const gridRows = options.gridRows ?? 8;
|
|
74
|
+
const maxHotspots = options.maxHotspots ?? 6;
|
|
75
|
+
assertAligned(design, render, target, drift);
|
|
76
|
+
const designScaled = design.width !== target.width || design.height !== target.height;
|
|
77
|
+
const renderScaled = render.width !== target.width || render.height !== target.height;
|
|
78
|
+
const designAligned = designScaled ? resizeRgba(design, target.width, target.height) : design;
|
|
79
|
+
const renderAligned = renderScaled ? resizeRgba(render, target.width, target.height) : render;
|
|
80
|
+
const includeDiffImage = options.includeDiffImage !== false;
|
|
81
|
+
const diffData = includeDiffImage ? new Uint8Array(target.width * target.height * 4) : null;
|
|
82
|
+
const diffPixels = pixelmatch(designAligned.data, renderAligned.data, diffData, target.width, target.height, { threshold, diffColor: [...DIFF_COLOR], includeAA: false });
|
|
83
|
+
const totalPixels = target.width * target.height;
|
|
84
|
+
const hotspots = diffData
|
|
85
|
+
? collectHotspots(diffData, target.width, target.height, gridCols, gridRows, maxHotspots)
|
|
86
|
+
: [];
|
|
87
|
+
return {
|
|
88
|
+
score: Number((1 - diffPixels / totalPixels).toFixed(4)),
|
|
89
|
+
diffPixels,
|
|
90
|
+
totalPixels,
|
|
91
|
+
threshold,
|
|
92
|
+
alignment: {
|
|
93
|
+
target,
|
|
94
|
+
design: { width: design.width, height: design.height, scaled: designScaled },
|
|
95
|
+
render: { width: render.width, height: render.height, scaled: renderScaled },
|
|
96
|
+
},
|
|
97
|
+
hotspots,
|
|
98
|
+
diffImagePng: diffData
|
|
99
|
+
? encodePng({ width: target.width, height: target.height, data: diffData })
|
|
100
|
+
: null,
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
function isDiffPixel(data, offset) {
|
|
104
|
+
return data[offset] >= 250 && data[offset + 1] <= 8 && data[offset + 2] <= 8;
|
|
105
|
+
}
|
|
106
|
+
function collectHotspots(diffData, width, height, cols, rows, maxHotspots) {
|
|
107
|
+
const cellWidth = Math.ceil(width / cols);
|
|
108
|
+
const cellHeight = Math.ceil(height / rows);
|
|
109
|
+
const cells = [];
|
|
110
|
+
for (let row = 0; row < rows; row += 1) {
|
|
111
|
+
const y0 = row * cellHeight;
|
|
112
|
+
const y1 = Math.min(height, y0 + cellHeight);
|
|
113
|
+
for (let col = 0; col < cols; col += 1) {
|
|
114
|
+
const x0 = col * cellWidth;
|
|
115
|
+
const x1 = Math.min(width, x0 + cellWidth);
|
|
116
|
+
let diff = 0;
|
|
117
|
+
let total = 0;
|
|
118
|
+
for (let y = y0; y < y1; y += 1) {
|
|
119
|
+
for (let x = x0; x < x1; x += 1) {
|
|
120
|
+
total += 1;
|
|
121
|
+
if (isDiffPixel(diffData, (y * width + x) * 4))
|
|
122
|
+
diff += 1;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
if (total > 0 && diff > 0) {
|
|
126
|
+
cells.push({
|
|
127
|
+
x: x0,
|
|
128
|
+
y: y0,
|
|
129
|
+
width: x1 - x0,
|
|
130
|
+
height: y1 - y0,
|
|
131
|
+
diffRatio: Number((diff / total).toFixed(4)),
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
cells.sort((a, b) => b.diffRatio - a.diffRatio);
|
|
137
|
+
return cells.slice(0, maxHotspots);
|
|
138
|
+
}
|
|
139
|
+
export function scoreVerdict(score) {
|
|
140
|
+
if (score >= 0.95)
|
|
141
|
+
return 'high';
|
|
142
|
+
if (score >= 0.85)
|
|
143
|
+
return 'medium';
|
|
144
|
+
return 'low';
|
|
145
|
+
}
|
|
146
|
+
export const VISUAL_DIFF_CAVEATS = [
|
|
147
|
+
'Font rasterization differs across OS and DPI; text areas may lower the score even when code is correct.',
|
|
148
|
+
'Scores are regression signals for comparing runs, not a pass/fail gate.',
|
|
149
|
+
'Dynamic states (hover, loading, animation) are captured only if visible at screenshot time.',
|
|
150
|
+
];
|
package/dist/mcp/result.js
CHANGED
|
@@ -122,6 +122,46 @@ function summarizeIntegrity(value) {
|
|
|
122
122
|
}
|
|
123
123
|
return `integrity: ${integrity.ok === false ? 'failed' : 'ok'}`;
|
|
124
124
|
}
|
|
125
|
+
export function summarizeVerifyPayload(payload) {
|
|
126
|
+
const lines = [payload.ok === false ? 'failed' : 'ok'];
|
|
127
|
+
const summary = payload.summary;
|
|
128
|
+
if (summary)
|
|
129
|
+
lines.push(`checks: pass=${summary.pass ?? 0} fail=${summary.fail ?? 0} warn=${summary.warn ?? 0}`);
|
|
130
|
+
const issues = Array.isArray(payload.issues) ? payload.issues : [];
|
|
131
|
+
const failed = issues.filter((issue) => /MISMATCH|DOUBLE_SCALE|WRONG_SCALE|UNUSED|UNAVAILABLE|UNRESOLVED|ORDER/.test(issue.code ?? ''));
|
|
132
|
+
if (failed.length > 0) {
|
|
133
|
+
lines.push('failed checks (first 5):');
|
|
134
|
+
for (const issue of failed.slice(0, 5)) {
|
|
135
|
+
lines.push(` [${issue.code}] ${issue.dimension ?? '?'} ${issue.layerObjectId ?? ''} @ ${issue.file ?? ''}:${issue.line ?? 0}`);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
const review = Array.isArray(payload.reviewRequired) ? payload.reviewRequired.length : 0;
|
|
139
|
+
if (review > 0)
|
|
140
|
+
lines.push(`reviewRequired: ${review} layers need manual review`);
|
|
141
|
+
lines.push('Full data is available in structuredContent.');
|
|
142
|
+
return lines.join('\n');
|
|
143
|
+
}
|
|
144
|
+
export function summarizeVisualDiffPayload(payload) {
|
|
145
|
+
const lines = ['visual_diff:'];
|
|
146
|
+
const score = typeof payload.score === 'number' ? payload.score.toFixed(4) : String(payload.score ?? '?');
|
|
147
|
+
lines.push(`score: ${score} (verdict ${String(payload.verdict ?? '?')})`);
|
|
148
|
+
lines.push(`diff pixels: ${String(payload.diffPixels ?? '?')} / ${String(payload.totalPixels ?? '?')}`);
|
|
149
|
+
const alignment = payload.alignment;
|
|
150
|
+
if (alignment?.target) {
|
|
151
|
+
lines.push(`viewport: ${alignment.target.width ?? '?'}x${alignment.target.height ?? '?'}`);
|
|
152
|
+
}
|
|
153
|
+
const hotspots = Array.isArray(payload.hotspots) ? payload.hotspots : [];
|
|
154
|
+
if (hotspots.length > 0) {
|
|
155
|
+
const preview = hotspots.slice(0, 3)
|
|
156
|
+
.map((h) => `(${h.x ?? 0},${h.y ?? 0})=${((h.diffRatio ?? 0) * 100).toFixed(0)}%`)
|
|
157
|
+
.join(' ');
|
|
158
|
+
lines.push(`top hotspots: ${preview}`);
|
|
159
|
+
}
|
|
160
|
+
if (typeof payload.diffImagePath === 'string')
|
|
161
|
+
lines.push(`diff image: ${payload.diffImagePath}`);
|
|
162
|
+
lines.push('Score is a regression signal, not a pass/fail verdict. Full data is in structuredContent.');
|
|
163
|
+
return lines.join('\n');
|
|
164
|
+
}
|
|
125
165
|
// 诊断记录本身就是给 LLM 阅读的内容,默认保留完整文本但不加缩进。
|
|
126
166
|
export function toolSuccessFull(payload) {
|
|
127
167
|
const structuredContent = { ok: true, ...payload };
|
|
@@ -62,7 +62,7 @@ const argsSchema = objectSchema({
|
|
|
62
62
|
export function registerDesignToCodePrompt(server) {
|
|
63
63
|
server.registerPrompt('implement_codesign_page', {
|
|
64
64
|
title: 'Implement CoDesign Page',
|
|
65
|
-
description: 'Generate a design-to-code workflow prompt that uses list_artboards, get_artboard_spec, and
|
|
65
|
+
description: 'Generate a design-to-code workflow prompt that uses list_artboards, get_artboard_spec, download_slice, verify_rendering, and optionally visual_diff in order.',
|
|
66
66
|
argsSchema,
|
|
67
67
|
}, async ({ sharingUrl, password, artboardName, screenId, layerObjectId, layerName, selectionScope, targetPlatform, targetUnit, customScale, customWidth, remBasePx, outputDir, }) => ({
|
|
68
68
|
messages: [
|
|
@@ -121,8 +121,11 @@ Requirements:
|
|
|
121
121
|
6. If the user specifies a unit, custom scale, target design width, or rem base, pass those as get_artboard_spec.targetUnit, customScale, customWidth, and remBasePx. For example, "1440px design width, rem, 1rem=100px" maps to targetUnit=rem, customWidth=1440, remBasePx=100.
|
|
122
122
|
7. Use spec.platformSpec or platformSelection when returned for platform id, units, converted rects, unit-adjusted CSS, and conversion metadata. Keep the raw CoDesign data available as the source of truth.
|
|
123
123
|
8. Unless the user's current request explicitly requires an absolute-positioned or canvas-style implementation, translate the CoDesign coordinates into semantic page structure and normal document flow before coding. Prefer Flexbox/Grid and existing layout primitives for page layout; do not recreate the whole page as a flat canvas of globally absolute-positioned layers. When the user explicitly requests absolute positioning, honor that instruction and scope positioning to the requested page or selection container where practical. Otherwise reserve absolute/fixed positioning for local overlays or intentionally overlapping elements required by the design.
|
|
124
|
-
9. When the design includes designer-exported slice assets, call download_slice for those assets. Do not crop production assets from the full preview image.
|
|
125
|
-
10.
|
|
124
|
+
9. When the design includes designer-exported slice assets, call download_slice for those assets with the same targetPlatform/unit/width options. Use the returned slice.designSize as the CSS display size — a 2x asset is shown at design size, never at its pixel size. Do not crop production assets from the full preview image.
|
|
125
|
+
10. Mark every slice usage in code with data-slice-id="<layerObjectId>" (attribute) or /* slice:<layerObjectId> */ (comment) so it can be verified.
|
|
126
126
|
11. Implement the page in the target directory when one is provided, following the existing project structure and styles.
|
|
127
|
-
12.
|
|
127
|
+
12. Before finishing, call verify_rendering with the written code files and the same platform options. Fix every error issue (size, scale, color, typography, radius, hierarchy), re-run until ok is true, and manually review every item in reviewRequired. It re-fetches the official spec itself, so pass the real file paths, not copied measurements.
|
|
128
|
+
13. If a local dev server is available, optionally call visual_diff with its pageUrl and the same artboard selector to get a 0..1 similarity score as an extra regression signal. Compare scores across iterations rather than treating one score as pass/fail; a drop means a change hurt fidelity. Font rasterization can lower the score.
|
|
129
|
+
14. Use get_artboard_image only for visual comparison and final review.
|
|
130
|
+
15. Surface any CoDesign access, password, login, or missing-spec failure clearly instead of fabricating design data.`;
|
|
128
131
|
}
|
|
@@ -11,10 +11,12 @@ Use this workflow when a user asks an agent to implement, recreate, or inspect a
|
|
|
11
11
|
6. If the user specifies a unit, custom scale, target design width, or rem base, pass those as \`targetUnit\`, \`customScale\`, \`customWidth\`, and \`remBasePx\`. For example, "1440px design width, rem, 1rem=100px" maps to \`targetUnit=rem\`, \`customWidth=1440\`, and \`remBasePx=100\`.
|
|
12
12
|
7. Use the returned \`spec.platformSpec\` or \`platformSelection\` for normalized platform id, units, converted rects, unit-adjusted CSS, and conversion metadata while keeping the raw spec as the original CoDesign data.
|
|
13
13
|
8. Unless the user's current request explicitly requires an absolute-positioned or canvas-style implementation, translate the CoDesign coordinates into semantic page structure and normal document flow before implementation. Prefer Flexbox/Grid and existing layout primitives for page layout; do not recreate the whole page as a flat canvas of globally absolute-positioned layers. When the user explicitly requests absolute positioning, honor that instruction and scope positioning to the requested page or selection container where practical. Otherwise reserve absolute/fixed positioning for local overlays or intentionally overlapping elements required by the design.
|
|
14
|
-
9. If the selected artboard includes designer-exported slice assets, call \`download_slice\` for those assets. Do not crop production assets from a preview image.
|
|
15
|
-
10.
|
|
16
|
-
11.
|
|
17
|
-
12.
|
|
14
|
+
9. If the selected artboard includes designer-exported slice assets, call \`download_slice\` for those assets with the same platform options and use the returned \`slice.designSize\` as the CSS display size (a 2x asset is shown at design size, not pixel size). Do not crop production assets from a preview image.
|
|
15
|
+
10. Mark each slice usage with \`data-slice-id="<layerObjectId>"\` or a \`/* slice:<layerObjectId> */\` comment. Before finishing, call \`verify_rendering\` with the written code files and the same platform options; fix its error issues, re-run until \`ok\` is true, and manually review every \`reviewRequired\` item. It re-fetches the official spec itself and never trusts measurements copied into the prompt.
|
|
16
|
+
11. If a local dev server is running, optionally call \`visual_diff\` with its \`pageUrl\` (or an existing \`screenshotPath\`) and the same artboard selector. Use the 0..1 \`score\` and \`hotspots\` as a regression signal across iterations, not as a pass/fail gate; font rasterization can lower the score. Alignment failures are reported explicitly.
|
|
17
|
+
12. Use \`get_artboard_image\` only for visual comparison, review, or debugging.
|
|
18
|
+
13. Use \`codesign_status\` before private designs when login state or runtime paths need to be checked. Use \`codesign_login\` only when the user needs to establish a CoDesign browser session.
|
|
19
|
+
14. Surface access, password, login, network, missing-artboard, and missing-spec failures clearly. Do not fabricate design data when the official CoDesign data is unavailable.
|
|
18
20
|
`;
|
|
19
21
|
export function registerWorkflowResource(server) {
|
|
20
22
|
server.registerResource('design-to-code-workflow', DESIGN_TO_CODE_WORKFLOW_URI, {
|
package/dist/server.js
CHANGED
|
@@ -5,6 +5,8 @@ import { registerArtboardsTool } from './tools/artboards.js';
|
|
|
5
5
|
import { registerSpecTool } from './tools/spec.js';
|
|
6
6
|
import { registerImageTool } from './tools/image.js';
|
|
7
7
|
import { registerSlicesTool } from './tools/slices.js';
|
|
8
|
+
import { registerVerifyRenderingTool } from './tools/verify-rendering.js';
|
|
9
|
+
import { registerVisualDiffTool } from './tools/visual-diff.js';
|
|
8
10
|
import { registerDiagnosticsTool } from './tools/diagnostics.js';
|
|
9
11
|
import { registerDesignToCodePrompt } from './prompts/design-to-code.js';
|
|
10
12
|
import { registerWorkflowResource } from './resources/workflow.js';
|
|
@@ -30,6 +32,8 @@ export function buildServer() {
|
|
|
30
32
|
registerSpecTool(server);
|
|
31
33
|
registerImageTool(server);
|
|
32
34
|
registerSlicesTool(server);
|
|
35
|
+
registerVerifyRenderingTool(server);
|
|
36
|
+
registerVisualDiffTool(server);
|
|
33
37
|
registerDiagnosticsTool(server);
|
|
34
38
|
registerDesignToCodePrompt(server);
|
|
35
39
|
registerWorkflowResource(server);
|
package/dist/tools/slices.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
2
|
import { objectSchema } from '../mcp/schema.js';
|
|
3
3
|
import { browserManager } from '../browser/manager.js';
|
|
4
|
-
import { getCachedSharingDetail, fetchCachedSliceManifest } from '../codesign/cache.js';
|
|
4
|
+
import { getCachedSharingDetail, fetchCachedSpec, fetchCachedSliceManifest } from '../codesign/cache.js';
|
|
5
5
|
import { findSliceByObjectId } from '../codesign/slices.js';
|
|
6
|
+
import { buildPlatformSpec } from '../codesign/platform.js';
|
|
6
7
|
import { inspectManifest, integrityView } from '../codesign/integrity.js';
|
|
7
8
|
import { CodesignError } from '../codesign/errors.js';
|
|
8
9
|
import { normalizeCodesignAssetUrl, parseSharingId } from '../utils/url.js';
|
|
@@ -37,6 +38,14 @@ const inputSchema = objectSchema({
|
|
|
37
38
|
items: { type: 'number' },
|
|
38
39
|
description: 'Filter exportables by scale list, e.g. [1, 2]',
|
|
39
40
|
},
|
|
41
|
+
targetPlatform: {
|
|
42
|
+
type: 'string',
|
|
43
|
+
description: 'Optional platform used to return the design layout size together with each slice.',
|
|
44
|
+
},
|
|
45
|
+
targetUnit: { type: 'string' },
|
|
46
|
+
customScale: { type: 'number', minimum: 0 },
|
|
47
|
+
customWidth: { type: 'number', minimum: 0 },
|
|
48
|
+
remBasePx: { type: 'number', minimum: 0 },
|
|
40
49
|
includeFullText: {
|
|
41
50
|
type: 'boolean',
|
|
42
51
|
default: false,
|
|
@@ -48,11 +57,13 @@ export function registerSlicesTool(server) {
|
|
|
48
57
|
title: 'Download CoDesign Slice',
|
|
49
58
|
description: 'Downloads designer-exported CoDesign slice assets from the official slice manifest, matched by layer object_id. ' +
|
|
50
59
|
'Use this for implementation assets instead of using Python/PIL or screenshot cropping. ' +
|
|
51
|
-
'Returns local paths under <workspaceRoot>/.codesign-mcp/artifacts/<sharingId>/slices/. Optional filters: format and scales.'
|
|
60
|
+
'Returns local paths under <workspaceRoot>/.codesign-mcp/artifacts/<sharingId>/slices/. Optional filters: format and scales. ' +
|
|
61
|
+
'Pass targetPlatform (with the same unit/width options used for get_artboard_spec) to also receive slice.designSize, ' +
|
|
62
|
+
'the converted layout width/height the image must be displayed at in code — 2x assets must be shown at this size, not their pixel size.',
|
|
52
63
|
inputSchema,
|
|
53
64
|
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
|
54
65
|
}, async (args) => {
|
|
55
|
-
const { sharingUrl, password, screenId, objectId, screenName, layerObjectId, format, scales, includeFullText } = args;
|
|
66
|
+
const { sharingUrl, password, screenId, objectId, screenName, layerObjectId, format, scales, targetPlatform, targetUnit, customScale, customWidth, remBasePx, includeFullText, } = args;
|
|
56
67
|
let sharingId;
|
|
57
68
|
try {
|
|
58
69
|
sharingId = parseSharingId(sharingUrl);
|
|
@@ -107,6 +118,47 @@ export function registerSlicesTool(server) {
|
|
|
107
118
|
})),
|
|
108
119
|
}));
|
|
109
120
|
}
|
|
121
|
+
// designSize 是「该图层在代码里应显示的布局宽高」,由 platformSpec 换算而来。
|
|
122
|
+
// 只有显式传 targetPlatform 时才额外拉 spec(有缓存),避免改变默认请求量。
|
|
123
|
+
let designSize;
|
|
124
|
+
if (targetPlatform) {
|
|
125
|
+
if (picked.meta_url) {
|
|
126
|
+
try {
|
|
127
|
+
const spec = await fetchCachedSpec(picked.meta_url);
|
|
128
|
+
const platformSpec = buildPlatformSpec(spec, targetPlatform, {
|
|
129
|
+
targetUnit,
|
|
130
|
+
customScale,
|
|
131
|
+
customWidth,
|
|
132
|
+
remBasePx,
|
|
133
|
+
});
|
|
134
|
+
const platformLayer = [...platformSpec.layers, ...platformSpec.groups].find((layer) => layer.objectId === slice.object_id);
|
|
135
|
+
designSize = platformLayer
|
|
136
|
+
? {
|
|
137
|
+
width: platformLayer.rect.width,
|
|
138
|
+
height: platformLayer.rect.height,
|
|
139
|
+
unit: platformLayer.rect.unit,
|
|
140
|
+
source: 'platformSpec',
|
|
141
|
+
}
|
|
142
|
+
: {
|
|
143
|
+
width: slice.rect.width,
|
|
144
|
+
height: slice.rect.height,
|
|
145
|
+
unit: platformSpec.unit,
|
|
146
|
+
source: 'sliceRect',
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
catch (err) {
|
|
150
|
+
log.warn({ err: err.message }, 'download_slice designSize lookup failed');
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
if (!designSize) {
|
|
154
|
+
designSize = {
|
|
155
|
+
width: slice.rect.width,
|
|
156
|
+
height: slice.rect.height,
|
|
157
|
+
unit: 'px',
|
|
158
|
+
source: 'sliceRect',
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
}
|
|
110
162
|
const integrity = integrityView(inspectManifest(manifest));
|
|
111
163
|
const downloads = [];
|
|
112
164
|
const skipped = [];
|
|
@@ -169,6 +221,7 @@ export function registerSlicesTool(server) {
|
|
|
169
221
|
name: slice.name,
|
|
170
222
|
objectId: slice.object_id,
|
|
171
223
|
rect: slice.rect,
|
|
224
|
+
designSize,
|
|
172
225
|
},
|
|
173
226
|
requested: filteredExportables.length,
|
|
174
227
|
downloaded: downloads.length,
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
// verify_rendering:重新拉取权威 spec,重建 platformSpec,读取生成代码,
|
|
2
|
+
// 按 data-slice-id 属性 / `slice:` 注释锚点比对尺寸、倍率、颜色、字号、圆角、层级。
|
|
3
|
+
// 期望值不信任 LLM 入参,全部由工具重新拉取重建,防止错误转录。
|
|
4
|
+
import { readFileSync, statSync } from 'node:fs';
|
|
5
|
+
import { isAbsolute, relative, resolve, sep } from 'node:path';
|
|
6
|
+
import { objectSchema } from '../mcp/schema.js';
|
|
7
|
+
import { browserManager } from '../browser/manager.js';
|
|
8
|
+
import { getCachedSharingDetail, fetchCachedSpec, fetchCachedSliceManifest } from '../codesign/cache.js';
|
|
9
|
+
import { normalizeSpec } from '../codesign/parser.js';
|
|
10
|
+
import { buildPlatformSpec } from '../codesign/platform.js';
|
|
11
|
+
import { verifyRendering, VERIFY_CHECKS } from '../codesign/verify.js';
|
|
12
|
+
import { CodesignError } from '../codesign/errors.js';
|
|
13
|
+
import { parseSharingId } from '../utils/url.js';
|
|
14
|
+
import { config } from '../config.js';
|
|
15
|
+
import { errorResult } from './artboards.js';
|
|
16
|
+
import { pickScreen, summarizeScreens } from './spec.js';
|
|
17
|
+
import { toolSuccess, summarizeVerifyPayload } from '../mcp/result.js';
|
|
18
|
+
import { getLogger } from '../logger.js';
|
|
19
|
+
const log = getLogger();
|
|
20
|
+
const MAX_FILE_BYTES = 2 * 1024 * 1024;
|
|
21
|
+
const inputSchema = objectSchema({
|
|
22
|
+
sharingUrl: { type: 'string', minLength: 1 },
|
|
23
|
+
password: { type: 'string' },
|
|
24
|
+
screenId: { anyOf: [{ type: 'integer' }, { type: 'string' }] },
|
|
25
|
+
objectId: { type: 'string' },
|
|
26
|
+
screenName: { type: 'string' },
|
|
27
|
+
codeFiles: {
|
|
28
|
+
type: 'array',
|
|
29
|
+
items: { type: 'string', minLength: 1 },
|
|
30
|
+
description: 'Project files to scan, relative to the workspace root.',
|
|
31
|
+
},
|
|
32
|
+
targetPlatform: {
|
|
33
|
+
type: 'string',
|
|
34
|
+
minLength: 1,
|
|
35
|
+
description: 'Same platform used for get_artboard_spec, e.g. web, wechat-miniprogram, raw.',
|
|
36
|
+
},
|
|
37
|
+
targetUnit: { type: 'string' },
|
|
38
|
+
customScale: { type: 'number', minimum: 0 },
|
|
39
|
+
customWidth: { type: 'number', minimum: 0 },
|
|
40
|
+
remBasePx: { type: 'number', minimum: 0 },
|
|
41
|
+
scale: { type: 'number', minimum: 1, default: 2, description: 'Expected slice scale, default 2.' },
|
|
42
|
+
checks: {
|
|
43
|
+
type: 'array',
|
|
44
|
+
items: { type: 'string', enum: [...VERIFY_CHECKS] },
|
|
45
|
+
description: 'Dimensions to verify. Defaults to all.',
|
|
46
|
+
},
|
|
47
|
+
includeFullText: { type: 'boolean', default: false },
|
|
48
|
+
}, ['sharingUrl', 'codeFiles', 'targetPlatform']);
|
|
49
|
+
export function registerVerifyRenderingTool(server) {
|
|
50
|
+
server.registerTool('verify_rendering', {
|
|
51
|
+
title: 'Verify Rendering Against Design',
|
|
52
|
+
description: 'Re-fetches the official CoDesign spec (bypassing any LLM-supplied measurements), rebuilds platformSpec, ' +
|
|
53
|
+
'then statically checks generated code against the design for size, slice scale, color, typography, radius, and hierarchy. ' +
|
|
54
|
+
'Anchors are data-slice-id="<layerObjectId>" attributes or /* slice:<layerObjectId> */ comments. ' +
|
|
55
|
+
'Returns per-issue file/line, a reviewRequired list for unresolvable visual areas, and ok=false when any hard check fails. ' +
|
|
56
|
+
'This tool never modifies files; use its issues to fix code before finishing.',
|
|
57
|
+
inputSchema,
|
|
58
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
|
59
|
+
}, async (args) => {
|
|
60
|
+
const { sharingUrl, password, screenId, objectId, screenName, codeFiles, targetPlatform, targetUnit, customScale, customWidth, remBasePx, scale, checks, includeFullText, } = args;
|
|
61
|
+
let sharingId;
|
|
62
|
+
try {
|
|
63
|
+
sharingId = parseSharingId(sharingUrl);
|
|
64
|
+
}
|
|
65
|
+
catch (err) {
|
|
66
|
+
return errorResult(err);
|
|
67
|
+
}
|
|
68
|
+
// 先做纯本地的文件读取与路径校验,避免无谓地拉取远端数据。
|
|
69
|
+
let files;
|
|
70
|
+
try {
|
|
71
|
+
files = codeFiles.map((entry) => readCodeFile(entry));
|
|
72
|
+
}
|
|
73
|
+
catch (err) {
|
|
74
|
+
return errorResult(err);
|
|
75
|
+
}
|
|
76
|
+
const call = await browserManager.acquireHeadless();
|
|
77
|
+
try {
|
|
78
|
+
const { detail } = await getCachedSharingDetail(call.page, sharingId, password);
|
|
79
|
+
const allScreens = [];
|
|
80
|
+
for (const design of detail.designs ?? []) {
|
|
81
|
+
for (const screen of design.screens ?? [])
|
|
82
|
+
allScreens.push(screen);
|
|
83
|
+
}
|
|
84
|
+
if (allScreens.length === 0) {
|
|
85
|
+
return errorResult(new CodesignError('SHARING_NOT_FOUND', 'sharing has no screens', { sharingId }));
|
|
86
|
+
}
|
|
87
|
+
const selector = { screenId, objectId, screenName };
|
|
88
|
+
const picked = pickScreen(allScreens, selector);
|
|
89
|
+
if (!picked) {
|
|
90
|
+
const needsSelector = selector.screenId != null || selector.objectId != null || selector.screenName != null;
|
|
91
|
+
return errorResult(needsSelector
|
|
92
|
+
? new CodesignError('SCREEN_NOT_FOUND', 'no screen matches the given selector', {
|
|
93
|
+
selector,
|
|
94
|
+
available: summarizeScreens(allScreens),
|
|
95
|
+
})
|
|
96
|
+
: new CodesignError('SCREEN_SELECTOR_REQUIRED', 'multiple screens present; specify a selector', {
|
|
97
|
+
available: summarizeScreens(allScreens),
|
|
98
|
+
}));
|
|
99
|
+
}
|
|
100
|
+
const spec = await fetchCachedSpec(picked.meta_url);
|
|
101
|
+
const manifest = picked.slices_url ? await fetchCachedSliceManifest(picked.slices_url) : [];
|
|
102
|
+
const platformSpec = buildPlatformSpec(spec, targetPlatform, {
|
|
103
|
+
targetUnit,
|
|
104
|
+
customScale,
|
|
105
|
+
customWidth,
|
|
106
|
+
remBasePx,
|
|
107
|
+
});
|
|
108
|
+
const normalized = normalizeSpec(spec, manifest, platformSpec);
|
|
109
|
+
const report = verifyRendering({
|
|
110
|
+
files,
|
|
111
|
+
layers: normalized.layers,
|
|
112
|
+
groups: normalized.groups,
|
|
113
|
+
hierarchy: normalized.hierarchy,
|
|
114
|
+
platformSpec,
|
|
115
|
+
manifest,
|
|
116
|
+
scale: scale ?? 2,
|
|
117
|
+
checks: checks && checks.length > 0 ? checks : undefined,
|
|
118
|
+
});
|
|
119
|
+
return toolSuccess({
|
|
120
|
+
sharingId,
|
|
121
|
+
screen: { id: picked.id, objectId: picked.object_id, name: picked.name },
|
|
122
|
+
platform: {
|
|
123
|
+
requested: platformSpec.requested,
|
|
124
|
+
id: platformSpec.id,
|
|
125
|
+
unit: platformSpec.unit,
|
|
126
|
+
scale: platformSpec.scale,
|
|
127
|
+
},
|
|
128
|
+
summary: report.summary,
|
|
129
|
+
ok: report.ok,
|
|
130
|
+
issues: report.issues,
|
|
131
|
+
reviewRequired: report.reviewRequired,
|
|
132
|
+
anchors: report.anchors,
|
|
133
|
+
checkedSlices: report.checkedSlices,
|
|
134
|
+
files: files.map((file) => file.path),
|
|
135
|
+
}, includeFullText, summarizeVerifyPayload);
|
|
136
|
+
}
|
|
137
|
+
catch (err) {
|
|
138
|
+
log.warn({ err: err.message, sharingId }, 'verify_rendering failed');
|
|
139
|
+
return errorResult(err);
|
|
140
|
+
}
|
|
141
|
+
finally {
|
|
142
|
+
await call.done();
|
|
143
|
+
}
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
function readCodeFile(entry) {
|
|
147
|
+
const root = resolve(config.workspaceRoot);
|
|
148
|
+
const target = isAbsolute(entry) ? resolve(entry) : resolve(root, entry);
|
|
149
|
+
const rel = relative(root, target);
|
|
150
|
+
if (rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {
|
|
151
|
+
throw new CodesignError('ARTIFACT_PATH_INVALID', 'code file escapes the workspace root', {
|
|
152
|
+
root,
|
|
153
|
+
entry,
|
|
154
|
+
target,
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
let stats;
|
|
158
|
+
try {
|
|
159
|
+
stats = statSync(target);
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
162
|
+
throw new CodesignError('CODE_FILE_INVALID', 'code file does not exist', { entry, target });
|
|
163
|
+
}
|
|
164
|
+
if (!stats.isFile()) {
|
|
165
|
+
throw new CodesignError('CODE_FILE_INVALID', 'code path is not a file', { entry, target });
|
|
166
|
+
}
|
|
167
|
+
if (stats.size > MAX_FILE_BYTES) {
|
|
168
|
+
throw new CodesignError('CODE_FILE_INVALID', 'code file is too large to verify', {
|
|
169
|
+
entry,
|
|
170
|
+
bytes: stats.size,
|
|
171
|
+
maxBytes: MAX_FILE_BYTES,
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
return { path: entry, text: readFileSync(target, 'utf8') };
|
|
175
|
+
}
|