codesign-mcp-next 0.3.3 → 0.3.4

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.4 - 2026-11-26
4
+
5
+ ### Added
6
+
7
+ - Added `verify_rendering`, a read-only tool that re-fetches the official spec, rebuilds `platformSpec`, and statically checks generated code for size, slice scale, color, typography, radius, and hierarchy. Slice usages are located via `data-slice-id="<layerObjectId>"` attributes or `/* slice:<layerObjectId> */` comments. It reports per-file/line issues and a `reviewRequired` list for areas that cannot be statically resolved, and returns `ok: false` when a hard check fails.
8
+ - Added `designSize` to `download_slice` results when `targetPlatform` is supplied: the converted layout width/height a slice must be displayed at, so 2x assets are shown at design size rather than pixel size.
9
+ - Added `CODE_FILE_INVALID` for missing, oversized, or out-of-workspace code files passed to `verify_rendering`.
10
+
11
+ ### Changed
12
+
13
+ - Updated the design-to-code prompt, workflow resource, and skill to mark slice anchors and run `verify_rendering` before finishing.
14
+
3
15
  ## 0.3.3 - 2026-11-26
4
16
 
5
17
  ### Added
package/README.md CHANGED
@@ -118,14 +118,15 @@ CODESIGN_LOG_LEVEL=info
118
118
  - `list_artboards`: Resolve a CoDesign sharing URL into designs and artboards.
119
119
  - `get_artboard_spec`: Fetch official CoDesign `meta_url` specs with layers, text, colors, CSS, groups, and slice metadata. Every response includes a `spec.hierarchy` tree built from `parent_id` and `layerIndex`; each node carries `rect` (artboard-absolute), `relativeRect` (relative to the artboard), and `relativeToParent` (relative to its direct parent) so a full-page layout can be mapped to DOM without rebuilding the tree yourself. With `layerObjectId`, `selectionScope` can be `layer`, `subtree`, or `region`; selected responses also include flat layers/groups, selection bounds, and relative coordinates. Optional `targetPlatform` accepts natural-language platform names such as `web`, `Android`, `安卓`, `iOS`, `微信小程序`, or `mini program` and returns platform-adjusted metadata. Optional `targetUnit`, `customScale`, `customWidth`, and `remBasePx` mirror CoDesign's platform settings.
120
120
  - `get_artboard_image`: Fetch preview or cover images for visual comparison.
121
- - `download_slice`: Download designer-exported slice assets from the official slice manifest.
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
+ - `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.
122
123
  - `debug_collect_network`: Collect a redacted network summary for diagnosis.
123
124
 
124
125
  ## Caching and tool output
125
126
 
126
127
  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.
127
128
 
128
- 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`) 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.
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.
129
130
 
130
131
  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.
131
132
 
@@ -147,7 +148,7 @@ Remote metadata and artifact downloads are restricted to `https://codesign.qq.co
147
148
 
148
149
  ## Prompts
149
150
 
150
- - `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`, and `download_slice` in the intended order.
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.
151
152
 
152
153
  ## Resources
153
154
 
@@ -156,10 +157,10 @@ Remote metadata and artifact downloads are restricted to `https://codesign.qq.co
156
157
  For design-to-code work, prefer this flow:
157
158
 
158
159
  ```text
159
- list_artboards -> get_artboard_spec -> download_slice
160
+ list_artboards -> get_artboard_spec -> download_slice -> (write code) -> verify_rendering
160
161
  ```
161
162
 
162
- Preview screenshots are for visual comparison, not for production slicing.
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.
163
164
 
164
165
  ## CoDesign AI Selection Userscript
165
166
 
@@ -345,14 +346,15 @@ CODESIGN_LOG_LEVEL=info
345
346
  - `list_artboards`:把 CoDesign 分享链接解析为设计稿和画板列表。
346
347
  - `get_artboard_spec`:读取官方 CoDesign `meta_url` 标注数据,包括图层、文字、颜色、CSS、分组和切图元数据。所有结果都包含按 `parent_id` 与 `layerIndex` 构建的 `spec.hierarchy` 层级树;每个节点带 `rect`(相对画板绝对坐标)、`relativeRect`(相对画板)和 `relativeToParent`(相对直接父节点),整页还原可直接映射为 DOM,无需自行拼树。传入 `layerObjectId` 后,`selectionScope` 可设为 `layer`、`subtree` 或 `region`;选区结果还包含扁平图层/分组、选区边界和相对坐标。可选的 `targetPlatform` 支持 `web`、`Android`、`安卓`、`iOS`、`微信小程序`、`mini program` 等自然语言平台名称,并返回平台转换后的标注信息。`targetUnit`、`customScale`、`customWidth`、`remBasePx` 对应 CoDesign 的平台设置。
