Merge origin/main: preserve native PCB tools and adopt upstream web services

This commit is contained in:
2026-11-16 18:18:19 +08:00
94 changed files with 5485 additions and 335 deletions
+4 -2
View File
@@ -1,7 +1,9 @@
# 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://127.0.0.1:8002
# Persistent Codex PCB session backend. Override when using a remote installation.
PCB_API_TARGET=http://39.105.93.138:8003
PCB_API_ORIGIN=http://127.0.0.1:5173
# Account and platform project API, independent of the AI task service:
API_TARGET=https://dev-vibemake-api.robotquan.com
HOST=127.0.0.1
PORT=5180
# For LAN HTTPS, supply a certificate trusted by the client browser:
+36 -4
View File
@@ -23,8 +23,40 @@ tools/libraries/out/
supabase/.temp/
tools/demos/index.json*.bak
# Local PCB worker state
backend/.venv/
backend/.cache/
# Local AI task history, generated evidence, and credentials
/runtime/
/history-archive/
/test-results/
/playwright-report/
*.sqlite
*.sqlite3
*.sqlite-wal
*.sqlite-shm
*.sqlite3-wal
*.sqlite3-shm
*.log
/auth.json
/config.toml
# Native backend Python environment and bytecode
__pycache__/
*.pyc
*.py[cod]
.pytest_cache/
.venv/
# KiCad personal view state and lock files
*.kicad_prl
*.lck
# Native backend caches and runtime data
/backend/.cache/
/backend/runtime/
/backend/.venv/
# Optional local Linux EDA application used by the backend container
/vendor/lceda-pro/
/codex_pcb/build-assets/*
!/codex_pcb/build-assets/README.md
# Local backend source backups
/backend/**/*.bak-*
+42 -6
View File
@@ -10,12 +10,12 @@ Review has no Shell or EDA editing access. Production starts the same thread wit
## Runtime
- Model: exact `gpt-6.1-sol`, reasoning `high`; no model substitution.
- Default provider: `PCB_AI_PROVIDER=openai`; OpenAI-compatible endpoint `PCB_OPENAI_BASE_URL=https://api.vip1129.cc`, model `PCB_OPENAI_MODEL=gpt-6.1-sol`. New designs can select DeepSeek or Doubao after server credentials are configured. Reasoning defaults to `PCB_REASONING_EFFORT=high`; there is no automatic model/provider substitution. API projects must have access to the configured model.
- Service: `vibemake-pcb2-session.service`, FastAPI on loopback `8003`.
- Web: `vibemake-pcb2-web.service`, HTTPS `15182`, `/pcb/pcb-api/` proxy.
- Source: `/home/wpz/auto_pcb_2/vibemake-pcb-studio/codex_pcb`.
- Persistent runtime: `/home/wpz/auto_pcb_2/persistent-runtime`.
- Dedicated Codex home stores native session history. Authentication links to the existing local Codex login; credentials are not sent to the browser or copied into the repository.
- Source: the installed checkout's `codex_pcb/` directory.
- Persistent runtime: `PCB_SESSION_ROOT` (default `~/.local/share/vibemake-pcb`; use a persistent mount such as `/data` in a container).
- Dedicated Codex home: `PCB_CODEX_HOME` (default `$PCB_SESSION_ROOT/codex-home`) stores native session history. Authentication can use a server-side OpenAI API key or an existing Codex login; credentials are not sent to the browser or copied into the repository.
- Each task owns a workspace, native EDA session, full EDA scripts/results and Codex event evidence. Official standalone EDA API references come from the installed `~/.codex/skills/easyeda-api`; no legacy design workflow is loaded.
- The original `~/auto_pcb` service and user-opened EDA windows are not modified.
@@ -27,6 +27,36 @@ When an agent turn ends without accepted delivery, the service asks the same ses
At approval the service hashes its Python source and instructions. Any subsequent change blocks production tool calls/resume. Therefore an acceptance run cannot silently continue with a patched backend. A new version requires a new task/run.
The approval hash also covers non-secret runtime settings, including the model, reasoning effort, provider and executable paths. Rotating an API key does not change this hash. An existing thread cannot be switched between the login and API providers; create a new task after changing provider/model settings. Deploy source changes only after active tasks have finished; already-approved tasks from an earlier source version cannot be resumed by rewriting their hash.
## Portable paths and OpenAI API authentication
For the backend-only Docker/1Panel upload bundle, build commands and EDA mount layout, see [codex_pcb/DEPLOY.md](codex_pcb/DEPLOY.md). Generate the bundle with `python3 scripts/package-pcb-backend.py`.
Backend settings are documented in `codex_pcb/.env.example`; they are separate from the frontend/proxy's `.env.pcb.example`. Copy the backend example to an ignored `.env.local`, fill in the key on the server, and inject it into the **backend process** using Compose `env_file`, systemd `EnvironmentFile`, or Uvicorn `--env-file` (requires `python-dotenv`). Merely creating an env file does not load it.
Existing installations must explicitly keep `PCB_SESSION_ROOT` pointing at their original runtime to retain access to task records and Codex history; the new portable default does not migrate old directories.
For API authentication set `PCB_CODEX_AUTH=apikey` and either `OPENAI_API_KEY` or `OPENAI_API_KEY_FILE`. The environment value takes precedence; the file is useful with Docker secrets. The service configures a dedicated Codex provider using the Responses API at the configured `PCB_OPENAI_BASE_URL` (project default `https://api.vip1129.cc`), with `env_key=OPENAI_API_KEY`. It passes the key only to the Codex process, without adding it to CLI arguments or writing an `auth.json`. No interactive Codex login is required in this mode. Existing login credentials are not used as a fallback. API use is billed to the OpenAI API project; authentication does not guarantee access to the configured model.
`PCB_OPENAI_BASE_URL` explicitly overrides that API base URL for credentials issued by another Responses-compatible provider. Use the exact base path supplied by the provider, paired with its own key; personal Codex configuration is not imported and there is no automatic provider/model fallback. The base URL is included in the approval runtime hash. Health metadata exposes the configured non-secret endpoint and authentication mode, but does not probe inference.
Native `error` notifications, including retry details, are surfaced to the website. A terminal native error fails the task immediately. `PCB_CODEX_IDLE_TIMEOUT` (default 300 seconds) fails a stalled model turn and retains the native session for retry; heartbeat/status/retry notifications alone do not count as model progress. Active native tool requests use their existing execution timeouts. This avoids an indefinitely opaque planning state while preserving normal reasoning/token progress and long tool execution.
To retain the earlier login setup, explicitly set `PCB_CODEX_AUTH=chatgpt` (also the default for compatibility) and provision the service's `PCB_CODEX_HOME` with the existing login. This mode removes API keys from the Codex process environment. Use a dedicated service home rather than your IDE's session directory. Both `thread/start` and `thread/resume` select the same provider.
Set `PCB_CODEX_BIN`, `PCB_EDA_BIN` and `PCB_BLENDER_BIN` to installed executables, or leave them unset to search `PATH` for `codex`, `lceda-pro` and `blender`. Set `PCB_FREEROUTING_JAR` when the JAR is outside `$PCB_SESSION_ROOT/resources/freerouting.jar`; both the production prompt and standalone launcher honor it. EDA subprocesses preserve an explicitly configured `XDG_RUNTIME_DIR` and `DISPLAY`; neither setting starts a display server. Create a private runtime directory owned by the service user with mode `0700`, and start/configure Xvfb separately on headless servers. The EDA application, Java, Xvfb/xauth and Blender still need to be installed and validated.
For example, after injecting the settings, start one backend instance from the checkout root:
```sh
python -m uvicorn codex_pcb.app:app --host 0.0.0.0 --port 8003 --workers 1
```
Persist `PCB_SESSION_ROOT`, any separately configured `PCB_CODEX_HOME`, and the native EDA application's user/project data. A key alone does not install CAD dependencies. A successful `/api/health` checks the HTTP service, not API billing/model permissions or native EDA execution; validate with a new proposal and a real approved design. Never use a key pasted into chat; revoke it and supply a replacement only through server-side configuration.
See [Codex authentication](https://developers.openai.com/codex/auth/) and [provider configuration](https://developers.openai.com/codex/config-advanced/).
## Delivery
The agent supplies real native project, schematic, routed layout, extracted assembled STEP and 3D render, plus optional BOM/reports. Delivery independently focuses the supplied native documents, saves them, exports native netlists and runs schematic/PCB checks. Both native gate booleans must be true. Basic file signatures and path boundaries are checked, then files are copied to a separate delivery directory with hashes and a ZIP. Downloads verify hashes again.
@@ -45,7 +75,7 @@ journalctl --user -u vibemake-pcb2-session.service -f
curl http://127.0.0.1:8003/api/health
```
The root `start.sh` starts the new services. All requests are asynchronous and the UI polls task state/events. The service binds loopback; the web proxy retains its same-origin write checks.
The root `start.sh --services` starts the new systemd services on a configured Linux server. Without this flag, `start.sh` builds/serves the frontend and proxies its API to the separately running backend (default `http://39.105.93.138:8003`, overridable with `PCB_API_TARGET`). All requests are asynchronous and the UI polls task state/events. The Linux service template binds loopback; the web proxy retains its same-origin write checks.
## Acceptance protocol
@@ -70,7 +100,7 @@ The root `start.sh` starts the new services. All requests are asynchronous and t
### 新服务器部署与使用
1. 安装 Python 3、可运行此 JAR 的 Java(1.9.0 官方要求 Java 17)、`xvfb` 和 `xauth`。Debian/Ubuntu 可以安装 `openjdk-17-jre xvfb xauth`;若已有兼容 Java,可保留现有版本。
2. 将已验证的 JAR 放到 `$PCB_SESSION_ROOT/resources/freerouting.jar`,或使用 `PCB_FREEROUTING_JAR` / `--jar` 指定绝对路径。未配置运行根目录时,默认仍是当前部署的 `/home/wpz/auto_pcb_2/persistent-runtime`,迁移必须修改它。
2. 将已验证的 JAR 放到 `$PCB_SESSION_ROOT/resources/freerouting.jar`,或使用 `PCB_FREEROUTING_JAR` / `--jar` 指定绝对路径。未配置运行根目录时默认使用 `~/.local/share/vibemake-pcb`;容器中应显式设置为持久化挂载路径,例如 `/data`。
3. 生产会话应使用批准消息提供的启动命令。下面路径需要按目标服务器替换:
```sh
@@ -94,3 +124,9 @@ python3 /path/to/vibemake-pcb-studio/codex_pcb/freerouting.py \
版本升级时重新核对参数和弹窗行为,不将 1.9.0 的命令行约定直接套到其他版本。
依据:[1.9.0 命令行说明](https://github.com/freerouting/freerouting/blob/v1.9.0/README.md#using-the-command-line-arguments)、[参数解析](https://github.com/freerouting/freerouting/blob/v1.9.0/src/main/java/app/freerouting/gui/StartupOptions.java)、[确认框与自动启动](https://github.com/freerouting/freerouting/blob/v1.9.0/src/main/java/app/freerouting/gui/MainApplication.java#L430-L488)。
## Per-design AI providers
`GET /api/providers` supplies the frontend selector without secrets. `POST /api/sessions` accepts an optional `provider` (`openai`, `deepseek`, `doubao`), defaulting to `PCB_AI_PROVIDER` / `openai`. Each task persists its non-secret runtime snapshot. Comments, production and restart keep that selection; runtime changes are rejected rather than migrating a native thread. Approval fingerprints cover the selected task runtime, so changing only the default for future tasks does not redirect existing ones. Credentials are injected only into their corresponding Codex process and removed from EDA subprocesses.
DeepSeek defaults to `deepseek-flash` at `https://api.deepseek.com` with `DEEPSEEK_API_KEY` (or `_FILE`); Doubao defaults to `doubao-seed-2-1-pro-260915` at `https://ark.cn-beijing.volces.com/api/v3` with `ARK_API_KEY` (or `_FILE`; DOUBAO_API_KEY aliases are accepted). Both use the native Responses API and provider-specific model metadata; no legacy agent loop or Chat Completions bridge is used. Doubao requires account model entitlement and has no built-in web search enabled by this integration. See the backend deployment guide for all provider-specific overrides.
+49 -3
View File
@@ -1,9 +1,55 @@
# PCB website service
The current implementation is the new **persistent Codex session** service. See [CODEX-SESSION.md](CODEX-SESSION.md) for architecture, deployment, validation and acceptance protocol.
当前 AI 入口使用新的持久化 Codex 会话服务 `codex_pcb.app`。架构、运行依赖、审核和交付协议见 [CODEX-SESSION.md](CODEX-SESSION.md)。旧 `backend/` 中的固定设计流程及 `backend/providers/codex.py` 不再是网站默认执行入口,旧任务不会自动迁移到新会话。
The former `backend/easyeda_backend/design_runtime` pipeline and `backend/providers/codex.py` adapter are **not used** by the current website entry. The old PCB2 API systemd service is disabled; no old task is migrated into the new session engine.
## 本地前端与代理
Open <https://192.168.1.200:15182/pcb/?ai=1>.
要求 Node.js 20+(建议 22 LTS)、npm,以及可访问的新会话后台。
```bash
cp .env.pcb.example .env.local
# 按实际部署修改 PCB_API_TARGET,默认 http://39.105.93.138:8003
./start.sh
```
普通 `./start.sh` 保留跨平台前端构建和静态服务器启动方式,默认访问 `http://localhost:5180/pcb/`。它不启动 AI 后台;后台缺失时仍可使用项目列表和原编辑器。开发时可运行 `pnpm -C designer dev`,默认端口 5173;代理配置通过启动进程的环境变量传入。`REBUILD=1 ./start.sh` 强制构建。
AI 请求使用同源 `/pcb/pcb-api/sessions` 等路径,代理转发为后台 `/api/sessions`,默认目标为 `http://39.105.93.138:8003`。旧后台 `/api/v1/tasks` 与新协议不同,不应把新入口指向旧 8000/8002 服务。修改目标时同时核对 Vite、静态服务器和反向代理配置。
账号与平台工程接口 `/api/` 独立转发至 `API_TARGET`,默认开发平台 API;保留 Authorization,移除 Origin/Referer。统一登录、项目封面、工程保存和重新打开继续使用平台流程,不与 AI 会话记录混为同一数据集。
AI 入口仅在打开项目且项目工作台加载完成后显示,返回项目列表时隐藏。默认收起,点击“Codex AI 自动绘板”打开;项目 URL 显式带 `?ai=1` 可直接打开。当前本地构建使用 `VITE_ENABLE_PCB_AI=true`;仍可在 `designer/.env.local` 中设置 `VITE_ENABLE_PCB_AI=false` 关闭 AI,关闭时不挂载 AI 组件、不轮询会话。修改此构建配置需重启开发服务器或重新构建。关闭工作台不取消服务端已提交的任务。
## 新会话后台与现有 Linux 部署
新服务代码在 `codex_pcb/`。当前部署模板为 [integration/vibemake-pcb2-session.service](integration/vibemake-pcb2-session.service),使用 Uvicorn 在 loopback 8003 运行;网页模板见 [integration/vibemake-pcb2-web.service](integration/vibemake-pcb2-web.service)。迁移时需按目标服务器修改模板中的用户、源码、运行目录、显示环境、认证和证书路径,不能照搬原开发者机器上的绝对路径。
在已正确安装并配置这两个 systemd 用户服务的 Linux 主机上:
```bash
./start.sh --services
```
原开发环境的网页地址是 `https://192.168.1.200:15182/pcb/?ai=1`,不是通用可达地址。本地未部署 Codex/嘉立创 EDA 及对应服务时,合并代码或打包前端不会使 AI 自动具备执行能力。具体依赖、持久化目录、原生会话和认证要求以 CODEX-SESSION.md 为准。旧版 KiCad 的 macOS 适配保留在 `backend/`,不代表新持久化会话引擎已在 macOS 验收。
部署 Freerouting 前请阅读 [无交互部署注意事项](CODEX-SESSION.md#freerouting-无交互部署注意事项2026-11-11)。生产会话统一使用 `codex_pcb/freerouting.py`,避免错误帮助参数和默认确认倒计时导致停顿。
## 独立静态发布包
根目录执行 `./build.sh`,使用固定版本 pnpm 安装缺失依赖、构建 `/pcb/` 前端,生成 `dist/vibemake-pcb.zip` 和 `dist/vibemake-pcb/`。ZIP 根目录直接包含 `index.html`、`assets/` 等文件,不包含额外的 `pcb/` 目录。构建失败时不会用旧产物生成新包。
```bash
unzip -o /path/to/ziro-designer-main/dist/vibemake-pcb.zip -d /path/to/vibemake/pcb
```
结果应为 `<网站根目录>/pcb/index.html`。不要解压到网站根目录、再套一层 `pcb/`,或只放 ZIP 而不解压。保留主站、CAD 和旧 PCB 资源,不要清空网站或 PCB 目录;三者分别发布。通过 `/pcb/build-info.json` 核对发布版本,包内 `DEPLOY.md` 包含部署说明。
静态包只包含浏览器前端,不包含 `backend/`、`codex_pcb/`、模型凭据或运行数据。保留账号 API 和 `/pcb/pcb-api/` 反向代理;AI 代理必须先于页面回退规则匹配,不能将 API 请求回退为 HTML。部署到其他路径时,构建 base、路由、代理和 PWA scope 必须保持一致。
## 数据与访问边界
AI 后台继续使用服务端私有认证,不将密钥或登录文件放入 `VITE_*`、前端源码或 Git。会话数据与生成文件应位于仓库外的持久化目录。当前会话 API 是共享后台,平台前端登录并不等于后端已具备逐用户任务隔离;对外开放前需要接入服务端认证和归属校验。
当前新会话入口按上游协议提供方案审核、进度、三维预览和交付下载。旧 `PlatformPcbService` 适配代码保留用于兼容与回归测试,但不会同时挂载旧工作台或向新服务重放旧命令。
浏览器编辑器依赖安全上下文;localhost HTTP 或受信任 HTTPS 可用。使用 HTTPS 反向代理时配置 `PUBLIC_ORIGIN`,API 不缓存;参考 [integration/nginx.example.conf](integration/nginx.example.conf)。
+34 -1
View File
@@ -1,3 +1,18 @@
> 新任务使用 DeepSeek + 原生 KiCad 后台,包含器件、原理图、布局、布线、检查和网页交付。完整后台启动与依赖见 [backend/README.md](backend/README.md)。
# VibeMake PCB Studio · AI PCB 接入
本版本接入服务端 AI PCB 工作流:需求与资料、方案选择、后台设计、成果预览、审核下载及独立编辑副本导入。
```bash
./start.sh
```
访问 http://localhost:5180/pcb/ 。首次启动自动安装依赖并构建;需要 Node.js 22+ 和可达的 PCB 后台。
现有 DeepSeek API key 留在后台,本仓库不保存模型密钥。配置和远程访问见 [PCB-SERVICE.md](./PCB-SERVICE.md)。
以下保留原项目文档和许可说明。
# ZiroEDA
**KiCad-compatible electronics design in a browser tab. Nothing to install.**
@@ -133,6 +148,7 @@ See **[STRUCTURE.md](./STRUCTURE.md)** for the full map and conventions.
pnpm install
pnpm -C designer dev # http://localhost:5173/pcb/
pnpm -C designer build # typecheck + production build
./build.sh # independent /pcb/ package: dist/vibemake-pcb.zip
pnpm -r test # all unit tests
pnpm -r typecheck
```
@@ -145,6 +161,23 @@ configure Nginx with `try_files $uri $uri/ /pcb/index.html;` inside the
`location ^~ /pcb/` block. Use `VITE_BASE=/another-path/ pnpm -C designer build`
only when deploying to a different path.
For an independent release, run `./build.sh`. It installs missing dependencies
with the pinned pnpm version, builds for `/pcb/`, and creates
`dist/vibemake-pcb/` and `dist/vibemake-pcb.zip`. Both contain `index.html`,
`assets/` and the other frontend files directly, with no enclosing `pcb/` directory.
Extract the ZIP directly into `<website-root>/pcb/`, so the result is
`<website-root>/pcb/index.html`. For example:
```sh
unzip -o /path/to/ziro-designer-main/dist/vibemake-pcb.zip -d /path/to/vibemake/pcb
```
Extract the archive itself; copying a ZIP into the directory does not publish it.
Preserve the main site, CAD and older PCB assets. Do not clear the website or PCB
directory first, extract into the website root, or add an extra enclosing directory.
The VibeMake main-site package does not include PCB. The account API and AI PCB
backend continue to run separately; preserve their proxy configuration.
For development, a clone starts with no configuration. Accounts, cloud
projects and sharing need a Supabase project; every integration is env-gated
and simply switches off when its variables are absent.
@@ -201,4 +234,4 @@ chat with us on [Discord](https://www.ziroeda.com/discord), or write to **admin@
新增入口支持需求输入、方案评论与版本审核、明确开始运行、嘉立创后台持续绘制,以及 STEP、3D 渲染、Layout 和原理图交付。
部署与使用见 [PCB-SERVICE.md](PCB-SERVICE.md)。本服务器入口:https://192.168.1.200:15182/pcb/?ai=1 。
部署与使用见 [PCB-SERVICE.md](PCB-SERVICE.md)。原开发环境入口为 https://192.168.1.200:15182/pcb/?ai=1 ,迁移时请配置自己的服务地址。
+20 -1
View File
@@ -1,6 +1,6 @@
# auto_pcb_2 运行说明
当前工作区默认使用 Codex GPT-6.1 Sol。本站入口、15182/8002 端口、独立数据目录、强制方案审核和 STEP 导出,以 [PCB-SERVICE.md](../PCB-SERVICE.md) 为准。
当前工作区默认使用 Codex GPT-6.1 Sol。本站入口、15182/8003 端口、独立数据目录、强制方案审核和 STEP 导出,以 [PCB-SERVICE.md](../PCB-SERVICE.md) 为准。
下面保留迁入后端的历史说明,涉及旧工作区路径、DeepSeek 默认值及 15180/8000 端口的段落不适用于本次部署。
@@ -34,6 +34,25 @@ DISPLAY=:1 lceda-pro doctor --no-sandbox
嘉立创客户端应在后台主机持续运行并能访问在线器件库。浏览器关闭或访问端断网不取消后台任务;服务器及客户端仍需运行和联网。`AI_PCB_EDA_EXTRA_ARGS` 默认为 `--no-sandbox`,按部署环境可覆盖。
可配置 `KICAD_CLI`、`KICAD_PYTHON`、`KICAD_SYMBOL_DIR`、`KICAD_FOOTPRINT_DIR`、`KICAD_3DMODEL_DIR`、`AI_PCB_FREEROUTING_JAR`。资源路径应与 KiCad 实际安装匹配。当前完整生成验收平台为 Linux;浏览器客户端不受此限制。
### macOS 本地启动旧版 KiCad 后台
安装 KiCad 10、Python 3.11+ 和 Java 17+ 后,在 `backend/.env.local` 中配置 DeepSeek 密钥,并设置 KiCad 应用内的 CLI、Python 和库目录:
```dotenv
AI_PCB_EDA_BACKEND=kicad
AI_PCB_API_HOST=127.0.0.1
AI_PCB_API_PORT=8000
KICAD_CLI=/Applications/KiCad/KiCad.app/Contents/MacOS/kicad-cli
KICAD_PYTHON=/Applications/KiCad/KiCad.app/Contents/Frameworks/Python.framework/Versions/Current/bin/python3
KICAD_SYMBOL_DIR=/Applications/KiCad/KiCad.app/Contents/SharedSupport/symbols
KICAD_FOOTPRINT_DIR=/Applications/KiCad/KiCad.app/Contents/SharedSupport/footprints
KICAD_3DMODEL_DIR=/Applications/KiCad/KiCad.app/Contents/SharedSupport/3dmodels
```
在已登录的 macOS 桌面会话中运行 `./start.sh`。布线器使用 Java 原生桌面,不要求 Xvfb;Linux 仍使用隔离的 Xvfb 显示。旧版 API 默认监听 `http://127.0.0.1:8000`;它不兼容当前持久化会话入口,不能用来替代 `8003` 上的新服务。macOS 已验证 KiCad 环境检查与小型板的 DSN/SES 布线,完整设计生成仍需单独验收。
## 流程与数据
需求确认后,模型搜索真实器件并提出有界的原理图器件操作;服务器检查 API 签名、脚本语法与目标身份,再交给持久化工位执行。连线、PCB 搬运、布局、Freerouting 布线、铺铜、保存重开、网络比对和导出由固定代码负责。失败先对账并自动恢复,有界重试耗尽后明确失败,不要求用户 SSH 排障,也不会把失败检查改成通过。
+6
View File
@@ -9,6 +9,7 @@ import shutil
import signal
import select
import subprocess
import sys
import time
import math
@@ -135,6 +136,11 @@ def rules(text, circuit, plan=None, parts=()):
@contextlib.contextmanager
def virtual_display(runtime, directory, cancel):
if sys.platform == 'darwin':
# macOS Java uses the native desktop; Xvfb is only needed on Linux.
cancel()
yield dict(os.environ)
return
binary = shutil.which('Xvfb')
if not binary:
raise KiCadError('The pinned router requires Xvfb for unattended operation; install xvfb')
+1 -1
View File
@@ -60,7 +60,7 @@ if __name__ == '__main__':
if not health['available']:
raise SystemExit('KiCad backend prerequisites failed: ' + '; '.join(health['findings']))
executable()
if not shutil.which('Xvfb'):
if sys.platform != 'darwin' and not shutil.which('Xvfb'):
raise SystemExit('Install Xvfb for unattended local routing')
else:
raise SystemExit('AI_PCB_EDA_BACKEND must be easyeda or kicad')
+1 -1
View File
@@ -37,7 +37,7 @@ class StartupTests(unittest.TestCase):
with tempfile.TemporaryDirectory() as directory:
auth=Path(directory)/'auth';auth.touch()
result=Mock(returncode=0,stdout=f'DISPLAY=:0\nXAUTHORITY={auth}\nSECRET=hidden')
with patch.dict(os.environ,{'DISPLAY':':1','XAUTHORITY':'/stale'}),patch.object(startup.subprocess,'run',return_value=result):
with patch.dict(os.environ,{'DISPLAY':':1','XAUTHORITY':'/stale'}),patch.object(startup.sys,'platform','linux'),patch.object(startup.subprocess,'run',return_value=result):
self.assertTrue(startup.restore_graphics())
self.assertEqual(os.environ['DISPLAY'],':0');self.assertEqual(os.environ['XAUTHORITY'],str(auth))
self.assertNotEqual(os.getenv('SECRET'),'hidden')
+1 -1
View File
@@ -114,7 +114,7 @@ class ProviderTests(unittest.TestCase):
'CODEX_HOME': '/private/deepseek', 'DEEPSEEK_API_KEY': 'private-placeholder',
'OPENAI_API_KEY': 'unit-test-only', 'AI_PCB_OPENAI_CODEX_HOME': tmp + '/api-codex'}), patch('providers.codex.resolve_codex', return_value='/fake/codex'):
args, env = process_config()
self.assertEqual(env['CODEX_HOME'], tmp + '/api-codex')
self.assertEqual(env['CODEX_HOME'], str((Path(tmp) / 'api-codex').resolve()))
self.assertNotIn('DEEPSEEK_API_KEY', env)
self.assertEqual(env['OPENAI_API_KEY'], 'unit-test-only')
self.assertIn('model_provider="vibemake_openai"', args)
Executable
+29
View File
@@ -0,0 +1,29 @@
#!/usr/bin/env bash
# Build an independently deployable /pcb/ archive without the main site or CAD.
set -euo pipefail
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
cd "$ROOT_DIR"
for tool in node npm zip unzip; do
if ! command -v "$tool" >/dev/null 2>&1; then
printf 'Error: required build tool is missing: %s\n' "$tool" >&2
exit 1
fi
done
if [ "$(node -p 'Number(process.versions.node.split(".")[0])')" -lt 20 ]; then
printf 'Error: Node.js 20 or newer is required.\n' >&2
exit 1
fi
if [ "${VITE_BASE:-/pcb/}" != '/pcb/' ]; then
printf 'Error: this package is deployed at /pcb/ and requires VITE_BASE=/pcb/.\n' >&2
exit 1
fi
PACKAGE_MANAGER="$(node -p 'require("./package.json").packageManager')"
if [ ! -d node_modules ] || [ ! -d designer/node_modules ]; then
npm exec --yes --package="$PACKAGE_MANAGER" -- pnpm install --frozen-lockfile
fi
printf 'Building the PCB application for /pcb/...\n'
VITE_BASE=/pcb/ npm exec --yes --package="$PACKAGE_MANAGER" -- pnpm -C designer build
node scripts/package-pcb.mjs
+42
View File
@@ -0,0 +1,42 @@
# Backend only. Copy to .env.local and inject with Compose env_file, systemd
# EnvironmentFile, or uvicorn --env-file (requires python-dotenv).
# Never put a real key in this example or a VITE_* variable.
PCB_CODEX_AUTH=apikey
PCB_AI_PROVIDER=openai
OPENAI_API_KEY=
# Alternatively mount a secret file; leave OPENAI_API_KEY empty when using it.
# OPENAI_API_KEY_FILE=/run/secrets/openai_api_key
# Explicit API endpoint paired with that key. Use the provider's exact base URL;
# the service does not import your personal Codex configuration automatically.
PCB_OPENAI_BASE_URL=https://api.vip1129.cc
PCB_OPENAI_MODEL=gpt-6.1-sol
# Optional alternatives, selectable for new designs in the website.
DEEPSEEK_API_KEY=
# DEEPSEEK_API_KEY_FILE=/run/secrets/deepseek_api_key
PCB_DEEPSEEK_BASE_URL=https://api.deepseek.com
PCB_DEEPSEEK_MODEL=deepseek-flash
ARK_API_KEY=
# ARK_API_KEY_FILE=/run/secrets/ark_api_key
# DOUBAO_API_KEY / DOUBAO_API_KEY_FILE are accepted aliases.
PCB_DOUBAO_BASE_URL=https://ark.cn-beijing.volces.com/api/v3
PCB_DOUBAO_MODEL=doubao-seed-2-1-pro-260915
# Fail visibly if no native model progress arrives (heartbeats do not count).
PCB_CODEX_IDLE_TIMEOUT=300
# Container examples: set these to the actual installed/mounted paths.
PCB_SESSION_ROOT=/data
PCB_CODEX_HOME=/data/codex-home
PCB_CODEX_BIN=/usr/local/bin/codex
PCB_EDA_BIN=/opt/lceda-pro/lceda-pro
PCB_BLENDER_BIN=/usr/bin/blender
PCB_FREEROUTING_JAR=/opt/pcb-resources/freerouting.jar
# Use exact model IDs supported by each provider account; no model fallback.
# Legacy PCB_MODEL applies only to the default provider. Prefer the provider-
# specific settings above so changing PCB_AI_PROVIDER cannot reuse a wrong ID.
PCB_REASONING_EFFORT=high
DISPLAY=:99
XDG_RUNTIME_DIR=/tmp/pcb-xdg
+271
View File
@@ -0,0 +1,271 @@
# 在 1Panel 部署 PCB AI 后端
后端可独立于前端部署。仅上传 `codex_pcb/` 会缺少独立 EDA API 文档;推荐使用下述部署包,不需要上传整个仓库或运行旧版 `backend/` 服务。
## 1. 在本地生成上传包
在仓库根目录执行:
```bash
python3 scripts/package-pcb-backend.py
```
如果服务器访问 GitHub 慢,在本地网络可访问 GitHub 时改用:
```bash
python3 scripts/package-pcb-backend.py --with-freerouting
```
该选项将固定版本的 Freerouting JAR 和许可一起放入部署包,并核对 JAR 的 SHA-256。下载缓存在本地 `dist/pcb-backend-downloads/`,重复打包不再下载;程序会优先使用系统 curl 的正常证书验证。服务器构建时直接使用包内文件,无需下载这两个 GitHub 文件。
生成 `dist/vibemake-pcb-backend.tar.gz`,包含当前后端源码、Dockerfile、Compose、启动脚本、Python 依赖、独立 API 参考文档和许可说明。打包按明确的文件清单进行,不包含 `.env.local`、任务历史、个人登录文件、前端、旧设计流程或嘉立创程序。
上传压缩包到 Linux 服务器,在 1Panel 文件管理器中解压到 `/opt`,结果应为:
```text
/opt/vibemake-pcb-backend/
├── LICENSE
├── codex_pcb/
│ ├── Dockerfile
│ ├── Dockerfile.dockerignore
│ ├── compose.yaml
│ ├── docker-entrypoint.sh
│ ├── requirements.txt
│ ├── .env.example
│ └── ...Python 后端源码
├── backend/easyeda_backend/skills/easyeda-api/
│ ├── SKILL.md
│ └── references/
└── vendor/lceda-pro/ # 需自行放入完整的 Linux EDA 程序
```
其中 `backend/` 只包含官方 API 文档和来源元数据,容器不启动旧版服务。
## 2. 准备嘉立创 EDA 专业版 Linux 程序
从[官网下载页](https://lceda.cn/page/download)获取与**服务器** CPU 架构一致的专业版 Linux ZIP。服务器 `uname -m` 的 `x86_64` 对应 x64,`aarch64` 对应 arm64。不要上传 macOS/Windows 程序。CLI 要求支持 `open`、`session list`、`invoke --code-file` 的专业版客户端,运行前请核对其 `--help`。
按压缩包内说明解压,找到实际包含 `lceda-pro` 可执行文件的**完整应用目录**,将该目录的内容放入:
```text
/opt/vibemake-pcb-backend/vendor/lceda-pro/
```
确保 `vendor/lceda-pro/lceda-pro` 是可执行程序;保留应用全部资源、共享库、辅助程序及符号链接,不要只复制一个二进制文件。若外层还有一层目录,需要展开到上述位置。程序以只读方式挂载到容器 `/opt/lceda-pro`,不打进镜像。
```bash
cd /opt/vibemake-pcb-backend
chmod +x vendor/lceda-pro/lceda-pro
```
容器以 `10001:10001` 运行,程序和每一级父目录也必须允许该用户读取/进入。只读挂载不等于不可执行,但宿主机文件系统的 `noexec` 会阻止启动。若容器内仍报 `Permission denied`,先检查宿主机 `stat vendor/lceda-pro/lceda-pro`、`namei -l vendor/lceda-pro/lceda-pro`、`findmnt -T vendor/lceda-pro/lceda-pro`,再检查容器内 `id` 和对应目录权限。不要在只读容器挂载中执行 chmod;在宿主机修复实际目录。保留原发行包中辅助程序的执行位,不要用 `chmod -R 777`。
如果发行包采用其他入口名称,修改 `.env.local` 的 `PCB_EDA_BIN` 为挂载目录中实际路径。首次激活、账号登录、组件库访问以及该版本在虚拟显示上的运行仍需在目标服务器验证;OpenAI Key 不代替嘉立创客户端所需的配置。
## 3. 填写后端环境变量
```bash
cp codex_pcb/.env.example codex_pcb/.env.local
chmod 600 codex_pcb/.env.local
```
在 1Panel 文件编辑器中填写:
```dotenv
PCB_AI_PROVIDER=openai
PCB_CODEX_AUTH=apikey
OPENAI_API_KEY=填入与该地址对应的服务端Key
PCB_OPENAI_BASE_URL=https://api.vip1129.cc
PCB_OPENAI_MODEL=gpt-6.1-sol
DEEPSEEK_API_KEY=
PCB_DEEPSEEK_MODEL=deepseek-flash
ARK_API_KEY=
PCB_DOUBAO_MODEL=doubao-seed-2-1-pro-260915
PCB_CODEX_IDLE_TIMEOUT=300
PCB_SESSION_ROOT=/data
PCB_CODEX_HOME=/data/codex-home
PCB_CODEX_BIN=/usr/local/bin/codex
PCB_EDA_BIN=/opt/lceda-pro/lceda-pro
PCB_BLENDER_BIN=/usr/bin/blender
PCB_FREEROUTING_JAR=/opt/pcb-resources/freerouting.jar
DISPLAY=:99
XDG_RUNTIME_DIR=/tmp/pcb-xdg
```
`PCB_OPENAI_MODEL`、`PCB_DEEPSEEK_MODEL`、`PCB_DOUBAO_MODEL` 必须分别是对应账号可用的准确模型 ID;服务不会自动替换模型。`PCB_REASONING_EFFORT` 也必须受所选模型支持,可用 `PCB_<服务>_REASONING_EFFORT` 分别覆盖。旧的 `PCB_MODEL` 只作用于默认服务,建议迁移为各服务独立设置。真实 Key 只放服务器的 `.env.local`,不要放进 `.env.example`、Dockerfile 或 `VITE_*`。
`PCB_OPENAI_BASE_URL` 是模型 API 的基础地址,与前端连接 PCB 后端的 `PCB_API_TARGET` 不同。当前项目的 OpenAI 兼容服务默认地址为 `https://api.vip1129.cc`;这是用户指定的兼容服务,不是 OpenAI 官方地址。若使用官方 OpenAI 账号,明确设为 `https://api.openai.com/v1` 并使用与该服务对应的 Key。如果凭据由兼容 Responses API 的其他服务签发,需明确配置该服务提供的基础地址,并使用与之匹配的 Key;是否带 `/v1` 以该服务说明为准,不要填写 `/responses` 完整接口地址。后端不会读取或继承个人 `~/.codex/config.toml` 中的模型服务地址,也不会自动切换服务或模型。地址禁止包含用户名、密码、查询参数或片段;Key 仍通过环境变量或 secret 文件注入。
### OpenAI / DeepSeek / 豆包切换
`PCB_AI_PROVIDER` 设定网站新建设计的默认服务,可选 `openai`(项目默认)、`deepseek`、`doubao`。用户可在新建设计表单的「AI 服务」中切换已配置的服务;缺少凭据的选项会禁用。选择在任务创建时保存,方案修改、生产和重启继续使用同一服务、模型及原生会话;已有设计不跨服务迁移,需要切换时新建设计。
| 服务 | 基础地址变量 / 默认值 | 模型变量 / 默认值 | 凭据变量 |
|---|---|---|---|
| OpenAI 兼容服务 | `PCB_OPENAI_BASE_URL` / `https://api.vip1129.cc` | `PCB_OPENAI_MODEL` / `gpt-6.1-sol` | `OPENAI_API_KEY` 或 `OPENAI_API_KEY_FILE` |
| DeepSeek | `PCB_DEEPSEEK_BASE_URL` / `https://api.deepseek.com` | `PCB_DEEPSEEK_MODEL` / `deepseek-flash` | `DEEPSEEK_API_KEY` 或 `DEEPSEEK_API_KEY_FILE` |
| 豆包(火山方舟) | `PCB_DOUBAO_BASE_URL` / `https://ark.cn-beijing.volces.com/api/v3` | `PCB_DOUBAO_MODEL` / `doubao-seed-2-1-pro-260915` | `ARK_API_KEY` 或 `ARK_API_KEY_FILE`;兼容 `DOUBAO_API_KEY` / `DOUBAO_API_KEY_FILE` |
三种服务都通过原生 Codex 的 Responses 协议运行,不引入旧版设计流水线。DeepSeek 使用官方 Responses 接口及原生模型元数据;豆包使用方舟 Responses 接口,需先在方舟控制台开通所选模型,亦可将模型设置为账号实际部署的 Endpoint ID。豆包当前未启用内置联网搜索,批准生产后代理仍可通过原生Shell访问厂商文档。不能仅凭成功的HTTP健康检查认定Key、额度或模型权限可用。
`GET /api/providers` 返回默认服务、各服务模型及凭据是否配置,不返回Key。`POST /api/sessions` 可发送 `{"text":"设计要求…","provider":"deepseek"}`;不填provider使用服务端默认值,未知服务返回400,未配置凭据返回503。每个任务仅向对应Codex进程传递该服务的凭据,其他模型Key及Key文件路径会从子进程环境中剔除;EDA子进程不接收模型凭据。变更已保存任务的模型/服务/地址会阻止继续执行,Key轮换不改变审批哈希。
参考:[DeepSeek Responses API](https://api-docs.deepseek.com/guides/responses_api/)、[DeepSeek Codex接入](https://api-docs.deepseek.com/quick_start/agent_integrations/codex)、[火山方舟 Responses API](https://docs.volcengine.com/docs/ark/1585128)。
原生模型请求的重试错误现在会显示在网站运行记录中,终止错误会将任务标记为失败。若连续 `PCB_CODEX_IDLE_TIMEOUT` 秒(默认300秒)没有原生模型进展,也会明确失败并保留会话供重试;仅有HTTP心跳或重连错误不会延长此期限。正在执行的原生工具请求使用其自身的执行超时,不由这个模型空闲期限中断。`/api/health` 返回当前认证模式、provider及API基础地址供核对,不返回凭据;`ok: true` 仍只代表HTTP服务可用。
Compose 的 `env_file` 会将 `.env.local` 注入后端。Dockerfile 的专用 ignore 文件只允许后端源码和 API 文档进入构建上下文,排除密钥、程序包及运行数据。不要使用 `docker compose config` 的完整输出对外分享配置,其中可能包含已展开的环境变量。
## 4. 构建并启动
在服务器终端执行:
```bash
cd /opt/vibemake-pcb-backend
sh codex_pcb/deploy.sh
docker compose -f codex_pcb/compose.yaml logs --tail=100 -f pcb-backend
```
或者在 1Panel「容器 → 编排 → 创建编排 → 路径选择」选择:
```text
/opt/vibemake-pcb-backend/codex_pcb/compose.yaml
```
需要预先在「容器 → 镜像」构建时,Dockerfile 选择 `codex_pcb/Dockerfile`,**构建上下文必须是 `/opt/vibemake-pcb-backend`,不是其 `codex_pcb/` 子目录**;镜像名用 `vibemake-pcb-backend:local`。
镜像使用 Node 22 / Debian Bookworm,安装 Python、Codex CLI(固定版本)、Java 17、Blender、Xvfb/xauth、字体及常用 Electron 库,并下载或读取包内的 Freerouting 1.9.0,始终校验其 SHA-256。构建需要服务器能访问基础镜像仓库及所选软件源;未预装路由器资源时,还需要访问 GitHub。入口先检查依赖和凭据是否存在,再启动虚拟显示及一个 Uvicorn worker。服务启动后自动执行深度环境检查;Docker 健康检查读取 `/api/ready`,只有文件权限、原生沙箱、EasyEDA 启动和真实只读 API 调用全部通过才判定健康。部署脚本使用 Compose 的 `--wait --wait-timeout 240`,等待健康后才报告部署成功,失败会打印日志并返回非零;需要支持 `--wait` 的 Docker Compose v2。1Panel 中也应确认容器健康状态,不能只看进程为 running。检查不调用模型,不验证 Key 额度或模型权限,也不会自动完成客户端激活。
可用以下命令独立构建:
```bash
docker build -f codex_pcb/Dockerfile -t vibemake-pcb-backend:local .
```
### 国内下载源与缓存
Dockerfile 和 Compose 默认使用以下国内源,可在 `codex_pcb/compose.yaml` 的 `build.args` 中修改:
| 参数 | 默认值 | 下载内容 |
|---|---|---|
| `DEBIAN_MIRROR` | `http://mirrors.tuna.tsinghua.edu.cn/debian` | Python、Blender、Java、图形运行库 |
| `DEBIAN_SECURITY_MIRROR` | `http://mirrors.tuna.tsinghua.edu.cn/debian-security` | Debian 安全更新 |
| `NPM_REGISTRY` | `https://registry.npmmirror.com` | Codex CLI 及匹配平台的原生包 |
| `PIP_INDEX_URL` | `https://mirrors.ustc.edu.cn/pypi/simple` | FastAPI、Uvicorn 及 Python 依赖 |
Debian 12 的 DEB822 `.sources` 文件及传统 `.list` 都会换源;仍使用 Debian 自带的包签名校验。APT 默认使用 HTTP 以支持尚未安装 CA 证书的 slim 基础镜像,npm/pip 保持 HTTPS 验证。不要通过关闭验证或添加 `trusted-host` 处理网络问题。
这些是**构建参数**,放在后端运行时 `.env.local` 中不会自动作用于镜像构建。修改 Compose 的 `build.args`,或直接构建时传 `--build-arg`。例如回到官方源:
```bash
docker build -f codex_pcb/Dockerfile -t vibemake-pcb-backend:local \
--build-arg DEBIAN_MIRROR=http://deb.debian.org/debian \
--build-arg DEBIAN_SECURITY_MIRROR=http://deb.debian.org/debian-security \
--build-arg NPM_REGISTRY=https://registry.npmjs.org \
--build-arg PIP_INDEX_URL=https://pypi.org/simple .
```
某个固定版本尚未同步到镜像站时,可单独切换对应源,无需更改版本。`BASE_IMAGE` 可指定你自己可信仓库中的 Node 22 Bookworm slim 镜像;`FREEROUTING_URL` 和 `FREEROUTING_LICENSE_URL` 可指向自己维护的下载地址,JAR 校验保持不变。
基础镜像 `node:22-bookworm-slim` 在执行 Dockerfile 的 `RUN` 之前拉取,不受上述 apt/npm/pip 源控制。若这一步慢,在 1Panel「容器 → 配置 → 镜像加速」中配置镜像加速器;[1Panel 官方文档](https://1panel-dev.github.io/docs/v2/user_manual/containers/setting/)当前列出 `https://docker.1panel.live`。已成功拉取的基础镜像会复用本地缓存。
镜像构建使用 BuildKit 缓存 APT、npm 和 pip 下载,并将三类安装拆成独立步骤;npm 或 Python 安装失败时不必重新安装已经完成的系统依赖。换源仅对下一次构建生效,已经运行的构建不会自动切换下载地址。更新部署文件后重新执行 `docker compose -f codex_pcb/compose.yaml up -d --build` 即可,不要加 `--no-cache`。
来源:[清华 Debian 镜像说明](https://mirrors.tuna.tsinghua.edu.cn/help/debian/)、[中科大 PyPI 镜像说明](https://mirrors.ustc.edu.cn/help/pypi.html)、[npmmirror 使用说明](https://npmmirror.com/)。
## 5. 验收并接上现有网站
先检查服务器本机接口:
```bash
curl -f http://127.0.0.1:8003/api/health
curl -i http://127.0.0.1:8003/api/ready
curl -s http://127.0.0.1:8003/api/readiness
curl -f http://127.0.0.1:8003/api/providers
docker compose -f codex_pcb/compose.yaml exec pcb-backend codex --version
docker compose -f codex_pcb/compose.yaml exec -T pcb-backend python -m codex_pcb.preflight
docker compose -f codex_pcb/compose.yaml exec pcb-backend /opt/lceda-pro/lceda-pro --help --no-sandbox
docker compose -f codex_pcb/compose.yaml exec pcb-backend /opt/lceda-pro/lceda-pro session list --no-sandbox
```
`python -m codex_pcb.preflight` 不调用模型,不创建设计。它会在独立临时工作区实际验证 `/data`、HOME、Codex HOME、任务目录的创建/写入/重命名、使用相同 workspace-write 配置的原生 Codex 沙箱写文件、EasyEDA `--help` 的启动,并打开自己独立的空白会话,调用 `eda.sys_Environment.isClient()` / `getEditorCurrentVersion()` 验证真实命令桥接。检查结束后关闭自己的诊断会话并清理临时文件,失败返回非零;不操作已有设计会话。`--help` 成功但 `BRIDGE_NOT_READY` 的情况现在会判定失败,不再放行。`ok: true` 不代替元件库权限、正式绘板和交付验证。
启动时会自动检查,并将结果记录到 `/data/runtime-readiness.json` 及容器日志。`GET /api/readiness` 返回 `checking` / `ready` / `unavailable`、检查时间和具体失败项;结果复用五分钟,并发访问共用一次检查。`POST /api/readiness/check` 请求重新检查,重复点击会合并并限速。`GET /api/ready` 是部署验收接口,检查中或失败返回 HTTP 503,通过才返回 200。`GET /api/health` 保留 HTTP 存活检查,另加 `runtime_ready`,不能再单凭其 `ok: true` 判断绘板可用。
用户进入已打开的项目页就会读取环境状态,无需点击生成或打开 AI 面板;未就绪时显示持续提示,工作台内列出失败项和「重新检查环境」。检查中、检查失败或接口不可达时,生成方案、批准绘板、继续设计和方案修改按钮均禁用;浏览已有记录和交付、手工编辑、停止任务不受阻。后端独立拦截创建/批准/恢复请求,环境失败返回 HTTP 503;创建前不会分配任务或启动模型,批准失败不记录生产授权。创建、批准和恢复会重新验证,不能只绕过页面按钮提交请求。
批准生产或恢复生产时,后端也会先对该任务的实际工作区执行同一预检。失败会立即终止本次运行,在任务中保存 `runtime.checked` 事件,并在目录可写时保存 `evidence/runtime-check.json`;不会启动模型反复尝试无法运行的 EDA。系统临时目录仍不开放写入,原生工具的 `TMPDIR`/`TMP`/`TEMP` 指向各任务自己的 `workspace/tmp`。
### 生产权限故障:EDA、namespace 和工作区
`Permission denied: /opt/lceda-pro/lceda-pro`、`bwrap: Creating new namespace failed` 和工作区写入失败属于不同的检查项,修复一个不代表其他项通过。先在**后端服务器**运行上述预检,并检查:
```bash
cd /opt/vibemake-pcb-backend
docker compose -f codex_pcb/compose.yaml ps
docker compose -f codex_pcb/compose.yaml logs --tail=100 pcb-backend
docker compose -f codex_pcb/compose.yaml exec -T pcb-backend sh -c \
'id; ls -ld /data /data/home /data/codex-home /data/tasks /opt/lceda-pro; ls -l /opt/lceda-pro/lceda-pro'
```
1. **EDA 执行权限**:在宿主机修复实际程序执行位、父目录的读取/进入权限;核对完整 Linux 发行包、CPU 架构及 `noexec`。容器中重跑 `--help --no-sandbox`;通过后再验证 `session list`。这里的 `--no-sandbox` 只作用于 Electron,不能解决 Codex 的 `bwrap` 限制。
2. **数据卷属主**:默认服务 UID/GID 为 `10001:10001`。旧卷、手工恢复的目录或改成宿主机 bind mount 后,可能仍归 root 所有。先备份数据、确认挂载路径和 UID,再停止服务,使用下面的一次性 root 容器只修复 `/data` 属主;服务本身继续以原非 root 用户运行。不要删除数据卷,也不要重新初始化任务。
```bash
docker compose -f codex_pcb/compose.yaml stop pcb-backend
docker compose -f codex_pcb/compose.yaml run --rm --no-deps --user 0 \
--entrypoint /bin/sh pcb-backend -c 'chown -R --no-dereference 10001:10001 /data'
docker compose -f codex_pcb/compose.yaml up -d pcb-backend
```
3. **Codex 原生沙箱**:若预检包含 `bwrap`/namespace/`Operation not permitted`,收集以下信息交给宿主机维护者,确认是内核禁用了非特权 user namespace,还是 seccomp/AppArmor/上层容器限制。各环境策略不同,不能仅凭该错误认定是哪一项,也不能靠修改 Key 或代理修复。
```bash
container_id=$(docker compose -f codex_pcb/compose.yaml ps -q pcb-backend)
docker inspect --format 'user={{.Config.User}} apparmor={{.AppArmorProfile}} security={{json .HostConfig.SecurityOpt}}' "$container_id"
sysctl user.max_user_namespaces kernel.unprivileged_userns_clone kernel.apparmor_restrict_unprivileged_userns
sudo journalctl -k --since '10 minutes ago' | grep -Ei 'apparmor|seccomp|denied|namespace'
```
部分内核没有其中某个 sysctl,这本身不等于失败。维护者应按实际拒绝日志为该工作负载开放所需的命名空间/沙箱操作,或换到支持嵌套沙箱的主机,再重新运行预检。模板保留原生沙箱,不默认设置 `privileged`、关闭 seccomp/AppArmor 或启用已弃用的沙箱实现。本地 macOS 的成功不能证明服务器 Linux/Docker 沙箱通过。
只修复宿主机程序权限、数据卷属主或容器策略、且服务源码/冻结配置未变时,可以点击「继续此设计」重试原任务。若升级后端源码导致审批冻结校验不匹配,应保留原任务及证据,在新版中重新创建并审核设计;不要手工篡改 `frozen_source`。
如果使用 `scripts/serve.mjs`,同机前端服务设置 `PCB_API_TARGET=http://127.0.0.1:8003`。若前端也在 Docker 的桥接网络中,改为同网络下的 `http://pcb-backend:8003`。
1Panel OpenResty 使用宿主机网络时,网站增加以下规则;若已有同路径代理,请更新原规则,避免重复:
```nginx
location ^~ /pcb/pcb-api/ {
proxy_pass http://127.0.0.1:8003/api/;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_buffering off;
proxy_read_timeout 3600s;
}
```
OpenResty 若使用桥接网络,其 `127.0.0.1` 指向 OpenResty 自身。此时把 PCB 和 OpenResty 加入同一个 Docker 网络,用 `http://pcb-backend:8003/api/` 转发。例如确认 OpenResty 已在 `1panel-network` 后,在 Compose 最外层添加:
```yaml
networks:
default:
external: true
name: 1panel-network
```
网络名以面板实际配置为准。改动后重建容器;无需将 8003 公开到互联网。当前 API 为共享任务服务,对外开放网站前仍需服务端认证和任务归属校验。
`/pcb/pcb-api/health`、`providers` 返回 HTML 时,先检查状态码:502/503/504 应检查上游连接、容器是否启动及 OpenResty 错误日志;200 则检查 API 路径是否落入前端 `index.html` 回退或登录跳转。不要让 `error_page` 把 API 错误改写成 HTTP 200 的网页。
最后通过网站新建方案、审核启动,验证完整的绘板及交付下载。HTTP 健康并不等于原生绘板成功。
## 数据、备份与升级
`pcb-data` 命名卷挂载到 `/data`,包含任务、交付、Codex 会话和以 `/data/home` 为 HOME 的 EDA 用户数据。默认 Compose 项目名为 `vibemake-pcb`,卷名通常为 `vibemake-pcb_pcb-data`。不要执行 `docker compose down -v`;该操作会删除数据卷。改用宿主机 bind mount 时,目录需允许 UID/GID `10001:10001` 写入。
更新代码后重新生成上传包,替换源码、文档及部署文件,保留服务器的 `.env.local`、`vendor/` 和命名卷,然后重新执行 `sh codex_pcb/deploy.sh`,以真实健康检查结果验收。有已批准任务时先完成该任务再升级;旧任务的源码冻结校验不能通过修改哈希绕过。
新增空卷时入口会将 `/data/resources` 链接到镜像中的 `/opt/pcb-resources`,文档随镜像升级;如果迁移现有运行目录,则保留原有 `resources/` 并检查其文档和路由器路径。独立更改 `PCB_CODEX_HOME` 或 EDA 工程数据位置时,也要额外挂载相应数据。
参考:[1Panel 编排](https://1panel-dev.github.io/docs/v2/user_manual/containers/compose/)、[Docker 构建上下文](https://docs.docker.com/build/concepts/context/)、[嘉立创 CLI](https://prodocs.lceda.cn/cn/api/guide/cli.html)。
+96
View File
@@ -0,0 +1,96 @@
# Build from the repository/deployment-bundle root:
# docker build -f codex_pcb/Dockerfile -t vibemake-pcb-backend:local .
ARG BASE_IMAGE=node:22-bookworm-slim
FROM ${BASE_IMAGE}
ARG DEBIAN_MIRROR=http://mirrors.tuna.tsinghua.edu.cn/debian
ARG DEBIAN_SECURITY_MIRROR=http://mirrors.tuna.tsinghua.edu.cn/debian-security
ENV DEBIAN_FRONTEND=noninteractive \
PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1 \
PATH=/opt/venv/bin:$PATH
RUN set -eu; \
for source in /etc/apt/sources.list /etc/apt/sources.list.d/*.sources /etc/apt/sources.list.d/*.list; do \
[ -f "$source" ] || continue; \
sed -i \
-e "s|https://deb[.]debian[.]org/debian-security|${DEBIAN_SECURITY_MIRROR%/}|g" \
-e "s|http://deb[.]debian[.]org/debian-security|${DEBIAN_SECURITY_MIRROR%/}|g" \
-e "s|https://security[.]debian[.]org/debian-security|${DEBIAN_SECURITY_MIRROR%/}|g" \
-e "s|http://security[.]debian[.]org/debian-security|${DEBIAN_SECURITY_MIRROR%/}|g" \
-e "s|https://deb[.]debian[.]org/debian|${DEBIAN_MIRROR%/}|g" \
-e "s|http://deb[.]debian[.]org/debian|${DEBIAN_MIRROR%/}|g" \
"$source"; \
done
# BuildKit caches survive a failed build; no package cache is added to the image.
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
--mount=type=cache,target=/var/lib/apt/lists,sharing=locked \
rm -f /etc/apt/apt.conf.d/docker-clean \
&& apt-get -o Acquire::Retries=3 update \
&& apt-get install -y --no-install-recommends \
python3 python3-venv ca-certificates curl tini \
openjdk-17-jre blender xvfb xauth x11-utils dbus-x11 \
libasound2 libatk-bridge2.0-0 libgtk-3-0 libnss3 libxss1 \
libgbm1 libdrm2 libx11-xcb1 libxtst6 libsecret-1-0 libfuse2 \
fonts-noto-cjk \
&& python3 -m venv /opt/venv
ARG CODEX_VERSION=0.169.0-alpha.11.1
ARG NPM_REGISTRY=https://registry.npmmirror.com
RUN --mount=type=cache,target=/root/.npm \
npm install -g --registry="${NPM_REGISTRY}" "@openai/codex@${CODEX_VERSION}"
COPY codex_pcb/requirements.txt /tmp/pcb-requirements.txt
COPY codex_pcb/requirements-delivery.txt /tmp/requirements-delivery.txt
ARG PIP_INDEX_URL=https://mirrors.ustc.edu.cn/pypi/simple
RUN --mount=type=cache,target=/root/.cache/pip \
python -m pip install --index-url "${PIP_INDEX_URL}" -r /tmp/pcb-requirements.txt
COPY backend/easyeda_backend/skills/easyeda-api/references/ /opt/pcb-resources/references/
COPY backend/easyeda_backend/skills/easyeda-api/SKILL.md /usr/share/doc/vibemake-pcb/easyeda-api-provenance.md
COPY LICENSE codex_pcb/THIRD-PARTY.md /usr/share/doc/vibemake-pcb/
COPY codex_pcb/build-assets/ /tmp/pcb-build-assets/
ARG FREEROUTING_SHA256=9084a4888937a7f31f857ecc12aa7a37407f51160e4d2892dff9c9bb47ae3102
ARG FREEROUTING_URL=https://github.com/freerouting/freerouting/releases/download/v1.9.0/freerouting-1.9.0.jar
ARG FREEROUTING_LICENSE_URL=https://raw.githubusercontent.com/freerouting/freerouting/v1.9.0/LICENSE
RUN if [ -s /tmp/pcb-build-assets/freerouting.jar ]; then \
cp /tmp/pcb-build-assets/freerouting.jar /opt/pcb-resources/freerouting.jar; \
else \
curl --fail --location --retry 3 "${FREEROUTING_URL}" \
--output /opt/pcb-resources/freerouting.jar; \
fi \
&& echo "${FREEROUTING_SHA256} /opt/pcb-resources/freerouting.jar" | sha256sum --check - \
&& if [ -s /tmp/pcb-build-assets/LICENSE.freerouting ]; then \
cp /tmp/pcb-build-assets/LICENSE.freerouting /usr/share/doc/vibemake-pcb/LICENSE.freerouting; \
else \
curl --fail --location --retry 3 "${FREEROUTING_LICENSE_URL}" \
--output /usr/share/doc/vibemake-pcb/LICENSE.freerouting; \
fi \
&& useradd --uid 10001 --create-home --shell /bin/bash pcb \
&& mkdir -p /data/home /data/codex-home /data/tasks \
&& chown -R pcb:pcb /data
WORKDIR /app
COPY codex_pcb/*.py codex_pcb/instructions.md /app/codex_pcb/
COPY --chmod=755 codex_pcb/docker-entrypoint.sh /usr/local/bin/pcb-entrypoint
ENV HOME=/data/home \
PCB_SESSION_ROOT=/data \
PCB_CODEX_HOME=/data/codex-home \
PCB_CODEX_AUTH=apikey \
PCB_CODEX_BIN=/usr/local/bin/codex \
PCB_EDA_BIN=/opt/lceda-pro/lceda-pro \
PCB_BLENDER_BIN=/usr/bin/blender \
PCB_FREEROUTING_JAR=/opt/pcb-resources/freerouting.jar \
DISPLAY=:99 \
XDG_RUNTIME_DIR=/tmp/pcb-xdg \
LIBGL_ALWAYS_SOFTWARE=1
USER pcb
EXPOSE 8003
HEALTHCHECK --interval=30s --timeout=5s --start-period=210s --retries=3 \
CMD ["python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8003/api/ready', timeout=4).read()"]
ENTRYPOINT ["/usr/bin/tini", "-g", "--", "/usr/local/bin/pcb-entrypoint"]
CMD ["python", "-m", "uvicorn", "codex_pcb.app:app", "--host", "0.0.0.0", "--port", "8003", "--workers", "1"]
+21
View File
@@ -0,0 +1,21 @@
# Allow only backend source and standalone API references into the build.
**
!LICENSE
!codex_pcb/
!codex_pcb/*.py
!codex_pcb/instructions.md
!codex_pcb/requirements.txt
!codex_pcb/Dockerfile
!codex_pcb/docker-entrypoint.sh
!codex_pcb/THIRD-PARTY.md
!codex_pcb/build-assets/
!codex_pcb/build-assets/README.md
!codex_pcb/build-assets/freerouting.jar
!codex_pcb/build-assets/LICENSE.freerouting
!backend/
!backend/easyeda_backend/
!backend/easyeda_backend/skills/
!backend/easyeda_backend/skills/easyeda-api/
!backend/easyeda_backend/skills/easyeda-api/SKILL.md
!backend/easyeda_backend/skills/easyeda-api/references/
!backend/easyeda_backend/skills/easyeda-api/references/**
+24
View File
@@ -0,0 +1,24 @@
# Backend deployment dependencies
VibeMake PCB Studio source is distributed under the repository's GPL-3.0 license;
the deployment bundle includes the original `LICENSE`.
The standalone EDA API references are copied from the bundled
`backend/easyeda_backend/skills/easyeda-api` 1.1.56 snapshot. Upstream:
https://github.com/easyeda/easyeda-api-skill . Its SKILL.md declares MIT and
attributes the package to JLCEDA; the image preserves that source metadata.
The legacy design runtime is not included.
Freerouting 1.9.0 is downloaded when building the image, or included in the upload
archive with `package-pcb-backend.py --with-freerouting`; it is not committed to Git.
Upstream and corresponding source: https://github.com/freerouting/freerouting/tree/v1.9.0
Binary: https://github.com/freerouting/freerouting/releases/download/v1.9.0/freerouting-1.9.0.jar
SHA-256: `9084a4888937a7f31f857ecc12aa7a37407f51160e4d2892dff9c9bb47ae3102`.
License: GPL-3.0. The image includes the upstream license in
`/usr/share/doc/vibemake-pcb/LICENSE.freerouting`.
Codex CLI: https://github.com/openai/codex (Apache-2.0), installed from its pinned
npm package. Debian packages retain their respective notices under
`/usr/share/doc/`. The EasyEDA application is supplied separately by the deployer
and mounted read-only; its commercial application and component libraries are
not part of this source bundle.
+151 -18
View File
@@ -1,21 +1,26 @@
import asyncio
import contextlib
import json
import shlex
import time
import uuid
from contextlib import asynccontextmanager
from pathlib import Path
from fastapi import FastAPI, HTTPException
from fastapi.responses import FileResponse
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
from .config import BLENDER_BIN, CODEX_IDLE_TIMEOUT, DEFAULT_PROVIDER, PROVIDERS, CODEX_HOME, runtime_for
from .storage import SOURCE, ROOT, TASKS, MODEL, EFFORT, task_dir, workspace, load, save, write, event, events, fingerprint, digest, inside
from .rpc import AppServer
from .rpc import AppServer, api_key
from .eda import execute
from .delivery import deliver
from .eda import verify_native
from .exports import prepare_delivery
from .checks import VALIDATION_POLICY
from .native_policy import DESIGN_POLICY, POLICY_TEXT, WORKSPACE_RULES, refresh_workspace_rules
from .preflight import check_runtime
from .readiness import readiness
CACHE, JOBS, CLIENTS = {}, {}, {}
@@ -35,6 +40,7 @@ TOOLS=[
tool('pcb_deliver','Submit real exported files for independent validation. Rejected submission returns evidence so you can repair in the SAME session.',{'schematic_id':STR,'pcb_id':STR,'notes':STR,'files':{'type':'array','items':object_schema({'path':STR,'kind':{'type':'string','enum':['project','schematic','layout','step','render','bom','report','other']},'label':STR}), 'minItems':5}}),
tool('pcb_blocked','Record a concrete unrecoverable blocker and preserve draft. Do not use for ordinary tool errors; investigate and repair first.',{'reason':STR,'evidence':STR}),
]
NATIVE_TOOL_ITEMS={'commandExecution','dynamicToolCall','mcpToolCall','webSearch','fileChange','imageGeneration'}
def get(tid):
try:
@@ -48,8 +54,47 @@ def public(t):
return {k:v for k,v in t.items() if k not in {'pending_prompt','internal'}}
def frozen(t):
if t.get('approval') and fingerprint()!=t['frozen_source']:
raise RuntimeError('Backend source changed after approval. This acceptance run is invalid; start a new task.')
if t.get('approval') and fingerprint(task_runtime(t))!=t['frozen_source']:
raise RuntimeError('Backend source or runtime settings changed after approval. This acceptance run is invalid; start a new task.')
def task_runtime(t):
provider_id = t.get('ai_provider')
if not provider_id:
# Existing tasks predate per-task selection and used OpenAI exclusively.
provider_id = 'openai' if t.get('provider') in {'openai','vibemake_openai'} else DEFAULT_PROVIDER
runtime = runtime_for(provider_id)
if (t.get('runtime') and t['runtime'] != runtime.snapshot()) or any(
t.get(key, value) != value for key, value in (
('model', runtime.model), ('effort', runtime.effort), ('provider', runtime.provider))
):
raise RuntimeError('Task model or provider settings changed; restore its original configuration or create a new design. Existing sessions cannot switch providers.')
return runtime
def provider_status(runtime):
try:
if runtime.auth_mode == 'chatgpt':
configured = (CODEX_HOME/'auth.json').is_file()
else:
api_key(runtime)
configured = True
return {'id':runtime.id,'label':runtime.label,'model':runtime.model,'effort':runtime.effort,'configured':configured}
except ValueError:
return {'id':runtime.id,'label':runtime.label,'model':runtime.model,'effort':runtime.effort,'configured':False}
def codex_error(error):
error = error or {}
return ': '.join(str(error[key]) for key in ('message', 'additionalDetails') if error.get(key)) or 'Unknown Codex error'
async def require_runtime_ready(force=False):
report = await readiness.verify(force=force)
if not report['ok']:
message = ';'.join(item['message'] for item in report['checks'] if not item['ok'])
raise HTTPException(503, '绘板环境未就绪,未启动生成:' + (message or '请等待环境检查完成'))
return report
async def handle(t, method, p):
if method != 'item/tool/call':
@@ -137,13 +182,16 @@ async def handle(t, method, p):
async def run_turn(t, prompt, production):
frozen(t)
runtime=task_runtime(t)
directory=workspace(t)
# Reassert on every turn, including resumed histories with obsolete routing advice.
refresh_workspace_rules(directory)
prompt=POLICY_TEXT+'\n'+prompt
async with AppServer(directory, production, lambda m,p:handle(t,m,p)) as client:
async with AppServer(directory, production, lambda m,p:handle(t,m,p), runtime=runtime) as client:
CLIENTS[t['id']]=client
common={'model':MODEL,'modelProvider':'openai','cwd':str(directory),'approvalPolicy':'never','sandbox':'workspace-write' if production else 'read-only','developerInstructions':(SOURCE/'instructions.md').read_text(),'serviceTier':'default'}
instructions=(SOURCE/'instructions.md').read_text()
if runtime.id=='doubao':
instructions+='\nThis provider has no built-in web-search tool in this integration. In review, mark unverified library/device choices as assumptions. During approved production, retrieve manufacturer references using native Shell/network and inspect the downloaded evidence.\n'
common={'model':runtime.model,'modelProvider':runtime.provider,'cwd':str(directory),'approvalPolicy':'never','sandbox':'workspace-write' if production else 'read-only','developerInstructions':instructions,'serviceTier':'default'}
if t.get('thread_id'):
result=await client.call('thread/resume',dict(common,threadId=t['thread_id'],excludeTurns=True))
if result['thread']['id']!=t['thread_id']:
@@ -153,18 +201,33 @@ async def run_turn(t, prompt, production):
result=await client.call('thread/start',dict(common,ephemeral=False,dynamicTools=TOOLS,serviceName='vibemake-persistent-pcb',allowProviderModelFallback=False))
t['thread_id']=result['thread']['id']
event(t,'session.created',{'thread_id':t['thread_id'],'model':result.get('model')})
if result.get('model') not in {None,MODEL}:
if result.get('model') not in {None,runtime.model}:
raise RuntimeError('Unexpected model substitution')
policy={'type':'workspaceWrite','writableRoots':[str(directory)],'networkAccess':True,'excludeSlashTmp':True,'excludeTmpdirEnvVar':True} if production else {'type':'readOnly','networkAccess':False}
reply=await client.call('turn/start',{'threadId':t['thread_id'],'input':[{'type':'text','text':prompt}],'model':MODEL,'effort':EFFORT,'approvalPolicy':'never','sandboxPolicy':policy})
reply=await client.call('turn/start',{'threadId':t['thread_id'],'input':[{'type':'text','text':prompt}],'model':runtime.model,'effort':runtime.effort,'approvalPolicy':'never','sandboxPolicy':policy})
t['turn_id']=reply['turn']['id'];t['turn_started_at']=time.time()
event(t,'turn.started',{'turn_id':t['turn_id'],'production':production,'model':MODEL,'effort':EFFORT,'source_hash':fingerprint()})
event(t,'turn.started',{'turn_id':t['turn_id'],'production':production,'ai_provider':runtime.id,'model':runtime.model,'effort':runtime.effort,'source_hash':fingerprint(runtime)})
trace=directory/'evidence'/'codex-events.jsonl'
trace.parent.mkdir(exist_ok=True)
last_heartbeat=time.monotonic()
last_progress=time.monotonic()
last_error=None
active_tools=set()
tools_were_active=False
while True:
# A live transport/heartbeat is not evidence that the model is making
# progress. Native tool requests have their own execution timeouts.
tools_active=bool(client.requests or active_tools)
# Give a request that finished during the wait a fresh model idle
# window, rather than charging its execution time to the model.
if tools_active or tools_were_active:
last_progress=time.monotonic()
tools_were_active=tools_active
remaining=CODEX_IDLE_TIMEOUT-(time.monotonic()-last_progress)
if remaining<=0:
detail=' Last upstream error: '+last_error if last_error else ''
raise RuntimeError(f'Codex made no progress for {CODEX_IDLE_TIMEOUT} seconds. Check the model API address, authentication and network; the same session is retained for retry.'+detail)
try:
msg=await asyncio.wait_for(client.events.get(),30)
msg=await asyncio.wait_for(client.events.get(),min(30,remaining))
except asyncio.TimeoutError:
event(t,'heartbeat',{'turn_id':t['turn_id'],'elapsed':round(time.time()-t['turn_started_at'])})
continue
@@ -173,17 +236,30 @@ async def run_turn(t, prompt, production):
raise ConnectionError(p.get('message','Codex disconnected'))
if p.get('threadId') not in {None,t['thread_id']}:
continue
if p.get('turnId') not in {None,t['turn_id']}:
continue
# Store complete native event evidence; no lossy context reconstruction.
with trace.open('a') as f:
f.write(json.dumps(msg,ensure_ascii=False)+'\n')
if method=='item/completed':
if method.startswith('item/') or method=='thread/tokenUsage/updated':
last_progress=time.monotonic()
if method=='error':
last_error=codex_error(p.get('error'))
if p.get('willRetry'):
event(t,'session.reconnecting',{'message':last_error,'native_retry':True})
else:
raise RuntimeError(last_error)
elif method=='item/completed':
item=p.get('item',{})
active_tools.discard(item.get('id'))
if item.get('type')=='agentMessage':
event(t,'message',{'role':'assistant','text':item.get('text',''),'phase':item.get('phase')})
elif item.get('type') not in {'userMessage','reasoning'}:
event(t,'activity',{'kind':item.get('type'),'status':item.get('status'),'command':item.get('command'),'tool':item.get('tool')})
elif method=='item/started':
item=p.get('item',{})
if item.get('type') in NATIVE_TOOL_ITEMS and item.get('id'):
active_tools.add(item['id'])
if item.get('type') not in {'userMessage','agentMessage','reasoning'}:
event(t,'activity',{'kind':item.get('type'),'status':'running','command':item.get('command'),'tool':item.get('tool')})
elif method=='thread/tokenUsage/updated':
@@ -192,13 +268,24 @@ async def run_turn(t, prompt, production):
turn=p['turn']
event(t,'turn.completed',{'turn_id':turn['id'],'status':turn['status'],'error':turn.get('error')})
if turn['status']!='completed':
raise RuntimeError('Codex turn '+turn['status']+': '+json.dumps(turn.get('error'),ensure_ascii=False))
raise RuntimeError('Codex turn '+turn['status']+': '+codex_error(turn.get('error')))
return
async def work(t, prompt, production):
t['pending_prompt']=prompt
save(t)
try:
if production:
frozen(t)
report = await check_runtime(workspace(t))
event(t, 'runtime.checked', report)
with contextlib.suppress(OSError):
write(workspace(t) / 'evidence/runtime-check.json', report)
if not report['ok']:
raise RuntimeError('生产环境预检未通过:' + ';'.join(
item['message'] for item in report['checks'] if not item['ok']))
else:
await require_runtime_ready()
failures=0;no_progress=0
while True:
before=t.get('eda_calls',0)
@@ -255,6 +342,7 @@ def schedule(t,prompt,production):
@asynccontextmanager
async def lifespan(app):
TASKS.mkdir(parents=True,exist_ok=True)
readiness.start(force=True)
for p in TASKS.glob('*/state.json'):
t=json.loads(p.read_text());CACHE[t['id']]=t
if t['state'] not in {'completed','cancelled','blocked','failed'} and (t.get('busy') or t['state'] in {'running','planning','interrupted'}):
@@ -265,27 +353,60 @@ async def lifespan(app):
for job in list(JOBS.values()):
job.cancel()
await asyncio.gather(*list(JOBS.values()),return_exceptions=True)
await readiness.close()
app=FastAPI(lifespan=lifespan)
class Request(BaseModel):
text:str=Field(min_length=5,max_length=16000)
class DesignRequest(Request):
provider:str | None=None
class Approval(BaseModel):
revision:int
hash:str
@app.get('/api/health')
async def health():
return {'ok':True,'engine':'persistent-codex','model':MODEL,'effort':EFFORT,'source_hash':fingerprint(),'legacy_pipeline':False,'design_policy':DESIGN_POLICY,'validation_policy':VALIDATION_POLICY,'delivery_toolkit':1}
runtime=runtime_for()
return {'ok':True,'runtime_ready':readiness.snapshot()['ok'],'engine':'persistent-codex','model':runtime.model,'effort':runtime.effort,'source_hash':fingerprint(),'legacy_pipeline':False,'auth_mode':runtime.auth_mode,'model_provider':runtime.provider,'model_api_base_url':runtime.api_base_url if runtime.auth_mode=='apikey' else None,'default_provider':DEFAULT_PROVIDER,'design_policy':DESIGN_POLICY,'validation_policy':VALIDATION_POLICY,'delivery_toolkit':1}
@app.get('/api/readiness')
async def runtime_readiness():
readiness.start()
return JSONResponse(readiness.snapshot(), headers={'Cache-Control': 'no-store'})
@app.post('/api/readiness/check')
async def recheck_runtime():
# Coalesce concurrent visitors and throttle repeated manual retries.
recent = readiness.report and time.time() - readiness.report['checked_at'] < 5
readiness.start(force=not recent)
return JSONResponse(readiness.snapshot(), headers={'Cache-Control': 'no-store'})
@app.get('/api/ready')
async def deployment_ready():
report = readiness.snapshot()
return JSONResponse(report, status_code=200 if report['ok'] else 503,
headers={'Cache-Control': 'no-store'})
@app.get('/api/providers')
async def list_providers():
return {'default_provider':DEFAULT_PROVIDER,'providers':[provider_status(runtime_for(name)) for name in PROVIDERS]}
@app.get('/api/sessions')
async def list_sessions():
return sorted([public(t) for t in CACHE.values()],key=lambda t:t['created_at'],reverse=True)
@app.post('/api/sessions',status_code=201)
async def create(req:Request):
async def create(req:DesignRequest):
try:
runtime=runtime_for(req.provider)
except ValueError as e:
raise HTTPException(400,str(e)) from None
if not provider_status(runtime)['configured']:
raise HTTPException(503,runtime.label+' 未配置可用的服务端凭据,请先配置 '+runtime.key_name+' 或对应登录文件。')
await require_runtime_ready(force=True)
tid='pcb-'+uuid.uuid4().hex[:24]
t={'id':tid,'request':req.text,'created_at':time.time(),'state':'planning','cursor':0,'model':MODEL,'effort':EFFORT,'busy':False,'design_policy':DESIGN_POLICY}
t={'id':tid,'request':req.text,'created_at':time.time(),'state':'planning','cursor':0,'model':runtime.model,'effort':runtime.effort,'provider':runtime.provider,'ai_provider':runtime.id,'runtime':runtime.snapshot(),'busy':False,'design_policy':DESIGN_POLICY,'validation_policy':VALIDATION_POLICY}
directory=workspace(t);directory.mkdir(parents=True)
for name in ('artifacts','evidence','scripts','tmp'):
(directory/name).mkdir()
@@ -310,6 +431,10 @@ async def comment(tid:str,req:Request):
t=get(tid)
if t.get('approval') or t['state'] not in {'review','needs_input','failed'} or t.get('busy'):
raise HTTPException(409,'Comments are allowed only while reviewing a proposal')
cursor=t['cursor']
await require_runtime_ready()
if t['cursor']!=cursor:
raise HTTPException(409,'Task changed during environment check; reload before retrying')
event(t,'message',{'role':'user','text':req.text})
schedule(t,'User review comment:\n'+req.text+'\nRevise the proposal in this same conversation and publish a replacement with pcb_proposal. This is not production authorization.',False)
return public(t)
@@ -324,8 +449,12 @@ async def approve(tid:str,req:Approval):
raise HTTPException(409,'Different proposal already approved')
if t['state']!='review' or t.get('busy') or p.get('revision')!=req.revision or p.get('hash')!=req.hash:
raise HTTPException(409,'Approve the latest completed proposal revision')
cursor=t['cursor']
await require_runtime_ready(force=True)
if t['cursor']!=cursor:
raise HTTPException(409,'Task changed during environment check; reload before approving')
t['approval']={'revision':req.revision,'hash':req.hash,'at':time.time()}
t['frozen_source']=fingerprint()
t['frozen_source']=fingerprint(task_runtime(t))
t['design_policy']=DESIGN_POLICY
event(t,'proposal.approved',t['approval'])
prompt=f'''The user explicitly clicked APPROVE AND START for proposal revision {req.revision}, SHA256 {req.hash}.
@@ -333,7 +462,7 @@ This server-owned approval authorizes production of the accepted proposal in thi
Workspace: {workspace(t)}
Official API documentation: {workspace(t)}/api-reference/references/_index.md
{POLICY_TEXT}
Blender: /snap/bin/blender (render exported native 3D geometry only).
Blender: {shlex.quote(BLENDER_BIN)} (render exported native 3D geometry only).
Now use native Codex tools and pcb_eda to implement, inspect, fix, route, verify and export the real board. You write the design scripts yourself. No fixed backend design pipeline exists. Keep working until pcb_deliver accepts native project, schematic, layout, assembled STEP and real 3D render. Do not edit backend code or use legacy PCB flows. Backend source is frozen for this run.
Accepted proposal:\n{p['markdown']}'''
schedule(t,prompt,True)
@@ -363,6 +492,10 @@ async def resume(tid:str):
frozen(t)
except RuntimeError as e:
raise HTTPException(409,str(e))
cursor=t['cursor']
await require_runtime_ready(force=True)
if t['cursor']!=cursor:
raise HTTPException(409,'Task changed during environment check; reload before resuming')
t['check_eda_session']=bool(t.get('eda_session'))
event(t,'task.resume_requested',{})
schedule(t,'The user requests continuing this same task. Preserve the accepted design and inspect actual saved files and EDA state. Continue to verified delivery.' if t.get('approval') else 'Continue the proposal review and publish a complete proposal.',bool(t.get('approval')))
+12
View File
@@ -0,0 +1,12 @@
# Optional local build downloads
The Dockerfile uses `freerouting.jar` and `LICENSE.freerouting` from this directory
when present, otherwise it downloads the pinned release. The JAR is always
verified against the SHA-256 in the Dockerfile.
Run `python3 scripts/package-pcb-backend.py --with-freerouting` on a machine that
can reach GitHub to include these files in the upload archive. The download is
cached under `dist/pcb-backend-downloads`, not committed into source control.
Debian, Python and npm downloads use the configurable mirrors in
`codex_pcb/compose.yaml`. No API keys belong in this directory or build args.
+36
View File
@@ -0,0 +1,36 @@
name: vibemake-pcb
services:
pcb-backend:
image: vibemake-pcb-backend:local
build:
context: ..
dockerfile: codex_pcb/Dockerfile
args:
DEBIAN_MIRROR: http://mirrors.tuna.tsinghua.edu.cn/debian
DEBIAN_SECURITY_MIRROR: http://mirrors.tuna.tsinghua.edu.cn/debian-security
NPM_REGISTRY: https://registry.npmmirror.com
PIP_INDEX_URL: https://mirrors.ustc.edu.cn/pypi/simple
restart: unless-stopped
env_file:
- .env.local
ports:
- "127.0.0.1:8003:8003"
volumes:
- pcb-data:/data
- type: bind
source: ../vendor/lceda-pro
target: /opt/lceda-pro
read_only: true
bind:
create_host_path: false
shm_size: "1gb"
stop_grace_period: 30s
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
volumes:
pcb-data:
+93
View File
@@ -0,0 +1,93 @@
"""Deployment settings; credentials are read separately and never fingerprinted."""
import os
from dataclasses import dataclass
from pathlib import Path
import shutil
from urllib.parse import urlsplit
def path_setting(name, default):
return Path(os.environ.get(name) or default).expanduser().resolve()
def executable(name, default):
value = os.environ.get(name) or default
return shutil.which(os.path.expanduser(value)) or os.path.expanduser(value)
PROVIDERS = {
'deepseek': ('DeepSeek', 'deepseek-flash', 'https://api.deepseek.com', 'DEEPSEEK_API_KEY', ()),
'openai': ('OpenAI', 'gpt-6.1-sol', 'https://api.vip1129.cc', 'OPENAI_API_KEY', ()),
'doubao': ('豆包', 'doubao-seed-2-1-pro-260915', 'https://ark.cn-beijing.volces.com/api/v3', 'ARK_API_KEY', ('DOUBAO_API_KEY',)),
}
DEFAULT_PROVIDER = os.environ.get('PCB_AI_PROVIDER') or 'openai'
def model_api_base_url(provider_id='openai'):
variable = f'PCB_{provider_id.upper()}_BASE_URL'
value = (os.environ.get(variable) or PROVIDERS[provider_id][2]).strip().rstrip('/')
try:
url = urlsplit(value)
valid = url.scheme in {'http', 'https'} and url.hostname and url.port != 0
except ValueError:
valid = False
if not valid or url.username or url.password or url.query or url.fragment:
raise ValueError(variable+' must be an HTTP(S) base URL without credentials, query or fragment')
return value
@dataclass(frozen=True)
class ModelRuntime:
id: str
label: str
model: str
effort: str
auth_mode: str
provider: str
api_base_url: str
key_name: str
key_aliases: tuple
def snapshot(self):
return {key: getattr(self, key) for key in ('id', 'model', 'effort', 'auth_mode', 'provider', 'api_base_url')}
def runtime_for(provider_id=None):
provider_id = provider_id or DEFAULT_PROVIDER
if provider_id not in PROVIDERS:
raise ValueError('Unknown PCB AI provider; choose deepseek, openai or doubao')
label, default_model, _, key, aliases = PROVIDERS[provider_id]
prefix = 'PCB_'+provider_id.upper()
legacy_model = os.environ.get('PCB_MODEL') if provider_id == DEFAULT_PROVIDER else None
model = os.environ.get(prefix+'_MODEL') or legacy_model or default_model
effort = os.environ.get(prefix+'_REASONING_EFFORT') or os.environ.get('PCB_REASONING_EFFORT') or 'high'
auth = (os.environ.get('PCB_CODEX_AUTH') or 'chatgpt') if provider_id == 'openai' else 'apikey'
provider = 'openai' if auth == 'chatgpt' else 'vibemake_'+provider_id
return ModelRuntime(provider_id, label, model, effort, auth, provider,
model_api_base_url(provider_id), key, aliases)
ROOT = path_setting('PCB_SESSION_ROOT', Path.home() / '.local/share/vibemake-pcb')
DEFAULT_RUNTIME = runtime_for()
MODEL, EFFORT = DEFAULT_RUNTIME.model, DEFAULT_RUNTIME.effort
AUTH_MODE, PROVIDER = DEFAULT_RUNTIME.auth_mode, DEFAULT_RUNTIME.provider
MODEL_API_BASE_URL = DEFAULT_RUNTIME.api_base_url
CODEX_IDLE_TIMEOUT = int(os.environ.get('PCB_CODEX_IDLE_TIMEOUT') or '300')
if CODEX_IDLE_TIMEOUT <= 0:
raise ValueError('PCB_CODEX_IDLE_TIMEOUT must be a positive number of seconds')
CODEX_HOME = path_setting('PCB_CODEX_HOME', ROOT / 'codex-home')
CODEX_BIN = executable('PCB_CODEX_BIN', 'codex')
EDA_BIN = executable('PCB_EDA_BIN', 'lceda-pro')
BLENDER_BIN = executable('PCB_BLENDER_BIN', 'blender')
FREEROUTING_JAR = path_setting('PCB_FREEROUTING_JAR', ROOT / 'resources/freerouting.jar')
def frozen_settings(runtime=None):
runtime = runtime or runtime_for()
# Key rotation is allowed; changing the runtime of an approved design is not.
return {name: str(value) for name, value in {
'root': ROOT, **runtime.snapshot(), 'codex_home': CODEX_HOME, 'codex_bin': CODEX_BIN,
'codex_idle_timeout': CODEX_IDLE_TIMEOUT,
'eda_bin': EDA_BIN, 'blender_bin': BLENDER_BIN,
'freerouting_jar': FREEROUTING_JAR,
}.items()}
+12
View File
@@ -0,0 +1,12 @@
#!/bin/sh
# Fail deployment unless the real runtime/EDA bridge healthcheck passes.
set -eu
cd "$(dirname "$0")/.."
if ! docker compose -f codex_pcb/compose.yaml up -d --build --wait --wait-timeout 240; then
printf '%s\n' 'PCB deployment failed: runtime is not ready. Inspect the failed checks below.' >&2
docker compose -f codex_pcb/compose.yaml ps || true
docker compose -f codex_pcb/compose.yaml logs --tail=100 pcb-backend || true
exit 1
fi
printf '%s\n' 'PCB deployment ready: filesystem, native sandbox and read-only EasyEDA bridge verified.'
+71
View File
@@ -0,0 +1,71 @@
#!/bin/sh
set -eu
fail() {
printf '%s\n' "PCB backend: $*" >&2
exit 1
}
# Allow diagnostics such as `docker compose run --rm pcb-backend codex --version`.
if [ "${1:-}" != python ] || [ "${2:-}" != -m ] || [ "${3:-}" != uvicorn ]; then
exec "$@"
fi
mkdir -p "$PCB_SESSION_ROOT" "$PCB_CODEX_HOME" "$HOME" "$XDG_RUNTIME_DIR" \
|| fail 'Cannot create runtime directories; check UID/GID 10001:10001 and volume ownership.'
chmod 700 "$XDG_RUNTIME_DIR"
for directory in "$PCB_SESSION_ROOT" "$PCB_CODEX_HOME" "$HOME"; do
probe=$(mktemp "$directory/.pcb-write-check.XXXXXX") \
|| fail "Runtime directory is not writable: $directory; check UID/GID 10001:10001 and read-only mounts."
rm "$probe"
done
if [ ! -e "$PCB_SESSION_ROOT/resources" ] && [ ! -L "$PCB_SESSION_ROOT/resources" ]; then
ln -s /opt/pcb-resources "$PCB_SESSION_ROOT/resources"
fi
[ -r "$PCB_SESSION_ROOT/resources/references/_index.md" ] || fail 'Missing EDA API references.'
[ -r "$PCB_FREEROUTING_JAR" ] || fail 'Missing Freerouting JAR.'
command -v "$PCB_CODEX_BIN" >/dev/null 2>&1 || fail 'Codex CLI not found; check PCB_CODEX_BIN.'
if [ -e "$PCB_EDA_BIN" ] && [ ! -x "$PCB_EDA_BIN" ]; then
fail 'EDA binary is not executable; fix permissions on the host vendor/lceda-pro directory (mounted read-only).'
fi
command -v "$PCB_EDA_BIN" >/dev/null 2>&1 || fail 'Mount the complete Linux EDA directory and check PCB_EDA_BIN.'
command -v "$PCB_BLENDER_BIN" >/dev/null 2>&1 || fail 'Blender not found; check PCB_BLENDER_BIN.'
# Validate credential presence without printing or writing its value.
python -c 'from codex_pcb.rpc import process_config; process_config(False)'
Xvfb "$DISPLAY" -screen 0 1920x1080x24 -nolisten tcp > /tmp/pcb-xvfb.log 2>&1 &
xvfb_pid=$!
app_pid=
cleanup() {
if [ -n "$app_pid" ]; then
kill -TERM "$app_pid" 2>/dev/null || true
wait "$app_pid" 2>/dev/null || true
fi
kill -TERM "$xvfb_pid" 2>/dev/null || true
wait "$xvfb_pid" 2>/dev/null || true
}
trap cleanup EXIT
trap 'exit 143' TERM
trap 'exit 130' INT
ready=0
for attempt in 1 2 3 4 5 6 7 8 9 10; do
kill -0 "$xvfb_pid" 2>/dev/null || fail 'Xvfb exited; inspect /tmp/pcb-xvfb.log.'
if xdpyinfo -display "$DISPLAY" >/dev/null 2>&1; then
ready=1
break
fi
sleep 1
done
[ "$ready" = 1 ] || fail 'Virtual display did not become ready.'
"$@" &
app_pid=$!
set +e
wait "$app_pid"
status=$?
set -e
app_pid=
exit "$status"
+30 -12
View File
@@ -6,6 +6,8 @@ import json
import os
import time
import uuid
import tempfile
from .config import EDA_BIN
from pathlib import Path
from .storage import ROOT, workspace, task_dir, inside, save, write, event, digest
from .native_policy import guarded_script, validate_export_name
@@ -14,28 +16,44 @@ from .checks import evaluate_verification
EDA_LOCK = asyncio.Lock()
async def cli(args, code=None, timeout=210):
env = dict(os.environ, DISPLAY=os.environ.get('DISPLAY',':0'), XDG_RUNTIME_DIR=f'/run/user/{os.getuid()}')
async def cli(args, code=None, timeout=210, *, binary=None, directory=None, environment=None):
env = dict(os.environ if environment is None else environment)
env.setdefault('DISPLAY', ':0')
env.setdefault('XDG_RUNTIME_DIR', f'/run/user/{os.getuid()}')
for key in ('OPENAI_API_KEY', 'OPENAI_API_KEY_FILE', 'DEEPSEEK_API_KEY', 'DEEPSEEK_API_KEY_FILE', 'ARK_API_KEY', 'ARK_API_KEY_FILE', 'DOUBAO_API_KEY', 'DOUBAO_API_KEY_FILE', 'CODEX_API_KEY', 'CODEX_API_KEY_FILE'):
env.pop(key, None)
if not env.get('XAUTHORITY'):
auth = list(Path(f'/run/user/{os.getuid()}').glob('.mutter-Xwaylandauth.*'))
if auth:
env['XAUTHORITY'] = str(auth[0])
p = await asyncio.create_subprocess_exec('/usr/local/bin/lceda-pro', *args, '--no-sandbox', stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env=env, cwd=ROOT)
try:
out, err = await asyncio.wait_for(p.communicate(code.encode() if code is not None else None),timeout)
except (asyncio.TimeoutError, asyncio.CancelledError):
p.kill()
await p.wait()
raise RuntimeError('EDA command outcome unknown; inspect live state before retrying mutations')
# Electron may leave a resident activation window/helper with inherited
# output handles. Pipes then never reach EOF even after the CLI exits.
# Private files let us wait for the actual command and retain its JSON error.
with tempfile.TemporaryFile() as stdout, tempfile.TemporaryFile() as stderr:
p = await asyncio.create_subprocess_exec(binary or EDA_BIN, *args, '--no-sandbox',
stdin=asyncio.subprocess.PIPE if code is not None else asyncio.subprocess.DEVNULL,
stdout=stdout, stderr=stderr, env=env, cwd=directory or ROOT)
try:
await asyncio.wait_for(p.communicate(code.encode() if code is not None else None), timeout)
except (asyncio.TimeoutError, asyncio.CancelledError):
try:
p.kill()
except ProcessLookupError:
pass
await p.communicate()
raise RuntimeError('EDA command outcome unknown; inspect live state before retrying mutations')
stdout.seek(0)
stderr.seek(0)
out, err = stdout.read(), stderr.read()
try:
result = json.loads(out)
except ValueError:
raise RuntimeError('EDA returned non-JSON: '+err.decode(errors='replace')[-1500:]) from None
if p.returncode or result.get('ok') is not True:
if not isinstance(result, dict) or p.returncode or result.get('ok') is not True:
raise RuntimeError('EDA native error: '+json.dumps(result,ensure_ascii=False)[:6000])
return result.get('value')
async def host_lock():
async def host_lock(timeout=240):
path = Path.home()/'.local/state/ai-pcb-eda/locks/host.lock'
path.parent.mkdir(parents=True,exist_ok=True)
fd = path.open('a+')
@@ -45,7 +63,7 @@ async def host_lock():
fcntl.flock(fd,fcntl.LOCK_EX|fcntl.LOCK_NB)
return fd
except BlockingIOError:
if time.monotonic()-started > 240:
if time.monotonic()-started > timeout:
fd.close()
raise RuntimeError('EDA host occupied by another task; no mutation executed')
await asyncio.sleep(1)
+2 -1
View File
@@ -8,6 +8,7 @@ import stat
import uuid
import zipfile
from .storage import SOURCE, workspace, inside, write, event
from .config import BLENDER_BIN
from .eda import execute, verify_native
@@ -58,7 +59,7 @@ async def render_obj(t, source, folder):
if len(objects)!=1:raise ValueError('Expected one native Outfit OBJ, found '+str(len(objects)))
output=folder/'assembly.png'
log=folder/'render.log'
blender=os.environ.get('PCB_BLENDER_BIN','/snap/bin/blender')
blender=BLENDER_BIN
with log.open('wb') as stream:
proc=await asyncio.create_subprocess_exec(blender,'-b','-t','2','--python',str(SOURCE/'render_assembly.py'),'--',str(objects[0]),str(output),cwd=workspace(t),stdout=stream,stderr=stream)
try:await asyncio.wait_for(proc.wait(),180)
+31
View File
@@ -0,0 +1,31 @@
"""Non-secret native model metadata for Responses-compatible providers."""
import hashlib
import json
def catalog_path(home, runtime):
identity = json.dumps(runtime.snapshot(), sort_keys=True).encode()
return home/'model-catalogs'/(hashlib.sha256(identity).hexdigest()+'.json')
def catalog(runtime):
vision = runtime.id == 'doubao' or runtime.model == 'deepseek-flash'
return {'models': [{
'slug': runtime.model, 'display_name': runtime.label+' · '+runtime.model,
'description': 'PCB design through native Codex tools and server-approved EDA operations.',
'default_reasoning_level': runtime.effort,
'supported_reasoning_levels': [{'effort': runtime.effort, 'description': 'Configured reasoning level'}],
'shell_type': 'shell_command', 'visibility': 'list', 'supported_in_api': True,
'priority': 0, 'prefer_websockets': False, 'upgrade': None,
'base_instructions': 'You are a PCB engineering assistant. Follow the developer instructions, user requirements and server approval boundaries.',
'supports_reasoning_summaries': False, 'default_reasoning_summary': 'none',
'support_verbosity': False, 'default_verbosity': None,
'apply_patch_tool_type': None, 'truncation_policy': {'mode': 'bytes', 'limit': 10000},
'supports_parallel_tool_calls': True, 'supports_image_detail_original': False,
'supports_standalone_web_search': runtime.id == 'deepseek',
'context_window': 1000000 if runtime.id == 'deepseek' else 128000,
'auto_compact_token_limit': 800000 if runtime.id == 'deepseek' else 100000,
'effective_context_window_percent': 95, 'experimental_supported_tools': [],
'input_modalities': ['text', 'image'] if vision else ['text'],
'tool_mode': None, 'supports_search_tool': False,
}]}
+203
View File
@@ -0,0 +1,203 @@
"""Check real production permissions without a model call or design mutation."""
import asyncio
import contextlib
import fcntl
import json
import os
from pathlib import Path
import sys
import tempfile
from .config import ROOT, CODEX_HOME, CODEX_BIN, EDA_BIN, BLENDER_BIN, FREEROUTING_JAR
from .rpc import SECRET_ENV_NAMES, sandbox_settings
from .eda import cli as eda_cli, EDA_LOCK, host_lock
def result(name, ok, message):
return {'name': name, 'ok': ok, 'message': message}
def writable(name, directory):
try:
directory.mkdir(mode=0o700, parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix='.pcb-write-check-', dir=directory) as temporary:
source = Path(temporary) / 'probe.tmp'
target = source.with_suffix('.json')
source.write_text('pcb-preflight')
source.replace(target)
if target.read_text() != 'pcb-preflight':
raise OSError('write/read verification failed')
return result(name, True, str(directory) + ' 可创建、写入和重命名文件')
except OSError as error:
return result(name, False, f'{directory} 无法写入:{error};检查容器 UID/GID、目录属主及只读挂载')
def executable(name, binary):
try:
ready = Path(binary).is_file() and os.access(binary, os.X_OK)
except OSError:
ready = False
if not ready:
return result(name, False, f'{binary} 不存在或当前用户无执行权限;检查完整 Linux 应用目录、chmod、父目录访问权限及 noexec 挂载')
return result(name, True, str(binary) + ' 存在且具备执行权限;仍需实际启动验证')
def readable(name, path):
try:
ready = path.is_file() and os.access(path, os.R_OK)
return result(name, ready, str(path) + (' 可读取' if ready else ' 不存在或当前用户无读取权限'))
except OSError as error:
return result(name, False, f'{path} 无法读取:{error}')
def safe_environment():
env = dict(os.environ, CODEX_HOME=str(CODEX_HOME))
for name in SECRET_ENV_NAMES:
env.pop(name, None)
return env
async def command(args, directory, env, timeout=30):
process = await asyncio.create_subprocess_exec(
*args, cwd=directory, env=env,
stdin=asyncio.subprocess.DEVNULL,
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE,
start_new_session=True)
try:
stdout, stderr = await asyncio.wait_for(process.communicate(), timeout)
except (asyncio.TimeoutError, asyncio.CancelledError):
# The CLI may have children (including bubblewrap/Electron).
import signal
with contextlib.suppress(ProcessLookupError):
os.killpg(process.pid, signal.SIGKILL)
await process.communicate()
raise
return process.returncode, (stderr or stdout).decode(errors='replace')[-1600:]
async def sandbox_check(directory, env):
try:
with tempfile.TemporaryDirectory(prefix='.pcb-sandbox-check-', dir=directory / 'tmp') as temporary:
marker = Path(temporary) / 'written.txt'
# The pinned CLI reserves -C for named permission profiles. The
# subprocess cwd already supplies the workspace for legacy settings.
args = [CODEX_BIN, 'sandbox']
settings = dict(sandbox_settings(True), **{
'sandbox_workspace_write.writable_roots': [str(directory)],
})
for key, value in settings.items():
args += ['-c', key + '=' + json.dumps(value)]
args += ['--', '/bin/sh', '-c', 'printf pcb-preflight > "$1"', 'pcb-preflight', str(marker)]
code, output = await command(args, directory, env)
if code != 0 or not marker.is_file() or marker.read_text() != 'pcb-preflight':
return result('codex_sandbox', False,
f'Codex 原生沙箱未能写入授权工作区(exit={code}):{output};'
'若包含 bwrap/namespace,需检查宿主机 user namespace、seccomp、AppArmor 策略')
return result('codex_sandbox', True, '原生 workspace-write 沙箱已实际创建文件;未调用模型')
except (OSError, asyncio.TimeoutError) as error:
return result('codex_sandbox', False, f'Codex 沙箱检测失败:{type(error).__name__}: {error}')
async def eda_check(directory, env):
try:
code, output = await command([EDA_BIN, '--help', '--no-sandbox'], directory, env)
if code != 0:
return result('eda_launch', False, f'EasyEDA --help 启动失败(exit={code}):{output}')
return result('eda_launch', True, 'EasyEDA --help 已实际启动;未创建或修改设计,不代表登录/绘板验收通过')
except (OSError, asyncio.TimeoutError) as error:
return result('eda_launch', False,
f'EasyEDA 无法启动:{type(error).__name__}: {error};检查执行权限、noexec、CPU 架构和动态库')
async def eda_bridge_check(directory, env):
"""Open only our blank diagnostic session; never touch an existing project."""
session = None
fd = None
locked = False
checks = []
options = {'binary': EDA_BIN, 'directory': ROOT, 'environment': env}
try:
await asyncio.wait_for(EDA_LOCK.acquire(), 10)
locked = True
fd = await host_lock(timeout=10)
opened = await eda_cli(['open', '--headless', 'true'], timeout=90, **options)
if not isinstance(opened, dict) or not isinstance(opened.get('sessionId'), str) or not opened['sessionId']:
raise RuntimeError('EasyEDA 未返回诊断会话 ID;未操作其他会话')
session = opened['sessionId']
value = await eda_cli(['invoke', '--session', session, '--ext-uuid', 'eda',
'--code-file', '-', '--timeout', '20000'],
'return {client: eda.sys_Environment.isClient(), version: eda.sys_Environment.getEditorCurrentVersion()};',
timeout=35, **options)
if not isinstance(value, dict) or value.get('client') is not True or not isinstance(value.get('version'), str) or not value['version'].strip():
raise RuntimeError('只读 EDA API 未返回有效的客户端标识及编辑器版本')
checks.append(result('eda_bridge', True,
f'独立空白会话及只读 EDA API 已验证,编辑器版本:{value["version"]}'))
except (OSError, RuntimeError, asyncio.TimeoutError) as error:
checks.append(result('eda_bridge', False,
f'EasyEDA 命令桥接不可用:{type(error).__name__}: {error};'
'确认客户端已激活并完成首次启动,再检查 CLI 与 pro-api 配套版本、显示服务和 HOME 日志权限'))
finally:
if session:
try:
await eda_cli(['session', 'close', '--session', session, '--destroy'], timeout=20, **options)
except (OSError, RuntimeError, asyncio.TimeoutError) as error:
checks.append(result('eda_cleanup', False, f'诊断会话未能关闭:{error};未关闭其他设计会话'))
if fd:
fcntl.flock(fd, fcntl.LOCK_UN)
fd.close()
if locked:
EDA_LOCK.release()
return checks
async def check_runtime(directory):
directory = Path(directory).resolve()
checks = [writable(name, path) for name, path in (
('runtime_write', ROOT), ('home_write', Path.home()),
('codex_home_write', CODEX_HOME), ('workspace_write', directory),
('temporary_write', directory / 'tmp'))]
programs = {name: executable(name, binary) for name, binary in (
('codex_binary', CODEX_BIN), ('eda_binary', EDA_BIN), ('blender_binary', BLENDER_BIN))}
checks.extend(programs.values())
for name, path in (('api_references', ROOT / 'resources/references/_index.md'),):
checks.append(readable(name, path))
env = safe_environment()
# EasyEDA uses the host temporary directory for its persistent IPC socket.
# A disposable probe/task directory breaks discovery across CLI calls (and
# long paths can exceed the macOS Unix-socket limit). Only sandbox probes
# need their temporary files confined to the diagnostic workspace.
sandbox_env = dict(env, TMPDIR=str(directory / 'tmp'),
TMP=str(directory / 'tmp'), TEMP=str(directory / 'tmp'))
# Run both checks even if another dependency failed, to report independent blockers.
if programs['codex_binary']['ok']:
checks.append(await sandbox_check(directory, sandbox_env))
if programs['eda_binary']['ok']:
launch = await eda_check(directory, env)
checks.append(launch)
if launch['ok']:
checks.extend(await eda_bridge_check(directory, env))
return {'ok': all(item['ok'] for item in checks), 'checks': checks,
'scope': 'filesystem, native sandbox, EDA startup and read-only bridge; no model call or design created'}
async def check_environment():
try:
# Keep probes separate from saved tasks, and remove all diagnostic files.
parent = ROOT / 'tasks'
parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix='.pcb-preflight-', dir=parent) as temporary:
report = await check_runtime(Path(temporary))
except OSError as error:
report = {'ok': False, 'checks': [result('workspace_write', False,
f'{ROOT / "tasks"} 无法创建诊断工作区:{error};检查 UID/GID 及挂载权限')]}
return report
async def main():
report = await check_environment()
print(json.dumps(report, ensure_ascii=False, indent=2))
return 0 if report['ok'] else 1
if __name__ == '__main__':
sys.exit(asyncio.run(main()))
+65
View File
@@ -0,0 +1,65 @@
"""Single-flight deployment readiness; fail closed before spending a model turn."""
import asyncio
import contextlib
import json
import logging
import time
from .config import ROOT
from .preflight import check_environment
from .storage import write
logger = logging.getLogger('uvicorn.error')
class RuntimeReadiness:
def __init__(self, checker=None, ttl=300):
self.checker = checker or check_environment
self.ttl = ttl
self.report = None
self.job = None
def snapshot(self):
checking = self.job is not None and not self.job.done()
report = self.report or {'ok': False, 'checks': [], 'checked_at': None}
return {**report, 'ok': bool(report['ok']) and not checking,
'status': 'checking' if checking or self.report is None else 'ready' if report['ok'] else 'unavailable'}
def start(self, force=False):
if self.job is not None and not self.job.done():
return self.job
if self.report and not force and time.time() - self.report['checked_at'] < self.ttl:
return None
self.job = asyncio.create_task(self._run())
return self.job
async def _run(self):
try:
report = await asyncio.wait_for(self.checker(), 200)
except asyncio.CancelledError:
raise
except Exception as error:
report = {'ok': False, 'checks': [{'name': 'runtime_check', 'ok': False,
'message': f'环境检查无法完成:{type(error).__name__}: {error}'}]}
self.report = {**report, 'checked_at': time.time()}
with contextlib.suppress(OSError):
write(ROOT / 'runtime-readiness.json', self.report)
if report['ok']:
logger.info('PCB runtime ready: filesystem, sandbox and read-only EDA bridge verified.')
else:
logger.error('PCB runtime NOT READY: %s', json.dumps(
[item for item in report['checks'] if not item['ok']], ensure_ascii=False))
async def verify(self, force=False):
job = self.start(force=force)
if job:
await asyncio.shield(job)
return self.snapshot()
async def close(self):
if self.job is not None and not self.job.done():
self.job.cancel()
await asyncio.gather(self.job, return_exceptions=True)
readiness = RuntimeReadiness()
+3
View File
@@ -0,0 +1,3 @@
fastapi==0.162.0
uvicorn==0.54.0
-r requirements-delivery.txt
+94 -26
View File
@@ -3,39 +3,105 @@ import asyncio
import json
import os
from pathlib import Path
from .storage import ROOT, MODEL, EFFORT
from .config import CODEX_BIN, CODEX_HOME, runtime_for
from .models import catalog, catalog_path
from .storage import write
SECRET_ENV_NAMES = tuple(name for key in ('OPENAI_API_KEY', 'DEEPSEEK_API_KEY', 'ARK_API_KEY', 'DOUBAO_API_KEY', 'CODEX_API_KEY') for name in (key, key+'_FILE'))
def sandbox_settings(production):
return {
'approval_policy': 'never',
'sandbox_mode': 'workspace-write' if production else 'read-only',
'features.shell_tool': production, 'features.multi_agent': False,
'sandbox_workspace_write.network_access': True,
'sandbox_workspace_write.exclude_slash_tmp': True,
'sandbox_workspace_write.exclude_tmpdir_env_var': True,
}
def api_key(runtime=None):
runtime = runtime or runtime_for()
names = (runtime.key_name, *runtime.key_aliases)
key = next((os.environ[name].strip() for name in names if os.environ.get(name, '').strip()), '')
file_name = next((name+'_FILE' for name in names if os.environ.get(name+'_FILE')), None)
if not key and file_name:
try:
with Path(os.environ[file_name]).expanduser().open() as stream:
key = stream.read(16385).strip()
except (OSError, UnicodeError):
raise ValueError('Cannot read '+file_name) from None
if not key:
raise ValueError(runtime.label+' requires '+runtime.key_name+' or '+runtime.key_name+'_FILE')
if len(key) > 16384 or any(c.isspace() for c in key):
raise ValueError(runtime.label+' API key must be a single non-empty value')
return key
def process_config(production, runtime=None):
runtime = runtime or runtime_for()
if runtime.auth_mode not in {'apikey', 'chatgpt'}:
raise ValueError('PCB_CODEX_AUTH must be apikey or chatgpt')
config = {
'model': runtime.model, 'model_provider': runtime.provider, 'model_reasoning_effort': runtime.effort,
**sandbox_settings(production),
'web_search': 'live' if runtime.id == 'openai' else 'disabled',
'shell_environment_policy.ignore_default_excludes': False,
}
env = dict(os.environ, CODEX_HOME=str(CODEX_HOME))
for key in (*SECRET_ENV_NAMES, 'OPENAI_BASE_URL'):
env.pop(key, None)
if runtime.auth_mode == 'apikey':
env[runtime.key_name] = api_key(runtime)
prefix = 'model_providers.' + runtime.provider + '.'
config.update({
prefix + 'name': 'VibeMake '+runtime.label,
prefix + 'base_url': runtime.api_base_url,
prefix + 'wire_api': 'responses',
prefix + 'env_key': runtime.key_name,
prefix + 'requires_openai_auth': False,
})
if runtime.id != 'openai':
config['model_catalog_json'] = str(catalog_path(CODEX_HOME, runtime))
if runtime.id == 'deepseek':
config['web_search'] = 'live'
config['features.standalone_web_search'] = True
args = [CODEX_BIN, 'app-server', '--listen', 'stdio://']
for key, value in config.items():
args += ['-c', key + '=' + json.dumps(value)]
return args, env
CODEX = os.environ.get('PCB_CODEX_BIN', '/home/wpz/auto_pcb_2/vibemake-pcb-studio/backend/.cache/codex-cli/node_modules/.bin/codex')
class AppServer:
def __init__(self, directory, production, handler):
def __init__(self, directory, production, handler, runtime=None):
self.directory, self.production, self.handler = directory, production, handler
self.pending, self.requests, self.counter = {}, set(), 0
self.events = asyncio.Queue()
self.proc = None
self.reader = None
self.err = None
self.runtime = runtime or runtime_for()
async def __aenter__(self):
config = {
'model': MODEL, 'model_reasoning_effort': EFFORT,
'approval_policy': 'never', 'web_search': 'live',
'sandbox_mode': 'workspace-write' if self.production else 'read-only',
'features.shell_tool': self.production,
'features.multi_agent': False,
'sandbox_workspace_write.network_access': True,
'sandbox_workspace_write.exclude_slash_tmp': True,
'sandbox_workspace_write.exclude_tmpdir_env_var': True,
}
args = [CODEX, 'app-server', '--listen', 'stdio://']
for k,v in config.items():
args += ['-c', k + '=' + json.dumps(v)]
env = dict(os.environ, CODEX_HOME=str(ROOT / 'codex-home'))
for key in ('OPENAI_API_KEY','DEEPSEEK_API_KEY','CODEX_API_KEY'):
env.pop(key, None)
args, env = process_config(self.production, self.runtime)
# Production excludes system temp directories from writable roots.
# Keep native shell/tool temporary files in this task's writable root.
temporary = self.directory / 'tmp'
temporary.mkdir(exist_ok=True)
env.update(TMPDIR=str(temporary), TMP=str(temporary), TEMP=str(temporary))
CODEX_HOME.mkdir(parents=True, exist_ok=True, mode=0o700)
if self.runtime.id != 'openai':
write(catalog_path(CODEX_HOME, self.runtime), catalog(self.runtime))
self.err = (self.directory / 'codex-stderr.log').open('ab')
self.proc = await asyncio.create_subprocess_exec(*args, stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=self.err, env=env, cwd=self.directory, limit=64*1024*1024)
self.reader = asyncio.create_task(self._read())
await self.call('initialize', {'clientInfo': {'name':'vibemake_persistent_pcb','title':'VibeMake Persistent PCB','version':'1.0.0'}, 'capabilities':{'experimentalApi':True}})
await self.send({'method':'initialized'})
try:
self.proc = await asyncio.create_subprocess_exec(*args, stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=self.err, env=env, cwd=self.directory, limit=64*1024*1024)
self.reader = asyncio.create_task(self._read())
await self.call('initialize', {'clientInfo': {'name':'vibemake_persistent_pcb','title':'VibeMake Persistent PCB','version':'1.0.0'}, 'capabilities':{'experimentalApi':True}})
await self.send({'method':'initialized'})
except BaseException:
await self.__aexit__()
raise
return self
async def send(self, message):
@@ -100,6 +166,8 @@ class AppServer:
except asyncio.TimeoutError:
self.proc.kill()
await self.proc.wait()
self.reader.cancel()
await asyncio.gather(self.reader,return_exceptions=True)
self.err.close()
if self.reader:
self.reader.cancel()
await asyncio.gather(self.reader,return_exceptions=True)
if self.err:
self.err.close()
+4 -5
View File
@@ -4,18 +4,17 @@ import os
import re
import time
from pathlib import Path
from .config import ROOT, MODEL, EFFORT, frozen_settings
SOURCE = Path(__file__).parent.resolve()
ROOT = Path(os.environ.get('PCB_SESSION_ROOT', '/home/wpz/auto_pcb_2/persistent-runtime')).resolve()
TASKS = ROOT / 'tasks'
MODEL = 'gpt-6.1-sol'
EFFORT = 'high'
def digest(data):
return hashlib.sha256(data).hexdigest()
def fingerprint():
return digest(b''.join(p.name.encode() + p.read_bytes() for p in sorted(SOURCE.iterdir()) if p.suffix in {'.py', '.md'}))
def fingerprint(runtime=None):
source = b''.join(p.name.encode() + p.read_bytes() for p in sorted(SOURCE.iterdir()) if p.suffix in {'.py', '.md'})
return digest(source + json.dumps(frozen_settings(runtime), sort_keys=True).encode())
def write(path, value):
path = Path(path)
+138
View File
@@ -0,0 +1,138 @@
"""Exercise startup/shutdown using fake programs; no Docker or EDA required."""
import os
from pathlib import Path
import signal
import subprocess
import sys
import tempfile
import time
import unittest
ENTRYPOINT = Path(__file__).resolve().parents[1] / 'docker-entrypoint.sh'
REPOSITORY = ENTRYPOINT.parents[1]
class ContainerStartup(unittest.TestCase):
def setUp(self):
self.temporary = tempfile.TemporaryDirectory()
self.addCleanup(self.temporary.cleanup)
self.root = Path(self.temporary.name)
self.bin = self.root / 'bin'
self.bin.mkdir()
resources = self.root / 'data/resources/references'
resources.mkdir(parents=True)
(resources / '_index.md').write_text('Test reference index')
self.jar = self.root / 'router.jar'
self.jar.touch()
self.env = {
'PATH': str(self.bin) + os.pathsep + os.defpath,
'HOME': str(self.root / 'home'),
'PYTHONPATH': str(REPOSITORY),
'PCB_SESSION_ROOT': str(self.root / 'data'),
'PCB_CODEX_HOME': str(self.root / 'codex-home'),
'PCB_CODEX_AUTH': 'apikey',
'OPENAI_API_KEY': 'unit-test-api-credential',
'PCB_AI_PROVIDER': 'openai',
'PCB_FREEROUTING_JAR': str(self.jar),
'PCB_CODEX_BIN': str(self.bin / 'codex'),
'PCB_EDA_BIN': str(self.bin / 'lceda-pro'),
'PCB_BLENDER_BIN': str(self.bin / 'blender'),
'DISPLAY': ':99', 'XDG_RUNTIME_DIR': str(self.root / 'xdg'),
'TEST_ROOT': str(self.root), 'APP_EXIT_CODE': '7',
}
for name in ('codex', 'lceda-pro', 'blender'):
self.program(name, 'pass\n')
self.program('python', '''import os,sys,time
from pathlib import Path
if sys.argv[1:2] == ['-c']:
os.execv(sys.executable, [sys.executable, *sys.argv[1:]])
Path(os.environ['TEST_ROOT'],'app.pid').write_text(str(os.getpid()))
if os.environ.get('APP_WAIT'):
while True:time.sleep(1)
sys.exit(int(os.environ['APP_EXIT_CODE']))
''')
self.program('Xvfb', '''import os,time
from pathlib import Path
Path(os.environ['TEST_ROOT'],'xvfb.pid').write_text(str(os.getpid()))
while True:time.sleep(1)
''')
self.program('xdpyinfo', '''import os,sys
from pathlib import Path
sys.exit(0 if Path(os.environ['TEST_ROOT'],'xvfb.pid').exists() else 1)
''')
def program(self, name, body):
path = self.bin / name
path.write_text(f'#!{sys.executable}\n' + body)
path.chmod(0o755)
def command(self):
return ['/bin/sh', str(ENTRYPOINT), 'python', '-m', 'uvicorn', 'codex_pcb.app:app']
def assert_process_gone(self, filename):
pid = int((self.root / filename).read_text())
with self.assertRaises(ProcessLookupError):
os.kill(pid, 0)
def test_diagnostic_command_bypasses_runtime_requirements(self):
result = subprocess.run(['/bin/sh', str(ENTRYPOINT), '/bin/echo', 'diagnostic'],
env={}, capture_output=True, text=True, timeout=5)
self.assertEqual(result.returncode, 0)
self.assertEqual(result.stdout.strip(), 'diagnostic')
def test_missing_eda_fails_before_display_or_app_start(self):
(self.bin / 'lceda-pro').unlink()
result = subprocess.run(self.command(), env=self.env, cwd=REPOSITORY,
capture_output=True, text=True, timeout=5)
self.assertEqual(result.returncode, 1)
self.assertIn('Mount the complete Linux EDA directory', result.stderr)
self.assertNotIn('unit-test-api-credential', result.stderr)
self.assertFalse((self.root / 'xvfb.pid').exists())
self.assertFalse((self.root / 'app.pid').exists())
def test_nonexecutable_eda_has_actionable_error_before_app_start(self):
(self.bin / 'lceda-pro').chmod(0o644)
result = subprocess.run(self.command(), env=self.env, cwd=REPOSITORY,
capture_output=True, text=True, timeout=5)
self.assertEqual(result.returncode, 1)
self.assertIn('EDA binary is not executable', result.stderr)
self.assertIn('host vendor/lceda-pro', result.stderr)
self.assertFalse((self.root / 'app.pid').exists())
def test_application_exit_preserves_status_and_stops_display(self):
result = subprocess.run(self.command(), env=self.env, cwd=REPOSITORY,
capture_output=True, text=True, timeout=8)
self.assertEqual(result.returncode, 7, result.stderr)
self.assert_process_gone('xvfb.pid')
self.assert_process_gone('app.pid')
self.assertEqual((self.root / 'xdg').stat().st_mode & 0o777, 0o700)
def test_shutdown_signal_stops_app_and_display(self):
self.env['APP_WAIT'] = '1'
process = subprocess.Popen(self.command(), env=self.env, cwd=REPOSITORY,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
try:
deadline = time.monotonic() + 5
while not (self.root / 'app.pid').exists() and time.monotonic() < deadline:
time.sleep(0.02)
self.assertTrue((self.root / 'app.pid').exists())
process.send_signal(signal.SIGTERM)
stdout, stderr = process.communicate(timeout=5)
self.assertEqual(process.returncode, 143, stderr)
self.assert_process_gone('xvfb.pid')
self.assert_process_gone('app.pid')
finally:
if process.poll() is None:
process.kill()
process.communicate(timeout=5)
for filename in ('app.pid', 'xvfb.pid'):
if (self.root / filename).exists():
try:
os.kill(int((self.root / filename).read_text()), signal.SIGTERM)
except ProcessLookupError:
pass
if __name__ == '__main__':
unittest.main()
+43
View File
@@ -0,0 +1,43 @@
"""The deployment command must not report success for unhealthy containers."""
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
SCRIPT = Path(__file__).resolve().parents[1] / 'deploy.sh'
class Deployment(unittest.TestCase):
def run_deploy(self, healthy):
with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary)
docker = root / 'docker'
docker.write_text(f'#!{sys.executable}\n' + '''import os,sys
args=sys.argv[1:]
if 'up' in args:
assert '--wait' in args and '--wait-timeout' in args
sys.exit(0 if os.environ['TEST_HEALTHY']=='1' else 42)
print('container runtime: BRIDGE_NOT_READY')
''')
docker.chmod(0o755)
return subprocess.run(['/bin/sh', str(SCRIPT)],
env={'PATH': str(root)+os.pathsep+os.defpath, 'TEST_HEALTHY': '1' if healthy else '0'},
capture_output=True, text=True, timeout=5)
def test_failed_readiness_fails_deployment_and_prints_evidence(self):
result = self.run_deploy(False)
self.assertNotEqual(result.returncode, 0)
self.assertIn('deployment failed', result.stderr)
self.assertIn('BRIDGE_NOT_READY', result.stdout)
self.assertNotIn('deployment ready:', result.stdout)
def test_only_successful_healthcheck_reports_ready(self):
result = self.run_deploy(True)
self.assertEqual(result.returncode, 0)
self.assertIn('deployment ready:', result.stdout)
if __name__ == '__main__':
unittest.main()
+41
View File
@@ -0,0 +1,41 @@
"""CLI output must settle even when Electron leaves a resident helper."""
import contextlib
import os
from pathlib import Path
import signal
import sys
import tempfile
import unittest
from codex_pcb.eda import cli
class EdaTransport(unittest.IsolatedAsyncioTestCase):
async def test_resident_child_does_not_hide_native_bridge_error(self):
with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary)
binary = root / 'eda'
pid_file = root / 'helper.pid'
binary.write_text(f'#!{sys.executable}\n' + '''import os,time
from pathlib import Path
child=os.fork()
if child == 0:
time.sleep(30)
os._exit(0)
Path(__file__).with_name('helper.pid').write_text(str(child))
print('{"ok":false,"error":{"code":"BRIDGE_NOT_READY","message":"activation required"}}',flush=True)
raise SystemExit(3)
''')
binary.chmod(0o755)
try:
with self.assertRaisesRegex(RuntimeError, 'BRIDGE_NOT_READY'):
await cli(['open', '--headless', 'true'], binary=str(binary),
directory=root, timeout=2)
finally:
if pid_file.exists():
with contextlib.suppress(ProcessLookupError):
os.kill(int(pid_file.read_text()), signal.SIGTERM)
if __name__ == '__main__':
unittest.main()
+193
View File
@@ -0,0 +1,193 @@
"""Native error propagation and stalled-model handling, without model requests."""
import asyncio
import importlib
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import AsyncMock, patch
app = importlib.import_module('codex_pcb.app')
def notification(method, **params):
return {'method': method, 'params': {'threadId': 'test-thread', 'turnId': 'test-turn', **params}}
class FakeAppServer:
def __init__(self, messages):
self.events = asyncio.Queue()
self.requests = set()
for message in messages:
self.events.put_nowait(message)
async def __aenter__(self):
return self
async def __aexit__(self, *args):
return False
async def call(self, method, params):
if method == 'thread/start':
return {'thread': {'id': 'test-thread'}, 'model': app.MODEL}
if method == 'turn/start':
return {'turn': {'id': 'test-turn'}}
raise AssertionError('Unexpected call: ' + method)
class ModelProgress(unittest.IsolatedAsyncioTestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.directory = Path(self.temp.name)
self.entries = []
self.task = {'id': 'test-task', 'state': 'planning', 'busy': True}
self.patches = [
patch.object(app, 'require_runtime_ready', new=AsyncMock(return_value={'ok': True})),
patch.object(app, 'workspace', return_value=self.directory),
patch.object(app, 'save'),
patch.object(app, 'event', side_effect=lambda t, kind, data: self.entries.append((kind, data))),
patch.object(app, 'fingerprint', return_value='test-source'),
patch.object(app, 'CODEX_IDLE_TIMEOUT', 0.04),
]
for p in self.patches:
p.start()
self.addCleanup(p.stop)
async def run_work(self, messages, prepare=None):
client = FakeAppServer(messages)
if prepare:
prepare(client)
with patch.object(app, 'AppServer', return_value=client):
await asyncio.wait_for(app.work(self.task, 'Publish a proposal only.', False), 1)
return client
async def test_native_retries_and_terminal_error_reach_public_state(self):
retry = notification('error', willRetry=True, error={
'message': 'Reconnecting... 1/5', 'additionalDetails': 'upstream returned 403 Forbidden'})
terminal = notification('error', willRetry=False, error={
'message': '403 Forbidden', 'additionalDetails': 'Country, region, or territory not supported'})
await self.run_work([retry, terminal])
self.assertEqual(self.task['state'], 'failed')
self.assertFalse(self.task['busy'])
self.assertIn('Country, region', self.task['error'])
retries = [data for kind, data in self.entries if kind == 'session.reconnecting']
self.assertEqual(len(retries), 1)
self.assertIn('upstream returned 403', retries[0]['message'])
trace = [json.loads(line) for line in (self.directory / 'evidence/codex-events.jsonl').read_text().splitlines()]
self.assertEqual(trace, [retry, terminal])
async def test_silent_model_fails_and_retains_thread_for_retry(self):
await self.run_work([])
self.assertEqual(self.task['state'], 'failed')
self.assertFalse(self.task['busy'])
self.assertEqual(self.task['thread_id'], 'test-thread')
self.assertIn('no progress', self.task['error'])
self.assertNotIn('test-task', app.CLIENTS)
self.assertFalse(any(kind == 'session.reconnecting' for kind, _ in self.entries))
async def test_status_and_retry_noise_do_not_keep_turn_alive(self):
producer = None
def prepare(client):
async def send_noise():
for _ in range(40):
await client.events.put(notification('thread/status/changed', status={'type': 'active'}))
await client.events.put(notification('error', willRetry=True, error={'message': 'Retrying'}))
await asyncio.sleep(0.01)
nonlocal producer
producer = asyncio.create_task(send_noise())
try:
await self.run_work([], prepare)
self.assertEqual(self.task['state'], 'failed')
self.assertIn('no progress', self.task['error'])
self.assertIn('Last upstream error: Retrying', self.task['error'])
self.assertFalse(producer.done())
finally:
producer.cancel()
await asyncio.gather(producer, return_exceptions=True)
async def test_real_model_deltas_reset_idle_deadline(self):
async def send_progress(client):
for _ in range(6):
await asyncio.sleep(0.015)
await client.events.put(notification('item/reasoning/textDelta', delta='progress'))
self.task['proposal'] = {'revision': 1}
await client.events.put(notification('turn/completed', turn={'id': 'test-turn', 'status': 'completed'}))
producer = None
def prepare(client):
nonlocal producer
producer = asyncio.create_task(send_progress(client))
await self.run_work([], prepare)
await producer
self.assertEqual(self.task['state'], 'review')
self.assertFalse(self.task['busy'])
self.assertNotIn('error', self.task)
async def test_active_native_tool_is_not_cut_off_by_model_idle_deadline(self):
producer = None
def prepare(client):
async def finish_tool():
await asyncio.sleep(0.1)
client.requests.clear()
self.task['proposal'] = {'revision': 1}
await client.events.put(notification('turn/completed', turn={'id': 'test-turn', 'status': 'completed'}))
nonlocal producer
producer = asyncio.create_task(finish_tool())
client.requests.add(producer)
await self.run_work([], prepare)
await producer
self.assertEqual(self.task['state'], 'review')
async def test_error_from_another_turn_is_ignored(self):
stale = notification('error', turnId='old-turn', willRetry=False, error={'message': 'old error'})
self.task['proposal'] = {'revision': 1}
done = notification('turn/completed', turn={'id': 'test-turn', 'status': 'completed'})
await self.run_work([stale, done])
self.assertEqual(self.task['state'], 'review')
self.assertNotIn('error', self.task)
async def test_long_native_shell_uses_its_own_execution_timeout(self):
producer = None
def prepare(client):
async def finish_command():
await asyncio.sleep(0.1)
await client.events.put(notification('item/completed', item={
'id': 'command-1', 'type': 'commandExecution', 'status': 'completed'}))
self.task['proposal'] = {'revision': 1}
await client.events.put(notification('turn/completed', turn={'id': 'test-turn', 'status': 'completed'}))
nonlocal producer
producer = asyncio.create_task(finish_command())
start = notification('item/started', item={
'id': 'command-1', 'type': 'commandExecution', 'status': 'inProgress'})
await self.run_work([start], prepare)
await producer
self.assertEqual(self.task['state'], 'review')
async def test_idle_deadline_resumes_after_native_tool_finishes(self):
producer = None
def prepare(client):
async def finish_tool():
await asyncio.sleep(0.1)
client.requests.clear()
nonlocal producer
producer = asyncio.create_task(finish_tool())
client.requests.add(producer)
await self.run_work([], prepare)
await producer
self.assertEqual(self.task['state'], 'failed')
self.assertIn('no progress', self.task['error'])
if __name__ == '__main__':
unittest.main()
+5 -5
View File
@@ -2,7 +2,7 @@ import asyncio
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
from unittest.mock import patch, AsyncMock
from codex_pcb import app as service
from codex_pcb.native_policy import DESIGN_POLICY
@@ -13,8 +13,8 @@ class SessionPolicyTest(unittest.IsolatedAsyncioTestCase):
self.folder=Path(self.tmp.name)
async def test_approval_has_no_external_launcher(self):
t={'id':'test','state':'review','proposal':{'revision':1,'hash':'approved','markdown':'accepted board'}}
with patch.object(service,'get',return_value=t),patch.object(service,'event'),patch.object(service,'workspace',return_value=self.folder),patch.object(service,'schedule') as schedule:
t={'id':'test','state':'review','proposal':{'revision':1,'hash':'approved','markdown':'accepted board'},'cursor':0}
with patch.object(service,'get',return_value=t),patch.object(service,'event'),patch.object(service,'workspace',return_value=self.folder),patch.object(service,'schedule') as schedule,patch.object(service,'require_runtime_ready',new_callable=AsyncMock):
await service.approve('test',service.Approval(revision=1,hash='approved'))
prompt=schedule.call_args.args[1]
self.assertIn(DESIGN_POLICY,prompt)
@@ -26,7 +26,7 @@ class SessionPolicyTest(unittest.IsolatedAsyncioTestCase):
async def test_resume_keeps_thread_and_reasserts_policy(self):
calls=[]
class FakeServer:
def __init__(self,*args):self.events=asyncio.Queue()
def __init__(self,*args,**kwargs):self.events=asyncio.Queue();self.requests=set()
async def __aenter__(self):return self
async def __aexit__(self,*args):pass
async def call(self,method,args):
@@ -48,5 +48,5 @@ class SessionPolicyTest(unittest.IsolatedAsyncioTestCase):
self.assertIn('Recovery project identity retained.',(self.folder/'AGENTS.md').read_text())
def test_source_freeze_still_rejects_unapproved_backend_drift(self):
with self.assertRaisesRegex(RuntimeError,'Backend source changed'):
with self.assertRaisesRegex(RuntimeError,'Backend source.*changed'):
service.frozen({'approval':{'hash':'accepted'},'frozen_source':'unexpected'})
+207
View File
@@ -0,0 +1,207 @@
"""Real filesystem/subprocess probes using fake CLIs, never a model or design."""
import asyncio
import importlib
import json
import os
from pathlib import Path
import sys
import tempfile
import unittest
from unittest.mock import AsyncMock, patch
from codex_pcb import preflight
class ProductionPreflight(unittest.IsolatedAsyncioTestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name).resolve()
self.workspace = self.root / 'data/tasks/test/workspace'
self.bin = self.root / 'bin'
self.bin.mkdir()
reference = self.root / 'data/resources/references/_index.md'
reference.parent.mkdir(parents=True)
reference.write_text('API index')
jar = self.root / 'router.jar'
jar.touch()
self.settings = patch.multiple(preflight, ROOT=self.root / 'data',
CODEX_HOME=self.root / 'codex-home', CODEX_BIN=str(self.bin / 'codex'),
EDA_BIN=str(self.bin / 'eda'), BLENDER_BIN=str(self.bin / 'blender'),
FREEROUTING_JAR=jar)
self.settings.start()
self.addCleanup(self.settings.stop)
self.environment = patch.dict(os.environ, {
'HOME': str(self.root / 'home'), 'PATH': os.defpath,
'OPENAI_API_KEY': 'must-not-reach-eda-or-probe',
'DEEPSEEK_API_KEY_FILE': '/must-not-reach-child',
}, clear=True)
self.environment.start()
self.addCleanup(self.environment.stop)
self.program('codex', '''import os,sys,json
from pathlib import Path
assert 'OPENAI_API_KEY' not in os.environ
assert 'DEEPSEEK_API_KEY_FILE' not in os.environ
assert sys.argv[1] == 'sandbox'
assert '-C' not in sys.argv # Requires a named profile in the pinned CLI.
assert 'sandbox_mode="workspace-write"' in sys.argv
assert 'sandbox_workspace_write.exclude_slash_tmp=true' in sys.argv
assert Path(os.environ['TMPDIR']).is_relative_to(Path.cwd())
if os.environ.get('FAIL_SANDBOX'):
print('bwrap: Creating new namespace failed: Operation not permitted',file=sys.stderr)
sys.exit(1)
if not os.environ.get('NO_SANDBOX_WRITE'):
Path(sys.argv[-1]).write_text('pcb-preflight')
''')
self.env_calls = self.root / 'eda-calls.jsonl'
os.environ['TEST_EDA_CALLS'] = str(self.env_calls)
self.program('eda', '''import os,sys,json
from pathlib import Path
assert 'OPENAI_API_KEY' not in os.environ
assert 'DEEPSEEK_API_KEY_FILE' not in os.environ
assert sys.argv[-1] == '--no-sandbox'
args=sys.argv[1:-1]
with Path(os.environ['TEST_EDA_CALLS']).open('a') as stream:stream.write(json.dumps(args)+'\\n')
if os.environ.get('FAIL_EDA'):
print('Permission denied: /opt/lceda-pro/lceda-pro',file=sys.stderr)
sys.exit(126)
if args == ['--help']:print('EasyEDA CLI help')
elif args == ['open','--headless','true']:print(json.dumps({'ok':True,'value':{'sessionId':'diagnostic-only'}}))
elif args[:1] == ['invoke']:
assert args[args.index('--session')+1] == 'diagnostic-only'
code=sys.stdin.read()
assert 'getEditorCurrentVersion' in code and 'createProject' not in code
if os.environ.get('FAIL_BRIDGE'):
print(json.dumps({'ok':False,'error':{'code':'BRIDGE_NOT_READY','message':'command-space-missing'}}))
sys.exit(1)
print(json.dumps({'ok':True,'value':{'client':True,'version':'test-editor'}}))
elif args == ['session','close','--session','diagnostic-only','--destroy']:
if os.environ.get('FAIL_CLOSE'):
print(json.dumps({'ok':False,'error':{'code':'CLOSE_FAILED'}}));sys.exit(1)
print(json.dumps({'ok':True,'value':None}))
else:raise AssertionError(args)
''')
self.program('blender', 'pass\n')
def program(self, name, body):
path = self.bin / name
path.write_text(f'#!{sys.executable}\n' + body)
path.chmod(0o755)
async def test_success_checks_real_writes_and_does_not_call_model_or_leave_probe_files(self):
report = await preflight.check_runtime(self.workspace)
self.assertTrue(report['ok'], report)
checks = {item['name']: item for item in report['checks']}
self.assertTrue(checks['codex_sandbox']['ok'])
self.assertTrue(checks['eda_launch']['ok'])
self.assertTrue(checks['eda_bridge']['ok'])
calls = [json.loads(line) for line in self.env_calls.read_text().splitlines()]
self.assertEqual(calls[-1], ['session', 'close', '--session', 'diagnostic-only', '--destroy'])
self.assertFalse(list(self.root.rglob('.pcb-*-check-*')))
self.assertEqual((self.root / 'codex-home').stat().st_mode & 0o777, 0o700)
self.assertNotIn('must-not-reach', json.dumps(report))
async def test_independent_eda_and_namespace_failures_both_reported(self):
os.environ.update(FAIL_SANDBOX='1', FAIL_EDA='1')
report = await preflight.check_runtime(self.workspace)
self.assertFalse(report['ok'])
failed = {item['name']: item['message'] for item in report['checks'] if not item['ok']}
self.assertIn('bwrap', failed['codex_sandbox'])
self.assertIn('Permission denied', failed['eda_launch'])
self.assertNotIn('must-not-reach', json.dumps(report))
async def test_eda_keeps_host_temp_directory_for_persistent_ipc(self):
host_tmp = str(self.root / 'host-tmp')
os.environ.update(TMPDIR=host_tmp, TMP=host_tmp, TEMP=host_tmp)
with patch.object(preflight, 'eda_cli', wraps=preflight.eda_cli) as cli:
report = await preflight.check_runtime(self.workspace)
self.assertTrue(report['ok'], report)
self.assertEqual(cli.await_count, 3)
for call in cli.await_args_list:
for name in ('TMPDIR', 'TMP', 'TEMP'):
self.assertEqual(call.kwargs['environment'][name], host_tmp)
async def test_native_only_workflow_does_not_require_external_router(self):
with patch.object(preflight, 'FREEROUTING_JAR', self.root / 'missing-router.jar'):
report = await preflight.check_runtime(self.workspace)
self.assertTrue(report['ok'], report)
self.assertNotIn('freerouting', [item['name'] for item in report['checks']])
async def test_nonexecutable_eda_is_detected_without_launch(self):
(self.bin / 'eda').chmod(0o644)
report = await preflight.check_runtime(self.workspace)
self.assertFalse(report['ok'])
failed = [item for item in report['checks'] if not item['ok']]
self.assertEqual([item['name'] for item in failed], ['eda_binary'])
self.assertIn('执行权限', failed[0]['message'])
async def test_help_success_does_not_hide_bridge_failure_and_owned_session_is_closed(self):
os.environ['FAIL_BRIDGE'] = '1'
report = await preflight.check_runtime(self.workspace)
checks = {item['name']: item for item in report['checks']}
self.assertTrue(checks['eda_launch']['ok'])
self.assertFalse(report['ok'])
self.assertIn('BRIDGE_NOT_READY', checks['eda_bridge']['message'])
calls = [json.loads(line) for line in self.env_calls.read_text().splitlines()]
self.assertEqual(calls[-1], ['session', 'close', '--session', 'diagnostic-only', '--destroy'])
async def test_cleanup_failure_is_not_reported_as_ready(self):
os.environ['FAIL_CLOSE'] = '1'
report = await preflight.check_runtime(self.workspace)
self.assertFalse(report['ok'])
self.assertIn('eda_cleanup', [item['name'] for item in report['checks'] if not item['ok']])
async def test_exit_zero_without_actual_sandbox_write_is_rejected(self):
os.environ['NO_SANDBOX_WRITE'] = '1'
report = await preflight.check_runtime(self.workspace)
failed = [item['name'] for item in report['checks'] if not item['ok']]
self.assertEqual(failed, ['codex_sandbox'])
async def test_unwritable_workspace_is_reported_as_failure(self):
blocker = self.root / 'not-a-directory'
blocker.touch()
report = await preflight.check_runtime(blocker / 'workspace')
self.assertFalse(report['ok'])
self.assertFalse(next(item for item in report['checks'] if item['name'] == 'workspace_write')['ok'])
async def test_probe_timeout_is_a_failure(self):
with patch.object(preflight, 'command', side_effect=asyncio.TimeoutError):
report = await preflight.check_runtime(self.workspace)
self.assertFalse(report['ok'])
self.assertFalse(next(item for item in report['checks'] if item['name'] == 'codex_sandbox')['ok'])
async def test_production_does_not_start_model_after_failed_preflight(self):
app = importlib.import_module('codex_pcb.app')
self.workspace.mkdir(parents=True)
task = {'id': 'preflight-test', 'state': 'running', 'busy': True, 'approval': {}}
report = {'ok': False, 'checks': [{'name': 'codex_sandbox', 'ok': False, 'message': 'bwrap namespace blocked'}]}
entries = []
with patch.object(app, 'frozen'), patch.object(app, 'save'), \
patch.object(app, 'workspace', return_value=self.workspace), \
patch.object(app, 'event', side_effect=lambda t, name, data: entries.append((name, data))), \
patch.object(app, 'check_runtime', AsyncMock(return_value=report)), \
patch.object(app, 'run_turn', AsyncMock()) as turn:
await app.work(task, 'Approved design', True)
turn.assert_not_awaited()
self.assertEqual(task['state'], 'failed')
self.assertFalse(task['busy'])
self.assertIn('bwrap namespace blocked', task['error'])
self.assertEqual(json.loads((self.workspace / 'evidence/runtime-check.json').read_text()), report)
self.assertIn(('runtime.checked', report), entries)
async def test_source_freeze_is_checked_before_production_probes(self):
app = importlib.import_module('codex_pcb.app')
task = {'id': 'frozen-test', 'state': 'running', 'busy': True}
with patch.object(app, 'frozen', side_effect=RuntimeError('Backend source changed after approval')), \
patch.object(app, 'save'), patch.object(app, 'event'), \
patch.object(app, 'check_runtime', AsyncMock()) as check, \
patch.object(app, 'run_turn', AsyncMock()) as turn:
await app.work(task, 'Approved design', True)
check.assert_not_awaited()
turn.assert_not_awaited()
self.assertIn('source changed', task['error'])
self.assertFalse(task['busy'])
if __name__ == '__main__':
unittest.main()
+203
View File
@@ -0,0 +1,203 @@
"""Per-design provider selection, credential isolation and runtime immutability."""
import importlib
import json
import os
from pathlib import Path
import tempfile
import unittest
from unittest.mock import AsyncMock, patch
import httpx
from codex_pcb import config, rpc, storage
from codex_pcb.models import catalog
app = importlib.import_module('codex_pcb.app')
class ProviderSelection(unittest.IsolatedAsyncioTestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.environment = patch.dict(os.environ, {
'HOME': str(self.root), 'PATH': os.defpath,
'PCB_SESSION_ROOT': str(self.root/'runtime'), 'PCB_CODEX_AUTH': 'apikey',
'OPENAI_API_KEY': 'test-openai-only', 'DEEPSEEK_API_KEY': 'test-deepseek-only',
'ARK_API_KEY': 'test-ark-only', 'DOUBAO_API_KEY': 'test-unused-alias',
}, clear=True)
self.environment.start()
self.reload()
self.scheduler = patch.object(app, 'schedule')
self.schedule = self.scheduler.start()
self.readiness_guard = patch.object(app, 'require_runtime_ready', new=AsyncMock(return_value={'ok': True}))
self.ready = self.readiness_guard.start()
self.addCleanup(self.restore)
def reload(self):
for module in (config, storage, rpc, app):
importlib.reload(module)
def restore(self):
self.readiness_guard.stop()
self.scheduler.stop()
self.environment.stop()
self.reload()
async def request(self, method, path, **kwargs):
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app.app), base_url='http://test') as client:
return await client.request(method, path, **kwargs)
async def create(self, provider=None):
body = {'text': 'Publish a proposal only; no production approval.'}
if provider is not None:
body['provider'] = provider
return await self.request('POST', '/api/sessions', json=body)
async def test_default_is_openai_at_requested_compatible_endpoint(self):
response = await self.create()
self.assertEqual(response.status_code, 201)
task = response.json()
self.assertEqual(task['ai_provider'], 'openai')
self.assertEqual(task['model'], 'gpt-6.1-sol')
self.assertEqual(task['runtime']['api_base_url'], 'https://api.vip1129.cc')
self.assertEqual(storage.load(task['id'])['runtime'], task['runtime'])
self.assertFalse(self.schedule.call_args.args[2])
async def test_select_deepseek_and_doubao_for_independent_tasks(self):
for name, model in (('deepseek','deepseek-flash'), ('doubao','doubao-seed-2-1-pro-260915')):
with self.subTest(provider=name):
response = await self.create(name)
self.assertEqual(response.status_code, 201)
task = response.json()
self.assertEqual(task['ai_provider'], name)
self.assertEqual(task['model'], model)
self.assertEqual(task['provider'], 'vibemake_'+name)
self.assertNotIn('test-', json.dumps(task))
async def test_unknown_or_unconfigured_provider_creates_no_task(self):
response = await self.create('unsupported')
self.assertEqual(response.status_code, 400)
del os.environ['DEEPSEEK_API_KEY']
response = await self.create('deepseek')
self.assertEqual(response.status_code, 503)
self.assertIn('DEEPSEEK_API_KEY', response.json()['detail'])
self.assertFalse(storage.TASKS.exists())
self.schedule.assert_not_called()
async def test_unready_environment_rejects_creation_before_allocating_task_or_model(self):
self.ready.side_effect = app.HTTPException(503, '绘板环境未就绪:BRIDGE_NOT_READY')
response = await self.create()
self.assertEqual(response.status_code, 503)
self.assertIn('BRIDGE_NOT_READY', response.json()['detail'])
self.assertFalse(storage.TASKS.exists())
self.schedule.assert_not_called()
async def test_unready_environment_does_not_record_approval_or_schedule_production(self):
task = app.get((await self.create()).json()['id'])
task.update(state='review', proposal={'revision': 1, 'hash': 'latest', 'markdown': 'Accepted design'})
self.schedule.reset_mock()
self.ready.reset_mock()
self.ready.side_effect = app.HTTPException(503, 'EasyEDA 命令桥接不可用')
response = await self.request('POST', '/api/sessions/'+task['id']+'/approve', json={'revision': 1, 'hash': 'latest'})
self.assertEqual(response.status_code, 503)
self.assertNotIn('approval', task)
self.assertEqual(task['state'], 'review')
self.ready.assert_awaited_once_with(force=True)
self.schedule.assert_not_called()
async def test_unready_environment_does_not_resume_or_revise_task(self):
task = app.get((await self.create()).json()['id'])
task.update(state='failed')
self.schedule.reset_mock()
self.ready.side_effect = app.HTTPException(503, 'EDA unavailable')
for suffix, body in (('resume', {}), ('comments', {'text': 'Please revise the proposal'})):
response = await self.request('POST', '/api/sessions/'+task['id']+'/'+suffix, json=body)
self.assertEqual(response.status_code, 503)
self.schedule.assert_not_called()
async def test_cancel_during_environment_check_cannot_be_overwritten_by_approval(self):
task = app.get((await self.create()).json()['id'])
task.update(state='review', proposal={'revision': 1, 'hash': 'latest', 'markdown': 'Accepted design'})
self.schedule.reset_mock()
async def cancel_while_checking(**kwargs):
await app.cancel(task['id'])
return {'ok': True}
self.ready.side_effect = cancel_while_checking
response = await self.request('POST', '/api/sessions/'+task['id']+'/approve', json={'revision': 1, 'hash': 'latest'})
self.assertEqual(response.status_code, 409)
self.assertEqual(task['state'], 'cancelled')
self.assertNotIn('approval', task)
self.schedule.assert_not_called()
async def test_provider_list_reports_readiness_without_credentials(self):
del os.environ['ARK_API_KEY']
del os.environ['DOUBAO_API_KEY']
response = await self.request('GET', '/api/providers')
result = response.json()
self.assertEqual(result['default_provider'], 'openai')
readiness = {p['id']:p['configured'] for p in result['providers']}
self.assertEqual(readiness, {'openai':True,'deepseek':True,'doubao':False})
self.assertNotIn('test-', response.text)
self.assertNotIn('API_KEY', response.text)
def test_each_process_receives_only_its_provider_credential(self):
for name, key, expected in (('openai','OPENAI_API_KEY','test-openai-only'),
('deepseek','DEEPSEEK_API_KEY','test-deepseek-only'),
('doubao','ARK_API_KEY','test-ark-only')):
with self.subTest(provider=name):
runtime = config.runtime_for(name)
args, env = rpc.process_config(False, runtime)
self.assertEqual(env[key], expected)
self.assertNotIn(expected, ' '.join(args))
for other in rpc.SECRET_ENV_NAMES:
if other != key:
self.assertNotIn(other, env)
setting = next(args[i+1] for i, arg in enumerate(args) if arg=='-c' and args[i+1].startswith('model_providers.'+runtime.provider+'.wire_api='))
self.assertTrue(setting.endswith('"responses"'))
if name == 'deepseek':
self.assertIn('features.standalone_web_search=true', args)
self.assertFalse(any('alpha_search' in arg for arg in args))
def test_doubao_alias_and_file_secret_do_not_leak_other_keys(self):
del os.environ['ARK_API_KEY']
runtime = config.runtime_for('doubao')
self.assertEqual(rpc.api_key(runtime), 'test-unused-alias')
del os.environ['DOUBAO_API_KEY']
secret = self.root/'ark-secret'
secret.write_text('file-ark-credential\n')
os.environ['ARK_API_KEY_FILE'] = str(secret)
args, env = rpc.process_config(False, runtime)
self.assertEqual(env['ARK_API_KEY'], 'file-ark-credential')
self.assertNotIn('ARK_API_KEY_FILE', env)
self.assertNotIn('file-ark-credential', ' '.join(args))
async def test_selected_runtime_is_independent_of_default_and_key_rotation(self):
task = (await self.create('deepseek')).json()
runtime = app.task_runtime(task)
before = storage.fingerprint(runtime)
os.environ.update(PCB_AI_PROVIDER='doubao', DEEPSEEK_API_KEY='rotated-provider-secret')
importlib.reload(config)
self.assertEqual(app.task_runtime(task).snapshot(), runtime.snapshot())
self.assertEqual(storage.fingerprint(app.task_runtime(task)), before)
async def test_saved_task_cannot_silently_change_model_or_endpoint(self):
task = (await self.create('deepseek')).json()
os.environ['PCB_DEEPSEEK_MODEL'] = 'different-model'
with self.assertRaisesRegex(RuntimeError, 'cannot switch providers'):
app.task_runtime(task)
del os.environ['PCB_DEEPSEEK_MODEL']
os.environ['PCB_DEEPSEEK_BASE_URL'] = 'https://different.example.test'
with self.assertRaisesRegex(RuntimeError, 'cannot switch providers'):
app.task_runtime(task)
def test_non_openai_metadata_keeps_requested_model_and_vision(self):
for name in ('deepseek','doubao'):
runtime = config.runtime_for(name)
metadata = catalog(runtime)['models'][0]
self.assertEqual(metadata['slug'], runtime.model)
self.assertIn('image', metadata['input_modalities'])
self.assertNotIn('test-', json.dumps(metadata))
if __name__ == '__main__':
unittest.main()
+107
View File
@@ -0,0 +1,107 @@
"""Deployment/readiness endpoints, caching and fail-closed model admission."""
import asyncio
import importlib
import json
from pathlib import Path
import tempfile
import time
import unittest
from unittest.mock import AsyncMock, patch
import httpx
from codex_pcb.readiness import RuntimeReadiness
module = importlib.import_module('codex_pcb.readiness')
app = importlib.import_module('codex_pcb.app')
def report(ok=True):
return {'ok': ok, 'checks': [{'name': 'eda_bridge', 'ok': ok,
'message': 'Bridge verified' if ok else 'BRIDGE_NOT_READY: command-space-missing'}]}
class Readiness(unittest.IsolatedAsyncioTestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.settings = patch.object(module, 'ROOT', self.root)
self.settings.start()
self.addCleanup(self.settings.stop)
async def request(self, method, path):
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app.app), base_url='http://test') as client:
return await client.request(method, path)
async def test_readiness_and_deployment_health_remain_closed_while_checking(self):
finish = asyncio.Event()
async def check():
await finish.wait()
return report()
manager = RuntimeReadiness(checker=check)
with patch.object(app, 'readiness', manager):
response = await self.request('GET', '/api/readiness')
self.assertEqual(response.json()['status'], 'checking')
self.assertFalse(response.json()['ok'])
self.assertEqual((await self.request('GET', '/api/ready')).status_code, 503)
finish.set()
await manager.verify()
response = await self.request('GET', '/api/ready')
self.assertEqual(response.status_code, 200)
self.assertTrue(response.json()['ok'])
await manager.close()
async def test_failed_bridge_has_structured_report_and_http503_for_deployment(self):
manager = RuntimeReadiness(checker=AsyncMock(return_value=report(False)))
with patch.object(app, 'readiness', manager):
await manager.verify()
response = await self.request('GET', '/api/readiness')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json()['status'], 'unavailable')
self.assertIn('BRIDGE_NOT_READY', response.text)
self.assertEqual((await self.request('GET', '/api/ready')).status_code, 503)
with self.assertRaises(app.HTTPException) as raised:
await app.require_runtime_ready()
self.assertEqual(raised.exception.status_code, 503)
saved = json.loads((self.root / 'runtime-readiness.json').read_text())
self.assertFalse(saved['ok'])
async def test_concurrent_visitors_share_one_probe_and_results_are_cached(self):
checker = AsyncMock(return_value=report())
manager = RuntimeReadiness(checker=checker)
await asyncio.gather(*(manager.verify() for _ in range(12)))
checker.assert_awaited_once()
await manager.verify()
checker.assert_awaited_once()
manager.report['checked_at'] = time.time() - manager.ttl - 1
await manager.verify()
self.assertEqual(checker.await_count, 2)
async def test_force_recheck_recovers_from_failure(self):
checker = AsyncMock(side_effect=[report(False), report()])
manager = RuntimeReadiness(checker=checker)
self.assertFalse((await manager.verify())['ok'])
self.assertTrue((await manager.verify(force=True))['ok'])
self.assertEqual(checker.await_count, 2)
async def test_checker_exception_is_not_reported_as_healthy(self):
manager = RuntimeReadiness(checker=AsyncMock(side_effect=OSError('Read-only filesystem')))
value = await manager.verify()
self.assertFalse(value['ok'])
self.assertIn('Read-only filesystem', value['checks'][0]['message'])
async def test_deployment_endpoint_does_not_launch_new_probe_on_each_healthcheck(self):
checker = AsyncMock(return_value=report())
manager = RuntimeReadiness(checker=checker)
with patch.object(app, 'readiness', manager):
for _ in range(5):
self.assertEqual((await self.request('GET', '/api/ready')).status_code, 503)
checker.assert_not_awaited()
await manager.verify()
for _ in range(5):
self.assertEqual((await self.request('GET', '/api/ready')).status_code, 200)
checker.assert_awaited_once()
if __name__ == '__main__':
unittest.main()
+218
View File
@@ -0,0 +1,218 @@
"""Deployment/authentication boundaries; no real credentials or model calls."""
import asyncio
import importlib
import json
import os
from pathlib import Path
import sys
import tempfile
import tomllib
import unittest
from unittest.mock import AsyncMock, patch
from codex_pcb import config, eda, rpc, storage
FAKE_KEY = 'unit-test-api-credential'
def command_settings(args):
return tomllib.loads('\n'.join(args[i + 1] for i, value in enumerate(args) if value == '-c'))
class RuntimeConfig(unittest.IsolatedAsyncioTestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name).resolve()
environment = {
'HOME': str(self.root), 'PATH': os.defpath,
'PCB_CODEX_AUTH': 'apikey',
'PCB_AI_PROVIDER': 'openai',
'PCB_SESSION_ROOT': str(self.root / 'runtime'),
'PCB_CODEX_BIN': str(self.root / 'codex'),
'PCB_EDA_BIN': str(self.root / 'native eda'),
'PCB_BLENDER_BIN': str(self.root / 'native blender'),
}
self.environment = patch.dict(os.environ, environment, clear=True)
self.environment.start()
self.addCleanup(self.restore_environment)
self.reload()
def reload(self):
for module in (config, storage, rpc, eda):
importlib.reload(module)
def restore_environment(self):
self.environment.stop()
self.reload()
def test_api_key_provider_does_not_put_credentials_in_arguments(self):
os.environ.update(OPENAI_API_KEY=FAKE_KEY, CODEX_API_KEY='unrelated',
DEEPSEEK_API_KEY='unrelated', OPENAI_BASE_URL='https://unused.invalid')
args, env = rpc.process_config(True)
settings = command_settings(args)
provider = settings['model_providers'][config.PROVIDER]
self.assertEqual(provider['base_url'], 'https://api.vip1129.cc')
self.assertEqual(provider['env_key'], 'OPENAI_API_KEY')
self.assertEqual(provider['wire_api'], 'responses')
self.assertFalse(provider['requires_openai_auth'])
self.assertEqual(settings['model_provider'], config.PROVIDER)
self.assertFalse(settings['shell_environment_policy']['ignore_default_excludes'])
self.assertEqual(env['OPENAI_API_KEY'], FAKE_KEY)
self.assertNotIn(FAKE_KEY, ' '.join(args))
for name in ('CODEX_API_KEY', 'DEEPSEEK_API_KEY', 'OPENAI_BASE_URL'):
self.assertNotIn(name, env)
def test_file_secret_does_not_create_login_file(self):
secret = self.root / 'api-key'
secret.write_text(FAKE_KEY + '\n')
os.environ['OPENAI_API_KEY_FILE'] = str(secret)
args, env = rpc.process_config(False)
self.assertEqual(env['OPENAI_API_KEY'], FAKE_KEY)
self.assertNotIn('OPENAI_API_KEY_FILE', env)
self.assertNotIn(FAKE_KEY, ' '.join(args))
self.assertFalse(config.CODEX_HOME.exists())
def test_explicit_api_endpoint_and_approval_fingerprint(self):
os.environ['OPENAI_API_KEY'] = FAKE_KEY
before = storage.fingerprint()
os.environ['PCB_OPENAI_BASE_URL'] = 'https://gateway.example.test/v1/'
self.reload()
args, _ = rpc.process_config(False)
provider = command_settings(args)['model_providers'][config.PROVIDER]
self.assertEqual(provider['base_url'], 'https://gateway.example.test/v1')
self.assertNotEqual(before, storage.fingerprint())
os.environ['OPENAI_API_KEY'] = 'rotated-unit-test-credential'
self.assertEqual(provider['base_url'], config.MODEL_API_BASE_URL)
def test_api_endpoint_rejects_embedded_secrets_and_invalid_urls(self):
for value in ('file:///tmp/socket', 'https://user:secret@example.test/v1',
'https://example.test/v1?key=secret', 'https://example.test/#secret',
'https://', 'https://example.test:invalid', 'https://example.test:0'):
with self.subTest(value=value):
os.environ['PCB_OPENAI_BASE_URL'] = value
with self.assertRaisesRegex(ValueError, 'PCB_OPENAI_BASE_URL'):
config.model_api_base_url()
def test_idle_timeout_is_part_of_frozen_runtime(self):
before = storage.fingerprint()
os.environ['PCB_CODEX_IDLE_TIMEOUT'] = '60'
self.reload()
self.assertEqual(config.CODEX_IDLE_TIMEOUT, 60)
self.assertNotEqual(before, storage.fingerprint())
def test_environment_key_takes_precedence_over_file(self):
os.environ.update(OPENAI_API_KEY=FAKE_KEY, OPENAI_API_KEY_FILE='/missing/file')
self.assertEqual(rpc.api_key(), FAKE_KEY)
def test_missing_and_invalid_secrets_fail_without_login_fallback(self):
with self.assertRaisesRegex(ValueError, 'requires OPENAI_API_KEY'):
rpc.process_config(False)
os.environ['OPENAI_API_KEY_FILE'] = str(self.root / 'missing')
with self.assertRaisesRegex(ValueError, 'Cannot read OPENAI_API_KEY_FILE'):
rpc.process_config(False)
for value in ('two values', 'x' * 16385):
os.environ['OPENAI_API_KEY'] = value
with self.assertRaisesRegex(ValueError, 'single non-empty value'):
rpc.process_config(False)
def test_chatgpt_mode_removes_api_credentials(self):
os.environ.update(PCB_CODEX_AUTH='chatgpt', OPENAI_API_KEY=FAKE_KEY,
OPENAI_API_KEY_FILE='/missing/file')
self.reload()
args, env = rpc.process_config(False)
settings = command_settings(args)
self.assertEqual(settings['model_provider'], 'openai')
self.assertNotIn('model_providers', settings)
self.assertNotIn('OPENAI_API_KEY', env)
self.assertNotIn('OPENAI_API_KEY_FILE', env)
self.assertEqual(env['CODEX_HOME'], str(config.ROOT / 'codex-home'))
def test_invalid_auth_mode_is_rejected(self):
os.environ['PCB_CODEX_AUTH'] = 'typo'
self.reload()
with self.assertRaisesRegex(ValueError, 'must be apikey or chatgpt'):
rpc.process_config(False)
def test_portable_defaults_and_explicit_model_paths(self):
for name in ('PCB_SESSION_ROOT', 'PCB_CODEX_AUTH'):
del os.environ[name]
self.reload()
self.assertEqual(config.ROOT, self.root / '.local/share/vibemake-pcb')
self.assertEqual(config.AUTH_MODE, 'chatgpt')
os.environ.update(PCB_SESSION_ROOT='~/data', PCB_CODEX_HOME='~/history',
PCB_MODEL='project-model', PCB_REASONING_EFFORT='medium',
PCB_FREEROUTING_JAR='~/router.jar')
self.reload()
self.assertEqual(config.ROOT, self.root / 'data')
self.assertEqual(config.CODEX_HOME, self.root / 'history')
self.assertEqual(config.FREEROUTING_JAR, self.root / 'router.jar')
self.assertEqual(storage.MODEL, 'project-model')
self.assertEqual(storage.EFFORT, 'medium')
def test_approval_hash_tracks_runtime_but_allows_key_rotation(self):
before = storage.fingerprint()
os.environ['OPENAI_API_KEY'] = FAKE_KEY
self.assertEqual(before, storage.fingerprint())
os.environ['OPENAI_API_KEY'] = 'rotated-unit-test-credential'
self.assertEqual(before, storage.fingerprint())
os.environ['PCB_MODEL'] = 'different-model'
self.reload()
self.assertNotEqual(before, storage.fingerprint())
async def test_eda_preserves_display_settings_without_api_credentials(self):
os.environ.update(OPENAI_API_KEY=FAKE_KEY, OPENAI_API_KEY_FILE='/secret',
DISPLAY=':99', XDG_RUNTIME_DIR=str(self.root / 'xdg'))
process = unittest.mock.Mock(returncode=0)
process.communicate = AsyncMock(return_value=(None, None))
async def start(*args, **kwargs):
kwargs['stdout'].write(b'{"ok":true,"value":{"alive":true}}')
return process
with patch.object(asyncio, 'create_subprocess_exec', new=AsyncMock(side_effect=start)) as spawn:
self.assertEqual(await eda.cli(['session', 'list']), {'alive': True})
args, kwargs = spawn.call_args
self.assertEqual(args[0], str(self.root / 'native eda'))
self.assertEqual(kwargs['env']['DISPLAY'], ':99')
self.assertEqual(kwargs['env']['XDG_RUNTIME_DIR'], str(self.root / 'xdg'))
self.assertNotIn('OPENAI_API_KEY', kwargs['env'])
self.assertNotIn('OPENAI_API_KEY_FILE', kwargs['env'])
async def test_rpc_starts_with_environment_auth_and_persistent_home(self):
os.environ['OPENAI_API_KEY'] = FAKE_KEY
binary = Path(config.CODEX_BIN)
binary.write_text(f'#!{sys.executable}\n' + '''import json,os,sys
assert os.environ.get('OPENAI_API_KEY') == 'unit-test-api-credential'
assert 'unit-test-api-credential' not in ' '.join(sys.argv)
for line in sys.stdin:
message=json.loads(line)
if 'id' in message:
result={'home':os.environ['CODEX_HOME']} if message['method']=='probe' else {}
print(json.dumps({'id':message['id'],'result':result}),flush=True)
''')
binary.chmod(0o755)
async with rpc.AppServer(self.root, False, AsyncMock()) as client:
reply = await client.call('probe', {}, timeout=5)
self.assertEqual(reply['home'], str(config.CODEX_HOME))
self.assertIsNotNone(client.proc.returncode)
self.assertTrue(client.err.closed)
self.assertFalse((config.CODEX_HOME / 'auth.json').exists())
async def test_failed_initialize_closes_process_and_log(self):
os.environ['OPENAI_API_KEY'] = FAKE_KEY
binary = Path(config.CODEX_BIN)
binary.write_text(f'#!{sys.executable}\n' + '''import json,sys
for line in sys.stdin:
message=json.loads(line)
print(json.dumps({'id':message['id'],'error':{'message':'invalid configuration'}}),flush=True)
''')
binary.chmod(0o755)
client = rpc.AppServer(self.root, False, AsyncMock())
with self.assertRaisesRegex(RuntimeError, 'invalid configuration'):
await client.__aenter__()
self.assertIsNotNone(client.proc.returncode)
self.assertTrue(client.err.closed)
if __name__ == '__main__':
unittest.main()
+3
View File
@@ -9,5 +9,8 @@ VITE_BASE=/pcb/
# AI and telemetry require explicitly configured services.
VITE_ENABLE_AI=false
# Set false in designer/.env.local to pause AI PCB connections and task polling.
VITE_ENABLE_PCB_AI=true
# Optional hosted 3D library override; defaults are in src/libraryHosts.ts.
VITE_MODELS3D_URL=
+12
View File
@@ -0,0 +1,12 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 94.2697 24" role="img" aria-labelledby="title">
<title id="title">make PCB</title>
<g>
<path fill="#3088e9" transform="translate(0.0000 18) scale(0.00976562 -0.00976562)" d="M1049 510V147Q1049 61 1010.0 18.0Q971 -25 907 -25Q845 -25 806.5 18.0Q768 61 768 147V582Q768 685 761.0 742.0Q754 799 723.0 835.5Q692 872 625 872Q491 872 448.5 780.0Q406 688 406 516V147Q406 62 367.5 18.5Q329 -25 266 -25Q204 -25 164.5 18.5Q125 62 125 147V928Q125 1005 160.5 1045.0Q196 1085 254 1085Q310 1085 347.5 1047.5Q385 1010 385 944V918Q456 1003 537.0 1043.0Q618 1083 717 1083Q820 1083 894.0 1042.0Q968 1001 1016 918Q1085 1002 1164.0 1042.5Q1243 1083 1339 1083Q1451 1083 1532.0 1039.0Q1613 995 1653 913Q1688 839 1688 680V147Q1688 61 1649.0 18.0Q1610 -25 1546 -25Q1484 -25 1444.5 18.5Q1405 62 1405 147V606Q1405 694 1397.5 747.0Q1390 800 1357.0 836.0Q1324 872 1257 872Q1203 872 1154.5 840.0Q1106 808 1079 754Q1049 685 1049 510Z"/>
<path fill="#f24c38" transform="translate(16.9953 18) scale(0.00976562 -0.00976562)" d="M831 129Q732 52 639.5 13.5Q547 -25 432 -25Q327 -25 247.5 16.5Q168 58 125.0 129.0Q82 200 82 283Q82 395 153.0 474.0Q224 553 348 580Q374 586 477.0 607.0Q580 628 653.5 645.5Q727 663 813 688Q808 796 769.5 846.5Q731 897 610 897Q506 897 453.5 868.0Q401 839 363.5 781.0Q326 723 310.5 704.5Q295 686 244 686Q198 686 164.5 715.5Q131 745 131 791Q131 863 182.0 931.0Q233 999 341.0 1043.0Q449 1087 610 1087Q790 1087 893.0 1044.5Q996 1002 1038.5 910.0Q1081 818 1081 666Q1081 570 1080.5 503.0Q1080 436 1079 354Q1079 277 1104.5 193.5Q1130 110 1130 86Q1130 44 1090.5 9.5Q1051 -25 1001 -25Q959 -25 918.0 14.5Q877 54 831 129ZM813 524Q753 502 638.5 477.5Q524 453 480.0 441.5Q436 430 396.0 396.5Q356 363 356 303Q356 241 403.0 197.5Q450 154 526 154Q607 154 675.5 189.5Q744 225 776 281Q813 343 813 485Z"/>
<path fill="#41b4a0" transform="translate(28.1801 18) scale(0.00976562 -0.00976562)" d="M821 100 580 496 432 356V139Q432 60 390.5 17.5Q349 -25 295 -25Q232 -25 196.0 17.0Q160 59 160 141V1305Q160 1396 195.0 1443.5Q230 1491 295 1491Q358 1491 395.0 1448.0Q432 1405 432 1321V659L739 981Q796 1041 826.0 1063.0Q856 1085 899 1085Q950 1085 984.0 1052.5Q1018 1020 1018 971Q1018 911 907 811L762 678L1042 238Q1073 189 1086.5 163.5Q1100 138 1100 115Q1100 50 1064.5 12.5Q1029 -25 971 -25Q921 -25 894.0 2.0Q867 29 821 100Z"/>
<path fill="#f4801d" transform="translate(38.9449 18) scale(0.00976562 -0.00976562)" d="M903 463H369Q370 370 406.5 299.0Q443 228 503.5 192.0Q564 156 637 156Q686 156 726.5 167.5Q767 179 805.0 203.5Q843 228 875.0 256.0Q907 284 958 332Q979 350 1018 350Q1060 350 1086.0 327.0Q1112 304 1112 262Q1112 225 1083.0 175.5Q1054 126 995.5 80.5Q937 35 848.5 5.0Q760 -25 645 -25Q382 -25 236.0 125.0Q90 275 90 532Q90 653 126.0 756.5Q162 860 231.0 934.0Q300 1008 401.0 1047.5Q502 1087 625 1087Q785 1087 899.5 1019.5Q1014 952 1071.0 845.0Q1128 738 1128 627Q1128 524 1069.0 493.5Q1010 463 903 463ZM369 618H864Q854 758 788.5 827.5Q723 897 616 897Q514 897 448.5 826.5Q383 756 369 618Z"/>
<path fill="#ffffff" transform="translate(54.1297 18) scale(0.02000000 -0.02000000)" d="M226 378V592H348Q375 592 400.0 588.0Q425 584 444.0 572.5Q463 561 474.5 540.0Q486 519 486 485Q486 451 474.5 430.0Q463 409 444.0 397.5Q425 386 400.0 382.0Q375 378 348 378ZM69 714V0H226V256H391Q458 256 505.0 275.5Q552 295 581.5 327.0Q611 359 624.5 400.5Q638 442 638 485Q638 529 624.5 570.0Q611 611 581.5 643.0Q552 675 505.0 694.5Q458 714 391 714Z"/>
<path fill="#ffffff" transform="translate(66.7697 18) scale(0.02000000 -0.02000000)" d="M545 474H697Q690 536 663.0 584.0Q636 632 594.5 664.5Q553 697 500.5 714.0Q448 731 389 731Q307 731 241.5 702.0Q176 673 131.0 622.0Q86 571 62.0 502.5Q38 434 38 354Q38 276 62.0 208.5Q86 141 131.0 91.0Q176 41 241.5 12.5Q307 -16 389 -16Q455 -16 510.0 4.0Q565 24 606.0 62.0Q647 100 672.0 154.0Q697 208 703 275H551Q542 203 501.5 159.0Q461 115 389 115Q336 115 299.0 135.5Q262 156 239.0 190.0Q216 224 205.5 266.5Q195 309 195 354Q195 401 205.5 445.0Q216 489 239.0 523.5Q262 558 299.0 578.5Q336 599 389 599Q418 599 444.5 589.5Q471 580 492.0 563.0Q513 546 527.0 523.5Q541 501 545 474Z"/>
<path fill="#ffffff" transform="translate(80.8897 18) scale(0.02000000 -0.02000000)" d="M226 425V592H373Q394 592 413.5 588.5Q433 585 448.0 576.0Q463 567 472.0 551.0Q481 535 481 510Q481 465 454.0 445.0Q427 425 385 425ZM69 714V0H415Q463 0 508.5 12.0Q554 24 589.5 49.0Q625 74 646.0 113.5Q667 153 667 207Q667 274 634.5 321.5Q602 369 536 388Q584 411 608.5 447.0Q633 483 633 537Q633 587 616.5 621.0Q600 655 570.0 675.5Q540 696 498.0 705.0Q456 714 405 714ZM226 122V318H397Q448 318 479.0 294.5Q510 271 510 216Q510 188 500.5 170.0Q491 152 475.0 141.5Q459 131 438.0 126.5Q417 122 394 122Z"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 4.6 KiB

+23
View File
@@ -17,6 +17,29 @@ if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker
.register(new URL('sw.js', appBase).href, { scope: appBase.href })
.then((registration) => {
// The platform launcher does not mount the editor's update watcher.
// Apply waiting builds here only while no project is open; otherwise
// an old cached entry can keep requesting chunks removed by a deploy.
const isLauncher = () =>
window.location.pathname.replace(/\/?$/, '/') === appBase.pathname;
let applying = false;
const activateWaiting = () => {
if (applying || !isLauncher() || !registration.waiting || !navigator.serviceWorker.controller) return;
applying = true;
registration.waiting.postMessage({ type: 'SKIP_WAITING' });
};
navigator.serviceWorker.addEventListener('controllerchange', () => {
if (applying && isLauncher()) window.location.reload();
});
registration.addEventListener('updatefound', () => {
const worker = registration.installing;
worker?.addEventListener('statechange', () => {
if (worker.state === 'installed') activateWaiting();
});
});
activateWaiting();
})
.catch((err) => {
console.warn('Service worker not registered; running without the offline cache:', err);
});
+24
View File
@@ -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';
@@ -2215,6 +2216,29 @@ export function App({ platform }: { platform?: PlatformBridge } = {}): JSX.Eleme
view={syncView}
>
{manager}
{!platform && (
<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');
}}
/>
)}
{!platform && view !== 'home' && <SaveIndicator />}
{aiEnabled() && <AiDock />}
{schMounted && (
+80 -67
View File
@@ -1,113 +1,126 @@
import { useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import './codex-pcb.css';
import { DesignPreview } from './DesignPreview.js';
import type { Artifact, Session, Entry } from './workbench-types.js';
import { DeliveryModel3D } from './DeliveryModel3D.js';
import { findObjArchive } from './model-appearance.js';
import { TaskProgress } from './TaskProgress.js';
import { Markdown as RichMarkdown } from '@ziroeda/ai/markdown.js';
import { parseApiResponse } from './api-response.js';
import { EnvironmentStatus, type RuntimeReadiness } from './EnvironmentStatus.js';
type Artifact = { name: string; kind: string; label: string; bytes: number; sha256: string };
type Session = { id: string; request: string; state: string; busy: boolean; ai_provider?: string; model?: string; effort?: string; thread_id?: string; error?: string; cursor: number; created_at: number; updated_at?: number; proposal?: { title: string; markdown: string; revision: number; hash: string; at?: number }; approval?: { revision: number; at?: number }; delivery?: { files: Artifact[]; notes: string }; };
type AiProvider = { id: string; label: string; model: string; effort: string; configured: boolean };
type ProviderConfig = { default_provider: string; providers: AiProvider[] };
type Entry = { seq: number; at: number; type: string; data: Record<string, unknown> };
const BASE = `${import.meta.env.BASE_URL}pcb-api`;
const ACTIVE = 'vibemake.pcb2.persistent-session';
const STATES: Record<string, string> = { planning: '正在制定方案', review: '等待审核方案', needs_input: '等待补充需求', running: '自主设计中', completed: '已完成交付', blocked: '遇到阻碍', failed: '运行失败', interrupted: '等待恢复', cancelled: '已停止' };
async function api<T>(path: string, data?: unknown): Promise<T> {
const r = await fetch(BASE + path, { method: data === undefined ? 'GET' : 'POST', headers: { 'Content-Type': 'application/json' }, body: data === undefined ? undefined : JSON.stringify(data) });
const value = await r.json();
if (!r.ok) throw new Error(typeof value.detail === 'string' ? value.detail : '请求失败,请重试');
return value as T;
const r = await fetch(BASE + path, { method: data === undefined ? 'GET' : 'POST', cache: 'no-store', headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, body: data === undefined ? undefined : JSON.stringify(data) });
return parseApiResponse<T>(r, BASE + path);
}
function text(value: unknown): string { return typeof value === 'string' ? value : ''; }
function Markdown({ value }: { value: string }): JSX.Element {
return <RichMarkdown text={value} className="cp-markdown"/>;
}
export function CodexPcbDock(): JSX.Element {
export function CodexPcbDock(): JSX.Element | null {
if (import.meta.env.VITE_ENABLE_PCB_AI === 'false') return null;
return <ConnectedCodexPcbDock />;
}
function ConnectedCodexPcbDock(): JSX.Element {
const [open, setOpen] = useState(new URLSearchParams(location.search).get('ai') === '1');
const [active, setActive] = useState<string | null>(() => localStorage.getItem(ACTIVE));
const [sessions, setSessions] = useState<Session[]>([]);
const [task, setTask] = useState<Session | null>(null);
const [entries, setEntries] = useState<Entry[]>([]);
const [request, setRequest] = useState('');
const [providers, setProviders] = useState<AiProvider[]>([]);
const [selectedProvider, setSelectedProvider] = useState('');
const [comment, setComment] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const [tab, setTab] = useState<'plan' | 'activity' | 'files'>('activity');
const [runtime, setRuntime] = useState<RuntimeReadiness | null>(null);
const [runtimeChecking, setRuntimeChecking] = useState(true);
const [runtimeError, setRuntimeError] = useState('');
const [runtimeRevision, setRuntimeRevision] = useState(0);
const [tab, setTab] = useState<'plan' | 'activity' | 'files'>('plan');
const cursor = useRef(0);
const activeRef = useRef(active);
const followChat = useRef(true);
const main = useRef<HTMLElement>(null);
// biome-ignore lint/correctness/useExhaustiveDependencies: changing the tab or task resets the content scroll position.
useEffect(() => { followChat.current = true; main.current?.scrollTo({ top: tab === 'activity' ? main.current.scrollHeight : 0 }); }, [tab, active]);
const choose = (id: string | null) => { setActive(id); setTask(null); setEntries([]); cursor.current = 0; activeRef.current = id; setTab('activity'); setComment(''); setError(''); if (id) localStorage.setItem(ACTIVE,id); else localStorage.removeItem(ACTIVE); };
const activity = useRef<HTMLDivElement>(null);
const choose = (id: string | null) => { setActive(id); setTask(null); setEntries([]); cursor.current = 0; activeRef.current = id; setTab('plan'); setError(''); if (id) localStorage.setItem(ACTIVE,id); else localStorage.removeItem(ACTIVE); };
const environmentReady = !runtimeChecking && !runtimeError && runtime?.ok === true && runtime.status === 'ready';
const recheckRuntime = () => { setRuntimeChecking(true); setRuntimeError(''); setRuntimeRevision(value => value + 1); };
// Check as soon as an opened project mounts this entry, even with the AI panel closed.
useEffect(() => {
let cancelled = false;
let timer: number;
let first = true;
const poll = async () => {
let delay = 15000;
try {
const report = await api<RuntimeReadiness>(first && runtimeRevision > 0 ? '/readiness/check' : '/readiness', first && runtimeRevision > 0 ? {} : undefined);
if (cancelled) return;
if (!report || typeof report.ok !== 'boolean' || !Array.isArray(report.checks) || !report.checks.every(check => check && typeof check.name === 'string' && typeof check.ok === 'boolean' && typeof check.message === 'string') || !['checking', 'ready', 'unavailable'].includes(report.status)) throw new Error('后端环境检查协议不匹配,请更新 PCB 后端。');
setRuntime(report); setRuntimeChecking(report.status === 'checking'); setRuntimeError('');
if (report.status === 'checking') delay = 1500;
} catch (e) {
if (!cancelled) { setRuntime(null); setRuntimeChecking(false); setRuntimeError(String(e)); }
} finally {
first = false;
if (!cancelled) timer = window.setTimeout(poll, delay);
}
};
void poll();
return () => { cancelled = true; clearTimeout(timer); };
}, [runtimeRevision]);
useEffect(() => { if (!open) return; let cancelled = false; let timer: number;
const poll = async () => {
try {
const list = await api<Session[]>('/sessions'); if (cancelled) return; setSessions(list);
const [list, config] = await Promise.all([api<Session[]>('/sessions'), api<ProviderConfig>('/providers')]); if (cancelled) return;
if (!Array.isArray(list) || !Array.isArray(config?.providers)) throw new Error('后端任务或 AI 服务列表协议不匹配,请更新 PCB 后端。');
setSessions(list); setProviders(config.providers); setSelectedProvider(current => current || config.default_provider);
if (active) {
const [next, changes] = await Promise.all([api<Session>(`/sessions/${active}`), api<Entry[]>(`/sessions/${active}/events?after=${cursor.current}`)]);
if (cancelled || activeRef.current !== active) return;
setTask(next);
if (changes.length) { cursor.current = changes[changes.length - 1]!.seq; setEntries(prev => [...prev, ...changes].slice(-600)); }
}
} catch (e) { if (!cancelled && activeRef.current === active) setError(String(e)); }
} catch (e) { if (!cancelled) setError(String(e)); }
finally { if (!cancelled) timer = window.setTimeout(poll, 2000); }
}; void poll(); return () => { cancelled = true; clearTimeout(timer); };
}, [open, active]);
useEffect(() => { if (tab === 'activity' && followChat.current) main.current?.scrollTo({ top: main.current.scrollHeight, behavior: 'smooth' }); }, [entries.length, tab]);
// biome-ignore lint/correctness/useExhaustiveDependencies: Entry count triggers scrolling when new activity arrives.
useEffect(() => { if (tab === 'activity') activity.current?.scrollTo({ top: activity.current.scrollHeight, behavior: 'smooth' }); }, [entries.length, tab]);
const action = async (fn: () => Promise<void>) => { setBusy(true); setError(''); try { await fn(); } catch(e) { setError(String(e)); } finally { setBusy(false); } };
const create = () => action(async () => { const t = await api<Session>('/sessions', { text: request }); choose(t.id); setTask(t); setRequest(''); });
const updateTask = (next: Session) => { if (activeRef.current === next.id) setTask(next); };
const send = () => action(async () => { const id = active; const t = await api<Session>(`/sessions/${id}/comments`, { text: comment }); updateTask(t); if (activeRef.current === id) { setComment(''); setTab('activity'); } });
const approve = () => action(async () => { if (!task?.proposal) return; const id = active; updateTask(await api<Session>(`/sessions/${id}/approve`, { revision: task.proposal.revision, hash: task.proposal.hash })); if (activeRef.current === id) setTab('activity'); });
const cancel = () => action(async () => { updateTask(await api<Session>(`/sessions/${active}/cancel`, {})); });
const resume = () => action(async () => { const id = active; updateTask(await api<Session>(`/sessions/${id}/resume`, {})); if (activeRef.current === id) setTab('activity'); });
const create = () => action(async () => { const t = await api<Session>('/sessions', { text: request, provider: selectedProvider }); choose(t.id); setTask(t); setRequest(''); });
const send = () => action(async () => { const t = await api<Session>(`/sessions/${active}/comments`, { text: comment }); setTask(t); setComment(''); });
const approve = () => action(async () => { if (!task?.proposal) return; setTask(await api<Session>(`/sessions/${active}/approve`, { revision: task.proposal.revision, hash: task.proposal.hash })); setTab('activity'); });
const cancel = () => action(async () => { setTask(await api<Session>(`/sessions/${active}/cancel`, {})); });
const resume = () => action(async () => { setTask(await api<Session>(`/sessions/${active}/resume`, {})); setTab('activity'); });
const downloadable = (f: Artifact) => `${BASE}/sessions/${active}/files/${encodeURIComponent(f.name)}`;
const step = task?.delivery?.files.find(f => f.kind === 'step' && /\.(step|stp)$/i.test(f.name));
const objArchive = findObjArchive(task?.delivery?.files ?? []);
const canReview = task && !task.approval && !task.busy && ['review','needs_input','failed'].includes(task.state);
const interesting = entries.filter(e => ['message','activity','eda.started','eda.error','session.reconnecting','session.failed','production.blocked','delivery.completed','proposal.approved','session.resumed'].includes(e.type));
const messages = interesting.filter(e => e.type === 'message');
const logs = interesting.filter(e => e.type !== 'message');
const setOpened = (value: boolean) => { setOpen(value); const url = new URL(location.href); if (value) url.searchParams.set('ai', '1'); else url.searchParams.delete('ai'); history.replaceState(null, '', url); };
const provider = providers.find(p => p.id === selectedProvider);
const taskProvider = providers.find(p => p.id === task?.ai_provider)?.label || task?.ai_provider || 'OpenAI';
const view = <div className="cp-root" data-native-text-shortcuts="true">
{!open ? <button className="cp-launch" onClick={() => setOpened(true)}>✦ Codex AI 自动绘板</button> : <section className="cp-window cp-workbench" aria-label="AI PCB 全屏工作台">
<header className="cp-header">
<div className="cp-brand"><strong>AI PCB <em>工作台</em></strong><span>从想法到真实电路板</span></div>
<div className="cp-workbench-actions"><select aria-label="选择设计任务" value={active ?? ''} disabled={busy} onChange={e => choose(e.target.value || null)}><option value="">新建设计</option>{sessions.map(s => <option key={s.id} value={s.id}>{s.proposal?.title || s.request.slice(0,36)} · {STATES[s.state] || s.state}</option>)}</select><button disabled={busy} onClick={() => choose(null)}>+ 新建设计</button><button className="cp-exit" onClick={() => setOpened(false)}>返回编辑器</button></div>
</header>
{active && task && <TaskProgress key={task.id} task={task} entries={entries} sessions={sessions}/>}
<div className="cp-workbench-body">
<DesignPreview key={active ?? 'new'} task={task}/>
<section className="cp-chat" aria-label="设计对话">
<header className="cp-chat-heading"><div><span className="cp-eyebrow">AI 设计助手</span><h2>{task?.proposal?.title || (task ? task.request.slice(0,60) : '一起设计你的电路板')}</h2></div>{task && <span className={`cp-status state-${task.state}`}>{task.busy && <i/>}{STATES[task.state] || task.state}</span>}</header>
<nav className="cp-tabs" aria-label="对话与交付"><button aria-selected={tab === 'activity'} onClick={() => setTab('activity')}>对话</button><button aria-selected={tab === 'plan'} onClick={() => setTab('plan')}>设计方案{task?.proposal ? ` · v${task.proposal.revision}` : ''}</button><button aria-selected={tab === 'files'} onClick={() => setTab('files')}>交付文件{task?.delivery ? ` · ${task.delivery.files.length}` : ''}</button></nav>
<main ref={main} className="cp-main" onScroll={e => { const el = e.currentTarget; followChat.current = el.scrollHeight - el.scrollTop - el.clientHeight < 80; }}>
{error && <div className="cp-error" role="alert">{error}<button onClick={() => setError('')} aria-label="关闭错误提示">×</button></div>}
{!active ? <div className="cp-chat-welcome"><div className="cp-assistant-avatar" aria-hidden="true">✦</div><h3>你想做一块怎样的电路板?</h3><p>告诉我用途、供电、接口和尺寸。我会先给出设计方案,确认后开始绘制。</p><ul><li>原理图与 PCB 布线过程在左侧自动更新</li><li>完成后查看 3D 模型,下载完整交付文件</li></ul></div> : !task ? <p className="cp-muted">正在加载设计…</p> : <>
{task.error && <div className="cp-error">{task.error}</div>}
{tab === 'activity' && <div className="cp-conversation">
{messages.map(e => <article key={e.seq} className={`cp-message ${text(e.data.role)}`}><header><strong>{e.data.role === 'user' ? '你' : 'AI 设计助手'}</strong><time>{new Date(e.at * 1000).toLocaleTimeString()}</time></header><Markdown value={text(e.data.text)}/></article>)}
{!messages.length && <article className="cp-message user"><header><strong>你</strong></header><p>{task.request}</p></article>}
{logs.length > 0 && <details className="cp-run-log"><summary>运行记录 · {logs.length} 条</summary>{logs.map(e => <article key={e.seq} className="cp-event"><time>{new Date(e.at * 1000).toLocaleTimeString()}</time><strong>{e.type === 'eda.started' ? '正在绘制 · ' + text(e.data.label) : e.type === 'activity' ? ({ commandExecution: '执行脚本', webSearch: '查阅资料', dynamicToolCall: '调用工具', fileChange: '编辑文件' }[text(e.data.kind)] || text(e.data.kind)) : ({ 'eda.error':'EDA 返回错误,AI 可继续处理', 'session.reconnecting':'正在恢复会话', 'session.failed':'会话失败', 'production.blocked':'遇到阻碍', 'delivery.completed':'交付校验通过', 'proposal.approved':'方案已确认,开始设计', 'session.resumed':'已继续原会话' }[e.type] || e.type)}</strong>{text(e.data.message) && <p>{text(e.data.message)}</p>}{text(e.data.command) && <details><summary>查看执行命令</summary><pre>{text(e.data.command)}</pre></details>}</article>)}</details>}
{task.proposal && !task.approval && <div className="cp-proposal-card"><strong>设计方案 v{task.proposal.revision} 已就绪</strong><p>先查看方案,在下方补充要求或确认开始绘制。</p><button onClick={() => setTab('plan')}>查看完整方案 →</button></div>}
{task.busy && <p className="cp-working" role="status"><i/>AI 正在继续处理,画面和消息会自动更新…</p>}
{task.approval && <details className="cp-session-info"><summary>会话信息</summary><code>{task.thread_id || '正在创建'}</code><p>模型:GPT-6.1 Sol · 方案与生产共用此会话</p></details>}
</div>}
{tab === 'plan' && <div className="cp-plan"><details><summary>原始需求</summary><p>{task.request}</p></details>{task.proposal ? <Markdown value={task.proposal.markdown}/> : <p className="cp-muted">AI 正在研究需求和制定方案。</p>}{task.approval && <div className="cp-approved">已确认方案 v{task.approval.revision},设计按此方案执行。</div>}</div>}
{tab === 'files' && <div className="cp-files">{!task.delivery ? <p className="cp-muted">完成设计和检查后,交付文件会显示在这里。生成过程可在左侧预览。</p> : <><p>{task.delivery.notes}</p><p className="cp-muted">交互式 3D 模型、原理图和布线图在左侧查看。</p>{task.delivery.files.map(f => <a className="cp-file" key={f.name} href={downloadable(f)} download><div><strong>{f.label}</strong><small>{f.name} · {(f.bytes / 1024).toFixed(1)} KB</small></div><span>下载 ↓</span></a>)}</>}</div>}
</>}
</main>
<form className="cp-composer" onSubmit={event => { event.preventDefault(); if (busy) return; if (!active && request.trim().length >= 5) void create(); else if (canReview && comment.trim().length >= 5) void send(); }}>
<label htmlFor="cp-compose">{!active ? '描述你的设计需求' : canReview ? '补充要求或修改方案' : '设计沟通'}</label>
<textarea id="cp-compose" rows={3} value={!active ? request : comment} disabled={busy || (!!active && !canReview)} onChange={e => active ? setComment(e.target.value) : setRequest(e.target.value)}
onKeyDown={event => { if ((event.ctrlKey || event.metaKey) && event.key === 'Enter' && !event.nativeEvent.isComposing) { event.preventDefault(); event.currentTarget.form?.requestSubmit(); } }}
placeholder={!active ? '例如:设计 ESP32 最小系统板,5V 供电,带下载接口…' : canReview ? '输入需要调整的地方,AI 会更新设计方案…' : task?.state === 'completed' ? '本次设计已完成,可查看交付文件或新建设计。' : task?.approval ? '正在按已确认方案制作,可在对话中查看最新进展。' : 'AI 正在处理,方案就绪后可继续沟通…'}/>
<div className="cp-compose-actions"><small>{!active || canReview ? '⌘ / Ctrl + Enter 发送' : '关闭页面,后台仍会继续'}</small><div>
{!active && <button type="submit" className="cp-primary" disabled={busy || request.trim().length < 5}>{busy ? '正在提交…' : '发送需求 →'}</button>}
{canReview && <><button type="submit" disabled={busy || comment.trim().length < 5}>发送修改意见</button><button type="button" className="cp-primary" disabled={busy || task.state !== 'review' || !!comment.trim()} onClick={approve}>确认方案并开始</button></>}
{task?.busy && <button type="button" className="cp-stop" disabled={busy} onClick={cancel}>停止运行</button>}
{task && !task.busy && task.approval && ['failed','blocked','cancelled','interrupted'].includes(task.state) && <button type="button" disabled={busy} onClick={resume}>继续此设计</button>}
{task?.state === 'completed' && <button type="button" onClick={() => choose(null)}>开始新设计</button>}
</div></div>{canReview && comment.trim() && <small className="cp-muted">请先发送修改意见,待新方案生成后再确认。</small>}
</form>
</section>
</div>
{!open ? <><div className="cp-environment-notice"><EnvironmentStatus report={runtime} checking={runtimeChecking} error={runtimeError} compact onRetry={recheckRuntime} onOpen={() => setOpen(true)}/></div><button className="cp-launch" onClick={() => setOpen(true)}>✦ Codex AI 自动绘板</button></> : <section className="cp-window" aria-label="Codex PCB 工作台">
<header className="cp-header"><div><strong>Codex PCB 工作台</strong><span>从方案到真实电路板</span></div><button className="cp-close" onClick={() => setOpen(false)} aria-label="关闭工作台">×</button></header>
<div className="cp-body"><aside className="cp-sidebar"><button className="cp-primary" onClick={() => choose(null)}>+ 新建设计</button><p className="cp-muted">设计记录</p>{sessions.map(s => <button key={s.id} className={`cp-session ${s.id === active ? 'selected' : ''}`} onClick={() => choose(s.id)}><strong>{s.proposal?.title || s.request.slice(0,36)}</strong><small>{STATES[s.state] || s.state}</small></button>)}<div className="cp-side-note">审核方案后开始设计。<br/>关闭网页,后台仍会继续。</div></aside>
<div className="cp-content">{active && task && <TaskProgress key={task.id} task={task} entries={entries} sessions={sessions}/>}
<main className="cp-main"><EnvironmentStatus report={runtime} checking={runtimeChecking} error={runtimeError} onRetry={recheckRuntime}/>{error && <div className="cp-error" role="alert">{error}<button onClick={() => setError('')}>×</button></div>}
{!active ? <div className="cp-intake"><div className="cp-eyebrow">让需求成为电路板</div><h1>你想设计什么?</h1><p>描述用途、供电、接口和尺寸要求。AI 会先提出方案,由你审核后再开始绘制。</p><div className="cp-provider"><label htmlFor="cp-provider">AI 服务</label><select id="cp-provider" value={selectedProvider} onChange={e => setSelectedProvider(e.target.value)} disabled={busy || !providers.length} aria-describedby="cp-provider-help">{!providers.length && <option value="">正在读取服务配置…</option>}{providers.map(p => <option key={p.id} value={p.id} disabled={!p.configured}>{p.label} · {p.model}{!p.configured ? '(未配置凭据)' : ''}</option>)}</select><small id="cp-provider-help">{provider && !provider.configured ? `${provider.label} 尚未配置服务端凭据,请先配置后端或选择其他服务。` : '所选服务及模型在本次设计中保持固定;新建设计时可以切换。'}</small></div><textarea aria-label="设计需求" value={request} onChange={e => setRequest(e.target.value)} placeholder="例如:设计一块 ESP32 最小系统板,5V 供电,带下载接口、复位和 BOOT 按键,双层板……" rows={7}/><button className="cp-primary" disabled={busy || !environmentReady || !provider?.configured || request.trim().length < 5} aria-describedby={!environmentReady ? "cp-environment-help" : undefined} onClick={create}>{busy ? '正在提交…' : '生成设计方案 →'}</button>{!environmentReady && <p id="cp-environment-help" className="cp-muted">绘板环境检查通过后才能生成方案。</p>}<div className="cp-delivery-hint">最终交付:原理图 · Layout · 板子 STEP · 3D 渲染图 · 可编辑工程</div></div> : !task ? <p>正在加载设计…</p> : <>
<div className="cp-task-header"><div><h2>{task.proposal?.title || task.request.slice(0,60)}</h2><span className={`cp-status state-${task.state}`}>{task.busy && <i/>}{STATES[task.state] || task.state}</span></div>{task.busy && <button className="cp-stop" disabled={busy} onClick={cancel}>停止运行</button>}{!task.busy && task.approval && ['failed','blocked','cancelled','interrupted'].includes(task.state) && <button disabled={busy || !environmentReady} onClick={resume}>继续此设计</button>}</div>
<p className="cp-task-model">{taskProvider} · {task.model || '原会话模型'}</p>
<nav className="cp-tabs"><button aria-selected={tab === 'plan'} onClick={() => setTab('plan')}>设计方案{task.proposal ? ` · v${task.proposal.revision}` : ''}</button><button aria-selected={tab === 'activity'} onClick={() => setTab('activity')}>运行记录</button><button aria-selected={tab === 'files'} onClick={() => setTab('files')}>交付文件{task.delivery ? ` · ${task.delivery.files.length}` : ''}</button></nav>
{task.error && <div className="cp-error">{task.error}</div>}
{tab === 'plan' && <div className="cp-plan"><details><summary>原始需求</summary><p>{task.request}</p></details>{task.proposal ? <Markdown value={task.proposal.markdown}/> : <p className="cp-muted">AI 正在研究需求和制定方案,可以在运行记录中查看进度。</p>}{task.approval && <div className="cp-approved">已确认方案 v{task.approval.revision},设计按此方案执行。</div>}{canReview && <div className="cp-review"><label htmlFor="cp-comment">对方案有修改意见?</label><textarea id="cp-comment" value={comment} onChange={e => setComment(e.target.value)} placeholder="补充要求或指出需要修改的地方…" rows={3}/><div className="cp-actions"><button disabled={busy || !environmentReady || comment.trim().length < 5} onClick={send}>提交意见,修改方案</button><button className="cp-primary" disabled={busy || !environmentReady || task.state !== 'review' || !!comment.trim()} onClick={approve}>同意此方案,开始运行</button></div>{comment.trim() && <small>请先提交修改意见,待新方案生成后再确认。</small>}</div>}</div>}
{tab === 'activity' && <div className="cp-activity" ref={activity}>{interesting.map(e => <article key={e.seq} className={e.type === 'message' ? `cp-message ${text(e.data.role)}` : 'cp-event'}><time>{new Date(e.at * 1000).toLocaleTimeString()}</time>{e.type === 'message' ? <Markdown value={text(e.data.text)}/> : <><strong>{e.type === 'eda.started' ? '嘉立创 EDA · ' + text(e.data.label) : e.type === 'activity' ? ({ commandExecution: '执行脚本', webSearch: '查阅资料', dynamicToolCall: '调用工具', fileChange: '编辑文件' }[text(e.data.kind)] || text(e.data.kind)) : ({ 'eda.error':'EDA 返回错误,AI 可继续处理', 'session.reconnecting':'正在恢复会话', 'session.failed':'会话失败', 'production.blocked':'遇到阻碍', 'delivery.completed':'交付校验通过', 'proposal.approved':'方案已确认,开始设计', 'session.resumed':'已继续原会话' }[e.type] || e.type)}</strong>{text(e.data.message) && <p>{text(e.data.message)}</p>}{text(e.data.command) && <details><summary>查看执行命令</summary><pre>{text(e.data.command)}</pre></details>}</>}</article>)}{task.busy && <p className="cp-muted">● AI 正在继续处理,请稍候…</p>}<details className="cp-session-info"><summary>会话信息</summary><code>{task.thread_id || '正在创建'}</code><p>模型:{taskProvider} · {task.model || '原会话模型'} · 方案与生产共用此会话</p></details></div>}
{tab === 'files' && <div className="cp-files">{!task.delivery ? <p className="cp-muted">完成设计和原生检查后,交付文件会显示在这里。</p> : <>{step && <DeliveryModel3D key={`${active}/${step.name}/${step.sha256}`} url={downloadable(step)} sha256={step.sha256} name={step.name} objUrl={objArchive ? downloadable(objArchive) : undefined} objSha256={objArchive?.sha256}/>}<p>{task.delivery.notes}</p>{task.delivery.files.filter(f => ['render','layout','schematic'].includes(f.kind) && /\.(png|jpe?g|svg)$/i.test(f.name)).map(f => <figure key={f.name}><img src={downloadable(f)} alt={f.label}/><figcaption>{f.label}</figcaption></figure>)}{task.delivery.files.map(f => <a className="cp-file" key={f.name} href={downloadable(f)} download><div><strong>{f.label}</strong><small>{f.name} · {(f.bytes / 1024).toFixed(1)} KB</small></div><span>下载 ↓</span></a>)}</>}</div>}
</>}
</main></div></div>
</section>}
</div>;
return createPortal(view, document.body);
@@ -0,0 +1,39 @@
export type RuntimeReadiness = {
ok: boolean;
status: 'checking' | 'ready' | 'unavailable';
checked_at: number | null;
checks: { name: string; ok: boolean; message: string }[];
};
const LABELS: Record<string, string> = {
runtime_write: '运行目录', home_write: '客户端数据目录', codex_home_write: 'AI 会话目录',
workspace_write: '设计工作区', temporary_write: '临时目录', codex_binary: 'AI 命令程序',
eda_binary: 'EasyEDA 程序权限', blender_binary: 'Blender 程序', api_references: 'EDA API 文档',
freerouting: '布线工具', codex_sandbox: 'AI 终端沙箱', eda_launch: 'EasyEDA 启动',
eda_bridge: 'EasyEDA 命令桥接', eda_cleanup: '诊断会话清理', runtime_check: '运行环境',
};
export function EnvironmentStatus({ report, checking, error, compact = false, onRetry, onOpen }: {
report: RuntimeReadiness | null;
checking: boolean;
error: string;
compact?: boolean;
onRetry: () => void;
onOpen?: () => void;
}): JSX.Element | null {
if (!checking && !error && report?.ok && report.status === 'ready') return null;
const failed = report?.checks.filter(check => !check.ok) ?? [];
return <section className={`cp-environment${compact ? ' is-compact' : ''}`}
role={checking ? 'status' : 'alert'} aria-label="绘板环境状态" aria-live={checking ? 'polite' : 'assertive'}>
<strong>{checking ? '正在检查绘板环境…' : '绘板环境未就绪,暂不能生成'}</strong>
<p>{checking ? '正在验证文件权限、AI 沙箱和真实 EasyEDA 命令桥接,检查完成前不会提交生成任务。'
: compact ? '请打开工作台查看失败项,修复后重新检查。' : '请先修复以下问题,再创建方案或开始绘板。'}</p>
{!compact && <>{error && <p className="cp-environment-error">{error}</p>}
{!!failed.length && <ul>{failed.map(check => <li key={check.name}><strong>{LABELS[check.name] || check.name}</strong><p>{check.message}</p></li>)}</ul>}
</>}
<div className="cp-environment-actions">
{compact && onOpen && <button onClick={onOpen}>查看检查结果</button>}
<button onClick={onRetry} disabled={checking}>{checking ? '检查中…' : '重新检查环境'}</button>
</div>
</section>;
}
+27
View File
@@ -0,0 +1,27 @@
/** Preserve useful API errors when a reverse proxy responds with an HTML page. */
export async function parseApiResponse<T>(response: Response, path: string): Promise<T> {
const source = await response.text();
const context = `${path}(HTTP ${response.status})`;
let value: unknown;
try {
value = JSON.parse(source);
} catch {
const html = /text\/html/i.test(response.headers.get('Content-Type') || '') || /^\s*</.test(source);
if (!response.ok) {
const hint = [502, 503, 504].includes(response.status)
? '网关无法正常连接 PCB 后端,请检查后端容器、代理上游地址及端口。'
: '请检查代理配置和后端日志。';
throw new Error(`${context}:${html ? '返回了 HTML 错误页' : '未返回有效 JSON'}。${hint}`);
}
throw new Error(`${context}:${html ? '返回了网页,请检查 /pcb/pcb-api/ 是否被前端路由回退或登录跳转接管' : '返回内容不是有效 JSON'}。`);
}
if (!response.ok) {
const error = value && typeof value === 'object' ? value as Record<string, unknown> : {};
const detail = typeof error.detail === 'string' ? error.detail
: typeof error.message === 'string' ? error.message
: Array.isArray(error.detail) ? error.detail.map(item => item && typeof item.msg === 'string' ? item.msg : '').filter(Boolean).join(';')
: '';
throw new Error(`${context}:${detail || '请求失败,请检查后端日志。'}`);
}
return value as T;
}
File diff suppressed because one or more lines are too long
+84 -21
View File
@@ -102,12 +102,17 @@ const kindNames: Record<string, string> = {
fabrication_info: '工艺信息',
};
export function PcbServiceDock({
onImport,
}: {
type PcbServiceDockProps = {
onImport?: (bytes: Uint8Array, task: Task) => Promise<void>;
}) {
const [open, setOpen] = useState(() => new URLSearchParams(location.search).get('ai') === '1'),
};
export function PcbServiceDock(props: PcbServiceDockProps) {
if (import.meta.env.VITE_ENABLE_PCB_AI === 'false') return null;
return <ConnectedPcbServiceDock {...props} />;
}
function ConnectedPcbServiceDock({ onImport }: PcbServiceDockProps) {
const [open, setOpen] = useState(false),
[tasks, setTasks] = useState<Task[]>([]),
[id, setId] = useState<string | null>(() => stored(ACTIVE));
const [queued, setQueued] = useState<Queued | null>(queuedCommand);
@@ -115,6 +120,9 @@ export function PcbServiceDock({
[pending, setPending] = useState<string | null>(() => stored(PENDING)),
[events, setEvents] = useState<Progress[]>([]);
const [connected, setConnected] = useState(false),
[connecting, setConnecting] = useState(true),
[connectionError, setConnectionError] = useState(''),
[connectionAttempt, setConnectionAttempt] = useState(0),
[error, setError] = useState(''),
[text, setText] = useState(''),
[answer, setAnswer] = useState(''),
@@ -134,25 +142,56 @@ export function PcbServiceDock({
useEffect(() => {
if (open) return installNativeTextClipboard();
}, [open]);
const refresh = useCallback(async () => {
const data = await request<{ items: Task[] }>('/tasks');
const refresh = useCallback(async (signal?: AbortSignal) => {
const data = await request<{ items: Task[] }>('/tasks', { signal });
if (signal?.aborted) return;
if (!Array.isArray(data.items))
throw new Error('PCB 后台响应格式不正确,请确认连接的是 AI 生成服务。');
setTasks(data.items);
setConnected(true);
}, []);
// biome-ignore lint/correctness/useExhaustiveDependencies: The retry counter explicitly restarts the connection effect.
useEffect(() => {
let alive = true;
void request('/session')
.then(() => refresh())
.catch(() => {
let controller: AbortController;
let timeout: ReturnType<typeof setTimeout> | undefined;
let retry: ReturnType<typeof setTimeout> | undefined;
setConnecting(true);
setConnectionError('');
const connect = async () => {
controller = new AbortController();
timeout = setTimeout(() => controller.abort(), 10000);
let delay = 15000;
try {
await request('/session', { signal: controller.signal });
if (!alive) return;
await refresh(controller.signal);
if (!alive || controller.signal.aborted) return;
setConnectionError('');
} catch (e) {
if (!alive) return;
setConnected(false);
const reason = controller.signal.aborted
? '连接 AI PCB 后台超时。'
: `无法连接 AI PCB 后台:${(e as Error).message}`;
setConnectionError(`${reason}请检查后台服务和网络连接,5 秒后自动重试。`);
delay = 5000;
} finally {
clearTimeout(timeout);
if (alive) {
setConnected(false);
setError('暂时无法连接 PCB 后台。请检查启动终端中的 PCB_API_TARGET 配置。');
setConnecting(false);
retry = setTimeout(() => void connect(), delay);
}
});
}
};
void connect();
return () => {
alive = false;
controller?.abort();
clearTimeout(timeout);
clearTimeout(retry);
};
}, [refresh]);
}, [refresh, connectionAttempt]);
useEffect(() => {
remember(ACTIVE, id);
setTask(null);
@@ -445,17 +484,30 @@ export function PcbServiceDock({
const feedback = feedbackDraft?.key === feedbackKey ? feedbackDraft.text : '';
return createPortal(
<div className="ze-app pcb-service-root">
<button className="pcb-service-launch" onClick={() => setOpen((v) => !v)}>
Codex AI 自动绘板
<button
className="pcb-service-launch"
aria-expanded={open}
aria-controls="pcb-service-workspace"
onClick={() => setOpen((v) => !v)}
>
AI 自动绘板
</button>
{open && (
<section className="pcb-service-window" role="dialog" aria-label="Codex PCB 设计工作台"
data-native-text-shortcuts="true" onPaste={(event) => event.stopPropagation()}>
<section
id="pcb-service-workspace"
className="pcb-service-window"
role="dialog"
data-native-text-shortcuts="true"
onPaste={(event) => event.stopPropagation()}
aria-label="AI PCB 设计工作台"
>
<header>
<div>
<strong>Codex PCB 设计工作台</strong>
<small>
{connected ? '已连接服务端 · 后台生成' : '连接后台中'} · 关闭此窗口不会取消任务
<strong>AI PCB 设计工作台</strong>
<small role="status">
{connected
? '已连接服务端 · 后台生成'
: connecting ? '连接后台中' : '后台未连接'} · 关闭此窗口不会取消任务
</small>
</div>
<button aria-label="关闭 PCB 工作台" onClick={() => setOpen(false)}>
@@ -476,6 +528,17 @@ export function PcbServiceDock({
<DesignHistory tasks={tasks} selected={id} disabled={busy} onSelect={(next)=>next ? setId(next) : newDesign()} onManage={manageHistory}/>
</div>
{connectionError && (
<div role="alert" className="pcb-service-warning">
<p>{connectionError}</p>
<button
disabled={connecting}
onClick={() => setConnectionAttempt((attempt) => attempt + 1)}
>
重新连接
</button>
</div>
)}
{error && (
<div role="alert" className="pcb-service-warning">
{error}
+4 -4
View File
@@ -72,12 +72,12 @@ export class ApiError extends Error {
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);
await request('/session', { signal: init.signal }, false);
return request(path, init, false);
}
const data = await r
.json()
.catch(() => ({ message: 'PCB 服务返回了无法识别的响应,请检查服务地址。' }));
const data = await r.json().catch(() => {
throw new ApiError('PCB 服务返回了无法识别的响应,请检查服务地址。', r.status);
});
if (!r.ok)
throw new ApiError(data.message || data.detail || `PCB 服务请求失败 (${r.status})`, r.status);
return data as T;
+25 -1
View File
@@ -643,7 +643,6 @@ function Workspace({
);
return (
<div className={`vm-platform vm-cad-design${route.code ? ' vm-platform-editor' : ''}`}>
<Suspense fallback={null}><CodexPcbDock /></Suspense>
{!activeWorkbench && (
<>
<PlatformHeader {...headerProps} editor={!!route.code} />
@@ -728,6 +727,11 @@ function Workspace({
importProject={create}
/>
)}
{activeWorkbench && allowed && api && auth.status === 'authenticated' && (
<Suspense fallback={null}>
<CodexPcbDock key={auth.record?.user.userCode} />
</Suspense>
)}
{!allowed && (
<div className="vm-desktop-mask" role="alert">
<h1>{tr('请在电脑端使用 PCB 编辑器', 'Open PCB on a desktop computer')}</h1>
@@ -834,6 +838,7 @@ function MockBar(): JSX.Element {
<option value="expired">签名过期 / Expired signature</option>
<option value="conflict">版本冲突 / Conflict</option>
<option value="too-large">超限 / Limit exceeded</option>
<option value="cover-failed">封面上传失败 / Cover upload failed</option>
</select>
</label>
</aside>
@@ -1016,6 +1021,7 @@ function Workbench({
status={
<span className={`vm-save-status cad-save-state ${state.phase}`} role="status">
{states[state.phase]}
{state.coverUpdating && tr(' · 正在更新封面…', ' · Updating cover…')}
</span>
}
>
@@ -1134,6 +1140,24 @@ function Workbench({
)}
</div>
)}
{state.coverWarning && (
<div className="vm-warning" role="alert">
{tr(
'工程已保存,封面更新失败。可重试更新封面。',
'Design saved. Cover update failed; you can retry.',
)}
<button
onClick={() => void runtime.retryCover()}
disabled={
state.coverUpdating ||
state.inputLocked ||
['preparing', 'uploading', 'confirming'].includes(state.phase)
}
>
{tr('重试封面', 'Retry cover')}
</button>
</div>
)}
{saveBlocked && (
<SaveBlockedNotice
retry={save}
+13 -6
View File
@@ -158,12 +158,19 @@ export function PlatformHeader({
}
>
<img
src={`${import.meta.env.BASE_URL}brand/make-web-384.png`}
srcSet={[256, 384, 512, 768]
.map((width) => `${import.meta.env.BASE_URL}brand/make-web-${width}.png ${width}w`)
.join(', ')}
sizes={editor ? '92px' : '(max-width: 820px) 96px, 112px'}
alt="make"
src={`${import.meta.env.BASE_URL}brand/${editor ? 'make-pcb.svg' : 'make-web-384.png'}`}
srcSet={
editor
? undefined
: [256, 384, 512, 768]
.map(
(width) =>
`${import.meta.env.BASE_URL}brand/make-web-${width}.png ${width}w`,
)
.join(', ')
}
sizes={editor ? undefined : '(max-width: 820px) 96px, 112px'}
alt={editor ? 'make PCB' : 'make'}
width={editor ? 92 : 112}
height={editor ? 34 : 42}
/>
@@ -0,0 +1,52 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import { useEffect, useRef } from 'react';
import { PcbServiceDock } from '../pcb-service/PcbServiceDock.js';
import { WorkspaceError, type NativeProject, type PcbProjectApi } from './types.js';
/** AI deliveries use the same project creation and leave guard as ordinary imports. */
export default function PlatformPcbService({
api,
importProject,
}: {
api: PcbProjectApi;
importProject: (name: string, project: NativeProject, requestId: string) => Promise<void>;
}): JSX.Element {
const mounted = useRef(false);
const currentApi = useRef(api);
currentApi.current = api;
const copies = useRef(new Map<string, { name: string; requestId: string }>());
useEffect(() => {
mounted.current = true;
return () => {
mounted.current = false;
};
}, []);
return (
<PcbServiceDock
onImport={async (bytes, task) => {
if (!task.delivery?.manifest_sha256) throw new Error('工程缺少来源摘要');
const key = `${task.task_id}:${task.delivery.manifest_sha256}`;
let copy = copies.current.get(key);
if (!copy) {
copy = { name: `AI-${task.task_id}-${Date.now()}`, requestId: crypto.randomUUID() };
copies.current.set(key, copy);
}
const [{ convertProject }, { importFiles }] = await Promise.all([
import('../pcb-service/import-project.js'),
import('./archive.js'),
]);
const [result, limits] = await Promise.all([
convertProject(bytes, copy.name, {
task_id: task.task_id,
manifest_sha256: task.delivery.manifest_sha256,
}),
api.capabilities(),
]);
if (!mounted.current || currentApi.current !== api)
throw new WorkspaceError('STALE_BINDING');
await importProject(copy.name, importFiles(result.files, limits), copy.requestId);
copies.current.delete(key);
}}
/>
);
}
+22
View File
@@ -0,0 +1,22 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import { useState } from 'react';
import { CircuitIcon } from './CircuitIcon.js';
export function ProjectCover({ url }: { url: string | null }): JSX.Element {
const [failedUrl, setFailedUrl] = useState<string | null>(null);
return url && failedUrl !== url ? (
<img
className="vm-project-cover"
src={url}
width={800}
height={450}
alt=""
loading="lazy"
decoding="async"
referrerPolicy="no-referrer"
onError={() => setFailedUrl(url)}
/>
) : (
<CircuitIcon />
);
}
+2 -1
View File
@@ -3,6 +3,7 @@ import { lazy, Suspense, useEffect, useState } from 'react';
import type { NativeProject, PcbProject, PcbProjectApi } from './types.js';
import { Modal, NameForm, errorText, useTr } from './ui.js';
import { CircuitIcon } from './CircuitIcon.js';
import { ProjectCover } from './ProjectCover.js';
import { SiteIcon } from './SiteIcon.js';
import '../assets/site-brand/css/cad.css';
const CatalogImport = lazy(() => import('./CatalogImport.js'));
@@ -207,7 +208,7 @@ export function ProjectList({
open(project);
}}
>
<CircuitIcon />
<ProjectCover url={project.coverUrl} />
</a>
<div className="cad-card-body">
<h2>{project.name}</h2>
+65 -3
View File
@@ -2,6 +2,7 @@
import {
WorkspaceError,
DEFAULT_LIMITS,
MAX_COVER_BYTES,
copyBytes,
platformTime,
validProjectCode,
@@ -10,6 +11,7 @@ import {
type PcbProject,
type PcbProjectApi,
type ProjectDocument,
type ProjectCover,
type SaveReceipt,
type UploadRequest,
type UploadSignature,
@@ -122,7 +124,7 @@ export class HttpPcbProjectApi implements PcbProjectApi {
try {
const value = await platformRequest<T>(url, this.identity.token, {
...init,
signal: this.signal,
signal: init?.signal ? AbortSignal.any([this.signal, init.signal]) : this.signal,
});
this.assert();
return value;
@@ -188,8 +190,8 @@ export class HttpPcbProjectApi implements PcbProjectApi {
throw error;
}
}
async get(code: string): Promise<PcbProject> {
const value = project(await this.call<PcbProject>(path(code)));
async get(code: string, signal?: AbortSignal): Promise<PcbProject> {
const value = project(await this.call<PcbProject>(path(code), { signal }));
if (value.pcbProjectCode !== code) throw new WorkspaceError('BAD_RESPONSE');
return value;
}
@@ -200,6 +202,66 @@ export class HttpPcbProjectApi implements PcbProjectApi {
if (value.pcbProjectCode !== code) throw new WorkspaceError('BAD_RESPONSE');
return value;
}
async uploadCover(cover: ProjectCover, signal?: AbortSignal): Promise<string> {
this.assert();
if (!['image/webp', 'image/png'].includes(cover.contentType) || !cover.bytes.length)
throw new WorkspaceError('PCB_INVALID_COVER');
if (cover.bytes.length > MAX_COVER_BYTES) throw new WorkspaceError('PCB_COVER_TOO_LARGE');
const signature = await this.call<{
uploadUrl: string;
formFields: Record<string, string>;
coverUrl: string;
}>('/uploads/project-covers/signature', {
method: 'POST',
body: JSON.stringify({ contentType: cover.contentType, fileSize: cover.bytes.length }),
signal,
});
if (
!signature?.formFields ||
typeof signature.formFields !== 'object' ||
Array.isArray(signature.formFields) ||
Object.values(signature.formFields).some((value) => typeof value !== 'string')
)
throw new WorkspaceError('BAD_RESPONSE');
const uploadUrl = objectUrl(signature.uploadUrl);
const coverUrl = objectUrl(signature.coverUrl);
const form = new FormData();
for (const [key, value] of Object.entries(signature.formFields)) form.append(key, value);
form.append(
'file',
new Blob([copyBytes(cover.bytes)], { type: cover.contentType }),
cover.contentType === 'image/webp' ? 'cover.webp' : 'cover.png',
);
const response = await fetch(uploadUrl, {
method: 'POST',
body: form,
credentials: 'omit',
referrerPolicy: 'no-referrer',
signal: AbortSignal.any([
this.signal,
...(signal ? [signal] : []),
AbortSignal.timeout(20000),
]),
});
this.assert();
signal?.throwIfAborted();
if (response.status !== 200)
throw new WorkspaceError('PCB_OSS_ERROR', 'Cover upload failed', response.status);
return coverUrl;
}
async setCover(code: string, coverUrl: string, signal?: AbortSignal): Promise<PcbProject> {
if (coverUrl) objectUrl(coverUrl);
const value = project(
await this.call<PcbProject>(path(code), {
method: 'PATCH',
body: JSON.stringify({ coverUrl }),
signal,
}),
);
if (value.pcbProjectCode !== code || (value.coverUrl ?? '') !== coverUrl)
throw new WorkspaceError('BAD_RESPONSE');
return value;
}
async remove(code: string): Promise<void> {
await this.call(path(code), { method: 'DELETE' });
}
+114
View File
@@ -0,0 +1,114 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import {
copyBytes,
MAX_COVER_BYTES,
WorkspaceError,
type Capabilities,
type ProjectCover,
} from './types.js';
import type { CoverSvg } from './cover-renderer.js';
function vector(
bytes: Uint8Array,
limits: Capabilities,
signal: AbortSignal,
): Promise<CoverSvg | null> {
return new Promise((resolve, reject) => {
const worker = new Worker(new URL('./cover.worker.ts', import.meta.url), { type: 'module' });
const stop = (): void => {
worker.terminate();
signal.removeEventListener('abort', abort);
};
const abort = (): void => {
stop();
reject(signal.reason);
};
if (signal.aborted) {
abort();
return;
}
signal.addEventListener('abort', abort, { once: true });
worker.onmessage = ({ data }) => {
stop();
data.error ? reject(new Error(data.error)) : resolve(data.value);
};
worker.onerror = () => {
stop();
reject(new Error('Cover worker failed'));
};
worker.postMessage({ bytes, limits });
});
}
/** Hard deadline covers module loading, native plotting, decoding and encoding. */
export async function generateProjectCover(
bytes: Uint8Array,
limits: Capabilities,
signal: AbortSignal,
): Promise<ProjectCover | null> {
const deadline = AbortSignal.any([signal, AbortSignal.timeout(12000)]);
const result = await vector(bytes, limits, deadline);
deadline.throwIfAborted();
if (!result) return null;
const url = URL.createObjectURL(new Blob([result.svg], { type: 'image/svg+xml' }));
const img = new Image();
try {
await new Promise<void>((resolve, reject) => {
const clean = (): void => {
deadline.removeEventListener('abort', abort);
img.onload = null;
img.onerror = null;
};
const abort = (): void => {
clean();
img.src = '';
reject(deadline.reason);
};
img.onload = () => {
clean();
resolve();
};
img.onerror = () => {
clean();
reject(new Error('Cover image could not be decoded'));
};
if (deadline.aborted) {
abort();
return;
}
deadline.addEventListener('abort', abort, { once: true });
img.src = url;
});
const canvas = document.createElement('canvas');
canvas.width = 800;
canvas.height = 450;
const ctx = canvas.getContext('2d');
if (!ctx) throw new Error('Cover canvas unavailable');
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
const blob = await new Promise<Blob>((resolve, reject) => {
const abort = (): void => reject(deadline.reason);
if (deadline.aborted) {
abort();
return;
}
deadline.addEventListener('abort', abort, { once: true });
canvas.toBlob(
(value) => {
deadline.removeEventListener('abort', abort);
if (value) resolve(value);
else reject(new Error('Cover encoding failed'));
},
'image/webp',
0.86,
);
});
if (blob.type !== 'image/webp' && blob.type !== 'image/png')
throw new Error('Unsupported cover encoding');
if (blob.size > MAX_COVER_BYTES) throw new WorkspaceError('PCB_COVER_TOO_LARGE');
const output = copyBytes(new Uint8Array(await blob.arrayBuffer()));
deadline.throwIfAborted();
return { bytes: output, contentType: blob.type };
} finally {
URL.revokeObjectURL(url);
}
}
+260
View File
@@ -0,0 +1,260 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import type { NativeProject } from './types.js';
export const COVER_WIDTH = 800;
export const COVER_HEIGHT = 450;
export const COVER_BACKGROUND = '#0f1114';
export interface CoverSvg {
svg: string;
source: 'pcb' | 'schematic';
viewBox: [number, number, number, number];
}
type Bounds = { minX: number; minY: number; maxX: number; maxY: number };
/** Ten percent breathing room on each side; expand the shorter axis, never crop. */
function frame(svg: string, bounds: Bounds, source: CoverSvg['source'], images = ''): CoverSvg {
if (!Object.values(bounds).every(Number.isFinite)) throw new Error('Invalid cover bounds');
let width = Math.max(0.5, bounds.maxX - bounds.minX) * 1.2;
let height = Math.max(0.5, bounds.maxY - bounds.minY) * 1.2;
width = Math.max(width, (height * COVER_WIDTH) / COVER_HEIGHT);
height = Math.max(height, (width * COVER_HEIGHT) / COVER_WIDTH);
const x = (bounds.minX + bounds.maxX - width) / 2;
const y = (bounds.minY + bounds.maxY - height) / 2;
const viewBox: CoverSvg['viewBox'] = [x, y, width, height];
const body = svg.slice(svg.indexOf('>', svg.indexOf('<svg')) + 1, svg.lastIndexOf('</svg>'));
const result = `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${COVER_WIDTH}" height="${COVER_HEIGHT}" viewBox="${viewBox.join(' ')}"><rect x="${x}" y="${y}" width="${width}" height="${height}" fill="${COVER_BACKGROUND}"/>${images}${body}</svg>`;
if (result.length > 16 * 1024 * 1024) throw new Error('Cover geometry is too large');
return { svg: result, source, viewBox };
}
/** Native plotters deliberately omit reference bitmaps; include safe raster payloads. */
async function bitmap(
data: string,
at: { x: number; y: number },
scale: number,
units: number,
): Promise<{ svg: string; bounds: Bounds }> {
const { imageMimeType } = await import('@ziroeda/eeschema/import_gfx/image_format.js');
const { imagePixelSize, imagePPI } = await import('@ziroeda/eeschema/tools/image_size.js');
const clean = data.replace(/\s/g, '');
const mime = imageMimeType(clean);
if (
!/^[A-Za-z0-9+/]*={0,2}$/.test(clean) ||
!['image/png', 'image/jpeg', 'image/gif', 'image/bmp'].includes(mime)
)
throw new Error('Unsupported cover bitmap');
let size = imagePixelSize(clean);
if (!size) {
const bytes = Uint8Array.from(atob(clean), (char) => char.charCodeAt(0));
const image = await createImageBitmap(new Blob([bytes], { type: mime }));
size = { w: image.width, h: image.height };
image.close();
}
if (size.w * size.h > 32 * 1024 * 1024) throw new Error('Cover bitmap is too large');
const factor = (25.4 / imagePPI(clean)) * scale;
const width = size.w * factor,
height = size.h * factor;
const x = at.x / units - width / 2,
y = at.y / units - height / 2;
return {
svg: `<image x="${x}" y="${y}" width="${width}" height="${height}" xlink:href="data:${mime};base64,${clean}"/>`,
bounds: { minX: x, minY: y, maxX: x + width, maxY: y + height },
};
}
function merge(a: Bounds, b: Bounds): void {
a.minX = Math.min(a.minX, b.minX);
a.minY = Math.min(a.minY, b.minY);
a.maxX = Math.max(a.maxX, b.maxX);
a.maxY = Math.max(a.maxY, b.maxY);
}
/** Only called in the cover worker: no live documents, selections or settings. */
export async function projectCoverSvg(project: NativeProject): Promise<CoverSvg | null> {
const text = (path: string | null): string | null => {
const file = project.files.find((item) => item.name === path);
return file ? new TextDecoder().decode(file.bytes) : null;
};
const boardText = text(project.roots.board);
if (boardText) {
const { ParseBoard } = await import('@ziroeda/pcbnew/pcb_io/kicad_sexpr/pcb_io_kicad_sexpr.js');
const board = ParseBoard(boardText);
if (
board.Footprints().length ||
board.Tracks().length ||
board.Zones().length ||
board.Drawings().length
) {
const [
{ PCB_LAYER_ID },
{ LSET },
{ COLOR_SETTINGS },
{ PCB_RENDER_SETTINGS },
{ SVG_PLOTTER },
{ PLOT_FORMAT, plotterPageInfo },
{ PCB_PLOT_PARAMS, DRILL_MARKS },
{ PlotBoardLayers },
{ pcbIUScale },
] = await Promise.all([
import('@ziroeda/common/layer_id.js'),
import('@ziroeda/common/lset.js'),
import('@ziroeda/common/settings/color_settings.js'),
import('@ziroeda/pcbnew/pcb_painter.js'),
import('@ziroeda/common/plotters/SVG_plotter.js'),
import('@ziroeda/common/plotters/plotter.js'),
import('@ziroeda/pcbnew/pcb_plot_params.js'),
import('@ziroeda/pcbnew/plot_board_layers.js'),
import('@ziroeda/common/eda_units.js'),
]);
// Fixed top view: copper, fabrication, silkscreen, outline and user graphics.
// Mask/paste/courtyard layers obscure the design at thumbnail scale.
const excluded = new Set([
PCB_LAYER_ID.F_Mask,
PCB_LAYER_ID.B_Mask,
PCB_LAYER_ID.F_Paste,
PCB_LAYER_ID.B_Paste,
PCB_LAYER_ID.F_CrtYd,
PCB_LAYER_ID.B_CrtYd,
PCB_LAYER_ID.F_Adhes,
PCB_LAYER_ID.B_Adhes,
]);
const enabled = board
.GetEnabledLayers()
.Seq()
.filter((layer) => !excluded.has(layer));
const layers = new LSET(enabled);
board.SetVisibleLayers(layers);
// Include off-board / unplaced footprints, not just the Edge.Cuts rectangle.
const box = board.ComputeBoundingBox();
const units = pcbIUScale.IU_PER_MM;
const bounds: Bounds = {
minX: box.GetLeft() / units,
minY: box.GetTop() / units,
maxX: box.GetRight() / units,
maxY: box.GetBottom() / units,
};
const colors = new COLOR_SETTINGS();
colors.SetColor(PCB_LAYER_ID.B_Cu, { r: 0.28, g: 0.48, b: 0.85, a: 1 });
colors.SetColor(PCB_LAYER_ID.F_Cu, { r: 0.94, g: 0.31, b: 0.29, a: 1 });
colors.SetColor(PCB_LAYER_ID.Edge_Cuts, { r: 0.78, g: 1, b: 0.24, a: 1 });
colors.SetColor(PCB_LAYER_ID.F_SilkS, { r: 0.87, g: 0.94, b: 0.91, a: 1 });
colors.SetColor(PCB_LAYER_ID.B_SilkS, { r: 0.55, g: 0.65, b: 0.76, a: 1 });
colors.SetColor(PCB_LAYER_ID.F_Fab, { r: 0.43, g: 0.55, b: 0.64, a: 1 });
colors.SetColor(PCB_LAYER_ID.B_Fab, { r: 0.35, g: 0.44, b: 0.56, a: 1 });
const render = new PCB_RENDER_SETTINGS();
render.LoadColors(colors);
render.SetDefaultPenWidth(units * 0.1);
const opts = new PCB_PLOT_PARAMS();
opts.SetFormat(PLOT_FORMAT.SVG);
opts.SetColorSettings(colors);
opts.SetBlackAndWhite(false);
opts.SetPlotFrameRef(false);
opts.SetPlotReference(true);
opts.SetPlotValue(false);
opts.SetPlotFPText(true);
opts.SetDrillMarksType(DRILL_MARKS.SMALL_DRILL_SHAPE);
const plotter = new SVG_PLOTTER(render);
plotter.SetPageSettings(plotterPageInfo({ sizeMils: { x: 12000, y: 9000 } }));
plotter.SetColorMode(true);
plotter.SetViewport({ x: 0, y: 0 }, pcbIUScale.IU_PER_MILS / 10, 1, false);
plotter.SetCreator('VibeMake PCB cover');
plotter.OpenFile('cover.svg');
plotter.StartPlot('1', new Date(0));
const order = layers.SeqStackupForPlotting();
// The front fabrication belongs behind copper and silk in this top view.
const frontFab = order.indexOf(PCB_LAYER_ID.F_Fab);
if (frontFab >= 0) {
order.splice(frontFab, 1);
order.unshift(PCB_LAYER_ID.F_Fab);
}
PlotBoardLayers(board, plotter, order, opts);
plotter.EndPlot();
let images = '';
const { PCB_REFERENCE_IMAGE } = await import('@ziroeda/pcbnew/pcb_reference_image.js');
for (const item of board.Drawings()) {
if (!(item instanceof PCB_REFERENCE_IMAGE)) continue;
const image = item.GetReferenceImage();
const bytes = image.GetImage().SaveImageData();
if (!bytes) throw new Error('Could not read board bitmap');
let data = '';
for (const value of bytes) data += String.fromCharCode(value);
const embedded = await bitmap(btoa(data), item.GetPosition(), image.GetImageScale(), units);
images += embedded.svg;
merge(bounds, embedded.bounds);
}
return frame(plotter.text(), bounds, 'pcb', images);
}
}
const schText = text(project.roots.schematic);
if (!schText) return null;
const [
{ parse },
{ readSchematic },
{ contentBBox },
{ isEmpty },
{ sheetToSvg },
{ KICAD_CLASSIC },
{ schIUScale },
] = await Promise.all([
import('@ziroeda/sexpr'),
import('@ziroeda/eeschema/sch_io/sexpr/read-schematic.js'),
import('@ziroeda/eeschema/tools/scene_bbox.js'),
import('@ziroeda/eeschema/tools/bbox.js'),
import('@ziroeda/eeschema/sch_plotter.js'),
import('@ziroeda/eeschema/sch_render_settings.js'),
import('@ziroeda/common/eda_units.js'),
]);
const sch = readSchematic(parse(schText));
const box = contentBBox(sch, new Map(sch.libSymbols.map((lib) => [lib.libId, lib])));
if (isEmpty(box)) return null;
const units = schIUScale.IU_PER_MM;
const bounds: Bounds = {
minX: box.minX / units,
minY: box.minY / units,
maxX: box.maxX / units,
maxY: box.maxY / units,
};
let images = '';
for (const image of sch.images) {
const embedded = await bitmap(image.data, image.at, image.scale, units);
images += embedded.svg;
merge(bounds, embedded.bounds);
}
const svg = sheetToSvg(
{ ...sch, images: [] },
{
...KICAD_CLASSIC,
// The built-in schematic themes target light paper. Use a fixed,
// readable dark preview palette without changing the editor's theme.
background: COVER_BACKGROUND,
wire: '#70dea6',
junction: '#70dea6',
bus: '#83adff',
busJunction: '#83adff',
symbolOutline: '#f5b778',
symbolFill: '#1c2632',
pin: '#efa39a',
pinName: '#a9d5ed',
pinNumber: '#b9c9dd',
reference: '#f3dc9c',
value: '#d9e4ed',
fields: '#b9c9dd',
label: '#c8ff75',
globalLabel: '#c8ff75',
hierLabel: '#9bc7ee',
noteLine: '#a1b6d1',
noText: '#a1b6d1',
noConnect: '#a1b6d1',
privateNote: '#c9aecf',
netclassFlag: '#c8ff75',
sheetBorder: '#8ba7c6',
sheetBackground: '#17212b',
sheetName: '#e1ebf2',
sheetFile: '#9bb0c7',
sheetLabel: '#c3d3e1',
sheetFields: '#c3d3e1',
},
{ color: true, drawingSheet: false, background: false },
{ now: new Date(0) },
);
return frame(svg, bounds, 'schematic', images);
}
+25
View File
@@ -0,0 +1,25 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import { openArchive } from './archive.js';
import { projectCoverSvg } from './cover-renderer.js';
import type { Capabilities } from './types.js';
// Vite instruments transitive wx JSX helpers even though this worker only
// uses native plotting. Workers have no React tree or refresh registration.
if (import.meta.env.DEV)
Object.assign(self, {
$RefreshReg$: () => {},
$RefreshSig$:
() =>
<T>(type: T): T =>
type,
});
self.onmessage = async ({ data }: MessageEvent<{ bytes: Uint8Array; limits: Capabilities }>) => {
try {
// ZIP and cover always describe exactly the same immutable saved snapshot.
const project = await openArchive(data.bytes, data.limits, true);
self.postMessage({ value: await projectCoverSvg(project) });
} catch (error) {
self.postMessage({
error: error instanceof Error ? (error.stack ?? error.message) : String(error),
});
}
};
+43
View File
@@ -4,6 +4,7 @@ import { openArchive } from './archive.js';
import { atomic, listValues, readValue, storageKey } from './storage.js';
import {
DEFAULT_LIMITS,
MAX_COVER_BYTES,
WorkspaceError,
copyBytes,
sha256,
@@ -12,6 +13,7 @@ import {
type PcbProject,
type PcbProjectApi,
type ProjectDocument,
type ProjectCover,
type SaveReceipt,
type UploadRequest,
type UploadSignature,
@@ -36,6 +38,7 @@ export type MockFault =
| 'confirmation-lost'
| 'expired'
| 'conflict'
| 'cover-failed'
| 'too-large';
export const mockFaults: { current: MockFault } = { current: 'none' };
const fail = (code: string): WorkspaceError =>
@@ -139,6 +142,46 @@ export class MockPcbProjectApi implements PcbProjectApi {
};
});
}
async uploadCover(cover: ProjectCover, signal?: AbortSignal): Promise<string> {
this.check();
signal?.throwIfAborted();
if (mockFaults.current === 'cover-failed') throw fail('PCB_OSS_ERROR');
if (!['image/webp', 'image/png'].includes(cover.contentType) || !cover.bytes.length)
throw fail('PCB_INVALID_COVER');
if (cover.bytes.length > MAX_COVER_BYTES) throw fail('PCB_COVER_TOO_LARGE');
// Persist the data URL with the project, never a blob URL tied to this page.
let binary = '';
for (const value of cover.bytes) binary += String.fromCharCode(value);
return `data:${cover.contentType};base64,${btoa(binary)}`;
}
async setCover(code: string, coverUrl: string, signal?: AbortSignal): Promise<PcbProject> {
this.check();
signal?.throwIfAborted();
if (mockFaults.current === 'cover-failed') throw fail('PCB_OSS_ERROR');
return atomic(['mockProjects'], (tx, done, reject) => {
const key = storageKey(this.owner, code);
const request = tx.objectStore('mockProjects').get(key);
request.onsuccess = () => {
if (signal?.aborted) {
reject(signal.reason);
return;
}
const current = request.result as MockProject | undefined;
if (!current || current.deleted || current.owner !== this.owner) {
reject(fail('NOT_FOUND'));
return;
}
const next = {
...current,
coverUrl: coverUrl || null,
updatedAt: new Date().toISOString(),
};
tx.objectStore('mockProjects').put(next, key);
const { owner: _owner, bytes: _bytes, ...metadata } = next;
done(metadata);
};
});
}
async remove(code: string): Promise<void> {
this.check();
return atomic(['mockProjects'], (tx, done, reject) => {
+9
View File
@@ -716,3 +716,12 @@
transition: none;
}
}
.vm-platform .cad-card-art {
overflow: hidden;
}
.vm-project-cover {
display: block;
width: 100%;
height: 100%;
object-fit: contain;
}
+75
View File
@@ -5,6 +5,7 @@ import type {
} from '@ziroeda/common/project_snapshot.js';
import { safePath, validateFiles } from './archive.js';
import { packProject } from './archive-client.js';
import { generateProjectCover } from './cover-client.js';
import { missingModels, rewriteReferences } from './resources.js';
import { atom, head, isList, list, parse, serialize, str } from '@ziroeda/sexpr/index.js';
import { childNamed } from '@ziroeda/sexpr/query.js';
@@ -45,6 +46,8 @@ export interface RuntimeState {
inputLocked: boolean;
error: unknown;
storageWarning: boolean;
coverUpdating: boolean;
coverWarning: boolean;
}
export interface CapturedProject {
project: NativeProject;
@@ -67,6 +70,8 @@ export class WorkspaceRuntime implements ProjectSnapshotHost {
private writeTail: Promise<unknown> = Promise.resolve();
private writes = new Map<string, Promise<void>>();
private pending: PendingSave | null = null;
private lastCover?: { pending: PendingSave; receipt: SaveReceipt };
private coverTask: Promise<void> | null = null;
private externalLock = false;
private currentState: RuntimeState;
private projectData: Omit<NativeProject, 'files'>;
@@ -101,6 +106,8 @@ export class WorkspaceRuntime implements ProjectSnapshotHost {
inputLocked: false,
error: null,
storageWarning: false,
coverUpdating: false,
coverWarning: false,
};
}
get code(): string {
@@ -489,9 +496,77 @@ export class WorkspaceRuntime implements ProjectSnapshotHost {
}
}
if (sameSession || this.currentState.revision > 0) await this.persistDraft();
// Cover errors must never turn an acknowledged native save into a failure.
// Keeping the original ZIP also makes retries / recovered confirmations exact.
if (this.coverTask) await this.coverTask;
this.lastCover = { pending, receipt };
await this.retryCover();
}
retryCover = (): Promise<void> => {
if (this.coverTask) return this.coverTask;
if (!this.lastCover || this.abort.signal.aborted || this.externalLock) return Promise.resolve();
const source = this.lastCover;
this.coverTask = this.updateCover(source.pending, source.receipt).finally(() => {
this.coverTask = null;
});
return this.coverTask;
};
private async updateCover(pending: PendingSave, receipt: SaveReceipt): Promise<void> {
const signal = AbortSignal.any([this.abort.signal, AbortSignal.timeout(30000)]);
// Race even adapters which fail to observe cancellation. Late responses may
// not update this session after the deadline, a switch or logout.
const bounded = <T>(operation: Promise<T>): Promise<T> =>
new Promise((resolve, reject) => {
const abort = (): void => reject(signal.reason);
if (signal.aborted) {
reject(signal.reason);
return;
}
signal.addEventListener('abort', abort, { once: true });
operation.then(resolve, reject).finally(() => signal.removeEventListener('abort', abort));
});
this.emit({ coverUpdating: true, coverWarning: false });
try {
const latest = await bounded(this.api.get(this.code, signal));
this.assertActive();
signal.throwIfAborted();
// An idempotent confirmation may describe an older version saved by this
// tab. Never knowingly attach its image to a newer cloud document.
if (latest.version !== receipt.version) {
this.lastCover = undefined;
return;
}
const cover = await bounded(generateProjectCover(pending.bytes, this.limits, signal));
this.assertActive();
signal.throwIfAborted();
const coverUrl = cover ? await bounded(this.api.uploadCover(cover, signal)) : '';
this.assertActive();
signal.throwIfAborted();
const current = await bounded(this.api.get(this.code, signal));
this.assertActive();
signal.throwIfAborted();
if (current.version !== receipt.version || (current.coverUrl ?? '') === coverUrl) {
this.lastCover = undefined;
return;
}
const updated = await bounded(this.api.setCover(this.code, coverUrl, signal));
this.assertActive();
signal.throwIfAborted();
if (updated.pcbProjectCode !== this.code) throw new WorkspaceError('BAD_RESPONSE');
// A metadata PATCH must not overwrite the runtime's version/name with a
// response racing another editor or a rename. Only merge the cover.
if (updated.version === receipt.version && this.metadata.version === receipt.version)
this.metadata = { ...this.metadata, coverUrl: updated.coverUrl };
this.lastCover = undefined;
} catch {
if (!this.abort.signal.aborted) this.emit({ coverWarning: true });
} finally {
if (!this.abort.signal.aborted) this.emit({ coverUpdating: false });
}
}
save = (): Promise<void> => {
if (this.saveTask) return this.saveTask;
if (!this.pending && !this.dirty && this.currentState.coverWarning) return this.retryCover();
this.saveTask = this.performSave().finally(() => {
this.saveTask = null;
});
+8 -1
View File
@@ -107,6 +107,11 @@ export interface ProjectDocument {
downloadUrl: string;
expiresAt: null;
}
export interface ProjectCover {
bytes: Uint8Array;
contentType: 'image/webp' | 'image/png';
}
export const MAX_COVER_BYTES = 5 * 1024 * 1024;
export interface PcbProjectApi {
capabilities(): Promise<Capabilities>;
list(
@@ -114,8 +119,10 @@ export interface PcbProjectApi {
keyword: string,
): Promise<{ items: PcbProject[]; page: number; size: number; total: number }>;
create(name: string, clientRequestId: string): Promise<PcbProject>;
get(code: string): Promise<PcbProject>;
get(code: string, signal?: AbortSignal): Promise<PcbProject>;
rename(code: string, name: string): Promise<PcbProject>;
uploadCover(cover: ProjectCover, signal?: AbortSignal): Promise<string>;
setCover(code: string, coverUrl: string, signal?: AbortSignal): Promise<PcbProject>;
remove(code: string): Promise<void>;
document(code: string): Promise<ProjectDocument>;
sign(code: string, request: UploadRequest): Promise<UploadSignature>;
+2
View File
@@ -5,6 +5,8 @@ interface ImportMetaEnv {
readonly VITE_SUPABASE_ANON_KEY?: string;
readonly VITE_ENABLE_CLOUD?: string;
readonly VITE_ENABLE_TELEMETRY?: string;
/** Set false to disable PCB AI connections, task polling and queued commands. */
readonly VITE_ENABLE_PCB_AI?: string;
/** Base URL of the hosted 3D-model library (R2); falls back to /models3d. */
readonly VITE_MODELS3D_URL?: string;
/** Hosted demo-corpus base URL (R2); falls back to the bundled /demos. */
+39 -10
View File
@@ -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://39.105.93.138:8003',
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,
@@ -105,9 +117,21 @@ 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 }) });
} },
{
name: 'pcb-worker-safe-react-refresh',
apply: 'serve',
enforce: 'post',
transform(code, id) {
if (id !== '/@react-refresh') return;
// Native plotters reach shared JSX helpers. The refresh wrapper already
// skips workers, but its runtime registers this hook unconditionally.
// globalThis is window on the page and self inside the cover worker.
return code.replace(
'window.__registerBeforePerformReactRefresh',
'globalThis.__registerBeforePerformReactRefresh',
);
},
},
{
name: 'pcb-production-mode',
configResolved(config) {
@@ -120,6 +144,16 @@ export default defineConfig({
throw new Error('PCB mock mode is development-only. Build with real API mode.');
},
},
{
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.
@@ -190,7 +224,7 @@ export default defineConfig({
maximumFileSizeToCacheInBytes: 4 * 1024 * 1024,
// Only the /pcb/ application scope uses this navigation fallback.
navigateFallback: 'index.html',
navigateFallbackDenylist: [/\/pcb-api\//, /\/api\//, /\.zip(?:\?|$)/],
navigateFallbackDenylist: [/\/api\//, /\/pcb-api\//, /\.zip(?:\?|$)/],
runtimeCaching: [
{
// WASM kernels are hashed like every other asset, so cache-first is
@@ -235,12 +269,7 @@ export default defineConfig({
server: {
port: 5173,
proxy: {
[`${APP_BASE}pcb-api`]: {
target: process.env.PCB_API_TARGET || 'http://127.0.0.1:8003',
changeOrigin: true,
rewrite: (path: string) => '/api' + path.slice(`${APP_BASE}pcb-api`.length),
configure: (proxy) => { proxy.on('proxyReq', request => request.setHeader('Origin', 'http://127.0.0.1:5173')); },
},
[`${APP_BASE}pcb-api`]: pcbProxy(),
'/api': {
target: process.env.API_TARGET || 'https://dev-vibemake-api.robotquan.com',
changeOrigin: true,
+13
View File
@@ -0,0 +1,13 @@
# 2026-11-16 main 合并记录
远程来源:origin/main 7ddc3c2。合并前本地快照:6051e2f,备份分支 backup/local-before-main-20261116。
冲突优先级:PCB 设计、检查、导出和交付以本地已验证实现为主;前端页面和网站代理以远程 main 为主。CodexPcbDock.tsx、codex-pcb.css、scripts/serve.mjs 的冲突采用远程文件。保留未冲突的本地改动。
app.py 同时承担设计工具和网站 API,逐段合并:保留原生设计约束、公共交付工具和警告分类;接入远程模型配置、readiness API、连接错误和空闲检测。EDA 底层 CLI 使用远程的可配置路径与子进程输出修复,原生对象操作、分块传输、检查保持本地行为。Freerouting 仍禁止,预检不再要求其 JAR。
将公共交付依赖加入 requirements、Docker COPY 和后端打包清单,防止仅本机能运行、部署包缺依赖。系统服务使用显式 PCB_CODEX_BIN、PCB_EDA_BIN、PCB_BLENDER_BIN 保留当前已验证可执行文件,继续使用现有 ChatGPT 登录和 gpt-6.1-sol,不迁移凭据或切换供应商。
验证:82 项后端测试通过;真实 Codex 沙箱及嘉立创 4.1.78 独立只读桥接通过;前端类型检查/生产构建和相关测试见 persistent-development/merge-main-20261116 日志。封面渲染初次并行运行出现 5 秒超时,独立延长测试时限后 5 项均通过,未修改远程封面代码。
发布时备份原静态产物及非完成任务状态,更新源码/运行配置指纹并记录迁移,保留已取消任务状态。所有 Git 提交仅在服务器本地,没有推送到远程。
+11 -1
View File
@@ -33,7 +33,17 @@
不请求 `/pcb/workspace/capabilities`,因为后端契约没有该接口。不向服务器发送 clientRequestId、clientOperationId、sha256、archiveFormat 或 manifestVersion,也不要求这些字段出现在签名、回执或 document 中。本地事务仍保留操作标识和 ZIP hash,用于草稿、缓存和恢复,与后端字段分开。
现有页面保留新建、导入、搜索、重命名、删除;本轮没有增加封面编辑器。coverUrl 随项目元数据保留,工程保存和重命名不清空封面。将来新增封面 UI 时使用文档中的公共封面上传流程,不混用 PCB ZIP 签名接口。
现有页面保留新建、导入、搜索、重命名、删除。封面在工程保存确认后自动生成,不增加手工封面编辑器。重命名不改变封面。
## 自动项目封面
- 从本次确认的原生 ZIP 重新解析并导出,不截取当前屏幕。PCB 有内容时使用完整二维顶视图;空板回退根原理图;两者都为空则恢复默认占位图。板外元件计入边界,默认不使用三维视角。
- 在独立 worker 使用原生绘图导出,固定图层、配色、完整内容边界和约 10% 留白;排除界面、网格、选中态、临时工具和图框。输出 800×450 WebP(浏览器不支持 WebP 编码时允许 PNG),保留嵌入位图,列表等比完整展示并延迟加载。编辑器缩放与用户设置不变。
- 使用 `POST /api/uploads/project-covers/signature`,仅发送 `{contentType,fileSize}`;最大 5 MiB。OSS 表单原样加入签名字段,图片文件最后追加,不携带平台 token、cookie 或手动 multipart Content-Type,HTTP 200 即成功。将返回的完整 `coverUrl` 用 `PATCH /api/pcb/workspace/projects/{code}` 绑定;空工程使用 `coverUrl: ""` 清除旧图。
- 工程确认成功后立即记为已保存,再显示“正在更新封面”。生成最长 12 秒,整个封面步骤最长 30 秒。封面失败不改变工程版本或保存结果,保留原图并显示可重试提示。重试使用同一 ZIP,不重新增加设计版本;未知确认恢复后也使用原批次 ZIP。保存期间的新修改继续保持未保存状态。
- 写入前核对云版本,账号/会话切换中止任务,已知过期版本不更新封面。现有 PATCH 没有版本条件,因此“检查后、PATCH 前”仍存在跨标签页竞态;严格保证封面与工程版本原子对应需要后端提供带版本条件的绑定。前端没有发送未文档化字段,也没有修改后端。
开发模拟模式把图片 data URL 保存在本机数据库,刷新仍可显示;不会创建真实 OSS 对象。真实封面签名、OSS CORS 和跨设备显示需后端联调。
## 保存、失败和重开
+5 -4
View File
@@ -3,11 +3,12 @@ Description=VibeMake PCB2 persistent Codex sessions
StartLimitIntervalSec=300
StartLimitBurst=5
[Service]
WorkingDirectory=/home/wpz/auto_pcb_2/vibemake-pcb-studio
Environment=PATH=/home/wpz/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/bin:/home/wpz/.local/bin:/usr/local/bin:/usr/bin:/bin:/snap/bin
Environment=PCB_SESSION_ROOT=/home/wpz/auto_pcb_2/persistent-runtime
WorkingDirectory=/opt/vibemake-pcb-studio
Environment=PATH=/usr/local/bin:/usr/bin:/bin:/snap/bin
Environment=DISPLAY=:0
ExecStart=/home/wpz/auto_pcb_2/vibemake-pcb-studio/backend/.venv/bin/python -m uvicorn codex_pcb.app:app --host 127.0.0.1 --port 8003
# Copy codex_pcb/.env.example here and adapt paths/display to this host.
EnvironmentFile=-%h/.config/vibemake-pcb/backend.env
ExecStart=/opt/vibemake-pcb-studio/.venv/bin/python -m uvicorn codex_pcb.app:app --host 127.0.0.1 --port 8003 --workers 1
Restart=on-failure
RestartSec=5
TimeoutStopSec=25
+2 -1
View File
@@ -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,27 @@
import { describe, expect, it } from 'vitest';
import { parseApiResponse } from '@ziroeda/designer/src/codex-pcb/api-response.js';
const path = '/pcb/pcb-api/providers';
describe('PCB API response diagnostics', () => {
it('returns backend JSON unchanged', async () => {
const value = { default_provider: 'openai', providers: [] };
await expect(parseApiResponse(Response.json(value), path)).resolves.toEqual(value);
});
it.each([502, 503, 504])('explains an HTML gateway error (%s)', async status => {
const response = new Response('<html><h1>Bad Gateway</h1></html>', { status, headers: { 'Content-Type': 'text/html' } });
await expect(parseApiResponse(response, path)).rejects.toThrow(`${path}(HTTP ${status}):返回了 HTML 错误页。网关`);
});
it('identifies a successful SPA fallback without displaying HTML', async () => {
await expect(parseApiResponse(new Response('<!doctype html><script>app()</script>'), path))
.rejects.toThrow('返回了网页,请检查 /pcb/pcb-api/');
});
it('retains backend errors including missing credentials and runtime blockers', async () => {
await expect(parseApiResponse(Response.json({ detail: '生产环境预检未通过:EDA 无执行权限' }, { status: 503 }), path))
.rejects.toThrow('HTTP 503):生产环境预检未通过:EDA 无执行权限');
});
it('handles null errors, validation errors and malformed JSON', async () => {
await expect(parseApiResponse(Response.json(null, { status: 500 }), path)).rejects.toThrow('HTTP 500):请求失败');
await expect(parseApiResponse(Response.json({ detail: [{ msg: 'Invalid input' }] }, { status: 422 }), path)).rejects.toThrow('Invalid input');
await expect(parseApiResponse(new Response('{broken'), path)).rejects.toThrow('返回内容不是有效 JSON');
});
});
@@ -0,0 +1,161 @@
// @vitest-environment happy-dom
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { afterEach, expect, it, vi } from 'vitest';
import { CodexPcbDock } from '@ziroeda/designer/src/codex-pcb/CodexPcbDock.js';
vi.mock('@ziroeda/designer/src/codex-pcb/DeliveryModel3D.js', () => ({
DeliveryModel3D: () => null,
}));
const healthy = { ok: true, status: 'ready', checked_at: 100, checks: [] };
const unavailable = { ok: false, status: 'unavailable', checked_at: 100,
checks: [{ name: 'eda_bridge', ok: false, message: 'BRIDGE_NOT_READY: command-space-missing' }] };
const providers = { default_provider: 'openai', providers: [
{ id: 'openai', label: 'OpenAI', model: 'test-model', effort: 'high', configured: true },
] };
function response(url: string, fallback: unknown): Response {
return Response.json(url.includes('/readiness') ? healthy : url.endsWith('/providers') ? providers : fallback);
}
afterEach(() => {
cleanup();
localStorage.clear();
window.history.replaceState(null, '', '/');
vi.unstubAllEnvs();
vi.unstubAllGlobals();
});
it('checks environment on project entry while keeping task history lazy until opened', async () => {
const fetch = vi.fn(async (url: string) => response(url, []));
vi.stubGlobal('fetch', fetch);
render(<CodexPcbDock />);
expect(screen.queryByLabelText('Codex PCB 工作台')).toBeNull();
expect(fetch.mock.calls.map(([url]) => url)).toEqual(['/pcb-api/readiness']);
fireEvent.click(screen.getByRole('button', { name: /Codex AI 自动绘板/ }));
expect(screen.getByLabelText('Codex PCB 工作台')).toBeTruthy();
await waitFor(() => expect(fetch.mock.calls.some(([url]) => url === '/pcb-api/sessions')).toBe(true));
fireEvent.click(screen.getByRole('button', { name: '关闭工作台' }));
expect(screen.queryByLabelText('Codex PCB 工作台')).toBeNull();
});
it('preserves the local disable switch even with an explicit AI URL and saved session', () => {
vi.stubEnv('VITE_ENABLE_PCB_AI', 'false');
window.history.replaceState(null, '', '/?ai=1');
localStorage.setItem('vibemake.pcb2.persistent-session', 'pcb-saved');
const fetch = vi.fn();
vi.stubGlobal('fetch', fetch);
render(<CodexPcbDock />);
expect(screen.queryByLabelText('Codex PCB 工作台')).toBeNull();
expect(screen.queryByRole('button', { name: /Codex AI 自动绘板/ })).toBeNull();
expect(fetch).not.toHaveBeenCalled();
expect(localStorage.getItem('vibemake.pcb2.persistent-session')).toBe('pcb-saved');
});
it('uses the new session protocol without replaying the legacy task outbox', async () => {
window.history.replaceState(null, '', '/?ai=1');
const queued = JSON.stringify({ action: 'create', request_id: 'old-request', payload: {} });
localStorage.setItem('vibemake.pcb-service.outbox', queued);
const task = {
id: 'pcb-new',
request: '测试电源板',
state: 'planning',
busy: true,
cursor: 0,
created_at: 0,
};
const fetch = vi.fn(
async (url: string, init?: RequestInit) =>
response(url, init?.method === 'POST' || url.endsWith('/sessions/pcb-new') ? task : []),
);
vi.stubGlobal('fetch', fetch);
render(<CodexPcbDock />);
fireEvent.change(screen.getByLabelText('设计需求'), { target: { value: '测试电源板设计' } });
await waitFor(() => expect((screen.getByRole('button', { name: '生成设计方案 →' }) as HTMLButtonElement).disabled).toBe(false));
fireEvent.click(screen.getByRole('button', { name: '生成设计方案 →' }));
await waitFor(() =>
expect(fetch.mock.calls.some(([, init]) => init?.method === 'POST')).toBe(true),
);
const [url, init] = fetch.mock.calls.find(([, init]) => init?.method === 'POST')!;
expect(url).toBe('/pcb-api/sessions');
expect(JSON.parse(String(init?.body))).toEqual({ text: '测试电源板设计', provider: 'openai' });
expect(
fetch.mock.calls.every(([url]) => !url.includes('/v1/') && !url.includes('/commands')),
).toBe(true);
expect(localStorage.getItem('vibemake.pcb-service.outbox')).toBe(queued);
});
it('keeps approval disabled while an unsubmitted proposal comment exists', async () => {
window.history.replaceState(null, '', '/?ai=1');
localStorage.setItem('vibemake.pcb2.persistent-session', 'pcb-review');
const task = {
id: 'pcb-review',
request: '测试电源板设计',
state: 'review',
busy: false,
cursor: 0,
created_at: 0,
proposal: {
title: '电源板方案',
markdown: '已完成待审核的方案。',
revision: 2,
hash: 'current-hash',
},
};
const fetch = vi.fn(
async (url: string) =>
response(url, url.endsWith('/sessions') ? [task] : url.includes('/events?') ? [] : task),
);
vi.stubGlobal('fetch', fetch);
render(<CodexPcbDock />);
const approve = await screen.findByRole('button', { name: '同意此方案,开始运行' });
await waitFor(() => expect((approve as HTMLButtonElement).disabled).toBe(false));
fireEvent.change(screen.getByLabelText('对方案有修改意见?'), {
target: { value: '请增加一个状态灯' },
});
expect((approve as HTMLButtonElement).disabled).toBe(true);
fireEvent.click(approve);
expect(fetch.mock.calls.every(([url]) => !url.endsWith('/approve'))).toBe(true);
});
it('warns immediately on project entry even before opening the AI panel', async () => {
const fetch = vi.fn(async () => Response.json(unavailable));
vi.stubGlobal('fetch', fetch);
render(<CodexPcbDock/>);
await screen.findByText('绘板环境未就绪,暂不能生成');
expect(screen.queryByLabelText('Codex PCB 工作台')).toBeNull();
expect(fetch.mock.calls.length).toBe(1);
fireEvent.click(screen.getByRole('button', { name: '查看检查结果' }));
expect(await screen.findByText('BRIDGE_NOT_READY: command-space-missing')).toBeTruthy();
});
it.each(['checking', 'unavailable'])('prevents generation while runtime is %s', async status => {
window.history.replaceState(null, '', '/?ai=1');
const fetch = vi.fn(async (url: string) => url.includes('/readiness')
? Response.json({ ...unavailable, status }) : response(url, []));
vi.stubGlobal('fetch', fetch);
render(<CodexPcbDock/>);
fireEvent.change(screen.getByLabelText('设计需求'), { target: { value: '测试电源板设计' } });
await screen.findByRole('option', { name: /OpenAI · test-model/ });
const create = screen.getByRole('button', { name: '生成设计方案 →' }) as HTMLButtonElement;
expect(create.disabled).toBe(true);
fireEvent.click(create);
expect(fetch.mock.calls.filter(([url]) => url.endsWith('/sessions')).length).toBe(1); // GET only
});
it('enables generation only after a successful manual recheck', async () => {
window.history.replaceState(null, '', '/?ai=1');
const fetch = vi.fn(async (url: string, _init?: RequestInit) => {
if (url.endsWith('/readiness')) return Response.json(unavailable);
if (url.endsWith('/readiness/check')) return Response.json(healthy);
return response(url, []);
});
vi.stubGlobal('fetch', fetch);
render(<CodexPcbDock/>);
fireEvent.change(screen.getByLabelText('设计需求'), { target: { value: '测试电源板设计' } });
const retry = await screen.findByRole('button', { name: '重新检查环境' });
expect((screen.getByRole('button', { name: '生成设计方案 →' }) as HTMLButtonElement).disabled).toBe(true);
fireEvent.click(retry);
await waitFor(() => expect((screen.getByRole('button', { name: '生成设计方案 →' }) as HTMLButtonElement).disabled).toBe(false));
expect(fetch.mock.calls.some(([url, init]) => url.endsWith('/readiness/check') && init?.method === 'POST')).toBe(true);
expect(fetch.mock.calls.some(([url, init]) => url.endsWith('/sessions') && init?.method === 'POST')).toBe(false);
});
@@ -0,0 +1,87 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import { readFileSync } from 'node:fs';
import { describe, expect, it } from 'vitest';
import { importFiles } from '@ziroeda/designer/src/platform/archive.js';
import { projectCoverSvg } from '@ziroeda/designer/src/platform/cover-renderer.js';
const file = (name: string, text: string) => ({ name, bytes: new TextEncoder().encode(text) });
const board = (content = '') => `(kicad_pcb (version 20241229) (generator test)
(layers (0 "F.Cu" signal) (2 "B.Cu" signal) (25 "Edge.Cuts" user))
(net 0 "") ${content})`;
const schematic = (content = '') => `(kicad_sch (version 20250114) (generator eeschema)
(uuid "00000000-0000-4000-8000-000000000001") (paper "A4")
(title_block (title "DO NOT SHOW PAGE TITLE")) (lib_symbols) ${content})`;
const wire =
'(wire (pts (xy 10 10) (xy 30 20)) (stroke (width 0) (type default)) (uuid "00000000-0000-4000-8000-000000000002"))';
describe('saved PCB project cover rendering', () => {
it('prefers the PCB, fits off-board components and is deterministic without modifying source bytes', async () => {
const project = importFiles([
file(
'main.kicad_pcb',
board(`
(gr_rect (start 0 0) (end 20 20) (stroke (width 0.1) (type solid)) (fill none) (layer "Edge.Cuts"))
(footprint "R" (layer "F.Cu") (at 100 10)
(pad "1" thru_hole circle (at 0 0) (size 2 2) (drill 1) (layers "*.Cu" "*.Mask")))`),
),
file('main.kicad_sch', schematic(wire)),
]);
const before = structuredClone(project);
const cover = await projectCoverSvg(project);
expect(cover?.source).toBe('pcb');
expect(cover?.svg).toContain('width="800" height="450"');
expect(cover?.viewBox[0]).toBeLessThan(0);
expect(cover!.viewBox[0] + cover!.viewBox[2]).toBeGreaterThan(101);
expect(cover?.svg).toContain('#0f1114');
expect(cover).toEqual(await projectCoverSvg(project));
expect(project).toEqual(before);
});
it('falls back from an empty board to the root schematic content, excluding the page frame', async () => {
const project = importFiles([
file('main.kicad_pcb', board()),
file('main.kicad_sch', schematic(wire)),
]);
const cover = await projectCoverSvg(project);
expect(cover?.source).toBe('schematic');
expect(cover?.svg).not.toContain('DO NOT SHOW PAGE TITLE');
expect(cover!.viewBox[2]).toBeLessThan(40);
expect(cover!.viewBox[2] / cover!.viewBox[3]).toBeCloseTo(16 / 9);
});
it('returns no image for a genuinely empty project instead of capturing a blank page', async () => {
expect(
await projectCoverSvg(
importFiles([file('main.kicad_pcb', board()), file('main.kicad_sch', schematic())]),
),
).toBeNull();
});
it('keeps embedded raster images in an image-only schematic', async () => {
const png =
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aX2kAAAAASUVORK5CYII=';
const cover = await projectCoverSvg(
importFiles([
file('main.kicad_sch', schematic(`(image (at 50 50) (scale 10) (data ${png}))`)),
]),
);
expect(cover?.source).toBe('schematic');
expect(cover?.svg).toContain(`data:image/png;base64,${png}`);
expect(cover?.svg).toContain('<image ');
});
it('plots a real filled board with native zones, tracks, pads and footprints', async () => {
const project = importFiles([
{
name: 'main.kicad_pcb',
bytes: readFileSync(
new URL('../../data/zone_fill/hatchsmall_kicad_cli.kicad_pcb', import.meta.url),
),
},
]);
const cover = await projectCoverSvg(project);
expect(cover?.source).toBe('pcb');
expect(cover!.svg.length).toBeGreaterThan(1000);
expect(cover?.svg).toContain('<path');
});
});
@@ -0,0 +1,208 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import 'fake-indexeddb/auto';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { importFiles, openArchive } from '@ziroeda/designer/src/platform/archive.js';
import { MockPcbProjectApi, mockFaults } from '@ziroeda/designer/src/platform/mock-api.js';
import { WorkspaceRuntime } from '@ziroeda/designer/src/platform/runtime.js';
import { DEFAULT_LIMITS, type ProjectCover } from '@ziroeda/designer/src/platform/types.js';
import { listPending } from '@ziroeda/designer/src/platform/storage.js';
import { generateProjectCover } from '@ziroeda/designer/src/platform/cover-client.js';
vi.mock('@ziroeda/designer/src/platform/archive-client.js', async () => {
const archive = await import('@ziroeda/designer/src/platform/archive.js');
return { packProject: archive.createArchive, unpackProject: archive.openArchive };
});
vi.mock('@ziroeda/designer/src/platform/cover-client.js', () => ({
generateProjectCover: vi.fn(),
}));
const image: ProjectCover = { bytes: new Uint8Array([82, 73, 70, 70]), contentType: 'image/webp' };
const active: WorkspaceRuntime[] = [];
async function setup() {
const owner = crypto.randomUUID(),
api = new MockPcbProjectApi(owner);
const metadata = await api.create('Cover test', crypto.randomUUID());
const native = importFiles([
{ name: 'main.kicad_pcb', bytes: new TextEncoder().encode('(kicad_pcb)') },
]);
const runtime = new WorkspaceRuntime(owner, metadata, native, api, DEFAULT_LIMITS, 'test');
active.push(runtime);
return { owner, api, metadata, native, runtime };
}
beforeEach(() => {
mockFaults.current = 'none';
vi.mocked(generateProjectCover).mockReset().mockResolvedValue(image);
});
afterEach(() => {
for (const runtime of active.splice(0)) runtime.revoke();
vi.restoreAllMocks();
vi.useRealTimers();
});
describe('PCB save cover coordination', () => {
it('renders the acknowledged ZIP, keeps edits made during upload dirty and binds after design commit', async () => {
const { api, runtime } = await setup();
const upload = api.upload.bind(api);
api.upload = async (signature, bytes) => {
await upload(signature, bytes);
runtime.writeFile('later.bin', new Uint8Array([99]));
};
const bind = vi.spyOn(api, 'setCover');
vi.mocked(generateProjectCover).mockImplementationOnce(async (bytes) => {
expect((await api.get(runtime.code)).version).toBe(1);
expect((await openArchive(bytes)).files.some((f) => f.name === 'later.bin')).toBe(false);
return image;
});
const saving = runtime.save();
expect(runtime.save()).toBe(saving);
await saving;
expect(bind).toHaveBeenCalledOnce();
expect(runtime.dirty).toBe(true);
expect(runtime.getSnapshot().phase).toBe('dirty');
expect(runtime.metadata.coverUrl).toMatch(/^data:image\/webp;base64,/);
expect(runtime.getSnapshot().coverUpdating).toBe(false);
});
it('keeps the previous cover on failure and retries the original ZIP without another design version', async () => {
const { api, runtime } = await setup();
await api.setCover(runtime.code, 'https://example.test/old.webp');
mockFaults.current = 'cover-failed';
await expect(runtime.save()).resolves.toBeUndefined();
expect(runtime.getSnapshot()).toMatchObject({
phase: 'saved',
error: null,
coverWarning: true,
});
expect((await api.get(runtime.code)).coverUrl).toBe('https://example.test/old.webp');
const original = vi.mocked(generateProjectCover).mock.calls[0]![0];
mockFaults.current = 'none';
await runtime.save();
expect(vi.mocked(generateProjectCover).mock.calls[1]![0]).toEqual(original);
expect((await api.get(runtime.code)).version).toBe(1);
expect(runtime.getSnapshot().coverWarning).toBe(false);
});
it('can retry cover generation failures and clears an old cover only for a saved empty design', async () => {
const { api, runtime } = await setup();
await api.setCover(runtime.code, 'https://example.test/old.webp');
vi.mocked(generateProjectCover).mockRejectedValueOnce(new Error('plot failed'));
await runtime.save();
expect((await api.get(runtime.code)).coverUrl).toBe('https://example.test/old.webp');
vi.mocked(generateProjectCover).mockResolvedValueOnce(null);
await runtime.retryCover();
expect((await api.get(runtime.code)).coverUrl).toBeNull();
expect((await api.get(runtime.code)).version).toBe(1);
});
it('uses the original snapshot after an unknown confirmation, never current working files', async () => {
const { api, runtime, owner } = await setup();
mockFaults.current = 'confirmation-lost';
await expect(runtime.save()).rejects.toThrow();
expect(generateProjectCover).not.toHaveBeenCalled();
const [pending] = await listPending(owner, runtime.code);
runtime.writeFile('new.bin', new Uint8Array([88]));
await runtime.save();
expect(vi.mocked(generateProjectCover).mock.calls[0]![0]).toEqual(pending!.bytes);
expect((await api.get(runtime.code)).version).toBe(1);
expect(runtime.dirty).toBe(true);
});
it('does not bind an older cover after another tab saves a newer design', async () => {
const { api, runtime } = await setup();
const get = api.get.bind(api);
let reads = 0;
api.get = async (code) => ({ ...(await get(code)), version: ++reads === 1 ? 1 : 2 });
const bind = vi.spyOn(api, 'setCover');
await runtime.save();
expect(bind).not.toHaveBeenCalled();
expect(runtime.getSnapshot().phase).toBe('saved');
});
it('cancels cover work when the session closes without marking a saved design failed', async () => {
const { runtime } = await setup();
let rendering!: () => void;
const started = new Promise<void>((resolve) => {
rendering = resolve;
});
vi.mocked(generateProjectCover).mockImplementationOnce(async () => {
rendering();
return new Promise(() => {});
});
const saving = runtime.save();
await started;
runtime.revoke();
await saving;
expect(runtime.getSnapshot().phase).toBe('saved');
expect(runtime.getSnapshot().error).toBeNull();
});
it('ends the cover phase at its deadline even if a renderer ignores cancellation', async () => {
const deadline = new AbortController();
const timeout = vi.spyOn(AbortSignal, 'timeout').mockReturnValue(deadline.signal);
const { runtime } = await setup();
let started!: () => void;
const rendering = new Promise<void>((resolve) => {
started = resolve;
});
vi.mocked(generateProjectCover).mockImplementationOnce(async () => {
started();
return new Promise(() => {});
});
const saving = runtime.save();
await rendering;
expect(timeout).toHaveBeenCalledWith(30000);
deadline.abort(new DOMException('Cover deadline reached', 'TimeoutError'));
await saving;
expect(runtime.getSnapshot()).toMatchObject({
phase: 'saved',
coverUpdating: false,
coverWarning: true,
error: null,
});
});
it('generates the new version cover when a previous cover retry overlaps the next design save', async () => {
const { api, runtime } = await setup();
vi.mocked(generateProjectCover).mockRejectedValueOnce(new Error('first cover failed'));
await runtime.save();
let release!: (cover: ProjectCover) => void;
let started!: () => void;
const rendering = new Promise<void>((resolve) => {
started = resolve;
});
vi.mocked(generateProjectCover).mockImplementationOnce(async () => {
started();
return new Promise((resolve) => {
release = resolve;
});
});
const retry = runtime.retryCover();
await rendering;
runtime.writeFile('version-two.bin', new Uint8Array([2]));
const commit = api.commit.bind(api);
let committed!: () => void;
const committedNew = new Promise<void>((resolve) => {
committed = resolve;
});
api.commit = async (code, upload) => {
const receipt = await commit(code, upload);
committed();
return receipt;
};
const bind = vi.spyOn(api, 'setCover');
const saving = runtime.save();
await committedNew;
release(image);
await Promise.all([retry, saving]);
expect((await api.get(runtime.code)).version).toBe(2);
expect(bind).toHaveBeenCalledOnce();
const snapshot = vi.mocked(generateProjectCover).mock.calls.at(-1)![0];
expect((await openArchive(snapshot)).files.some((f) => f.name === 'version-two.bin')).toBe(
true,
);
expect(runtime.getSnapshot()).toMatchObject({
phase: 'saved',
coverWarning: false,
coverUpdating: false,
});
});
});
@@ -0,0 +1,35 @@
// @vitest-environment happy-dom
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import { afterEach, expect, it, vi } from 'vitest';
import { EnvironmentStatus, type RuntimeReadiness } from '@ziroeda/designer/src/codex-pcb/EnvironmentStatus.js';
afterEach(cleanup);
const unavailable: RuntimeReadiness = {
ok: false, status: 'unavailable', checked_at: 100,
checks: [{ name: 'eda_bridge', ok: false, message: 'BRIDGE_NOT_READY: command-space-missing' }],
};
it('shows a persistent accessible failure and preserves exact diagnostic details', () => {
const retry = vi.fn();
render(<EnvironmentStatus report={unavailable} checking={false} error="" onRetry={retry}/>);
expect(screen.getByRole('alert')).toBeTruthy();
expect(screen.getByText('EasyEDA 命令桥接')).toBeTruthy();
expect(screen.getByText(/BRIDGE_NOT_READY/)).toBeTruthy();
fireEvent.click(screen.getByRole('button', { name: '重新检查环境' }));
expect(retry).toHaveBeenCalledOnce();
});
it('shows progress and disables duplicate retries while checking', () => {
render(<EnvironmentStatus report={null} checking error="" onRetry={vi.fn()}/>);
expect(screen.getByRole('status')).toBeTruthy();
expect((screen.getByRole('button', { name: '检查中…' }) as HTMLButtonElement).disabled).toBe(true);
});
it('does not leave an error banner after recovery', () => {
const { container } = render(<EnvironmentStatus report={{ ok: true, status: 'ready', checks: [], checked_at: 200 }} checking={false} error="" onRetry={vi.fn()}/>);
expect(container.textContent).toBe('');
});
it('keeps a failure visible when the workbench is closed and links to its details', () => {
const open = vi.fn();
render(<EnvironmentStatus report={unavailable} checking={false} error="" compact onRetry={vi.fn()} onOpen={open}/>);
fireEvent.click(screen.getByRole('button', { name: '查看检查结果' }));
expect(open).toHaveBeenCalledOnce();
expect(screen.getByRole('alert')).toBeTruthy();
});
@@ -0,0 +1,36 @@
// @vitest-environment happy-dom
import { afterEach, expect, it, vi } from 'vitest';
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import { DesignHistory } from '@ziroeda/designer/src/pcb-service/DesignHistory.js';
afterEach(cleanup);
const tasks=[{task_id:'pcb-a',title:'电源板',state:'failed'}, {task_id:'pcb-b',title:'传感器板',state:'completed',pinned:true}];
it('puts pinned history first and keeps ellipsis actions separate from task selection',()=>{
const select=vi.fn(),manage=vi.fn(async()=>true);
render(<DesignHistory tasks={tasks} selected="pcb-a" disabled={false} onSelect={select} onManage={manage}/>);
fireEvent.click(screen.getByLabelText('展开设计历史'));
const list=screen.getByLabelText('设计历史列表');
expect(list.textContent!.indexOf('传感器板')).toBeLessThan(list.textContent!.indexOf('电源板'));
fireEvent.click(screen.getByLabelText('管理设计:电源板'));
expect(select).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole('menuitem',{name:/^置顶$/}));
expect(manage).toHaveBeenCalledWith('pcb-a','pin',true);
});
it('renames on submit and uses archive as deletion rather than task selection',async()=>{
const manage=vi.fn(async()=>false),select=vi.fn();
render(<DesignHistory tasks={tasks} selected={null} disabled={false} onSelect={select} onManage={manage}/>);
fireEvent.click(screen.getByLabelText('展开设计历史'));fireEvent.click(screen.getByLabelText('管理设计:电源板'));
fireEvent.click(screen.getByRole('menuitem',{name:'重命名'}));
fireEvent.change(screen.getByLabelText('新的设计名称'),{target:{value:' 新电源板 '}});
fireEvent.submit(screen.getByRole('form',{name:'重命名设计'}));
expect(manage).toHaveBeenCalledWith('pcb-a','rename','新电源板');
await vi.waitFor(()=>expect((screen.getByRole('menuitem',{name:'归档(删除)'}) as HTMLButtonElement).disabled).toBe(false));
fireEvent.click(screen.getByRole('menuitem',{name:'归档(删除)'}));
expect(manage).toHaveBeenCalledWith('pcb-a','archive',undefined);expect(select).not.toHaveBeenCalled();
});
it('closes history on Escape and selects designs with a separate button',()=>{
const select=vi.fn();render(<DesignHistory tasks={tasks} selected={null} disabled={false} onSelect={select} onManage={async()=>true}/>);
fireEvent.click(screen.getByLabelText('展开设计历史'));fireEvent.keyDown(document,{key:'Escape'});
expect(screen.queryByLabelText('设计历史列表')).toBeNull();
fireEvent.click(screen.getByLabelText('展开设计历史'));fireEvent.click(screen.getByTitle('电源板'));
expect(select).toHaveBeenCalledWith('pcb-a');expect(screen.queryByLabelText('设计历史列表')).toBeNull();
});
@@ -185,6 +185,58 @@ describe('published PCB workspace HTTP contract', () => {
runtime.revoke();
});
it('uploads the signed cover without platform credentials and binds only the documented coverUrl field', async () => {
const { api } = client();
const coverUrl = 'https://cdn.example.test/project-covers/cover.webp';
fetcher.mockResolvedValueOnce(reply({ ...signature(), coverUrl }));
fetcher.mockResolvedValueOnce(new Response('', { status: 200 }));
const url = await api.uploadCover({
bytes: new Uint8Array([0, 128, 255]),
contentType: 'image/webp',
});
expect(url).toBe(coverUrl);
expect(fetcher.mock.calls[0]![0]).toBe('/api/uploads/project-covers/signature');
expect(JSON.parse(String(fetcher.mock.calls[0]![1]?.body))).toEqual({
contentType: 'image/webp',
fileSize: 3,
});
expect(new Headers(fetcher.mock.calls[0]![1]?.headers).get('Authorization')).toBe(
'Bearer platform-token',
);
const [, upload] = fetcher.mock.calls[1]!;
expect(upload?.headers).toBeUndefined();
expect(upload?.credentials).toBe('omit');
const fields = [...(upload!.body as FormData).entries()];
expect(fields.slice(0, -1)).toEqual(Object.entries(signature().formFields));
expect(fields.at(-1)?.[0]).toBe('file');
expect((fields.at(-1)![1] as File).type).toBe('image/webp');
fetcher.mockResolvedValueOnce(reply({ ...project(), coverUrl }));
await api.setCover(project().pcbProjectCode, url);
expect(fetcher.mock.calls[2]![1]?.method).toBe('PATCH');
expect(JSON.parse(String(fetcher.mock.calls[2]![1]?.body))).toEqual({ coverUrl });
});
it('rejects invalid cover signatures, oversize data and stale identity after object upload', async () => {
const { api, current } = client();
const cover = { bytes: new Uint8Array([1]), contentType: 'image/webp' as const };
await expect(
api.uploadCover({ ...cover, bytes: new Uint8Array(5 * 1024 * 1024 + 1) }),
).rejects.toMatchObject({ code: 'PCB_COVER_TOO_LARGE' });
expect(fetcher).not.toHaveBeenCalled();
fetcher.mockResolvedValueOnce(reply({ ...signature(), coverUrl: 'javascript:alert(1)' }));
await expect(api.uploadCover(cover)).rejects.toMatchObject({ code: 'BAD_RESPONSE' });
expect(fetcher).toHaveBeenCalledTimes(1);
fetcher.mockResolvedValueOnce(
reply({ ...signature(), coverUrl: 'https://cdn.example.test/cover.webp' }),
);
fetcher.mockImplementationOnce(async () => {
current.value = null;
return new Response('', { status: 200 });
});
await expect(api.uploadCover(cover)).rejects.toMatchObject({ code: 'STALE_IDENTITY' });
expect(fetcher).toHaveBeenCalledTimes(3);
});
it('rejects truncated downloads, non-HTTPS storage URLs and malformed signatures', async () => {
const { api } = client();
const document = {
@@ -1,32 +1,53 @@
import { describe, expect, it } from 'vitest';
import { strToU8, zipSync } from 'fflate';
import { findObjArchive, stepHasColors, unpackColoredObj } from '../../../designer/src/codex-pcb/model-appearance.js';
import { strToU8, zipSync, type Zippable } from 'fflate';
import {
findObjArchive,
stepHasColors,
unpackColoredObj,
} from '@ziroeda/designer/src/codex-pcb/model-appearance.js';
const obj = strToU8('mtllib board.mtl\nv 0 0 0\nv 1 0 0\nv 0 1 0\nusemtl board\nf 1 2 3\n');
const mtl = strToU8('newmtl board\nKd 0.1 0.5 0.2\n');
describe('delivered model appearance', () => {
it('prefers original colored STEP and ignores color mentions inside comments', () => {
expect(stepHasColors(strToU8("#1=COLOUR_RGB('',0.,1.,0.);#2=STYLED_ITEM('',(#3),#4);"))).toBe(true);
expect(stepHasColors(strToU8("#1=COLOUR_RGB('',0.,1.,0.);#2=STYLED_ITEM('',(#3),#4);"))).toBe(
true,
);
expect(stepHasColors(strToU8('ISO-10303-21; /* COLOUR_RGB( STYLED_ITEM( */'))).toBe(false);
expect(stepHasColors(strToU8('ISO-10303-21; COLOUR_RGB( )'))).toBe(false);
});
it('finds the companion archive without selecting a generic delivery or Gerber ZIP', () => {
const files = [{name:'delivery.zip',kind:'bundle'},{name:'12-gerber.zip',kind:'other'},{name:'14-final-obj.zip',kind:'other'}];
const files = [
{ name: 'delivery.zip', kind: 'bundle' },
{ name: '12-gerber.zip', kind: 'other' },
{ name: '14-final-obj.zip', kind: 'other' },
];
expect(findObjArchive(files)?.name).toBe('14-final-obj.zip');
expect(findObjArchive([{name:'16-ESP32-R1-3D.zip',kind:'other'}])?.name).toContain('3D');
expect(findObjArchive(files.slice(0,2))).toBeUndefined();
expect(findObjArchive([{ name: '16-ESP32-R1-3D.zip', kind: 'other' }])?.name).toContain('3D');
expect(findObjArchive(files.slice(0, 2))).toBeUndefined();
});
it('preserves the actual nested OBJ, MTL and textures', () => {
const files = {'model/board.obj':obj,'model/board.mtl':mtl,'model/texture.png':new Uint8Array([1,2,3])};
const files = {
'model/board.obj': obj,
'model/board.mtl': mtl,
'model/texture.png': new Uint8Array([1, 2, 3]),
};
expect(unpackColoredObj(zipSync(files))).toEqual(files);
});
it('rejects missing/mismatched material libraries and ambiguous geometry', () => {
for (const files of [{ 'board.obj': obj }, {'board.obj':obj,'wrong.mtl':mtl}, {'a.obj':obj,'b.obj':obj,'board.mtl':mtl}]) {
const archives: Zippable[] = [
{ 'board.obj': obj },
{ 'board.obj': obj, 'wrong.mtl': mtl },
{ 'a.obj': obj, 'b.obj': obj, 'board.mtl': mtl },
];
for (const files of archives) {
expect(() => unpackColoredObj(zipSync(files))).toThrow();
}
});
it('rejects traversal and malformed archives', () => {
expect(() => unpackColoredObj(zipSync({'../board.obj':obj,'board.mtl':mtl}))).toThrow('路径');
expect(() => unpackColoredObj(new Uint8Array([1,2,3]))).toThrow();
expect(() => unpackColoredObj(zipSync({ '../board.obj': obj, 'board.mtl': mtl }))).toThrow(
'路径',
);
expect(() => unpackColoredObj(new Uint8Array([1, 2, 3]))).toThrow();
});
});
@@ -0,0 +1,114 @@
import { copyFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { spawn } from 'node:child_process';
import { createServer, type Server } from 'node:http';
import { expect, it } from 'vitest';
const listen = async (server: Server): Promise<number> => {
await new Promise<void>((done) => server.listen(0, '127.0.0.1', done));
return (server.address() as { port: number }).port;
};
const close = async (server: Server): Promise<void> => {
server.closeAllConnections();
await new Promise<void>((done) => server.close(() => done()));
};
it('keeps account and AI APIs on separate upstreams with the appropriate headers', async () => {
const dir = mkdtempSync(join(tmpdir(), 'vibemake-platform-proxy-'));
const scripts = join(dir, 'scripts'),
dist = join(dir, 'designer/dist');
mkdirSync(scripts, { recursive: true });
mkdirSync(dist, { recursive: true });
copyFileSync(resolve(__dirname, '../../../scripts/serve.mjs'), join(scripts, 'serve.mjs'));
writeFileSync(join(dist, 'index.html'), '<h1>Platform fixture</h1>');
writeFileSync(join(dist, 'pcb-service-config.json'), JSON.stringify({ base: '/pcb/' }));
const seen: {
service: string;
path?: string;
origin?: string;
referer?: string;
authorization?: string;
body: string;
}[] = [];
const upstream = (service: string) =>
createServer((req, res) => {
let body = '';
req.on('data', (chunk) => {
body += chunk;
});
req.on('end', () => {
seen.push({
service,
path: req.url,
origin: req.headers.origin,
referer: req.headers.referer,
authorization: req.headers.authorization,
body,
});
res.setHeader('content-type', 'application/json');
res.end(JSON.stringify({ service }));
});
});
const platform = upstream('platform'),
pcb = upstream('pcb');
const platformPort = await listen(platform),
pcbPort = await listen(pcb);
const reservation = createServer();
const port = await listen(reservation);
await close(reservation);
const child = spawn(process.execPath, [join(scripts, 'serve.mjs')], {
env: {
...process.env,
HOST: '127.0.0.1',
PORT: String(port),
API_TARGET: `http://127.0.0.1:${platformPort}`,
PCB_API_TARGET: `http://127.0.0.1:${pcbPort}`,
PCB_API_ORIGIN: 'http://127.0.0.1:5173',
PUBLIC_ORIGIN: '',
TLS_CERT: '',
TLS_KEY: '',
},
stdio: ['ignore', 'pipe', 'pipe'],
});
try {
await new Promise<void>((done, reject) => {
child.stdout.once('data', () => done());
child.once('exit', (code) => reject(Error(`Server exited ${code}`)));
child.stderr.once('data', (bytes) => reject(Error(String(bytes))));
});
const base = `http://127.0.0.1:${port}`;
const response = await fetch(base + '/api/pcb/workspace/projects?name=board', {
method: 'POST',
body: '{"name":"board"}',
headers: { Origin: base, Referer: base + '/pcb/', Authorization: 'Bearer test-token' },
});
expect(await response.json()).toEqual({ service: 'platform' });
expect(response.headers.get('cache-control')).toBe('no-store');
expect(seen[0]).toEqual({
service: 'platform',
path: '/api/pcb/workspace/projects?name=board',
origin: undefined,
referer: undefined,
authorization: 'Bearer test-token',
body: '{"name":"board"}',
});
expect(await (await fetch(base + '/pcb/pcb-api/v1/tasks')).json()).toEqual({ service: 'pcb' });
expect(seen[1]).toMatchObject({
service: 'pcb',
path: '/api/v1/tasks',
origin: 'http://127.0.0.1:5173',
});
const rejected = await fetch(base + '/api/auth/logout', {
method: 'POST',
headers: { Origin: 'http://foreign.invalid' },
});
expect(rejected.status).toBe(403);
expect(seen).toHaveLength(2);
} finally {
const exited = new Promise<void>((done) => child.once('exit', () => done()));
child.kill();
await exited;
await Promise.all([close(platform), close(pcb)]);
rmSync(dir, { recursive: true, force: true });
}
}, 20000);
@@ -0,0 +1,116 @@
// @vitest-environment happy-dom
import { act, cleanup, render } from '@testing-library/react';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import PlatformPcbService from '@ziroeda/designer/src/platform/PlatformPcbService.js';
import {
DEFAULT_LIMITS,
type NativeProject,
type PcbProjectApi,
} from '@ziroeda/designer/src/platform/types.js';
import type { Task } from '@ziroeda/designer/src/pcb-service/client.js';
const mocks = vi.hoisted(() => ({
convert: vi.fn(),
onImport: null as null | ((bytes: Uint8Array, task: Task) => Promise<void>),
}));
vi.mock('@ziroeda/designer/src/pcb-service/PcbServiceDock.js', () => ({
PcbServiceDock: (props: { onImport: typeof mocks.onImport }) => {
mocks.onImport = props.onImport;
return null;
},
}));
vi.mock('@ziroeda/designer/src/pcb-service/import-project.js', () => ({
convertProject: mocks.convert,
}));
const enc = new TextEncoder();
const binary = new Uint8Array([0, 255, 128, 3]);
const files = () => [
{ name: 'copy/board.kicad_pro', bytes: enc.encode('{}') },
{ name: 'copy/board.kicad_sch', bytes: enc.encode('(kicad_sch (version 20250114))') },
{ name: 'copy/board.kicad_pcb', bytes: enc.encode('(kicad_pcb (version 20241229))') },
{ name: 'copy/models/part.step', bytes: binary },
{ name: 'copy/AI-SOURCE.json', bytes: enc.encode('{"validation_state":"unverified"}') },
];
const task: Task = {
task_id: 'pcb-generated',
state: 'completed',
delivery: { manifest_sha256: 'source-digest', artifacts: [] },
};
const api = () => ({ capabilities: vi.fn(async () => DEFAULT_LIMITS) }) as unknown as PcbProjectApi;
type ImportProject = (name: string, project: NativeProject, requestId: string) => Promise<void>;
beforeEach(() => {
mocks.convert.mockReset().mockResolvedValue({ files: files() });
});
afterEach(cleanup);
it('creates a platform project with native roots, binary resources and unverified provenance', async () => {
const create = vi.fn<ImportProject>(async () => {});
render(<PlatformPcbService api={api()} importProject={create} />);
const bytes = new Uint8Array([1, 2, 3]);
await act(async () => {
await mocks.onImport!(bytes, task);
});
expect(create).toHaveBeenCalledTimes(1);
const [name, native, requestId] = create.mock.calls[0]!;
expect(name).toMatch(/^AI-pcb-generated-\d+$/);
expect(requestId).toBeTruthy();
expect(native.roots).toEqual({
project: 'board.kicad_pro',
schematic: 'board.kicad_sch',
board: 'board.kicad_pcb',
});
expect(native.files.find((f) => f.name === 'models/part.step')!.bytes).toEqual(binary);
expect(native.files.find((f) => f.name === 'AI-SOURCE.json')!.bytes).toEqual(files()[4]!.bytes);
expect(mocks.convert).toHaveBeenCalledWith(bytes, name, {
task_id: task.task_id,
manifest_sha256: 'source-digest',
});
});
it('enforces platform import limits before creating an account project', async () => {
const sourceApi = api();
vi.mocked(sourceApi.capabilities).mockResolvedValue({ ...DEFAULT_LIMITS, maxFileCount: 1 });
const create = vi.fn(async () => {});
render(<PlatformPcbService api={sourceApi} importProject={create} />);
await expect(mocks.onImport!(new Uint8Array(), task)).rejects.toMatchObject({
code: 'PCB_TOO_MANY_FILES',
});
expect(create).not.toHaveBeenCalled();
});
it('reuses the creation identity on retry and propagates the current-project leave guard', async () => {
const create = vi
.fn()
.mockRejectedValueOnce(new Error('已取消新建工程。'))
.mockResolvedValue(undefined);
render(<PlatformPcbService api={api()} importProject={create} />);
await expect(mocks.onImport!(new Uint8Array(), task)).rejects.toThrow('已取消');
await mocks.onImport!(new Uint8Array(), task);
expect(create.mock.calls[1]![0]).toBe(create.mock.calls[0]![0]);
expect(create.mock.calls[1]![2]).toBe(create.mock.calls[0]![2]);
});
it('rejects an import completed after the account API has changed or the dock has unmounted', async () => {
let finish!: (value: { files: ReturnType<typeof files> }) => void;
mocks.convert.mockImplementation(
() =>
new Promise((resolve) => {
finish = resolve;
}),
);
const create = vi.fn(async () => {});
const view = render(<PlatformPcbService api={api()} importProject={create} />);
const pending = mocks.onImport!(new Uint8Array(), task);
const rejected = expect(pending).rejects.toMatchObject({ code: 'STALE_BINDING' });
await vi.waitFor(() => expect(finish).toBeTypeOf('function'));
view.rerender(<PlatformPcbService api={api()} importProject={create} />);
finish({ files: files() });
await rejected;
expect(create).not.toHaveBeenCalled();
const unmounted = mocks.onImport!(new Uint8Array(), task);
const rejectedUnmount = expect(unmounted).rejects.toMatchObject({ code: 'STALE_BINDING' });
await vi.waitFor(() => expect(mocks.convert).toHaveBeenCalledTimes(2));
view.unmount();
finish({ files: files() });
await rejectedUnmount;
});
@@ -0,0 +1,20 @@
// @vitest-environment happy-dom
// SPDX-License-Identifier: GPL-3.0-or-later
import { cleanup, fireEvent, render } from '@testing-library/react';
import { afterEach, describe, expect, it } from 'vitest';
import { ProjectCover } from '@ziroeda/designer/src/platform/ProjectCover.js';
afterEach(cleanup);
describe('PCB project card cover', () => {
it('reserves image dimensions, loads lazily and falls back after a failed image', () => {
const { container, rerender } = render(<ProjectCover url="https://example.test/cover.webp" />);
const image = container.querySelector('img')!;
expect(image.getAttribute('loading')).toBe('lazy');
expect(image.getAttribute('width')).toBe('800');
expect(image.getAttribute('height')).toBe('450');
fireEvent.error(image);
expect(container.querySelector('img')).toBeNull();
expect(container.querySelector('svg')).not.toBeNull();
rerender(<ProjectCover url="https://example.test/replaced.webp" />);
expect(container.querySelector('img')?.getAttribute('src')).toContain('replaced.webp');
});
});
+62
View File
@@ -0,0 +1,62 @@
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',
]);
});
it('rejects an HTML success response from an incorrect proxy target', async () => {
vi.stubGlobal('fetch', vi.fn(async () => new Response('<html>website</html>')));
await expect(request('/session')).rejects.toThrow('无法识别的响应');
});
it('keeps the connection timeout signal when renewing an expired API session', async () => {
const controller = new AbortController();
const fetch = vi.fn()
.mockResolvedValueOnce(new Response('{}', { status: 401 }))
.mockResolvedValueOnce(new Response('{}'))
.mockResolvedValueOnce(new Response(JSON.stringify({ items: [] })));
vi.stubGlobal('fetch', fetch);
await request('/tasks', { signal: controller.signal });
for (const [, init] of fetch.mock.calls)
expect(init.signal).toBe(controller.signal);
});
@@ -0,0 +1,135 @@
// @vitest-environment happy-dom
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { afterEach, expect, it, vi } from 'vitest';
import { PcbServiceDock } from '@ziroeda/designer/src/pcb-service/PcbServiceDock.js';
afterEach(() => {
cleanup();
localStorage.clear();
vi.useRealTimers();
vi.unstubAllGlobals();
vi.unstubAllEnvs();
});
function openWorkspace() {
const view = render(<PcbServiceDock onImport={async () => {}} />);
fireEvent.click(screen.getByRole('button', { name: 'AI 自动绘板' }));
return view;
}
function response(path: string) {
return new Response(JSON.stringify(path.endsWith('/tasks') ? { items: [] } : { connected: true }));
}
it('does not connect, poll or replay saved commands while PCB AI is disabled', async () => {
vi.stubEnv('VITE_ENABLE_PCB_AI', 'false');
vi.useFakeTimers();
const fetch = vi.fn();
const eventSource = vi.fn();
vi.stubGlobal('fetch', fetch);
vi.stubGlobal('EventSource', eventSource);
localStorage.setItem('vibemake.pcb-service.active', 'pcb-paused');
localStorage.setItem('vibemake.pcb-service.operation', 'op-paused');
const queued = JSON.stringify({
action: 'create',
payload: { description: '保留待提交需求' },
request_id: 'paused-request',
});
localStorage.setItem('vibemake.pcb-service.outbox', queued);
render(<PcbServiceDock onImport={async () => {}} />);
await act(async () => { await vi.advanceTimersByTimeAsync(60000); });
expect(fetch).not.toHaveBeenCalled();
expect(eventSource).not.toHaveBeenCalled();
expect(screen.queryByRole('button', { name: 'AI 自动绘板' })).toBeNull();
expect(localStorage.getItem('vibemake.pcb-service.active')).toBe('pcb-paused');
expect(localStorage.getItem('vibemake.pcb-service.operation')).toBe('op-paused');
expect(localStorage.getItem('vibemake.pcb-service.outbox')).toBe(queued);
});
it('stops reporting a connection in progress when the backend times out and retries without an active task', async () => {
vi.useFakeTimers();
let available = false;
const fetch = vi.fn((path: string, init?: RequestInit) => {
if (available) return Promise.resolve(response(path));
return new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener('abort', () => reject(new DOMException('Aborted', 'AbortError')));
});
});
vi.stubGlobal('fetch', fetch);
openWorkspace();
expect(screen.getByText(/连接后台中/)).toBeTruthy();
await act(async () => { await vi.advanceTimersByTimeAsync(10000); });
expect(screen.getByText(/后台未连接/)).toBeTruthy();
expect(screen.getByRole('alert').textContent).toContain('超时');
fireEvent.change(screen.getByLabelText('PCB 设计需求'), { target: { value: '测试电源板' } });
expect((screen.getByRole('button', { name: '开始分析' }) as HTMLButtonElement).disabled).toBe(true);
available = true;
await act(async () => { await vi.advanceTimersByTimeAsync(5000); });
expect(screen.getByText(/已连接服务端/)).toBeTruthy();
expect(screen.queryByRole('alert')).toBeNull();
expect((screen.getByRole('button', { name: '开始分析' }) as HTMLButtonElement).disabled).toBe(false);
expect(fetch.mock.calls.map(([path]) => path.endsWith('/commands'))).not.toContain(true);
});
it('allows immediate reconnection without clearing entered requirements', async () => {
let available = false;
const fetch = vi.fn(async (path: string) => {
if (!available) throw new TypeError('Failed to fetch');
return response(path);
});
vi.stubGlobal('fetch', fetch);
openWorkspace();
await waitFor(() => expect(screen.getByText(/后台未连接/)).toBeTruthy());
fireEvent.change(screen.getByLabelText('PCB 设计需求'), { target: { value: '保留当前需求' } });
available = true;
fireEvent.click(screen.getByRole('button', { name: '重新连接' }));
await waitFor(() => expect(screen.getByText(/已连接服务端/)).toBeTruthy());
expect((screen.getByLabelText('PCB 设计需求') as HTMLTextAreaElement).value).toBe('保留当前需求');
expect(screen.queryByRole('alert')).toBeNull();
expect(fetch.mock.calls.filter(([path]) => path.endsWith('/session'))).toHaveLength(2);
});
it('detects a dropped idle connection and reconnects when the service returns', async () => {
vi.useFakeTimers();
let available = true;
vi.stubGlobal('fetch', vi.fn(async (path: string) => {
if (!available) throw new TypeError('Failed to fetch');
return response(path);
}));
openWorkspace();
await act(async () => { await vi.advanceTimersByTimeAsync(0); });
expect(screen.getByText(/已连接服务端/)).toBeTruthy();
available = false;
await act(async () => { await vi.advanceTimersByTimeAsync(15000); });
expect(screen.getByText(/后台未连接/)).toBeTruthy();
available = true;
await act(async () => { await vi.advanceTimersByTimeAsync(5000); });
expect(screen.getByText(/已连接服务端/)).toBeTruthy();
});
it('rejects a non-task service response instead of claiming to be connected', async () => {
vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ status: 'ok' }))));
openWorkspace();
await waitFor(() => expect(screen.getByText(/后台未连接/)).toBeTruthy());
expect(screen.getByRole('alert').textContent).toContain('确认连接的是 AI 生成服务');
});
it('aborts an unfinished connection and cancels retries when unmounted', async () => {
vi.useFakeTimers();
let signal: AbortSignal | null | undefined;
const fetch = vi.fn((_path: string, init?: RequestInit) => {
signal = init?.signal;
return new Promise<Response>((_resolve, reject) => {
signal?.addEventListener('abort', () => reject(new DOMException('Aborted', 'AbortError')));
});
});
vi.stubGlobal('fetch', fetch);
const view = openWorkspace();
view.unmount();
await act(async () => { await vi.advanceTimersByTimeAsync(30000); });
expect(signal?.aborted).toBe(true);
expect(fetch).toHaveBeenCalledTimes(1);
});
@@ -0,0 +1,82 @@
import { readFileSync } from 'node:fs';
import { expect, it } from 'vitest';
import { zipSync, unzipSync } from 'fflate';
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,
);
it('rejects incomplete native projects and traversal paths', async () => {
const source = { task_id: 'fixture', manifest_sha256: 'digest' };
const enc = new TextEncoder();
await expect(
convertProject(zipSync({ 'board.kicad_pcb': enc.encode('(kicad_pcb)') }), 'bad', source),
).rejects.toThrow('缺少同名');
await expect(
convertProject(zipSync({ '../board.kicad_pcb': enc.encode('(kicad_pcb)') }), 'bad', source),
).rejects.toThrow('不安全路径');
});
it.runIf(!!process.env.KICAD_IMPORT_FIXTURE)(
'imports native KiCad bytes without converting the original files',
async () => {
const bytes = new Uint8Array(readFileSync(process.env.KICAD_IMPORT_FIXTURE!));
const r = await convertProject(bytes, 'native-copy', {
task_id: 'native-fixture',
manifest_sha256: 'digest',
});
const original = unzipSync(bytes);
expect(r.components).toBe(2);
expect(r.tracks).toBe(2);
expect(r.zones).toBe(1);
expect(r.files.some((f) => f.name.endsWith('.kicad_prl'))).toBe(false);
for (const [name, content] of Object.entries(original).filter(([name]) => !name.endsWith('.kicad_prl'))) {
expect(r.files.find((f) => f.name === `native-copy/${name}`)?.bytes).toEqual(content);
}
const source = JSON.parse(
new TextDecoder().decode(r.files.find((f) => f.name.endsWith('AI-SOURCE.json'))!.bytes),
);
expect(source.source_format).toBe('kicad');
expect(source.validation_state).toBe('unverified');
},
60000,
);
it.runIf(!!process.env.KICAD_COMPLEX_IMPORT_FIXTURE)(
'preserves a routed STM32 native project with local USB STEP and license notices',
async () => {
const bytes = new Uint8Array(readFileSync(process.env.KICAD_COMPLEX_IMPORT_FIXTURE!));
const result = await convertProject(bytes, 'stm32-copy', { task_id: 'native-stm32', manifest_sha256: 'digest' });
expect(result.components).toBe(24);
expect(result.tracks).toBeGreaterThan(100);
expect(result.zones).toBe(2);
const original = unzipSync(bytes);
for (const [path, content] of Object.entries(original))
expect(result.files.find((f) => f.name === `stm32-copy/${path}`)?.bytes).toEqual(content);
expect(result.files.some((f) => f.name.endsWith('LICENSE.CERN-OHL-P-2.0'))).toBe(true);
expect(result.files.some((f) => f.name.endsWith('.STEP'))).toBe(true);
},
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,113 @@
// @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 () => {}} />);
fireEvent.click(screen.getByRole('button', { name: 'AI 自动绘板' }));
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(screen.queryByRole('dialog', { name: 'AI PCB 设计工作台' })).toBeNull();
expect(bodies[0]?.request_id).toBeTruthy();
expect(bodies[1]).toEqual(bodies[0]);
});
it('forgets deleted task and operation references without replaying commands', async () => {
// The updated task backend intentionally isolates its records from the old service.
localStorage.setItem('vibemake.pcb2.codex-service.active', 'pcb-removed');
localStorage.setItem('vibemake.pcb2.codex-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 () => {}} />);
fireEvent.click(screen.getByRole('button', { name: 'AI 自动绘板' }));
await waitFor(() => {
expect(localStorage.getItem('vibemake.pcb2.codex-service.active')).toBeNull();
expect(localStorage.getItem('vibemake.pcb2.codex-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);
});
it('clears the previous requirements when starting a new design', async () => {
vi.stubGlobal('fetch', vi.fn(async (path: string) =>
new Response(JSON.stringify(path.endsWith('/tasks') ? { items: [] } : {})),
));
render(<PcbServiceDock onImport={async () => {}} />);
fireEvent.click(screen.getByRole('button', { name: 'AI 自动绘板' }));
const input = screen.getByLabelText('PCB 设计需求') as HTMLTextAreaElement;
fireEvent.change(input, { target: { value: '上一次输入的分电板需求' } });
await waitFor(() => expect((screen.getByRole('button', { name: '开始分析' }) as HTMLButtonElement).disabled).toBe(false));
fireEvent.click(screen.getByRole('button', { name: '+ 新建设计' }));
expect(input.value).toBe('');
expect((screen.getByRole('button', { name: '开始分析' }) as HTMLButtonElement).disabled).toBe(true);
});
it('starts collapsed and preserves requirements when the user opens, closes and reopens the workspace', async () => {
vi.stubGlobal('fetch', vi.fn(async (path: string) =>
new Response(JSON.stringify(path.endsWith('/tasks') ? { items: [] } : {})),
));
render(<PcbServiceDock onImport={async () => {}} />);
const launcher = screen.getByRole('button', { name: 'AI 自动绘板' });
expect(launcher.getAttribute('aria-expanded')).toBe('false');
expect(screen.queryByRole('dialog', { name: 'AI PCB 设计工作台' })).toBeNull();
fireEvent.click(launcher);
expect(launcher.getAttribute('aria-expanded')).toBe('true');
expect(screen.getByRole('dialog', { name: 'AI PCB 设计工作台' })).toBeTruthy();
fireEvent.change(screen.getByLabelText('PCB 设计需求'), { target: { value: '保留这份 PCB 需求' } });
fireEvent.click(screen.getByRole('button', { name: '关闭 PCB 工作台' }));
expect(screen.queryByRole('dialog', { name: 'AI PCB 设计工作台' })).toBeNull();
expect(launcher.getAttribute('aria-expanded')).toBe('false');
fireEvent.click(launcher);
expect((screen.getByLabelText('PCB 设计需求') as HTMLTextAreaElement).value).toBe('保留这份 PCB 需求');
await waitFor(() => expect((screen.getByRole('button', { name: '开始分析' }) as HTMLButtonElement).disabled).toBe(false));
});
+67 -12
View File
@@ -1,13 +1,29 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import { describe, expect, it } from 'vitest';
import { observedProductionStage, progressStage, productionEstimate, remainingEstimate, type ProgressSession } from '../../../designer/src/codex-pcb/task-progress.js';
import {
observedProductionStage,
progressStage,
productionEstimate,
remainingEstimate,
type ProgressSession,
} from '@ziroeda/designer/src/codex-pcb/task-progress.js';
const running: ProgressSession = { id: 'running', state: 'running', busy: true, created_at: 100, approval: { at: 1000 } };
const running: ProgressSession = {
id: 'running',
state: 'running',
busy: true,
created_at: 100,
approval: { at: 1000 },
};
const event = (label: string) => ({ type: 'eda.started', at: 1100, data: { label } });
describe('PCB task progress from observed work', () => {
it('does not interpret future work in proposals or chat as completed milestones', () => {
expect(observedProductionStage([{ type: 'message', at: 101, data: { text: '接下来完成 layout、导出最终STEP与交付' } }])).toBe(2);
expect(
observedProductionStage([
{ type: 'message', at: 101, data: { text: '接下来完成 layout、导出最终STEP与交付' } },
]),
).toBe(2);
expect(progressStage({ ...running, approval: undefined, state: 'planning' }, 4, 4)).toBe(0);
expect(progressStage({ ...running, approval: undefined, state: 'review' }, 4)).toBe(1);
expect(progressStage({ ...running, approval: undefined, state: 'needs_input' }, 4)).toBe(0);
@@ -15,7 +31,12 @@ describe('PCB task progress from observed work', () => {
it('recognizes Chinese and English layout work but not early schematic/library setup', () => {
expect(observedProductionStage([event('select exact BOM and initialize schematic')])).toBe(2);
expect(observedProductionStage([event('read footprint library identities')])).toBe(2);
expect(observedProductionStage([event('place board components with bottom male headers'), event('inspect placement after outline API error')])).toBe(3);
expect(
observedProductionStage([
event('place board components with bottom male headers'),
event('inspect placement after outline API error'),
]),
).toBe(3);
expect(observedProductionStage([event('完成55×28mm原生板框与器件布局')])).toBe(3);
});
it('does not mistake intermediate STEP export for final delivery', () => {
@@ -30,17 +51,43 @@ describe('PCB task progress from observed work', () => {
expect(progressStage({ ...running, state: 'completed' }, 2)).toBe(5);
});
it('does not mark delivery completed just because the agent called the delivery tool', () => {
expect(progressStage(running, observedProductionStage([{ type: 'tool.started', at: 1200, data: { tool: 'pcb_deliver' } }]))).toBe(4);
expect(
progressStage(
running,
observedProductionStage([
{ type: 'tool.started', at: 1200, data: { tool: 'pcb_deliver' } },
]),
),
).toBe(4);
});
});
describe('PCB duration reference', () => {
const history: ProgressSession[] = [
{ id: 'a', state: 'completed', busy: false, created_at: 1, approval: { at: 20000 }, updated_at: 24300 },
{ id: 'b', state: 'completed', busy: false, created_at: 1, approval: { at: 40000 }, updated_at: 49200 },
{
id: 'a',
state: 'completed',
busy: false,
created_at: 1,
approval: { at: 20000 },
updated_at: 24300,
},
{
id: 'b',
state: 'completed',
busy: false,
created_at: 1,
approval: { at: 40000 },
updated_at: 49200,
},
];
it('uses completed production only, excluding review delay, active jobs and this job', () => {
expect(productionEstimate([...history, running, { ...history[0]!, id: 'bad', updated_at: 5 }], 'running')).toEqual({ low: 4200, high: 9300, samples: 2 });
expect(
productionEstimate(
[...history, running, { ...history[0]!, id: 'bad', updated_at: 5 }],
'running',
),
).toEqual({ low: 4200, high: 9300, samples: 2 });
expect(productionEstimate(history, 'a')?.samples).toBe(1);
expect(productionEstimate([running], 'running')).toBeNull();
});
@@ -48,10 +95,18 @@ describe('PCB duration reference', () => {
const estimate = { low: 4200, high: 9300, samples: 2 };
expect(remainingEstimate(running, estimate, 1600)).toBe('预计还需约 60–145 分钟');
expect(remainingEstimate(running, estimate, 11000)).toContain('已超出历史耗时参考');
expect(remainingEstimate({ ...running, state: 'review', approval: undefined }, estimate, 11000)).toContain('等待你确认方案');
expect(remainingEstimate({ ...running, state: 'needs_input', approval: undefined }, estimate, 11000)).toContain('补充需求');
expect(remainingEstimate({ ...running, state: 'failed' }, estimate, 11000)).toContain('恢复运行后');
expect(remainingEstimate({ ...running, state: 'completed' }, estimate, 11000)).toBe('交付文件已就绪');
expect(
remainingEstimate({ ...running, state: 'review', approval: undefined }, estimate, 11000),
).toContain('等待你确认方案');
expect(
remainingEstimate({ ...running, state: 'needs_input', approval: undefined }, estimate, 11000),
).toContain('补充需求');
expect(remainingEstimate({ ...running, state: 'failed' }, estimate, 11000)).toContain(
'恢复运行后',
);
expect(remainingEstimate({ ...running, state: 'completed' }, estimate, 11000)).toBe(
'交付文件已就绪',
);
expect(remainingEstimate(running, null, 1600)).toContain('历史样本不足');
});
});
+22
View File
@@ -0,0 +1,22 @@
import { expect, it } from 'vitest';
import { parseVisualBoard } from '@ziroeda/designer/src/pcb-service/board-visual.js';
const footprint=`(footprint "R" (at 10 20 90) (property "Reference" "R1") (property "Value" "10k") (pad "1" smd rect (at 2 0) (net 1 "VCC")) (pad "2" smd rect (at -2 0) (net 2 "GND")))`;
it('uses real pad networks and rotated footprint coordinates, preserving routed geometry',()=>{
const b=parseVisualBoard(`(kicad_pcb (net 1 "VCC") (net 2 "GND") ${footprint} (segment (start 10 18) (end 15 18) (net 1)))`);
expect(b.parts[0]?.ref).toBe('R1');expect(b.parts[0]?.value).toBe('10k');
expect(b.pads[0]?.x).toBeCloseTo(10);expect(b.pads[0]?.y).toBeCloseTo(18);
expect(b.paths).toEqual([{d:'M10 18 L15 18',net:'VCC',logical:false}]);
expect(b.nets).toEqual(['GND','VCC']);
});
it('marks unrouted connectivity as logical, without connecting unrelated pads',()=>{
const b=parseVisualBoard(`(kicad_pcb ${footprint} (footprint "C" (at 15 20) (property "Reference" "C1") (pad "1" smd rect (at 0 0) (net 1 "VCC"))))`);
expect(b.paths).toHaveLength(1);expect(b.paths[0]?.net).toBe('VCC');expect(b.paths[0]?.logical).toBe(true);
});
it('rejects malformed or empty project data instead of displaying a fabricated circuit',()=>{
expect(()=>parseVisualBoard('(kicad_pcb')).toThrow();expect(()=>parseVisualBoard('(kicad_pcb)')).toThrow();expect(()=>parseVisualBoard('(other)')).toThrow();
});
it('reads KiCad 10 string net names used by generated projects',()=>{
const b=parseVisualBoard(`(kicad_pcb ${footprint.replace('(net 1 "VCC")','(net "/VIN")')} (segment (start 10 18) (end 12 18) (net "/VIN")))`);
expect(b.pads[0]?.net).toBe('/VIN');expect(b.paths[0]?.net).toBe('/VIN');
});
+114
View File
@@ -0,0 +1,114 @@
#!/usr/bin/env python3
"""Create a backend-only upload bundle; exclude credentials, tasks and EDA binaries."""
import argparse
import hashlib
from pathlib import Path
import re
import shutil
import subprocess
import tarfile
import tempfile
import urllib.request
ROOT = Path(__file__).resolve().parents[1]
DEPLOY_FILES = (
'.env.example', 'Dockerfile', 'Dockerfile.dockerignore', 'compose.yaml',
'docker-entrypoint.sh', 'deploy.sh', 'requirements.txt', 'instructions.md',
'DEPLOY.md', 'THIRD-PARTY.md',
'build-assets/README.md',
)
API_ROOT = Path('backend/easyeda_backend/skills/easyeda-api')
def routing_assets():
# Read the release pin from the Dockerfile so packaging and building agree.
dockerfile = (ROOT / 'codex_pcb/Dockerfile').read_text()
checksum = re.search(r'^ARG FREEROUTING_SHA256=([0-9a-f]{64})$', dockerfile, re.M).group(1)
cache = ROOT / 'dist/pcb-backend-downloads'
cache.mkdir(parents=True, exist_ok=True)
files = []
for name, argument in (('freerouting.jar', 'FREEROUTING_URL'), ('LICENSE.freerouting', 'FREEROUTING_LICENSE_URL')):
path = cache / name
if path.is_file() and (name != 'freerouting.jar' or hashlib.sha256(path.read_bytes()).hexdigest() == checksum):
files.append(path)
continue
url = re.search(r'^ARG ' + argument + r'=(https://\S+)$', dockerfile, re.M).group(1)
print(f'Downloading {name} from the pinned upstream release...', flush=True)
with tempfile.NamedTemporaryFile(dir=cache, delete=False) as stream:
pending = Path(stream.name)
try:
curl = shutil.which('curl')
if curl:
subprocess.run([curl, '--fail', '--location', '--silent', '--show-error',
'--retry', '3', '--connect-timeout', '15', '--max-time', '180',
'--output', str(pending), url], check=True)
else:
with urllib.request.urlopen(url, timeout=60) as response, pending.open('wb') as stream:
shutil.copyfileobj(response, stream)
if name == 'freerouting.jar' and hashlib.sha256(pending.read_bytes()).hexdigest() != checksum:
raise ValueError('Freerouting checksum mismatch; no upload bundle was changed')
if not pending.stat().st_size:
raise ValueError(f'Empty download: {name}')
if name == 'LICENSE.freerouting' and b'GNU GENERAL PUBLIC LICENSE' not in pending.read_bytes():
raise ValueError('Freerouting license download is not a GPL license')
pending.replace(path)
finally:
pending.unlink(missing_ok=True)
files.append(path)
return files
def package(output, with_freerouting=False):
assets = routing_assets() if with_freerouting else []
output = output.expanduser().resolve()
output.parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix='pcb-backend-package-') as temporary:
bundle = Path(temporary) / 'vibemake-pcb-backend'
code = bundle / 'codex_pcb'
code.mkdir(parents=True)
sources = [ROOT / 'codex_pcb' / name for name in DEPLOY_FILES]
sources += sorted((ROOT / 'codex_pcb').glob('*.py'))
for source in sources:
target = code / source.relative_to(ROOT / 'codex_pcb')
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(source, target)
for source in assets:
shutil.copy2(source, code / 'build-assets' / source.name)
shutil.copy2(ROOT / 'LICENSE', bundle / 'LICENSE')
api = bundle / API_ROOT
api.mkdir(parents=True)
shutil.copytree(ROOT / API_ROOT / 'references', api / 'references')
shutil.copy2(ROOT / API_ROOT / 'SKILL.md', api / 'SKILL.md')
if not (api / 'references/_index.md').is_file():
raise ValueError('The standalone EDA API reference index is missing')
vendor = bundle / 'vendor/lceda-pro'
vendor.mkdir(parents=True)
(vendor / 'PLACE-LINUX-APP-HERE.txt').write_text(
'Place the complete Linux EasyEDA Pro application directory here.\n'
'The configured executable must be /opt/lceda-pro/lceda-pro.\n'
'See codex_pcb/DEPLOY.md. No application binary is bundled.\n'
)
# Write next to the destination, so the final replacement is atomic.
with tempfile.NamedTemporaryFile(dir=output.parent, suffix='.tar.gz', delete=False) as stream:
pending = Path(stream.name)
try:
with tarfile.open(pending, 'w:gz') as archive:
archive.add(bundle, arcname=bundle.name)
pending.replace(output)
finally:
pending.unlink(missing_ok=True)
return output
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output', type=Path, default=ROOT / 'dist/vibemake-pcb-backend.tar.gz')
parser.add_argument('--with-freerouting', action='store_true', help='Include the verified JAR and license so the server need not download from GitHub')
args = parser.parse_args()
output = package(args.output, with_freerouting=args.with_freerouting)
print(f'Backend upload bundle: {output} ({output.stat().st_size:,} bytes)')
if __name__ == '__main__':
main()
+76
View File
@@ -0,0 +1,76 @@
// Package only the built PCB application; never include server configuration or secrets.
import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { execFileSync } from 'node:child_process';
const ROOT = resolve(fileURLToPath(new URL('..', import.meta.url)));
export function packagePcb({ source = join(ROOT, 'designer/dist'), output = join(ROOT, 'dist') } = {}) {
source = resolve(source);
output = resolve(output);
if (!existsSync(join(source, 'index.html'))) throw new Error('PCB build missing: run ./build.sh first.');
const config = JSON.parse(readFileSync(join(source, 'pcb-service-config.json'), 'utf8'));
if (config.base !== '/pcb/') throw new Error('The independent PCB package requires the /pcb/ build base.');
mkdirSync(output, { recursive: true });
const stage = mkdtempSync(join(output, '.pcb-package-'));
const directory = join(output, 'vibemake-pcb');
const archive = join(output, 'vibemake-pcb.zip');
const buildId = Date.now().toString(36);
try {
const pcb = join(stage, 'contents');
cpSync(source, pcb, {
recursive: true,
filter: file => !/(?:^|\/)(?:\.DS_Store|Thumbs\.db|\.env(?:\.[^/]*)?|node_modules)(?:\/|$)/.test(file),
});
writeFileSync(join(pcb, 'build-info.json'), JSON.stringify({
scope: 'pcb', buildId, builtAt: new Date().toISOString(), base: '/pcb/', archive: 'vibemake-pcb.zip',
}, null, 2) + '\n');
writeFileSync(join(pcb, 'DEPLOY.md'), `# PCB independent deployment
Extract vibemake-pcb.zip directly into <website-root>/pcb/. The ZIP root contains index.html, assets/ and the other PCB frontend files, with no enclosing pcb/ or vibemake-pcb/ directory.
mkdir -p /path/to/vibemake/pcb
unzip -o /path/to/vibemake-pcb.zip -d /path/to/vibemake/pcb
The result must be <website-root>/pcb/index.html, never pcb/pcb/index.html. Do not extract this package into the website root or copy the ZIP without extracting it.
This package updates only pcb/. Preserve the main site, cad/, js/cad/, existing server configuration and backend services. Never clear the website or PCB directory before extraction.
Check /pcb/build-info.json after deployment: scope=pcb, buildId=${buildId}.
Configure frontend routes to fall back to /pcb/index.html. Keep /pcb/pcb-api/ routed to the separately running AI PCB service before applying the frontend fallback; static hosting does not start that backend. Keep existing account /api/ proxy and CORS settings.
The browser uses same-origin /pcb/pcb-api/ requests. Choose an upstream reachable from OpenResty's own network namespace. The backend Compose publishes 8003 only on the server's 127.0.0.1; proxying to the public IP will not reach that loopback binding. For OpenResty using the same server's host network, add or update this location before the PCB frontend fallback:
location ^~ /pcb/pcb-api/ {
proxy_pass http://127.0.0.1:8003/api/;
proxy_http_version 1.1;
proxy_set_header Host $proxy_host;
proxy_set_header Origin http://127.0.0.1:5173;
proxy_buffering off;
proxy_read_timeout 3600s;
add_header Cache-Control "no-store" always;
}
For OpenResty in a bridge-network container, its 127.0.0.1 is OpenResty itself. Join both containers to the same Docker network and use proxy_pass http://pcb-backend:8003/api/; instead. Use a remote server address only when its backend deliberately listens on an address reachable by OpenResty. Do not expose port 8003 publicly just to bypass a network mismatch.
Verify /pcb/pcb-api/ready returns HTTP 200 with ok=true after deployment; checking or unavailable environments return HTTP 503. /pcb/pcb-api/health is only a liveness check. Deploy the backend with sh codex_pcb/deploy.sh, which waits for the real runtime healthcheck and fails on unavailable environments. The AI entry is enabled in this build and appears only after opening a project and loading its workbench.
If an API returns HTTP 502/503/504 with HTML, inspect the backend container and OpenResty error log. If it returns HTTP 200 with HTML, check the API location priority and frontend fallback. A healthy HTTP endpoint does not verify EDA execution permissions or Codex sandbox availability; run python -m codex_pcb.preflight inside the backend container before approving a real design.
This build also requires /pcb/pcb-api/readiness and /pcb/pcb-api/providers from the updated backend. Project entry checks readiness immediately, shows persistent failures and blocks generation/approval/resume until the native EDA bridge is verified. Backend admission checks also reject these actions when unavailable. Readiness opens only a blank diagnostic session, calls a read-only API and closes that session; it makes no model request or design. New designs can select OpenAI, DeepSeek or Doubao; OpenAI is the default. Configure each provider's key only in the backend environment, never in the frontend ZIP. Unconfigured providers remain disabled.
Serve index.html, sw.js, registerSW.js, build-info.json and the web manifest with Cache-Control: no-cache. Hashed assets can use immutable caching. Keep old hashed assets for already open editors.
`);
execFileSync('zip', ['-qr', join(stage, 'vibemake-pcb.zip'), '.'], { cwd: pcb });
execFileSync('unzip', ['-tq', join(stage, 'vibemake-pcb.zip')], { stdio: 'pipe' });
rmSync(directory, { recursive: true, force: true });
renameSync(pcb, directory);
renameSync(join(stage, 'vibemake-pcb.zip'), archive);
return { archive, directory, buildId };
} finally {
rmSync(stage, { recursive: true, force: true });
}
}
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const result = packagePcb();
console.log(`PCB directory: ${result.directory}`);
console.log(`PCB package ZIP: ${result.archive}`);
console.log('Extract the ZIP directly into <website-root>/pcb/; index.html is at the ZIP root.');
}
+55
View File
@@ -0,0 +1,55 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { execFileSync } from 'node:child_process';
import { dirname, join } from 'node:path';
import { tmpdir } from 'node:os';
import { packagePcb } from './package-pcb.mjs';
test('PCB releases extract directly into pcb/ and exclude local configuration', t => {
const root = mkdtempSync(join(tmpdir(), 'vibemake-pcb-package-'));
t.after(() => rmSync(root, { recursive: true, force: true }));
const put = (file, value) => {
mkdirSync(dirname(join(root, file)), { recursive: true });
writeFileSync(join(root, file), value);
};
put('source/index.html', '<script src="/pcb/assets/app.js"></script>');
put('source/assets/app.js', 'console.log("PCB");');
put('source/pcb-service-config.json', '{"base":"/pcb/"}');
put('source/.env.local', 'PRIVATE_BUILD_VALUE=example');
const output = join(root, 'output');
put('output/vibemake-pcb/pcb/stale.html', 'old nested package');
put('output/vibemake-pcb/stale.html', 'old package file');
const result = packagePcb({ source: join(root, 'source'), output });
const entries = execFileSync('unzip', ['-Z1', result.archive], { encoding: 'utf8' }).trim().split('\n');
assert.ok(entries.includes('index.html'));
assert.ok(entries.includes('assets/app.js'));
assert.ok(entries.includes('build-info.json'));
assert.ok(!entries.some(path => path.startsWith('pcb/') || path.startsWith('vibemake-pcb/')));
assert.ok(!entries.some(path => path.includes('.env')));
assert.ok(existsSync(join(result.directory, 'index.html')));
assert.ok(existsSync(join(result.directory, 'assets/app.js')));
assert.equal(existsSync(join(result.directory, 'pcb')), false);
assert.equal(existsSync(join(result.directory, 'stale.html')), false);
const website = join(root, 'website');
const protectedFiles = ['index.html', 'cad/index.html', 'js/cad/app.js', 'css/cad.css', 'pcb/assets/previous.js'];
for (const file of protectedFiles) put(`website/${file}`, `published:${file}`);
execFileSync('unzip', ['-oq', result.archive, '-d', join(website, 'pcb')]);
for (const file of protectedFiles) assert.equal(readFileSync(join(website, file), 'utf8'), `published:${file}`);
assert.equal(readFileSync(join(website, 'pcb/index.html'), 'utf8'), readFileSync(join(root, 'source/index.html'), 'utf8'));
assert.equal(existsSync(join(website, 'pcb/pcb')), false);
assert.equal(JSON.parse(readFileSync(join(website, 'pcb/build-info.json'))).scope, 'pcb');
assert.match(readFileSync(join(website, 'pcb/DEPLOY.md'), 'utf8'), /directly into <website-root>\/pcb\//);
const deployment = readFileSync(join(website, 'pcb/DEPLOY.md'), 'utf8');
assert.match(deployment, /proxy_pass http:\/\/127\.0\.0\.1:8003\/api\//);
assert.match(deployment, /proxy_pass http:\/\/pcb-backend:8003\/api\//);
assert.doesNotMatch(deployment, /proxy_pass http:\/\/39\.105\.93\.138/);
assert.match(deployment, /codex_pcb\.preflight/);
assert.match(deployment, /\/pcb\/pcb-api\/ready returns HTTP 200/);
assert.match(deployment, /codex_pcb\/deploy\.sh/);
const previous = readFileSync(result.archive);
put('source/pcb-service-config.json', '{"base":"/"}');
assert.throws(() => packagePcb({ source: join(root, 'source'), output }), /\/pcb\//);
assert.deepEqual(readFileSync(result.archive), previous);
assert.equal(existsSync(join(result.directory, '.env.local')), false);
});
+67
View File
@@ -0,0 +1,67 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import vm from 'node:vm';
const script = readFileSync(new URL('../designer/public/registerSW.js', import.meta.url), 'utf8');
async function page(pathname, { waiting = true, controlled = true } = {}) {
const messages = [];
const events = {};
const updates = {};
const states = {};
let reloads = 0;
const worker = { state: 'installing', addEventListener: (event, fn) => { states[event] = fn; } };
const next = { postMessage: (message) => messages.push(message.type) };
const registration = {
waiting: waiting ? next : null,
installing: worker,
addEventListener: (event, fn) => { updates[event] = fn; },
};
const location = { pathname, reload: () => { reloads++; } };
const serviceWorker = {
controller: controlled ? {} : null,
register: async () => registration,
addEventListener: (event, fn) => { events[event] = fn; },
};
vm.runInNewContext(script, {
URL, console,
document: { currentScript: { src: 'http://localhost:8091/pcb/registerSW.js' } },
window: { location, addEventListener: (event, fn) => { events[event] = fn; } },
navigator: { serviceWorker },
});
events.load();
await new Promise(setImmediate);
return { messages, events, updates, states, worker, registration, next, location, reloads: () => reloads };
}
test('project launcher activates a waiting build and reloads after takeover', async () => {
const p = await page('/pcb/');
assert.deepEqual(p.messages, ['SKIP_WAITING']);
p.events.controllerchange();
assert.equal(p.reloads(), 1);
});
test('an open project is never automatically activated or reloaded', async () => {
const p = await page('/pcb/p/example/pcb');
assert.deepEqual(p.messages, []);
p.events.controllerchange();
assert.equal(p.reloads(), 0);
});
test('an update finishing after entering a project waits for explicit approval', async () => {
const p = await page('/pcb/', { waiting: false });
p.updates.updatefound();
p.location.pathname = '/pcb/p/example/pcb';
p.registration.waiting = p.next;
p.worker.state = 'installed';
p.states.statechange();
assert.deepEqual(p.messages, []);
});
test('first installation does not reload the page', async () => {
const p = await page('/pcb/', { controlled: false });
assert.deepEqual(p.messages, []);
p.events.controllerchange();
assert.equal(p.reloads(), 0);
});
+27 -28
View File
@@ -1,6 +1,5 @@
/** Production static server + fixed-upstream task proxy. No provider credentials in the browser. */
import http from 'node:http';
import { createPreviewHandler } from './pcb-preview.mjs';
import https from 'node:https';
import { readFile, stat } from 'node:fs/promises';
import { createReadStream } from 'node:fs';
@@ -13,11 +12,16 @@ 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 previewPrefix = `${siteBase}pcb-preview/`;
const preview = createPreviewHandler();
const target = new URL(process.env.PCB_API_TARGET || 'http://127.0.0.1:8002');
const target = new URL(process.env.PCB_API_TARGET || 'http://39.105.93.138:8003');
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 platformTarget = new URL(process.env.API_TARGET || 'https://dev-vibemake-api.robotquan.com');
if (
!['http:', 'https:'].includes(platformTarget.protocol) ||
platformTarget.username ||
platformTarget.password
)
throw Error('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 = {
@@ -34,24 +38,8 @@ const mime = {
const handler = async (req, res) => {
try {
const url = new URL(req.url, 'http://localhost');
if (url.pathname.startsWith(previewPrefix)) {
if (req.headers.origin && req.headers.origin !== (process.env.PUBLIC_ORIGIN || `${process.env.TLS_CERT ? 'https' : 'http'}://${req.headers.host}`)) {
res.writeHead(403); res.end(); return;
}
await preview(req, res, url.pathname.slice(previewPrefix.length), url.searchParams);
return;
}
if (url.pathname.startsWith('/api/')) {
const upstream = https.request(new URL(url.pathname + url.search, process.env.API_TARGET || 'https://dev-vibemake-api.robotquan.com'),
{ method: req.method, headers: Object.fromEntries(Object.entries(req.headers).filter(([key]) => !['host', 'origin', 'referer'].includes(key))) },
reply => { res.writeHead(reply.statusCode || 502, { ...reply.headers, 'cache-control': 'no-store' }); pipeline(reply, res, () => {}); });
upstream.on('error', () => { if (!res.headersSent) res.writeHead(502); res.end('Platform API unavailable'); });
req.on('aborted', () => upstream.destroy());
res.on('close', () => upstream.destroy());
pipeline(req, upstream, () => {});
return;
}
if (url.pathname.startsWith(apiPrefix)) {
const pcbApi = url.pathname.startsWith(apiPrefix);
if (pcbApi || url.pathname === '/api' || url.pathname.startsWith('/api/')) {
const ownOrigin =
process.env.PUBLIC_ORIGIN ||
`${process.env.TLS_CERT && process.env.TLS_KEY ? 'https' : 'http'}://${req.headers.host}`;
@@ -63,13 +51,19 @@ const handler = async (req, res) => {
res.end(JSON.stringify({ message: '请求来源不匹配' }));
return;
}
const upstreamTarget = pcbApi ? target : platformTarget;
const headers = {
...req.headers,
host: target.host,
origin: process.env.PCB_API_ORIGIN || 'http://127.0.0.1:5173',
host: upstreamTarget.host,
};
const upstream = (target.protocol === 'https:' ? https : http).request(
new URL('/api/' + url.pathname.slice(apiPrefix.length) + url.search, target),
if (pcbApi) headers.origin = process.env.PCB_API_ORIGIN || 'http://127.0.0.1:5173';
else {
delete headers.origin;
delete headers.referer;
}
const upstreamPath = pcbApi ? '/api/' + url.pathname.slice(apiPrefix.length) : url.pathname;
const upstream = (upstreamTarget.protocol === 'https:' ? https : http).request(
new URL(upstreamPath + url.search, upstreamTarget),
{ method: req.method, headers },
(reply) => {
res.writeHead(reply.statusCode || 502, {
@@ -83,7 +77,11 @@ const handler = async (req, res) => {
upstream.on('error', () => {
if (!res.headersSent) res.writeHead(502, { 'content-type': 'application/json' });
res.end(
JSON.stringify({ message: '无法连接 PCB 后台,请检查 PCB_API_TARGET 和后台运行状态。' }),
JSON.stringify({
message: pcbApi
? '无法连接 PCB 后台,请检查 PCB_API_TARGET 和后台运行状态。'
: '无法连接平台后台,请检查 API_TARGET 和后台运行状态。',
}),
);
});
req.on('aborted', () => upstream.destroy());
@@ -151,7 +149,8 @@ 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(`PCB API: ${target.origin}`);
console.log(`Platform API: ${platformTarget.origin}`);
console.log(
'For a remote server, use SSH port forwarding and visit http://localhost:' + port + siteBase,
);
+22 -2
View File
@@ -1,4 +1,24 @@
#!/usr/bin/env bash
set -euo pipefail
systemctl --user start vibemake-pcb2-session.service vibemake-pcb2-web.service
systemctl --user --no-pager status vibemake-pcb2-session.service vibemake-pcb2-web.service
cd "$(dirname "$0")"
# Existing Linux deployments can explicitly start the persistent-session units.
if [ "${1:-}" = --services ]; then
systemctl --user start vibemake-pcb2-session.service vibemake-pcb2-web.service
exec systemctl --user --no-pager status vibemake-pcb2-session.service vibemake-pcb2-web.service
fi
# 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 ] || [ ! -f designer/dist/pcb-service-config.json ] || [ "${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