加入ai绘制pcb功能
This commit is contained in:
@@ -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
|
||||
@@ -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。
|
||||
@@ -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.**
|
||||
|
||||
@@ -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 (
|
||||
<ProjectSyncProvider projectName={projectName} projectUid={openUid} view={syncView}>
|
||||
{manager}
|
||||
<PcbServiceDock
|
||||
onImport={async (bytes, task) => {
|
||||
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' && <SaveIndicator />}
|
||||
{aiEnabled() && <AiDock />}
|
||||
{schMounted && (
|
||||
|
||||
@@ -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<string, unknown>; 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<string, string> = {
|
||||
'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<string, string> = {
|
||||
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<void>;
|
||||
}) {
|
||||
const [open, setOpen] = useState(true),
|
||||
[tasks, setTasks] = useState<Task[]>([]),
|
||||
[id, setId] = useState<string | null>(() => stored(ACTIVE));
|
||||
const [queued, setQueued] = useState<Queued | null>(queuedCommand);
|
||||
const [task, setTask] = useState<Task | null>(null),
|
||||
[pending, setPending] = useState<string | null>(() => stored(PENDING)),
|
||||
[events, setEvents] = useState<Progress[]>([]);
|
||||
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<Artifact | null>(null),
|
||||
[bom, setBom] = useState<{ columns: string[]; rows: string[][] } | null>(null);
|
||||
const idRef = useRef(id),
|
||||
downloadFor = useRef<string | null>(null),
|
||||
cursor = useRef(0),
|
||||
fileRef = useRef<HTMLInputElement>(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<Task>('/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<typeof setTimeout> | 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<Operation>('/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<typeof setTimeout> | 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<string, unknown>) => {
|
||||
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(
|
||||
<div className="ze-app pcb-service-root">
|
||||
<button className="pcb-service-launch" onClick={() => setOpen((v) => !v)}>
|
||||
AI 自动绘板
|
||||
</button>
|
||||
{open && (
|
||||
<section className="pcb-service-window" role="dialog" aria-label="AI PCB 设计工作台">
|
||||
<header>
|
||||
<div>
|
||||
<strong>AI PCB 设计工作台</strong>
|
||||
<small>
|
||||
{connected ? '已连接服务端 · 后台生成' : '连接后台中'} · 关闭此窗口不会取消任务
|
||||
</small>
|
||||
</div>
|
||||
<button aria-label="关闭 PCB 工作台" onClick={() => setOpen(false)}>
|
||||
关闭
|
||||
</button>
|
||||
</header>
|
||||
<div className="pcb-service-body">
|
||||
<aside>
|
||||
<button
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
setId(null);
|
||||
setTask(null);
|
||||
setError('');
|
||||
setAttachments([]);
|
||||
}}
|
||||
>
|
||||
+ 新建设计
|
||||
</button>
|
||||
<button onClick={() => void refresh().catch((e) => setError(String(e)))}>
|
||||
刷新任务列表
|
||||
</button>
|
||||
{tasks.map((t) => (
|
||||
<button
|
||||
className={t.task_id === id ? 'selected' : ''}
|
||||
key={t.task_id}
|
||||
onClick={() => setId(t.task_id)}
|
||||
>
|
||||
<strong>{t.title || t.task_id}</strong>
|
||||
<small>
|
||||
{stateLabel[t.state] || t.state} · {t.revision || 'RevA'}
|
||||
</small>
|
||||
</button>
|
||||
))}
|
||||
</aside>
|
||||
<main>
|
||||
{error && (
|
||||
<div role="alert" className="pcb-service-warning">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
{!id ? (
|
||||
<>
|
||||
<h2>描述你需要的 PCB</h2>
|
||||
<p>需求明确并选定方案后,设计由服务器继续执行。服务器需保持联网。</p>
|
||||
<textarea
|
||||
aria-label="PCB 设计需求"
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
placeholder="例如:12V 转 5V、输出 1A 的电源板,40×30mm,无安装孔,两个电源接口。"
|
||||
/>
|
||||
<input
|
||||
ref={fileRef}
|
||||
type="file"
|
||||
multiple
|
||||
hidden
|
||||
onChange={(e) => void upload(e.target.files)}
|
||||
/>
|
||||
<div className="pcb-service-actions">
|
||||
<button disabled={uploading || busy} onClick={() => fileRef.current?.click()}>
|
||||
{uploading ? '上传中…' : '添加手册或图片'}
|
||||
</button>
|
||||
<button
|
||||
disabled={!text.trim() || busy || uploading || !connected}
|
||||
onClick={() =>
|
||||
void invoke('create', {
|
||||
description: text,
|
||||
selection_policy: 'propose',
|
||||
attachments: attachments.map((a) => ({ upload_id: a.upload_id })),
|
||||
})
|
||||
}
|
||||
>
|
||||
开始分析
|
||||
</button>
|
||||
</div>
|
||||
{attachments.map((a) => (
|
||||
<span className="pcb-service-attachment" key={a.upload_id}>
|
||||
{a.name}
|
||||
<button onClick={() => setAttachments((old) => old.filter((v) => v !== a))}>
|
||||
移除
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
</>
|
||||
) : !task ? (
|
||||
<p>正在读取任务…</p>
|
||||
) : (
|
||||
<>
|
||||
<h2>{task.title || 'PCB 设计任务'}</h2>
|
||||
<p>
|
||||
<strong>{stateLabel[task.state] || task.state}</strong> · {task.revision} ·{' '}
|
||||
<code>{task.task_id}</code>
|
||||
</p>
|
||||
{task.simulation && (
|
||||
<p className="pcb-service-warning">模拟环境:文件不能用于制造。</p>
|
||||
)}
|
||||
{task.state === 'needs_input' && (
|
||||
<>
|
||||
<ul>
|
||||
{task.questions?.map((q) => (
|
||||
<li key={q}>{q}</li>
|
||||
))}
|
||||
</ul>
|
||||
<textarea
|
||||
aria-label="补充需求"
|
||||
value={answer}
|
||||
onChange={(e) => setAnswer(e.target.value)}
|
||||
/>
|
||||
<button
|
||||
disabled={!answer.trim() || busy}
|
||||
onClick={() => {
|
||||
void invoke('message', { task_id: id, text: answer });
|
||||
setAnswer('');
|
||||
}}
|
||||
>
|
||||
提交补充
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{task.state === 'awaiting_selection' &&
|
||||
task.proposal?.options.map((o) => (
|
||||
<article key={o.id}>
|
||||
<h3>{o.summary}</h3>
|
||||
<p>{o.implementation}</p>
|
||||
<ul>
|
||||
{o.advantages.map((v) => (
|
||||
<li key={v}>{v}</li>
|
||||
))}
|
||||
</ul>
|
||||
<p>{o.disadvantages.join(';')}</p>
|
||||
<button
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
void invoke('select', {
|
||||
task_id: id,
|
||||
proposal_hash: task.proposal_hash,
|
||||
option_id: o.id,
|
||||
})
|
||||
}
|
||||
>
|
||||
采用这个方案
|
||||
</button>
|
||||
</article>
|
||||
))}
|
||||
{!terminal.has(task.state) && (
|
||||
<p>服务器正在执行,可稍后重新打开查看。中途异常由服务端核对恢复。</p>
|
||||
)}
|
||||
{task.state === 'failed' && (
|
||||
<p className="pcb-service-warning">
|
||||
服务未能完成本次设计,已保留执行记录。
|
||||
{task.error && (
|
||||
<details>
|
||||
<summary>查看诊断</summary>
|
||||
{task.error}
|
||||
</details>
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
{(task.state === 'draft_ready' || !!task.manufacturing_blockers?.length) && (
|
||||
<div className="pcb-service-warning">
|
||||
<strong>当前结果为草稿,不能作为检查通过的制造文件。</strong>
|
||||
<ul>
|
||||
{task.manufacturing_blockers?.map((v) => (
|
||||
<li key={v}>{v}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
{canAccept(task) && (
|
||||
<article>
|
||||
<h3>检查已通过,审核后即可下载 PCB</h3>
|
||||
<p>
|
||||
交付包已在服务端准备好,包含原生工程、Gerber、钻孔、BOM
|
||||
和检查记录。软件检查不代替实板功能验证。
|
||||
</p>
|
||||
<button
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
downloadFor.current = id;
|
||||
void invoke('accept', {
|
||||
task_id: id,
|
||||
manifest_sha256: task.delivery!.manifest_sha256,
|
||||
accepted: true,
|
||||
});
|
||||
}}
|
||||
>
|
||||
审核通过并下载 PCB
|
||||
</button>
|
||||
</article>
|
||||
)}
|
||||
{task.state === 'completed' && task.manufacturing_package && (
|
||||
<a
|
||||
className="pcb-service-download"
|
||||
href={artifactUrl(task.manufacturing_package)}
|
||||
>
|
||||
下载 PCB 交付包
|
||||
</a>
|
||||
)}
|
||||
{artifacts.length > 0 && (
|
||||
<>
|
||||
<h3>设计成果</h3>
|
||||
<div className="pcb-service-gallery">
|
||||
{artifacts
|
||||
.filter(
|
||||
(a) =>
|
||||
['pcb_preview', 'render', 'schematic'].includes(a.kind) &&
|
||||
a.mime_type.startsWith('image/'),
|
||||
)
|
||||
.map((a) => (
|
||||
<button key={a.artifact_id} onClick={() => void show(a)}>
|
||||
<img src={artifactUrl(a, true)} alt={kindNames[a.kind] || a.name} />
|
||||
{kindNames[a.kind] || a.kind}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<p>
|
||||
原生工程由后台 EDA 生成;兼容 epro
|
||||
工程可导入为新的编辑副本;原制造检查不适用于转换或修改后的副本。
|
||||
</p>
|
||||
{artifacts.find((a) => a.kind === 'editor_native') && (
|
||||
<button
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
void importCopy(artifacts.find((a) => a.kind === 'editor_native')!)
|
||||
}
|
||||
>
|
||||
导入编辑器副本(需重新校验)
|
||||
</button>
|
||||
)}
|
||||
{artifacts.map((a) => (
|
||||
<div className="pcb-service-artifact" key={a.artifact_id}>
|
||||
<span>
|
||||
{kindNames[a.kind] || a.kind} · {a.name}
|
||||
</span>
|
||||
<button onClick={() => void show(a)}>查看</button>
|
||||
<a href={artifactUrl(a)}>下载</a>
|
||||
</div>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
{events.length > 0 && (
|
||||
<details open>
|
||||
<summary>执行记录</summary>
|
||||
<ol>
|
||||
{events.slice(-16).map((e) => (
|
||||
<li key={e.seq}>
|
||||
<time>{new Date(e.created * 1000).toLocaleTimeString()}</time>{' '}
|
||||
{e.data.message || eventNames[e.kind] || e.kind}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</details>
|
||||
)}
|
||||
{!terminal.has(task.state) && (
|
||||
<button disabled={busy} onClick={() => void invoke('cancel', { task_id: id })}>
|
||||
取消此任务
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{preview && (
|
||||
<section className="pcb-service-preview">
|
||||
<button onClick={() => setPreview(null)}>关闭预览</button>
|
||||
<h3>{kindNames[preview.kind] || preview.name}</h3>
|
||||
{bom ? (
|
||||
<div className="pcb-service-table">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
{bom.columns.map((v, i) => (
|
||||
<th key={i}>{v}</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{bom.rows.map((r, i) => (
|
||||
<tr key={i}>
|
||||
{r.map((v, j) => (
|
||||
<td key={j}>{v}</td>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
) : preview.mime_type.startsWith('image/') ? (
|
||||
<img src={artifactUrl(preview, true)} alt={preview.name} />
|
||||
) : preview.mime_type === 'application/pdf' ? (
|
||||
<iframe title={preview.name} src={artifactUrl(preview, true)} />
|
||||
) : (
|
||||
<p>该格式请下载后使用对应 EDA 软件打开。</p>
|
||||
)}
|
||||
<a href={artifactUrl(preview)}>下载文件</a>
|
||||
</section>
|
||||
)}
|
||||
</main>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
</div>,
|
||||
document.body,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
/** Task API: execution belongs to the server; this client only observes it. */
|
||||
export interface Artifact {
|
||||
artifact_id: string;
|
||||
kind: string;
|
||||
name: string;
|
||||
sha256: string;
|
||||
mime_type: string;
|
||||
download_url: string;
|
||||
simulation: boolean;
|
||||
}
|
||||
export interface Task {
|
||||
task_id: string;
|
||||
state: string;
|
||||
title?: string;
|
||||
revision?: string;
|
||||
questions?: string[];
|
||||
proposal_hash?: string;
|
||||
proposal?: {
|
||||
options: {
|
||||
id: string;
|
||||
summary: string;
|
||||
implementation: string;
|
||||
advantages: string[];
|
||||
disadvantages: string[];
|
||||
}[];
|
||||
};
|
||||
error?: string;
|
||||
manufacturing_blockers?: string[];
|
||||
findings?: string[];
|
||||
download_ready?: boolean;
|
||||
delivery?: { manifest_sha256: string; artifacts: Artifact[] };
|
||||
manufacturing_package?: Artifact;
|
||||
simulation?: boolean;
|
||||
}
|
||||
export interface Operation {
|
||||
operation_id: string;
|
||||
state: string;
|
||||
task_id?: string;
|
||||
result?: Task & { message?: string };
|
||||
}
|
||||
export interface Progress {
|
||||
seq: number;
|
||||
task_id?: string;
|
||||
kind: string;
|
||||
created: number;
|
||||
data: { message?: string; role?: string };
|
||||
}
|
||||
export const base = `${import.meta.env.BASE_URL || '/'}pcb-api/v1`;
|
||||
export const requestId = (): string =>
|
||||
globalThis.crypto?.randomUUID?.() ??
|
||||
`request-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
||||
export class ApiError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly status: number,
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'ApiError';
|
||||
}
|
||||
}
|
||||
export async function request<T>(path: string, init: RequestInit = {}, retry = true): Promise<T> {
|
||||
const r = await fetch(base + path, { ...init, credentials: 'same-origin' });
|
||||
if (r.status === 401 && retry) {
|
||||
await request('/session', {}, false);
|
||||
return request(path, init, false);
|
||||
}
|
||||
const data = await r
|
||||
.json()
|
||||
.catch(() => ({ message: 'PCB 服务返回了无法识别的响应,请检查服务地址。' }));
|
||||
if (!r.ok)
|
||||
throw new ApiError(data.message || data.detail || `PCB 服务请求失败 (${r.status})`, r.status);
|
||||
return data as T;
|
||||
}
|
||||
export function artifactUrl(a: Artifact, preview = false) {
|
||||
if (!/^\/api\/v1\/tasks\/[a-zA-Z0-9_-]+\/artifacts\/[a-zA-Z0-9_-]+$/.test(a.download_url))
|
||||
throw new Error('成果地址不合法');
|
||||
return base + a.download_url.slice('/api/v1'.length) + (preview ? '?preview=true' : '');
|
||||
}
|
||||
export function command(action: string, payload: Record<string, unknown>, id = requestId()) {
|
||||
return request<Operation>('/commands', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ request_id: id, action, payload }),
|
||||
});
|
||||
}
|
||||
export function canAccept(task: Task) {
|
||||
return (
|
||||
task.state === 'delivery_ready' &&
|
||||
task.download_ready === true &&
|
||||
!task.manufacturing_blockers?.length &&
|
||||
!!task.delivery?.manifest_sha256
|
||||
);
|
||||
}
|
||||
export const terminal = new Set([
|
||||
'delivery_ready',
|
||||
'draft_ready',
|
||||
'completed',
|
||||
'failed',
|
||||
'cancelled',
|
||||
'needs_input',
|
||||
'awaiting_selection',
|
||||
]);
|
||||
export const stateLabel: Record<string, string> = {
|
||||
assessing: '整理需求',
|
||||
needs_input: '等待补充需求',
|
||||
awaiting_selection: '等待选择方案',
|
||||
designing: '正在设计与检查',
|
||||
exporting: '正在打包成果',
|
||||
needs_operator: '服务器自动恢复中',
|
||||
draft_ready: '草稿:检查未通过',
|
||||
delivery_ready: '检查通过,等待审核',
|
||||
completed: '已完成,可下载',
|
||||
failed: '本次设计未能完成',
|
||||
cancelled: '已取消',
|
||||
cancel_requested: '正在取消',
|
||||
};
|
||||
@@ -0,0 +1,127 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
/** Import a separate, explicitly unverified editing copy. Never replace the frozen source. */
|
||||
import { unzipSync } from 'fflate';
|
||||
import { PCB_IO_EASYEDAPRO } from '@ziroeda/pcbnew/pcb_io/easyedapro/pcb_io_easyedapro.js';
|
||||
import { FormatBoard } from '@ziroeda/pcbnew/pcb_io/kicad_sexpr/pcb_io_kicad_sexpr.js';
|
||||
import { EMBEDDED_FILES } from '@ziroeda/common/embedded_files.js';
|
||||
import { PGM_BASE, SETTINGS_MANAGER, PgmOrNull, SetPgm } from '@ziroeda/common/pgm_base.js';
|
||||
import { MEMORY_FILESYSTEM, wxMountFileSystem } from '@ziroeda/wx/filefn.js';
|
||||
import {
|
||||
LIBRARY_TABLE,
|
||||
LIBRARY_TABLE_SCOPE,
|
||||
LIBRARY_TABLE_TYPE,
|
||||
} from '@ziroeda/common/libraries/library_table.js';
|
||||
import { SCHEMATIC, SCH_CLEANUP_FLAGS } from '@ziroeda/eeschema/schematic.js';
|
||||
import { SCH_EDIT_FRAME, type SCH_EDIT_FRAME_HOOKS } from '@ziroeda/eeschema/sch_edit_frame.js';
|
||||
import { SCH_IO_EASYEDAPRO } from '@ziroeda/eeschema/sch_io/easyedapro/sch_io_easyedapro.js';
|
||||
import { SCH_IO_KICAD_SEXPR } from '@ziroeda/eeschema/sch_io/kicad_sexpr/sch_io_kicad_sexpr.js';
|
||||
import { SCH_SCREENS } from '@ziroeda/eeschema/sch_screen.js';
|
||||
import { projectJson } from '../home/new_project.js';
|
||||
import type { StoredFile } from '../home/projectStore.js';
|
||||
|
||||
export async function convertProject(
|
||||
bytes: Uint8Array,
|
||||
name: string,
|
||||
source: { task_id: string; manifest_sha256: string },
|
||||
) {
|
||||
const zip = unzipSync(bytes);
|
||||
if (!zip['project.json'])
|
||||
throw Error('当前文件不是可导入的旧版 epro 工程;epro2 不能通过改名转换。');
|
||||
if (
|
||||
Object.keys(zip).length > 5000 ||
|
||||
Object.values(zip).reduce((n, v) => n + v.length, 0) > 256 * 1024 * 1024
|
||||
)
|
||||
throw Error('导入工程超过大小限制');
|
||||
const metadata = JSON.parse(new TextDecoder().decode(zip['project.json']));
|
||||
if (
|
||||
Object.keys(metadata.pcbs || {}).length !== 1 ||
|
||||
Object.keys(metadata.schematics || {}).length !== 1
|
||||
)
|
||||
throw Error('目前只支持单 PCB、单原理图工程导入');
|
||||
await EMBEDDED_FILES.InitCodec();
|
||||
const io = new PCB_IO_EASYEDAPRO();
|
||||
io.SetFileReader(() => bytes);
|
||||
const board = io.LoadBoard(`${name}.epro`, null, null);
|
||||
if (!board.Footprints().length) throw Error('导入结果没有器件,已拒绝创建空白项目');
|
||||
const enc = new TextEncoder(),
|
||||
files: StoredFile[] = [],
|
||||
put = (n: string, t: string) => files.push({ name: `${name}/${n}`, bytes: enc.encode(t) });
|
||||
put(`${name}.kicad_pcb`, FormatBoard(board, 'pcbnew'));
|
||||
put(`${name}.kicad_pro`, projectJson(name, null));
|
||||
const previous = PgmOrNull(),
|
||||
program = new PGM_BASE(null, new SETTINGS_MANAGER()),
|
||||
fs = new MEMORY_FILESYSTEM(),
|
||||
folder = `/tmp/${name}`;
|
||||
const unmount = wxMountFileSystem(folder, fs);
|
||||
SetPgm(program);
|
||||
try {
|
||||
fs.Write(`${name}.kicad_pro`, enc.encode(projectJson(name, null)));
|
||||
program.GetSettingsManager().LoadProject(`${folder}/${name}.kicad_pro`, null);
|
||||
const table = LIBRARY_TABLE.Empty(LIBRARY_TABLE_SCOPE.PROJECT, LIBRARY_TABLE_TYPE.SYMBOL);
|
||||
table.SetPath(`${folder}/sym-lib-table`);
|
||||
program
|
||||
.GetLibraryManager()
|
||||
.SetTable(LIBRARY_TABLE_TYPE.SYMBOL, LIBRARY_TABLE_SCOPE.PROJECT, table);
|
||||
const frame = new SCH_EDIT_FRAME({
|
||||
crossProbingSettings: () => ({}) as ReturnType<SCH_EDIT_FRAME_HOOKS['crossProbingSettings']>,
|
||||
saveProject: () => true,
|
||||
getNetlist: () => null,
|
||||
});
|
||||
const schematic = new SCHEMATIC(frame.Prj()),
|
||||
parser = new SCH_IO_EASYEDAPRO();
|
||||
parser.SetFileReader(() => bytes);
|
||||
const sheet = parser.LoadSchematicFile(`${folder}/${name}.epro`, schematic, null, null);
|
||||
if (!sheet) throw Error('原理图导入失败');
|
||||
schematic.SetTopLevelSheets([sheet]);
|
||||
frame.SetSchematic(schematic);
|
||||
frame.SetScreen(schematic.RootScreen());
|
||||
sheet.SetFileName(`${name}.kicad_sch`);
|
||||
frame.GetScreen()!.SetFileName(`${folder}/${name}.kicad_sch`);
|
||||
frame.RecalculateConnections(null, SCH_CLEANUP_FLAGS.GLOBAL_CLEANUP);
|
||||
frame.SetSheetNumberAndCount();
|
||||
const screens = new SCH_SCREENS(schematic.Root()),
|
||||
writer = new SCH_IO_KICAD_SEXPR('eeschema');
|
||||
for (let i = 0; i < screens.GetCount(); i++) {
|
||||
const screen = screens.GetScreen(i)!;
|
||||
const filename = screen.GetFileName().split('/').pop()!;
|
||||
if (filename) put(filename, writer.SaveSchematicFile(screens.GetSheet(i)!, schematic));
|
||||
}
|
||||
const collect = (dir: string) => {
|
||||
for (const entry of fs.List(dir) || []) {
|
||||
const path = dir ? `${dir}/${entry.name}` : entry.name;
|
||||
if (entry.isDir) collect(path);
|
||||
else if (path === 'sym-lib-table' || path.endsWith('.kicad_sym')) {
|
||||
const content = fs.Read(path);
|
||||
if (content) files.push({ name: `${name}/${path}`, bytes: content });
|
||||
}
|
||||
}
|
||||
};
|
||||
collect('');
|
||||
} finally {
|
||||
SetPgm(previous);
|
||||
unmount();
|
||||
}
|
||||
put(
|
||||
'AI-SOURCE.json',
|
||||
JSON.stringify(
|
||||
{
|
||||
...source,
|
||||
editing_copy: true,
|
||||
validation_state: 'unverified',
|
||||
note: 'Converted editing copy. Original manufacturing checks apply only to the frozen original revision.',
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
put(
|
||||
'DESIGN.md',
|
||||
'# AI 生成工程的编辑副本\n\n该副本经过格式转换,修改或转换后的工程须重新进行 ERC/DRC 及制造检查。原生成版本的检查结论不适用于这个副本。\n',
|
||||
);
|
||||
return {
|
||||
files,
|
||||
components: board.Footprints().length,
|
||||
tracks: board.Tracks().length,
|
||||
zones: board.Zones().length,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
/* Application chrome uses the shared shell tokens. Dimensions describe this task panel. */
|
||||
.pcb-service-root {
|
||||
font: var(--ui-font-size) var(--ui-font-family);
|
||||
color: var(--chrome-fg);
|
||||
}
|
||||
.pcb-service-launch {
|
||||
position: fixed;
|
||||
right: 18px;
|
||||
bottom: 34px;
|
||||
z-index: 1200;
|
||||
padding: 9px 16px;
|
||||
background: var(--chrome-bg);
|
||||
color: inherit;
|
||||
border: 1px solid var(--chrome-border);
|
||||
border-radius: 5px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.pcb-service-window {
|
||||
position: fixed;
|
||||
inset: 4vh 3vw;
|
||||
z-index: 1250;
|
||||
background: var(--chrome-bg);
|
||||
color: inherit;
|
||||
border: 1px solid var(--chrome-border);
|
||||
box-shadow: 0 12px 80px #0008;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border-radius: 7px;
|
||||
overflow: hidden;
|
||||
font: inherit;
|
||||
}
|
||||
.pcb-service-window header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 14px 20px;
|
||||
border-bottom: 1px solid var(--chrome-border);
|
||||
}
|
||||
.pcb-service-window small {
|
||||
display: block;
|
||||
opacity: 0.75;
|
||||
margin-top: 5px;
|
||||
}
|
||||
.pcb-service-body {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
.pcb-service-body aside {
|
||||
width: 245px;
|
||||
flex-shrink: 0;
|
||||
overflow: auto;
|
||||
padding: 12px;
|
||||
border-right: 1px solid var(--chrome-border);
|
||||
}
|
||||
.pcb-service-body aside button {
|
||||
display: block;
|
||||
width: 100%;
|
||||
text-align: left;
|
||||
margin-bottom: 8px;
|
||||
padding: 10px;
|
||||
}
|
||||
.pcb-service-body aside strong {
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
font-weight: normal;
|
||||
}
|
||||
.pcb-service-body aside .selected {
|
||||
outline: 2px solid var(--chrome-active);
|
||||
}
|
||||
.pcb-service-body main {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
padding: 18px 26px;
|
||||
overflow: auto;
|
||||
}
|
||||
.pcb-service-window button,
|
||||
.pcb-service-window a {
|
||||
font: inherit;
|
||||
}
|
||||
.pcb-service-window button {
|
||||
padding: 7px 12px;
|
||||
cursor: pointer;
|
||||
background: var(--chrome-bg);
|
||||
color: inherit;
|
||||
border: 1px solid var(--chrome-border);
|
||||
border-radius: 4px;
|
||||
}
|
||||
.pcb-service-window button:disabled {
|
||||
opacity: 0.45;
|
||||
cursor: default;
|
||||
}
|
||||
.pcb-service-window a {
|
||||
color: var(--chrome-active);
|
||||
}
|
||||
.pcb-service-window textarea {
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
min-height: 130px;
|
||||
font: inherit;
|
||||
padding: 12px;
|
||||
resize: vertical;
|
||||
background: var(--chrome-bg);
|
||||
color: inherit;
|
||||
border: 1px solid var(--chrome-border);
|
||||
}
|
||||
.pcb-service-window article {
|
||||
border: 1px solid var(--chrome-border);
|
||||
border-radius: 5px;
|
||||
padding: 14px;
|
||||
margin: 14px 0;
|
||||
}
|
||||
.pcb-service-window article h3 {
|
||||
margin-top: 0;
|
||||
}
|
||||
.pcb-service-window p {
|
||||
line-height: 1.65;
|
||||
}
|
||||
.pcb-service-actions {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
margin: 12px 0;
|
||||
}
|
||||
.pcb-service-warning {
|
||||
padding: 12px;
|
||||
border: 1px solid var(--chrome-border);
|
||||
border-left: 4px solid #c39748;
|
||||
margin: 10px 0;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
.pcb-service-attachment {
|
||||
display: inline-block;
|
||||
margin: 5px;
|
||||
}
|
||||
.pcb-service-artifact {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
border-bottom: 1px solid var(--chrome-border);
|
||||
padding: 10px 0;
|
||||
}
|
||||
.pcb-service-artifact span {
|
||||
flex: 1;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.pcb-service-gallery {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(190px, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
.pcb-service-gallery img {
|
||||
width: 100%;
|
||||
height: 160px;
|
||||
object-fit: contain;
|
||||
display: block;
|
||||
background: #182125;
|
||||
}
|
||||
.pcb-service-preview {
|
||||
position: fixed;
|
||||
inset: 8vh 7vw;
|
||||
padding: 20px;
|
||||
background: var(--chrome-bg);
|
||||
border: 1px solid var(--chrome-border);
|
||||
box-shadow: 0 10px 50px #0009;
|
||||
z-index: 1300;
|
||||
overflow: auto;
|
||||
}
|
||||
.pcb-service-preview > img {
|
||||
display: block;
|
||||
max-height: 65vh;
|
||||
max-width: 100%;
|
||||
object-fit: contain;
|
||||
margin: 15px auto;
|
||||
}
|
||||
.pcb-service-preview iframe {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 60vh;
|
||||
}
|
||||
.pcb-service-table {
|
||||
overflow: auto;
|
||||
}
|
||||
.pcb-service-table td,
|
||||
.pcb-service-table th {
|
||||
padding: 6px;
|
||||
border: 1px solid var(--chrome-border);
|
||||
}
|
||||
.pcb-service-window time {
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.pcb-service-download {
|
||||
display: inline-block;
|
||||
margin: 10px;
|
||||
padding: 12px;
|
||||
border: 1px solid var(--chrome-border);
|
||||
}
|
||||
@media (max-width: 850px) {
|
||||
.pcb-service-window {
|
||||
inset: 1vh 1vw;
|
||||
}
|
||||
.pcb-service-body aside {
|
||||
width: 165px;
|
||||
}
|
||||
.pcb-service-body main {
|
||||
padding: 12px;
|
||||
}
|
||||
}
|
||||
+31
-1
@@ -66,6 +66,18 @@ const uploadMaps = telemetryEnabled && !!(SENTRY_ORG && SENTRY_PROJECT && SENTRY
|
||||
// Assets, the router and the installed PWA share this base. VITE_BASE can
|
||||
// override it when building for another deployment path.
|
||||
const APP_BASE = process.env.VITE_BASE ?? '/pcb/';
|
||||
function pcbProxy(): import('vite').ProxyOptions {
|
||||
return {
|
||||
target: process.env.PCB_API_TARGET || 'http://192.168.1.200:8000',
|
||||
changeOrigin: true,
|
||||
rewrite: (path: string) => '/api' + path.slice(`${APP_BASE}pcb-api`.length),
|
||||
configure: (proxy) => {
|
||||
proxy.on('proxyReq', (request) =>
|
||||
request.setHeader('Origin', process.env.PCB_API_ORIGIN || 'http://127.0.0.1:5173'),
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export default defineConfig({
|
||||
base: APP_BASE,
|
||||
@@ -106,6 +118,16 @@ export default defineConfig({
|
||||
*/
|
||||
worker: { format: 'es' },
|
||||
plugins: [
|
||||
{
|
||||
name: 'pcb-service-deployment',
|
||||
generateBundle() {
|
||||
this.emitFile({
|
||||
type: 'asset',
|
||||
fileName: 'pcb-service-config.json',
|
||||
source: JSON.stringify({ base: APP_BASE }),
|
||||
});
|
||||
},
|
||||
},
|
||||
react(),
|
||||
/**
|
||||
* The app is installed, not fetched.
|
||||
@@ -178,6 +200,7 @@ export default defineConfig({
|
||||
// vercel.json's rewrite already says. Serving it from the precache is
|
||||
// what makes a cold-start with no network still paint the launcher.
|
||||
navigateFallback: 'index.html',
|
||||
navigateFallbackDenylist: [/\/pcb-api\//],
|
||||
runtimeCaching: [
|
||||
{
|
||||
// WASM kernels are hashed like every other asset, so cache-first is
|
||||
@@ -219,7 +242,14 @@ export default defineConfig({
|
||||
]
|
||||
: []),
|
||||
],
|
||||
server: { port: 5173 },
|
||||
server: {
|
||||
host: '127.0.0.1',
|
||||
port: 5180,
|
||||
strictPort: true,
|
||||
proxy: {
|
||||
[`${APP_BASE}pcb-api`]: pcbProxy(),
|
||||
},
|
||||
},
|
||||
// zstd-wasm locates zstd.wasm next to its own module via import.meta.url;
|
||||
// pre-bundling would move the JS into .vite/deps without the wasm, so serve
|
||||
// the package as-is (production builds handle new URL(..., import.meta.url)
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Optional backend capability: add an immutable legacy epro artifact for Ziro.
|
||||
Run on the PCB server: python3 integration/install-editor-export.py ~/auto_pcb
|
||||
No credentials are read or copied. Existing frozen deliveries are unchanged.
|
||||
"""
|
||||
import ast,os,pathlib,shutil,sqlite3,sys,time
|
||||
root=pathlib.Path(sys.argv[1]).expanduser().resolve();path=root/'deliver_pack/design_runtime/eda.py'
|
||||
source=path.read_text();line=' (\'editor_native\',\'pcb\',\'eda.sys_FileManager.getProjectFile("design-editor",undefined,"epro")\',\'native/design-editor.epro\'),\n'
|
||||
if line in source:print('Editor export already installed');raise SystemExit(0)
|
||||
dbpath=root/'runtime/web-v3/api.sqlite3'
|
||||
if dbpath.exists():
|
||||
db=sqlite3.connect('file:'+str(dbpath)+'?mode=ro',uri=True)
|
||||
if db.execute("select 1 from operations where state in ('queued','running')").fetchone():raise SystemExit('An operation is active; retry after it finishes.')
|
||||
db.close()
|
||||
anchor=' (\'schematic\',\'schematic\',\'eda.sch_ManufactureData.getPngFile("schematic",{width:1800})\',\'schematic/schematic.png\'),\n'
|
||||
if source.count(anchor)!=1:raise SystemExit('Backend version differs: expected export entry not found. No change made.')
|
||||
updated=source.replace(anchor,line+anchor);ast.parse(updated)
|
||||
backup=root/'runtime/repair-backups'/time.strftime('%Y%m%d-%H%M%S-ziro-editor');backup.mkdir(parents=True);shutil.copy2(path,backup/'eda.py')
|
||||
temp=path.with_name(path.name+'.ziro-tmp');temp.write_text(updated);os.replace(temp,path)
|
||||
print('Installed. New tasks export native/design-editor.epro; backup:',backup)
|
||||
@@ -0,0 +1,11 @@
|
||||
# Inside an existing HTTPS server block; preserve /pcb/ paths.
|
||||
location = /pcb { return 302 /pcb/; }
|
||||
location /pcb/ {
|
||||
proxy_pass http://127.0.0.1:5180;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header Origin $http_origin;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_buffering off;
|
||||
proxy_read_timeout 3600s;
|
||||
}
|
||||
+2
-1
@@ -17,7 +17,8 @@
|
||||
"demos:bundle": "node --env-file=.env tools/demos/bundle.mjs",
|
||||
"libraries:split": "node --env-file=.env tools/libraries/split_upload.mjs",
|
||||
"libraries:reindex": "node --env-file=.env tools/libraries/reindex.mjs",
|
||||
"libraries:bundle": "node --env-file=.env tools/libraries/bundle.mjs"
|
||||
"libraries:bundle": "node --env-file=.env tools/libraries/bundle.mjs",
|
||||
"pcb:start": "bash start.sh"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@biomejs/biome": "^2.5.3",
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { afterEach, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
artifactUrl,
|
||||
canAccept,
|
||||
request,
|
||||
type Artifact,
|
||||
} from '@ziroeda/designer/src/pcb-service/client.js';
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
it('requires a packaged, current, unblocked delivery before acceptance', () => {
|
||||
const t = {
|
||||
task_id: 'pcb-test',
|
||||
state: 'delivery_ready',
|
||||
download_ready: true,
|
||||
delivery: { manifest_sha256: 'digest', artifacts: [] },
|
||||
};
|
||||
expect(canAccept(t)).toBe(true);
|
||||
expect(canAccept({ ...t, download_ready: false })).toBe(false);
|
||||
expect(canAccept({ ...t, state: 'draft_ready' })).toBe(false);
|
||||
expect(canAccept({ ...t, manufacturing_blockers: ['DRC'] })).toBe(false);
|
||||
});
|
||||
it('does not allow artifact URLs to point at another origin or non-artifact route', () => {
|
||||
const a = { download_url: '/api/v1/tasks/pcb-test/artifacts/art-test' } as Artifact;
|
||||
expect(artifactUrl(a, true)).toBe('/pcb-api/v1/tasks/pcb-test/artifacts/art-test?preview=true');
|
||||
for (const url of [
|
||||
'https://example.com/key',
|
||||
'/api/v1/session',
|
||||
'/api/v1/tasks/../artifacts/a',
|
||||
]) {
|
||||
expect(() => artifactUrl({ ...a, download_url: url })).toThrow();
|
||||
}
|
||||
});
|
||||
it('renews the API session once after a server restart and repeats the same request', async () => {
|
||||
const fetch = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(new Response('{}', { status: 401 }))
|
||||
.mockResolvedValueOnce(new Response('{}'))
|
||||
.mockResolvedValueOnce(new Response(JSON.stringify({ items: [] })));
|
||||
vi.stubGlobal('fetch', fetch);
|
||||
expect(await request('/tasks')).toEqual({ items: [] });
|
||||
expect(fetch.mock.calls.map((c) => c[0])).toEqual([
|
||||
'/pcb-api/v1/tasks',
|
||||
'/pcb-api/v1/session',
|
||||
'/pcb-api/v1/tasks',
|
||||
]);
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { expect, it } from 'vitest';
|
||||
import { convertProject } from '@ziroeda/designer/src/pcb-service/import-project.js';
|
||||
it('rejects malformed archives without creating a project', async () => {
|
||||
await expect(
|
||||
convertProject(new Uint8Array([1, 2, 3]), 'bad', { task_id: 'x', manifest_sha256: 'x' }),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
it.runIf(!!process.env.PCB_IMPORT_FIXTURE)(
|
||||
'imports a real 18-part service export without losing footprints or copper objects',
|
||||
async () => {
|
||||
const r = await convertProject(
|
||||
new Uint8Array(readFileSync(process.env.PCB_IMPORT_FIXTURE!)),
|
||||
'service-fixture',
|
||||
{ task_id: 'fixture', manifest_sha256: 'digest' },
|
||||
);
|
||||
expect(r.components).toBe(18);
|
||||
expect(r.tracks).toBe(138);
|
||||
expect(r.zones).toBe(2);
|
||||
expect(r.files.some((f) => f.name.endsWith('.kicad_sch'))).toBe(true);
|
||||
expect(r.files.some((f) => f.name.endsWith('.kicad_pcb'))).toBe(true);
|
||||
expect(r.files.some((f) => f.name.endsWith('.kicad_sym'))).toBe(true);
|
||||
const source = JSON.parse(
|
||||
new TextDecoder().decode(r.files.find((f) => f.name.endsWith('AI-SOURCE.json'))!.bytes),
|
||||
);
|
||||
expect(source.validation_state).toBe('unverified');
|
||||
},
|
||||
60000,
|
||||
);
|
||||
@@ -0,0 +1,30 @@
|
||||
import {mkdtempSync,mkdirSync,writeFileSync,copyFileSync,rmSync} from "node:fs";
|
||||
import {tmpdir} from "node:os";
|
||||
import {join,resolve} from "node:path";
|
||||
import {spawn} from "node:child_process";
|
||||
import {createServer} from "node:http";
|
||||
import {expect,it} from "vitest";
|
||||
|
||||
it("serves /pcb/ assets and SPA routes, proxies the nested API and rejects foreign origins",async()=>{
|
||||
const dir=mkdtempSync(join(tmpdir(),"vibemake-proxy-"));
|
||||
const scripts=join(dir,"scripts"),dist=join(dir,"designer/dist");mkdirSync(scripts,{recursive:true});mkdirSync(join(dist,"assets"),{recursive:true});
|
||||
copyFileSync(resolve(__dirname,"../../../scripts/serve.mjs"),join(scripts,"serve.mjs"));
|
||||
writeFileSync(join(dist,"index.html"),"<h1>VibeMake fixture</h1>");writeFileSync(join(dist,"assets/app.js"),"window.fixture=true");writeFileSync(join(dist,"pcb-service-config.json"),JSON.stringify({base:"/pcb/"}));
|
||||
let forwarded=0;
|
||||
const upstream=createServer((req,res)=>{forwarded++;res.setHeader("Content-Type","application/json");res.end(JSON.stringify({path:req.url,origin:req.headers.origin}))});
|
||||
await new Promise<void>(r=>upstream.listen(0,"127.0.0.1",r));const upstreamPort=(upstream.address() as {port:number}).port;
|
||||
// Reserve an ephemeral port briefly; no fixed developer-machine ports are consumed.
|
||||
const reservation=createServer();await new Promise<void>(r=>reservation.listen(0,"127.0.0.1",r));const port=(reservation.address() as {port:number}).port;await new Promise<void>(r=>reservation.close(()=>r()));
|
||||
const child=spawn(process.execPath,[join(scripts,"serve.mjs")],{env:{...process.env,HOST:"127.0.0.1",PORT:String(port),PCB_API_TARGET:`http://127.0.0.1:${upstreamPort}`,PUBLIC_ORIGIN:""},stdio:["ignore","pipe","pipe"]});
|
||||
try{
|
||||
await new Promise<void>((resolve,reject)=>{child.stdout.on("data",()=>resolve());child.on("exit",code=>reject(Error(`Server exited ${code}`)));child.stderr.on("data",b=>reject(Error(String(b))))});
|
||||
const base=`http://127.0.0.1:${port}`;
|
||||
const redirect=await fetch(base,{redirect:"manual"});expect(redirect.status).toBe(302);expect(redirect.headers.get("location")).toBe("/pcb/");
|
||||
expect(await (await fetch(base+"/pcb/p/local/pcb")).text()).toContain("VibeMake fixture");
|
||||
expect(await (await fetch(base+"/pcb/assets/app.js")).text()).toBe("window.fixture=true");
|
||||
const response=await fetch(base+"/pcb/pcb-api/v1/health");expect(await response.json()).toEqual({path:"/api/v1/health",origin:"http://127.0.0.1:5173"});expect(response.headers.get("cache-control")).toBe("no-store");
|
||||
const before=forwarded;const bad=await fetch(base+"/pcb/pcb-api/v1/commands",{method:"POST",headers:{Origin:"http://foreign.invalid"},body:"{}"});expect(bad.status).toBe(403);expect(forwarded).toBe(before);
|
||||
const good=await fetch(base+"/pcb/pcb-api/v1/commands",{method:"POST",headers:{Origin:base},body:"{}"});expect(good.status).toBe(200);
|
||||
expect((await fetch(base+"/pcb-api/v1/health")).status).toBe(404);
|
||||
}finally{child.kill();await new Promise<void>(r=>{upstream.closeAllConnections();upstream.close(()=>r())});rmSync(dir,{recursive:true,force:true})}
|
||||
},20000);
|
||||
@@ -0,0 +1,74 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { afterEach, expect, it, vi } from 'vitest';
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { PcbServiceDock } from '@ziroeda/designer/src/pcb-service/PcbServiceDock.js';
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
localStorage.clear();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
it('replays a submit interrupted before HTTP 202 using the same request identity', async () => {
|
||||
const bodies: Record<string, unknown>[] = [];
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(async (path: string, init?: RequestInit) => {
|
||||
if (path.endsWith('/commands')) {
|
||||
bodies.push(JSON.parse(String(init?.body)));
|
||||
if (bodies.length === 1) return await new Promise<Response>(() => {});
|
||||
return new Response(JSON.stringify({ operation_id: 'op-test', state: 'queued' }));
|
||||
}
|
||||
if (path.includes('/operations/'))
|
||||
return new Response(JSON.stringify({ operation_id: 'op-test', state: 'queued' }));
|
||||
return new Response(JSON.stringify(path.endsWith('/tasks') ? { items: [] } : {}));
|
||||
}),
|
||||
);
|
||||
const first = render(<PcbServiceDock onImport={async () => {}} />);
|
||||
await waitFor(() =>
|
||||
expect((screen.getByRole('button', { name: '开始分析' }) as HTMLButtonElement).disabled).toBe(
|
||||
true,
|
||||
),
|
||||
);
|
||||
fireEvent.change(screen.getByLabelText('PCB 设计需求'), { target: { value: '测试电源板' } });
|
||||
await waitFor(() =>
|
||||
expect((screen.getByRole('button', { name: '开始分析' }) as HTMLButtonElement).disabled).toBe(
|
||||
false,
|
||||
),
|
||||
);
|
||||
fireEvent.click(screen.getByRole('button', { name: '开始分析' }));
|
||||
await waitFor(() => expect(bodies).toHaveLength(1));
|
||||
first.unmount();
|
||||
render(<PcbServiceDock onImport={async () => {}} />);
|
||||
await waitFor(() => expect(bodies).toHaveLength(2));
|
||||
expect(bodies[0]?.request_id).toBeTruthy();
|
||||
expect(bodies[1]).toEqual(bodies[0]);
|
||||
});
|
||||
|
||||
it('forgets deleted task and operation references without replaying commands', async () => {
|
||||
localStorage.setItem('vibemake.pcb-service.active', 'pcb-removed');
|
||||
localStorage.setItem('vibemake.pcb-service.operation', 'op-removed');
|
||||
vi.stubGlobal(
|
||||
'EventSource',
|
||||
class {
|
||||
addEventListener() {}
|
||||
close() {}
|
||||
},
|
||||
);
|
||||
const fetchMock = vi.fn(async (path: string) => {
|
||||
if (path.includes('/tasks/') || path.includes('/operations/'))
|
||||
return new Response(JSON.stringify({ message: 'Not found' }), { status: 404 });
|
||||
return new Response(JSON.stringify(path.endsWith('/tasks') ? { items: [] } : {}));
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
render(<PcbServiceDock onImport={async () => {}} />);
|
||||
await waitFor(() => {
|
||||
expect(localStorage.getItem('vibemake.pcb-service.active')).toBeNull();
|
||||
expect(localStorage.getItem('vibemake.pcb-service.operation')).toBeNull();
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText('PCB 设计需求'), { target: { value: '新的电源板' } });
|
||||
await waitFor(() =>
|
||||
expect((screen.getByRole('button', { name: '开始分析' }) as HTMLButtonElement).disabled).toBe(
|
||||
false,
|
||||
),
|
||||
);
|
||||
expect(fetchMock.mock.calls.some(([path]) => path.endsWith('/commands'))).toBe(false);
|
||||
});
|
||||
@@ -0,0 +1,138 @@
|
||||
/** Production static server + fixed-upstream task proxy. No provider credentials in the browser. */
|
||||
import http from 'node:http';
|
||||
import https from 'node:https';
|
||||
import { readFile, stat } from 'node:fs/promises';
|
||||
import { createReadStream } from 'node:fs';
|
||||
import { resolve, extname, sep } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { pipeline } from 'node:stream';
|
||||
const root = resolve(fileURLToPath(new URL('../designer/dist/', import.meta.url)));
|
||||
const deployment = JSON.parse(await readFile(resolve(root, 'pcb-service-config.json'), 'utf8'));
|
||||
const siteBase = deployment.base;
|
||||
if (typeof siteBase !== 'string' || !siteBase.startsWith('/') || !siteBase.endsWith('/'))
|
||||
throw Error('Build base must be an absolute URL path ending in /');
|
||||
const apiPrefix = `${siteBase}pcb-api/`;
|
||||
const target = new URL(process.env.PCB_API_TARGET || 'http://192.168.1.200:8000');
|
||||
if (!['http:', 'https:'].includes(target.protocol) || target.username || target.password)
|
||||
throw Error('PCB_API_TARGET must be an HTTP(S) address without embedded credentials');
|
||||
const host = process.env.HOST || '127.0.0.1',
|
||||
port = Number(process.env.PORT || 5180);
|
||||
const mime = {
|
||||
'.html': 'text/html; charset=utf-8',
|
||||
'.js': 'text/javascript; charset=utf-8',
|
||||
'.css': 'text/css; charset=utf-8',
|
||||
'.json': 'application/json',
|
||||
'.svg': 'image/svg+xml',
|
||||
'.png': 'image/png',
|
||||
'.jpg': 'image/jpeg',
|
||||
'.wasm': 'application/wasm',
|
||||
'.webmanifest': 'application/manifest+json',
|
||||
};
|
||||
const handler = async (req, res) => {
|
||||
try {
|
||||
const url = new URL(req.url, 'http://localhost');
|
||||
if (url.pathname.startsWith(apiPrefix)) {
|
||||
const ownOrigin =
|
||||
process.env.PUBLIC_ORIGIN ||
|
||||
`${process.env.TLS_CERT && process.env.TLS_KEY ? 'https' : 'http'}://${req.headers.host}`;
|
||||
if (
|
||||
(req.headers.origin && req.headers.origin !== ownOrigin) ||
|
||||
(!['GET', 'HEAD', 'OPTIONS'].includes(req.method) && req.headers.origin !== ownOrigin)
|
||||
) {
|
||||
res.writeHead(403, { 'content-type': 'application/json' });
|
||||
res.end(JSON.stringify({ message: '请求来源不匹配' }));
|
||||
return;
|
||||
}
|
||||
const headers = {
|
||||
...req.headers,
|
||||
host: target.host,
|
||||
origin: process.env.PCB_API_ORIGIN || 'http://127.0.0.1:5173',
|
||||
};
|
||||
const upstream = (target.protocol === 'https:' ? https : http).request(
|
||||
new URL('/api/' + url.pathname.slice(apiPrefix.length) + url.search, target),
|
||||
{ method: req.method, headers },
|
||||
(reply) => {
|
||||
res.writeHead(reply.statusCode || 502, {
|
||||
...reply.headers,
|
||||
'cache-control': 'no-store',
|
||||
'x-accel-buffering': 'no',
|
||||
});
|
||||
pipeline(reply, res, () => {});
|
||||
},
|
||||
);
|
||||
upstream.on('error', () => {
|
||||
if (!res.headersSent) res.writeHead(502, { 'content-type': 'application/json' });
|
||||
res.end(
|
||||
JSON.stringify({ message: '无法连接 PCB 后台,请检查 PCB_API_TARGET 和后台运行状态。' }),
|
||||
);
|
||||
});
|
||||
req.on('aborted', () => upstream.destroy());
|
||||
res.on('close', () => upstream.destroy());
|
||||
pipeline(req, upstream, () => {});
|
||||
return;
|
||||
}
|
||||
if (!['GET', 'HEAD'].includes(req.method)) {
|
||||
res.writeHead(405);
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
if (siteBase !== '/' && (url.pathname === '/' || url.pathname === siteBase.slice(0, -1))) {
|
||||
res.writeHead(302, { location: siteBase + url.search });
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
if (!url.pathname.startsWith(siteBase)) {
|
||||
res.writeHead(404);
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
let path = resolve(root, './' + decodeURIComponent(url.pathname.slice(siteBase.length)));
|
||||
if (path !== root && !path.startsWith(root + sep)) {
|
||||
res.writeHead(403);
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if ((await stat(path)).isDirectory()) path = resolve(path, 'index.html');
|
||||
await stat(path);
|
||||
} catch {
|
||||
if (extname(url.pathname)) {
|
||||
res.writeHead(404);
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
path = resolve(root, 'index.html');
|
||||
}
|
||||
res.writeHead(200, {
|
||||
'content-type': mime[extname(path)] || 'application/octet-stream',
|
||||
'cache-control': url.pathname.startsWith(`${siteBase}assets/`)
|
||||
? 'public, max-age=31536000, immutable'
|
||||
: 'no-cache',
|
||||
'x-content-type-options': 'nosniff',
|
||||
});
|
||||
if (req.method === 'HEAD') {
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
pipeline(createReadStream(path), res, () => {});
|
||||
} catch {
|
||||
if (!res.headersSent) res.writeHead(500);
|
||||
res.end('Request failed');
|
||||
}
|
||||
};
|
||||
const server =
|
||||
process.env.TLS_CERT && process.env.TLS_KEY
|
||||
? https.createServer(
|
||||
{ cert: await readFile(process.env.TLS_CERT), key: await readFile(process.env.TLS_KEY) },
|
||||
handler,
|
||||
)
|
||||
: http.createServer(handler);
|
||||
server.listen(port, host, () => {
|
||||
console.log(
|
||||
`VibeMake PCB: ${process.env.TLS_CERT ? 'https' : 'http'}://${host}:${port}${siteBase}`,
|
||||
);
|
||||
console.log(`PCB API: ${target.origin} (existing server-side model/key configuration)`);
|
||||
console.log(
|
||||
'For a remote server, use SSH port forwarding and visit http://localhost:' + port + siteBase,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
# A configured runtime is optional; ordinary Node 20+ installations also work.
|
||||
if ! command -v node >/dev/null || [ "$(node -p 'Number(process.versions.node.split(".")[0])')" -lt 20 ]; then
|
||||
runtime="$HOME/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/bin"
|
||||
if [ -x "$runtime/node" ]; then export PATH="$runtime:$PATH"; else echo 'Please install Node.js 20+ (recommended 22 LTS) and npm first.'; exit 1; fi
|
||||
fi
|
||||
# Local configuration is read by Node's env parser, never evaluated as shell code.
|
||||
node_args=()
|
||||
if [ -f .env.local ]; then
|
||||
node_args=("--env-file=$PWD/.env.local")
|
||||
fi
|
||||
if ! command -v npm >/dev/null; then echo 'npm is required to bootstrap the pinned pnpm version.'; exit 1; fi
|
||||
if [ ! -d node_modules ]; then npm exec --yes --package=pnpm@10.33.0 -- pnpm install --frozen-lockfile; fi
|
||||
if [ ! -f designer/dist/index.html ] || [ "${REBUILD:-0}" = 1 ] || find designer/src ai common -type f -newer designer/dist/index.html -print -quit | grep -q .; then
|
||||
npm exec --yes --package=pnpm@10.33.0 -- pnpm -C designer build
|
||||
fi
|
||||
exec node "${node_args[@]}" scripts/serve.mjs
|
||||
Reference in New Issue
Block a user