Commit 997fd13f by liimin

fix(ai): 解决AI执行流程中provider请求挂起问题

- 诊断并确认大请求负载导致provider响应缓慢的问题
- 优化请求负载大小从219KB压缩至30KB以避免挂起
- 添加调试工具和环境配置用于追踪provider响应状态
- 更新执行结果记录以支持失败状态和修复轮次跟踪
- 添加截图摘要文件到上下文束以改进调试信息
- 修复命令完成但无响应日志输出的超时处理逻辑
1 parent da744985
Showing 25 changed files with 342 additions and 50 deletions
DEBUG_SERVER_URL=http://127.0.0.1:7777/event
DEBUG_SESSION_ID=provider-hang
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
"meta": { "meta": {
"generator": "scripts/ai-direct-context.mjs", "generator": "scripts/ai-direct-context.mjs",
"mode": "ai-direct", "mode": "ai-direct",
"generatedAt": "2026-06-01T12:26:59.210Z", "generatedAt": "2026-06-02T00:47:26.933Z",
"repoRoot": "D:/work/venus" "repoRoot": "D:/work/venus"
}, },
"figma": { "figma": {
...@@ -1464,6 +1464,7 @@ ...@@ -1464,6 +1464,7 @@
"designContextFile": "d:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix/.ai-direct/allocationmanagement/allocationmanagement.design-context.html", "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", "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", "screenshotFile": "d:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix/.ai-direct/allocationmanagement/allocationmanagement.screenshot.png",
"screenshotSummaryFile": "d:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix/.ai-direct/allocationmanagement/allocationmanagement.screenshot-summary.json",
"promptFile": "d:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix/.ai-direct/allocationmanagement/allocationmanagement.prompt.md" "promptFile": "d:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix/.ai-direct/allocationmanagement/allocationmanagement.prompt.md"
} }
} }
{ {
"meta": { "meta": {
"generator": "scripts/ai-direct-execute.mjs", "generator": "scripts/ai-direct-execute.mjs",
"generatedAt": "2026-06-01T13:07:17.948Z", "generatedAt": "2026-06-02T04:30:31.599Z",
"mode": "openai-compatible", "mode": "openai-compatible",
"bundleFile": "D:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix/.ai-direct/allocationmanagement/allocationmanagement.ai-direct-context-bundle.json", "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", "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", "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" "validationFile": "d:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix/.ai-direct/allocationmanagement/allocationmanagement.provider-response.validation-result.json"
}, },
"status": "passed", "status": "failed",
"repairRoundsAttempted": 0 "repairRoundsAttempted": 1,
"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"
}
} }
{ {
"meta": { "meta": {
"generator": "scripts/ai-direct-preview-project.mjs", "generator": "scripts/ai-direct-preview-project.mjs",
"generatedAt": "2026-06-01T13:01:06.795Z", "generatedAt": "2026-06-02T04:27:13.503Z",
"mode": "reuse-existing", "mode": "reuse-existing",
"bundleFile": "D:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix/.ai-direct/allocationmanagement/allocationmanagement.ai-direct-context-bundle.json" "bundleFile": "d:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix/.ai-direct/allocationmanagement/allocationmanagement.ai-direct-context-bundle.json"
}, },
"previewProject": { "previewProject": {
"name": "allocationmanagement-qwen-autofix", "name": "allocationmanagement-qwen-autofix",
"projectRoot": "D:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix", "projectRoot": "d:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix",
"template": "vue", "template": "vue",
"ui": "element-plus", "ui": "element-plus",
"install": false, "install": false,
......
{ {
"meta": { "meta": {
"generator": "scripts/ai-direct-apply-output.mjs", "generator": "scripts/ai-direct-apply-output.mjs",
"generatedAt": "2026-06-01T13:05:34.471Z", "generatedAt": "2026-06-02T04:31:58.209Z",
"responseFile": "D:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix/.ai-direct/allocationmanagement/allocationmanagement.provider-response.json", "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" "previewFile": "d:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix/.ai-direct/allocationmanagement/allocationmanagement.preview-project.json"
}, },
"result": { "result": {
"projectRoot": "D:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix", "projectRoot": "d:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix",
"writtenFiles": [ "writtenFiles": [
{ {
"path": "apps/web/ai-previews/allocationmanagement-qwen-autofix/src/views/AllocationManagement.vue", "path": "apps/web/ai-previews/allocationmanagement-qwen-autofix/src/views/AllocationManagement.vue",
"language": "vue", "language": "vue",
"purpose": "调拨管理页面主视图" "purpose": "调拨管理页面主视图,包含筛选、搜索、表格和分页功能"
} }
], ],
"autoFixResults": [ "autoFixResults": [
...@@ -35,12 +35,13 @@ ...@@ -35,12 +35,13 @@
"dependencyPlan": { "dependencyPlan": {
"needsDependencyChange": false, "needsDependencyChange": false,
"packages": [], "packages": [],
"reason": "所需组件 @vui/vue 和 element-plus 均已在项目中安装。" "reason": "所有使用的组件均来自项目已安装的 @vui/vue 和 element-plus,无需新增依赖。"
}, },
"notes": [ "notes": [
"VUI 组件 VSelect 和 VInput 优先使用,分页组件因 VUI 未提供而降级使用 element-plus 的 ElPagination。", "为所有 ref 变量显式添加了泛型类型声明(如 ref<string>),确保 TypeScript 类型推断准确,解决搜索字段类型初始化警告。",
"表格多行文本通过 CSS white-space: pre-line 实现,以还原 Figma 中的换行效果。", "通过为 .allocation-management、.table-section 和 .data-table 添加 width: 100% 及 !important 确保表格横向铺满容器。",
"严格遵循多行标签首属性与标签名同行的 lint 规则。" "使用更全面的 :deep() 选择器并添加 !important 强制覆盖表头背景色为 #f4f6fc。",
"在 .pagination-section 和 :deep(.el-pagination) 上强制设置 justify-content: flex-start !important 确保分页器左对齐。"
], ],
"validationChecklist": [ "validationChecklist": [
"通过 lint、typecheck、template contract、review trigger 和 fitness 等根级质量门禁。", "通过 lint、typecheck、template contract、review trigger 和 fitness 等根级质量门禁。",
...@@ -48,7 +49,7 @@ ...@@ -48,7 +49,7 @@
"未绕过项目现有路由、目录和命名约定。", "未绕过项目现有路由、目录和命名约定。",
"优先满足 VUI 第一顺位与按框架降级的规则。", "优先满足 VUI 第一顺位与按框架降级的规则。",
"预览项目基于 Venus CLI 生成的项目结构。", "预览项目基于 Venus CLI 生成的项目结构。",
"预览页面不依赖模板演示壳层样式,生成文件本身包含可运行的页面结构与样式。" "预览页面自带完整容器、间距、尺寸和必要样式,不依赖模板演示壳层。"
] ]
} }
} }
{
"meta": {
"generator": "scripts/ai-direct-repair-output.mjs",
"generatedAt": "2026-06-02T04:32:28.663Z",
"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",
"messagesFile": "d:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix/.ai-direct/allocationmanagement/allocationmanagement.messages.json",
"requestFile": "d:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix/.ai-direct/allocationmanagement/allocationmanagement.provider-response.repair-request.md",
"feedbackFile": "d:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix/.ai-direct/allocationmanagement/allocationmanagement.provider-response.repair-feedback.json",
"provider": "openai-compatible",
"model": "qwen3.7-max"
},
"status": "failed",
"validationFile": "d:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix/.ai-direct/allocationmanagement/allocationmanagement.provider-response.validation-result.json"
}
{ {
"meta": { "meta": {
"generator": "scripts/ai-direct-validate-output.mjs", "generator": "scripts/ai-direct-validate-output.mjs",
"generatedAt": "2026-06-01T13:07:17.910Z", "generatedAt": "2026-06-02T04:32:58.568Z",
"responseFile": "D:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix/.ai-direct/allocationmanagement/allocationmanagement.provider-response.json", "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", "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" "bundleFile": "d:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix/.ai-direct/allocationmanagement/allocationmanagement.ai-direct-context-bundle.json"
}, },
"status": "passed", "status": "passed",
"files": [ "files": [
...@@ -18,6 +18,14 @@ ...@@ -18,6 +18,14 @@
"errors": [], "errors": [],
"warnings": [] "warnings": []
}, },
"primaryDataValidation": {
"errors": [],
"warnings": []
},
"visualSummaryValidation": {
"errors": [],
"warnings": []
},
"commandResults": [ "commandResults": [
{ {
"command": "node scripts/lint-changed.mjs \"apps/web/ai-previews/allocationmanagement-qwen-autofix/src/views/AllocationManagement.vue\"", "command": "node scripts/lint-changed.mjs \"apps/web/ai-previews/allocationmanagement-qwen-autofix/src/views/AllocationManagement.vue\"",
...@@ -45,7 +53,7 @@ ...@@ -45,7 +53,7 @@
}, },
{ {
"command": "pnpm run type-check", "command": "pnpm run type-check",
"cwd": "D:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix", "cwd": "d:/work/venus/apps/web/ai-previews/allocationmanagement-qwen-autofix",
"exitCode": 0, "exitCode": 0,
"stdout": "\n> @venus/allocationmanagement-qwen-autofix@1.0.0 type-check D:\\work\\venus\\apps\\web\\ai-previews\\allocationmanagement-qwen-autofix\n> vue-tsc --noEmit\n\n", "stdout": "\n> @venus/allocationmanagement-qwen-autofix@1.0.0 type-check D:\\work\\venus\\apps\\web\\ai-previews\\allocationmanagement-qwen-autofix\n> vue-tsc --noEmit\n\n",
"stderr": "", "stderr": "",
......
{
"layoutOrder": [
"filters",
"toolbar",
"table",
"pagination"
],
"filterGroupLabels": [
"调出方",
"调入方"
],
"requiredSelectCount": 4,
"headerTitle": "调拨列表",
"searchLabel": "调拨",
"primaryActionLabel": "查询",
"tableColumns": [
"序号",
"商品名称",
"规格",
"商品编码",
"系列",
"所属分类",
"所属仓库",
"所属门店",
"膜卷号",
"操作"
],
"actionColumnLabel": "操作",
"actionLinkLabel": "选择",
"pagination": {
"present": true,
"containerAlignment": "left",
"totalTextVisible": true,
"pageSizeSelectorVisible": true,
"jumperVisible": true,
"activePageStyle": "blue-filled"
},
"style": {
"backgroundTone": "white",
"headerTone": "light-gray",
"primaryColor": "blue"
},
"notes": []
}
1. **整体布局**:垂直分块结构,自上而下依次为:顶部筛选表单区、中部列表标题与搜索区、主体数据表格区、底部分页区。 # Screenshot Visual Summary
2. **筛选表单**:两行布局。每行左侧为文本标签(“调出方”、“调入方”),右侧并列两个带红色星号的下拉选择框(仓库、门店),下拉框宽度均等且水平对齐。
3. **列表头部**:左侧为加粗标题“调拨列表”,右侧为搜索输入框(前缀文本“调拨:”)及蓝色实心“查询”按钮,整体靠右对齐。 - layoutOrder: filters -> toolbar -> table -> pagination
4. **表格结构**:10 列宽表格。表头浅灰色背景,深灰文字。列名依次为:序号、商品名称、规格、商品编码、系列、所属分类、所属仓库、所属门店、膜卷号、操作。 - filterGroupLabels: 调出方, 调入方
5. **表格样式**:表体白色背景,行高固定,行间有极细浅灰分割线。文本左对齐,最后一列“操作”显示蓝色“选择”链接。 - requiredSelectCount: 4
6. **分页组件**:底部通栏布局。左侧显示总数“共 800 条”及“每页 10 条”下拉框;右侧为分页器,含翻页箭头、数字页码(当前页“1”为蓝色背景白字)、“跳至 [ ] 页”输入框。 - headerTitle: 调拨列表
7. **色彩规范**:主交互色为蓝色(查询按钮、当前页码、操作链接)。必填项前缀红色星号。表头背景色略深于表体白色背景。 - searchLabel: 调拨
- primaryActionLabel: 查询
- tableColumns: 序号, 商品名称, 规格, 商品编码, 系列, 所属分类, 所属仓库, 所属门店, 膜卷号, 操作
- actionColumnLabel: 操作
- actionLinkLabel: 选择
- pagination.present: true
- pagination.containerAlignment: left
- pagination.totalTextVisible: true
- pagination.pageSizeSelectorVisible: true
- pagination.jumperVisible: true
- pagination.activePageStyle: blue-filled
- style.backgroundTone: white
- style.headerTone: light-gray
- style.primaryColor: blue
...@@ -144,6 +144,7 @@ ...@@ -144,6 +144,7 @@
"designContextFile": { "type": "string" }, "designContextFile": { "type": "string" },
"variableDefsFile": { "type": "string" }, "variableDefsFile": { "type": "string" },
"screenshotFile": { "type": "string" }, "screenshotFile": { "type": "string" },
"screenshotSummaryFile": { "type": "string" },
"promptFile": { "type": "string" } "promptFile": { "type": "string" }
}, },
"additionalProperties": false "additionalProperties": false
......
# Debug Session: provider-hang [OPEN]
## Symptom
- `pnpm ai:execute` can finish `ai-direct-messages` and `ai-direct-preview-project`
- Execution then appears to hang before a new `provider-response`, `validation`, or `execute-result` artifact is produced
- A direct `ai-direct-validate-output` run also appears to stall after initial startup logs
## Scope
- Repo: `d:/work/venus`
- Target flow: `scripts/ai-direct-execute.mjs` and `scripts/ai-direct-validate-output.mjs`
- Preview project: `apps/web/ai-previews/allocationmanagement-qwen-autofix`
## Hypotheses
1. Provider request is not returning and Node `fetch` timeout is not aborting as expected.
2. A child command spawned by `ai-direct-validate-output` blocks under the sandboxed shell.
3. The request payload size causes the provider to respond extremely slowly, making the flow look hung.
4. The command completes but artifact writes are delayed or blocked by filesystem/sandbox behavior.
## Evidence Log
- `execute` instrumentation logged `run:before-provider` and `callOpenAiCompatible:start`, but never logged `provider response received` or `after-provider`.
- Logged provider request size is `219495` bytes.
- A tiny direct request to the same DashScope endpoint and model returned successfully within the test command timeout.
- During the hung run, no new `provider-response`, `validation`, or `execute-result` artifacts were written.
- After compacting the prompt, request size dropped to `54767` bytes and then to `30278` bytes.
- With `requestBytes = 30278`, instrumentation captured `provider response received` with `200 OK`.
- The end-to-end flow progressed through `apply` and `validate`, then hit a real `type-check` failure in generated `VTable` column typing and entered `auto-repair`.
- Over-compressing the prompt removed too much VUI signature detail, so a slim component-signature section was added back into the prompt snapshot.
## Hypothesis Status
| ID | Hypothesis | Status | Evidence |
|---|---|---|---|
| A | Provider request is not returning and `fetch` timeout is not aborting as expected | Confirmed (request stalls before response) | Debug log contains request-start events but no response event |
| B | A child command spawned by `ai-direct-validate-output` blocks under the sandboxed shell | Rejected for this hang | `execute` never reaches apply/validate stage in the captured run |
| C | Request payload size causes provider to respond extremely slowly | Confirmed | Large request is ~219 KB; tiny request to same endpoint/model succeeds quickly |
| D | Command completes but artifact writes are delayed or blocked by filesystem/sandbox behavior | Rejected | No after-provider log and no downstream artifact updates |
## Next Step
- Keep the reduced prompt payload, retain the slim VUI component signatures, and rerun the repair loop to verify the `VTable.columns` typing issue can now auto-converge.
...@@ -30,15 +30,15 @@ ...@@ -30,15 +30,15 @@
```text ```text
Figma Developer MCP Figma Developer MCP
-> raw design context / variables -> raw design context / variables / screenshot
project-intelligence project-intelligence
-> project-context -> project-context
component manifest / meta index component manifest / meta index
-> component facts -> component facts
ai-direct-context bundle ai-direct-context bundle
-> AI / IDE direct generation -> AI / IDE direct generation with screenshot visual summary
venus validation venus validation
-> lint / typecheck / contract / review trigger / fitness -> lint / typecheck / contract / review trigger / visual-summary adherence / fitness
``` ```
这条链路中,`venus` 不再主导“中间映射决策”,而是主导以下四件事: 这条链路中,`venus` 不再主导“中间映射决策”,而是主导以下四件事:
...@@ -213,6 +213,19 @@ AI 在生成页面时必须遵守以下原则: ...@@ -213,6 +213,19 @@ AI 在生成页面时必须遵守以下原则:
- 传入 `--provider openai-compatible` - 传入 `--provider openai-compatible`
- 通过环境变量 `AI_DIRECT_OPENAI_BASE_URL`、`AI_DIRECT_OPENAI_API_KEY`、`AI_DIRECT_OPENAI_MODEL` 直调兼容接口 - 通过环境变量 `AI_DIRECT_OPENAI_BASE_URL`、`AI_DIRECT_OPENAI_API_KEY`、`AI_DIRECT_OPENAI_MODEL` 直调兼容接口
常用执行开关:
- `--existing-preview-project-root`
- 复用已有预览项目,不再每次新建目录
- `--refresh-context`
- 强制重新拉取最新 Figma context、variables 和 screenshot
- `--auto-repair`
- 校验失败后自动发起 repair 回合
- `--max-repair-rounds`
- 控制自动 repair 最大轮次
- `--install`
- 在预览项目中安装依赖,以便本地 `type-check`
当校验失败时,总控脚本会生成: 当校验失败时,总控脚本会生成:
- `*.repair-feedback.json` - `*.repair-feedback.json`
...@@ -220,6 +233,20 @@ AI 在生成页面时必须遵守以下原则: ...@@ -220,6 +233,20 @@ AI 在生成页面时必须遵守以下原则:
用于把失败原因回喂给 AI 做下一轮修复。 用于把失败原因回喂给 AI 做下一轮修复。
当存在 Figma screenshot 时,链路还会额外生成:
- `*.screenshot.png`
- `*.screenshot-summary.json`
- `*.screenshot-summary.md`
其中结构化截图摘要会同时进入 prompt 和 validate,用于约束标题、筛选组、表格列、操作文案和分页布局等关键视觉事实。
典型执行方式:
```bash
pnpm ai:execute --bundle-file <bundle-file> --provider openai-compatible --existing-preview-project-root <project-root> --auto-repair --max-repair-rounds 2 --install
```
而不是在生成前替 AI 完成全部组件映射。 而不是在生成前替 AI 完成全部组件映射。
## 当前依赖的基础设施 ## 当前依赖的基础设施
...@@ -256,11 +283,11 @@ AI 在生成页面时必须遵守以下原则: ...@@ -256,11 +283,11 @@ AI 在生成页面时必须遵守以下原则:
当前推荐执行顺序: 当前推荐执行顺序:
1. `ai-direct-context` 通过 `figma-developer-mcp` 拉取 Figma 数据并生成 bundle 1. `ai-direct-context` 通过 `figma-developer-mcp` 拉取 Figma 数据并生成 bundle
2. `ai-direct-messages` 把 bundle、设计上下文和规则组装成可直接投喂 AI 的 messages/request 2. `ai-direct-messages` 把 bundle、设计上下文、截图视觉摘要和规则组装成可直接投喂 AI 的 messages/request
3. `ai-direct-preview-project` 使用 Venus CLI 创建预览项目骨架 3. `ai-direct-preview-project` 使用 Venus CLI 创建预览项目骨架
4. AI 返回结构化文件产物后,`ai-direct-apply-output` 将 `files[]` 落盘到预览项目 4. AI 返回结构化文件产物后,`ai-direct-apply-output` 将 `files[]` 落盘到预览项目
5. `ai-direct-validate-output` 对本次 AI 结果执行规则校验、定向 lint、review trigger、file budget 与可选 type-check 5. `ai-direct-validate-output` 对本次 AI 结果执行规则校验、样式责任校验、截图视觉摘要遵守性校验、定向 lint、review trigger、file budget 与可选 type-check
6. `ai-direct-execute` 可作为总控入口,自动串起上述步骤;在校验失败时生成 repair feedback 与 repair request 6. `ai-direct-execute` 可作为总控入口,自动串起上述步骤;在校验失败时生成 repair feedback 与 repair request,并可进入 auto-repair 回合
### 质量门禁 ### 质量门禁
......
...@@ -494,6 +494,7 @@ function buildBundle({ ...@@ -494,6 +494,7 @@ function buildBundle({
designContext, designContext,
variableDefsFile, variableDefsFile,
screenshotFile, screenshotFile,
screenshotSummaryFile,
designContextFile, designContextFile,
promptFile, promptFile,
workspaceExports, workspaceExports,
...@@ -536,6 +537,7 @@ function buildBundle({ ...@@ -536,6 +537,7 @@ function buildBundle({
designContextFile: normalizePath(designContextFile), designContextFile: normalizePath(designContextFile),
variableDefsFile: variableDefsFile ? normalizePath(variableDefsFile) : "", variableDefsFile: variableDefsFile ? normalizePath(variableDefsFile) : "",
screenshotFile: screenshotFile ? normalizePath(screenshotFile) : "", screenshotFile: screenshotFile ? normalizePath(screenshotFile) : "",
screenshotSummaryFile: screenshotSummaryFile ? normalizePath(screenshotSummaryFile) : "",
promptFile: normalizePath(promptFile), promptFile: normalizePath(promptFile),
}, },
}; };
...@@ -643,6 +645,7 @@ async function run() { ...@@ -643,6 +645,7 @@ async function run() {
const screenshotFile = screenshot const screenshotFile = screenshot
? path.join(outputDir, `${pageSlug}.screenshot${screenshotExtensionForMimeType(screenshot.mimeType)}`) ? path.join(outputDir, `${pageSlug}.screenshot${screenshotExtensionForMimeType(screenshot.mimeType)}`)
: ""; : "";
const screenshotSummaryFile = screenshot ? path.join(outputDir, `${pageSlug}.screenshot-summary.json`) : "";
const promptFile = path.join(outputDir, `${pageSlug}.prompt.md`); const promptFile = path.join(outputDir, `${pageSlug}.prompt.md`);
const bundleFile = path.join(outputDir, `${pageSlug}.ai-direct-context-bundle.json`); const bundleFile = path.join(outputDir, `${pageSlug}.ai-direct-context-bundle.json`);
...@@ -674,6 +677,7 @@ async function run() { ...@@ -674,6 +677,7 @@ async function run() {
designContext, designContext,
variableDefsFile, variableDefsFile,
screenshotFile, screenshotFile,
screenshotSummaryFile,
designContextFile, designContextFile,
promptFile, promptFile,
workspaceExports, workspaceExports,
......
...@@ -121,6 +121,34 @@ function normalizePath(targetPath) { ...@@ -121,6 +121,34 @@ function normalizePath(targetPath) {
return targetPath.replaceAll("\\", "/"); return targetPath.replaceAll("\\", "/");
} }
// #region debug-point A:report-helper
function reportDebugEvent(hypothesisId, location, msg, data = {}, runId = process.env.DEBUG_RUN_ID || "pre-fix") {
try {
const envPath = path.join(repoRoot, ".dbg", "provider-hang.env");
let debugServerUrl = "http://127.0.0.1:7777/event";
let sessionId = "provider-hang";
if (fs.existsSync(envPath)) {
const envText = fs.readFileSync(envPath, "utf8");
debugServerUrl = envText.match(/DEBUG_SERVER_URL=(.+)/)?.[1]?.trim() || debugServerUrl;
sessionId = envText.match(/DEBUG_SESSION_ID=(.+)/)?.[1]?.trim() || sessionId;
}
fetch(debugServerUrl, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
sessionId,
runId,
hypothesisId,
location,
msg,
data,
ts: Date.now(),
}),
}).catch(() => {});
} catch {}
}
// #endregion
function slugify(value) { function slugify(value) {
const normalized = String(value || "") const normalized = String(value || "")
.trim() .trim()
...@@ -257,6 +285,20 @@ async function callOpenAiCompatible(messages, model) { ...@@ -257,6 +285,20 @@ async function callOpenAiCompatible(messages, model) {
} }
const endpoint = `${baseUrl.replace(/\/$/, "")}/chat/completions`; const endpoint = `${baseUrl.replace(/\/$/, "")}/chat/completions`;
const requestBody = JSON.stringify({
model: resolvedModel,
temperature: 0.2,
response_format: { type: "json_object" },
messages,
});
// #region debug-point A:provider-request-start
reportDebugEvent("A", "scripts/ai-direct-execute.mjs:callOpenAiCompatible:start", "[DEBUG] provider request start", {
endpoint,
model: resolvedModel,
messageCount: messages.length,
requestBytes: Buffer.byteLength(requestBody, "utf8"),
});
// #endregion
const response = await fetch(endpoint, { const response = await fetch(endpoint, {
method: "POST", method: "POST",
headers: { headers: {
...@@ -264,14 +306,16 @@ async function callOpenAiCompatible(messages, model) { ...@@ -264,14 +306,16 @@ async function callOpenAiCompatible(messages, model) {
authorization: `Bearer ${apiKey}`, authorization: `Bearer ${apiKey}`,
connection: "close", connection: "close",
}, },
signal: AbortSignal.timeout(180000), signal: AbortSignal.timeout(180_000),
body: JSON.stringify({ body: requestBody,
model: resolvedModel,
temperature: 0.2,
response_format: { type: "json_object" },
messages,
}),
}); });
// #region debug-point A:provider-response
reportDebugEvent("A", "scripts/ai-direct-execute.mjs:callOpenAiCompatible:response", "[DEBUG] provider response received", {
status: response.status,
statusText: response.statusText,
ok: response.ok,
});
// #endregion
if (!response.ok) { if (!response.ok) {
const errorText = (await response.text()).trim(); const errorText = (await response.text()).trim();
...@@ -356,6 +400,14 @@ function buildRepairArtifacts({ bundle, preview, response, validation, responseP ...@@ -356,6 +400,14 @@ function buildRepairArtifacts({ bundle, preview, response, validation, responseP
const feedbackPath = path.join(path.dirname(responsePath), `${baseName}.repair-feedback.json`); const feedbackPath = path.join(path.dirname(responsePath), `${baseName}.repair-feedback.json`);
const requestPath = path.join(path.dirname(responsePath), `${baseName}.repair-request.md`); const requestPath = path.join(path.dirname(responsePath), `${baseName}.repair-request.md`);
const failedCommands = (validation.commandResults || []).filter((item) => !item.ok); const failedCommands = (validation.commandResults || []).filter((item) => !item.ok);
const ruleErrors = validation.ruleValidation?.errors || [];
const ruleWarnings = validation.ruleValidation?.warnings || [];
const styleErrors = validation.styleValidation?.errors || [];
const styleWarnings = validation.styleValidation?.warnings || [];
const primaryDataErrors = validation.primaryDataValidation?.errors || [];
const primaryDataWarnings = validation.primaryDataValidation?.warnings || [];
const visualSummaryErrors = validation.visualSummaryValidation?.errors || [];
const visualSummaryWarnings = validation.visualSummaryValidation?.warnings || [];
const feedback = { const feedback = {
meta: { meta: {
...@@ -371,8 +423,14 @@ function buildRepairArtifacts({ bundle, preview, response, validation, responseP ...@@ -371,8 +423,14 @@ function buildRepairArtifacts({ bundle, preview, response, validation, responseP
responseFile: normalizePath(responsePath), responseFile: normalizePath(responsePath),
}, },
status: validation.status, status: validation.status,
ruleErrors: validation.ruleValidation?.errors || [], ruleErrors,
ruleWarnings: validation.ruleValidation?.warnings || [], ruleWarnings,
styleErrors,
styleWarnings,
primaryDataErrors,
primaryDataWarnings,
visualSummaryErrors,
visualSummaryWarnings,
failedCommands: failedCommands.map((item) => ({ failedCommands: failedCommands.map((item) => ({
command: item.command, command: item.command,
exitCode: item.exitCode, exitCode: item.exitCode,
...@@ -395,9 +453,30 @@ function buildRepairArtifacts({ bundle, preview, response, validation, responseP ...@@ -395,9 +453,30 @@ function buildRepairArtifacts({ bundle, preview, response, validation, responseP
"", "",
]; ];
for (const error of feedback.ruleErrors) { for (const error of ruleErrors) {
requestLines.push(`- Rule Error: ${error}`); requestLines.push(`- Rule Error: ${error}`);
} }
for (const error of styleErrors) {
requestLines.push(`- Style Error: ${error}`);
}
for (const error of primaryDataErrors) {
requestLines.push(`- Primary Data Error: ${error}`);
}
for (const error of visualSummaryErrors) {
requestLines.push(`- Visual Summary Error: ${error}`);
}
for (const warning of ruleWarnings) {
requestLines.push(`- Rule Warning: ${warning}`);
}
for (const warning of styleWarnings) {
requestLines.push(`- Style Warning: ${warning}`);
}
for (const warning of primaryDataWarnings) {
requestLines.push(`- Primary Data Warning: ${warning}`);
}
for (const warning of visualSummaryWarnings) {
requestLines.push(`- Visual Summary Warning: ${warning}`);
}
for (const command of feedback.failedCommands) { for (const command of feedback.failedCommands) {
requestLines.push(`- Command Failure: ${command.command} (exit=${command.exitCode})`); requestLines.push(`- Command Failure: ${command.command} (exit=${command.exitCode})`);
if (command.stderr) { if (command.stderr) {
...@@ -418,6 +497,9 @@ function buildRepairArtifacts({ bundle, preview, response, validation, responseP ...@@ -418,6 +497,9 @@ function buildRepairArtifacts({ bundle, preview, response, validation, responseP
"", "",
"- 保持 previewProject.mustUseVenusCli=true。", "- 保持 previewProject.mustUseVenusCli=true。",
"- 只修复失败项,不要引入新的 UI 包违规。", "- 只修复失败项,不要引入新的 UI 包违规。",
"- 如果失败项来自 Figma 原始数据校验,优先保留 design context 中明确给出的标签、placeholder、列名和示例数据,不要让截图摘要覆盖这些文本事实。",
"- 如果失败项来自截图视觉摘要校验,优先修正标题、筛选标签、选择框数量、表格列、操作文案和分页布局,使页面与截图摘要一致。",
"- 如果失败项来自样式责任校验,直接在生成文件中补齐页面级样式,不要把布局或视觉修复转嫁给预览项目壳层。",
"- 输出完整结构化 JSON,沿用既定 response schema。", "- 输出完整结构化 JSON,沿用既定 response schema。",
); );
...@@ -464,10 +546,30 @@ async function run() { ...@@ -464,10 +546,30 @@ async function run() {
); );
const preview = readJson(previewPath); const preview = readJson(previewPath);
// #region debug-point A:before-provider
reportDebugEvent("A", "scripts/ai-direct-execute.mjs:run:before-provider", "[DEBUG] entering resolveAiResponse", {
bundleFile: normalizePath(bundlePath),
previewFile: normalizePath(previewPath),
provider: args.provider || "manual",
model: args.model || process.env.AI_DIRECT_OPENAI_MODEL || process.env.OPENAI_MODEL || "",
});
// #endregion
const aiResult = await resolveAiResponse({ args, bundlePath }); const aiResult = await resolveAiResponse({ args, bundlePath });
const plainResponse = aiResult.mode === "manual-replay" ? aiResult.response : aiResult.response; const plainResponse = aiResult.mode === "manual-replay" ? aiResult.response : aiResult.response;
// #region debug-point D:after-provider
reportDebugEvent("D", "scripts/ai-direct-execute.mjs:run:after-provider", "[DEBUG] resolveAiResponse completed", {
mode: aiResult.mode,
responseFile: normalizePath(aiResult.responsePath),
fileExists: fileExists(aiResult.responsePath),
});
// #endregion
persistPlainResponse(aiResult.responsePath, plainResponse); persistPlainResponse(aiResult.responsePath, plainResponse);
// #region debug-point D:before-apply
reportDebugEvent("D", "scripts/ai-direct-execute.mjs:run:before-apply", "[DEBUG] starting apply stage", {
responseFile: normalizePath(aiResult.responsePath),
});
// #endregion
runNodeScript("ai-direct-apply-output.mjs", [ runNodeScript("ai-direct-apply-output.mjs", [
"--response-file", "--response-file",
aiResult.responsePath, aiResult.responsePath,
...@@ -477,6 +579,12 @@ async function run() { ...@@ -477,6 +579,12 @@ async function run() {
let validationPassed = true; let validationPassed = true;
try { try {
// #region debug-point B:before-validate
reportDebugEvent("B", "scripts/ai-direct-execute.mjs:run:before-validate", "[DEBUG] starting validate stage", {
responseFile: normalizePath(aiResult.responsePath),
previewFile: normalizePath(previewPath),
});
// #endregion
runNodeScript("ai-direct-validate-output.mjs", [ runNodeScript("ai-direct-validate-output.mjs", [
"--response-file", "--response-file",
aiResult.responsePath, aiResult.responsePath,
...@@ -486,6 +594,11 @@ async function run() { ...@@ -486,6 +594,11 @@ async function run() {
} catch { } catch {
validationPassed = false; validationPassed = false;
} }
// #region debug-point D:after-validate
reportDebugEvent("D", "scripts/ai-direct-execute.mjs:run:after-validate", "[DEBUG] validate stage completed", {
validationPassed,
});
// #endregion
const validationPath = path.join( const validationPath = path.join(
path.dirname(aiResult.responsePath), path.dirname(aiResult.responsePath),
......
...@@ -154,14 +154,21 @@ function deriveFeedbackFile(responsePath) { ...@@ -154,14 +154,21 @@ function deriveFeedbackFile(responsePath) {
function buildRepairMessages({ systemMessage, requestText, feedback }) { function buildRepairMessages({ systemMessage, requestText, feedback }) {
const sections = [requestText.trim()]; const sections = [requestText.trim()];
const hasStructuredFeedback =
Boolean(feedback?.ruleErrors?.length) ||
Boolean(feedback?.styleErrors?.length) ||
Boolean(feedback?.visualSummaryErrors?.length) ||
Boolean(feedback?.failedCommands?.length);
if (feedback?.failedCommands?.length) { if (hasStructuredFeedback) {
sections.push( sections.push(
[ [
"## Repair Focus", "## Repair Focus",
"- 只修复失败项,不改变无关页面结构、样式和组件选型。", "- 只修复失败项,不改变无关页面结构、样式和组件选型。",
"- 输出完整结构化 JSON,并保持既有 response schema。", "- 输出完整结构化 JSON,并保持既有 response schema。",
"- 如果问题来自 TypeScript 类型,请给出最小必要类型声明,不要扩大为宽泛 string/any。", "- 如果问题来自 TypeScript 类型,请给出最小必要类型声明,不要扩大为宽泛 string/any。",
"- 如果问题来自截图视觉摘要,请优先修正标题、筛选标签、字段数量、表格列和分页布局。",
"- 如果问题来自样式责任校验,请直接在页面文件内补齐样式,不要依赖预览壳层补救。",
].join("\n"), ].join("\n"),
); );
} }
......
...@@ -596,6 +596,13 @@ function validateAiDirectContextBundle(data, file) { ...@@ -596,6 +596,13 @@ function validateAiDirectContextBundle(data, file) {
if ("screenshotFile" in data.artifacts) { if ("screenshotFile" in data.artifacts) {
check(typeof data.artifacts.screenshotFile === "string", file, "artifacts.screenshotFile must be a string"); check(typeof data.artifacts.screenshotFile === "string", file, "artifacts.screenshotFile must be a string");
} }
if ("screenshotSummaryFile" in data.artifacts) {
check(
typeof data.artifacts.screenshotSummaryFile === "string",
file,
"artifacts.screenshotSummaryFile must be a string",
);
}
} }
} }
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!