diff --git a/codex_pcb/DEPLOY.md b/codex_pcb/DEPLOY.md index 9b6f85e..58c3771 100644 --- a/codex_pcb/DEPLOY.md +++ b/codex_pcb/DEPLOY.md @@ -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 工程数据位置时,也要额外挂载相应数据。 diff --git a/codex_pcb/Dockerfile b/codex_pcb/Dockerfile index e18ea96..d69f374 100644 --- a/codex_pcb/Dockerfile +++ b/codex_pcb/Dockerfile @@ -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"] diff --git a/codex_pcb/app.py b/codex_pcb/app.py index 5e1d6ca..7864c29 100644 --- a/codex_pcb/app.py +++ b/codex_pcb/app.py @@ -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'))) diff --git a/codex_pcb/deploy.sh b/codex_pcb/deploy.sh new file mode 100644 index 0000000..957a44b --- /dev/null +++ b/codex_pcb/deploy.sh @@ -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.' diff --git a/codex_pcb/eda.py b/codex_pcb/eda.py index 983ec85..647b363 100644 --- a/codex_pcb/eda.py +++ b/codex_pcb/eda.py @@ -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) diff --git a/codex_pcb/freerouting.py b/codex_pcb/freerouting.py index 861d2ed..c0e9df5 100644 --- a/codex_pcb/freerouting.py +++ b/codex_pcb/freerouting.py @@ -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) diff --git a/codex_pcb/instructions.md b/codex_pcb/instructions.md index 1eeff2c..8ba9e68 100644 --- a/codex_pcb/instructions.md +++ b/codex_pcb/instructions.md @@ -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. diff --git a/codex_pcb/preflight.py b/codex_pcb/preflight.py index 44354da..5dbaeb9 100644 --- a/codex_pcb/preflight.py +++ b/codex_pcb/preflight.py @@ -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 diff --git a/codex_pcb/readiness.py b/codex_pcb/readiness.py new file mode 100644 index 0000000..fb9ceeb --- /dev/null +++ b/codex_pcb/readiness.py @@ -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() diff --git a/codex_pcb/tests/test_deployment.py b/codex_pcb/tests/test_deployment.py new file mode 100644 index 0000000..9ccfa94 --- /dev/null +++ b/codex_pcb/tests/test_deployment.py @@ -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() diff --git a/codex_pcb/tests/test_eda_transport.py b/codex_pcb/tests/test_eda_transport.py new file mode 100644 index 0000000..aafcae8 --- /dev/null +++ b/codex_pcb/tests/test_eda_transport.py @@ -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() diff --git a/codex_pcb/tests/test_freerouting.py b/codex_pcb/tests/test_freerouting.py index 1bfba6e..f38616c 100644 --- a/codex_pcb/tests/test_freerouting.py +++ b/codex_pcb/tests/test_freerouting.py @@ -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) diff --git a/codex_pcb/tests/test_model_progress.py b/codex_pcb/tests/test_model_progress.py index f3c4db5..c898b8e 100644 --- a/codex_pcb/tests/test_model_progress.py +++ b/codex_pcb/tests/test_model_progress.py @@ -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))), diff --git a/codex_pcb/tests/test_preflight.py b/codex_pcb/tests/test_preflight.py index ac91e26..675d6ea 100644 --- a/codex_pcb/tests/test_preflight.py +++ b/codex_pcb/tests/test_preflight.py @@ -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) diff --git a/codex_pcb/tests/test_provider_selection.py b/codex_pcb/tests/test_provider_selection.py index 2248c4c..ade08d9 100644 --- a/codex_pcb/tests/test_provider_selection.py +++ b/codex_pcb/tests/test_provider_selection.py @@ -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'] diff --git a/codex_pcb/tests/test_readiness.py b/codex_pcb/tests/test_readiness.py new file mode 100644 index 0000000..d4ed598 --- /dev/null +++ b/codex_pcb/tests/test_readiness.py @@ -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() diff --git a/codex_pcb/tests/test_runtime_config.py b/codex_pcb/tests/test_runtime_config.py index 6c64af7..f018c5f 100644 --- a/codex_pcb/tests/test_runtime_config.py +++ b/codex_pcb/tests/test_runtime_config.py @@ -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')) diff --git a/designer/public/registerSW.js b/designer/public/registerSW.js index c31b341..79b2b6d 100644 --- a/designer/public/registerSW.js +++ b/designer/public/registerSW.js @@ -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); }); diff --git a/designer/src/codex-pcb/CodexPcbDock.tsx b/designer/src/codex-pcb/CodexPcbDock.tsx index e3c0a05..2eb2427 100644 --- a/designer/src/codex-pcb/CodexPcbDock.tsx +++ b/designer/src/codex-pcb/CodexPcbDock.tsx @@ -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(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(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(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('/sessions'), api('/providers')]); if (cancelled) return; setSessions(list); setProviders(config.providers); setSelectedProvider(current => current || config.default_provider); + const [list, config] = await Promise.all([api('/sessions'), api('/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(`/sessions/${active}`), api(`/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 =
- {!open ? :
+ {!open ? <>
setOpen(true)}/>
:
Codex PCB 工作台从方案到真实电路板
{active && task && } -
{error &&
{error}
} - {!active ?
让需求成为电路板

你想设计什么?

描述用途、供电、接口和尺寸要求。AI 会先提出方案,由你审核后再开始绘制。

{provider && !provider.configured ? `${provider.label} 尚未配置服务端凭据,请先配置后端或选择其他服务。` : '所选服务及模型在本次设计中保持固定;新建设计时可以切换。'}