codesign-mcp-next 0.3.4 → 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 CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.5 - 2026-11-26
4
+
5
+ ### Added
6
+
7
+ - Added `visual_diff`, a pixel-level visual regression tool. Provide `pageUrl` (a local http dev server) or `screenshotPath`, plus the artboard selector. It downloads the artboard preview, aligns both images to the artboard viewport, and returns a 0..1 similarity score, verdict, diff pixels, difference hotspots, and a diff image path. Aspect-ratio drift beyond tolerance is reported as `VISUAL_DIFF_ALIGNMENT` rather than a misleading score. The score is a regression signal, not a pass/fail gate.
8
+ - Added `acquireHeadlessIsolated()` to the browser manager so local dev-server screenshots use a dedicated page and never disturb the shared CoDesign page.
9
+ - Added `VISUAL_DIFF_IMAGE_INVALID`, `VISUAL_DIFF_ALIGNMENT`, and `VISUAL_DIFF_PAGE_INVALID` error codes; `pageUrl` is restricted to local loopback hosts.
10
+
11
+ ### Changed
12
+
13
+ - Updated the design-to-code prompt, workflow resource, README, and skill to include optional `visual_diff` as the L3 visual-regression layer.
14
+
3
15
  ## 0.3.4 - 2026-11-26
4
16
 
5
17
  ### Added
package/README.md CHANGED
@@ -120,13 +120,14 @@ CODESIGN_LOG_LEVEL=info
120
120
  - `get_artboard_image`: Fetch preview or cover images for visual comparison.
121
121
  - `download_slice`: Download designer-exported slice assets from the official slice manifest. Passing the same `targetPlatform`/unit/width options used for `get_artboard_spec` also returns `slice.designSize` — the converted layout width/height the slice must be displayed at. A 2x asset must be shown at `designSize`, never at its pixel size.
122
122
  - `verify_rendering`: Re-fetch the official spec (ignoring any LLM-supplied measurements), rebuild `platformSpec`, and statically check generated code against the design. Mark each slice usage with a `data-slice-id="<layerObjectId>"` attribute or a `/* slice:<layerObjectId> */` comment, pass the code files plus the same platform options, and it reports per-file/line issues across size, scale, color, typography, radius, and hierarchy, plus a `reviewRequired` list for areas that cannot be statically resolved. Returns `ok: false` when any hard check fails. Read-only.
123
+ - `visual_diff`: Pixel-level visual regression. Provide either `pageUrl` (a running local http dev server on localhost/127.0.0.1, screenshotted at the artboard viewport) or `screenshotPath` (an existing screenshot), plus the same artboard selector. It downloads the artboard preview, aligns both images to the artboard's CSS dimensions, and returns a 0..1 similarity `score`, a `verdict` (high/medium/low), `diffPixels`, difference `hotspots`, and a `diffImagePath` under `.codesign-mcp/artifacts/`. Alignment failure is reported as an error rather than a misleading score. The score is a regression signal for comparing runs, not a pass/fail gate — font rasterization can lower it. Read-only; only writes the diff image.
123
124
  - `debug_collect_network`: Collect a redacted network summary for diagnosis.
124
125
 
125
126
  ## Caching and tool output
126
127
 
127
128
  Sharing details, meta JSON, and slice manifests are cached in memory for 60 seconds (`CODESIGN_CACHE_TTL_MS`, in milliseconds). Concurrent calls for the same resource share a single request. Set the variable to `0` to disable caching. The cache is process-local and is never written to disk.
128
129
 
