Commit da744985 by liimin

1

1 parent cb0c184f
Showing 20 changed files with 740 additions and 33 deletions
......@@ -3,7 +3,7 @@
"meta": {
"generator": "scripts/ai-direct-context.mjs",
"mode": "ai-direct",
"generatedAt": "2026-06-01T11:50:15.423Z",
"generatedAt": "2026-06-01T12:26:59.210Z",
"repoRoot": "D:/work/venus"
},
"figma": {
......@@ -1463,6 +1463,7 @@
"artifacts": {
"designContextFile": "d:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix/.ai-direct/allocationmanagement/allocationmanagement.design-context.html",
"variableDefsFile": "d:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix/.ai-direct/allocationmanagement/allocationmanagement.variable-defs.json",
"screenshotFile": "d:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix/.ai-direct/allocationmanagement/allocationmanagement.screenshot.png",
"promptFile": "d:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix/.ai-direct/allocationmanagement/allocationmanagement.prompt.md"
}
}
{
"meta": {
"generator": "scripts/ai-direct-execute.mjs",
"generatedAt": "2026-06-01T12:01:32.435Z",
"generatedAt": "2026-06-01T13:07:17.948Z",
"mode": "openai-compatible",
"bundleFile": "D:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix/.ai-direct/allocationmanagement/allocationmanagement.ai-direct-context-bundle.json",
"previewFile": "D:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix/.ai-direct/allocationmanagement/allocationmanagement.preview-project.json",
"responseFile": "D:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix/.ai-direct/allocationmanagement/allocationmanagement.provider-response.json",
"validationFile": "D:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix/.ai-direct/allocationmanagement/allocationmanagement.provider-response.validation-result.json"
},
"status": "failed",
"repairArtifacts": {
"feedbackFile": "D:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix/.ai-direct/allocationmanagement/allocationmanagement.provider-response.repair-feedback.json",
"requestFile": "D:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix/.ai-direct/allocationmanagement/allocationmanagement.provider-response.repair-request.md"
}
"status": "passed",
"repairRoundsAttempted": 0
}
{
"meta": {
"generator": "scripts/ai-direct-preview-project.mjs",
"generatedAt": "2026-06-01T11:59:12.656Z",
"generatedAt": "2026-06-01T13:01:06.795Z",
"mode": "reuse-existing",
"bundleFile": "D:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix/.ai-direct/allocationmanagement/allocationmanagement.ai-direct-context-bundle.json"
},
......
......@@ -12,6 +12,7 @@
- Read `allocationmanagement.ai-direct-context-bundle.json` first for project constraints and component facts.
- Read `allocationmanagement.design-context.html` as the raw Figma developer MCP context.
- Read `allocationmanagement.variable-defs.json` for design token and variable hints.
- Read `allocationmanagement.screenshot.png` as the rendered screenshot context of the selected Figma node.
## Project UI Packages
......
{
"meta": {
"generator": "scripts/ai-direct-apply-output.mjs",
"generatedAt": "2026-06-01T12:09:27.579Z",
"generatedAt": "2026-06-01T13:05:34.471Z",
"responseFile": "D:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix/.ai-direct/allocationmanagement/allocationmanagement.provider-response.json",
"previewFile": "D:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix/.ai-direct/allocationmanagement/allocationmanagement.preview-project.json"
},
......@@ -11,7 +11,7 @@
{
"path": "apps/web/ai-previews/allocationmanagement-qwen-autofix/src/views/AllocationManagement.vue",
"language": "vue",
"purpose": "调拨管理页面主文件,修复 TypeScript 类型检查错误"
"purpose": "调拨管理页面主视图"
}
],
"autoFixResults": [
......@@ -35,19 +35,20 @@
"dependencyPlan": {
"needsDependencyChange": false,
"packages": [],
"reason": "所有使用的组件均在项目已安装的 @vui/vue 和 element-plus 中,无需新增依赖。"
"reason": "所需组件 @vui/vue 和 element-plus 均已在项目中安装。"
},
"notes": [
"修复 type-check 失败:为 form、options、columns、tableData 显式声明 TypeScript 接口,避免 vue-tsc 推断过窄或报错。",
"修复 VTable 插槽类型错误:在 columns 中补充 actions 列定义,并在 template 的 #actions 插槽中使用 `row as TableRow` 断言,确保类型安全。",
"VUI 当前未提供分页组件,因此分页功能降级使用 element-plus 的 ElPagination。",
"表格中的多行文本通过 CSS white-space: pre-line 实现换行效果。"
"VUI 组件 VSelect 和 VInput 优先使用,分页组件因 VUI 未提供而降级使用 element-plus 的 ElPagination。",
"表格多行文本通过 CSS white-space: pre-line 实现,以还原 Figma 中的换行效果。",
"严格遵循多行标签首属性与标签名同行的 lint 规则。"
],
"validationChecklist": [
"通过 lint 和 type-check",
"组件导入合法且符合 VUI 优先规则",
"页面样式完整,无需额外补充",
"所有变量与 props 具备明确的 TypeScript 类型声明"
"通过 lint、typecheck、template contract、review trigger 和 fitness 等根级质量门禁。",
"未引入项目中不存在的组件 import。",
"未绕过项目现有路由、目录和命名约定。",
"优先满足 VUI 第一顺位与按框架降级的规则。",
"预览项目基于 Venus CLI 生成的项目结构。",
"预览页面不依赖模板演示壳层样式,生成文件本身包含可运行的页面结构与样式。"
]
}
}
{
"meta": {
"generator": "scripts/ai-direct-validate-output.mjs",
"generatedAt": "2026-06-01T12:09:48.919Z",
"generatedAt": "2026-06-01T13:07:17.910Z",
"responseFile": "D:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix/.ai-direct/allocationmanagement/allocationmanagement.provider-response.json",
"previewFile": "D:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix/.ai-direct/allocationmanagement/allocationmanagement.preview-project.json",
"bundleFile": "D:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix/.ai-direct/allocationmanagement/allocationmanagement.ai-direct-context-bundle.json"
......
......@@ -46,8 +46,13 @@ Vue SFC 输出规则:
- template 内遵守 Vue lint:多属性组件每行只放 1 个属性,多行标签首属性仍与标签名同行,不要强制换到下一行。
- 属性顺序优先遵守 Vue lint 分组:v-model/指令 -> 其他属性 -> 事件。
- 能单行放下的原生标签保持单行;复杂组件使用多行属性并保持闭合标签对齐。
- 必须优先依据 Figma design context 中可见的布局线索还原页面:direction、gap、padding、宽高、对齐方式、字号、字重、边框、圆角、背景色和分区层次。
- 不要把设计稿简化成通用后台 demo 壳;若设计中没有额外标题、副标题、说明卡片或装饰块,不要自行添加。
- 筛选区、工具栏、表格区和分页区应按设计中的分组关系与横纵节奏摆放,避免平均铺满导致布局松散。
- 对于表格列、按钮组和筛选表单,尽量对齐设计里的字段宽度、行高、间距和主次层次,不要只追求“能显示”。
- 生成的页面必须包含完整的页面级样式;筛选区、表格区、卡片、间距、字号、宽度和响应式处理不能留给人工补救。
- 不要依赖模板 demo 壳层或全局渐变/居中样式来让页面看起来成立;在中性预览骨架里也必须结构完整。
- TypeScript 类型也必须一次正确,尤其是传给 VUI/Element Plus 的 columns、align、status 等联合类型,不要偷懒写成宽泛 string。
- 如果预览项目骨架已有 `src/router.ts` 等现有文件,优先修改现有文件,不要再生成冲突的 `src/router/index.ts` 一类并行结构。
- 变量命名、文件命名、组件导入与项目现状保持一致。
- 不要输出 markdown 代码块、解释性文字或伪代码,files[].content 必须是可直接落盘的源码。
......@@ -100,6 +105,7 @@ Vue SFC 输出规则:
- Read `allocationmanagement.ai-direct-context-bundle.json` first for project constraints and component facts.
- Read `allocationmanagement.design-context.html` as the raw Figma developer MCP context.
- Read `allocationmanagement.variable-defs.json` for design token and variable hints.
- Read `allocationmanagement.screenshot.png` as the rendered screenshot context of the selected Figma node.
## Project UI Packages
......@@ -132,7 +138,7 @@ Vue SFC 输出规则:
"meta": {
"generator": "scripts/ai-direct-context.mjs",
"mode": "ai-direct",
"generatedAt": "2026-06-01T11:50:15.423Z",
"generatedAt": "2026-06-01T12:26:59.210Z",
"repoRoot": "D:/work/venus"
},
"figma": {
......@@ -1592,6 +1598,7 @@ Vue SFC 输出规则:
"artifacts": {
"designContextFile": "d:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix/.ai-direct/allocationmanagement/allocationmanagement.design-context.html",
"variableDefsFile": "d:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix/.ai-direct/allocationmanagement/allocationmanagement.variable-defs.json",
"screenshotFile": "d:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix/.ai-direct/allocationmanagement/allocationmanagement.screenshot.png",
"promptFile": "d:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix/.ai-direct/allocationmanagement/allocationmanagement.prompt.md"
}
}
......@@ -5933,5 +5940,21 @@ definitions:
- 如无法确认某个 VUI 组件的 props 细节,优先保持组件合法、结构简洁,不要为了追求还原度写出高风险属性组合。
- 页面级样式必须直接在本次生成文件中给出;不要假设我会再去 `allocationmanagement-qwen-autofix` 之类的目标产物里手工补样式。
- 若生成 Vue 页面,请在页面文件中包含 `<style>`,并让页面在中性骨架下也具备完整布局和基本视觉层次。
- 请优先参考 design context 中可直接读取的布局与视觉参数,尽量还原真实的间距、分栏、输入控件宽度、表头层次与分页位置。
- 如果设计稿里没有某些装饰信息,不要自己脑补 banner、渐变块、统计卡或解释性文案。
- 传给表格组件的 columns 类型必须与目标组件兼容,尤其 `align` 只能使用合法联合字面量,而不是宽泛字符串。
- 如果预览骨架已有 `src/router.ts`,请直接修改它,不要新增 `src/router/index.ts` 与现有结构冲突。
# Screenshot Context
- Screenshot file: allocationmanagement.screenshot.png
- 该截图来自当前 Figma node 的渲染结果,请优先用它校正分区、留白、字段宽度、表格层次和分页位置。
# Screenshot Visual Summary
1. **整体布局**:垂直分块结构,自上而下依次为:顶部筛选表单区、中部列表标题与搜索区、主体数据表格区、底部分页区。
2. **筛选表单**:两行布局。每行左侧为文本标签(“调出方”、“调入方”),右侧并列两个带红色星号的下拉选择框(仓库、门店),下拉框宽度均等且水平对齐。
3. **列表头部**:左侧为加粗标题“调拨列表”,右侧为搜索输入框(前缀文本“调拨:”)及蓝色实心“查询”按钮,整体靠右对齐。
4. **表格结构**:10 列宽表格。表头浅灰色背景,深灰文字。列名依次为:序号、商品名称、规格、商品编码、系列、所属分类、所属仓库、所属门店、膜卷号、操作。
5. **表格样式**:表体白色背景,行高固定,行间有极细浅灰分割线。文本左对齐,最后一列“操作”显示蓝色“选择”链接。
6. **分页组件**:底部通栏布局。左侧显示总数“共 800 条”及“每页 10 条”下拉框;右侧为分页器,含翻页箭头、数字页码(当前页“1”为蓝色背景白字)、“跳至 [ ] 页”输入框。
7. **色彩规范**:主交互色为蓝色(查询按钮、当前页码、操作链接)。必填项前缀红色星号。表头背景色略深于表体白色背景。
```
1. **整体布局**:垂直分块结构,自上而下依次为:顶部筛选表单区、中部列表标题与搜索区、主体数据表格区、底部分页区。
2. **筛选表单**:两行布局。每行左侧为文本标签(“调出方”、“调入方”),右侧并列两个带红色星号的下拉选择框(仓库、门店),下拉框宽度均等且水平对齐。
3. **列表头部**:左侧为加粗标题“调拨列表”,右侧为搜索输入框(前缀文本“调拨:”)及蓝色实心“查询”按钮,整体靠右对齐。
4. **表格结构**:10 列宽表格。表头浅灰色背景,深灰文字。列名依次为:序号、商品名称、规格、商品编码、系列、所属分类、所属仓库、所属门店、膜卷号、操作。
5. **表格样式**:表体白色背景,行高固定,行间有极细浅灰分割线。文本左对齐,最后一列“操作”显示蓝色“选择”链接。
6. **分页组件**:底部通栏布局。左侧显示总数“共 800 条”及“每页 10 条”下拉框;右侧为分页器,含翻页箭头、数字页码(当前页“1”为蓝色背景白字)、“跳至 [ ] 页”输入框。
7. **色彩规范**:主交互色为蓝色(查询按钮、当前页码、操作链接)。必填项前缀红色星号。表头背景色略深于表体白色背景。
......@@ -143,6 +143,7 @@
"properties": {
"designContextFile": { "type": "string" },
"variableDefsFile": { "type": "string" },
"screenshotFile": { "type": "string" },
"promptFile": { "type": "string" }
},
"additionalProperties": false
......
......@@ -36,6 +36,7 @@
"ai:direct-messages": "node scripts/ai-direct-messages.mjs",
"ai:preview-project": "node scripts/ai-direct-preview-project.mjs",
"ai:apply-output": "node scripts/ai-direct-apply-output.mjs",
"ai:repair-output": "node scripts/ai-direct-repair-output.mjs",
"ai:validate-output": "node scripts/ai-direct-validate-output.mjs",
"ai:execute": "node scripts/ai-direct-execute.mjs",
"check:fitness": "node tools/fitness/engine.mjs",
......
......@@ -6,7 +6,13 @@ import process from "node:process";
import { loadComponentManifest } from "../packages/ai/design-mapper/src/index.mjs";
import { readProjectContext, toJson as toPrettyJson } from "../packages/ai/project-intelligence/src/index.mjs";
import { fetchDesignContext, fetchVariableDefs, isMcpAvailable, parseFigmaUrl } from "./mcp-bridge/figma-client.mjs";
import {
fetchDesignContext,
fetchScreenshot,
fetchVariableDefs,
isMcpAvailable,
parseFigmaUrl,
} from "./mcp-bridge/figma-client.mjs";
import { requireWorkspaceRoot } from "./workspace-root.mjs";
const repoRoot = requireWorkspaceRoot();
......@@ -57,6 +63,7 @@ function parseCliArgs() {
pageName: "",
pageTitle: "",
outputDir: "",
withoutScreenshot: false,
withoutVariables: false,
};
......@@ -79,6 +86,8 @@ function parseCliArgs() {
} else if (arg === "--output-dir" && next) {
parsed.outputDir = next;
index++;
} else if (arg === "--without-screenshot") {
parsed.withoutScreenshot = true;
} else if (arg === "--without-variables") {
parsed.withoutVariables = true;
}
......@@ -103,6 +112,21 @@ function normalizePath(targetPath) {
return targetPath.replaceAll("\\", "/");
}
function screenshotExtensionForMimeType(mimeType) {
switch (String(mimeType || "").toLowerCase()) {
case "image/jpeg":
case "image/jpg": {
return ".jpg";
}
case "image/webp": {
return ".webp";
}
default: {
return ".png";
}
}
}
function toRelativeSchemaPath(fromDir, targetFile) {
return normalizePath(path.relative(fromDir, targetFile));
}
......@@ -385,6 +409,7 @@ function buildAiPrompt({
bundleFileName,
designContextFileName,
variableDefsFileName,
screenshotFileName,
workspaceExports,
selectionRules,
}) {
......@@ -416,6 +441,9 @@ function buildAiPrompt({
if (variableDefsFileName) {
lines.push(`- Read \`${variableDefsFileName}\` for design token and variable hints.`);
}
if (screenshotFileName) {
lines.push(`- Read \`${screenshotFileName}\` as the rendered screenshot context of the selected Figma node.`);
}
lines.push(
"",
......@@ -465,6 +493,7 @@ function buildBundle({
pageSlug,
designContext,
variableDefsFile,
screenshotFile,
designContextFile,
promptFile,
workspaceExports,
......@@ -506,6 +535,7 @@ function buildBundle({
artifacts: {
designContextFile: normalizePath(designContextFile),
variableDefsFile: variableDefsFile ? normalizePath(variableDefsFile) : "",
screenshotFile: screenshotFile ? normalizePath(screenshotFile) : "",
promptFile: normalizePath(promptFile),
},
};
......@@ -549,9 +579,20 @@ async function run() {
const designContext = await fetchDesignContext(args.figmaUrl);
console.log(` ✓ design context: ${designContext.length} 字符`);
let screenshot = null;
if (!args.withoutScreenshot) {
console.log("\n[step 2] 拉取 Figma 截图上下文...");
try {
screenshot = await fetchScreenshot(args.figmaUrl);
console.log(` ✓ screenshot fetched (${screenshot.mimeType || "image/png"})`);
} catch (error) {
console.warn(` ⚠ 截图获取失败,继续生成上下文包: ${error.message}`);
}
}
let variableDefs = null;
if (!args.withoutVariables) {
console.log("\n[step 2] 拉取 Figma 变量定义...");
console.log("\n[step 3] 拉取 Figma 变量定义...");
try {
variableDefs = await fetchVariableDefs(args.figmaUrl);
console.log(" ✓ variable definitions fetched");
......@@ -560,7 +601,7 @@ async function run() {
}
}
console.log("\n[step 3] 读取项目上下文与组件事实源...");
console.log("\n[step 4] 读取项目上下文与组件事实源...");
const projectContext = readProjectContext(projectDir);
const { allDependencies } = extractDependencies(projectDir);
const projectUiPackages = detectProjectUiPackages(allDependencies);
......@@ -596,9 +637,12 @@ async function run() {
` → Fallback catalogs: ${fallbackCatalogs.map((catalog) => `${catalog.packageName}=${catalog.components.length}`).join(", ") || "none"}`,
);
console.log("\n[step 4] 写入上下文包...");
console.log("\n[step 5] 写入上下文包...");
const designContextFile = path.join(outputDir, `${pageSlug}.design-context.html`);
const variableDefsFile = variableDefs ? path.join(outputDir, `${pageSlug}.variable-defs.json`) : "";
const screenshotFile = screenshot
? path.join(outputDir, `${pageSlug}.screenshot${screenshotExtensionForMimeType(screenshot.mimeType)}`)
: "";
const promptFile = path.join(outputDir, `${pageSlug}.prompt.md`);
const bundleFile = path.join(outputDir, `${pageSlug}.ai-direct-context-bundle.json`);
......@@ -611,6 +655,7 @@ async function run() {
bundleFileName: path.basename(bundleFile),
designContextFileName: path.basename(designContextFile),
variableDefsFileName: variableDefsFile ? path.basename(variableDefsFile) : "",
screenshotFileName: screenshotFile ? path.basename(screenshotFile) : "",
workspaceExports,
selectionRules: finalizedSelectionRules,
});
......@@ -628,6 +673,7 @@ async function run() {
pageSlug,
designContext,
variableDefsFile,
screenshotFile,
designContextFile,
promptFile,
workspaceExports,
......@@ -640,6 +686,9 @@ async function run() {
if (variableDefsFile) {
fs.writeFileSync(variableDefsFile, toPrettyJson(variableDefs), "utf8");
}
if (screenshotFile && screenshot?.base64) {
fs.writeFileSync(screenshotFile, Buffer.from(screenshot.base64, "base64"));
}
fs.writeFileSync(promptFile, promptContent, "utf8");
fs.writeFileSync(bundleFile, toPrettyJson(bundle), "utf8");
......@@ -650,6 +699,9 @@ async function run() {
if (variableDefsFile) {
console.log(` → variable defs: ${variableDefsFile}`);
}
if (screenshotFile) {
console.log(` → screenshot: ${screenshotFile}`);
}
}
run().catch((error) => {
......
......@@ -24,6 +24,8 @@ function parseCliArgs() {
responseFile: "",
provider: "",
model: "",
autoRepair: false,
maxRepairRounds: 1,
withoutVariables: false,
install: false,
refreshContext: false,
......@@ -70,8 +72,16 @@ function parseCliArgs() {
} else if (arg === "--model" && next) {
parsed.model = next;
index++;
} else if (arg === "--max-repair-rounds" && next) {
parsed.maxRepairRounds = Number.parseInt(next, 10) || 1;
index++;
} else
switch (arg) {
case "--auto-repair": {
parsed.autoRepair = true;
break;
}
case "--force": {
parsed.force = true;
......@@ -252,7 +262,9 @@ async function callOpenAiCompatible(messages, model) {
headers: {
"content-type": "application/json",
authorization: `Bearer ${apiKey}`,
connection: "close",
},
signal: AbortSignal.timeout(180000),
body: JSON.stringify({
model: resolvedModel,
temperature: 0.2,
......@@ -415,6 +427,10 @@ function buildRepairArtifacts({ bundle, preview, response, validation, responseP
return { feedbackPath, requestPath };
}
function shouldAttemptAutoRepair(args) {
return Boolean(args.autoRepair && args.provider === "openai-compatible" && !args.responseFile);
}
async function run() {
const args = parseCliArgs();
const bundlePath = deriveBundlePath(args);
......@@ -488,14 +504,18 @@ async function run() {
validationFile: normalizePath(validationPath),
},
status: validationPassed ? "passed" : "failed",
repairRoundsAttempted: 0,
};
let latestResponse = plainResponse;
let latestValidation = validation;
let repairArtifacts = null;
if (!validationPassed) {
const repairArtifacts = buildRepairArtifacts({
repairArtifacts = buildRepairArtifacts({
bundle,
preview,
response: plainResponse,
validation,
response: latestResponse,
validation: latestValidation,
responsePath: aiResult.responsePath,
});
summary.repairArtifacts = {
......@@ -504,6 +524,53 @@ async function run() {
};
}
while (!validationPassed && shouldAttemptAutoRepair(args) && summary.repairRoundsAttempted < args.maxRepairRounds) {
summary.repairRoundsAttempted += 1;
console.log(`[ai-direct-execute] 尝试第 ${summary.repairRoundsAttempted} 轮 repair...`);
try {
const repairArgs = [
"--response-file",
aiResult.responsePath,
"--preview-file",
previewPath,
"--provider",
args.provider,
"--request-file",
repairArtifacts.requestPath,
"--feedback-file",
repairArtifacts.feedbackPath,
];
if (args.model) {
repairArgs.push("--model", args.model);
}
runNodeScript("ai-direct-repair-output.mjs", repairArgs);
} catch {
// Repair script writes validation artifacts even on failure.
}
latestResponse = unwrapResponseFile(aiResult.responsePath);
latestValidation = readJson(validationPath);
validationPassed = latestValidation.status === "passed";
summary.status = validationPassed ? "passed" : "failed";
if (!validationPassed) {
repairArtifacts = buildRepairArtifacts({
bundle,
preview,
response: latestResponse,
validation: latestValidation,
responsePath: aiResult.responsePath,
});
summary.repairArtifacts = {
feedbackFile: normalizePath(repairArtifacts.feedbackPath),
requestFile: normalizePath(repairArtifacts.requestPath),
};
}
}
const summaryPath = path.join(
path.dirname(bundlePath),
`${path.basename(bundlePath, ".ai-direct-context-bundle.json")}.execute-result.json`,
......@@ -517,6 +584,7 @@ async function run() {
}
console.log("[ai-direct-execute] ✓ 完成");
process.exit(0);
}
run().catch((error) => {
......
......@@ -198,8 +198,13 @@ function buildSystemPrompt(bundle) {
"- template 内遵守 Vue lint:多属性组件每行只放 1 个属性,多行标签首属性仍与标签名同行,不要强制换到下一行。",
"- 属性顺序优先遵守 Vue lint 分组:v-model/指令 -> 其他属性 -> 事件。",
"- 能单行放下的原生标签保持单行;复杂组件使用多行属性并保持闭合标签对齐。",
"- 必须优先依据 Figma design context 中可见的布局线索还原页面:direction、gap、padding、宽高、对齐方式、字号、字重、边框、圆角、背景色和分区层次。",
"- 不要把设计稿简化成通用后台 demo 壳;若设计中没有额外标题、副标题、说明卡片或装饰块,不要自行添加。",
"- 筛选区、工具栏、表格区和分页区应按设计中的分组关系与横纵节奏摆放,避免平均铺满导致布局松散。",
"- 对于表格列、按钮组和筛选表单,尽量对齐设计里的字段宽度、行高、间距和主次层次,不要只追求“能显示”。",
"- 生成的页面必须包含完整的页面级样式;筛选区、表格区、卡片、间距、字号、宽度和响应式处理不能留给人工补救。",
"- 不要依赖模板 demo 壳层或全局渐变/居中样式来让页面看起来成立;在中性预览骨架里也必须结构完整。",
"- TypeScript 类型也必须一次正确,尤其是传给 VUI/Element Plus 的 columns、align、status 等联合类型,不要偷懒写成宽泛 string。",
"- 如果预览项目骨架已有 `src/router.ts` 等现有文件,优先修改现有文件,不要再生成冲突的 `src/router/index.ts` 一类并行结构。",
"- 变量命名、文件命名、组件导入与项目现状保持一致。",
"- 不要输出 markdown 代码块、解释性文字或伪代码,files[].content 必须是可直接落盘的源码。",
......@@ -254,10 +259,123 @@ function buildUserPrompt({ bundle, promptText, designContext, variableDefsText }
"- 如无法确认某个 VUI 组件的 props 细节,优先保持组件合法、结构简洁,不要为了追求还原度写出高风险属性组合。",
"- 页面级样式必须直接在本次生成文件中给出;不要假设我会再去 `allocationmanagement-qwen-autofix` 之类的目标产物里手工补样式。",
"- 若生成 Vue 页面,请在页面文件中包含 `<style>`,并让页面在中性骨架下也具备完整布局和基本视觉层次。",
"- 请优先参考 design context 中可直接读取的布局与视觉参数,尽量还原真实的间距、分栏、输入控件宽度、表头层次与分页位置。",
"- 如果设计稿里没有某些装饰信息,不要自己脑补 banner、渐变块、统计卡或解释性文案。",
"- 传给表格组件的 columns 类型必须与目标组件兼容,尤其 `align` 只能使用合法联合字面量,而不是宽泛字符串。",
"- 如果预览骨架已有 `src/router.ts`,请直接修改它,不要新增 `src/router/index.ts` 与现有结构冲突。",
].join("\n");
}
function resolveScreenshotMimeType(screenshotFilePath) {
const extension = path.extname(screenshotFilePath).toLowerCase();
if (extension === ".jpg" || extension === ".jpeg") {
return "image/jpeg";
}
if (extension === ".webp") {
return "image/webp";
}
return "image/png";
}
async function summarizeScreenshotWithVisionModel(screenshotFilePath) {
if (!screenshotFilePath || !fileExists(screenshotFilePath)) {
return "";
}
const baseUrl = process.env.AI_DIRECT_OPENAI_BASE_URL || process.env.OPENAI_BASE_URL;
const apiKey = process.env.AI_DIRECT_OPENAI_API_KEY || process.env.OPENAI_API_KEY;
const visionModel =
process.env.AI_DIRECT_VISION_MODEL ||
process.env.AI_DIRECT_OPENAI_VISION_MODEL ||
process.env.OPENAI_VISION_MODEL ||
"qwen3.6-plus";
if (!baseUrl || !apiKey || !visionModel) {
return "";
}
const mimeType = resolveScreenshotMimeType(screenshotFilePath);
const dataUrl = `data:${mimeType};base64,${fs.readFileSync(screenshotFilePath).toString("base64")}`;
const endpoint = `${baseUrl.replace(/\/$/, "")}/chat/completions`;
const response = await fetch(endpoint, {
method: "POST",
headers: {
"content-type": "application/json",
authorization: `Bearer ${apiKey}`,
connection: "close",
},
signal: AbortSignal.timeout(120_000),
body: JSON.stringify({
model: visionModel,
temperature: 0.1,
messages: [
{
role: "system",
content:
"你是 Venus 的截图视觉摘要器。请只基于页面截图,提取对页面还原最关键的视觉信息:整体分区结构、每个区域的对齐关系、间距节奏、输入框/按钮/表格/分页的大致尺寸与位置、标题层级、边框和背景色。输出 6-12 条简洁要点,不要输出解释性前缀。",
},
{
role: "user",
content: [
{
type: "text",
text: "请把这张 Figma 页面截图总结成用于前端还原的视觉要点。",
},
{
type: "image_url",
image_url: {
url: dataUrl,
},
},
],
},
],
}),
});
if (!response.ok) {
const errorText = (await response.text()).trim();
const errorPreview = errorText ? ` | ${errorText.slice(0, 600)}` : "";
throw new Error(`截图视觉摘要请求失败: ${response.status} ${response.statusText}${errorPreview}`);
}
const payload = await response.json();
return String(payload.choices?.[0]?.message?.content || "").trim();
}
function buildUserMessageContent({
bundle,
promptText,
designContext,
variableDefsText,
screenshotFilePath,
screenshotSummaryText,
}) {
const prompt = buildUserPrompt({ bundle, promptText, designContext, variableDefsText });
const sections = [prompt];
if (screenshotFilePath && fileExists(screenshotFilePath)) {
sections.push(
[
"# Screenshot Context",
`- Screenshot file: ${path.basename(screenshotFilePath)}`,
"- 该截图来自当前 Figma node 的渲染结果,请优先用它校正分区、留白、字段宽度、表格层次和分页位置。",
].join("\n"),
);
}
if (screenshotSummaryText) {
sections.push(
[
"# Screenshot Visual Summary",
screenshotSummaryText,
].join("\n"),
);
}
return sections.join("\n\n");
}
function buildRequestMarkdown({ bundle, messages }) {
return [
"# AI Direct Request",
......@@ -282,7 +400,7 @@ function buildRequestMarkdown({ bundle, messages }) {
].join("\n");
}
function run() {
async function run() {
const args = parseCliArgs();
const bundlePath = deriveBundlePath(args);
......@@ -300,9 +418,23 @@ function run() {
const designContext = fs.readFileSync(designContextPath, "utf8");
const variableDefsText =
variableDefsPath && fileExists(variableDefsPath) ? fs.readFileSync(variableDefsPath, "utf8") : "";
const screenshotPath = resolveArtifactPath(bundleDir, bundle.artifacts.screenshotFile);
const baseName = path.basename(bundlePath, ".ai-direct-context-bundle.json");
const messagesPath = path.join(bundleDir, `${baseName}.messages.json`);
const requestPath = path.join(bundleDir, `${baseName}.request.md`);
const screenshotSummaryPath = path.join(bundleDir, `${baseName}.screenshot-summary.md`);
let screenshotSummaryText = "";
if (screenshotPath && fileExists(screenshotPath)) {
try {
screenshotSummaryText = await summarizeScreenshotWithVisionModel(screenshotPath);
if (screenshotSummaryText) {
fs.writeFileSync(screenshotSummaryPath, `${screenshotSummaryText}\n`, "utf8");
}
} catch (error) {
console.warn(`[ai-direct-messages] warning: 截图视觉摘要生成失败,继续走文本上下文: ${error.message}`);
}
}
const messages = [
{
......@@ -311,7 +443,14 @@ function run() {
},
{
role: "user",
content: buildUserPrompt({ bundle, promptText, designContext, variableDefsText }),
content: buildUserMessageContent({
bundle,
promptText,
designContext,
variableDefsText,
screenshotFilePath: screenshotPath,
screenshotSummaryText,
}),
},
];
......@@ -332,4 +471,7 @@ function run() {
console.log(` → request: ${requestPath}`);
}
run();
run().catch((error) => {
console.error("[ai-direct-messages] 执行失败:", error.message);
process.exit(1);
});
#!/usr/bin/env node
import childProcess from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import process from "node:process";
import { requireWorkspaceRoot } from "./workspace-root.mjs";
const repoRoot = requireWorkspaceRoot();
function parseCliArgs() {
const args = process.argv.slice(2);
const parsed = {
responseFile: "",
previewFile: "",
messagesFile: "",
requestFile: "",
feedbackFile: "",
provider: "",
model: "",
};
for (let index = 0; index < args.length; index++) {
const arg = args[index];
const next = args[index + 1];
if (arg === "--response-file" && next) {
parsed.responseFile = next;
index++;
} else if (arg === "--preview-file" && next) {
parsed.previewFile = next;
index++;
} else if (arg === "--messages-file" && next) {
parsed.messagesFile = next;
index++;
} else if (arg === "--request-file" && next) {
parsed.requestFile = next;
index++;
} else if (arg === "--feedback-file" && next) {
parsed.feedbackFile = next;
index++;
} else if (arg === "--provider" && next) {
parsed.provider = next;
index++;
} else if (arg === "--model" && next) {
parsed.model = next;
index++;
}
}
return parsed;
}
function readJson(filePath) {
return JSON.parse(fs.readFileSync(filePath, "utf8"));
}
function normalizePath(targetPath) {
return targetPath.replaceAll("\\", "/");
}
function extractJsonPayload(text) {
const trimmed = String(text || "").trim();
if (!trimmed) {
throw new Error("AI 返回为空");
}
try {
return JSON.parse(trimmed);
} catch {}
const fencedMatch = trimmed.match(/```(?:json)?\s*([\s\S]*?)```/i);
if (fencedMatch) {
return JSON.parse(fencedMatch[1].trim());
}
const start = trimmed.indexOf("{");
const end = trimmed.lastIndexOf("}");
if (start !== -1 && end !== -1 && end > start) {
return JSON.parse(trimmed.slice(start, end + 1));
}
throw new Error("无法从 AI 返回中提取 JSON");
}
async function callOpenAiCompatible(messages, model) {
const baseUrl = process.env.AI_DIRECT_OPENAI_BASE_URL || process.env.OPENAI_BASE_URL;
const apiKey = process.env.AI_DIRECT_OPENAI_API_KEY || process.env.OPENAI_API_KEY;
const resolvedModel = model || process.env.AI_DIRECT_OPENAI_MODEL || process.env.OPENAI_MODEL;
if (!baseUrl || !apiKey || !resolvedModel) {
throw new Error(
"openai-compatible 模式需要配置 AI_DIRECT_OPENAI_BASE_URL、AI_DIRECT_OPENAI_API_KEY、AI_DIRECT_OPENAI_MODEL",
);
}
const endpoint = `${baseUrl.replace(/\/$/, "")}/chat/completions`;
const response = await fetch(endpoint, {
method: "POST",
headers: {
"content-type": "application/json",
authorization: `Bearer ${apiKey}`,
connection: "close",
},
signal: AbortSignal.timeout(180_000),
body: JSON.stringify({
model: resolvedModel,
temperature: 0.1,
response_format: { type: "json_object" },
messages,
}),
});
if (!response.ok) {
const errorText = (await response.text()).trim();
const errorPreview = errorText ? ` | ${errorText.slice(0, 600)}` : "";
throw new Error(`AI provider 请求失败: ${response.status} ${response.statusText}${errorPreview}`);
}
const payload = await response.json();
const content = payload.choices?.[0]?.message?.content;
return {
provider: "openai-compatible",
model: resolvedModel,
raw: payload,
content,
};
}
function runNodeScript(scriptFile, scriptArgs) {
const commandArgs = [path.join(repoRoot, "scripts", scriptFile), ...scriptArgs];
childProcess.execFileSync(process.execPath, commandArgs, {
cwd: repoRoot,
stdio: "inherit",
});
}
function deriveMessagesFile(responsePath) {
const dir = path.dirname(responsePath);
const baseName = path.basename(responsePath, ".provider-response.json");
return path.join(dir, `${baseName}.messages.json`);
}
function deriveRequestFile(responsePath) {
const baseName = path.basename(responsePath, ".json");
return path.join(path.dirname(responsePath), `${baseName}.repair-request.md`);
}
function deriveFeedbackFile(responsePath) {
const baseName = path.basename(responsePath, ".json");
return path.join(path.dirname(responsePath), `${baseName}.repair-feedback.json`);
}
function buildRepairMessages({ systemMessage, requestText, feedback }) {
const sections = [requestText.trim()];
if (feedback?.failedCommands?.length) {
sections.push(
[
"## Repair Focus",
"- 只修复失败项,不改变无关页面结构、样式和组件选型。",
"- 输出完整结构化 JSON,并保持既有 response schema。",
"- 如果问题来自 TypeScript 类型,请给出最小必要类型声明,不要扩大为宽泛 string/any。",
].join("\n"),
);
}
return [
{
role: "system",
content: systemMessage,
},
{
role: "user",
content: sections.join("\n\n"),
},
];
}
async function run() {
const args = parseCliArgs();
if (!args.responseFile || !args.previewFile) {
throw new Error(
"用法: node scripts/ai-direct-repair-output.mjs --response-file <response.json> --preview-file <preview.json> --provider openai-compatible",
);
}
if (!args.provider || args.provider !== "openai-compatible") {
throw new Error("当前 repair 仅支持 --provider openai-compatible");
}
const responsePath = path.resolve(args.responseFile);
const previewPath = path.resolve(args.previewFile);
const messagesPath = path.resolve(args.messagesFile || deriveMessagesFile(responsePath));
const requestPath = path.resolve(args.requestFile || deriveRequestFile(responsePath));
const feedbackPath = path.resolve(args.feedbackFile || deriveFeedbackFile(responsePath));
const messagesPayload = readJson(messagesPath);
const requestText = fs.readFileSync(requestPath, "utf8");
const feedback = fs.existsSync(feedbackPath) ? readJson(feedbackPath) : null;
const systemMessage = messagesPayload.messages?.[0]?.content;
if (!systemMessage) {
throw new Error(`messages 文件缺少 system message: ${messagesPath}`);
}
console.log("[ai-direct-repair-output] 开始执行 repair 回合...");
console.log(` → response: ${responsePath}`);
console.log(` → request: ${requestPath}`);
const providerResult = await callOpenAiCompatible(
buildRepairMessages({ systemMessage, requestText, feedback }),
args.model,
);
const structured = extractJsonPayload(providerResult.content);
fs.writeFileSync(responsePath, `${JSON.stringify(structured, null, 2)}\n`, "utf8");
runNodeScript("ai-direct-apply-output.mjs", ["--response-file", responsePath, "--preview-file", previewPath]);
let validationPassed = true;
try {
runNodeScript("ai-direct-validate-output.mjs", ["--response-file", responsePath, "--preview-file", previewPath]);
} catch {
validationPassed = false;
}
const validationPath = path.join(
path.dirname(responsePath),
`${path.basename(responsePath, path.extname(responsePath))}.validation-result.json`,
);
const validation = readJson(validationPath);
const summaryPath = path.join(
path.dirname(responsePath),
`${path.basename(responsePath, path.extname(responsePath))}.repair-result.json`,
);
const summary = {
meta: {
generator: "scripts/ai-direct-repair-output.mjs",
generatedAt: new Date().toISOString(),
responseFile: normalizePath(responsePath),
previewFile: normalizePath(previewPath),
messagesFile: normalizePath(messagesPath),
requestFile: normalizePath(requestPath),
feedbackFile: feedback ? normalizePath(feedbackPath) : "",
provider: providerResult.provider,
model: providerResult.model,
},
status: validationPassed ? "passed" : "failed",
validationFile: normalizePath(validationPath),
};
fs.writeFileSync(summaryPath, `${JSON.stringify(summary, null, 2)}\n`, "utf8");
console.log(` → summary: ${summaryPath}`);
if (!validationPassed || validation.status !== "passed") {
console.error("[ai-direct-repair-output] repair 后校验仍未通过");
process.exit(1);
}
console.log("[ai-direct-repair-output] ✓ 完成");
process.exit(0);
}
run().catch((error) => {
console.error("[ai-direct-repair-output] 执行失败:", error.message);
process.exit(1);
});
......@@ -593,6 +593,9 @@ function validateAiDirectContextBundle(data, file) {
for (const key of ["designContextFile", "variableDefsFile", "promptFile"]) {
check(key in data.artifacts, file, `artifacts missing '${key}'`);
}
if ("screenshotFile" in data.artifacts) {
check(typeof data.artifacts.screenshotFile === "string", file, "artifacts.screenshotFile must be a string");
}
}
}
......
......@@ -26,6 +26,10 @@ const DEFAULT_UPSTREAM_URL = process.env.FIGMA_DESKTOP_MCP_URL || "http://127.0.
let clientPromise = null;
let toolNameCache = null;
function getFigmaApiKey() {
return process.env.FIGMA_DEVELOPER_MCP_API_KEY || process.env.FIGMA_API_KEY || "";
}
function getDefaultCommandArgs() {
return ["--dir", MCP_BRIDGE_DIR, "exec", DEFAULT_SERVER_BIN, "--stdio"];
}
......@@ -188,6 +192,111 @@ export function extractHtmlFromMcpResponse(mcpResult) {
return "";
}
function bufferToBase64(buffer) {
return Buffer.from(buffer).toString("base64");
}
async function fetchRemoteImageAsBase64(imageUrl) {
const response = await fetch(imageUrl, {
headers: {
connection: "close",
},
});
if (!response.ok) {
throw new Error(`截图资源下载失败: ${response.status} ${response.statusText}`);
}
const contentType = response.headers.get("content-type") || "image/png";
const arrayBuffer = await response.arrayBuffer();
return {
mimeType: contentType,
base64: bufferToBase64(arrayBuffer),
};
}
function extractImageUrlFromMcpResponse(mcpResult) {
if (Array.isArray(mcpResult?.content)) {
for (const item of mcpResult.content) {
if (item.type === "image" && typeof item.data === "string") {
return {
mimeType: item.mimeType || "image/png",
base64: item.data,
};
}
if (item.type === "resource_link" && typeof item.uri === "string") {
return {
url: item.uri,
};
}
if (item.type === "text" && typeof item.text === "string") {
const urlMatch = item.text.match(/https?:\/\/\S+/u);
if (urlMatch) {
return {
url: urlMatch[0],
};
}
}
}
}
if (mcpResult?.structuredContent && typeof mcpResult.structuredContent === "object") {
const candidates = [
mcpResult.structuredContent.imageUrl,
mcpResult.structuredContent.url,
mcpResult.structuredContent.image?.url,
].filter(Boolean);
if (candidates.length > 0) {
return {
url: candidates[0],
};
}
}
return null;
}
async function fetchRenderedNodeScreenshot({ fileKey, nodeId, scale = 1 }) {
const figmaApiKey = getFigmaApiKey();
if (!figmaApiKey) {
throw new Error("当前未配置 FIGMA_API_KEY,无法通过 Figma Images API 获取截图");
}
const endpoint = new URL(`https://api.figma.com/v1/images/${fileKey}`);
endpoint.searchParams.set("ids", nodeId);
endpoint.searchParams.set("format", "png");
endpoint.searchParams.set("scale", String(scale));
endpoint.searchParams.set("use_absolute_bounds", "true");
const response = await fetch(endpoint, {
headers: {
"x-figma-token": figmaApiKey,
connection: "close",
},
});
if (!response.ok) {
const errorText = (await response.text()).trim();
const errorPreview = errorText ? ` | ${errorText.slice(0, 600)}` : "";
throw new Error(`Figma Images API 请求失败: ${response.status} ${response.statusText}${errorPreview}`);
}
const payload = await response.json();
const imageUrl = payload?.images?.[nodeId];
if (!imageUrl) {
throw new Error("Figma Images API 未返回当前 node 的截图地址");
}
const imagePayload = await fetchRemoteImageAsBase64(imageUrl);
return {
source: "figma-rest-image-render",
fileKey,
nodeId,
imageUrl,
...imagePayload,
};
}
// ── Public API ──
/**
......@@ -248,10 +357,42 @@ export async function fetchScreenshot(figmaUrl, options = {}) {
throw new Error("缺少 nodeId,或 figmaUrl 中没有 node-id。");
}
return callUpstreamTool(upstreamUrl, ["get_screenshot", "figma_get_screenshot"], {
try {
const mcpResult = await callUpstreamTool(upstreamUrl, ["get_screenshot", "figma_get_screenshot"], {
fileKey,
nodeId,
contentsOnly: options.contentsOnly ?? true,
});
const extracted = extractImageUrlFromMcpResponse(mcpResult);
if (extracted?.base64) {
return {
source: "mcp-screenshot-tool",
fileKey,
nodeId,
mimeType: extracted.mimeType || "image/png",
base64: extracted.base64,
};
}
if (extracted?.url) {
const imagePayload = await fetchRemoteImageAsBase64(extracted.url);
return {
source: "mcp-screenshot-tool",
fileKey,
nodeId,
imageUrl: extracted.url,
...imagePayload,
};
}
} catch (error) {
if (!isToolNotFoundError(error)) {
throw error;
}
}
return fetchRenderedNodeScreenshot({
fileKey,
nodeId,
contentsOnly: options.contentsOnly ?? true,
scale: options.scale || 1,
});
}
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!