commit
CI / typecheck + test + build (push) Has been cancelled

This commit is contained in:
2026-11-16 17:50:15 +08:00
parent 4cba4bcd35
commit 7ddc3c22c5
27 changed files with 827 additions and 61 deletions
+10 -4
View File
@@ -122,7 +122,7 @@ Compose 的 `env_file` 会将 `.env.local` 注入后端。Dockerfile 的专用 i
```bash
cd /opt/vibemake-pcb-backend
docker compose -f codex_pcb/compose.yaml up -d --build
sh codex_pcb/deploy.sh
docker compose -f codex_pcb/compose.yaml logs --tail=100 -f pcb-backend
```
@@ -134,7 +134,7 @@ docker compose -f codex_pcb/compose.yaml logs --tail=100 -f pcb-backend
需要预先在「容器 → 镜像」构建时,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。它不会自动检查 Key 额度或模型权限,也不会自动完成客户端激活。
镜像使用 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 额度或模型权限,也不会自动完成客户端激活。
可用以下命令独立构建:
@@ -179,6 +179,8 @@ docker build -f codex_pcb/Dockerfile -t vibemake-pcb-backend:local \
```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
@@ -186,7 +188,11 @@ docker compose -f codex_pcb/compose.yaml exec pcb-backend /opt/lceda-pro/lceda-p
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` 的启动;结束后清理诊断文件,失败返回非零状态。比只执行 `/bin/true` 更能发现“终端能启动但工作区不能写入”的故障。`ok: true` 只代表这些前置条件通过,不代替 EDA 登录、正式绘板和交付验证。
`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`。
@@ -258,7 +264,7 @@ networks:
`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/` 和命名卷,然后重新执行 `up -d --build`。有已批准任务时先完成该任务再升级;旧任务的源码冻结校验不能通过修改哈希绕过。
更新代码后重新生成上传包,替换源码、文档及部署文件,保留服务器的 `.env.local`、`vendor/` 和命名卷,然后重新执行 `sh codex_pcb/deploy.sh`,以真实健康检查结果验收。有已批准任务时先完成该任务再升级;旧任务的源码冻结校验不能通过修改哈希绕过。
新增空卷时入口会将 `/data/resources` 链接到镜像中的 `/opt/pcb-resources`,文档随镜像升级;如果迁移现有运行目录,则保留原有 `resources/` 并检查其文档和路由器路径。独立更改 `PCB_CODEX_HOME` 或 EDA 工程数据位置时,也要额外挂载相应数据。
+2 -2
View File
@@ -89,7 +89,7 @@ ENV HOME=/data/home \
USER pcb
EXPOSE 8003
HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 \
CMD ["python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8003/api/health', timeout=4).read()"]
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"]
+46 -1
View File
@@ -8,6 +8,7 @@ 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, FREEROUTING_JAR, 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
@@ -15,6 +16,7 @@ from .rpc import AppServer, api_key
from .eda import execute
from .delivery import deliver
from .preflight import check_runtime
from .readiness import readiness
CACHE, JOBS, CLIENTS = {}, {}, {}
@@ -80,6 +82,14 @@ 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':
event(t,'request.unhandled',{'method':method})
@@ -247,6 +257,8 @@ async def work(t, prompt, production):
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)
@@ -303,6 +315,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'}):
@@ -313,6 +326,7 @@ 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)
@@ -327,7 +341,25 @@ class Approval(BaseModel):
@app.get('/api/health')
async def health():
runtime=runtime_for()
return {'ok':True,'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}
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}
@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():
@@ -345,6 +377,7 @@ async def create(req:DesignRequest):
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':runtime.model,'effort':runtime.effort,'provider':runtime.provider,'ai_provider':runtime.id,'runtime':runtime.snapshot(),'busy':False}
directory=workspace(t);directory.mkdir(parents=True)
@@ -371,6 +404,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)
@@ -385,6 +422,10 @@ 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(task_runtime(t))
event(t,'proposal.approved',t['approval'])
@@ -423,6 +464,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 @@
#!/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.'
+27 -12
View File
@@ -5,36 +5,51 @@ import fcntl
import json
import os
import time
import tempfile
from pathlib import Path
from .config import EDA_BIN
from .storage import ROOT, workspace, task_dir, inside, save, write, event, digest
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=os.environ.get('XDG_RUNTIME_DIR') or 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(EDA_BIN, *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+')
@@ -44,7 +59,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)
+5 -3
View File
@@ -80,8 +80,10 @@ def main(argv=None):
java = shutil.which('java')
if not java:
raise ValueError('Java is not installed or not on PATH')
xvfb = shutil.which('xvfb-run')
if not args.visible and (not xvfb or not shutil.which('Xvfb') or not shutil.which('xauth')):
# macOS supplies a native desktop; Xvfb is only needed on Linux hosts.
virtual_display = not args.visible and sys.platform != 'darwin'
xvfb = shutil.which('xvfb-run') if virtual_display else None
if virtual_display and (not xvfb or not shutil.which('Xvfb') or not shutil.which('xauth')):
raise ValueError('Install xvfb and xauth for unattended routing; --visible is diagnostic only')
target.parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix='.freerouting-', dir=target.parent) as temporary:
@@ -95,7 +97,7 @@ def main(argv=None):
pending = temporary / 'result.ses'
command = [java, f'-Duser.home={home}', f'-Djava.io.tmpdir={temporary}', '-jar', str(jar),
'-de', str(isolated_source), '-do', str(pending), *options, '-dct', '0', '-da']
if not args.visible:
if virtual_display:
command = [xvfb, '-a', '-f', str(temporary / 'Xauthority'), '-s', '-screen 0 1280x1024x24 -nolisten tcp', *command]
env = dict(os.environ, TMPDIR=str(temporary))
print(f'Freerouting: {source} -> {target}; confirmation disabled; timeout={args.timeout:g}s', flush=True)
+3 -1
View File
@@ -8,11 +8,13 @@ PRODUCTION PHASE: the server's approval message authorizes the accepted proposal
EDA access: call pcb_eda with a JavaScript async function body. The server creates a dedicated headless native EDA session for this task and executes your script there with the normal global `eda`. There are no design-specific restrictions on APIs. You can search libraries, create schematic/PCB, draw/connect, place and route, export native documents, inspect DRC and save. The tool records full commands and results. A timeout means the mutation outcome is UNKNOWN: inspect the live state before deciding what to do. Do not touch other EDA sessions.
The server owns the native EDA process, writable client HOME, display and session lifecycle. Do not launch another EasyEDA client from the native Shell as a fallback: that Shell can write only this task workspace, not the shared client HOME/logs. Use pcb_eda for all EDA operations. A confirmed BRIDGE_NOT_READY/command-space-missing is a runtime integration blocker, not a circuit-design error; preserve its exact evidence and report it rather than repeatedly opening clients or changing service configuration.
The helper `await pcb_export(file, 'relative/name.ext')` inside pcb_eda stores a native File/Blob in workspace/artifacts and returns its filename and bytes. It is a transport convenience, not a fake exporter. `pcb_eda` also accepts code_file to execute a JS file you wrote under the workspace. Long raw results are saved to workspace/evidence for you to read with shell tools. Read API signatures from the supplied api-reference directory before guessing; use the class index and individual class docs. EDA native coordinate units are documented in the API. Always distinguish schematic page IDs, board IDs and editor TAB IDs. Focus the requested editor before global sch_/pcb_ calls, and read back. Schematic getAll('part') excludes drawing frames. Consult the native DRC documentation for exact return types and error groups.
External utilities: Java/Freerouting and Blender are installed. You may export DSN and import SES, use native routing APIs, or implement your own routing scripts. Decide from evidence; no website algorithm dictates routing. If external router output is partial, retain the best actual result and fix remaining connections. Use genuine exported OBJ/STEP geometry for renders. Never draw a substitute board picture or invent 3D components. STEP exports may be ZIP-wrapped: inspect, extract and independently validate them. Do not treat a successful export or empty DRC array as proof of electrical correctness.
Freerouting deployment contract: use the Python freerouting.py launcher supplied in the production message for all external Freerouting runs. Its --help is handled locally and does not launch Java. The installed 1.9.0 JAR understands -help, NOT --help: the latter opens an idle file-selection window. Never invoke the JAR without an existing DSN input and a new SES output, and do not use raw java -jar probes. The launcher always supplies -dct 0 (no 20-second confirmation) and runs in private Xvfb; do not add -Djava.awt.headless=true because this GUI-based version throws HeadlessException. Keep logs in your workspace; after a timeout inspect evidence and choose a recovery rather than blindly retrying. Use a new output filename for each attempt. The launcher only controls process startup, not engineering decisions. SES existence or router exit zero does not prove full connectivity or native DRC success.
Freerouting deployment contract: use the Python freerouting.py launcher supplied in the production message for all external Freerouting runs. Its --help is handled locally and does not launch Java. The installed 1.9.0 JAR understands -help, NOT --help: the latter opens an idle file-selection window. Never invoke the JAR without an existing DSN input and a new SES output, and do not use raw java -jar probes. The launcher always supplies -dct 0 (no 20-second confirmation) and uses private Xvfb on Linux or the native desktop on macOS; do not add -Djava.awt.headless=true because this GUI-based version throws HeadlessException. Keep logs in your workspace; after a timeout inspect evidence and choose a recovery rather than blindly retrying. Use a new output filename for each attempt. The launcher only controls process startup, not engineering decisions. SES existence or router exit zero does not prove full connectivity or native DRC success.
Engineering: verify regulator pinout, supply limits/decoupling, reset/boot behavior, programming access and connector pin labeling. Check exact chip/module manufacturer's reference circuitry. Antenna keepout, plug access and component envelopes must be respected. Layout and routing must correspond to the actual schematic pin/net mapping. Never remove required nets/components, mask checks, disable DRC categories or weaken rules to obtain a pass. Use sensible manufacturing clearances and trace widths and leave unconnected pins intentionally marked, not accidentally unrouted. Save and reopen/check the native design when practical. Inspect schematic, top layout and genuine 3D views yourself before submission.
+63 -6
View File
@@ -1,6 +1,7 @@
"""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
@@ -9,6 +10,7 @@ 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):
@@ -42,7 +44,8 @@ def executable(name, binary):
def readable(name, path):
try:
return result(name, path.is_file() and os.access(path, os.R_OK), str(path))
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}')
@@ -106,6 +109,47 @@ async def eda_check(directory, env):
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 (
@@ -119,17 +163,25 @@ async def check_runtime(directory):
('freerouting', FREEROUTING_JAR)):
checks.append(readable(name, path))
env = safe_environment()
env.update(TMPDIR=str(directory / 'tmp'), TMP=str(directory / 'tmp'), TEMP=str(directory / 'tmp'))
# 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, env))
checks.append(await sandbox_check(directory, sandbox_env))
if programs['eda_binary']['ok']:
checks.append(await eda_check(directory, env))
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': 'permissions and CLI startup only; no model call or design created'}
'scope': 'filesystem, native sandbox, EDA startup and read-only bridge; no model call or design created'}
async def main():
async def check_environment():
try:
# Keep probes separate from saved tasks, and remove all diagnostic files.
parent = ROOT / 'tasks'
@@ -139,6 +191,11 @@ async def main():
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
+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()
+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()
+22 -3
View File
@@ -32,9 +32,28 @@ if not os.environ.get('NO_OUTPUT'):
java.chmod(0o755)
self.env = dict(os.environ, PATH=str(self.root), CALL_LOG=str(self.root / 'calls.json'))
def run_cli(self, *extra, help_only=False):
args = [] if help_only else ['--input', str(self.source), '--output', str(self.output), '--jar', str(self.jar), '--visible']
return subprocess.run([sys.executable, str(LAUNCHER), *args, *extra], env=self.env, capture_output=True, text=True, timeout=10)
def run_cli(self, *extra, help_only=False, visible=True, platform=None):
args = [] if help_only else ['--input', str(self.source), '--output', str(self.output), '--jar', str(self.jar)]
if not help_only and visible:
args.append('--visible')
command = [sys.executable, str(LAUNCHER)]
if platform is not None:
command = [sys.executable, '-c',
'import runpy,sys; sys.platform=sys.argv.pop(1); '
'sys.argv=sys.argv[1:]; runpy.run_path(sys.argv[0],run_name="__main__")',
platform, str(LAUNCHER)]
return subprocess.run([*command, *args, *extra], env=self.env, capture_output=True, text=True, timeout=10)
def test_macos_uses_native_desktop_without_xvfb(self):
r = self.run_cli(visible=False, platform='darwin')
self.assertEqual(r.returncode, 0, r.stderr)
self.assertTrue(self.output.is_file())
def test_linux_requires_xvfb_before_starting_java(self):
r = self.run_cli(visible=False, platform='linux')
self.assertEqual(r.returncode, 2, r.stderr)
self.assertIn('Install xvfb and xauth', r.stderr)
self.assertFalse((self.root / 'calls.json').exists())
def test_help_never_starts_java(self):
r = self.run_cli('--help', help_only=True)
+2 -1
View File
@@ -5,7 +5,7 @@ import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
from unittest.mock import AsyncMock, patch
app = importlib.import_module('codex_pcb.app')
@@ -43,6 +43,7 @@ class ModelProgress(unittest.IsolatedAsyncioTestCase):
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))),
+53 -3
View File
@@ -53,13 +53,33 @@ if os.environ.get('FAIL_SANDBOX'):
if not os.environ.get('NO_SANDBOX_WRITE'):
Path(sys.argv[-1]).write_text('pcb-preflight')
''')
self.program('eda', '''import os,sys
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 sys.argv[1:] == ['--help','--no-sandbox']
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)
print('EasyEDA CLI help')
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')
@@ -74,6 +94,9 @@ print('EasyEDA CLI help')
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))
@@ -87,6 +110,17 @@ print('EasyEDA CLI help')
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_nonexecutable_eda_is_detected_without_launch(self):
(self.bin / 'eda').chmod(0o644)
report = await preflight.check_runtime(self.workspace)
@@ -95,6 +129,22 @@ print('EasyEDA CLI help')
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)
+49 -1
View File
@@ -5,7 +5,7 @@ import os
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
from unittest.mock import AsyncMock, patch
import httpx
from codex_pcb import config, rpc, storage
@@ -29,6 +29,8 @@ class ProviderSelection(unittest.IsolatedAsyncioTestCase):
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):
@@ -36,6 +38,7 @@ class ProviderSelection(unittest.IsolatedAsyncioTestCase):
importlib.reload(module)
def restore(self):
self.readiness_guard.stop()
self.scheduler.stop()
self.environment.stop()
self.reload()
@@ -81,6 +84,51 @@ class ProviderSelection(unittest.IsolatedAsyncioTestCase):
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']
+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()
+5 -2
View File
@@ -165,8 +165,11 @@ class RuntimeConfig(unittest.IsolatedAsyncioTestCase):
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=(b'{"ok":true,"value":{"alive":true}}', b''))
with patch.object(asyncio, 'create_subprocess_exec', new=AsyncMock(return_value=process)) as spawn:
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'))
+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);
});
+38 -6
View File
@@ -6,6 +6,7 @@ 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 }; };
@@ -39,15 +40,46 @@ function ConnectedCodexPcbDock(): JSX.Element {
const [comment, setComment] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
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 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, config] = await Promise.all([api<Session[]>('/sessions'), api<ProviderConfig>('/providers')]); if (cancelled) return; setSessions(list); setProviders(config.providers); setSelectedProvider(current => current || config.default_provider);
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;
@@ -74,17 +106,17 @@ function ConnectedCodexPcbDock(): JSX.Element {
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={() => setOpen(true)}>✦ Codex AI 自动绘板</button> : <section className="cp-window" aria-label="Codex PCB 工作台">
{!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">{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 || !provider?.configured || request.trim().length < 5} onClick={create}>{busy ? '正在提交…' : '生成设计方案 →'}</button><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} onClick={resume}>继续此设计</button>}</div>
<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 || comment.trim().length < 5} onClick={send}>提交意见,修改方案</button><button className="cp-primary" disabled={busy || task.state !== 'review' || !!comment.trim()} onClick={approve}>同意此方案,开始运行</button></div>{comment.trim() && <small>请先提交修改意见,待新方案生成后再确认。</small>}</div>}</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>}
</>}
@@ -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>;
}
+3
View File
@@ -9,3 +9,6 @@
.cp-model-actions{display:flex;gap:8px;flex-wrap:wrap;justify-content:flex-end}.cp-model-source{display:block;font-size:12px;margin-top:4px;color:var(--cp-muted)}@media(max-width:850px){.cp-model-header{flex-wrap:wrap}.cp-model-actions{justify-content:flex-start}}
.cp-provider{display:grid;gap:7px;margin:22px 0}.cp-provider label{font-weight:600}.cp-provider select{font:inherit;min-height:44px;width:100%;max-width:540px;padding:9px 12px;border:1px solid #3a4e65;border-radius:9px;background:#0c1520;color:#f1f5f9}.cp-provider select:focus-visible{outline:2px solid var(--cp-blue);outline-offset:2px}.cp-provider select:disabled{opacity:.6}.cp-provider small,.cp-task-model{color:var(--cp-muted);font-size:12px}.cp-task-model{margin:12px 0 0}
.cp-root{--cp-bg:#101a27;--cp-panel:#142233;--cp-text:#e6edf5}
.cp-environment{border:1px solid var(--cp-border);border-left:3px solid var(--cp-blue);border-radius:10px;padding:16px;margin-bottom:20px;background:var(--cp-panel);font-size:13px;line-height:1.6;overflow-wrap:anywhere}.cp-environment>strong{font-size:15px}.cp-environment p{margin:6px 0 10px}.cp-environment ul{padding-left:20px;margin:12px 0;max-height:32vh;overflow:auto}.cp-environment li+li{margin-top:12px}.cp-environment li p{color:var(--cp-muted);white-space:pre-wrap}.cp-environment-actions{display:flex;gap:8px;flex-wrap:wrap}.cp-environment button{min-height:40px;font:inherit;padding:7px 12px;border:1px solid var(--cp-border);border-radius:7px;background:var(--cp-bg);color:var(--cp-text);cursor:pointer}.cp-environment button:focus-visible{outline:2px solid var(--cp-blue);outline-offset:2px}.cp-environment button:disabled{opacity:.6;cursor:wait}.cp-environment-notice{position:fixed;right:28px;bottom:88px;width:min(380px,calc(100vw - 32px));z-index:2147482999}.cp-environment-notice .cp-environment{margin:0;box-shadow:0 12px 36px #0004}@media(max-width:550px){.cp-environment-notice{right:16px;bottom:82px}.cp-environment{padding:12px}}
+62 -13
View File
@@ -7,6 +7,16 @@ 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();
@@ -15,16 +25,15 @@ afterEach(() => {
vi.unstubAllGlobals();
});
it('keeps the new workspace closed and does not call the backend until opened', async () => {
const fetch = vi.fn(async (_url: string) => new Response('[]'));
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).not.toHaveBeenCalled();
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).toHaveBeenCalledTimes(1));
expect(fetch.mock.calls[0]?.[0]).toBe('/pcb-api/sessions');
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();
});
@@ -56,20 +65,19 @@ it('uses the new session protocol without replaying the legacy task outbox', asy
};
const fetch = vi.fn(
async (url: string, init?: RequestInit) =>
new Response(
JSON.stringify(init?.method === 'POST' || url.endsWith('/sessions/pcb-new') ? task : []),
),
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: '测试电源板设计' });
expect(JSON.parse(String(init?.body))).toEqual({ text: '测试电源板设计', provider: 'openai' });
expect(
fetch.mock.calls.every(([url]) => !url.includes('/v1/') && !url.includes('/commands')),
).toBe(true);
@@ -95,14 +103,12 @@ it('keeps approval disabled while an unsubmitted proposal comment exists', async
};
const fetch = vi.fn(
async (url: string) =>
new Response(
JSON.stringify(url.endsWith('/sessions') ? [task] : url.includes('/events?') ? [] : task),
),
response(url, url.endsWith('/sessions') ? [task] : url.includes('/events?') ? [] : task),
);
vi.stubGlobal('fetch', fetch);
render(<CodexPcbDock />);
const approve = await screen.findByRole('button', { name: '同意此方案,开始运行' });
expect((approve as HTMLButtonElement).disabled).toBe(false);
await waitFor(() => expect((approve as HTMLButtonElement).disabled).toBe(false));
fireEvent.change(screen.getByLabelText('对方案有修改意见?'), {
target: { value: '请增加一个状态灯' },
});
@@ -110,3 +116,46 @@ it('keeps approval disabled while an unsubmitted proposal comment exists', async
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,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();
});
+1 -1
View File
@@ -14,7 +14,7 @@ import urllib.request
ROOT = Path(__file__).resolve().parents[1]
DEPLOY_FILES = (
'.env.example', 'Dockerfile', 'Dockerfile.dockerignore', 'compose.yaml',
'docker-entrypoint.sh', 'requirements.txt', 'instructions.md',
'docker-entrypoint.sh', 'deploy.sh', 'requirements.txt', 'instructions.md',
'DEPLOY.md', 'THIRD-PARTY.md',
'build-assets/README.md',
)
+2 -2
View File
@@ -52,9 +52,9 @@ The browser uses same-origin /pcb/pcb-api/ requests. Choose an upstream reachabl
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/health returns JSON with ok=true after deployment. The AI entry is enabled in this build and appears only after opening a project and loading its workbench.
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/providers from the updated backend. 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.
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 });
+2
View File
@@ -45,6 +45,8 @@ test('PCB releases extract directly into pcb/ and exclude local configuration',
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\//);
+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);
});