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,292 @@
|
|
|
1
|
+
// visual_diff:L3 像素级视觉回归。把「生成页的截图」与「CoDesign 画板预览图」
|
|
2
|
+
// 在同一种子尺寸下对齐后做逐像素差分,输出 0..1 相似度分数与差异热区。
|
|
3
|
+
// 分数只作为回归信号,不做通过/失败硬判定。
|
|
4
|
+
import { readFileSync, statSync, writeFileSync, mkdirSync } 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 } from '../codesign/cache.js';
|
|
9
|
+
import { CodesignError } from '../codesign/errors.js';
|
|
10
|
+
import { parseSharingId } from '../utils/url.js';
|
|
11
|
+
import { downloadToArtifact } from '../utils/download.js';
|
|
12
|
+
import { config } from '../config.js';
|
|
13
|
+
import { errorResult } from './artboards.js';
|
|
14
|
+
import { pickScreen, summarizeScreens } from './spec.js';
|
|
15
|
+
import { toolSuccess, summarizeVisualDiffPayload } from '../mcp/result.js';
|
|
16
|
+
import { decodePng, compareImages, scoreVerdict, VISUAL_DIFF_CAVEATS, } from '../codesign/visual-diff.js';
|
|
17
|
+
import { getLogger } from '../logger.js';
|
|
18
|
+
const log = getLogger();
|
|
19
|
+
const MAX_FILE_BYTES = 25 * 1024 * 1024;
|
|
20
|
+
const DEFAULT_WAIT_MS = 800;
|
|
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
|
+
pageUrl: {
|
|
28
|
+
type: 'string',
|
|
29
|
+
description: 'Local dev server URL to screenshot, e.g. http://127.0.0.1:5173/page. Mutually exclusive with screenshotPath.',
|
|
30
|
+
},
|
|
31
|
+
screenshotPath: {
|
|
32
|
+
type: 'string',
|
|
33
|
+
description: 'Path to an existing screenshot (relative to workspace root). Mutually exclusive with pageUrl.',
|
|
34
|
+
},
|
|
35
|
+
viewportWidth: { type: 'integer', minimum: 1, description: 'Override screenshot viewport width in CSS px.' },
|
|
36
|
+
viewportHeight: { type: 'integer', minimum: 1, description: 'Override screenshot viewport height in CSS px.' },
|
|
37
|
+
waitMs: { type: 'integer', minimum: 0, description: 'Milliseconds to wait after page load before screenshotting.' },
|
|
38
|
+
threshold: { type: 'number', minimum: 0, maximum: 1, description: 'pixelmatch color threshold, default 0.1.' },
|
|
39
|
+
maxAspectRatioDrift: {
|
|
40
|
+
type: 'number',
|
|
41
|
+
minimum: 0,
|
|
42
|
+
description: 'Allowed aspect-ratio drift between image and viewport, default 0.05.',
|
|
43
|
+
},
|
|
44
|
+
includeDiffImage: { type: 'boolean', default: true, description: 'Also write a diff heat-map PNG under artifacts.' },
|
|
45
|
+
includeFullText: { type: 'boolean', default: false },
|
|
46
|
+
}, ['sharingUrl']);
|
|
47
|
+
export function registerVisualDiffTool(server) {
|
|
48
|
+
server.registerTool('visual_diff', {
|
|
49
|
+
title: 'Visual Regression Against Artboard',
|
|
50
|
+
description: 'Compares a rendered page with the CoDesign artboard preview and reports a 0..1 similarity score plus difference hotspots. ' +
|
|
51
|
+
'Provide either pageUrl (a running local dev server; it will be screenshotted at the artboard viewport) or screenshotPath (an existing screenshot). ' +
|
|
52
|
+
'The score is a regression signal for comparing runs, not a pass/fail verdict; font rasterization can lower it. ' +
|
|
53
|
+
'Never modifies the page or project files; only writes a diff image under <workspaceRoot>/.codesign-mcp/artifacts/.',
|
|
54
|
+
inputSchema,
|
|
55
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
|
56
|
+
}, async (args) => {
|
|
57
|
+
const { sharingUrl, password, screenId, objectId, screenName, pageUrl, screenshotPath, viewportWidth, viewportHeight, waitMs, threshold, maxAspectRatioDrift, includeDiffImage, includeFullText, } = args;
|
|
58
|
+
if (!pageUrl && !screenshotPath) {
|
|
59
|
+
return errorResult(new CodesignError('VISUAL_DIFF_PAGE_INVALID', 'provide pageUrl or screenshotPath', {}));
|
|
60
|
+
}
|
|
61
|
+
if (pageUrl && screenshotPath) {
|
|
62
|
+
return errorResult(new CodesignError('VISUAL_DIFF_PAGE_INVALID', 'pageUrl and screenshotPath are mutually exclusive', {}));
|
|
63
|
+
}
|
|
64
|
+
let sharingId;
|
|
65
|
+
try {
|
|
66
|
+
sharingId = parseSharingId(sharingUrl);
|
|
67
|
+
}
|
|
68
|
+
catch (err) {
|
|
69
|
+
return errorResult(err);
|
|
70
|
+
}
|
|
71
|
+
// 本地截图路径先做存在性与越界校验,避免无谓的远端请求。
|
|
72
|
+
let screenshotBuffer = null;
|
|
73
|
+
if (screenshotPath) {
|
|
74
|
+
try {
|
|
75
|
+
screenshotBuffer = readScreenshot(screenshotPath);
|
|
76
|
+
}
|
|
77
|
+
catch (err) {
|
|
78
|
+
return errorResult(err);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
const call = await browserManager.acquireHeadless();
|
|
82
|
+
try {
|
|
83
|
+
const { detail } = await getCachedSharingDetail(call.page, sharingId, password);
|
|
84
|
+
const allScreens = [];
|
|
85
|
+
for (const design of detail.designs ?? []) {
|
|
86
|
+
for (const screen of design.screens ?? [])
|
|
87
|
+
allScreens.push(screen);
|
|
88
|
+
}
|
|
89
|
+
if (allScreens.length === 0) {
|
|
90
|
+
return errorResult(new CodesignError('SHARING_NOT_FOUND', 'sharing has no screens', { sharingId }));
|
|
91
|
+
}
|
|
92
|
+
const selector = { screenId, objectId, screenName };
|
|
93
|
+
const picked = pickScreen(allScreens, selector);
|
|
94
|
+
if (!picked) {
|
|
95
|
+
const needsSelector = selector.screenId != null || selector.objectId != null || selector.screenName != null;
|
|
96
|
+
return errorResult(needsSelector
|
|
97
|
+
? new CodesignError('SCREEN_NOT_FOUND', 'no screen matches the given selector', {
|
|
98
|
+
selector,
|
|
99
|
+
available: summarizeScreens(allScreens),
|
|
100
|
+
})
|
|
101
|
+
: new CodesignError('SCREEN_SELECTOR_REQUIRED', 'multiple screens present; specify a selector', {
|
|
102
|
+
available: summarizeScreens(allScreens),
|
|
103
|
+
}));
|
|
104
|
+
}
|
|
105
|
+
// viewport 来自画板预览图自身标注的 CSS 逻辑尺寸,可被显式参数覆盖。
|
|
106
|
+
const target = {
|
|
107
|
+
width: viewportWidth ?? Math.max(1, Math.round(picked.width || picked.image?.width || 0)),
|
|
108
|
+
height: viewportHeight ?? Math.max(1, Math.round(picked.height || picked.image?.height || 0)),
|
|
109
|
+
};
|
|
110
|
+
if (!Number.isSafeInteger(target.width) || !Number.isSafeInteger(target.height)) {
|
|
111
|
+
return errorResult(new CodesignError('VISUAL_DIFF_ALIGNMENT', 'cannot determine a valid artboard viewport', {
|
|
112
|
+
picked: { width: picked.width, height: picked.height },
|
|
113
|
+
}));
|
|
114
|
+
}
|
|
115
|
+
// 取生成页截图:本地 dev server 用独立 headless 页,绝不污染共享 CoDesign 页。
|
|
116
|
+
let renderPng;
|
|
117
|
+
let renderSource;
|
|
118
|
+
if (pageUrl) {
|
|
119
|
+
const captured = await capturePage(pageUrl, target, waitMs ?? DEFAULT_WAIT_MS);
|
|
120
|
+
renderPng = captured.buffer;
|
|
121
|
+
renderSource = { kind: 'pageUrl', url: captured.url, viewport: target };
|
|
122
|
+
}
|
|
123
|
+
else {
|
|
124
|
+
renderPng = screenshotBuffer;
|
|
125
|
+
renderSource = { kind: 'screenshotPath', path: screenshotPath };
|
|
126
|
+
}
|
|
127
|
+
// 取设计稿基准图:下载画板 full 预览图到 artifacts。
|
|
128
|
+
const designUrl = picked.image?.url;
|
|
129
|
+
if (!designUrl) {
|
|
130
|
+
return errorResult(new CodesignError('SCREEN_NOT_FOUND', 'screen has no preview image url', {
|
|
131
|
+
screen: { id: picked.id, objectId: picked.object_id, name: picked.name },
|
|
132
|
+
}));
|
|
133
|
+
}
|
|
134
|
+
const designDownload = await downloadToArtifact(designUrl, `${sharingId}/screens`, `${picked.id}-visual-diff.png`, 'META_FETCH_FAILED', { request: call.context.request, expectedBytes: picked.image?.size });
|
|
135
|
+
const designPng = await normalizeToPng(readFileSync(designDownload.path), designDownload.mime);
|
|
136
|
+
const designImage = decodePng(designPng);
|
|
137
|
+
const renderImage = decodePng(renderPng);
|
|
138
|
+
const report = compareImages(designImage, renderImage, target, {
|
|
139
|
+
threshold,
|
|
140
|
+
maxAspectRatioDrift,
|
|
141
|
+
includeDiffImage: includeDiffImage !== false,
|
|
142
|
+
});
|
|
143
|
+
let diffImagePath = null;
|
|
144
|
+
if (report.diffImagePng) {
|
|
145
|
+
const rel = `${sharingId}/diffs/${picked.id}-${Date.now()}.png`;
|
|
146
|
+
const abs = resolve(config.artifactsDir, rel);
|
|
147
|
+
mkdirSync(resolve(abs, '..'), { recursive: true });
|
|
148
|
+
writeFileSync(abs, report.diffImagePng);
|
|
149
|
+
diffImagePath = rel;
|
|
150
|
+
}
|
|
151
|
+
return toolSuccess({
|
|
152
|
+
sharingId,
|
|
153
|
+
screen: { id: picked.id, objectId: picked.object_id, name: picked.name },
|
|
154
|
+
renderSource,
|
|
155
|
+
score: report.score,
|
|
156
|
+
verdict: scoreVerdict(report.score),
|
|
157
|
+
diffPixels: report.diffPixels,
|
|
158
|
+
totalPixels: report.totalPixels,
|
|
159
|
+
threshold: report.threshold,
|
|
160
|
+
alignment: report.alignment,
|
|
161
|
+
hotspots: report.hotspots,
|
|
162
|
+
diffImagePath,
|
|
163
|
+
caveats: [...VISUAL_DIFF_CAVEATS],
|
|
164
|
+
}, includeFullText, summarizeVisualDiffPayload);
|
|
165
|
+
}
|
|
166
|
+
catch (err) {
|
|
167
|
+
log.warn({ err: err.message, sharingId }, 'visual_diff failed');
|
|
168
|
+
return errorResult(err);
|
|
169
|
+
}
|
|
170
|
+
finally {
|
|
171
|
+
await call.done();
|
|
172
|
+
}
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
// 打开本地 dev server 截图。独立页用完即关,返回 PNG buffer。
|
|
176
|
+
async function capturePage(pageUrl, viewport, waitMs) {
|
|
177
|
+
validateLocalUrl(pageUrl);
|
|
178
|
+
const call = await browserManager.acquireHeadlessIsolated();
|
|
179
|
+
try {
|
|
180
|
+
await call.page.setViewportSize(viewport);
|
|
181
|
+
const response = await call.page.goto(pageUrl, {
|
|
182
|
+
waitUntil: 'domcontentloaded',
|
|
183
|
+
timeout: config.navTimeoutMs,
|
|
184
|
+
});
|
|
185
|
+
if (!response) {
|
|
186
|
+
throw new CodesignError('VISUAL_DIFF_PAGE_INVALID', 'pageUrl did not return a response', { pageUrl });
|
|
187
|
+
}
|
|
188
|
+
if (!response.ok() && response.status() !== 0) {
|
|
189
|
+
throw new CodesignError('VISUAL_DIFF_PAGE_INVALID', 'pageUrl returned an error status', {
|
|
190
|
+
pageUrl,
|
|
191
|
+
status: response.status(),
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
if (waitMs > 0) {
|
|
195
|
+
await new Promise((resolveDelay) => setTimeout(resolveDelay, waitMs));
|
|
196
|
+
}
|
|
197
|
+
await call.page.evaluate(() => globalThis.document?.fonts?.ready);
|
|
198
|
+
const buffer = await call.page.screenshot({ type: 'png', animations: 'disabled' });
|
|
199
|
+
return { buffer, url: call.page.url() };
|
|
200
|
+
}
|
|
201
|
+
finally {
|
|
202
|
+
await call.done();
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
// 只允许本地回环地址,避免把任意 URL 交给浏览器(SSRF 风险)。
|
|
206
|
+
function validateLocalUrl(input) {
|
|
207
|
+
let url;
|
|
208
|
+
try {
|
|
209
|
+
url = new URL(input);
|
|
210
|
+
}
|
|
211
|
+
catch {
|
|
212
|
+
throw new CodesignError('VISUAL_DIFF_PAGE_INVALID', 'pageUrl is not a valid URL', { pageUrl: input });
|
|
213
|
+
}
|
|
214
|
+
const localHosts = new Set(['localhost', '127.0.0.1', '::1', '[::1]', '0.0.0.0']);
|
|
215
|
+
if (url.protocol !== 'http:' || !localHosts.has(url.hostname.toLowerCase())) {
|
|
216
|
+
throw new CodesignError('VISUAL_DIFF_PAGE_INVALID', 'pageUrl must be a local http dev server', {
|
|
217
|
+
pageUrl: input,
|
|
218
|
+
protocol: url.protocol,
|
|
219
|
+
hostname: url.hostname,
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
function readScreenshot(entry) {
|
|
224
|
+
const root = resolve(config.workspaceRoot);
|
|
225
|
+
const target = isAbsolute(entry) ? resolve(entry) : resolve(root, entry);
|
|
226
|
+
const rel = relative(root, target);
|
|
227
|
+
if (rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {
|
|
228
|
+
throw new CodesignError('ARTIFACT_PATH_INVALID', 'screenshot path escapes the workspace root', {
|
|
229
|
+
root,
|
|
230
|
+
entry,
|
|
231
|
+
target,
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
let stats;
|
|
235
|
+
try {
|
|
236
|
+
stats = statSync(target);
|
|
237
|
+
}
|
|
238
|
+
catch {
|
|
239
|
+
throw new CodesignError('VISUAL_DIFF_IMAGE_INVALID', 'screenshot does not exist', { entry, target });
|
|
240
|
+
}
|
|
241
|
+
if (!stats.isFile()) {
|
|
242
|
+
throw new CodesignError('VISUAL_DIFF_IMAGE_INVALID', 'screenshot path is not a file', { entry, target });
|
|
243
|
+
}
|
|
244
|
+
if (stats.size > MAX_FILE_BYTES) {
|
|
245
|
+
throw new CodesignError('VISUAL_DIFF_IMAGE_INVALID', 'screenshot is too large', {
|
|
246
|
+
entry,
|
|
247
|
+
bytes: stats.size,
|
|
248
|
+
maxBytes: MAX_FILE_BYTES,
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
return readFileSync(target);
|
|
252
|
+
}
|
|
253
|
+
// 设计稿预览图可能是 PNG/JPEG/WEBP,pngjs 只解 PNG。用浏览器 canvas 统一转 PNG。
|
|
254
|
+
async function normalizeToPng(buf, mime) {
|
|
255
|
+
if (looksLikePng(buf))
|
|
256
|
+
return buf;
|
|
257
|
+
const mediaType = mime && mime.startsWith('image/') ? mime : 'image/*';
|
|
258
|
+
const dataUrl = `data:${mediaType};base64,${buf.toString('base64')}`;
|
|
259
|
+
const call = await browserManager.acquireHeadlessIsolated();
|
|
260
|
+
try {
|
|
261
|
+
const base64 = await call.page.evaluate(async (src) => {
|
|
262
|
+
const browserGlobals = globalThis;
|
|
263
|
+
return await new Promise((resolvePromise, reject) => {
|
|
264
|
+
const img = new browserGlobals.Image();
|
|
265
|
+
img.onload = () => {
|
|
266
|
+
const canvas = browserGlobals.document.createElement('canvas');
|
|
267
|
+
canvas.width = img.naturalWidth;
|
|
268
|
+
canvas.height = img.naturalHeight;
|
|
269
|
+
const ctx = canvas.getContext('2d');
|
|
270
|
+
if (!ctx) {
|
|
271
|
+
reject(new Error('canvas 2d context unavailable'));
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
ctx.drawImage(img, 0, 0);
|
|
275
|
+
resolvePromise(canvas.toDataURL('image/png').split(',')[1] ?? '');
|
|
276
|
+
};
|
|
277
|
+
img.onerror = () => reject(new Error('preview image failed to decode'));
|
|
278
|
+
img.src = src;
|
|
279
|
+
});
|
|
280
|
+
}, dataUrl);
|
|
281
|
+
if (!base64) {
|
|
282
|
+
throw new CodesignError('VISUAL_DIFF_IMAGE_INVALID', 'preview image conversion produced no data', {});
|
|
283
|
+
}
|
|
284
|
+
return Buffer.from(base64, 'base64');
|
|
285
|
+
}
|
|
286
|
+
finally {
|
|
287
|
+
await call.done();
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
function looksLikePng(buf) {
|
|
291
|
+
return buf.length >= 8 && buf.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]));
|
|
292
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "codesign-mcp-next",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.5",
|
|
4
4
|
"description": "Local MCP server for Tencent CoDesign — read sharing artboards, specs, screenshots and slices.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -43,15 +43,18 @@
|
|
|
43
43
|
"start": "node dist/index.js",
|
|
44
44
|
"dev": "tsx watch src/index.ts",
|
|
45
45
|
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
46
|
-
"test": "npm run build && node --check userscripts/codesign-ai-selection.user.js && node --test tests/cache.test.mjs tests/config.test.mjs tests/download.test.mjs tests/hierarchy.test.mjs tests/http.test.mjs tests/integrity.test.mjs tests/login.test.mjs tests/manager.test.mjs tests/mcp.test.mjs tests/parser.test.mjs tests/platform.test.mjs tests/rate-limit.test.mjs tests/redact.test.mjs tests/result.test.mjs tests/retry.test.mjs tests/selection.test.mjs tests/sharing.test.mjs tests/slices.test.mjs tests/startup.test.mjs tests/url.test.mjs",
|
|
46
|
+
"test": "npm run build && node --check userscripts/codesign-ai-selection.user.js && node --test tests/cache.test.mjs tests/config.test.mjs tests/download.test.mjs tests/hierarchy.test.mjs tests/http.test.mjs tests/integrity.test.mjs tests/login.test.mjs tests/manager.test.mjs tests/mcp.test.mjs tests/parser.test.mjs tests/platform.test.mjs tests/rate-limit.test.mjs tests/redact.test.mjs tests/result.test.mjs tests/retry.test.mjs tests/selection.test.mjs tests/sharing.test.mjs tests/slices.test.mjs tests/startup.test.mjs tests/url.test.mjs tests/verify-rendering.test.mjs tests/visual-diff.test.mjs",
|
|
47
47
|
"prepack": "npm run build",
|
|
48
48
|
"install:browsers": "playwright install chromium"
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
|
-
"
|
|
51
|
+
"pixelmatch": "^8.0.0",
|
|
52
|
+
"playwright": "1.60.0",
|
|
53
|
+
"pngjs": "^7.0.0"
|
|
52
54
|
},
|
|
53
55
|
"devDependencies": {
|
|
54
56
|
"@types/node": "22.19.19",
|
|
57
|
+
"@types/pngjs": "^6.0.5",
|
|
55
58
|
"tsx": "4.22.2",
|
|
56
59
|
"typescript": "5.9.3"
|
|
57
60
|
}
|