129
- Successful tool results keep the complete payload in `structuredContent`. `content[0].text` contains only a short summary, so the same JSON is not counted twice in the model context. For `get_artboard_spec`, the text summary additionally includes a two-level `hierarchy` skeleton, artboard dimensions, layer/group/slice counts, and any integrity warnings, so clients that ignore `structuredContent` still receive the structural cues needed for design-to-code. If your MCP client does not read `structuredContent`, pass `includeFullText: true` to any data tool (`list_artboards`, `get_artboard_spec`, `get_artboard_image`, `download_slice`, `verify_rendering`) to receive the full JSON as text instead. `debug_collect_network` keeps full records in the text channel because those records are the diagnostic output itself.
130
+ Successful tool results keep the complete payload in `structuredContent`. `content[0].text` contains only a short summary, so the same JSON is not counted twice in the model context. For `get_artboard_spec`, the text summary additionally includes a two-level `hierarchy` skeleton, artboard dimensions, layer/group/slice counts, and any integrity warnings, so clients that ignore `structuredContent` still receive the structural cues needed for design-to-code. If your MCP client does not read `structuredContent`, pass `includeFullText: true` to any data tool (`list_artboards`, `get_artboard_spec`, `get_artboard_image`, `download_slice`, `verify_rendering`, `visual_diff`) to receive the full JSON as text instead. `debug_collect_network` keeps full records in the text channel because those records are the diagnostic output itself.
130
131
 
131
132
  All headless tools reuse one browser page, so the sharing page is opened only once per session instead of once per tool call. The headed login window uses an exclusive page and mode switches wait for in-flight calls to finish.
132
133
 
@@ -148,7 +149,7 @@ Remote metadata and artifact downloads are restricted to `https://codesign.qq.co
148
149
 
149
150
  ## Prompts
150
151
 
151
- - `implement_codesign_page`: Generate a structured design-to-code prompt for a full page or copied CoDesign selection. It guides an Agent to call `list_artboards`, `get_artboard_spec`, `download_slice`, and `verify_rendering` in the intended order.
152
+ - `implement_codesign_page`: Generate a structured design-to-code prompt for a full page or copied CoDesign selection. It guides an Agent to call `list_artboards`, `get_artboard_spec`, `download_slice`, `verify_rendering`, and optionally `visual_diff` in the intended order.
152
153
 
153
154
  ## Resources
154
155
 
@@ -157,10 +158,10 @@ Remote metadata and artifact downloads are restricted to `https://codesign.qq.co
157
158
  For design-to-code work, prefer this flow:
158
159
 
159
160
  ```text
160
- list_artboards -> get_artboard_spec -> download_slice -> (write code) -> verify_rendering
161
+ list_artboards -> get_artboard_spec -> download_slice -> (write code) -> verify_rendering -> visual_diff (optional)
161
162
  ```
162
163
 
163
- `verify_rendering` re-fetches the spec itself, so its expected values never depend on numbers copied into the prompt. Check its `issues` and `reviewRequired`, fix the code, and re-run until `ok: true`. Preview screenshots are for visual comparison, not for production slicing.
164
+ `verify_rendering` re-fetches the spec itself, so its expected values never depend on numbers copied into the prompt. Check its `issues` and `reviewRequired`, fix the code, and re-run until `ok: true`. `visual_diff` is an optional extra signal: start your local dev server, pass its `pageUrl`, and compare the `score` across iterations; a drop means a change hurt visual fidelity. Preview screenshots are for visual comparison, not for production slicing.
164
165
 
165
166
  ## CoDesign AI Selection Userscript
166
167
 
@@ -348,13 +349,14 @@ CODESIGN_LOG_LEVEL=info
348
349
  - `get_artboard_image`:获取预览图或封面图,主要用于视觉对比。
349
350
  - `download_slice`:从官方切图清单下载设计师导出的切图资源。传入与 `get_artboard_spec` 相同的 `targetPlatform`/单位/宽度参数时,会同时返回 `slice.designSize`,即该切图在代码中应显示的换算后布局宽高;2x 图必须按 `designSize` 显示,而不是按图片像素尺寸显示。
350
351
  - `verify_rendering`:重新拉取官方 spec(不信任任何由模型转录的尺寸),重建 `platformSpec`,然后静态校验生成代码与设计稿是否一致。在每处切图使用点用 `data-slice-id="<图层objectId>"` 属性或 `/* slice:<图层objectId> */` 注释标注,传入代码文件与相同的平台参数,即可按文件/行号返回尺寸、倍率、颜色、字号、圆角、层级六个维度的 issue,并给出 `reviewRequired`(无法静态判定的区域清单)。任一硬性检查失败时返回 `ok: false`。只读,不修改文件。
