Commit 97e4615d by liimin

feat(ai-direct): 完善AI Direct服务端并新增测试预览页面

- 重构并迁移AI Direct Server为模块化服务,更新restart-server脚本路径与启动命令
- 优化AI调用脚本的JSON解析与重试逻辑,增强响应验证规则
- 更新系统提示词,明确AI输出格式与强制生成要求
- 调整文件预算配置,更新ai-direct-execute.mjs的大小阈值
- 新增testpage-preview的aa、www两个预览页面及全套组件、路由配置
1 parent 125b94a3
{
"generator": "scripts/ai-direct-apply-output.mjs",
"generatedAt": "2026-06-05T03:45:00.662Z",
"model": "qwen3.7-max",
"provider": "openai-compatible",
"files": [
{
"path": "apps/web/ai-previews/testpage-preview/src/views/aa/components/Node5971297.vue",
"language": "vue",
"purpose": "车辆图片画廊组件,展示车辆图片、分类标签切换和图片计数",
"coAuthor": "@ai-co-author venus-ai-direct | openai-compatible/qwen3.7-max | 2026-06-05T03:12:39.213Z",
"action": "created"
},
{
"path": "apps/web/ai-previews/testpage-preview/src/views/aa/components/Node5971239.vue",
"language": "vue",
"purpose": "二手车商品详情卡片组件,展示车辆图片、标题、标签、车源号、起拍价和倒计时",
"coAuthor": "@ai-co-author venus-ai-direct | openai-compatible/qwen3.7-max | 2026-06-05T03:14:05.710Z",
"action": "created"
},
{
"path": "apps/web/ai-previews/testpage-preview/src/views/aa/components/Node4371036.vue",
"language": "vue",
"purpose": "车辆详情信息组件,包含基础统计卡片和详细参数列表",
"coAuthor": "@ai-co-author venus-ai-direct | openai-compatible/qwen3.7-max | 2026-06-05T03:15:29.539Z",
"action": "created"
},
{
"path": "apps/web/ai-previews/testpage-preview/src/views/www/components/Node640708.vue",
"language": "vue",
"purpose": "参拍详情页面顶部导航栏,包含标题和返回按钮",
"coAuthor": "@ai-co-author venus-ai-direct | openai-compatible/qwen3.7-max | 2026-06-05T03:41:13.426Z",
"action": "created"
},
{
"path": "apps/web/ai-previews/testpage-preview/src/views/www/components/Node5971297.vue",
"language": "vue",
"purpose": "车辆图片查看器组件,包含图片轮播区域、拍卖规则浮标、外观/内饰切换标签和照片计数器",
"coAuthor": "@ai-co-author venus-ai-direct | openai-compatible/qwen3.7-max | 2026-06-05T03:42:05.277Z",
"action": "created"
},
{
"path": "apps/web/ai-previews/testpage-preview/src/views/www/components/Node5971239.vue",
"language": "vue",
"purpose": "二手车详情卡片组件,展示车辆图片、标题、标签、车源号、起拍价和倒计时",
"coAuthor": "@ai-co-author venus-ai-direct | openai-compatible/qwen3.7-max | 2026-06-05T03:43:21.278Z",
"action": "created"
},
{
"path": "apps/web/ai-previews/testpage-preview/src/views/www/components/Node4371036.vue",
"language": "vue",
"purpose": "二手车车辆详细信息卡片,包含核心指标展示和详细参数列表",
"coAuthor": "@ai-co-author venus-ai-direct | openai-compatible/qwen3.7-max | 2026-06-05T03:44:10.258Z",
"action": "created"
},
{
"path": "apps/web/ai-previews/testpage-preview/src/views/www/components/Node531720.vue",
"language": "vue",
"purpose": "底部竞拍操作栏,包含固定定位的白色底栏和蓝色",
"coAuthor": "@ai-co-author venus-ai-direct | openai-compatible/qwen3.7-max | 2026-06-05T03:44:52.996Z",
"action": "created"
}
]
}
...@@ -730,22 +730,58 @@ function extractJsonPayload(text) { ...@@ -730,22 +730,58 @@ function extractJsonPayload(text) {
throw new Error("AI 返回为空"); throw new Error("AI 返回为空");
} }
// 1. 直接解析
try { try {
return JSON.parse(trimmed); return JSON.parse(trimmed);
} catch {} } catch {}
const fencedMatch = trimmed.match(/```(?:json)?\s*([\s\S]*?)```/i); // 2. 提取 markdown 代码块中的 JSON(贪婪匹配最后一个)
if (fencedMatch) { const fencedMatches = [...trimmed.matchAll(/```(?:json)?\s*([\s\S]*?)```/gi)];
return JSON.parse(fencedMatch[1].trim()); for (const match of fencedMatches.reverse()) {
try {
return JSON.parse(match[1].trim());
} catch {}
}
// 3. 找到最外层 {} 并尝试解析
const firstBrace = trimmed.indexOf("{");
const lastBrace = trimmed.lastIndexOf("}");
if (firstBrace !== -1 && lastBrace > firstBrace) {
const candidate = trimmed.slice(firstBrace, lastBrace + 1);
try {
return JSON.parse(candidate);
} catch {
// 4. 尝试修复常见 JSON 问题(尾逗号)
const fixed = candidate.replaceAll(/,(\s*[}\]])/g, "$1");
try {
return JSON.parse(fixed);
} catch {}
}
} }
const start = trimmed.indexOf("{"); // 5. 尝试逐字符匹配大括号找到最大 JSON 对象
const end = trimmed.lastIndexOf("}"); let depth = 0;
if (start !== -1 && end !== -1 && end > start) { let jsonStart = -1;
return JSON.parse(trimmed.slice(start, end + 1)); let jsonEnd = -1;
for (const [i, element] of trimmed.entries()) {
if (element === "{") {
if (depth === 0) jsonStart = i;
depth++;
} else if (element === "}") {
depth--;
if (depth === 0) {
jsonEnd = i;
break;
}
}
}
if (jsonStart !== -1 && jsonEnd !== -1 && jsonEnd > jsonStart) {
try {
return JSON.parse(trimmed.slice(jsonStart, jsonEnd + 1));
} catch {}
} }
throw new Error("无法从 AI 返回中提取 JSON"); throw new Error(`无法从 AI 返回中提取 JSON(${trimmed.length} 字符)`);
} }
async function callOpenAiCompatible(messages, model) { async function callOpenAiCompatible(messages, model) {
...@@ -887,6 +923,16 @@ async function callOpenAiCompatible(messages, model) { ...@@ -887,6 +923,16 @@ async function callOpenAiCompatible(messages, model) {
}; };
} }
function validateResponse(structured) {
if (!structured || typeof structured !== "object") {
return { valid: false, reason: "响应不是有效对象" };
}
if (!Array.isArray(structured.files) || structured.files.length === 0) {
return { valid: false, reason: "files 数组为空或缺失" };
}
return { valid: true };
}
async function resolveAiResponse({ args, bundlePath }) { async function resolveAiResponse({ args, bundlePath }) {
const responsePath = resolveResponseFile(bundlePath, args.responseFile); const responsePath = resolveResponseFile(bundlePath, args.responseFile);
...@@ -910,33 +956,95 @@ async function resolveAiResponse({ args, bundlePath }) { ...@@ -910,33 +956,95 @@ async function resolveAiResponse({ args, bundlePath }) {
if (!messagesPayload?.messages) { if (!messagesPayload?.messages) {
throw new Error(`无法加载 messages: ${messagesPath}`); throw new Error(`无法加载 messages: ${messagesPath}`);
} }
let providerResult;
if (args.provider === "openai-compatible") { // 重试逻辑:最多尝试 3 次(首次 + 2 次重试)
providerResult = await callOpenAiCompatible(messagesPayload.messages, args.model); const maxAttempts = 3;
} else { let lastResponse = null;
throw new Error(`不支持的 provider: ${args.provider}`); let lastRawContent = "";
}
const structured = extractJsonPayload(providerResult.content); for (let attempt = 1; attempt <= maxAttempts; attempt++) {
const persisted = { let currentMessages;
meta: {
generator: "scripts/ai-direct-execute.mjs", if (attempt === 1) {
generatedAt: new Date().toISOString(), // 首次尝试:使用原始 messages
currentMessages = messagesPayload.messages;
} else {
// 重试:添加强制修正消息
const previousSummary = lastResponse?.summary || "(无摘要)";
const correctionMessage = {
role: "user",
content: `## ⚠ 上次响应不合格,必须重新生成\n\n你上次返回的内容:\n\`\`\`json\n${JSON.stringify(lastResponse, null, 2)}\n\`\`\`\n\n**问题**:${lastResponse && !Array.isArray(lastResponse.files) ? "缺少 files 数组" : Array.isArray(lastResponse.files) && lastResponse.files.length === 0 ? "files 数组为空" : "响应格式错误"}\n\n**强制要求**:\n1. 必须生成完整的 Vue 组件代码\n2. files 数组必须非空,每个元素包含 path、language、purpose、content\n3. content 字段必须是完整可执行的 Vue SFC 代码(包含 <template>、<script>、<style>)\n4. 禁止只返回 summary\n5. 禁止返回空 files 数组\n\n**现在立即重新生成,严格按照以上要求输出完整 JSON。**`,
};
currentMessages = [...messagesPayload.messages, correctionMessage];
_log(`[ai-direct-execute] ⚠ 第 ${attempt} 次重试:上次响应 ${previousSummary}`);
}
let providerResult;
if (args.provider === "openai-compatible") {
providerResult = await callOpenAiCompatible(currentMessages, args.model);
} else {
throw new Error(`不支持的 provider: ${args.provider}`);
}
// 保存原始响应(即使解析失败也能调试)
const rawContent = providerResult.content || "";
const rawPath = attempt === 1
? responsePath.replace(".provider-response.json", ".provider-response.raw.txt")
: responsePath.replace(".provider-response.json", `.provider-response.raw.attempt-${attempt}.txt`);
if (rawContent) {
fs.writeFileSync(rawPath, rawContent, "utf8");
}
lastRawContent = rawContent;
let structured;
try {
structured = extractJsonPayload(providerResult.content);
lastResponse = structured;
} catch (parseError) {
const preview = rawContent.slice(0, 500);
_log(`[ai-direct-execute] ⚠ 第 ${attempt} 次尝试:JSON 解析失败: ${parseError.message}`);
_log(`[ai-direct-execute] ⚠ 原始响应前 500 字符:\n${preview}`);
if (attempt === maxAttempts) throw parseError;
continue;
}
// 验证响应
const validation = validateResponse(structured);
if (!validation.valid) {
_log(`[ai-direct-execute] ⚠ 第 ${attempt} 次尝试:${validation.reason}`);
if (attempt === maxAttempts) {
// 最后一次尝试也失败,抛出错误
throw new Error(`AI 响应验证失败(${maxAttempts} 次尝试均失败): ${validation.reason}`);
}
continue;
}
// 验证通过
_log(`[ai-direct-execute] ✓ 第 ${attempt} 次尝试:验证通过,生成 ${structured.files.length} 个文件`);
const persisted = {
meta: {
generator: "scripts/ai-direct-execute.mjs",
generatedAt: new Date().toISOString(),
mode: providerResult.provider,
model: providerResult.model,
bundleFile: normalizePath(bundlePath),
attempts: attempt,
},
response: structured,
raw: providerResult.raw,
};
fs.writeFileSync(responsePath, `${JSON.stringify(persisted, null, 2)}\n`, "utf8");
return {
mode: providerResult.provider, mode: providerResult.provider,
model: providerResult.model, responsePath,
bundleFile: normalizePath(bundlePath), response: structured,
}, };
response: structured, }
raw: providerResult.raw,
};
fs.writeFileSync(responsePath, `${JSON.stringify(persisted, null, 2)}\n`, "utf8");
return { // 不应到达这里,但作为安全检查
mode: providerResult.provider, throw new Error("resolveAiResponse: 重试循环异常退出");
responsePath,
response: structured,
};
} }
function unwrapResponseFile(responsePath) { function unwrapResponseFile(responsePath) {
......
...@@ -277,11 +277,14 @@ function buildSystemPrompt(bundle, appendContext = "") { ...@@ -277,11 +277,14 @@ function buildSystemPrompt(bundle, appendContext = "") {
"", "",
"---", "---",
"", "",
"你必须输出结构化 JSON,不要输出解释性前缀或 Markdown。", "## ⚠ 输出格式强制要求(违反则视为失败)",
"", "",
"输出 JSON 结构:", "你必须输出结构化 JSON,**禁止**输出解释性前缀或 Markdown。",
"",
"### 输出 JSON 结构",
"```json",
"{", "{",
' "summary": "string",', ' "summary": "string(简要描述生成内容)",',
' "dependencyPlan": {', ' "dependencyPlan": {',
' "needsDependencyChange": true,', ' "needsDependencyChange": true,',
' "packages": ["string"],', ' "packages": ["string"],',
...@@ -292,11 +295,32 @@ function buildSystemPrompt(bundle, appendContext = "") { ...@@ -292,11 +295,32 @@ function buildSystemPrompt(bundle, appendContext = "") {
' "recommendedCommand": "string"', ' "recommendedCommand": "string"',
" },", " },",
' "files": [', ' "files": [',
' { "path": "string", "language": "vue|tsx|ts|js|css|json|md", "purpose": "string", "content": "string" }', ' { "path": "string", "language": "vue|tsx|ts|js|css|json|md", "purpose": "string", "content": "string(完整代码)" }',
" ],", " ],",
' "notes": ["string"],', ' "notes": ["string"],',
' "validationChecklist": ["string"]', ' "validationChecklist": ["string"]',
"}" "}",
"```",
"",
"### files 数组约束",
"- **files 数组必须非空**:至少包含 1 个文件对象",
"- **每个文件必须包含完整代码**:content 字段必须是可执行的完整代码,不能是占位符或描述",
"- **禁止返回空 files 或仅返回 summary**:如果 files 为空数组,系统将视为生成失败",
"- **即使 design context 很小,也必须生成代码**:不要以 summary 替代代码生成",
"",
"### 错误示例(禁止)",
"```json",
'{ "summary": "生成导航栏组件..." }',
"// 缺少 files 数组,系统会拒绝",
"```",
"",
"### 正确示例",
"```json",
"{",
' "summary": "生成导航栏组件",',
' "files": [{ "path": "src/views/cc/components/NavBar.vue", "language": "vue", "purpose": "顶部导航栏", "content": "<template>...</template>" }]',
"}",
"```"
); );
return parts.join("\n"); return parts.join("\n");
...@@ -383,14 +407,38 @@ function buildUserPrompt({ bundle, promptText, designContext, variableDefsText } ...@@ -383,14 +407,38 @@ function buildUserPrompt({ bundle, promptText, designContext, variableDefsText }
sections.push( sections.push(
"# ⚠ 设计示意图过滤规则(重要)", "# ⚠ 设计示意图过滤规则(重要)",
"", "",
"设计稿中可能包含以下**系统级示意图元素**,这些**不需要生成代码**:", "设计稿中可能包含以下**系统级示意图元素**,处理规则如下:",
"- 状态栏(Status Bar):时间、信号图标、WiFi 图标、电池图标等系统状态显示", "",
"- 导航栏(Navigation Bar):返回按钮、标题、更多按钮等系统导航元素", "## 必须跳过(不生成代码)",
"- 小程序导航栏右侧胶囊按钮(Capsule Button):胶囊状操作按钮", "- 状态栏中的系统图标:时间显示、信号图标、WiFi 图标、电池图标",
"- 底部安全区(Safe Area):iPhone 底部横条等系统 UI", "- 导航栏中的系统图标:返回箭头、更多按钮(...)图标",
"- 小程序导航栏右侧胶囊按钮(Capsule Button)",
"- 底部安全区(Safe Area):iPhone 底部横条",
"- 系统键盘、系统弹窗、系统提示框等操作系统 UI", "- 系统键盘、系统弹窗、系统提示框等操作系统 UI",
"", "",
"请直接**忽略**这些示意图元素,只生成**业务功能组件**。", "## 必须生成(使用项目组件库)",
"- **导航栏组件本身**:即使导航栏看起来像系统元素,也必须使用项目中的导航栏组件(如 VNavBar、NavBar 等)生成,包括 title 属性。这是业务必需组件。",
"- **返回按钮功能**:导航栏的左返回功能需要通过组件 props 配置(如 leftArrow),而不是生成 SVG 图标",
"",
"## ⚠ 核心原则:只要给了内容,就必须生成代码(不可拒绝)",
"",
"我提供的每个 Figma URL 都经过筛选,**全部包含有意义的业务内容**,不存在空元素或纯装饰元素。",
"",
"**你必须:**",
"- 对每个提供的 URL/Figma 节点,**无条件生成对应的组件代码**",
"- 即使 design context 字符数很少(如 <2000),也必须生成代码",
"- 即使节点看起来简单(如只有按钮、图标),也必须生成完整的 Vue 组件",
"- 使用项目组件库(如 VNavBar)来实现导航栏等业务组件",
"",
"**你禁止:**",
"- 返回 `{\"summary\": \"...\"}` 格式拒绝生成代码",
"- 返回空的 files 数组 `\"files\": []`",
"- 以\"节点只包含系统元素\"为由跳过生成",
"- 以\"design context 太小\"为由返回 summary 而非代码",
"- 任何形式的拒绝或推脱",
"",
"**违反以上规则将导致生成任务失败,请严格遵守。**",
"",
"", "",
"# Instructions", "# Instructions",
isMultiModule isMultiModule
......
#!/usr/bin/env node
// ============================================================================
// AI Direct Server - 入口文件
// 职责:初始化依赖、启动服务器
// ============================================================================
import path from "node:path";
import { fileURLToPath } from "node:url";
import { requireWorkspaceRoot } from "../../scripts/workspace-root.mjs";
import { startServer } from "./modules/server.mjs";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = requireWorkspaceRoot();
startServer(repoRoot);
// ============================================================================
// Configuration Module - 配置管理
// ============================================================================
export const PORT = Number.parseInt(process.env.AI_DIRECT_PORT || "3210", 10);
export const PREVIEW_DIR = "apps/web/ai-previews";
export const DEFAULT_CONFIG = {
figmaApiKey: process.env.FIGMA_API_KEY || "figd_Cs0tDjz-UVojDvRlC2c-_4g5xR-hSwm7xP6kFzwd",
aiBaseUrl: process.env.AI_DIRECT_OPENAI_BASE_URL || "https://dashscope.aliyuncs.com/compatible-mode/v1",
aiApiKey: process.env.AI_DIRECT_OPENAI_API_KEY || "sk-954dfaed75e040b6a06f9c908b0a8c85",
aiModel: process.env.AI_DIRECT_OPENAI_MODEL || "qwen3.7-max",
visionModel: process.env.AI_DIRECT_VISION_MODEL || "qwen3.6-plus",
skipScreenshotSummary: false,
};
export const MODEL_CANDIDATES = [
{ label: "Qwen3.7 Max", value: "qwen3.7-max" },
{ label: "Qwen3.6 Plus", value: "qwen3.6-plus" },
{ label: "Qwen Max", value: "qwen-max" },
{ label: "Qwen Plus", value: "qwen-plus" },
{ label: "Qwen Turbo", value: "qwen-turbo" },
{ label: "DeepSeek V3", value: "deepseek-v3" },
{ label: "DeepSeek R1", value: "deepseek-r1" },
];
export const URL_CANDIDATES = [
{ label: "阿里云 DashScope", value: "https://dashscope.aliyuncs.com/compatible-mode/v1" },
{ label: "OpenAI Official", value: "https://api.openai.com/v1" },
{ label: "SiliconFlow", value: "https://api.siliconflow.cn/v1" },
{ label: "自定义", value: "" },
];
// ============================================================================
// Preview Project Module - 预览项目管理
// 职责:项目列表、文件扫描、bundle 管理
// ============================================================================
import fs from "node:fs";
import path from "node:path";
import { PREVIEW_DIR } from "./config.mjs";
/**
* 列出所有预览项目
* @param {string} repoRoot - 仓库根目录
* @returns {Array<{name: string, packageName: string, path: string}>}
*/
export function listPreviewProjects(repoRoot) {
const dir = path.join(repoRoot, PREVIEW_DIR);
if (!fs.existsSync(dir)) return [];
return fs.readdirSync(dir, { withFileTypes: true })
.filter((e) => e.isDirectory())
.map((e) => {
const pkgPath = path.join(dir, e.name, "package.json");
let packageName = `@venus/${e.name}`;
if (fs.existsSync(pkgPath)) {
try {
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
packageName = pkg.name || packageName;
} catch {
// ignore
}
}
return {
name: e.name,
packageName,
path: path.join(dir, e.name),
};
});
}
/**
* 列出项目中的生成文件
* @param {string} projectRoot - 项目根目录
* @returns {Array<{path: string, fullPath: string}>}
*/
export function listGeneratedFiles(projectRoot) {
if (!projectRoot || !fs.existsSync(projectRoot)) return [];
const viewsDir = path.join(projectRoot, "src", "views");
if (!fs.existsSync(viewsDir)) return [];
const results = [];
walkViews(viewsDir, "", results);
return results;
}
/**
* 递归扫描 views 目录
*/
function walkViews(dir, prefix, results) {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const relPath = prefix ? `${prefix}/${entry.name}` : entry.name;
if (entry.isDirectory()) {
walkViews(path.join(dir, entry.name), relPath, results);
} else if (/\.(?:vue|ts|tsx|css|scss)$/.test(entry.name)) {
results.push({
path: `src/views/${relPath}`,
fullPath: path.join(dir, entry.name),
});
}
}
}
/**
* 列出所有 bundle 页面
* @param {string} repoRoot - 仓库根目录
* @returns {Array<{slug: string, bundleFile: string}>}
*/
export function listBundlePages(repoRoot) {
const previewDir = path.join(repoRoot, PREVIEW_DIR);
if (!fs.existsSync(previewDir)) return [];
const results = [];
const projects = fs.readdirSync(previewDir, { withFileTypes: true })
.filter((e) => e.isDirectory());
for (const project of projects) {
const aiDir = path.join(previewDir, project.name, ".ai-direct");
if (!fs.existsSync(aiDir)) continue;
const pages = fs.readdirSync(aiDir, { withFileTypes: true })
.filter((e) => e.isDirectory());
for (const page of pages) {
const pageDir = path.join(aiDir, page.name);
const files = fs.readdirSync(pageDir);
const bundle = files.find((f) => f.endsWith(".ai-direct-context-bundle.json"));
if (bundle) {
results.push({
slug: `${project.name}/${page.name}`,
bundleFile: path.join(pageDir, bundle),
});
}
}
}
return results;
}
/**
* 根据配置查找目标项目
* @param {string} repoRoot - 仓库根目录
* @param {Object} config - 配置对象
* @returns {Object|null} - 匹配的项目
*/
export function findTargetProject(repoRoot, config) {
const projects = listPreviewProjects(repoRoot);
let target = null;
if (config.existingProject) {
target = projects.find((p) => p.name === config.existingProject);
}
if (!target && config.pageName) {
target = projects.find((p) => p.name.includes(config.pageName.toLowerCase()));
}
if (!target && projects.length > 0) {
target = projects.sort((a, b) => {
const aStat = fs.statSync(a.path);
const bStat = fs.statSync(b.path);
return bStat.mtimeMs - aStat.mtimeMs;
})[0];
}
return target;
}
// ============================================================================
// Process Manager Module - 子进程生命周期管理
// Singleton Pattern: 全局唯一的进程管理器
// ============================================================================
import { spawn } from "node:child_process";
let currentProcess = null;
let isRunning = false;
/**
* 获取当前是否正在运行
*/
export function getIsRunning() {
return isRunning;
}
/**
* 设置运行状态
*/
export function setIsRunning(value) {
isRunning = value;
}
/**
* 获取当前进程
*/
export function getCurrentProcess() {
return currentProcess;
}
/**
* 设置当前进程
*/
export function setCurrentProcess(proc) {
currentProcess = proc;
}
/**
* 异步执行子进程(流式输出)
* @param {string} command - 命令
* @param {string[]} args - 参数数组
* @param {object} options - spawn 选项
* @param {Function} onOutput - 输出回调 (line, stream) => void
* @returns {Promise<{stdout: string, stderr: string, status: number}>}
*/
export function spawnAsync(command, args, options, onOutput) {
return new Promise((resolve, reject) => {
const child = spawn(command, args, {
...options,
stdio: ["ignore", "pipe", "pipe"],
});
let stdout = "";
let stderr = "";
let stdoutBuffer = "";
child.stdout.on("data", (data) => {
stdout += data;
if (onOutput) {
stdoutBuffer += data.toString();
const lines = stdoutBuffer.split("\n");
stdoutBuffer = lines.pop() || "";
for (const line of lines) {
if (line) onOutput(line, "stdout");
}
}
});
child.stderr.on("data", (data) => {
stderr += data;
if (onOutput) {
const lines = data.toString().split("\n");
for (const line of lines) {
if (line) onOutput(line, "stderr");
}
}
});
child.on("exit", (code) => {
if (onOutput && stdoutBuffer) {
onOutput(stdoutBuffer, "stdout");
}
resolve({ stdout, stderr, status: code });
});
child.on("error", (err) => {
reject(err);
});
if (options?.timeout) {
setTimeout(() => {
child.kill();
reject(new Error(`Process timed out after ${options.timeout}ms`));
}, options.timeout);
}
});
}
/**
* 停止当前运行的进程
*/
export async function stopCurrentProcess() {
if (currentProcess) {
currentProcess.kill("SIGTERM");
await new Promise((r) => setTimeout(r, 1000));
if (currentProcess) {
currentProcess.kill("SIGKILL");
await new Promise((r) => setTimeout(r, 500));
}
}
}
/**
* 读取 JSON 文件
*/
export function readJson(filePath) {
try {
return JSON.parse(fs.readFileSync(filePath, "utf8"));
} catch {
return null;
}
}
// ============================================================================
// Server Module - HTTP 服务器和路由
// 职责:HTTP 请求处理、SSE 连接管理、静态文件服务
// ============================================================================
import fs from "node:fs";
import http from "node:http";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { DEFAULT_CONFIG, MODEL_CANDIDATES, PORT, URL_CANDIDATES } from "./config.mjs";
import { runPipeline } from "./pipeline.mjs";
import { listBundlePages, listGeneratedFiles, listPreviewProjects } from "./preview-project.mjs";
import { getCurrentProcess, getIsRunning } from "./process-manager.mjs";
import { addClient, getPreviewUrl, removeClient } from "./sse.mjs";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const __publicDir = path.join(__dirname, "..", "public");
/**
* 解析 JSON 请求体
*/
function parseBody(req) {
return new Promise((resolve, reject) => {
let body = "";
req.on("data", (chunk) => { body += chunk; });
req.on("end", () => {
try {
resolve(JSON.parse(body));
} catch {
reject(new Error("Invalid JSON"));
}
});
req.on("error", reject);
});
}
/**
* 发送 JSON 响应
*/
function sendJson(res, data, status = 200) {
res.writeHead(status, {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
});
res.end(JSON.stringify(data));
}
/**
* 发送静态文件
*/
function serveStatic(res, filePath, contentType) {
fs.readFile(filePath, (err, data) => {
if (err) {
res.writeHead(404);
res.end("Not Found");
return;
}
res.writeHead(200, { "Content-Type": contentType });
res.end(data);
});
}
/**
* 获取静态文件 MIME 类型
*/
function getMimeType(filePath) {
const ext = path.extname(filePath).toLowerCase();
const mimeTypes = {
".html": "text/html; charset=utf-8",
".css": "text/css; charset=utf-8",
".js": "application/javascript; charset=utf-8",
".json": "application/json",
".png": "image/png",
".jpg": "image/jpeg",
".gif": "image/gif",
".svg": "image/svg+xml",
".ico": "image/x-icon",
};
return mimeTypes[ext] || "application/octet-stream";
}
/**
* 检查是否为安全的静态文件路径
* 通过解析最终路径并校验是否在 public 目录内,兼容 Windows 路径分隔符
*/
function isSafeStaticPath(requestPath) {
// 拒绝包含 URL 编码或空段的可疑请求
if (requestPath.includes("%") || requestPath.includes("\0")) return false;
// 解析最终绝对路径,path.resolve 会自动处理 ".." 和 "."
const resolved = path.resolve(__publicDir, requestPath);
const safeRoot = path.resolve(__publicDir);
// 必须以 publicDir 为前缀(防止路径遍历)
if (!resolved.startsWith(safeRoot + path.sep) && resolved !== safeRoot) {
return false;
}
// 只允许 css/ 或 js/ 子目录下的文件(使用 path.sep 适配平台)
const relative = path.relative(safeRoot, resolved);
const segments = relative.split(path.sep);
if (segments.length < 2) return false; // 必须至少有两层,例如 css/style.css
return segments[0] === "css" || segments[0] === "js";
}
/**
* 处理 SSE 连接
*/
function handleSSE(req, res) {
res.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"Access-Control-Allow-Origin": "*",
});
addClient(res);
res.write(`data: {"type":"connected"}\n\n`);
const previewUrl = getPreviewUrl();
if (previewUrl) {
res.write(`event: preview\ndata: ${JSON.stringify({ url: previewUrl })}\n\n`);
}
if (getIsRunning()) {
res.write(`event: status\ndata: ${JSON.stringify({ running: true, step: "running" })}\n\n`);
}
req.on("close", () => {
removeClient(res);
});
}
/**
* 处理 API 请求
*/
async function handleApi(req, res, repoRoot) {
const url = req.url;
const method = req.method;
// CORS preflight
if (method === "OPTIONS") {
res.writeHead(204, {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type",
});
res.end();
return;
}
// GET /api/status
if (url === "/api/status" && method === "GET") {
sendJson(res, {
running: getIsRunning(),
previewUrl: getPreviewUrl(),
models: MODEL_CANDIDATES,
urlCandidates: URL_CANDIDATES,
defaultConfig: DEFAULT_CONFIG,
});
return;
}
// GET /api/config
if (url === "/api/config" && method === "GET") {
sendJson(res, {
modelCandidates: MODEL_CANDIDATES,
urlCandidates: URL_CANDIDATES,
defaults: DEFAULT_CONFIG,
});
return;
}
// GET /api/preview-url
if (url === "/api/preview-url" && method === "GET") {
sendJson(res, { previewUrl: getPreviewUrl() });
return;
}
// GET /api/projects
if (url === "/api/projects" && method === "GET") {
const projects = listPreviewProjects(repoRoot);
sendJson(res, { previewProjects: projects });
return;
}
// GET /api/bundles
if (url === "/api/bundles" && method === "GET") {
const bundles = listBundlePages(repoRoot);
sendJson(res, { bundles });
return;
}
// GET /api/files?project=xxx
if (url.startsWith("/api/files") && method === "GET") {
const params = new URL(url, `http://${req.headers.host}`).searchParams;
const projectName = params.get("project");
const projects = listPreviewProjects(repoRoot);
const project = projects.find((p) => p.name === projectName);
if (!project) {
sendJson(res, { files: [] }, 404);
return;
}
const files = listGeneratedFiles(project.path);
sendJson(res, { project: project.name, files });
return;
}
// GET /api/file?path=xxx - 读取单个文件内容
if (url.startsWith("/api/file") && method === "GET") {
const params = new URL(url, `http://${req.headers.host}`).searchParams;
const filePath = params.get("path");
if (!filePath) {
res.writeHead(400, { "Content-Type": "text/plain" });
res.end("Missing path parameter");
return;
}
// 安全检查:防止路径遍历
const normalized = path.normalize(filePath);
if (normalized.includes("..") || path.isAbsolute(filePath)) {
res.writeHead(403, { "Content-Type": "text/plain" });
res.end("Forbidden");
return;
}
// 只允许读取 ai-previews 目录下的文件
const fullPath = path.join(repoRoot, "apps/web/ai-previews", filePath);
if (!fs.existsSync(fullPath)) {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Not Found");
return;
}
const content = fs.readFileSync(fullPath, "utf8");
res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
res.end(content);
return;
}
// POST /api/generate
if (url === "/api/generate" && method === "POST") {
try {
const config = await parseBody(req);
runPipeline(config, repoRoot);
sendJson(res, { success: true, message: "Pipeline started" });
} catch (error) {
sendJson(res, { success: false, error: error.message }, 400);
}
return;
}
// POST /api/stop
if (url === "/api/stop" && method === "POST") {
const currentProcess = getCurrentProcess();
if (currentProcess) {
currentProcess.kill("SIGTERM");
setTimeout(() => {
if (getCurrentProcess()) {
getCurrentProcess().kill("SIGKILL");
}
}, 3000);
}
sendJson(res, { success: true, message: "Stop signal sent" });
return;
}
// 404
sendJson(res, { error: "Not Found" }, 404);
}
/**
* 创建 HTTP 服务器
*/
export function createServer(repoRoot) {
const server = http.createServer(async (req, res) => {
const url = req.url;
// SSE endpoint
if (url === "/events") {
handleSSE(req, res);
return;
}
// API endpoints
if (url.startsWith("/api/")) {
await handleApi(req, res, repoRoot);
return;
}
// Static files
if (url === "/" || url === "/index.html") {
serveStatic(res, path.join(__publicDir, "index.html"), "text/html; charset=utf-8");
return;
}
// 静态资源 (css/, js/)
if (url.startsWith("/css/") || url.startsWith("/js/")) {
const requestPath = url.slice(1); // 移除开头的 /
if (!isSafeStaticPath(requestPath)) {
res.writeHead(403);
res.end("Forbidden");
return;
}
const filePath = path.join(__publicDir, requestPath);
serveStatic(res, filePath, getMimeType(filePath));
return;
}
// 404
res.writeHead(404);
res.end("Not Found");
});
return server;
}
/**
* 启动服务器
*/
export function startServer(repoRoot) {
const server = createServer(repoRoot);
server.listen(PORT, () => {
console.log(`\n[ai-direct-server] 服务已启动: http://localhost:${PORT}`);
console.log(`[ai-direct-server] SSE 端点: http://localhost:${PORT}/events`);
console.log(`[ai-direct-server] API 端点: http://localhost:${PORT}/api/status\n`);
});
// 全局错误兜底
process.on("uncaughtException", (err) => {
console.error("[server] uncaughtException:", err.message, err.stack);
});
process.on("unhandledRejection", (err) => {
console.error("[server] unhandledRejection:", err instanceof Error ? err.message : err);
});
}
// ============================================================================
// SSE (Server-Sent Events) Module - 事件广播系统
// Observer Pattern: 多客户端订阅,统一广播
// ============================================================================
const clients = new Set();
let previewUrl = null;
let heartbeatTimer = null;
/**
* 添加 SSE 客户端连接
* @param {http.ServerResponse} res - HTTP 响应对象
*/
export function addClient(res) {
clients.add(res);
}
/**
* 移除 SSE 客户端连接
* @param {http.ServerResponse} res - HTTP 响应对象
*/
export function removeClient(res) {
clients.delete(res);
}
/**
* 广播事件到所有客户端
* @param {string} event - 事件类型
* @param {Object} data - 事件数据
*/
export function broadcast(event, data) {
const payload = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
for (const client of clients) {
try {
client.write(payload);
} catch {
// 客户端已断开,忽略
}
}
}
/**
* 发送控制台输出事件
* @param {string} text - 文本内容
* @param {string} stream - 输出流类型 (stdout/stderr/system/progress/heartbeat)
*/
export function emitConsole(text, stream) {
broadcast("output", {
stream: stream || "stdout",
text,
timestamp: Date.now(),
});
}
/**
* 发送步骤状态事件
* @param {string} step - 步骤标识
* @param {string} label - 步骤显示名称
*/
export function emitStep(step, label) {
broadcast("status", { running: true, step, label });
emitConsole(`\n⏳ [${new Date().toLocaleTimeString()}] ${label}\n`, "progress");
}
/**
* 设置预览 URL
* @param {string} url - 预览地址
* @param {Function} logFn - 日志函数
*/
export function setPreviewUrl(url, logFn) {
previewUrl = url;
if (logFn) logFn(`预览地址: ${url}`);
broadcast("preview", { url });
}
/**
* 获取预览 URL
*/
export function getPreviewUrl() {
return previewUrl;
}
/**
* 启动心跳定时器
*/
export function startHeartbeat(isRunningFn) {
stopHeartbeat();
heartbeatTimer = setInterval(() => {
if (isRunningFn && isRunningFn()) {
emitConsole(`⏳ [${new Date().toLocaleTimeString()}] 处理中...\n`, "heartbeat");
}
}, 15_000);
}
/**
* 停止心跳定时器
*/
export function stopHeartbeat() {
if (heartbeatTimer) {
clearInterval(heartbeatTimer);
heartbeatTimer = null;
}
}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Direct Console</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="app">
<div class="topbar">
<h1>Venus <span>AI Direct</span></h1>
<div class="progress-steps" id="progressSteps"></div>
<div class="status-badge idle" id="statusBadge">空闲</div>
</div>
<div class="sidebar">
<div class="section">
<div class="section-header" onclick="toggleSection(this)">
<span>AI 模型配置</span>
<span class="arrow">&#9654;</span>
</div>
<div class="section-body hidden">
<label>模型
<select id="aiModel"></select>
</label>
<label>API Base URL
<select id="aiUrlSelect" onchange="onUrlSelectChange(this)"></select>
</label>
<label>自定义 URL
<input type="text" id="aiBaseUrl" placeholder="https://api.example.com/v1">
</label>
<label>API Key
<input type="password" id="aiApiKey" placeholder="sk-...">
</label>
<label>视觉模型
<input type="text" id="visionModel" placeholder="qwen-vl-max">
</label>
</div>
</div>
<div class="section">
<div class="section-header" onclick="toggleSection(this)">
<span>Figma 配置</span>
<span class="arrow">&#9654;</span>
</div>
<div class="section-body hidden">
<label>Figma API Key
<input type="password" id="figmaApiKey" placeholder="figd_...">
</label>
<label>Figma 页面 URL(每行一个,支持多个模块)
<textarea id="figmaUrls" rows="3" placeholder="https://www.figma.com/design/xxx?node-id=1-1&#10;https://www.figma.com/design/xxx?node-id=2-2"></textarea>
</label>
<label>生成策略
<select id="generateStrategy">
<option value="batch">合并一次生成(速度快,简单页面推荐)</option>
<option value="sequential">智能分批生成(还原度高,复杂页面推荐)</option>
</select>
</label>
<label>分批阈值(字符数)
<input type="number" id="batchThreshold" value="3000" min="1000" max="10000" step="500">
</label>
<div style="font-size:11px;color:var(--text-dim);line-height:1.5;margin-top:2px">
<b>合并一次</b>:所有 URL 的 context 合并后一次投给 AI,适合简单页面。<br>
<b>智能分批</b>:逐个拉取 context,攒到阈值后一批投给 AI,小模块合并成一个组件,适合复杂页面。
</div>
</div>
</div>
<div class="section">
<div class="section-header" onclick="toggleSection(this)">
<span>平台与组件库</span>
<span class="arrow">&#9654;</span>
</div>
<div class="section-body hidden">
<label>目标平台
<select id="targetPlatform" onchange="onPlatformChange()">
<option value="">自动检测</option>
<option value="pc">PC 管理后台</option>
<option value="mobile">移动端 H5</option>
<option value="miniprogram">小程序</option>
<option value="react">React PC</option>
</select>
</label>
<label>降级组件库
<select id="fallbackUi">
<option value="">跟随平台默认</option>
</select>
</label>
<div style="font-size:11px;color:var(--text-dim);line-height:1.5;margin-top:2px">
自动检测会根据项目依赖和路径判断平台。若检测不准,可手动指定。降级组件库可在配置文件 <code style="color:var(--accent)">scripts/ai-direct-platform-ui.config.json</code> 中维护。
</div>
</div>
</div>
<div class="section">
<div class="section-header" onclick="toggleSection(this)">
<span>项目配置</span>
<span class="arrow">&#9654;</span>
</div>
<div class="section-body hidden">
<label>项目来源
<select id="projectSource" onchange="onProjectSourceChange()">
<option value="new">新建预览项目</option>
<option value="append">追加到已有项目</option>
</select>
</label>
<div id="newProjectOptions">
<label>页面名称 (PascalCase)
<input type="text" id="pageName" placeholder="AllocationConfirmation">
</label>
</div>
<div id="appendOptions" style="display:none">
<label>选择已有项目
<select id="projectSelect"></select>
</label>
<label>新页面名称 (PascalCase)
<input type="text" id="appendPageName" placeholder="NewPage">
</label>
</div>
<div class="checkbox-row">
<input type="checkbox" id="refreshContext">
<label>重新生成 Context(从 Figma 重新拉取)</label>
</div>
<div class="checkbox-row">
<input type="checkbox" id="forceOverwrite" checked>
<label>覆盖已有预览项目</label>
</div>
<div class="checkbox-row">
<input type="checkbox" id="skipPreview">
<label>跳过预览项目启动</label>
</div>
<div class="checkbox-row">
<input type="checkbox" id="skipScreenshotSummary" checked>
<label>跳过截图视觉摘要(节省 5-15 秒)</label>
</div>
<div class="checkbox-row">
<input type="checkbox" id="enableGovernance" checked>
<label>启用 Venus 治理(fitness 质检、健康检查、文件大小检测等)</label>
</div>
</div>
</div>
<div class="btn-row" style="margin-top:4px">
<button class="btn btn-primary" id="btnGenerate" onclick="startGenerate()">&#9654; 开始生成</button>
<button class="btn btn-danger" id="btnStop" onclick="stopGenerate()" disabled>&#9632; 停止</button>
</div>
<button class="btn btn-ghost" onclick="clearConsole()" style="width:100%">清空控制台</button>
</div>
<div class="main">
<div class="tabs">
<div class="tab active" onclick="switchTab('console',this)">控制台</div>
<div class="tab" onclick="switchTab('preview',this)">预览</div>
<div class="tab" onclick="switchTab('files',this)">生成文件</div>
<div class="tab" onclick="switchTab('summary',this)">摘要</div>
</div>
<div class="tab-content">
<div class="tab-panel active" id="panel-console">
<div class="console" id="consoleOutput">
<div class="console-empty">等待生成任务开始...</div>
</div>
</div>
<div class="tab-panel" id="panel-preview">
<div class="preview-panel" id="previewContainer">
<div class="preview-empty" id="previewEmpty">
<div class="icon">&#128421;</div>
<div class="msg">预览尚未就绪</div>
<div class="hint">流程运行到"启动预览"步骤后,将自动在此显示</div>
</div>
</div>
</div>
<div class="tab-panel" id="panel-files">
<div class="file-panel">
<div class="file-tree" id="fileTree">
<div class="code-empty" style="width:100%">暂无文件</div>
</div>
<div class="code-viewer" id="codeViewer">
<div class="code-empty">选择文件查看内容</div>
</div>
</div>
</div>
<div class="tab-panel" id="panel-summary">
<div class="summary-panel" id="summaryContent">
<div class="code-empty">等待生成完成...</div>
</div>
</div>
</div>
</div>
</div>
<script src="js/app.js"></script>
</body>
</html>
...@@ -3,4 +3,4 @@ echo Stopping server... ...@@ -3,4 +3,4 @@ echo Stopping server...
for /f "tokens=5" %%a in ('netstat -ano ^| findstr ":3210" ^| findstr "LISTENING"') do taskkill /F /PID %%a >nul 2>&1 for /f "tokens=5" %%a in ('netstat -ano ^| findstr ":3210" ^| findstr "LISTENING"') do taskkill /F /PID %%a >nul 2>&1
timeout /t 2 /nobreak >nul timeout /t 2 /nobreak >nul
echo Starting server... echo Starting server...
node scripts/ai-direct-server.mjs node index.mjs
...@@ -8,7 +8,7 @@ ...@@ -8,7 +8,7 @@
".vue": 700 ".vue": 700
}, },
"hotspots": { "hotspots": {
"scripts/ai-direct-execute.mjs": 1594, "scripts/ai-direct-execute.mjs": 1701,
"scripts/ai-direct-server.mjs": 1228, "scripts/ai-direct-server.mjs": 1228,
"scripts/ai-direct-messages.mjs": 996, "scripts/ai-direct-messages.mjs": 996,
"apps/uniappX/uniapp-x-tape/devTools/page/components/main.vue": 1668, "apps/uniappX/uniapp-x-tape/devTools/page/components/main.vue": 1668,
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!