diff --git a/.env.pcb.example b/.env.pcb.example new file mode 100644 index 0000000..1c5cf57 --- /dev/null +++ b/.env.pcb.example @@ -0,0 +1,13 @@ +# Copy to .env.local. Real provider keys NEVER belong in VITE_* or Git. +# This is the existing shared internal PCB service. Change for another installation. +PCB_API_TARGET=http://192.168.1.200:8000 +PCB_API_ORIGIN=http://127.0.0.1:5173 +HOST=127.0.0.1 +PORT=5180 +# For LAN HTTPS, supply a certificate trusted by the client browser: +# HOST=0.0.0.0 +# TLS_CERT=/absolute/path/server.crt +# TLS_KEY=/absolute/path/server.key + +# With an HTTPS reverse proxy, explicitly set the browser-facing origin: +# PUBLIC_ORIGIN=https://cadworld-studio.robotquan.com diff --git a/PCB-SERVICE.md b/PCB-SERVICE.md new file mode 100644 index 0000000..a63644d --- /dev/null +++ b/PCB-SERVICE.md @@ -0,0 +1,83 @@ +# AI PCB 服务接入 + +这份仓库包含 VibeMake PCB 网站、PCB 任务客户端、启动脚本及同源代理。AI 生成运行在独立的 auto_pcb 服务器上;本仓库不包含 DeepSeek 密钥,也不要求每个浏览器配置模型。 + +## 拉取后启动 + +要求 Node.js 20+(建议 22 LTS)、npm,以及能连接 PCB 后台的网络。 + +```bash +cp .env.pcb.example .env.local # 可选,默认连接现有 192.168.1.200:8000 +./start.sh +``` + +首次启动自动安装锁文件指定的依赖并构建,之后复用构建。访问 http://localhost:5180/pcb/ 。`REBUILD=1 ./start.sh` 强制重新构建。Ctrl+C 停止网站,不会取消已提交给后台的 PCB 任务。 + +默认服务地址是现有内部共享后台。其他网络/其他服务器需要在 `.env.local` 中设置 `PCB_API_TARGET`;没有后台时仍能关闭任务窗口使用编辑器,但不能生成 PCB。仅拉取本仓库不等于安装 EasyEDA、DeepSeek 和自动布线服务。 + +### 在已有远程服务器运行 + +在自己电脑的终端执行下面一条命令(项目已在服务器 `~/auto_pcb/vibemake-pcb-studio` 时): + +```bash +ssh -t -L 5180:127.0.0.1:5180 wpz@192.168.1.200 'cd ~/auto_pcb/vibemake-pcb-studio && ./start.sh' +``` + +然后访问 http://localhost:5180/pcb/ 。终端中的 SSH 连接用于访问网页;任务执行不依赖该连接。若服务器网站已在运行,使用 `ssh -N -L 5180:127.0.0.1:5180 wpz@192.168.1.200` 只建立访问通道。 + +浏览器编辑器依赖安全上下文中的 Web Crypto 和 navigator.locks。localhost 的 HTTP 可用;直接访问普通 LAN HTTP 地址可能被浏览器能力检测拒绝。LAN 直接访问应配置受信任 HTTPS:`HOST=0.0.0.0 TLS_CERT=/path/cert TLS_KEY=/path/key ./start.sh`。这两个路径可写入被忽略的 `.env.local`。 + +## 功能和边界 + +- 需求、附件上传、补答、方案选择、服务器后台生成、进度事件、断线重连、任务查询、真实图片与 BOM 预览、摘要绑定审核及下载。 +- operation_id 在任务建立前就持久化;刷新后继续查询操作。不能把 operation succeeded 当作设计成功,最终以 task.state 为准。 +- `delivery_ready` 且 `download_ready=true`、没有阻塞项时才能审核。`draft_ready` 可下载草稿,但不开放制造包。后台校验不通过不能通过前端按钮绕过。 +- 当前后台是内部共享工作台,不是多租户服务;任务列表会包含同一后台的其他任务。对公网提供多用户服务前必须增加用户认证和任务/附件/成果归属校验。 +- 上传给 AI 服务器的需求和资料由服务器处理,与 Ziro 的浏览器端加密云项目不是同一数据边界。此接入不自动上传用户已有云项目。 + +## 兼容工程导入 + +Ziro 导入器需要含 `project.json` 的旧版 `.epro`,不能通过把 `.epro2` 改名转换。现有 auto_pcb 默认只导出 epro2;后端可执行以下一次性扩展(不读取/更改 API key): + +```bash +python3 integration/install-editor-export.py ~/auto_pcb +``` + +这只为**新生成的任务**额外导出 `editor_native` 成果,旧任务冻结包保持原样。此脚本针对当前 auto_pcb 导出函数,版本不匹配或有任务执行中时会拒绝修改,并保留备份。 + +有兼容成果时,按钮“导入 编辑器副本”会验证下载摘要,转换原理图和 PCB,保存为新的本地 KiCad 项目。`AI-SOURCE.json` 记录来源 task_id 和 manifest;导入副本标为 unverified,原有制造检查和放行不延续到转换或编辑后的副本。当前仅支持单板、单原理图工程,多原理图/异常格式会明确拒绝。缺失的 3D 模型不应凭空补成已验证几何。 + +## 密钥与部署 + +DeepSeek API key 继续使用后台现有配置。禁止把 key 填入 `VITE_*`、源码、示例或 Git。本仓库不需要 provider key。`.env.local` 已被 Git 忽略;对接新后台只需配置其地址,不需要复制其模型凭据。 + +`start.sh` 启动的是 production 构建和固定目标的 `/pcb-api/` 代理;Cookie、上传、SSE 和文件下载通过同源通道。代理不缓存 API,PWA 不拦截 API 导航。代理对后台使用 `PCB_API_ORIGIN`(默认 http://127.0.0.1:5173);后台须允许这个来源。 + +保留上游 GPL-3.0-or-later 许可与 NOTICE。当前 Git remote 保持该 VibeMake 仓库配置;提交和推送由维护者执行。 + +## 子路径与现有设置 + +默认构建和启动地址是 `/pcb/`,任务接口使用同源 `/pcb/pcb-api/v1/`。构建产物中的 `pcb-service-config.json` 会通知启动服务器使用同一 base;设置 `VITE_BASE=/` 重新构建时亦能使用根路径。已有品牌、中文 JSX 运行时、云同步/遥测/旧 AI 关闭开关均保留。新的 PCB 任务入口独立使用服务端 API,不启用原来的本地 AI agent。 + +生产反向代理可以把整个 `/pcb/` 转发到 `http://127.0.0.1:5180`,保留原始路径。API 流式响应需要关闭代理缓冲并保留长连接;参考 `integration/nginx.example.conf`。 + +使用 HTTPS 反向代理终止 TLS 时,在服务器 `.env.local` 显式设置 `PUBLIC_ORIGIN=https://cadworld-studio.robotquan.com`(更换域名时对应修改),用于校验浏览器请求来源。默认 localhost 测试不需要配置此项。 + +## 开发环境与测试记录 + +网站开发需要 Git、Bash、Node.js 20+ 和 npm。仓库通过 `packageManager` 固定 pnpm 10.33.0;`start.sh` 会用 npm 启动这个版本。依赖安装使用锁文件,不需要全局安装 TypeScript 或 Vite。 + +```bash +npm exec --yes --package=pnpm@10.33.0 -- pnpm install --frozen-lockfile +npm exec --yes --package=pnpm@10.33.0 -- pnpm -C designer dev +# 生产构建及同源 API 代理: +./start.sh +``` + +本地开发服务器默认端口由 Vite 配置决定;连接 AI 任务仍需要能访问 `PCB_API_TARGET` 指定的后台。使用支持 WebAssembly、Web Crypto 和 navigator.locks 的现代浏览器,并通过 localhost 或受信任 HTTPS 访问。 + +仅开发网站、接口客户端和编辑器,不需要在电脑上安装 Python、EasyEDA、Java、自动布线器或 DeepSeek key。独立部署生成后台则需要另外取得 `ai_service_api`、`deliver_pack` 及其运行资产,安装 Python 依赖、EDA SDK/CLI、模型调用运行器、Java/布线器和渲染工具,并配置后台凭据。本仓库没有打包这些后台源码和运行环境;它不是完整生成服务器的离线安装包。 + +网站历史来自后台的 `runtime/web-v3/api.sqlite3` 和 `runtime/web-v3/core/`;不存放在本仓库。`.gitignore` 排除了本地运行记录、日志、数据库和私有环境配置。`qa/unittests/` 是应保留的自动化测试源码,不是用户测试任务记录。浏览器中已导入的编辑器项目属于本地用户数据,清空后台任务不会删除这些项目。 + +现有服务器的模型配置在 `/home/wpz/.config/ai-pcb-codex/config.toml`,通过 `AI_PCB_CODEX_HOME` 引用,独立于网站仓库。共享同一后台可以继续使用同一后台 key;开发者不需要拿到该 key。自建后台时应在仓库外的配置文件或部署密钥中提供各自的凭据,避免上传真实 key。 diff --git a/README.md b/README.md index 253597b..1e8a7b5 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,16 @@ +# VibeMake PCB Studio · AI PCB 接入 + +本版本接入服务端 AI PCB 工作流:需求与资料、方案选择、后台设计、成果预览、审核下载及独立编辑副本导入。 + +```bash +./start.sh +``` + +访问 http://localhost:5180/pcb/ 。首次启动自动安装依赖并构建;需要 Node.js 20+ 和可达的 PCB 后台。 +现有 DeepSeek API key 留在后台,本仓库不保存模型密钥。配置和远程访问见 [PCB-SERVICE.md](./PCB-SERVICE.md)。 + +以下保留原项目文档和许可说明。 + # ZiroEDA **KiCad-compatible electronics design in a browser tab. Nothing to install.** diff --git a/designer/src/App.tsx b/designer/src/App.tsx index 39caa73..c0946c3 100644 --- a/designer/src/App.tsx +++ b/designer/src/App.tsx @@ -2,6 +2,7 @@ // Copyright (C) 2026 ZiroEDA and contributors. // Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md. // Modified by VibeMake to keep frame-loading status on brand. +import { PcbServiceDock } from './pcb-service/PcbServiceDock.js'; import { OUTPUT_DOWNLOADER } from './output_downloads.js'; import { FRAME_T } from '@ziroeda/common/frame_type.js'; import { AiDock, aiEnabled, registerAiBridge } from '@ziroeda/ai'; @@ -2084,6 +2085,27 @@ export function App(): JSX.Element { return ( {manager} + { + flushSaves(); + const { convertProject } = await import('./pcb-service/import-project.js'); + const name = `AI-${task.task_id}-${Date.now()}`; + const result = await convertProject(bytes, name, { + task_id: task.task_id, + manifest_sha256: task.delivery!.manifest_sha256, + }); + const localId = await saveProject(name, result.files); + const loaded = await loadProject(localId); + if (!loaded) throw Error('编辑副本保存失败'); + raiseOrOpen(openedFromStored(loaded.files)); + onProjectIdChange(localId); + setDemoProject(false); + setDemoSource(null); + setStandalonePcb(null); + setPcbMounted(true); + setView('pcb'); + }} + /> {view !== 'home' && } {aiEnabled() && } {schMounted && ( diff --git a/designer/src/pcb-service/PcbServiceDock.tsx b/designer/src/pcb-service/PcbServiceDock.tsx new file mode 100644 index 0000000..de661e4 --- /dev/null +++ b/designer/src/pcb-service/PcbServiceDock.tsx @@ -0,0 +1,660 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import { useCallback, useEffect, useRef, useState } from 'react'; +import { createPortal } from 'react-dom'; +import { + ApiError, + artifactUrl, + base, + canAccept, + command, + request, + requestId, + stateLabel, + terminal, + type Artifact, + type Operation, + type Progress, + type Task, +} from './client.js'; +import './pcb-service.css'; + +const ACTIVE = 'vibemake.pcb-service.active', + PENDING = 'vibemake.pcb-service.operation'; +const OUTBOX = 'vibemake.pcb-service.outbox'; +type Queued = { action: string; payload: Record; request_id: string }; +function queuedCommand(): Queued | null { + try { + return JSON.parse(stored(OUTBOX) || 'null'); + } catch { + return null; + } +} +function stored(key: string) { + try { + return localStorage.getItem(key); + } catch { + return null; + } +} +function remember(key: string, value: string | null) { + try { + if (value) localStorage.setItem(key, value); + else localStorage.removeItem(key); + } catch { + /* Server history remains authoritative. */ + } +} +const eventNames: Record = { + 'agent.started': '模型开始处理', + 'agent.completed': '模型完成当前步骤', + 'design.round': '设计检查点', + 'design.fallback_started': '执行固定绘图流程', + 'schematic.wiring_verified': '引脚连接已核对', + 'pcb.component_created': '导入 PCB 器件', + 'pcb.placement_completed': '完成布局', + 'pcb.routing_progress': '正在布线', + 'delivery.ready': '检查通过,成果已打包', + 'delivery.draft': '草稿已保存', + 'manufacturing.released': 'PCB 交付包已开放下载', + 'auto.recover': '正在自动恢复', + 'operation.finished': '本次操作结束', +}; +const kindNames: Record = { + native: '可编辑原生工程', + editor_native: '编辑器兼容工程', + schematic: '原理图', + schematic_vector: '矢量原理图', + pcb: 'PCB 图纸', + pcb_preview: 'PCB 预览', + render: '三维渲染', + bom: 'BOM 物料表', + model: '三维模型', + manufacturing_package: 'PCB 交付包', + review_package: '检查与成果压缩包', + fabrication_info: '工艺信息', +}; + +export function PcbServiceDock({ + onImport, +}: { + onImport: (bytes: Uint8Array, task: Task) => Promise; +}) { + const [open, setOpen] = useState(true), + [tasks, setTasks] = useState([]), + [id, setId] = useState(() => stored(ACTIVE)); + const [queued, setQueued] = useState(queuedCommand); + const [task, setTask] = useState(null), + [pending, setPending] = useState(() => stored(PENDING)), + [events, setEvents] = useState([]); + const [connected, setConnected] = useState(false), + [error, setError] = useState(''), + [text, setText] = useState(''), + [answer, setAnswer] = useState(''), + [sending, setSending] = useState(false); + const [attachments, setAttachments] = useState<{ upload_id: string; name: string }[]>([]), + [uploading, setUploading] = useState(false); + const [preview, setPreview] = useState(null), + [bom, setBom] = useState<{ columns: string[]; rows: string[][] } | null>(null); + const idRef = useRef(id), + downloadFor = useRef(null), + cursor = useRef(0), + fileRef = useRef(null); + idRef.current = id; + const refresh = useCallback(async () => { + const data = await request<{ items: Task[] }>('/tasks'); + setTasks(data.items); + setConnected(true); + }, []); + useEffect(() => { + let alive = true; + void request('/session') + .then(() => refresh()) + .catch(() => { + if (alive) { + setConnected(false); + setError('暂时无法连接 PCB 后台。请检查启动终端中的 PCB_API_TARGET 配置。'); + } + }); + return () => { + alive = false; + }; + }, [refresh]); + useEffect(() => { + remember(ACTIVE, id); + setTask(null); + setEvents([]); + setPreview(null); + setBom(null); + cursor.current = 0; + if (!id) return; + let alive = true; + const poll = async () => { + try { + const t = await request('/tasks/' + encodeURIComponent(id)); + if (alive) { + setTask(t); + setConnected(true); + } + } catch (e) { + if (alive) { + if (e instanceof ApiError && e.status === 404) { + remember(ACTIVE, null); + setId(null); + setConnected(true); + setError('先前任务记录已清理,可以新建设计。'); + } else { + setConnected(false); + setError((e as Error).message); + } + } + } + }; + void poll(); + const timer = setInterval(() => void poll(), 5000); + return () => { + alive = false; + clearInterval(timer); + }; + }, [id]); + useEffect(() => { + if (!id) return; + let stopped = false, + source: EventSource | null = null, + timer: ReturnType | undefined; + const connect = () => { + source = new EventSource( + `${base}/events?task_id=${encodeURIComponent(id)}&after=${cursor.current}`, + ); + source.addEventListener('progress', (event) => { + try { + const e = JSON.parse((event as MessageEvent).data) as Progress; + cursor.current = e.seq; + setEvents((old) => [...old.filter((x) => x.seq !== e.seq), e].slice(-80)); + } catch { + /* A later snapshot restores the state. */ + } + }); + source.onerror = () => { + source?.close(); + if (!stopped) + timer = setTimeout(() => { + void request('/session') + .then(() => { + if (!stopped) connect(); + }) + .catch(() => { + if (!stopped) timer = setTimeout(connect, 5000); + }); + }, 3000); + }; + }; + connect(); + return () => { + stopped = true; + source?.close(); + if (timer) clearTimeout(timer); + }; + }, [id]); + useEffect(() => { + remember(PENDING, pending); + if (!pending) return; + let stopped = false; + const poll = async () => { + try { + const op = await request('/operations/' + encodeURIComponent(pending)); + if (stopped) return; + if (op.task_id && !idRef.current) setId(op.task_id); + if (!['queued', 'running'].includes(op.state)) { + setPending(null); + await refresh(); + if (op.result?.task_id) { + if (idRef.current === op.result.task_id || !idRef.current) { + setId(op.result.task_id); + setTask(op.result); + } + if ( + downloadFor.current === op.result.task_id && + op.result.state === 'completed' && + op.result.manufacturing_package + ) { + downloadFor.current = null; + const a = document.createElement('a'); + a.href = artifactUrl(op.result.manufacturing_package); + a.download = op.result.manufacturing_package.name; + document.body.appendChild(a); + a.click(); + a.remove(); + } + } + if ( + op.state === 'failed' || + op.state === 'outcome_unknown' || + (op.result?.error && op.result.state !== 'failed') + ) + setError( + op.result?.message || op.result?.error || '操作结果尚未确认,请查看任务状态。', + ); + } + } catch (e) { + if (!stopped) { + if (e instanceof ApiError && e.status === 404) { + remember(PENDING, null); + setPending(null); + setConnected(true); + setError('先前操作记录已清理,可以新建设计。'); + } else setError((e as Error).message); + } + } + }; + void poll(); + const timer = setInterval(() => void poll(), 1500); + return () => { + stopped = true; + clearInterval(timer); + }; + }, [pending, refresh]); + useEffect(() => { + if (!queued) return; + let stopped = false; + let timer: ReturnType | undefined; + const send = async () => { + try { + const op = await command(queued.action, queued.payload, queued.request_id); + if (stopped) return; + remember(PENDING, op.operation_id); + setPending(op.operation_id); + if (op.task_id) setId(op.task_id); + remember(OUTBOX, null); + setQueued(null); + setError(''); + } catch (e) { + if (stopped) return; + setError(`请求尚未确认,正在用同一请求身份重连:${(e as Error).message}`); + timer = setTimeout(() => void send(), 5000); + } + }; + void send(); + return () => { + stopped = true; + if (timer) clearTimeout(timer); + }; + }, [queued]); + const invoke = async (action: string, payload: Record) => { + if (sending || pending || queued) return; + const next = { action, payload, request_id: requestId() }; + remember(OUTBOX, JSON.stringify(next)); + setQueued(next); + setError(''); + }; + const upload = async (files: FileList | null) => { + if (!files) return; + setUploading(true); + setError(''); + try { + for (const f of files) { + const form = new FormData(); + form.append('file', f); + form.append( + 'kind', + /\.(png|jpe?g|dxf|step|stp)$/i.test(f.name) ? 'mechanical' : 'datasheet', + ); + const a = await request<{ upload_id: string; name: string }>('/uploads', { + method: 'POST', + body: form, + }); + setAttachments((old) => [...old, a]); + } + } catch (e) { + setError((e as Error).message); + } finally { + setUploading(false); + if (fileRef.current) fileRef.current.value = ''; + } + }; + const importCopy = async (a: Artifact) => { + if (!task) return; + setSending(true); + setError(''); + try { + const response = await fetch(artifactUrl(a), { credentials: 'same-origin' }); + if (!response.ok) throw Error('工程下载失败,请重连后重试'); + const bytes = new Uint8Array(await response.arrayBuffer()); + const digest = Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes))) + .map((v) => v.toString(16).padStart(2, '0')) + .join(''); + if (digest !== a.sha256) throw Error('工程摘要不匹配,拒绝导入'); + await onImport(bytes, task); + setOpen(false); + } catch (e) { + setError((e as Error).message); + } finally { + setSending(false); + } + }; + const show = async (a: Artifact) => { + setPreview(a); + setBom(null); + if (a.kind === 'bom' && task) + try { + setBom(await request(`/tasks/${task.task_id}/artifacts/${a.artifact_id}/table`)); + } catch (e) { + setError((e as Error).message); + } + }; + const artifacts = task?.delivery?.artifacts ?? [], + busy = sending || !!pending || !!queued; + return createPortal( +
+ + {open && ( +
+
+
+ AI PCB 设计工作台 + + {connected ? '已连接服务端 · 后台生成' : '连接后台中'} · 关闭此窗口不会取消任务 + +
+ +
+
+ +
+ {error && ( +
+ {error} +
+ )} + {!id ? ( + <> +

描述你需要的 PCB

+

需求明确并选定方案后,设计由服务器继续执行。服务器需保持联网。

+