352
+ - `visual_diff`:像素级视觉回归。提供 `pageUrl`(本机 localhost/127.0.0.1 上运行的本地 dev server,按画板 viewport 截图)或 `screenshotPath`(已有截图),加上相同的画板选择器。工具下载画板预览图,把两张图对齐到画板 CSS 尺寸后,返回 0..1 的相似度 `score`、`verdict`(high/medium/low)、`diffPixels`、差异 `hotspots` 以及 `.codesign-mcp/artifacts/` 下的 `diffImagePath`。对齐失败会直接报错,而不是给出一个误导性的分数。分数是比较多次运行的回归信号,不是通过/失败硬判定——字体渲染会拉低分数。只读,仅写入差异图。
351
353
  - `debug_collect_network`:收集脱敏后的网络摘要,用于诊断。
352
354
 
353
355
  ## 缓存与工具输出
354
356
 
355
357
  分享详情、标注 JSON 和切图清单会在内存中缓存 60 秒(`CODESIGN_CACHE_TTL_MS`,单位毫秒),相同资源的并发调用会合并为一次请求。设为 `0` 可关闭缓存。缓存只存在于当前进程,不会写入磁盘。
356
358
 
357
- 工具成功结果把完整数据放在 `structuredContent` 中,`content[0].text` 只返回简短摘要,避免同一份 JSON 在模型上下文里被计算两次。`get_artboard_spec` 的文本摘要还会带出两层 `hierarchy` 骨架、画板尺寸、图层/分组/切图数量以及完整性告警,因此不读取 `structuredContent` 的客户端也能拿到还原所需的结构信息。如果你的 MCP 客户端不读取 `structuredContent`,可以对任意数据工具(`list_artboards`、`get_artboard_spec`、`get_artboard_image`、`download_slice`、`verify_rendering`)传 `includeFullText: true`,改为接收完整 JSON 文本。`debug_collect_network` 的诊断记录本身就是输出内容,因此仍在文本通道中保留完整记录。
359
+ 工具成功结果把完整数据放在 `structuredContent` 中,`content[0].text` 只返回简短摘要,避免同一份 JSON 在模型上下文里被计算两次。`get_artboard_spec` 的文本摘要还会带出两层 `hierarchy` 骨架、画板尺寸、图层/分组/切图数量以及完整性告警,因此不读取 `structuredContent` 的客户端也能拿到还原所需的结构信息。如果你的 MCP 客户端不读取 `structuredContent`,可以对任意数据工具(`list_artboards`、`get_artboard_spec`、`get_artboard_image`、`download_slice`、`verify_rendering`、`visual_diff`)传 `includeFullText: true`,改为接收完整 JSON 文本。`debug_collect_network` 的诊断记录本身就是输出内容,因此仍在文本通道中保留完整记录。
358
360
 
359
361
  所有 headless 工具复用同一个浏览器页面,分享页在每个会话中只打开一次,而不是每次工具调用都打开。登录用的 headed 窗口使用独占页面,模式切换会等待正在进行的调用结束。
360
362
 
@@ -376,7 +378,7 @@ CODESIGN_LOG_LEVEL=info
376
378
 
377
379
  ## 提示词
378
380
 
379
- - `implement_codesign_page`:为完整页面或复制的 CoDesign 选区生成结构化设计还原提示词,引导 Agent 按预期顺序调用 `list_artboards`、`get_artboard_spec`、`download_slice` 和 `verify_rendering`。
381
+ - `implement_codesign_page`:为完整页面或复制的 CoDesign 选区生成结构化设计还原提示词,引导 Agent 按预期顺序调用 `list_artboards`、`get_artboard_spec`、`download_slice`、`verify_rendering`,并可选用 `visual_diff`。
380
382
 
381
383
  ## 资源
382
384
 
@@ -385,10 +387,10 @@ CODESIGN_LOG_LEVEL=info
385
387
  设计还原建议优先使用:
386
388
 
387
389
  ```text
388
- list_artboards -> get_artboard_spec -> download_slice -> (写代码) -> verify_rendering
390
+ list_artboards -> get_artboard_spec -> download_slice -> (写代码) -> verify_rendering -> visual_diff(可选)
389
391
  ```
390
392
 