347
348
  - `get_artboard_image`:获取预览图或封面图,主要用于视觉对比。
348
- - `download_slice`:从官方切图清单下载设计师导出的切图资源。
349
+ - `download_slice`:从官方切图清单下载设计师导出的切图资源。传入与 `get_artboard_spec` 相同的 `targetPlatform`/单位/宽度参数时,会同时返回 `slice.designSize`,即该切图在代码中应显示的换算后布局宽高;2x 图必须按 `designSize` 显示,而不是按图片像素尺寸显示。
350
+ - `verify_rendering`:重新拉取官方 spec(不信任任何由模型转录的尺寸),重建 `platformSpec`,然后静态校验生成代码与设计稿是否一致。在每处切图使用点用 `data-slice-id="<图层objectId>"` 属性或 `/* slice:<图层objectId> */` 注释标注,传入代码文件与相同的平台参数,即可按文件/行号返回尺寸、倍率、颜色、字号、圆角、层级六个维度的 issue,并给出 `reviewRequired`(无法静态判定的区域清单)。任一硬性检查失败时返回 `ok: false`。只读,不修改文件。
349
351
  - `debug_collect_network`:收集脱敏后的网络摘要,用于诊断。
350
352
 
351
353
  ## 缓存与工具输出
352
354
 
353
355
  分享详情、标注 JSON 和切图清单会在内存中缓存 60 秒(`CODESIGN_CACHE_TTL_MS`,单位毫秒),相同资源的并发调用会合并为一次请求。设为 `0` 可关闭缓存。缓存只存在于当前进程,不会写入磁盘。
354
356
 
355
- 工具成功结果把完整数据放在 `structuredContent` 中,`content[0].text` 只返回简短摘要,避免同一份 JSON 在模型上下文里被计算两次。`get_artboard_spec` 的文本摘要还会带出两层 `hierarchy` 骨架、画板尺寸、图层/分组/切图数量以及完整性告警,因此不读取 `structuredContent` 的客户端也能拿到还原所需的结构信息。如果你的 MCP 客户端不读取 `structuredContent`,可以对任意数据工具(`list_artboards`、`get_artboard_spec`、`get_artboard_image`、`download_slice`)传 `includeFullText: true`,改为接收完整 JSON 文本。`debug_collect_network` 的诊断记录本身就是输出内容,因此仍在文本通道中保留完整记录。
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` 的诊断记录本身就是输出内容,因此仍在文本通道中保留完整记录。
356
358
 
357
359
  所有 headless 工具复用同一个浏览器页面,分享页在每个会话中只打开一次,而不是每次工具调用都打开。登录用的 headed 窗口使用独占页面,模式切换会等待正在进行的调用结束。
358
360
 
@@ -374,7 +376,7 @@ CODESIGN_LOG_LEVEL=info
374
376
 
375
377
  ## 提示词
376
378
 
377
- - `implement_codesign_page`:为完整页面或复制的 CoDesign 选区生成结构化设计还原提示词,引导 Agent 按预期顺序调用 `list_artboards`、`get_artboard_spec` 和 `download_slice`。
379
+ - `implement_codesign_page`:为完整页面或复制的 CoDesign 选区生成结构化设计还原提示词,引导 Agent 按预期顺序调用 `list_artboards`、`get_artboard_spec`、`download_slice` 和 `verify_rendering`。
378
380
 
379
381
  ## 资源
380
382
 
@@ -383,10 +385,10 @@ CODESIGN_LOG_LEVEL=info
383
385
  设计还原建议优先使用:
384
386
 
385
387
  ```text