391
- `verify_rendering` 会自行重新拉取 spec,因此期望值不依赖写入提示词的数字。检查其 `issues` 与 `reviewRequired`,修复代码后重跑,直到 `ok: true`。预览截图只适合做视觉对比,不应作为生产切图来源。
393
+ `verify_rendering` 会自行重新拉取 spec,因此期望值不依赖写入提示词的数字。检查其 `issues` 与 `reviewRequired`,修复代码后重跑,直到 `ok: true`。`visual_diff` 是可选的额外信号:启动本地 dev server,传入其 `pageUrl`,比较多次运行的 `score`;分数下降说明某次改动损害了视觉还原度。预览截图只适合做视觉对比,不应作为生产切图来源。
392
394
 
393
395
  ## CoDesign AI 选区油猴脚本
394
396
 
@@ -185,6 +185,9 @@ export function createBrowserManager(launcher = defaultLauncher) {
185
185
  acquireHeadless() {
186
186
  return acquireCall('headless', true);
187
187
  },
188
+ acquireHeadlessIsolated() {
189
+ return acquireCall('headless', false);
190
+ },
188
191
  acquireHeaded() {
189
192
  return acquireCall('headed', false);
190
193
  },
@@ -23,6 +23,9 @@ export const ERROR_CODES = [
23
23
  'ARTIFACT_MAGIC_MISMATCH',
24
24
  'ARTIFACT_PATH_INVALID',
25
25
  'CODE_FILE_INVALID',
26
+ 'VISUAL_DIFF_IMAGE_INVALID',
27
+ 'VISUAL_DIFF_ALIGNMENT',
28
+ 'VISUAL_DIFF_PAGE_INVALID',
26
29
  ];
27
30
  export class CodesignError extends Error {
28
31
  code;
@@ -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
+ ];
@@ -141,6 +141,27 @@ export function summarizeVerifyPayload(payload) {
141
141
  lines.push('Full data is available in structuredContent.');
142
142
  return lines.join('\n');
143
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
+ }
144
165
  // 诊断记录本身就是给 LLM 阅读的内容,默认保留完整文本但不加缩进。
145
166
  export function toolSuccessFull(payload) {
146
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, download_slice, and verify_rendering in order.',
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: [
@@ -125,6 +125,7 @@ Requirements:
125
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
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. Use get_artboard_image only for visual comparison and final review.
129
- 14. Surface any CoDesign access, password, login, or missing-spec failure clearly instead of fabricating design data.`;
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.`;
130
131
  }
@@ -13,9 +13,10 @@ Use this workflow when a user asks an agent to implement, recreate, or inspect a
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
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
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. Use \`get_artboard_image\` only for visual comparison, review, or debugging.
17
- 12. 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.
18
- 13. Surface access, password, login, network, missing-artboard, and missing-spec failures clearly. Do not fabricate design data when the official CoDesign data is unavailable.
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.
19
20
  `;
20
21
  export function registerWorkflowResource(server) {
21
22
  server.registerResource('design-to-code-workflow', DESIGN_TO_CODE_WORKFLOW_URI, {
package/dist/server.js CHANGED
@@ -6,6 +6,7 @@ import { registerSpecTool } from './tools/spec.js';
6
6
  import { registerImageTool } from './tools/image.js';
7
7
  import { registerSlicesTool } from './tools/slices.js';
8
8
  import { registerVerifyRenderingTool } from './tools/verify-rendering.js';
9
+ import { registerVisualDiffTool } from './tools/visual-diff.js';
9
10
  import { registerDiagnosticsTool } from './tools/diagnostics.js';
10
11
  import { registerDesignToCodePrompt } from './prompts/design-to-code.js';
11
12
  import { registerWorkflowResource } from './resources/workflow.js';
@@ -32,6 +33,7 @@ export function buildServer() {
32
33
  registerImageTool(server);
33
34
  registerSlicesTool(server);
34
35
  registerVerifyRenderingTool(server);
36
+ registerVisualDiffTool(server);
35
37
  registerDiagnosticsTool(server);
36
38
  registerDesignToCodePrompt(server);
37
39
  registerWorkflowResource(server);
@@ -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.4",
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 tests/verify-rendering.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
- "playwright": "1.60.0"
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
  }