386
- list_artboards -> get_artboard_spec -> download_slice
388
+ list_artboards -> get_artboard_spec -> download_slice -> (写代码) -> verify_rendering
387
389
  ```
388
390
 
389
- 预览截图只适合做视觉对比,不应作为生产切图来源。
391
+ `verify_rendering` 会自行重新拉取 spec,因此期望值不依赖写入提示词的数字。检查其 `issues` 与 `reviewRequired`,修复代码后重跑,直到 `ok: true`。预览截图只适合做视觉对比,不应作为生产切图来源。
390
392
 
391
393
  ## CoDesign AI 选区油猴脚本
392
394
 
@@ -22,6 +22,7 @@ export const ERROR_CODES = [
22
22
  'ARTIFACT_SIZE_MISMATCH',
23
23
  'ARTIFACT_MAGIC_MISMATCH',
24
24
  'ARTIFACT_PATH_INVALID',
25
+ 'CODE_FILE_INVALID',
25
26
  ];
26
27
  export class CodesignError extends Error {
27
28
  code;
@@ -0,0 +1,495 @@
1
+ // 还原度静态校验的纯函数部分:锚点解析、代码声明提取、六维度比对、盲区枚举。
2
+ // 不依赖浏览器/网络,便于单测。期望值一律由调用方传入(MCP 工具层重新拉 spec 重建)。
3
+ export const VERIFY_CHECKS = ['size', 'scale', 'color', 'typography', 'radius', 'hierarchy'];
4
+ const WINDOW_LINES = 16;
5
+ const ATTR_RE = /data-slice-id\s*=\s*["'`]([^"'`]+)["'`]/gi;
6
+ const COMMENT_RE = /\/\*\s*slice\s*[::]\s*([^*]+?)\s*\*\//gi;
7
+ const NUM = '(-?\\d+(?:\\.\\d+)?)';
8
+ const UNIT = '(px|rem|rpx|dp|pt|%)?';
9
+ function cssProp(prop) {
10
+ return new RegExp(`(?:^|[;{\\s])${prop}\\s*:\\s*${NUM}\\s*${UNIT}`, 'gi');
11
+ }
12
+ function htmlAttr(prop) {
13
+ return new RegExp(`${prop}\\s*=\\s*["']${NUM}${UNIT}["']`, 'gi');
14
+ }
15
+ const BG_SIZE_RE = new RegExp(`background-size\\s*:\\s*${NUM}\\s*${UNIT}[\\s,]+${NUM}\\s*${UNIT}`, 'gi');
16
+ const URL_RE = /(?:url\(\s*["']?|src\s*=\s*["'])([^"')>\s]+)/gi;
17
+ const COLOR_RE = /#[0-9a-fA-F]{3,8}\b|rgba?\([^)]+\)/g;
18
+ function extractAnchors(files) {
19
+ const anchors = [];
20
+ for (const file of files) {
21
+ const lines = file.text.split(/\r?\n/);
22
+ for (let i = 0; i < lines.length; i += 1) {
23
+ const line = lines[i];
24
+ for (const [pattern, kind] of [
25
+ [ATTR_RE, 'attribute'],
26
+ [COMMENT_RE, 'comment'],
27
+ ]) {
28
+ pattern.lastIndex = 0;
29
+ let match;
30
+ while ((match = pattern.exec(line)) !== null) {
31
+ const objectId = match[1].trim();
32
+ if (!objectId)
33
+ continue;
34
+ const end = Math.min(lines.length, i + WINDOW_LINES);
35
+ anchors.push({
36
+ objectId,
37
+ kind,
38
+ file: file.path,
39
+ line: i + 1,
40
+ block: lines.slice(i, end).join('\n'),
41
+ });
42
+ }
43
+ }
44
+ }
45
+ }
46
+ return anchors;
47
+ }
48
+ function firstValue(block, prop) {
49
+ const css = cssProp(prop);
50
+ const match = css.exec(block);
51
+ if (match)
52
+ return { value: Number(match[1]), unit: (match[2] ?? '').toLowerCase() };
53
+ const attr = htmlAttr(prop);
54
+ const attrMatch = attr.exec(block);
55
+ if (attrMatch)
56
+ return { value: Number(attrMatch[1]), unit: (attrMatch[2] ?? '').toLowerCase() };
57
+ return undefined;
58
+ }
59
+ function extractDeclarations(block) {
60
+ const declarations = {
61
+ width: firstValue(block, 'width'),
62
+ height: firstValue(block, 'height'),
63
+ fontSize: firstValue(block, 'font-size'),
64
+ lineHeight: firstValue(block, 'line-height'),
65
+ radius: firstValue(block, 'border-radius'),
66
+ colors: [],
67
+ assetRefs: [],
68
+ };
69
+ BG_SIZE_RE.lastIndex = 0;
70
+ const bg = BG_SIZE_RE.exec(block);
71
+ if (bg) {
72
+ declarations.backgroundSize = [
73
+ { value: Number(bg[1]), unit: (bg[2] ?? '').toLowerCase() },
74
+ { value: Number(bg[3]), unit: (bg[4] ?? '').toLowerCase() },
75
+ ];
76
+ }
77
+ let match;
78
+ COLOR_RE.lastIndex = 0;
79
+ while ((match = COLOR_RE.exec(block)) !== null)
80
+ declarations.colors.push(normalizeColor(match[0]));
81
+ URL_RE.lastIndex = 0;
82
+ while ((match = URL_RE.exec(block)) !== null)
83
+ declarations.assetRefs.push(match[1]);
84
+ return declarations;
85
+ }
86
+ function normalizeColor(raw) {
87
+ const value = raw.trim().toLowerCase();
88
+ if (value.startsWith('#')) {
89
+ const hex = value.slice(1);
90
+ if (hex.length === 3)
91
+ return `#${hex.split('').map((c) => c + c).join('')}`;
92
+ return `#${hex}`;
93
+ }
94
+ const numbers = value.match(/\d+(?:\.\d+)?/g) ?? [];
95
+ return `rgba(${numbers.slice(0, 4).join(',')})`;
96
+ }
97
+ // 统一以 px 为基准:rem 用 remBasePx 换算,px 原值,
98
+ // rpx/dp/pt 只在与目标平台同单位时按数值直接比较(跨单位无法静态换算)。
99
+ function toPixels(value, platform) {
100
+ const unit = value.unit || platform.unit;
101
+ if (unit === 'rem')
102
+ return value.value * remBase(platform);
103
+ if (unit === 'px')
104
+ return value.value;
105
+ if (unit === platform.unit)
106
+ return value.value;
107
+ return undefined;
108
+ }
109
+ function remBase(platform) {
110
+ const base = platform.conversion.remBasePx;
111
+ return typeof base === 'number' && base > 0 ? base : 16;
112
+ }
113
+ function expectedPixels(value, platform) {
114
+ return platform.unit === 'rem' ? value * remBase(platform) : value;
115
+ }
116
+ function compareSize(expected, platform, actual) {
117
+ if (!actual || actual.unit === '%')
118
+ return { status: 'unverifiable' };
119
+ const actualPx = toPixels(actual, platform);
120
+ const expectedPx = expectedPixels(expected, platform);
121
+ if (actualPx == null || !Number.isFinite(expectedPx) || expectedPx <= 0)
122
+ return { status: 'unverifiable' };
123
+ const ratio = actualPx / expectedPx;
124
+ if (Math.abs(ratio - 1) <= 0.02 || Math.abs(actualPx - expectedPx) <= 1) {
125
+ return { status: 'pass', actualPx };
126
+ }
127
+ if (Math.abs(ratio - 2) <= 0.02)
128
+ return { status: 'double', actualPx };
129
+ return { status: 'mismatch', actualPx };
130
+ }
131
+ function detectScaleRefs(refs) {
132
+ const scales = new Set();
133
+ for (const ref of refs) {
134
+ const match = ref.match(/@(\d)x|[-_](\d)x\.|scale[=_-]?(\d)/i);
135
+ if (!match)
136
+ continue;
137
+ const value = Number(match[1] ?? match[2] ?? match[3]);
138
+ if ([1, 2, 3, 4].includes(value))
139
+ scales.add(value);
140
+ }
141
+ return [...scales];
142
+ }
143
+ function expectedColors(layer) {
144
+ const found = [];
145
+ const visit = (value, depth) => {
146
+ if (depth > 4 || found.length > 8)
147
+ return;
148
+ if (typeof value === 'string') {
149
+ let match;
150
+ COLOR_RE.lastIndex = 0;
151
+ while ((match = COLOR_RE.exec(value)) !== null)
152
+ found.push(normalizeColor(match[0]));
153
+ return;
154
+ }
155
+ if (Array.isArray(value)) {
156
+ for (const item of value)
157
+ visit(item, depth + 1);
158
+ return;
159
+ }
160
+ if (value && typeof value === 'object') {
161
+ for (const [key, item] of Object.entries(value)) {
162
+ if (/color|fill|stroke|background/i.test(key))
163
+ visit(item, depth + 1);
164
+ }
165
+ }
166
+ };
167
+ if (layer.fills)
168
+ visit(layer.fills, 0);
169
+ if (layer.color)
170
+ visit(layer.color, 0);
171
+ return [...new Set(found)];
172
+ }
173
+ function reviewReasons(layer) {
174
+ const reasons = [];
175
+ const extra = layer;
176
+ if (Array.isArray(extra.masks) && extra.masks.length > 0)
177
+ reasons.push('mask');
178
+ if (Array.isArray(layer.effects) && layer.effects.length > 0)
179
+ reasons.push('effect');
180
+ if (Array.isArray(layer.shadows) && layer.shadows.length > 0)
181
+ reasons.push('shadow');
182
+ const css = Array.isArray(layer.css) ? layer.css.join(' ') : (layer.css ?? '');
183
+ if (/gradient|mask|filter|backdrop-filter|blur|mix-blend/i.test(css))
184
+ reasons.push('css-complex');
185
+ if (layer.type === 'text' && !layer.content)
186
+ reasons.push('text-content-missing');
187
+ return reasons;
188
+ }
189
+ function collectOrder(nodes, output = []) {
190
+ for (const node of nodes) {
191
+ if (!node || typeof node !== 'object')
192
+ continue;
193
+ const record = node;
194
+ const id = record.object_id ?? record.objectId ?? record.id;
195
+ if (typeof id === 'string' && id && !output.includes(id))
196
+ output.push(id);
197
+ for (const key of ['children', 'layers', 'groups']) {
198
+ const child = record[key];
199
+ if (Array.isArray(child))
200
+ collectOrder(child, output);
201
+ }
202
+ }
203
+ return output;
204
+ }
205
+ function scaleFromManifest(manifest, objectId) {
206
+ const item = manifest.find((entry) => entry.object_id === objectId);
207
+ if (!item)
208
+ return [];
209
+ return [...new Set(item.exportables.map((e) => e.scale).filter((s) => typeof s === 'number'))];
210
+ }
211
+ export function verifyRendering(input) {
212
+ const checks = new Set(input.checks ?? VERIFY_CHECKS);
213
+ const expectedScale = input.scale ?? 2;
214
+ const anchors = extractAnchors(input.files);
215
+ const allLayers = [...input.layers, ...input.groups];
216
+ const layerByObjectId = new Map(allLayers.map((layer) => [layer.object_id, layer]));
217
+ const platformByObjectId = new Map([...input.platformSpec.layers, ...input.platformSpec.groups].map((layer) => [layer.objectId, layer]));
218
+ const issues = [];
219
+ const seen = new Set();
220
+ let pass = 0;
221
+ const addIssue = (issue) => {
222
+ issues.push(issue);
223
+ };
224
+ for (const anchor of anchors) {
225
+ const layer = layerByObjectId.get(anchor.objectId);
226
+ if (!layer) {
227
+ addIssue({
228
+ code: 'ANCHOR_UNRESOLVED',
229
+ dimension: 'parse',
230
+ severity: 'warning',
231
+ layerObjectId: anchor.objectId,
232
+ file: anchor.file,
233
+ line: anchor.line,
234
+ message: `anchor ${anchor.objectId} does not match any spec layer`,
235
+ });
236
+ continue;
237
+ }
238
+ seen.add(anchor.objectId);
239
+ const declarations = extractDeclarations(anchor.block);
240
+ const platformLayer = platformByObjectId.get(anchor.objectId);
241
+ if (checks.has('size') && platformLayer) {
242
+ for (const [axis, actual] of [
243
+ ['width', declarations.width],
244
+ ['height', declarations.height],
245
+ ]) {
246
+ const result = compareSize(platformLayer.rect[axis], input.platformSpec, actual);
247
+ const expectedText = `${platformLayer.rect[axis]}${platformLayer.rect.unit}`;
248
+ const actualText = actual ? `${actual.value}${actual.unit || input.platformSpec.unit}` : null;
249
+ if (result.status === 'pass') {
250
+ pass += 1;
251
+ }
252
+ else if (result.status === 'double') {
253
+ addIssue({
254
+ code: 'DOUBLE_SCALE',
255
+ dimension: 'size',
256
+ severity: 'error',
257
+ layerObjectId: anchor.objectId,
258
+ file: anchor.file,
259
+ line: anchor.line,
260
+ expected: expectedText,
261
+ actual: actualText,
262
+ message: `${axis} is about 2x the design size (2x asset must be displayed at design size)`,
263
+ });
264
+ }
265
+ else if (result.status === 'mismatch') {
266
+ addIssue({
267
+ code: 'SIZE_MISMATCH',
268
+ dimension: 'size',
269
+ severity: 'error',
270
+ layerObjectId: anchor.objectId,
271
+ file: anchor.file,
272
+ line: anchor.line,
273
+ expected: expectedText,
274
+ actual: actualText,
275
+ message: `${axis} does not match the design size`,
276
+ });
277
+ }
278
+ else {
279
+ addIssue({
280
+ code: 'UNVERIFIABLE',
281
+ dimension: 'size',
282
+ severity: 'warning',
283
+ layerObjectId: anchor.objectId,
284
+ file: anchor.file,
285
+ line: anchor.line,
286
+ expected: expectedText,
287
+ actual: actualText,
288
+ message: `${axis} cannot be statically resolved (external class, percentage, or dynamic style)`,
289
+ });
290
+ }
291
+ }
292
+ if (declarations.backgroundSize) {
293
+ const [bgWidth, bgHeight] = declarations.backgroundSize;
294
+ for (const [axis, actual] of [
295
+ ['width', bgWidth],
296
+ ['height', bgHeight],
297
+ ]) {
298
+ const result = compareSize(platformLayer.rect[axis], input.platformSpec, actual);
299
+ if (result.status === 'pass')
300
+ pass += 1;
301
+ else if (result.status !== 'unverifiable') {
302
+ addIssue({
303
+ code: result.status === 'double' ? 'DOUBLE_SCALE' : 'SIZE_MISMATCH',
304
+ dimension: 'size',
305
+ severity: 'error',
306
+ layerObjectId: anchor.objectId,
307
+ file: anchor.file,
308
+ line: anchor.line,
309
+ expected: `${platformLayer.rect[axis]}${platformLayer.rect.unit}`,
310
+ actual: `${actual.value}${actual.unit || input.platformSpec.unit}`,
311
+ message: `background-size ${axis} does not match the design size`,
312
+ });
313
+ }
314
+ }
315
+ }
316
+ }
317
+ if (checks.has('scale')) {
318
+ const assetScales = detectScaleRefs(declarations.assetRefs);
319
+ const wrong = assetScales.filter((scale) => scale !== expectedScale);
320
+ if (wrong.length > 0) {
321
+ addIssue({
322
+ code: 'WRONG_SCALE_ASSET',
323
+ dimension: 'scale',
324
+ severity: 'error',
325
+ layerObjectId: anchor.objectId,
326
+ file: anchor.file,
327
+ line: anchor.line,
328
+ expected: `${expectedScale}x`,
329
+ actual: wrong.map((s) => `${s}x`).join(','),
330
+ message: `code references a non-${expectedScale}x slice asset`,
331
+ });
332
+ }
333
+ else if (assetScales.includes(expectedScale)) {
334
+ pass += 1;
335
+ }
336
+ const available = scaleFromManifest(input.manifest, anchor.objectId);
337
+ if (available.length > 0 && !available.includes(expectedScale)) {
338
+ addIssue({
339
+ code: 'SCALE_UNAVAILABLE',
340
+ dimension: 'scale',
341
+ severity: 'error',
342
+ layerObjectId: anchor.objectId,
343
+ file: anchor.file,
344
+ line: anchor.line,
345
+ expected: `${expectedScale}x`,
346
+ actual: available.map((s) => `${s}x`).join(','),
347
+ message: `design manifest has no ${expectedScale}x export for this layer`,
348
+ });
349
+ }
350
+ }
351
+ if (checks.has('typography')) {
352
+ if (layer.fontSize != null && declarations.fontSize) {
353
+ const expectedFont = expectedPixels(layer.fontSize * input.platformSpec.scale, input.platformSpec);
354
+ const result = compareSize(expectedFont, input.platformSpec, declarations.fontSize);
355
+ if (result.status === 'pass')
356
+ pass += 1;
357
+ else if (result.status !== 'unverifiable') {
358
+ addIssue({
359
+ code: 'FONT_SIZE_MISMATCH',
360
+ dimension: 'typography',
361
+ severity: 'warning',
362
+ layerObjectId: anchor.objectId,
363
+ file: anchor.file,
364
+ line: anchor.line,
365
+ expected: `${expectedFont}${input.platformSpec.unit}`,
366
+ actual: `${declarations.fontSize.value}${declarations.fontSize.unit || input.platformSpec.unit}`,
367
+ message: 'font-size does not match the design annotation',
368
+ });
369
+ }
370
+ }
371
+ if (layer.lineHeight != null && declarations.lineHeight) {
372
+ const expectedLine = expectedPixels(layer.lineHeight * input.platformSpec.scale, input.platformSpec);
373
+ const result = compareSize(expectedLine, input.platformSpec, declarations.lineHeight);
374
+ if (result.status === 'pass')
375
+ pass += 1;
376
+ else if (result.status !== 'unverifiable') {
377
+ addIssue({
378
+ code: 'LINE_HEIGHT_MISMATCH',
379
+ dimension: 'typography',
380
+ severity: 'warning',
381
+ layerObjectId: anchor.objectId,
382
+ file: anchor.file,
383
+ line: anchor.line,
384
+ expected: `${expectedLine}${input.platformSpec.unit}`,
385
+ actual: `${declarations.lineHeight.value}${declarations.lineHeight.unit || input.platformSpec.unit}`,
386
+ message: 'line-height does not match the design annotation',
387
+ });
388
+ }
389
+ }
390
+ }
391
+ if (checks.has('radius')) {
392
+ const radius = Array.isArray(layer.radius) ? layer.radius[0] : layer.radius;
393
+ if (typeof radius === 'number' && declarations.radius) {
394
+ const expectedRadius = expectedPixels(radius * input.platformSpec.scale, input.platformSpec);
395
+ const result = compareSize(expectedRadius, input.platformSpec, declarations.radius);
396
+ if (result.status === 'pass')
397
+ pass += 1;
398
+ else if (result.status !== 'unverifiable') {
399
+ addIssue({
400
+ code: 'RADIUS_MISMATCH',
401
+ dimension: 'radius',
402
+ severity: 'warning',
403
+ layerObjectId: anchor.objectId,
404
+ file: anchor.file,
405
+ line: anchor.line,
406
+ expected: `${expectedRadius}${input.platformSpec.unit}`,
407
+ actual: `${declarations.radius.value}${declarations.radius.unit || input.platformSpec.unit}`,
408
+ message: 'border-radius does not match the design annotation',
409
+ });
410
+ }
411
+ }
412
+ }
413
+ if (checks.has('color') && declarations.colors.length > 0) {
414
+ const expected = expectedColors(layer);
415
+ if (expected.length > 0 && !expected.some((color) => declarations.colors.includes(color))) {
416
+ addIssue({
417
+ code: 'COLOR_MISMATCH',
418
+ dimension: 'color',
419
+ severity: 'warning',
420
+ layerObjectId: anchor.objectId,
421
+ file: anchor.file,
422
+ line: anchor.line,
423
+ expected: expected.slice(0, 3).join(','),
424
+ actual: declarations.colors.slice(0, 3).join(','),
425
+ message: 'no code color matches the design fills (CSS variables may need mapping)',
426
+ });
427
+ }
428
+ else if (expected.length > 0) {
429
+ pass += 1;
430
+ }
431
+ }
432
+ }
433
+ if (checks.has('hierarchy')) {
434
+ const expectedOrder = collectOrder(input.hierarchy).filter((id) => seen.has(id));
435
+ const actualOrder = anchors.map((anchor) => anchor.objectId).filter((id, index, list) => seen.has(id) && list.indexOf(id) === index);
436
+ for (let i = 0; i < Math.min(expectedOrder.length, actualOrder.length); i += 1) {
437
+ if (expectedOrder[i] === actualOrder[i])
438
+ pass += 1;
439
+ else {
440
+ const first = anchors.find((anchor) => anchor.objectId === actualOrder[i]);
441
+ addIssue({
442
+ code: 'HIERARCHY_ORDER',
443
+ dimension: 'hierarchy',
444
+ severity: 'warning',
445
+ layerObjectId: actualOrder[i],
446
+ file: first?.file ?? '',
447
+ line: first?.line ?? 0,
448
+ expected: expectedOrder[i],
449
+ actual: actualOrder[i],
450
+ message: 'anchor order differs from the design hierarchy',
451
+ });
452
+ break;
453
+ }
454
+ }
455
+ }
456
+ const unusedSlices = input.manifest
457
+ .filter((item) => item.exportables.some((e) => e.scale === expectedScale))
458
+ .map((item) => item.object_id)
459
+ .filter((id) => !seen.has(id));
460
+ for (const objectId of unusedSlices) {
461
+ addIssue({
462
+ code: 'SLICE_UNUSED',
463
+ dimension: 'asset',
464
+ severity: 'error',
465
+ layerObjectId: objectId,
466
+ file: '',
467
+ line: 0,
468
+ message: `design has a ${expectedScale}x slice but no code anchor uses it`,
469
+ });
470
+ }
471
+ const reviewRequired = [];
472
+ for (const layer of allLayers) {
473
+ const reasons = reviewReasons(layer);
474
+ if (reasons.length === 0)
475
+ continue;
476
+ const anchor = anchors.find((item) => item.objectId === layer.object_id);
477
+ reviewRequired.push({
478
+ layerObjectId: layer.object_id,
479
+ name: layer.name,
480
+ reasons,
481
+ file: anchor?.file,
482
+ line: anchor?.line,
483
+ });
484
+ }
485
+ const fail = issues.filter((issue) => issue.severity === 'error').length;
486
+ const warn = issues.filter((issue) => issue.severity === 'warning').length;
487
+ return {
488
+ ok: fail === 0,
489
+ summary: { pass, fail, warn },
490
+ issues,
491
+ reviewRequired,
492
+ anchors: anchors.length,
493
+ checkedSlices: input.manifest.filter((item) => item.exportables.some((e) => e.scale === expectedScale)).length,
494
+ };
495
+ }
@@ -122,6 +122,25 @@ 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
+ }
125
144
  // 诊断记录本身就是给 LLM 阅读的内容,默认保留完整文本但不加缩进。
126
145
  export function toolSuccessFull(payload) {
127
146
  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 download_slice in order.',
65
+ description: 'Generate a design-to-code workflow prompt that uses list_artboards, get_artboard_spec, download_slice, and verify_rendering 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,10 @@ 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. Use get_artboard_image only for visual comparison and final review.
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. Surface any CoDesign access, password, login, or missing-spec failure clearly instead of fabricating design data.`;
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
130
  }
@@ -11,10 +11,11 @@ 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. Use \`get_artboard_image\` only for visual comparison, review, or debugging.
16
- 11. 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.
17
- 12. Surface access, password, login, network, missing-artboard, and missing-spec failures clearly. Do not fabricate design data when the official CoDesign data is unavailable.
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. 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.
18
19
  `;
19
20
  export function registerWorkflowResource(server) {
20
21
  server.registerResource('design-to-code-workflow', DESIGN_TO_CODE_WORKFLOW_URI, {
package/dist/server.js CHANGED
@@ -5,6 +5,7 @@ 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';
8
9
  import { registerDiagnosticsTool } from './tools/diagnostics.js';
9
10
  import { registerDesignToCodePrompt } from './prompts/design-to-code.js';
10
11
  import { registerWorkflowResource } from './resources/workflow.js';
@@ -30,6 +31,7 @@ export function buildServer() {
30
31
  registerSpecTool(server);
31
32
  registerImageTool(server);
32
33
  registerSlicesTool(server);
34
+ registerVerifyRenderingTool(server);
33
35
  registerDiagnosticsTool(server);
34
36
  registerDesignToCodePrompt(server);
35
37
  registerWorkflowResource(server);
@@ -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
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codesign-mcp-next",
3
- "version": "0.3.3",
3
+ "version": "0.3.4",
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,7 +43,7 @@
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",
47
47
  "prepack": "npm run build",
48
48
  "install:browsers": "playwright install chromium"
49
49
  },