Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e26f160a35 | |||
| 06b25be1e4 |
+5
-2
@@ -1,7 +1,10 @@
|
||||
# Copy to .env.local. Real provider keys NEVER belong in VITE_* or Git.
|
||||
# Persistent Codex PCB session backend. Override when using a remote installation.
|
||||
PCB_API_TARGET=http://39.105.93.138:8003
|
||||
# Persistent Codex PCB session backend. Use a trusted HTTPS endpoint for a remote installation; session requests carry the signed-in user’s bearer token.
|
||||
PCB_API_TARGET=http://127.0.0.1:8003
|
||||
PCB_API_ORIGIN=http://127.0.0.1:5173
|
||||
# For LAN HTTPS sites whose Origin is not allowed by the platform storage bucket:
|
||||
# PCB_OBJECT_RELAY=1
|
||||
# PCB_OBJECT_ORIGINS=https://linkerbot.oss-cn-beijing.aliyuncs.com
|
||||
# Open-source project library, independent of PCB design jobs:
|
||||
PCB_LIBRARY_TARGET=http://127.0.0.1:8004
|
||||
# Account and platform project API, independent of the AI task service:
|
||||
|
||||
+1
-1
@@ -75,7 +75,7 @@ journalctl --user -u vibemake-pcb2-session.service -f
|
||||
curl http://127.0.0.1:8003/api/health
|
||||
```
|
||||
|
||||
The root `start.sh --services` starts the new systemd services on a configured Linux server. Without this flag, `start.sh` builds/serves the frontend and proxies its API to the separately running backend (default `http://39.105.93.138:8003`, overridable with `PCB_API_TARGET`). All requests are asynchronous and the UI polls task state/events. The Linux service template binds loopback; the web proxy retains its same-origin write checks.
|
||||
The root `start.sh --services` starts the new systemd services on a configured Linux server. Without this flag, `start.sh` builds/serves the frontend and proxies its API to the separately running backend (default `http://127.0.0.1:8003`, overridable with `PCB_API_TARGET`). All requests are asynchronous and the UI polls task state/events. The Linux service template binds loopback; the web proxy retains its same-origin write checks.
|
||||
|
||||
## Acceptance protocol
|
||||
|
||||
|
||||
+2
-2
@@ -10,13 +10,13 @@
|
||||
|
||||
```bash
|
||||
cp .env.pcb.example .env.local
|
||||
# 按实际部署修改 PCB_API_TARGET,默认 http://39.105.93.138:8003
|
||||
# 按实际部署修改 PCB_API_TARGET,默认 http://127.0.0.1:8003
|
||||
./start.sh
|
||||
```
|
||||
|
||||
普通 `./start.sh` 保留跨平台前端构建和静态服务器启动方式,默认访问 `http://localhost:5180/pcb/`。它不启动 AI 后台;后台缺失时仍可使用项目列表和原编辑器。开发时可运行 `pnpm -C designer dev`,默认端口 5173;代理配置通过启动进程的环境变量传入。`REBUILD=1 ./start.sh` 强制构建。
|
||||
|
||||
AI 请求使用同源 `/pcb/pcb-api/sessions` 等路径,代理转发为后台 `/api/sessions`,默认目标为 `http://39.105.93.138:8003`。旧后台 `/api/v1/tasks` 与新协议不同,不应把新入口指向旧 8000/8002 服务。修改目标时同时核对 Vite、静态服务器和反向代理配置。
|
||||
AI 请求使用同源 `/pcb/pcb-api/sessions` 等路径,代理转发为后台 `/api/sessions`,默认目标为 `http://127.0.0.1:8003`。旧后台 `/api/v1/tasks` 与新协议不同,不应把新入口指向旧 8000/8002 服务。代理会携带当前用户的登录凭据。跨主机部署时,请将 PCB_API_TARGET 配为受信任的 HTTPS 服务地址,并让绘板后台和网页代理使用同一个账号平台 API_TARGET。
|
||||
|
||||
账号与平台工程接口 `/api/` 独立转发至 `API_TARGET`,默认开发平台 API;保留 Authorization,移除 Origin/Referer。统一登录、项目封面、工程保存和重新打开继续使用平台流程,不与 AI 会话记录混为同一数据集。
|
||||
|
||||
|
||||
@@ -300,3 +300,15 @@ PCB_CLAUDE_MODEL=Claude Fable 5.2
|
||||
讨论/修订、明确批准、旧版本不能恢复生产及已交付只读问答规则同样适用。询问工具结果并不等于获得批准。问答使用独立 session,只开放交付文本读取。
|
||||
|
||||
连接超时 15 秒,读取无新数据超时 1800 秒,单响应最多 2 MB;每轮至多 200 步,连续三次无效协议报错并保留会话。网络失败不自动重放工具。工具执行前记录 uncertain_call,执行后保存结果;恢复时把不确定操作及最近结果交给模型,要求先核实,避免重复创建对象。取消会终止本地等待和后续工具操作;中转上游未提供取消接口,远端文字生成可能继续。远端 session 的保存期限与上下文容量仍取决于中转服务,后端不能保证其无限记忆。完整 PCB 产出质量需要独立绘板测试,不以一次连通性测试替代。
|
||||
|
||||
## AI 绘板工程归属与在线编辑
|
||||
|
||||
将 AI 服务的 `API_TARGET` 配置为网站登录和 PCB 工作空间使用的同一个平台 API 源站(仅源站,例如 `https://dev-vibemake-api.robotquan.com`)。服务向该平台的 `/api/users/me` 验证 Bearer 凭据,用平台源站和 userCode 确定归属。持久卷中 `editing-projects.sqlite3` 保存任务归属及编辑副本的云工程编号,应与 `tasks/` 一同备份和恢复。记录不含登录令牌。
|
||||
|
||||
历史任务没有可信用户标识。管理员先核实历史任务和平台 userCode,再在 AI 服务的工作目录使用相同的 `PCB_SESSION_ROOT`、`API_TARGET` 和 Python 环境执行下列命令。重复绑定到同一账号安全;已有其他归属时命令会中止。此操作即时生效,原交付包和任务状态文件保持原样。
|
||||
|
||||
```sh
|
||||
python -m codex_pcb.editing_projects bind <任务ID> <已核实的平台userCode>
|
||||
```
|
||||
|
||||
首次在网页打开编辑副本时,服务使用当前用户凭据创建云工程。若云平台创建请求超时,请刷新后再次打开。服务将在该用户的项目列表中按精确关联标记找回项目。若平台始终没有返回创建结果,管理员应核对平台请求记录,确认原创建请求已经结束且没有创建工程后,执行 `python -m codex_pcb.editing_projects allow-create-after-confirmed-absent <任务ID> <userCode>` 释放该申请。用户再次打开即可重试。
|
||||
|
||||
+33
-20
@@ -9,7 +9,7 @@ import time
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
from fastapi import FastAPI, HTTPException, Request as HttpRequest, Response
|
||||
from fastapi import APIRouter, Depends, FastAPI, HTTPException, Request as HttpRequest, Response
|
||||
from fastapi.responses import FileResponse
|
||||
from fastapi.responses import JSONResponse
|
||||
from pydantic import BaseModel, Field
|
||||
@@ -26,7 +26,7 @@ from .native_policy import DESIGN_POLICY, POLICY_TEXT, WORKSPACE_RULES, refresh_
|
||||
from .preflight import check_runtime
|
||||
from .readiness import readiness
|
||||
from .preview import previews
|
||||
from . import aftercare
|
||||
from . import aftercare, editing_projects
|
||||
|
||||
CACHE, JOBS, CLIENTS = {}, {}, {}
|
||||
|
||||
@@ -56,8 +56,10 @@ def get(tid):
|
||||
except (ValueError,FileNotFoundError):
|
||||
raise HTTPException(404,'Task not found')
|
||||
|
||||
def public(t):
|
||||
return {k:v for k,v in t.items() if k not in {'pending_prompt','internal'}}
|
||||
def public(t, project_code=None):
|
||||
state = {k:v for k,v in t.items() if k not in {'pending_prompt','internal'}}
|
||||
state.update(editing_projects.editing_fields(t, project_code))
|
||||
return state
|
||||
|
||||
def frozen(t):
|
||||
if t.get('approval') and fingerprint(task_runtime(t))!=t['frozen_source']:
|
||||
@@ -403,6 +405,7 @@ async def lifespan(app):
|
||||
await previews.close()
|
||||
|
||||
app=FastAPI(lifespan=lifespan)
|
||||
task_api = APIRouter(prefix='/api/sessions/{tid}', dependencies=[Depends(editing_projects.require_owned)])
|
||||
|
||||
class Request(BaseModel):
|
||||
text:str=Field(min_length=5,max_length=16000)
|
||||
@@ -440,11 +443,13 @@ async def list_providers():
|
||||
return {'default_provider':DEFAULT_PROVIDER,'providers':[provider_status(runtime_for(name)) for name in PROVIDERS]}
|
||||
|
||||
@app.get('/api/sessions')
|
||||
async def list_sessions():
|
||||
return sorted([public(t) for t in CACHE.values()],key=lambda t:t['created_at'],reverse=True)
|
||||
async def list_sessions(account: editing_projects.Account = Depends(editing_projects.current_account)):
|
||||
links = editing_projects.owned(account.owner)
|
||||
return sorted([public(CACHE[tid], code) for tid, code in links.items() if tid in CACHE],
|
||||
key=lambda t:t['created_at'], reverse=True)
|
||||
|
||||
@app.post('/api/sessions',status_code=201)
|
||||
async def create(req:DesignRequest):
|
||||
async def create(req:DesignRequest, account: editing_projects.Account = Depends(editing_projects.current_account)):
|
||||
try:
|
||||
runtime=runtime_for(req.provider)
|
||||
except ValueError as e:
|
||||
@@ -459,16 +464,21 @@ async def create(req:DesignRequest):
|
||||
(directory/name).mkdir()
|
||||
(directory/'api-reference').symlink_to(ROOT/'resources',target_is_directory=True)
|
||||
(directory/'AGENTS.md').write_text(WORKSPACE_RULES)
|
||||
editing_projects.bind(tid, account.owner)
|
||||
CACHE[tid]=t;save(t)
|
||||
event(t,'message',{'role':'user','text':req.text})
|
||||
schedule(t,'User requirement:\n'+req.text+'\n\nFirst prepare a reviewable proposal and publish it with pcb_proposal. Do not produce the board yet.',False)
|
||||
return public(t)
|
||||
|
||||
@app.get('/api/sessions/{tid}')
|
||||
async def detail(tid:str):
|
||||
return public(get(tid))
|
||||
@task_api.get('')
|
||||
async def detail(tid:str, binding=Depends(editing_projects.require_owned)):
|
||||
return public(get(tid), binding['project_code'])
|
||||
|
||||
@app.get('/api/sessions/{tid}/preview')
|
||||
@task_api.post('/editing-project')
|
||||
async def open_editing_project(tid:str, account: editing_projects.Account = Depends(editing_projects.current_account)):
|
||||
return {'project_code': await editing_projects.editing_project(get(tid), account)}
|
||||
|
||||
@task_api.get('/preview')
|
||||
async def preview(tid:str, request:HttpRequest, kind:Literal['auto','schematic','layout','3d']='auto'):
|
||||
task=get(tid)
|
||||
snapshot=await previews.snapshot(task,kind)
|
||||
@@ -478,7 +488,7 @@ async def preview(tid:str, request:HttpRequest, kind:Literal['auto','schematic',
|
||||
return Response(status_code=304,headers=headers)
|
||||
return Response(snapshot.body,media_type='application/json',headers=headers)
|
||||
|
||||
@app.get('/api/sessions/{tid}/events')
|
||||
@task_api.get('/events')
|
||||
async def history(tid:str,after:int=0):
|
||||
get(tid)
|
||||
return events(tid,after)
|
||||
@@ -486,14 +496,14 @@ async def history(tid:str,after:int=0):
|
||||
class Question(BaseModel):
|
||||
text:str=Field(min_length=1,max_length=8000)
|
||||
|
||||
@app.get('/api/sessions/{tid}/questions')
|
||||
@task_api.get('/questions')
|
||||
async def question_history(tid:str):
|
||||
t=get(tid)
|
||||
if t['state']!='completed' or not t.get('delivery'):
|
||||
raise HTTPException(409,'交付完成后可询问板子的使用方法')
|
||||
return aftercare.public(aftercare.state(t))
|
||||
|
||||
@app.post('/api/sessions/{tid}/questions',status_code=202)
|
||||
@task_api.post('/questions',status_code=202)
|
||||
async def ask_question(tid:str,req:Question):
|
||||
t=get(tid)
|
||||
if t['state']!='completed' or not t.get('delivery'):
|
||||
@@ -510,7 +520,7 @@ async def ask_question(tid:str,req:Question):
|
||||
except (ValueError,RuntimeError) as exc:
|
||||
raise HTTPException(409,str(exc)) from None
|
||||
|
||||
@app.post('/api/sessions/{tid}/comments')
|
||||
@task_api.post('/comments')
|
||||
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'):
|
||||
@@ -529,7 +539,7 @@ class Feedback(BaseModel):
|
||||
revision:int
|
||||
hash:str
|
||||
|
||||
@app.post('/api/sessions/{tid}/feedback',status_code=202)
|
||||
@task_api.post('/feedback',status_code=202)
|
||||
async def feedback(tid:str,req:Feedback):
|
||||
t=get(tid)
|
||||
if not t.get('approval') or t.get('busy') or t['state'] not in {'blocked','failed','interrupted','cancelled','review','needs_input'}:
|
||||
@@ -571,7 +581,7 @@ Finish your reply and wait for the website action. No automatic production resum
|
||||
schedule(t,prompt,False)
|
||||
return public(t)
|
||||
|
||||
@app.post('/api/sessions/{tid}/approve')
|
||||
@task_api.post('/approve')
|
||||
async def approve(tid:str,req:Approval):
|
||||
t=get(tid)
|
||||
p=t.get('proposal',{})
|
||||
@@ -609,7 +619,7 @@ Accepted proposal:\n{p['markdown']}'''
|
||||
schedule(t,prompt,True)
|
||||
return public(t)
|
||||
|
||||
@app.post('/api/sessions/{tid}/cancel')
|
||||
@task_api.post('/cancel')
|
||||
async def cancel(tid:str):
|
||||
t=get(tid)
|
||||
if t['state']=='completed':
|
||||
@@ -624,7 +634,7 @@ async def cancel(tid:str):
|
||||
job.cancel()
|
||||
return public(t)
|
||||
|
||||
@app.post('/api/sessions/{tid}/resume')
|
||||
@task_api.post('/resume')
|
||||
async def resume(tid:str):
|
||||
t=get(tid)
|
||||
if t.get('busy') or t['state'] not in {'failed','blocked','interrupted','cancelled'}:
|
||||
@@ -646,7 +656,7 @@ async def resume(tid:str):
|
||||
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')))
|
||||
return public(t)
|
||||
|
||||
@app.get('/api/sessions/{tid}/files/{name}')
|
||||
@task_api.get('/files/{name}')
|
||||
async def download(tid:str,name:str):
|
||||
t=get(tid)
|
||||
item=next((f for f in t.get('delivery',{}).get('files',[]) if f['name']==name),None)
|
||||
@@ -656,3 +666,6 @@ async def download(tid:str,name:str):
|
||||
if digest(path.read_bytes())!=item['sha256']:
|
||||
raise HTTPException(409,'Artifact checksum mismatch')
|
||||
return FileResponse(path,filename=name,headers={'Cache-Control':'no-store','X-Content-Type-Options':'nosniff'})
|
||||
|
||||
|
||||
app.include_router(task_api)
|
||||
|
||||
@@ -0,0 +1,268 @@
|
||||
"""Authenticated task ownership and idempotent creation of cloud editing copies."""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import sqlite3
|
||||
import zipfile
|
||||
from contextlib import closing, contextmanager
|
||||
from dataclasses import dataclass, field
|
||||
from functools import lru_cache
|
||||
from urllib.parse import quote
|
||||
|
||||
import httpx
|
||||
from fastapi import Depends, HTTPException
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
|
||||
from . import storage
|
||||
|
||||
|
||||
def origin():
|
||||
return (os.environ.get('API_TARGET') or 'https://dev-vibemake-api.robotquan.com').rstrip('/')
|
||||
|
||||
|
||||
def owner_key(user_code):
|
||||
return hashlib.sha256((origin() + '\0' + user_code).encode()).hexdigest()
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Account:
|
||||
owner: str
|
||||
token: str = field(repr=False)
|
||||
|
||||
|
||||
async def platform(method, path, token, **kwargs):
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=12, follow_redirects=False) as client:
|
||||
response = await client.request(method, origin() + '/api' + path,
|
||||
headers={'Authorization': 'Bearer ' + token, 'Accept': 'application/json'}, **kwargs)
|
||||
if response.status_code in (401, 403):
|
||||
raise HTTPException(response.status_code, '登录已失效或没有权限,请重新登录。')
|
||||
if response.status_code == 429:
|
||||
raise HTTPException(429, '平台请求过于频繁,请稍后再试。')
|
||||
if response.status_code in (400, 404, 422):
|
||||
raise HTTPException(response.status_code, '平台未接受该工程请求。')
|
||||
response.raise_for_status()
|
||||
payload = response.json()
|
||||
except (httpx.HTTPError, ValueError) as exc:
|
||||
raise HTTPException(503, '暂时无法确认平台响应,请稍后重试。') from exc
|
||||
if not isinstance(payload, dict):
|
||||
raise HTTPException(502, '平台返回的数据无法识别。')
|
||||
if payload.get('code') == 'PCB_PROJECT_NOT_FOUND':
|
||||
raise HTTPException(404, '这个云工程已删除。')
|
||||
if payload.get('code') in ('UNAUTHORIZED', 'FORBIDDEN'):
|
||||
raise HTTPException(401, '登录已失效,请重新登录。')
|
||||
if payload.get('code') not in (None, 'OK') or 'data' not in payload:
|
||||
raise HTTPException(502, '平台未确认请求。')
|
||||
return payload['data']
|
||||
|
||||
|
||||
async def current_account(credentials: HTTPAuthorizationCredentials | None = Depends(HTTPBearer(auto_error=False))):
|
||||
if not credentials or credentials.scheme.lower() != 'bearer':
|
||||
raise HTTPException(401, '请先登录后再查看 AI 绘板工程。', headers={'WWW-Authenticate':'Bearer'})
|
||||
user = await platform('GET', '/users/me', credentials.credentials)
|
||||
if not isinstance(user, dict) or not isinstance(user.get('userCode'), str) or not user['userCode'].strip():
|
||||
raise HTTPException(502, '平台未返回有效的登录用户。')
|
||||
return Account(owner_key(user['userCode']), credentials.credentials)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def connection():
|
||||
# Kept outside every agent workspace and original delivery directory.
|
||||
folder = storage.TASKS.parent
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
with closing(sqlite3.connect(folder/'editing-projects.sqlite3', timeout=5)) as db, db:
|
||||
db.row_factory = sqlite3.Row
|
||||
db.execute('''CREATE TABLE IF NOT EXISTS projects(
|
||||
task_id TEXT PRIMARY KEY, owner TEXT NOT NULL, marker TEXT NOT NULL UNIQUE,
|
||||
attempted INTEGER NOT NULL DEFAULT 0, project_code TEXT UNIQUE)''')
|
||||
db.execute('CREATE INDEX IF NOT EXISTS task_owner ON projects(owner)')
|
||||
yield db
|
||||
|
||||
|
||||
def bind(tid, owner):
|
||||
storage.task_dir(tid) # validate the task identifier
|
||||
with connection() as db:
|
||||
db.execute('INSERT OR IGNORE INTO projects(task_id,owner,marker) VALUES(?,?,?)',
|
||||
(tid, owner, 'AI PCB · ' + secrets.token_hex(16)))
|
||||
row = db.execute('SELECT owner FROM projects WHERE task_id=?', (tid,)).fetchone()
|
||||
if not row or row['owner'] != owner:
|
||||
raise ValueError('任务已经绑定到其他账号,不能转移。')
|
||||
|
||||
|
||||
def owned(owner):
|
||||
with connection() as db:
|
||||
return {row['task_id']: row['project_code'] for row in db.execute(
|
||||
'SELECT task_id, project_code FROM projects WHERE owner=?', (owner,))}
|
||||
|
||||
|
||||
def record(tid, owner):
|
||||
with connection() as db:
|
||||
row = db.execute('SELECT * FROM projects WHERE task_id=? AND owner=?', (tid, owner)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, '找不到此 AI 绘板工程。')
|
||||
return row
|
||||
|
||||
|
||||
async def require_owned(tid: str, account: Account = Depends(current_account)):
|
||||
return record(tid, account.owner)
|
||||
|
||||
|
||||
def file_key(path):
|
||||
info = path.stat()
|
||||
return path, info.st_mtime_ns, info.st_size
|
||||
|
||||
|
||||
@lru_cache(maxsize=256)
|
||||
def source_info(path, mtime, size):
|
||||
try:
|
||||
with zipfile.ZipFile(path) as z:
|
||||
files = z.namelist()
|
||||
boards = [name for name in files if name.endswith('.kicad_pcb')]
|
||||
if boards:
|
||||
stem = boards[0].removesuffix('.kicad_pcb')
|
||||
if len(boards) == 1 and all(stem + suffix in files for suffix in ('.kicad_pro','.kicad_sch')):
|
||||
return 'available', None
|
||||
return 'unsupported', '工程缺少配套的单板 KiCad 工程或原理图。'
|
||||
if 'project.json' not in files:
|
||||
if 'project2.json' in files or any(n.lower().endswith('.epru') for n in files):
|
||||
return 'unsupported', '此工程使用新版嘉立创格式,当前网页编辑器暂不支持。'
|
||||
return 'unsupported', '未找到网页编辑器支持的工程源文件。'
|
||||
if z.getinfo('project.json').file_size > 32 * 1024**2:
|
||||
return 'unsupported', '工程索引超过网页编辑器支持的大小。'
|
||||
meta = json.loads(z.read('project.json'))
|
||||
if not isinstance(meta, dict):
|
||||
raise ValueError('metadata')
|
||||
if len(meta.get('pcbs') or {}) != 1 or len(meta.get('schematics') or {}) != 1:
|
||||
return 'unsupported', '当前编辑器需要单 PCB、单原理图工程,请先在嘉立创中选择实际交付板。'
|
||||
return 'available', None
|
||||
except (ValueError, TypeError, OSError, KeyError, zipfile.BadZipFile, RuntimeError):
|
||||
return 'unsupported', '无法读取交付的工程源文件。'
|
||||
|
||||
|
||||
@lru_cache(maxsize=256)
|
||||
def manifest_digest(path, mtime, size):
|
||||
return storage.digest(path.read_bytes())
|
||||
|
||||
|
||||
def editing_fields(task, code):
|
||||
status, reason, manifest = 'pending', None, None
|
||||
if task.get('state') == 'completed':
|
||||
source = next((f for f in (task.get('delivery') or {}).get('files', []) if f.get('kind') == 'project'), None)
|
||||
try:
|
||||
folder = storage.task_dir(task['id'])/'delivery'
|
||||
manifest = manifest_digest(*file_key(folder/'manifest.json'))
|
||||
if not source:
|
||||
raise ValueError('missing source')
|
||||
status, reason = source_info(*file_key(storage.inside(folder, source['name'])))
|
||||
except (OSError, ValueError, KeyError):
|
||||
status, reason = 'unsupported', '缺少已核验的交付清单或工程源文件。'
|
||||
return {'project_code': code, 'editing_status': status, 'editing_reason': reason, 'manifest_sha256': manifest}
|
||||
|
||||
|
||||
def code_for(item, marker):
|
||||
if not isinstance(item, dict) or item.get('description') != marker:
|
||||
return None
|
||||
code = item.get('pcbProjectCode')
|
||||
if not isinstance(code, str) or not code or code in {'.','..'} or not code.isprintable():
|
||||
raise HTTPException(502, '平台未返回有效的工程编号。')
|
||||
return code
|
||||
|
||||
|
||||
async def recover_code(token, marker):
|
||||
# The platform has no creation idempotency key. Only match our private request
|
||||
# marker inside the authenticated user's list, including renamed projects.
|
||||
page = 1
|
||||
found = set()
|
||||
while True:
|
||||
result = await platform('GET', '/pcb/workspace/projects', token,
|
||||
params={'page':page, 'size':20, 'keyword':''})
|
||||
if not isinstance(result, dict) or result.get('page') != page or not isinstance(result.get('items'), list):
|
||||
raise HTTPException(502, '暂时无法核对平台工程列表。')
|
||||
found.update(code for item in result['items'] if (code := code_for(item, marker)))
|
||||
total, size = result.get('total'), result.get('size')
|
||||
if not isinstance(total, int) or not isinstance(size, int) or size < 1 or total < 0:
|
||||
raise HTTPException(502, '暂时无法核对平台工程分页。')
|
||||
if page * size >= total or not result['items']:
|
||||
break
|
||||
page += 1
|
||||
if len(found) != 1:
|
||||
raise HTTPException(409, '正在核实上次创建的云工程。请稍后再试;若持续出现,请管理员核查创建记录。')
|
||||
return found.pop()
|
||||
|
||||
|
||||
async def editing_project(task, account):
|
||||
tid = task['id']
|
||||
row = record(tid, account.owner)
|
||||
code = row['project_code']
|
||||
if code:
|
||||
try:
|
||||
item = await platform('GET', '/pcb/workspace/projects/' + quote(code, safe=''), account.token)
|
||||
if not isinstance(item, dict) or item.get('pcbProjectCode') != code:
|
||||
raise HTTPException(502, '平台未确认编辑副本的工程编号。')
|
||||
return code
|
||||
except HTTPException as exc:
|
||||
if exc.status_code != 404:
|
||||
raise
|
||||
# An explicit open may rebuild a deleted copy. Concurrent opens must
|
||||
# share the new marker; an outage or authorization failure never resets it.
|
||||
with connection() as db:
|
||||
db.execute('UPDATE projects SET project_code=NULL, attempted=0, marker=? WHERE task_id=? AND owner=? AND project_code=?',
|
||||
('AI PCB · ' + secrets.token_hex(16), tid, account.owner, code))
|
||||
row = record(tid, account.owner)
|
||||
if row['project_code']:
|
||||
return row['project_code']
|
||||
info = editing_fields(task, None)
|
||||
if info['editing_status'] != 'available':
|
||||
raise HTTPException(409, info['editing_reason'] or '交付完成后可打开编辑副本。')
|
||||
marker = row['marker']
|
||||
with connection() as db:
|
||||
first = db.execute('UPDATE projects SET attempted=1 WHERE task_id=? AND owner=? AND marker=? AND attempted=0 AND project_code IS NULL',
|
||||
(tid, account.owner, marker)).rowcount
|
||||
if first:
|
||||
name = (task.get('proposal') or {}).get('title') or task.get('request') or 'AI PCB'
|
||||
name = ''.join(c if c.isprintable() else ' ' for c in name).strip()[:100] or 'AI PCB'
|
||||
try:
|
||||
item = await platform('POST', '/pcb/workspace/projects', account.token,
|
||||
json={'name':name, 'description':marker})
|
||||
except HTTPException as exc:
|
||||
if exc.status_code in (400, 401, 403, 404, 422, 429): # definitive rejection
|
||||
with connection() as db:
|
||||
db.execute('UPDATE projects SET attempted=0 WHERE task_id=? AND marker=? AND project_code IS NULL', (tid, marker))
|
||||
raise
|
||||
code = code_for(item, marker)
|
||||
if not code:
|
||||
raise HTTPException(502, '平台创建回执不完整,请重试以核对原工程。')
|
||||
else:
|
||||
code = await recover_code(account.token, marker)
|
||||
with connection() as db:
|
||||
db.execute('UPDATE projects SET project_code=? WHERE task_id=? AND owner=? AND marker=? AND project_code IS NULL',
|
||||
(code, tid, account.owner, marker))
|
||||
linked = db.execute('SELECT project_code FROM projects WHERE task_id=? AND owner=?', (tid,account.owner)).fetchone()
|
||||
if not linked or linked[0] != code:
|
||||
raise HTTPException(409, '工程关联发生变化,请刷新后重新打开。')
|
||||
return code
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import argparse
|
||||
parser = argparse.ArgumentParser(description='Bind a verified historical AI task to its confirmed platform owner')
|
||||
parser.add_argument('command', choices=['bind', 'allow-create-after-confirmed-absent'])
|
||||
parser.add_argument('task_id')
|
||||
parser.add_argument('user_code', help='Verified platform userCode (not a nickname or email)')
|
||||
args = parser.parse_args()
|
||||
if not args.user_code.strip() or not args.user_code.isprintable():
|
||||
parser.error('Invalid userCode')
|
||||
if storage.load(args.task_id).get('id') != args.task_id:
|
||||
parser.error('Task does not exist')
|
||||
owner = owner_key(args.user_code)
|
||||
if args.command == 'bind':
|
||||
bind(args.task_id, owner)
|
||||
print('已绑定任务 ' + args.task_id)
|
||||
else:
|
||||
with connection() as db:
|
||||
count = db.execute('UPDATE projects SET attempted=0, marker=? WHERE task_id=? AND owner=? AND attempted=1 AND project_code IS NULL',
|
||||
('AI PCB · ' + secrets.token_hex(16), args.task_id, owner)).rowcount
|
||||
if not count:
|
||||
parser.error('此账号和任务没有待核实的云工程创建记录。')
|
||||
print('已允许该任务再次申请云工程。')
|
||||
@@ -0,0 +1,146 @@
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
from zipfile import ZipFile
|
||||
|
||||
import httpx
|
||||
from fastapi import HTTPException
|
||||
from codex_pcb import app as service, editing_projects as ep, storage
|
||||
|
||||
TID = 'pcb-' + '1'*24
|
||||
OTHER = 'pcb-' + '2'*24
|
||||
|
||||
|
||||
class EditingProjects(unittest.IsolatedAsyncioTestCase):
|
||||
def setUp(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp.cleanup)
|
||||
tasks = Path(temp.name)/'tasks'
|
||||
self.enterContext(patch.object(storage, 'TASKS', tasks))
|
||||
self.enterContext(patch.object(service, 'CACHE', {}))
|
||||
for tid in (TID, OTHER):
|
||||
folder = tasks/tid/'delivery'
|
||||
folder.mkdir(parents=True)
|
||||
source = folder/'design.epro'
|
||||
with ZipFile(source,'w') as z:
|
||||
z.writestr('project.json', json.dumps({'pcbs':{'b':'PCB'},'schematics':{'s':'Schematic'}}))
|
||||
(folder/'manifest.json').write_text('{}')
|
||||
service.CACHE[tid] = {'id':tid, 'state':'completed', 'created_at':1, 'request':'Board',
|
||||
'delivery':{'files':[{'kind':'project','name':'design.epro','sha256':hashlib.sha256(source.read_bytes()).hexdigest()}]}}
|
||||
self.posts = 0
|
||||
self.cloud = []
|
||||
self.fail_after_create = False
|
||||
self.enterContext(patch.object(ep, 'platform', self.platform))
|
||||
self.owner = ep.owner_key('alice')
|
||||
ep.bind(TID,self.owner)
|
||||
self.client = httpx.AsyncClient(transport=httpx.ASGITransport(app=service.app),base_url='http://test')
|
||||
self.addAsyncCleanup(self.client.aclose)
|
||||
|
||||
async def platform(self, method, path, token, **kwargs):
|
||||
if path == '/users/me':
|
||||
if token not in ('alice','bob'):
|
||||
raise HTTPException(401,'expired')
|
||||
return {'userCode':token}
|
||||
self.assertEqual(token,'alice')
|
||||
if method == 'POST':
|
||||
self.posts += 1
|
||||
item = {'pcbProjectCode':f'code-{self.posts}', **kwargs['json']}
|
||||
self.cloud.append(item)
|
||||
if self.fail_after_create:
|
||||
raise HTTPException(503,'unknown result')
|
||||
return item
|
||||
self.assertEqual(method,'GET')
|
||||
if path.startswith('/pcb/workspace/projects/'):
|
||||
code = path.rsplit('/',1)[-1]
|
||||
for item in self.cloud:
|
||||
if item['pcbProjectCode'] == code:
|
||||
return item
|
||||
raise HTTPException(404,'deleted')
|
||||
return {'page':1,'size':20,'total':len(self.cloud),'items':list(self.cloud)}
|
||||
|
||||
async def call(self, method, path, token=None, **kwargs):
|
||||
headers = {'Authorization':'Bearer '+token} if token else {}
|
||||
return await self.client.request(method,'/api/sessions'+path,headers=headers,**kwargs)
|
||||
|
||||
async def test_identity_comes_from_platform_and_all_task_routes_include_owner_guard(self):
|
||||
self.assertEqual((await self.call('GET','')).status_code,401)
|
||||
self.assertEqual((await self.call('GET','','expired')).status_code,401)
|
||||
self.assertEqual((await self.call('GET','','bob')).json(),[])
|
||||
alice = (await self.call('GET','','alice')).json()
|
||||
self.assertEqual([t['id'] for t in alice],[TID])
|
||||
self.assertEqual(alice[0]['manifest_sha256'],storage.digest(b'{}'))
|
||||
self.assertEqual(alice[0]['editing_status'],'available')
|
||||
self.assertNotIn('owner',alice[0])
|
||||
result = await self.call('GET','/'+TID+'/files/design.epro','alice')
|
||||
self.assertEqual(result.status_code,200)
|
||||
for method,path in [('GET',''),('GET','/preview'),('GET','/events'),('GET','/questions'),
|
||||
('GET','/files/design.epro'),('POST','/cancel'),('POST','/resume'),('POST','/questions'),
|
||||
('POST','/comments'),('POST','/approve'),('POST','/feedback'),('POST','/editing-project')]:
|
||||
for tid,token in [(TID,'bob'),(OTHER,'alice')]:
|
||||
result=await self.call(method,'/'+tid+path,token,json={} if method=='POST' else None)
|
||||
self.assertEqual(result.status_code,404,(method,path,result.text))
|
||||
with self.assertRaises(ValueError):
|
||||
ep.bind(TID,ep.owner_key('bob'))
|
||||
ep.bind(TID,self.owner)
|
||||
|
||||
async def test_retry_lost_receipt_recovers_same_project_after_restart(self):
|
||||
self.cloud.append({'pcbProjectCode':'unrelated','name':'Board','description':''})
|
||||
self.fail_after_create=True
|
||||
path='/'+TID+'/editing-project'
|
||||
self.assertEqual((await self.call('POST',path,'alice')).status_code,503)
|
||||
self.cloud[-1]['name']='renamed'
|
||||
self.fail_after_create=False
|
||||
for _ in range(2):
|
||||
self.assertEqual((await self.call('POST',path,'alice')).json(),{'project_code':'code-1'})
|
||||
self.assertEqual(self.posts,1)
|
||||
self.assertEqual((await self.call('GET','/'+TID,'alice')).json()['project_code'],'code-1')
|
||||
|
||||
async def test_overlapping_creation_issues_one_platform_post(self):
|
||||
started,release=asyncio.Event(),asyncio.Event()
|
||||
async def delayed(method,path,token,**kwargs):
|
||||
if method=='POST':
|
||||
started.set()
|
||||
await release.wait()
|
||||
return await self.platform(method,path,token,**kwargs)
|
||||
path='/'+TID+'/editing-project'
|
||||
with patch.object(ep,'platform',delayed):
|
||||
first=asyncio.create_task(self.call('POST',path,'alice'))
|
||||
await started.wait()
|
||||
second=await self.call('POST',path,'alice')
|
||||
self.assertEqual(second.status_code,409)
|
||||
release.set()
|
||||
self.assertEqual((await first).status_code,200)
|
||||
self.assertEqual((await self.call('POST',path,'alice')).status_code,200)
|
||||
self.assertEqual(self.posts,1)
|
||||
|
||||
async def test_deleted_copy_can_be_recreated_but_platform_outage_does_not_rebind(self):
|
||||
path='/'+TID+'/editing-project'
|
||||
first=await self.call('POST',path,'alice')
|
||||
self.assertEqual(first.json(),{'project_code':'code-1'})
|
||||
async def outage(method,path,token,**kwargs):
|
||||
if path.endswith('/code-1'):
|
||||
raise HTTPException(503,'temporarily unavailable')
|
||||
return await self.platform(method,path,token,**kwargs)
|
||||
with patch.object(ep,'platform',outage):
|
||||
self.assertEqual((await self.call('POST',path,'alice')).status_code,503)
|
||||
self.assertEqual(self.posts,1)
|
||||
self.assertEqual(ep.record(TID,self.owner)['project_code'],'code-1')
|
||||
self.cloud.clear()
|
||||
self.assertEqual((await self.call('POST',path,'alice')).json(),{'project_code':'code-2'})
|
||||
self.assertEqual((await self.call('POST',path,'alice')).json(),{'project_code':'code-2'})
|
||||
self.assertEqual(self.posts,2)
|
||||
|
||||
async def test_newer_format_inside_a_legacy_extension_is_download_only(self):
|
||||
path=storage.task_dir(TID)/'delivery/design.epro'
|
||||
with ZipFile(path,'w') as z:
|
||||
z.writestr('project2.json','{}')
|
||||
z.writestr('design.epru','document')
|
||||
dto=(await self.call('GET','/'+TID,'alice')).json()
|
||||
self.assertEqual(dto['editing_status'],'unsupported')
|
||||
self.assertIn('新版',dto['editing_reason'])
|
||||
self.assertEqual((await self.call('POST','/'+TID+'/editing-project','alice')).status_code,409)
|
||||
self.assertEqual(self.posts,0)
|
||||
@@ -30,6 +30,11 @@ class PreviewTests(unittest.IsolatedAsyncioTestCase):
|
||||
self.capture = AsyncMock(return_value={'available': True, 'kind': 'layout', 'image': IMAGE})
|
||||
self.previews = PreviewService(root=self.root, capture=self.capture)
|
||||
self.addAsyncCleanup(self.previews.close)
|
||||
auth = patch.dict(service.app.dependency_overrides, {
|
||||
service.editing_projects.current_account: lambda: service.editing_projects.Account('verified-owner','token')
|
||||
})
|
||||
auth.start()
|
||||
self.addCleanup(auth.stop)
|
||||
self.tasks = {}
|
||||
for tid in (TID, OTHER):
|
||||
task = {'id': tid, 'state': 'running', 'approval': {'hash': 'accepted'},
|
||||
@@ -46,6 +51,8 @@ class PreviewTests(unittest.IsolatedAsyncioTestCase):
|
||||
patch.object(module.Path, 'home', return_value=self.root / 'home')):
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
for tid in self.tasks:
|
||||
service.editing_projects.bind(tid, 'verified-owner')
|
||||
|
||||
async def request(self, tid=TID, *, kind='auto', method='GET', headers=None):
|
||||
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=service.app), base_url='http://test') as client:
|
||||
|
||||
@@ -27,6 +27,7 @@ class ProviderSelection(unittest.IsolatedAsyncioTestCase):
|
||||
}, clear=True)
|
||||
self.environment.start()
|
||||
self.reload()
|
||||
app.app.dependency_overrides[app.editing_projects.current_account] = lambda: app.editing_projects.Account('verified-owner','token')
|
||||
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}))
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
/** Optional host port. Native editors do not know about accounts or HTTP. */
|
||||
export interface ProjectSnapshotParticipant {
|
||||
flush: () => void | Promise<void>;
|
||||
flush: (reason?: 'clean-draft' | 'snapshot') => void | Promise<void>;
|
||||
isBusy?: () => boolean;
|
||||
isDirty?: () => boolean;
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ export function useProjectSnapshot(
|
||||
useEffect(
|
||||
() =>
|
||||
host?.register(key, {
|
||||
flush: () => live.current.flush(),
|
||||
flush: (reason) => live.current.flush(reason),
|
||||
isDirty: () => live.current.isDirty?.() ?? false,
|
||||
isBusy: () => live.current.isBusy?.() ?? false,
|
||||
}),
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import { useLayoutEffect, useRef } from 'react';
|
||||
import type { TourLocale } from '../onboarding/pcb.steps.js';
|
||||
import { usePcbOnboarding } from '../onboarding/usePcbOnboarding.js';
|
||||
|
||||
export function AiPcbTourButton({
|
||||
owner, locale, binding, busy,
|
||||
}: {
|
||||
owner: string;
|
||||
locale: TourLocale;
|
||||
binding: string;
|
||||
busy: boolean;
|
||||
}) {
|
||||
const button = useRef<HTMLButtonElement>(null);
|
||||
const { available, onSource, start } = usePcbOnboarding({
|
||||
surface: 'ai', owner, locale, binding, available: !busy,
|
||||
});
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const root = button.current?.closest<HTMLElement>('.cp-workbench');
|
||||
if (!root) return;
|
||||
onSource({ root, isReady: () => root.isConnected, isBusy: () => false });
|
||||
return () => onSource(null);
|
||||
}, [onSource]);
|
||||
|
||||
return (
|
||||
<button type="button" data-ai-pcb-tour-help="" ref={button} onClick={start} disabled={!available}>
|
||||
{locale === 'en' ? 'Workflow guide' : '使用引导'}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -1,34 +1,34 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import './codex-pcb.css';
|
||||
import type { TourLocale } from '../onboarding/pcb.steps.js';
|
||||
import { AiPcbTourButton } from './AiPcbTourButton.js';
|
||||
import { DesignPreview } from './DesignPreview.js';
|
||||
import { DeliveryChat } from './DeliveryChat.js';
|
||||
import type { Artifact, Session, Entry } from './workbench-types.js';
|
||||
import { parseApiResponse } from './api-response.js';
|
||||
import { type SessionApi } from './session-api.js';
|
||||
import { EnvironmentStatus, type RuntimeReadiness } from './EnvironmentStatus.js';
|
||||
import { TaskProgress } from './TaskProgress.js';
|
||||
import { Markdown as RichMarkdown } from '@ziroeda/ai/markdown.js';
|
||||
|
||||
type AiProvider = { id: string; label: string; model: string; effort: string; configured: boolean };
|
||||
type ProviderConfig = { default_provider: string; providers: AiProvider[] };
|
||||
const BASE = `${import.meta.env.BASE_URL}pcb-api`;
|
||||
const ACTIVE = 'vibemake.pcb2.persistent-session';
|
||||
const STATES: Record<string, string> = { planning: '正在制定方案', review: '等待审核方案', needs_input: '等待补充需求', running: '自主设计中', completed: '已完成交付', blocked: '已暂停,等待你的决定', failed: '运行失败', interrupted: '等待恢复', cancelled: '已停止' };
|
||||
async function api<T>(path: string, data?: unknown): Promise<T> {
|
||||
const r = await fetch(BASE + path, { method: data === undefined ? 'GET' : 'POST', cache: 'no-store', headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, body: data === undefined ? undefined : JSON.stringify(data) });
|
||||
return parseApiResponse<T>(r, BASE + path);
|
||||
}
|
||||
function text(value: unknown): string { return typeof value === 'string' ? value : ''; }
|
||||
function Markdown({ value }: { value: string }): JSX.Element {
|
||||
return <RichMarkdown text={value} className="cp-markdown"/>;
|
||||
}
|
||||
export function CodexPcbDock(): JSX.Element | null {
|
||||
type DockProps = { owner: string; client: SessionApi; onProjectsChanged?: () => void; locale?: TourLocale };
|
||||
export function CodexPcbDock(props: DockProps): JSX.Element | null {
|
||||
if (import.meta.env.VITE_ENABLE_PCB_AI === 'false') return null;
|
||||
return <ConnectedCodexPcbDock />;
|
||||
return <ConnectedCodexPcbDock {...props} />;
|
||||
}
|
||||
function ConnectedCodexPcbDock(): JSX.Element {
|
||||
function ConnectedCodexPcbDock({ owner, client, onProjectsChanged, locale = 'zh' }: DockProps): JSX.Element {
|
||||
const api = client.json;
|
||||
const storageKey = `${ACTIVE}.${owner}`;
|
||||
const [open, setOpen] = useState(new URLSearchParams(location.search).get('ai') === '1');
|
||||
const [active, setActive] = useState<string | null>(() => localStorage.getItem(ACTIVE));
|
||||
const [active, setActive] = useState<string | null>(() => new URLSearchParams(location.search).get('aiTask') || localStorage.getItem(storageKey));
|
||||
const [sessions, setSessions] = useState<Session[]>([]);
|
||||
const [task, setTask] = useState<Session | null>(null);
|
||||
const [entries, setEntries] = useState<Entry[]>([]);
|
||||
@@ -49,7 +49,7 @@ function ConnectedCodexPcbDock(): JSX.Element {
|
||||
const main = useRef<HTMLElement>(null);
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: changing the tab or task resets the content scroll position.
|
||||
useEffect(() => { followChat.current = true; main.current?.scrollTo({ top: tab === 'activity' ? main.current.scrollHeight : 0 }); }, [tab, active]);
|
||||
const choose = (id: string | null) => { setActive(id); setTask(null); setEntries([]); cursor.current = 0; activeRef.current = id; setTab('activity'); setComment(''); setError(''); if (id) localStorage.setItem(ACTIVE,id); else localStorage.removeItem(ACTIVE); };
|
||||
const choose = (id: string | null) => { setActive(id); setTask(null); setEntries([]); cursor.current = 0; activeRef.current = id; setTab('activity'); setComment(''); setError(''); if (id) localStorage.setItem(storageKey,id); else localStorage.removeItem(storageKey); const url = new URL(location.href); if (url.searchParams.has('aiTask')) { if (id) url.searchParams.set('aiTask', id); else url.searchParams.delete('aiTask'); history.replaceState(history.state, '', url); } };
|
||||
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.
|
||||
@@ -74,13 +74,14 @@ function ConnectedCodexPcbDock(): JSX.Element {
|
||||
};
|
||||
void poll();
|
||||
return () => { cancelled = true; clearTimeout(timer); };
|
||||
}, [runtimeRevision]);
|
||||
}, [api, 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;
|
||||
const [list, config] = await Promise.all([client.list(), 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 && !list.some(session => session.id === active)) { choose(null); return; }
|
||||
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;
|
||||
@@ -90,17 +91,17 @@ function ConnectedCodexPcbDock(): JSX.Element {
|
||||
} catch (e) { if (!cancelled && activeRef.current === active) setError(String(e)); }
|
||||
finally { if (!cancelled) timer = window.setTimeout(poll, 2000); }
|
||||
}; void poll(); return () => { cancelled = true; clearTimeout(timer); };
|
||||
}, [open, active]);
|
||||
}, [client, open, active]);
|
||||
useEffect(() => { if (tab === 'activity' && followChat.current) main.current?.scrollTo({ top: main.current.scrollHeight, behavior: 'smooth' }); }, [entries.length, tab]);
|
||||
const action = async (fn: () => Promise<void>) => { setBusy(true); setError(''); try { await fn(); } catch(e) { setError(String(e)); } finally { setBusy(false); } };
|
||||
const create = () => action(async () => { const t = await api<Session>('/sessions', { text: request, provider: selectedProvider }); choose(t.id); setTask(t); setRequest(''); });
|
||||
const create = () => action(async () => { const t = await api<Session>('/sessions', { text: request, provider: selectedProvider }); choose(t.id); setTask(t); setRequest(''); onProjectsChanged?.(); });
|
||||
const updateTask = (next: Session) => { if (activeRef.current === next.id) setTask(next); };
|
||||
const send = () => action(async () => { const id = active; const t = await api<Session>(`/sessions/${id}/comments`, { text: comment }); updateTask(t); if (activeRef.current === id) { setComment(''); setTab('activity'); } });
|
||||
const feedback = (intent: 'discuss' | 'revise') => action(async () => { if (!task?.proposal) return; const id = active; const t = await api<Session>(`/sessions/${id}/feedback`, { text: comment, intent, revision: task.proposal.revision, hash: task.proposal.hash }); updateTask(t); if (activeRef.current === id) { setComment(''); setTab('activity'); } });
|
||||
const approve = () => action(async () => { if (!task?.proposal) return; const id = active; updateTask(await api<Session>(`/sessions/${id}/approve`, { revision: task.proposal.revision, hash: task.proposal.hash })); if (activeRef.current === id) setTab('activity'); });
|
||||
const cancel = () => action(async () => { updateTask(await api<Session>(`/sessions/${active}/cancel`, {})); });
|
||||
const resume = () => action(async () => { const id = active; updateTask(await api<Session>(`/sessions/${id}/resume`, {})); if (activeRef.current === id) setTab('activity'); });
|
||||
const downloadable = (f: Artifact) => `${BASE}/sessions/${active}/files/${encodeURIComponent(f.name)}`;
|
||||
const download = (file: Artifact) => action(async () => { if (active) await client.download(active, file); });
|
||||
const canReview = task && !task.approval && !task.busy && ['review','needs_input','failed'].includes(task.state);
|
||||
const canRecover = !!task?.approval && !task.busy && ['blocked','failed','cancelled','interrupted','review','needs_input'].includes(task.state);
|
||||
const canCompose = canReview || canRecover;
|
||||
@@ -112,19 +113,19 @@ function ConnectedCodexPcbDock(): JSX.Element {
|
||||
const taskProvider = providers.find(p => p.id === task?.ai_provider)?.label || task?.ai_provider || 'OpenAI';
|
||||
const messages = interesting.filter(e => e.type === 'message');
|
||||
const logs = interesting.filter(e => e.type !== 'message');
|
||||
const setOpened = (value: boolean) => { setOpen(value); const url = new URL(location.href); if (value) url.searchParams.set('ai', '1'); else url.searchParams.delete('ai'); history.replaceState(history.state, '', url); };
|
||||
const setOpened = (value: boolean) => { setOpen(value); if (!value) onProjectsChanged?.(); const url = new URL(location.href); if (value) url.searchParams.set('ai', '1'); else { url.searchParams.delete('ai'); url.searchParams.delete('aiTask'); } history.replaceState(history.state, '', url); };
|
||||
const view = <div className="cp-root" data-native-text-shortcuts="true" data-pcb-tour-blocked={open || busy || task?.busy ? 'true' : undefined}>
|
||||
{!open ? <><div className="cp-environment-notice"><EnvironmentStatus report={runtime} checking={runtimeChecking} error={runtimeError} compact onRetry={recheckRuntime} onOpen={() => setOpened(true)}/></div><button className="cp-launch" data-pcb-tour="assistant" onClick={() => setOpened(true)}>✦ Codex AI 自动绘板</button></> : <section className="cp-window cp-workbench" aria-label="AI PCB 全屏工作台">
|
||||
<header className="cp-header">
|
||||
<div className="cp-brand"><strong>AI PCB <em>工作台</em></strong><span>从想法到真实电路板</span></div>
|
||||
<div className="cp-workbench-actions"><select aria-label="选择设计任务" value={active ?? ''} disabled={busy} onChange={e => choose(e.target.value || null)}><option value="">新建设计</option>{sessions.map(s => <option key={s.id} value={s.id}>{s.proposal?.title || s.request.slice(0,36)} · {STATES[s.state] || s.state}</option>)}</select><button disabled={busy} onClick={() => choose(null)}>+ 新建设计</button><button onClick={() => window.open(`${import.meta.env.BASE_URL}?library=1`, '_blank', 'noopener,noreferrer')}>开源项目库</button><button className="cp-exit" onClick={() => setOpened(false)}>返回编辑器</button></div>
|
||||
<div className="cp-workbench-actions"><select data-ai-pcb-tour="tasks" aria-label="选择设计任务" value={active ?? ''} disabled={busy} onChange={e => choose(e.target.value || null)}><option value="">新建设计</option>{sessions.map(s => <option key={s.id} value={s.id}>{s.proposal?.title || s.request.slice(0,36)} · {STATES[s.state] || s.state}</option>)}</select><button data-ai-pcb-tour={active ? 'request' : undefined} disabled={busy} onClick={() => choose(null)}>+ 新建设计</button><button onClick={() => window.open(`${import.meta.env.BASE_URL}?library=1`, '_blank', 'noopener,noreferrer')}>开源项目库</button>{owner && <AiPcbTourButton owner={owner} locale={locale} binding={active || 'new'} busy={busy}/>}<button className="cp-exit" onClick={() => setOpened(false)}>返回编辑器</button></div>
|
||||
</header>
|
||||
{active && task && <TaskProgress key={task.id} task={task} entries={entries} sessions={sessions}/>}
|
||||
<div className="cp-workbench-body">
|
||||
<DesignPreview key={active ?? 'new'} task={task}/>
|
||||
<DesignPreview key={active ?? 'new'} task={task} client={client}/>
|
||||
<section className="cp-chat" aria-label="设计对话">
|
||||
<header className="cp-chat-heading"><div><span className="cp-eyebrow">AI 设计助手</span><h2>{task?.proposal?.title || (task ? task.request.slice(0,60) : '一起设计你的电路板')}</h2>{task && <p className="cp-task-model">{taskProvider} · {task.model || '原会话模型'}</p>}</div>{task && <span className={`cp-status state-${task.state}`}>{task.busy && <i/>}{STATES[task.state] || task.state}</span>}</header>
|
||||
<nav className="cp-tabs" aria-label="对话与交付"><button aria-selected={tab === 'activity'} onClick={() => setTab('activity')}>对话</button><button aria-selected={tab === 'plan'} onClick={() => setTab('plan')}>设计方案{task?.proposal ? ` · v${task.proposal.revision}` : ''}</button><button aria-selected={tab === 'files'} onClick={() => setTab('files')}>交付文件{task?.delivery ? ` · ${task.delivery.files.length}` : ''}</button>{task?.state === 'completed' && <button aria-selected={tab === 'qa'} onClick={() => setTab('qa')}>使用问答</button>}</nav>
|
||||
<nav className="cp-tabs" aria-label="对话与交付"><button data-ai-pcb-tour="conversation" aria-selected={tab === 'activity'} onClick={() => setTab('activity')}>对话</button><button data-ai-pcb-tour="proposal" aria-selected={tab === 'plan'} onClick={() => setTab('plan')}>设计方案{task?.proposal ? ` · v${task.proposal.revision}` : ''}</button><button data-ai-pcb-tour="delivery" aria-selected={tab === 'files'} onClick={() => setTab('files')}>交付文件{task?.delivery ? ` · ${task.delivery.files.length}` : ''}</button>{task?.state === 'completed' && <button aria-selected={tab === 'qa'} onClick={() => setTab('qa')}>使用问答</button>}</nav>
|
||||
<main ref={main} className="cp-main" onScroll={e => { const el = e.currentTarget; followChat.current = el.scrollHeight - el.scrollTop - el.clientHeight < 80; }}>
|
||||
<EnvironmentStatus report={runtime} checking={runtimeChecking} error={runtimeError} onRetry={recheckRuntime}/>
|
||||
{error && <div className="cp-error" role="alert">{error}<button onClick={() => setError('')} aria-label="关闭错误提示">×</button></div>}
|
||||
@@ -139,22 +140,22 @@ function ConnectedCodexPcbDock(): JSX.Element {
|
||||
{task.busy && <p className="cp-working" role="status"><i/>AI 正在继续处理,画面和消息会自动更新…</p>}
|
||||
{task.approval && <details className="cp-session-info"><summary>会话信息</summary><code>{task.thread_id || '正在创建'}</code><p>模型:{taskProvider} · {task.model || '原会话模型'} · 方案与生产共用此会话</p></details>}
|
||||
</div>}
|
||||
{tab === 'qa' && task.state === 'completed' && <DeliveryChat key={task.id} taskId={task.id}/>}
|
||||
{tab === 'qa' && task.state === 'completed' && <DeliveryChat key={task.id} taskId={task.id} client={client}/>}
|
||||
{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}{task.recovery?.requires_approval ? ';制作已暂停,等待新方案确认。' : '。'}</div>}{!!task.proposal_history?.length && <details><summary>历史方案与批准记录</summary>{task.proposal_history.map(item => <details key={item.proposal.revision}><summary>v{item.proposal.revision} · {item.approval ? '曾批准' : '未批准'} · {item.proposal.title}</summary><Markdown value={item.proposal.markdown}/></details>)}</details>}</div>}
|
||||
{tab === 'files' && <div className="cp-files">{!task.delivery ? <p className="cp-muted">完成设计和检查后,交付文件会显示在这里。生成过程可在左侧预览。</p> : <><p>{task.delivery.notes}</p><p className="cp-muted">交互式 3D 模型、原理图和布线图在左侧查看。</p>{task.delivery.files.map(f => <a className="cp-file" key={f.name} href={downloadable(f)} download><div><strong>{f.label}</strong><small>{f.name} · {(f.bytes / 1024).toFixed(1)} KB</small></div><span>下载 ↓</span></a>)}</>}</div>}
|
||||
{tab === 'files' && <div className="cp-files">{!task.delivery ? <p className="cp-muted">完成设计和检查后,交付文件会显示在这里。生成过程可在左侧预览。</p> : <><p>{task.delivery.notes}</p><p className="cp-muted">交互式 3D 模型、原理图和布线图在左侧查看。</p>{task.delivery.files.map(f => <button type="button" className="cp-file" key={f.name} disabled={busy} onClick={() => void download(f)}><div><strong>{f.label}</strong><small>{f.name} · {(f.bytes / 1024).toFixed(1)} KB</small></div><span>下载 ↓</span></button>)}</>}</div>}
|
||||
</>}
|
||||
</main>
|
||||
{task?.state === 'completed' ? <div className="cp-composer cp-completed-actions"><p>设计已交付,可继续询问使用方法。</p><div><button className="cp-primary" onClick={() => setTab('qa')}>询问这块板子</button><button onClick={() => choose(null)}>开始新设计</button></div></div> : <form className="cp-composer" onSubmit={event => { event.preventDefault(); if (busy) return; if (canRecover && comment.trim()) { void feedback('discuss'); return; } if (!environmentReady) return; if (!active && provider?.configured && request.trim().length >= 5) void create(); else if (canReview && comment.trim().length >= 5) void send(); }}>
|
||||
{!active && <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>}
|
||||
<label htmlFor="cp-compose">{!active ? '描述你的设计需求' : canRecover ? '讨论阻碍或提出修改' : canReview ? '补充要求或修改方案' : '设计沟通'}</label>
|
||||
<textarea id="cp-compose" rows={3} value={!active ? request : comment} disabled={busy || (!!active && !canCompose)} onChange={e => active ? setComment(e.target.value) : setRequest(e.target.value)}
|
||||
<textarea data-ai-pcb-tour={!active ? 'request' : undefined} id="cp-compose" rows={3} value={!active ? request : comment} disabled={busy || (!!active && !canCompose)} onChange={e => active ? setComment(e.target.value) : setRequest(e.target.value)}
|
||||
onKeyDown={event => { if ((event.ctrlKey || event.metaKey) && event.key === 'Enter' && !event.nativeEvent.isComposing) { event.preventDefault(); event.currentTarget.form?.requestSubmit(); } }}
|
||||
placeholder={!active ? '例如:设计 ESP32 最小系统板,5V 供电,带下载接口…' : canRecover ? '可以询问原因、补充资料,或描述希望修改的方案。发送讨论不会自动恢复绘板。' : canReview ? '输入需要调整的地方,AI 会更新设计方案…' : task?.approval ? '正在按已确认方案制作,可在对话中查看最新进展。' : 'AI 正在处理,方案就绪后可继续沟通…'}/>
|
||||
<div className="cp-compose-actions"><small>{canRecover ? '发送后只讨论或修订,确认后才恢复制作' : !active || canReview ? '⌘ / Ctrl + Enter 发送' : task?.busy ? '关闭页面,后台仍会继续' : '任务已暂停,等待操作'}</small><div>
|
||||
{!active && <button type="submit" className="cp-primary" disabled={busy || !environmentReady || !provider?.configured || request.trim().length < 5}>{busy ? '正在提交…' : '发送需求 →'}</button>}
|
||||
{canReview && <button type="submit" disabled={busy || !environmentReady || comment.trim().length < 5}>发送修改意见</button>}
|
||||
{canRecover && <><button type="submit" disabled={busy || !comment.trim()}>发送讨论</button><button type="button" disabled={busy || !comment.trim()} onClick={() => feedback('revise')}>生成修订方案</button></>}
|
||||
{canApprove && <button type="button" className="cp-primary" disabled={busy || !environmentReady || !!comment.trim()} onClick={approve}>{pendingRevision ? '确认修订并继续制作' : '确认方案并开始'}</button>}
|
||||
{canApprove && <button data-ai-pcb-tour="approve" type="button" className="cp-primary" disabled={busy || !environmentReady || !!comment.trim()} onClick={approve}>{pendingRevision ? '确认修订并继续制作' : '确认方案并开始'}</button>}
|
||||
{task?.busy && <button type="button" className="cp-stop" disabled={busy} onClick={cancel}>停止运行</button>}
|
||||
{canResume && <button type="button" disabled={busy || !environmentReady || !!comment.trim()} onClick={resume}>按原方案重试</button>}
|
||||
</div></div>{canCompose && comment.trim() && <small className="cp-muted">请先发送输入内容;修订方案需要审核确认后才会制作。</small>}
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Markdown } from '@ziroeda/ai/markdown.js';
|
||||
import { parseApiResponse } from './api-response.js';
|
||||
import type { SessionApi } from './session-api.js';
|
||||
|
||||
type Message = { id: string; role: 'user' | 'assistant'; text: string; at: number; phase?: string };
|
||||
type Conversation = { busy: boolean; messages: Message[]; error?: string };
|
||||
const BASE = `${import.meta.env.BASE_URL}pcb-api`;
|
||||
|
||||
export function DeliveryChat({ taskId }: { taskId: string }): JSX.Element {
|
||||
|
||||
export function DeliveryChat({ taskId, client }: { taskId: string; client: SessionApi }): JSX.Element {
|
||||
const [chat, setChat] = useState<Conversation>({ busy: false, messages: [] });
|
||||
const [question, setQuestion] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
@@ -23,7 +24,7 @@ export function DeliveryChat({ taskId }: { taskId: string }): JSX.Element {
|
||||
const poll = async () => {
|
||||
const version = revision.current;
|
||||
try {
|
||||
const response = await fetch(`${BASE}/sessions/${taskId}/questions`, { cache: 'no-store', headers: { Accept: 'application/json' } });
|
||||
const response = await client.fetch(`/sessions/${taskId}/questions`, { cache: 'no-store', headers: { Accept: 'application/json' } });
|
||||
const value = await parseApiResponse<Conversation>(response, '交付后问答');
|
||||
if (!Array.isArray(value.messages) || typeof value.busy !== 'boolean') throw new Error('问答服务响应格式不正确');
|
||||
if (!cancelled && version === revision.current && !posting.current) { setChat(value); setError(''); }
|
||||
@@ -32,12 +33,12 @@ export function DeliveryChat({ taskId }: { taskId: string }): JSX.Element {
|
||||
};
|
||||
void poll();
|
||||
return () => { cancelled = true; mounted.current = false; clearTimeout(timer); };
|
||||
}, [taskId]);
|
||||
}, [client, taskId]);
|
||||
const send = async () => {
|
||||
if (posting.current || chat.busy || !question.trim()) return;
|
||||
posting.current = true; revision.current++; setSending(true); setError('');
|
||||
try {
|
||||
const response = await fetch(`${BASE}/sessions/${taskId}/questions`, { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, body: JSON.stringify({ text: question.trim() }) });
|
||||
const response = await client.fetch(`/sessions/${taskId}/questions`, { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, body: JSON.stringify({ text: question.trim() }) });
|
||||
const value = await parseApiResponse<Conversation>(response, '交付后问答');
|
||||
if (mounted.current) { setChat(value); setQuestion(''); }
|
||||
} catch (e) { if (mounted.current) setError(String(e)); }
|
||||
|
||||
@@ -2,11 +2,14 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { readVerifiedModel, stepHasColors, unpackColoredObj } from './model-appearance.js';
|
||||
|
||||
import type { SessionApi } from './session-api.js';
|
||||
|
||||
type Source = 'obj' | 'step';
|
||||
type Viewer = { reset: () => void; dispose: () => void };
|
||||
|
||||
/** Preview the delivered mesh directly; keep the original STEP available for CAD use. */
|
||||
export function DeliveryModel3D({ url, sha256, name, objUrl, objSha256 }: {
|
||||
export function DeliveryModel3D({ client, download, url, sha256, name, objUrl, objSha256 }: {
|
||||
client: SessionApi; download: () => void;
|
||||
url: string; sha256: string; name: string; objUrl?: string; objSha256?: string;
|
||||
}) {
|
||||
const host = useRef<HTMLDivElement>(null);
|
||||
@@ -36,7 +39,7 @@ export function DeliveryModel3D({ url, sha256, name, objUrl, objSha256 }: {
|
||||
const mount = async (source: Source): Promise<{ viewer: Viewer; caption: string } | null> => {
|
||||
if (source === 'obj') {
|
||||
setStatus('正在加载交付包中的彩色外观模型…');
|
||||
const packed = await readVerifiedModel(objUrl!, objSha256!, signal, 64 * 1024 * 1024);
|
||||
const packed = await readVerifiedModel(objUrl!, objSha256!, signal, 64 * 1024 * 1024, client.fetch);
|
||||
if (signal.aborted) return null;
|
||||
const files = unpackColoredObj(packed);
|
||||
const { mountProjectObj } = await import('../pcb-service/project-model-obj.js');
|
||||
@@ -44,7 +47,7 @@ export function DeliveryModel3D({ url, sha256, name, objUrl, objSha256 }: {
|
||||
return { viewer: mountProjectObj(element, files), caption: '彩色外观来自已交付的 OBJ/MTL;机械尺寸请以原始 STEP 为准。' };
|
||||
}
|
||||
setStatus('正在解析装配模型,首次打开可能需要一些时间…');
|
||||
const bytes = await readVerifiedModel(url, sha256, signal);
|
||||
const bytes = await readVerifiedModel(url, sha256, signal, undefined, client.fetch);
|
||||
if (signal.aborted) return null;
|
||||
const { mountDeliveryStep } = await import('./delivery-step-viewer.js');
|
||||
if (signal.aborted) return null;
|
||||
@@ -93,7 +96,7 @@ export function DeliveryModel3D({ url, sha256, name, objUrl, objSha256 }: {
|
||||
dispose?.();
|
||||
reset.current = null;
|
||||
};
|
||||
}, [url, sha256, retry, forceStep, hasObj, objUrl, objSha256]);
|
||||
}, [client, url, sha256, retry, forceStep, hasObj, objUrl, objSha256]);
|
||||
|
||||
const reload = () => { setStatus('正在重新加载模型…'); setRetry(value => value + 1); };
|
||||
const switchSource = () => {
|
||||
@@ -118,6 +121,6 @@ export function DeliveryModel3D({ url, sha256, name, objUrl, objSha256 }: {
|
||||
{failed && <button onClick={reload}>重新加载模型</button>}
|
||||
</div>}
|
||||
</div>
|
||||
<div className="cp-model-footer"><span>{name}</span><a href={url} download>下载 STEP 模型 ↓</a></div>
|
||||
<div className="cp-model-footer"><span>{name}</span><button onClick={download}>下载 STEP 模型 ↓</button></div>
|
||||
</section>;
|
||||
}
|
||||
|
||||
@@ -4,12 +4,13 @@ import { DeliveryModel3D } from './DeliveryModel3D.js';
|
||||
import { findObjArchive } from './model-appearance.js';
|
||||
import { parseApiResponse } from './api-response.js';
|
||||
import type { Artifact, Session } from './workbench-types.js';
|
||||
import { filePath, type SessionApi } from './session-api.js';
|
||||
|
||||
type Mode = 'auto' | 'schematic' | 'layout' | '3d';
|
||||
type Frame = { kind: Exclude<Mode, 'auto'>; image: string; capturedAt: number; source: 'canvas' | 'export' };
|
||||
type PreviewResponse = { taskId: string; frame: Frame | null; reason: string };
|
||||
const LABELS = { auto: '跟随进度', schematic: '原理图', layout: 'PCB 布线', '3d': '3D 模型' };
|
||||
const BASE = `${import.meta.env.BASE_URL}pcb-api`;
|
||||
|
||||
|
||||
function ImageCanvas({ url, label }: { url: string; label: string }) {
|
||||
const [scale, setScale] = useState(1);
|
||||
@@ -28,11 +29,26 @@ function ImageCanvas({ url, label }: { url: string; label: string }) {
|
||||
</div>;
|
||||
}
|
||||
|
||||
export function DesignPreview({ task }: { task: Session | null }) {
|
||||
function DeliveryImage({ client, id, file }: { client: SessionApi; id: string; file: Artifact }) {
|
||||
const [source, setSource] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
let url = '';
|
||||
void client.file(id, file, controller.signal).then(blob => {
|
||||
if (!controller.signal.aborted) { url = URL.createObjectURL(blob); setSource(url); }
|
||||
}).catch(e => { if (!controller.signal.aborted) setError(String(e)); });
|
||||
return () => { controller.abort(); if (url) URL.revokeObjectURL(url); };
|
||||
}, [client, id, file.name, file.sha256]);
|
||||
return source ? <ImageCanvas url={source} label={file.label}/> : <p role="status">{error || '正在读取交付图纸…'}</p>;
|
||||
}
|
||||
export function DesignPreview({ task, client }: { task: Session | null; client: SessionApi }) {
|
||||
const [mode, setMode] = useState<Mode>('auto');
|
||||
const [frame, setFrame] = useState<Frame | null>(null);
|
||||
const [notice, setNotice] = useState('正在连接设计画面…');
|
||||
const [selectedFile, setSelectedFile] = useState('');
|
||||
const [downloadError, setDownloadError] = useState('');
|
||||
const [downloading, setDownloading] = useState(false);
|
||||
const id = task?.id;
|
||||
const state = task?.state;
|
||||
const completed = state === 'completed';
|
||||
@@ -46,8 +62,8 @@ export function DesignPreview({ task }: { task: Session | null }) {
|
||||
const poll = async () => {
|
||||
try {
|
||||
if (document.visibilityState === 'hidden') return;
|
||||
const path = `${BASE}/sessions/${id}/preview?kind=${mode}`;
|
||||
const response = await fetch(path, { signal: controller.signal, cache: 'no-store', headers: etag ? { 'If-None-Match': etag } : {} });
|
||||
const path = `/sessions/${id}/preview?kind=${mode}`;
|
||||
const response = await client.fetch(path, { signal: controller.signal, cache: 'no-store', headers: etag ? { 'If-None-Match': etag } : {} });
|
||||
if (controller.signal.aborted) return;
|
||||
if (response.status === 304) { setNotice(lastNotice); return; }
|
||||
const value = await parseApiResponse<PreviewResponse>(response, path);
|
||||
@@ -66,22 +82,31 @@ export function DesignPreview({ task }: { task: Session | null }) {
|
||||
};
|
||||
void poll();
|
||||
return () => { controller.abort(); clearTimeout(timer); };
|
||||
}, [id, completed, approved, mode, state]);
|
||||
}, [client, id, completed, approved, mode, state]);
|
||||
const files = task?.delivery?.files ?? [];
|
||||
const step = files.find(f => f.kind === 'step' && /\.(step|stp)$/i.test(f.name));
|
||||
const obj = findObjArchive(files);
|
||||
const kind = mode === 'auto' ? completed ? '3d' : frame?.kind : mode;
|
||||
const pictures = files.filter(f => /\.(png|jpe?g|svg)$/i.test(f.name) && f.kind === (kind === '3d' ? 'render' : kind));
|
||||
const picture = pictures.find(f => f.name === selectedFile) ?? pictures[0];
|
||||
const download = (file: Artifact) => `${BASE}/sessions/${id}/files/${encodeURIComponent(file.name)}`;
|
||||
const download = (file: Artifact) => filePath(id!, file.name);
|
||||
const bundle = files.find(f => f.kind === 'bundle');
|
||||
const saveFile = async (file: Artifact) => {
|
||||
if (!id) return;
|
||||
setDownloading(true); setDownloadError('');
|
||||
try { await client.download(id, file); }
|
||||
catch (error) { setDownloadError(String(error)); }
|
||||
finally { setDownloading(false); }
|
||||
};
|
||||
const shownFrame = frame && (mode === 'auto' || frame.kind === mode) ? frame : null;
|
||||
const emptyTitle = !task ? '从一个想法,开始一块电路板' : !approved ? '设计画布已准备就绪' : '等待设计画面';
|
||||
return <section className="cp-preview" aria-label="设计实时预览">
|
||||
<header className="cp-preview-header"><div><span className="cp-eyebrow">设计画布</span><h2>{kind ? LABELS[kind] : '实时设计预览'}</h2></div><span className={`cp-live-badge${completed ? ' is-complete' : ''}`}>{completed ? '已完成交付' : approved ? '自动更新' : '等待开始'}</span></header>
|
||||
<nav className="cp-preview-tabs" aria-label="切换设计视图">{(Object.keys(LABELS) as Mode[]).map(value => <button key={value} aria-pressed={mode === value} onClick={() => { setMode(value); setSelectedFile(''); }}>{LABELS[value]}</button>)}</nav>
|
||||
<nav data-ai-pcb-tour="preview" className="cp-preview-tabs" aria-label="切换设计视图">{(Object.keys(LABELS) as Mode[]).map(value => <button key={value} aria-pressed={mode === value} onClick={() => { setMode(value); setSelectedFile(''); }}>{LABELS[value]}</button>)}{bundle && <button disabled={downloading} onClick={() => void saveFile(bundle)}>下载交付包 ↓</button>}</nav>
|
||||
{downloadError && <p role="alert">{downloadError}</p>}
|
||||
<div className="cp-preview-stage">
|
||||
{completed && kind === '3d' && step ? <DeliveryModel3D key={`${id}/${step.sha256}`} url={download(step)} sha256={step.sha256} name={step.name} objUrl={obj ? download(obj) : undefined} objSha256={obj?.sha256}/>
|
||||
: completed && picture ? <><label className="cp-picture-picker">图页<select aria-label="选择图页" value={picture.name} onChange={e => setSelectedFile(e.target.value)}>{pictures.map(f => <option key={f.name} value={f.name}>{f.label} · {f.name}</option>)}</select></label><ImageCanvas key={picture.name} url={download(picture)} label={picture.label}/></>
|
||||
{completed && kind === '3d' && step ? <DeliveryModel3D key={`${id}/${step.sha256}`} client={client} download={() => void saveFile(step)} url={download(step)} sha256={step.sha256} name={step.name} objUrl={obj ? download(obj) : undefined} objSha256={obj?.sha256}/>
|
||||
: completed && picture ? <><label className="cp-picture-picker">图页<select aria-label="选择图页" value={picture.name} onChange={e => setSelectedFile(e.target.value)}>{pictures.map(f => <option key={f.name} value={f.name}>{f.label} · {f.name}</option>)}</select></label><DeliveryImage key={picture.sha256} client={client} id={id!} file={picture}/></>
|
||||
: !completed && shownFrame ? <ImageCanvas key={shownFrame.kind} url={shownFrame.image} label={`${LABELS[shownFrame.kind]}当前画面`}/>
|
||||
: <div className="cp-preview-empty"><div className="cp-canvas-symbol" aria-hidden="true">⌘</div><h3>{completed ? '此视图暂无可预览文件' : emptyTitle}</h3><p>{!task ? '在右侧描述需求,AI 将为你生成方案。' : !approved ? '确认右侧方案后,这里将自动展示原理图和 PCB 布线过程。' : completed ? '可切换其他视图,或在右侧下载交付文件。' : '原理图、布线画面会随设计更新;交付完成后自动切换到可交互的 3D 模型。'}</p><div className="cp-preview-journey"><span>01 原理图</span><i>→</i><span>02 PCB 布线</span><i>→</i><span>03 3D 模型</span></div></div>}
|
||||
</div>
|
||||
|
||||
@@ -34,8 +34,8 @@ export function unpackColoredObj(bytes: Uint8Array): Record<string, Uint8Array>
|
||||
return files;
|
||||
}
|
||||
|
||||
export async function readVerifiedModel(url: string, sha256: string, signal: AbortSignal, limit = 128 * 1024 * 1024): Promise<Uint8Array> {
|
||||
const response = await fetch(url, { signal, credentials: 'same-origin' });
|
||||
export async function readVerifiedModel(url: string, sha256: string, signal: AbortSignal, limit = 128 * 1024 * 1024, request: (url: string, init: RequestInit) => Promise<Response> = fetch): Promise<Uint8Array> {
|
||||
const response = await request(url, { signal, credentials: 'same-origin' });
|
||||
if (!response.ok) throw new Error('模型文件读取失败,请重试或下载原文件查看。');
|
||||
if (Number(response.headers.get('content-length')) > limit) throw new Error('模型较大,请下载原文件查看。');
|
||||
const bytes = new Uint8Array(await response.arrayBuffer());
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import { sha256, type AuthRecord } from '../platform/types.js';
|
||||
import { parseApiResponse } from './api-response.js';
|
||||
import type { Artifact, Session } from './workbench-types.js';
|
||||
|
||||
const BASE = `${import.meta.env.BASE_URL}pcb-api`;
|
||||
export const sessionPath = (id: string) => `/sessions/${encodeURIComponent(id)}`;
|
||||
export const filePath = (id: string, name: string) =>
|
||||
`${sessionPath(id)}/files/${encodeURIComponent(name)}`;
|
||||
|
||||
export class SessionApi {
|
||||
constructor(
|
||||
private identity: AuthRecord,
|
||||
private current: () => AuthRecord | null,
|
||||
) {}
|
||||
assertCurrent(): void {
|
||||
const now = this.current();
|
||||
if (now?.user.userCode !== this.identity.user.userCode || now.token !== this.identity.token)
|
||||
throw new Error('登录账号已更换,请重新打开项目。');
|
||||
}
|
||||
fetch = async (path: string, init: RequestInit = {}): Promise<Response> => {
|
||||
this.assertCurrent();
|
||||
if (!path.startsWith('/') || path.startsWith('//')) throw new Error('AI 服务地址无效');
|
||||
const headers = new Headers(init.headers);
|
||||
headers.set('Authorization', `Bearer ${this.identity.token}`);
|
||||
const response = await fetch(BASE + path, {
|
||||
...init,
|
||||
headers,
|
||||
credentials: 'omit',
|
||||
redirect: 'error',
|
||||
cache: 'no-store',
|
||||
signal: init.signal
|
||||
? AbortSignal.any([init.signal, AbortSignal.timeout(120000)])
|
||||
: AbortSignal.timeout(120000),
|
||||
});
|
||||
this.assertCurrent();
|
||||
if (response.status === 401)
|
||||
window.dispatchEvent(new CustomEvent('vm:pcb:unauthorized', { detail: this.identity.token }));
|
||||
return response;
|
||||
};
|
||||
json = async <T>(path: string, data?: unknown, signal?: AbortSignal): Promise<T> => {
|
||||
const response = await this.fetch(path, {
|
||||
method: data === undefined ? 'GET' : 'POST',
|
||||
signal,
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
...(data === undefined ? {} : { 'Content-Type': 'application/json' }),
|
||||
},
|
||||
body: data === undefined ? undefined : JSON.stringify(data),
|
||||
});
|
||||
const value = await parseApiResponse<T>(response, BASE + path);
|
||||
this.assertCurrent();
|
||||
return value;
|
||||
};
|
||||
async list(signal?: AbortSignal): Promise<Session[]> {
|
||||
const items = await this.json<Session[]>('/sessions', undefined, signal);
|
||||
if (
|
||||
!Array.isArray(items) ||
|
||||
!items.every((item) => Object.hasOwn(item, 'project_code') && item.editing_status)
|
||||
)
|
||||
throw new Error('AI 项目服务尚未支持账号归属,请更新后端。');
|
||||
return items;
|
||||
}
|
||||
async file(id: string, artifact: Artifact, signal?: AbortSignal): Promise<Blob> {
|
||||
const response = await this.fetch(filePath(id, artifact.name), { signal });
|
||||
if (!response.ok) await parseApiResponse(response, artifact.name);
|
||||
const blob = await response.blob();
|
||||
if (
|
||||
blob.size !== artifact.bytes ||
|
||||
(await sha256(new Uint8Array(await blob.arrayBuffer()))) !== artifact.sha256
|
||||
)
|
||||
throw new Error('交付文件与清单不一致,请重新下载。');
|
||||
this.assertCurrent();
|
||||
return blob;
|
||||
}
|
||||
async download(id: string, artifact: Artifact): Promise<void> {
|
||||
const blob = await this.file(id, artifact);
|
||||
const href = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.download = artifact.name;
|
||||
link.href = href;
|
||||
link.click();
|
||||
window.setTimeout(() => URL.revokeObjectURL(href), 1000);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
export type Artifact = { name: string; kind: string; label: string; bytes: number; sha256: string };
|
||||
export type Proposal = { title: string; markdown: string; revision: number; hash: string; at?: number };
|
||||
export 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?: Proposal; recovery?: { reason: string; evidence?: string; intent: 'discuss' | 'revise'; requires_approval: boolean }; proposal_history?: { proposal: Proposal; approval?: { revision: number; hash?: string; at?: number } | null }[]; approval?: { revision: number; at?: number }; delivery?: { files: Artifact[]; notes: string }; };
|
||||
export type Session = { project_code?: string | null; editing_status?: 'pending' | 'available' | 'unsupported'; editing_reason?: string | null; manifest_sha256?: string | null; 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?: Proposal; recovery?: { reason: string; evidence?: string; intent: 'discuss' | 'revise'; requires_approval: boolean }; proposal_history?: { proposal: Proposal; approval?: { revision: number; hash?: string; at?: number } | null }[]; approval?: { revision: number; at?: number }; delivery?: { files: Artifact[]; notes: string }; };
|
||||
export type Entry = { seq: number; at: number; type: string; data: Record<string, unknown> };
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import type { PCB_TOUR_STEPS } from './pcb.steps.js';
|
||||
|
||||
export const AI_PCB_TOUR_STEPS: typeof PCB_TOUR_STEPS = [
|
||||
{
|
||||
id: 'tasks',
|
||||
side: 'bottom',
|
||||
title: ['找到你的设计任务', 'Find your design'],
|
||||
body: [
|
||||
'用这个列表回到之前的设计。要画另一块板,点击旁边的「新建设计」。',
|
||||
'Use this list to return to an earlier design. Choose New design next to it to start another board.',
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'request',
|
||||
side: 'top',
|
||||
title: ['描述你要做的板子', 'Describe your board'],
|
||||
body: [
|
||||
'新建设计时,先选 AI 服务,再写用途、供电、接口、板框尺寸和指定器件。例如「5 V 供电的 ESP32 最小系统板,带 USB 下载接口」。点击「发送需求」后,AI 会先拟定方案。',
|
||||
'For a new design, choose an AI service and describe the purpose, power supply, interfaces, board dimensions and required parts. For example, ask for a 5 V ESP32 board with USB programming. Send the request to get a proposal.',
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'proposal',
|
||||
side: 'bottom',
|
||||
title: ['审核方案,再开始绘制', 'Review the proposal before drawing'],
|
||||
body: [
|
||||
'打开「设计方案」,核对器件、接口和尺寸。需要调整时,在下方发送修改意见,再查看新版本。满意后点击「确认方案并开始」,AI 才会开始绘制。',
|
||||
'Open the proposal to check parts, interfaces and dimensions. Send changes in the message box and review the revised version. Approve the proposal when you are ready for the AI to draw.',
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'approve',
|
||||
side: 'top',
|
||||
title: ['确认当前版本', 'Approve this revision'],
|
||||
body: [
|
||||
'这里确认的是当前显示的方案版本。如果还写有修改意见,先发送并等新版本返回,再确认。',
|
||||
'This button approves the current revision. If you have drafted changes, send them first and review the updated proposal.',
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'preview',
|
||||
side: 'bottom',
|
||||
title: ['查看原理图和布线进度', 'Follow the schematic and layout'],
|
||||
body: [
|
||||
'绘制开始后,左侧画布会跟随进度更新。也可以切换到「原理图」或「PCB 布线」查看。关闭工作台后,后台任务会继续。',
|
||||
'Once drawing starts, the canvas follows progress. Switch to the schematic or PCB layout to inspect a view. An active job continues in the background when you close the workbench.',
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'conversation',
|
||||
side: 'bottom',
|
||||
title: ['查看运行记录,处理暂停', 'Read updates and handle pauses'],
|
||||
body: [
|
||||
'在「对话」里查看设计进展,展开「运行记录」看细节。制作暂停时,可以补充资料、讨论原因,或请 AI 修订方案;修订后要重新确认才能继续制作。',
|
||||
'Open the conversation for updates and expand the run log for details. If production pauses, add information, discuss the issue or request a revised proposal. Review and approve a revision before resuming.',
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'delivery',
|
||||
side: 'bottom',
|
||||
title: ['下载成果,询问用法', 'Download files and ask about the board'],
|
||||
body: [
|
||||
'完成后,在「交付文件」下载原理图、PCB 布线图和 STEP 模型。要了解怎么供电或某个接口怎么接,打开「使用问答」询问这块板子。',
|
||||
'After completion, download the schematic, PCB layout and STEP model from the delivery files. Use the board Q&A for questions such as how to power it or wire a connector.',
|
||||
],
|
||||
},
|
||||
];
|
||||
@@ -2,16 +2,19 @@
|
||||
import type { driver, Driver, DriveStep } from 'driver.js';
|
||||
export type { Config, Driver, HookOpts } from 'driver.js';
|
||||
import type { PcbTourSource } from '@ziroeda/pcbnew/browser/pcb_tour_source.js';
|
||||
import { AI_PCB_TOUR_STEPS } from './ai-pcb.steps.js';
|
||||
import { PCB_TOUR_STEPS, tourText, type TourLocale } from './pcb.steps.js';
|
||||
import {
|
||||
onboardingStorageKey,
|
||||
readTourPreferences,
|
||||
writeTourPreferences,
|
||||
type TourPreferences,
|
||||
type TourSurface,
|
||||
type TourStorage,
|
||||
} from './preferences.js';
|
||||
|
||||
export interface PcbTourContext {
|
||||
surface?: TourSurface;
|
||||
owner: string;
|
||||
binding: string;
|
||||
locale: TourLocale;
|
||||
@@ -75,6 +78,8 @@ export class PcbOnboarding {
|
||||
private lastFocus?: HTMLElement;
|
||||
private identity = '';
|
||||
private owner = '';
|
||||
private surface?: TourSurface;
|
||||
private sourceRoot?: HTMLElement;
|
||||
private locale: TourLocale = 'zh';
|
||||
private generation = 0;
|
||||
private disposed = false;
|
||||
@@ -129,14 +134,20 @@ export class PcbOnboarding {
|
||||
|
||||
isActive = (): boolean => this.phase !== null;
|
||||
|
||||
private get preferenceKey(): string {
|
||||
return onboardingStorageKey(this.owner, this.surface);
|
||||
}
|
||||
|
||||
private preferences(): TourPreferences {
|
||||
return memory.get(this.owner) ?? readTourPreferences(storage(), this.owner);
|
||||
return (
|
||||
memory.get(this.preferenceKey) ?? readTourPreferences(storage(), this.owner, this.surface)
|
||||
);
|
||||
}
|
||||
|
||||
private savePreferences(preferences: TourPreferences): void {
|
||||
if (!this.owner) return;
|
||||
memory.set(this.owner, preferences);
|
||||
writeTourPreferences(storage(), this.owner, preferences);
|
||||
memory.set(this.preferenceKey, preferences);
|
||||
writeTourPreferences(storage(), this.owner, preferences, this.surface);
|
||||
this.changed({ available: this.canOffer(), enabled: preferences.enabled });
|
||||
}
|
||||
|
||||
@@ -150,6 +161,7 @@ export class PcbOnboarding {
|
||||
const ctx = this.context();
|
||||
if (
|
||||
this.disposed ||
|
||||
(!this.phase && document.body.classList.contains('pcb-tour-active')) ||
|
||||
!ctx.available ||
|
||||
(ctx.inputLocked && !this.phase) ||
|
||||
!ctx.owner ||
|
||||
@@ -160,25 +172,50 @@ export class PcbOnboarding {
|
||||
return false;
|
||||
const source = ctx.source;
|
||||
if (!source || !visible(source.root) || !source.isReady() || source.isBusy()) return false;
|
||||
// Covers native/browser dialogs, host recovery/auth masks and the full-screen AI workbench.
|
||||
return !document.querySelector(
|
||||
'dialog[open]:not(.pcb-tour-welcome):not(.driver-layer), [role="dialog"]:not(.pcb-tour-welcome):not(.pcb-tour-popover), ' +
|
||||
'.vm-auth-mask, .vm-desktop-mask, .ze-modal-backdrop, [data-pcb-tour-blocked="true"]',
|
||||
if (
|
||||
document.querySelector(
|
||||
'dialog[open]:not(.pcb-tour-welcome):not(.driver-layer), [role="dialog"]:not(.pcb-tour-welcome):not(.pcb-tour-popover), ' +
|
||||
'.vm-auth-mask, .vm-desktop-mask, .ze-modal-backdrop',
|
||||
)
|
||||
)
|
||||
return false;
|
||||
// The full-screen AI portal blocks the editor underneath it. Its own help can still open.
|
||||
const ownBlocker =
|
||||
ctx.surface === 'ai' ? source.root.closest('[data-pcb-tour-blocked="true"]') : null;
|
||||
return Array.from(document.querySelectorAll('[data-pcb-tour-blocked="true"]')).every(
|
||||
(blocker) => blocker === ownBlocker,
|
||||
);
|
||||
}
|
||||
|
||||
private menuOpen(): boolean {
|
||||
return !!document.querySelector('[role="menu"], details.vm-more[open]');
|
||||
private shouldOfferAutomatically(preferences: TourPreferences): boolean {
|
||||
if (
|
||||
!preferences.enabled ||
|
||||
offered.has(this.preferenceKey) ||
|
||||
document.querySelector('[role="menu"], details.vm-more[open]')
|
||||
)
|
||||
return false;
|
||||
if (this.surface !== 'ai') return true;
|
||||
const focused = document.activeElement;
|
||||
return (
|
||||
preferences.status !== 'completed' &&
|
||||
!(
|
||||
focused instanceof HTMLElement &&
|
||||
this.context().source?.root.contains(focused) &&
|
||||
(focused.matches('input, textarea, select, [role="textbox"]') || focused.isContentEditable)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
sync = (): void => {
|
||||
if (this.disposed) return;
|
||||
const ctx = this.context();
|
||||
const identity = `${ctx.owner}\n${ctx.binding}\n${ctx.locale}`;
|
||||
if (identity !== this.identity) {
|
||||
const identity = `${ctx.surface ?? 'editor'}\n${ctx.owner}\n${ctx.binding}\n${ctx.locale}`;
|
||||
if (identity !== this.identity || ctx.source?.root !== this.sourceRoot) {
|
||||
this.finish(undefined, false);
|
||||
this.identity = identity;
|
||||
this.sourceRoot = ctx.source?.root;
|
||||
this.owner = ctx.owner;
|
||||
this.surface = ctx.surface;
|
||||
this.locale = ctx.locale;
|
||||
}
|
||||
const available = this.canOffer();
|
||||
@@ -189,11 +226,16 @@ export class PcbOnboarding {
|
||||
this.finish();
|
||||
return;
|
||||
}
|
||||
if (!this.phase && this.menuOpen()) {
|
||||
if (this.phase) {
|
||||
const anchor = this.driver?.getActiveElement();
|
||||
if (ctx.surface === 'ai' && anchor && !visible(anchor)) this.finish();
|
||||
return;
|
||||
}
|
||||
if (!this.shouldOfferAutomatically(preferences)) {
|
||||
this.cancelOffer();
|
||||
return;
|
||||
}
|
||||
if (this.phase || this.offerTimer || offered.has(ctx.owner) || !preferences.enabled) return;
|
||||
if (this.offerTimer) return;
|
||||
this.offerTimer = setTimeout(() => {
|
||||
this.offerTimer = undefined;
|
||||
this.offer();
|
||||
@@ -206,17 +248,19 @@ export class PcbOnboarding {
|
||||
}
|
||||
|
||||
offer = (manual = false): void => {
|
||||
if (!this.canOffer() || this.phase || (!manual && this.menuOpen())) return;
|
||||
if (!this.canOffer() || this.phase) return;
|
||||
const ctx = this.context();
|
||||
this.owner = ctx.owner;
|
||||
this.surface = ctx.surface;
|
||||
this.locale = ctx.locale;
|
||||
if (!manual && (offered.has(ctx.owner) || !this.preferences().enabled)) return;
|
||||
if (!manual && !this.shouldOfferAutomatically(this.preferences())) return;
|
||||
this.cancelOffer();
|
||||
offered.add(ctx.owner);
|
||||
offered.add(this.preferenceKey);
|
||||
this.phase = 'welcome';
|
||||
const focused = document.activeElement;
|
||||
this.lastFocus =
|
||||
focused instanceof HTMLElement &&
|
||||
(this.surface !== 'ai' || ctx.source?.root.contains(focused)) &&
|
||||
focused !== document.body &&
|
||||
focused !== document.documentElement
|
||||
? focused
|
||||
@@ -225,20 +269,28 @@ export class PcbOnboarding {
|
||||
const dialog = node('dialog', 'pcb-tour-welcome');
|
||||
dialog.setAttribute('aria-labelledby', 'pcb-tour-title');
|
||||
dialog.setAttribute('aria-describedby', 'pcb-tour-description');
|
||||
const eyebrow = node('p', 'pcb-tour-eyebrow', 'PCB WORKSPACE');
|
||||
const ai = this.surface === 'ai';
|
||||
const eyebrow = node('p', 'pcb-tour-eyebrow', ai ? 'AI PCB' : 'PCB WORKSPACE');
|
||||
const title = node(
|
||||
'h2',
|
||||
'',
|
||||
this.text('花 1 分钟认识 PCB 编辑器', 'Get to know the PCB editor'),
|
||||
ai
|
||||
? this.text('认识 AI 绘板工作台', 'Explore the AI PCB workbench')
|
||||
: this.text('花 1 分钟认识 PCB 编辑器', 'Get to know the PCB editor'),
|
||||
);
|
||||
title.id = 'pcb-tour-title';
|
||||
const description = node(
|
||||
'p',
|
||||
'pcb-tour-description',
|
||||
this.text(
|
||||
'了解工具栏、编辑画布、图层和保存入口,帮助你开始第一个设计。整个引导只介绍界面,不会修改电路板。',
|
||||
'Explore the tools, canvas, layers and saving controls before your first design. This tour only explains the interface and leaves your board unchanged.',
|
||||
),
|
||||
ai
|
||||
? this.text(
|
||||
'看看在哪里描述电路需求、审核设计方案、跟踪绘制进度和下载交付文件。',
|
||||
'Find where to describe your circuit, review a proposal, follow the design and download the finished files.',
|
||||
)
|
||||
: this.text(
|
||||
'了解工具栏、编辑画布、图层和保存入口,帮助你开始第一个设计。整个引导只介绍界面,不会修改电路板。',
|
||||
'Explore the tools, canvas, layers and saving controls before your first design. This tour only explains the interface and leaves your board unchanged.',
|
||||
),
|
||||
);
|
||||
description.id = 'pcb-tour-description';
|
||||
const actions = node('div', 'pcb-tour-actions');
|
||||
@@ -282,6 +334,10 @@ export class PcbOnboarding {
|
||||
}
|
||||
|
||||
private target(step: (typeof PCB_TOUR_STEPS)[number], ctx: PcbTourContext): HTMLElement | null {
|
||||
if (ctx.surface === 'ai') {
|
||||
const target = ctx.source?.root.querySelector(`[data-ai-pcb-tour="${step.id}"]`);
|
||||
return visible(target) ? target : null;
|
||||
}
|
||||
const scope =
|
||||
step.scope === 'page'
|
||||
? document
|
||||
@@ -293,19 +349,20 @@ export class PcbOnboarding {
|
||||
}
|
||||
|
||||
private applyTheme(element: HTMLElement): void {
|
||||
const root = this.context().source?.root.closest('.vm-platform');
|
||||
const source = this.context().source?.root;
|
||||
const root = this.surface === 'ai' ? source : source?.closest('.vm-platform');
|
||||
if (!root) return;
|
||||
const computed = getComputedStyle(root);
|
||||
element.style.fontFamily = computed.fontFamily;
|
||||
for (const token of [
|
||||
'--vm-bg',
|
||||
'--vm-panel',
|
||||
'--vm-text',
|
||||
'--vm-muted',
|
||||
'--vm-line',
|
||||
'--vm-accent',
|
||||
]) {
|
||||
const value = computed.getPropertyValue(token).trim();
|
||||
for (const [token, aiToken] of [
|
||||
['--vm-bg', '--cp-bg'],
|
||||
['--vm-panel', '--cp-panel'],
|
||||
['--vm-text', '--cp-text'],
|
||||
['--vm-muted', '--cp-muted'],
|
||||
['--vm-line', '--cp-border'],
|
||||
['--vm-accent', '--cp-blue'],
|
||||
] as const) {
|
||||
const value = computed.getPropertyValue(this.surface === 'ai' ? aiToken : token).trim();
|
||||
if (value) element.style.setProperty(token, value);
|
||||
}
|
||||
element.lang = this.locale === 'en' ? 'en' : 'zh-CN';
|
||||
@@ -322,13 +379,15 @@ export class PcbOnboarding {
|
||||
generation !== this.generation ||
|
||||
!this.phase ||
|
||||
!this.canOffer() ||
|
||||
current.source !== ctx.source ||
|
||||
current.source?.root !== ctx.source?.root ||
|
||||
current.owner !== ctx.owner ||
|
||||
current.binding !== ctx.binding ||
|
||||
current.surface !== ctx.surface ||
|
||||
current.locale !== ctx.locale
|
||||
)
|
||||
return;
|
||||
const steps: DriveStep[] = PCB_TOUR_STEPS.flatMap((step) => {
|
||||
const definitions = ctx.surface === 'ai' ? AI_PCB_TOUR_STEPS : PCB_TOUR_STEPS;
|
||||
const steps: DriveStep[] = definitions.flatMap((step) => {
|
||||
const element = this.target(step, ctx);
|
||||
return element
|
||||
? [
|
||||
@@ -360,7 +419,10 @@ export class PcbOnboarding {
|
||||
progressText: this.text('{{current}} / {{total}}', '{{current}} of {{total}}'),
|
||||
nextBtnText: this.text('下一步', 'Next'),
|
||||
prevBtnText: this.text('上一步', 'Back'),
|
||||
doneBtnText: this.text('开始设计', 'Start designing'),
|
||||
doneBtnText:
|
||||
this.surface === 'ai'
|
||||
? this.text('完成引导', 'Finish tour')
|
||||
: this.text('开始设计', 'Start designing'),
|
||||
closeBtnLabel: this.text('退出引导', 'Exit tour'),
|
||||
showButtons: ['previous', 'next', 'close'],
|
||||
disableActiveInteraction: true,
|
||||
@@ -407,10 +469,16 @@ export class PcbOnboarding {
|
||||
error.setAttribute('role', 'alert');
|
||||
this.dialog.querySelector('.pcb-tour-actions')?.before(error);
|
||||
}
|
||||
error.textContent = this.text(
|
||||
'引导暂时无法加载,请重试或跳过后继续编辑。',
|
||||
'The tour could not load. Retry or skip it to continue editing.',
|
||||
);
|
||||
error.textContent =
|
||||
this.surface === 'ai'
|
||||
? this.text(
|
||||
'引导暂时无法加载。可以重试,或跳过后使用工作台。',
|
||||
'The tour could not load. Retry or skip it to use the workbench.',
|
||||
)
|
||||
: this.text(
|
||||
'引导暂时无法加载,请重试或跳过后继续编辑。',
|
||||
'The tour could not load. Retry or skip it to continue editing.',
|
||||
);
|
||||
const button = this.dialog.querySelector<HTMLButtonElement>('[data-pcb-tour-begin]');
|
||||
if (button) {
|
||||
button.disabled = false;
|
||||
@@ -483,8 +551,8 @@ export class PcbOnboarding {
|
||||
this.finish(undefined, false);
|
||||
};
|
||||
private onStorage = (event: StorageEvent): void => {
|
||||
if (event.key === null || event.key === onboardingStorageKey(this.owner)) {
|
||||
memory.delete(this.owner);
|
||||
if (event.key === null || event.key === this.preferenceKey) {
|
||||
memory.delete(this.preferenceKey);
|
||||
this.finish();
|
||||
this.sync();
|
||||
}
|
||||
@@ -494,7 +562,12 @@ export class PcbOnboarding {
|
||||
this.cancelOffer();
|
||||
if (!this.phase) return;
|
||||
++this.generation;
|
||||
if (status) this.savePreferences({ ...this.preferences(), status });
|
||||
if (status) {
|
||||
const prefs = this.preferences();
|
||||
// Skipping a manual replay does not reverse an earlier completion.
|
||||
if (this.surface !== 'ai' || prefs.status !== 'completed')
|
||||
this.savePreferences({ ...prefs, status });
|
||||
}
|
||||
const tour = this.driver;
|
||||
this.driver = undefined;
|
||||
this.phase = null;
|
||||
@@ -512,7 +585,9 @@ export class PcbOnboarding {
|
||||
visible(this.lastFocus) && !this.lastFocus.closest('[inert]')
|
||||
? this.lastFocus
|
||||
: this.context().source?.root.querySelector<HTMLElement>(
|
||||
'[data-pcb-tour="canvas"] canvas[tabindex]',
|
||||
this.surface === 'ai'
|
||||
? '[data-ai-pcb-tour-help]'
|
||||
: '[data-pcb-tour="canvas"] canvas[tabindex]',
|
||||
);
|
||||
if (visible(target) && !target.closest('[inert]')) target.focus({ preventScroll: true });
|
||||
}
|
||||
|
||||
@@ -6,8 +6,9 @@ export interface TourPreferences {
|
||||
status: 'completed' | 'skipped' | null;
|
||||
}
|
||||
export type TourStorage = Pick<Storage, 'getItem' | 'setItem'>;
|
||||
export const onboardingStorageKey = (owner: string): string =>
|
||||
`vm.pcb.onboarding.${encodeURIComponent(owner)}`;
|
||||
export type TourSurface = 'editor' | 'ai';
|
||||
export const onboardingStorageKey = (owner: string, surface?: TourSurface): string =>
|
||||
`vm.pcb.${surface === 'ai' ? 'ai-onboarding' : 'onboarding'}.${encodeURIComponent(owner)}`;
|
||||
export const defaultTourPreferences = (): TourPreferences => ({
|
||||
version: TOUR_VERSION,
|
||||
enabled: true,
|
||||
@@ -16,9 +17,12 @@ export const defaultTourPreferences = (): TourPreferences => ({
|
||||
export function readTourPreferences(
|
||||
storage: TourStorage | undefined,
|
||||
owner: string,
|
||||
surface?: TourSurface,
|
||||
): TourPreferences {
|
||||
try {
|
||||
const value: unknown = JSON.parse(storage?.getItem(onboardingStorageKey(owner)) ?? 'null');
|
||||
const value: unknown = JSON.parse(
|
||||
storage?.getItem(onboardingStorageKey(owner, surface)) ?? 'null',
|
||||
);
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value))
|
||||
return defaultTourPreferences();
|
||||
const record = value as Record<string, unknown>;
|
||||
@@ -40,10 +44,11 @@ export function writeTourPreferences(
|
||||
storage: TourStorage | undefined,
|
||||
owner: string,
|
||||
preferences: TourPreferences,
|
||||
surface?: TourSurface,
|
||||
): boolean {
|
||||
try {
|
||||
if (!storage) return false;
|
||||
storage.setItem(onboardingStorageKey(owner), JSON.stringify(preferences));
|
||||
storage.setItem(onboardingStorageKey(owner, surface), JSON.stringify(preferences));
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
|
||||
@@ -35,6 +35,7 @@ export function usePcbOnboarding(context: Omit<PcbTourContext, 'source'>) {
|
||||
}, []);
|
||||
const start = useCallback(() => controller.current?.offer(true), []);
|
||||
const setEnabled = useCallback((enabled: boolean) => controller.current?.setEnabled(enabled), []);
|
||||
const isActive = useCallback(() => controller.current?.isActive() ?? false, []);
|
||||
// The editor's global capture listeners must also yield to the tour in the AI portal.
|
||||
const isActive = useCallback(() => document.body.classList.contains('pcb-tour-active'), []);
|
||||
return { ...controls, onSource, start, setEnabled, isActive };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import { loadKicadNetlist } from '@ziroeda/common/netlist_reader/kicad_netlist_reader.js';
|
||||
import { Edge_Cuts, F_Cu, IsCopperLayer } from '@ziroeda/common/layer_id.js';
|
||||
import { ToKiCadLibID } from '@ziroeda/common/io/easyedapro/easyedapro_import_utils.js';
|
||||
import { NETLIST_EXPORTER_KICAD } from '@ziroeda/eeschema/netlist_exporters/netlist_exporter_kicad.js';
|
||||
import { GNL_ALL, GNL_T } from '@ziroeda/eeschema/netlist_exporters/netlist_exporter_xml.js';
|
||||
import { SCH_REFERENCE_LIST } from '@ziroeda/eeschema/sch_reference_list.js';
|
||||
import { SYMBOL_FILTER } from '@ziroeda/eeschema/sch_sheet_path.js';
|
||||
import type { SCHEMATIC } from '@ziroeda/eeschema/schematic.js';
|
||||
import type { BOARD } from '@ziroeda/pcbnew/board.js';
|
||||
import { PCB_ARC, PCB_VIA } from '@ziroeda/pcbnew/pcb_track.js';
|
||||
import { PCB_IO_EASYEDAPRO_PARSER as SourceUnits } from '@ziroeda/pcbnew/pcb_io/easyedapro/pcb_io_easyedapro_parser.js';
|
||||
|
||||
export function excludeDrawingFrames(
|
||||
schematic: SCHEMATIC,
|
||||
symbols: Record<string, { docType?: number; title: string }>,
|
||||
) {
|
||||
// Source docType 20 is a drawing frame. The EasyEDA reader imports frames as
|
||||
// unannotated symbols, which otherwise block Update PCB from Schematic.
|
||||
const frames = new Set(
|
||||
Object.values(symbols)
|
||||
.filter((s) => s.docType === 20)
|
||||
.map((s) => ToKiCadLibID('', s.title).GetLibItemName()),
|
||||
);
|
||||
const refs = new SCH_REFERENCE_LIST();
|
||||
schematic.Hierarchy().GetSymbols(refs, SYMBOL_FILTER.SYMBOL_FILTER_ALL, true);
|
||||
for (let i = 0; i < refs.GetCount(); i++) {
|
||||
const instance = refs.at(i);
|
||||
const symbol = instance.GetSymbol();
|
||||
if (!frames.has(symbol.GetLibId().GetLibItemName())) continue;
|
||||
symbol.SetRef(instance.GetSheetPath(), '#FRAME' + (i + 1));
|
||||
symbol.SetExcludedFromBoard(true);
|
||||
symbol.SetExcludedFromBOM(true);
|
||||
}
|
||||
}
|
||||
|
||||
function fail(detail: string): never {
|
||||
throw Error('暂时无法生成可靠的编辑副本。' + detail + '。原始嘉立创工程仍可下载。');
|
||||
}
|
||||
|
||||
export function verifyAndLinkBoard(board: BOARD, schematic: SCHEMATIC, sourceBoard: Uint8Array) {
|
||||
const rows: unknown[][] = new TextDecoder()
|
||||
.decode(sourceBoard)
|
||||
.split(/\r?\n/)
|
||||
.filter((line) => line.trim())
|
||||
.map((line) => JSON.parse(line));
|
||||
const designators = new Map(
|
||||
rows
|
||||
.filter((row) => row[0] === 'ATTR' && row[7] === 'Designator')
|
||||
.map((row) => [String(row[3]), String(row[8])]),
|
||||
);
|
||||
const netlist = loadKicadNetlist(
|
||||
new NETLIST_EXPORTER_KICAD(schematic).Format(GNL_ALL | GNL_T.GNL_OPT_KICAD),
|
||||
);
|
||||
const sourceRefs = new Set<string>();
|
||||
const separatePads = new Set(rows.filter((r) => r[0] === 'PAD').map((r) => 'Pad_' + r[1]));
|
||||
const footprints = new Map<string, ReturnType<BOARD['Footprints']>[number]>();
|
||||
for (const fp of board.Footprints()) {
|
||||
const ref = fp.GetReference();
|
||||
if (!ref && separatePads.delete(fp.GetFPIDAsString())) {
|
||||
fp.SetBoardOnly(true);
|
||||
continue;
|
||||
}
|
||||
if (!ref || footprints.has(ref)) fail('导入后存在缺失或重复的 PCB 位号 ' + ref);
|
||||
footprints.set(ref, fp);
|
||||
}
|
||||
if (separatePads.size) fail('导入后缺少板级独立焊盘');
|
||||
|
||||
const parser = new SourceUnits(board);
|
||||
const offset = board.GetDesignSettings().GetAuxOrigin();
|
||||
function point(x: unknown, y: unknown) {
|
||||
const p = SourceUnits.ScalePos({ x: Number(x), y: Number(y) });
|
||||
return { x: p.x + offset.x, y: p.y + offset.y };
|
||||
}
|
||||
const routed = new Map<string, number>();
|
||||
function routeKey(
|
||||
type: string,
|
||||
net: string,
|
||||
layer: number,
|
||||
a: { x: number; y: number },
|
||||
b: { x: number; y: number },
|
||||
width: number,
|
||||
drill: number,
|
||||
) {
|
||||
const ends = [
|
||||
[a.x, a.y],
|
||||
[b.x, b.y],
|
||||
].sort((p, q) => p[0]! - q[0]! || p[1]! - q[1]!);
|
||||
return JSON.stringify([type, net, layer, ends, width, drill]);
|
||||
}
|
||||
for (const t of board.Tracks()) {
|
||||
const via = t instanceof PCB_VIA;
|
||||
const key = routeKey(
|
||||
via ? 'VIA' : t instanceof PCB_ARC ? 'ARC' : 'LINE',
|
||||
t.GetNetname(),
|
||||
via ? -1 : t.GetLayer(),
|
||||
t.GetStart(),
|
||||
via ? t.GetStart() : t.GetEnd(),
|
||||
via ? t.GetWidth(F_Cu) : t.GetWidth(),
|
||||
via ? t.GetDrillValue() : 0,
|
||||
);
|
||||
routed.set(key, (routed.get(key) || 0) + 1);
|
||||
}
|
||||
const expectedNets = new Map<string, string>();
|
||||
const sourcePadIds = new Map<string, Set<string>>();
|
||||
const copperLayers = new Set<number>();
|
||||
for (const row of rows) {
|
||||
const type = String(row[0]);
|
||||
if (type === 'COMPONENT') {
|
||||
const ref = designators.get(String(row[1])) || '';
|
||||
const fp = footprints.get(ref);
|
||||
if (!fp || sourceRefs.has(ref))
|
||||
fail('器件 ' + (ref || String(row[1])) + ' 的位号未能唯一对应');
|
||||
const pos = point(row[4], row[5]);
|
||||
if (
|
||||
fp.GetPosition().x !== pos.x ||
|
||||
fp.GetPosition().y !== pos.y ||
|
||||
fp.GetLayer() !== parser.LayerToKi(Number(row[3]))
|
||||
)
|
||||
fail('器件 ' + ref + ' 的位置或板面发生变化');
|
||||
sourceRefs.add(ref);
|
||||
} else if (type === 'PAD_NET' && row[3]) {
|
||||
const ref = designators.get(String(row[1]));
|
||||
if (!ref) fail('有网络的焊盘缺少所属器件');
|
||||
const key = JSON.stringify([ref, String(row[2])]);
|
||||
const net = String(row[3]);
|
||||
if (expectedNets.has(key) && expectedNets.get(key) !== net)
|
||||
fail(ref + ' 的同号焊盘连接到了不同网络');
|
||||
expectedNets.set(key, net);
|
||||
const ids = sourcePadIds.get(key) ?? new Set<string>();
|
||||
ids.add(String(row[4]));
|
||||
sourcePadIds.set(key, ids);
|
||||
} else if (type === 'LAYER' && row[4]) {
|
||||
const layer = parser.LayerToKi(Number(row[1]));
|
||||
if (IsCopperLayer(layer)) copperLayers.add(layer);
|
||||
} else if (type === 'VIA' || type === 'LINE' || type === 'ARC') {
|
||||
const via = type === 'VIA';
|
||||
const start = point(row[5], row[6]);
|
||||
const key = routeKey(
|
||||
type,
|
||||
String(row[3]),
|
||||
via ? -1 : parser.LayerToKi(Number(row[4])),
|
||||
start,
|
||||
via ? start : point(row[7], row[8]),
|
||||
SourceUnits.ScaleSize(Number(row[via ? 8 : type === 'LINE' ? 9 : 10])),
|
||||
via ? SourceUnits.ScaleSize(Number(row[7])) : 0,
|
||||
);
|
||||
const count = routed.get(key) || 0;
|
||||
if (!count) fail('走线或过孔 ' + row[1] + ' 的网络、尺寸或位置与源工程不符');
|
||||
if (count === 1) routed.delete(key);
|
||||
else routed.set(key, count - 1);
|
||||
}
|
||||
}
|
||||
if (routed.size || sourceRefs.size !== footprints.size) fail('导入后的走线或器件数与源工程不符');
|
||||
if (
|
||||
copperLayers.size !== board.GetCopperLayerCount() ||
|
||||
!board
|
||||
.GetEnabledLayers()
|
||||
.CuStack()
|
||||
.every((layer) => copperLayers.has(layer))
|
||||
)
|
||||
fail('铜层堆叠与源工程不符');
|
||||
if (!board.Drawings().some((item) => item.IsOnLayer(Edge_Cuts))) fail('导入后没有板框');
|
||||
|
||||
for (const part of netlist.Components()) {
|
||||
if (!footprints.has(part.GetReference()))
|
||||
fail('原理图上的 ' + part.GetReference() + ' 在 PCB 中没有对应器件');
|
||||
}
|
||||
const remainingNets = new Map(expectedNets);
|
||||
let physicalConnections = 0;
|
||||
const canonicalNames = new Map<string, string>();
|
||||
for (const [ref, fp] of footprints) {
|
||||
const part = netlist.GetComponentByReference(ref);
|
||||
if (!part?.kiids.length) fail('PCB 上的 ' + ref + ' 在原理图中没有对应器件');
|
||||
if (part.GetFPID() && part.GetFPID() !== fp.GetFPIDAsString())
|
||||
fail(ref + ' 的原理图封装与 PCB 封装不一致');
|
||||
fp.SetPath([...part.path.split('/').filter(Boolean), part.kiids[0]!]);
|
||||
for (const pad of fp.Pads()) {
|
||||
const key = JSON.stringify([ref, pad.GetNumber()]);
|
||||
const expected = expectedNets.get(key);
|
||||
if (expected && !pad.GetNetname()) {
|
||||
// The upstream reader assigns PAD_NET to only the first pad of a number.
|
||||
// Some connector shells have several physical pads numbered 0. Restore
|
||||
// the rest only when the source explicitly connects every one of them.
|
||||
const copies = fp.Pads().filter((other) => other.GetNumber() === pad.GetNumber()).length;
|
||||
const netItem = board.FindNet(expected);
|
||||
if (copies > 1 && sourcePadIds.get(key)?.size === copies && netItem) pad.SetNet(netItem);
|
||||
}
|
||||
const net = pad.GetNetname();
|
||||
const schematicName = part.GetNet(pad.GetNumber()).netName;
|
||||
if (!net && !expectedNets.has(key)) {
|
||||
if (schematicName && !schematicName.startsWith('unconnected-('))
|
||||
fail(ref + ' 的焊盘 ' + pad.GetNumber() + ' 在 PCB 中悬空,在原理图中却有连接');
|
||||
continue;
|
||||
}
|
||||
if (expectedNets.get(key) !== net)
|
||||
fail(ref + ' 的焊盘 ' + pad.GetNumber() + ' 与源工程网络不符');
|
||||
remainingNets.delete(key);
|
||||
physicalConnections++;
|
||||
if (schematicName !== net && !schematicName.endsWith('/' + net))
|
||||
fail(ref + ' 的焊盘 ' + pad.GetNumber() + ' 在原理图和 PCB 中的网络不一致');
|
||||
if (canonicalNames.has(net) && canonicalNames.get(net) !== schematicName)
|
||||
fail('网络 ' + net + ' 在原理图中被拆分');
|
||||
canonicalNames.set(net, schematicName);
|
||||
}
|
||||
}
|
||||
if (remainingNets.size) {
|
||||
const [key, net] = remainingNets.entries().next().value!;
|
||||
const [ref, pad] = JSON.parse(key);
|
||||
fail(ref + ' 的' + (pad ? '焊盘 ' + pad : '未编号焊盘') + ' 缺少源工程记录的 ' + net + ' 网络');
|
||||
}
|
||||
// Rename shared NETINFO_ITEMs together: pads, tracks, vias and pours all refer
|
||||
// to these objects. The writer then serializes the schematic's canonical names.
|
||||
const allNets = [...board.BeginNets()];
|
||||
const names = allNets.map((n) => canonicalNames.get(n.GetNetname()) ?? n.GetNetname());
|
||||
if (new Set(names).size !== names.length) fail('转换后存在重名网络');
|
||||
allNets.forEach((n, i) => n.SetNetname(names[i]!));
|
||||
return {
|
||||
linked_components: footprints.size,
|
||||
connected_pad_numbers: expectedNets.size,
|
||||
connected_physical_pads: physicalConnections,
|
||||
copper_layers: copperLayers.size,
|
||||
routed_objects: board.Tracks().length,
|
||||
};
|
||||
}
|
||||
@@ -1,8 +1,13 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
/** Import a separate, explicitly unverified editing copy. Never replace the frozen source. */
|
||||
import { serializeFpLibTable } from '@ziroeda/common/fp_lib_table.js';
|
||||
import { unzipSync } from 'fflate';
|
||||
import { PCB_IO_EASYEDAPRO } from '@ziroeda/pcbnew/pcb_io/easyedapro/pcb_io_easyedapro.js';
|
||||
import { FormatBoard, ParseBoard } from '@ziroeda/pcbnew/pcb_io/kicad_sexpr/pcb_io_kicad_sexpr.js';
|
||||
import {
|
||||
FormatBoard,
|
||||
FormatFootprintForLibrary,
|
||||
ParseBoard,
|
||||
} from '@ziroeda/pcbnew/pcb_io/kicad_sexpr/pcb_io_kicad_sexpr.js';
|
||||
import { EMBEDDED_FILES } from '@ziroeda/common/embedded_files.js';
|
||||
import { PGM_BASE, SETTINGS_MANAGER, PgmOrNull, SetPgm } from '@ziroeda/common/pgm_base.js';
|
||||
import { MEMORY_FILESYSTEM, wxMountFileSystem } from '@ziroeda/wx/filefn.js';
|
||||
@@ -16,29 +21,41 @@ import { SCH_EDIT_FRAME, type SCH_EDIT_FRAME_HOOKS } from '@ziroeda/eeschema/sch
|
||||
import { SCH_IO_EASYEDAPRO } from '@ziroeda/eeschema/sch_io/easyedapro/sch_io_easyedapro.js';
|
||||
import { SCH_IO_KICAD_SEXPR } from '@ziroeda/eeschema/sch_io/kicad_sexpr/sch_io_kicad_sexpr.js';
|
||||
import { SCH_SCREENS } from '@ziroeda/eeschema/sch_screen.js';
|
||||
import { excludeDrawingFrames, verifyAndLinkBoard } from './editing-copy.js';
|
||||
import { projectJson } from '../home/new_project.js';
|
||||
import type { StoredFile } from '../home/projectStore.js';
|
||||
|
||||
export async function convertProject(
|
||||
bytes: Uint8Array,
|
||||
name: string,
|
||||
source: { task_id: string; manifest_sha256: string },
|
||||
) {
|
||||
const zip = unzipSync(bytes);
|
||||
if (
|
||||
Object.keys(zip).length > 5000 ||
|
||||
Object.values(zip).reduce((n, v) => n + v.length, 0) > 256 * 1024 * 1024
|
||||
)
|
||||
throw Error('导入工程超过大小限制');
|
||||
for (const path of Object.keys(zip)) {
|
||||
if (
|
||||
path.startsWith('/') ||
|
||||
path.includes('\\') ||
|
||||
path.includes(':') ||
|
||||
path.split('/').some((p) => p === '..' || p === '.')
|
||||
)
|
||||
throw Error('工程包含有不安全路径');
|
||||
}
|
||||
type Source = { task_id: string; manifest_sha256: string };
|
||||
|
||||
export function convertProject(bytes: Uint8Array, name: string, source: Source) {
|
||||
return convert(bytes, name, source, false);
|
||||
}
|
||||
|
||||
export function convertAiEditingProject(bytes: Uint8Array, name: string, source: Source) {
|
||||
if (!name || /[\u0000-\u001f/\\:]/.test(name) || name === '.' || name === '..')
|
||||
throw Error('编辑副本的文件名无效');
|
||||
return convert(bytes, name, source, true);
|
||||
}
|
||||
|
||||
async function convert(bytes: Uint8Array, name: string, source: Source, editingCopy: boolean) {
|
||||
let count = 0,
|
||||
size = 0;
|
||||
const zip = unzipSync(bytes, {
|
||||
filter(entry) {
|
||||
count++;
|
||||
size += entry.originalSize;
|
||||
if (count > 5000 || size > 256 * 1024 * 1024) throw Error('导入工程超过大小限制');
|
||||
const path = entry.name;
|
||||
if (
|
||||
path.startsWith('/') ||
|
||||
path.includes('\\') ||
|
||||
path.includes(':') ||
|
||||
path.split('/').some((p) => p === '..' || p === '.')
|
||||
)
|
||||
throw Error('工程包含有不安全路径');
|
||||
return true;
|
||||
},
|
||||
});
|
||||
const nativeBoards = Object.keys(zip).filter((p) => p.endsWith('.kicad_pcb'));
|
||||
if (nativeBoards.length) {
|
||||
if (nativeBoards.length !== 1) throw Error('目前只支持单 PCB 工程导入');
|
||||
@@ -58,7 +75,10 @@ export async function convertProject(
|
||||
.filter(
|
||||
([path]) =>
|
||||
path.startsWith(prefix) &&
|
||||
(allowed.test(path) || /(?:^|\/)(?:sym-lib-table|fp-lib-table|MODEL-SOURCES\.md|LICENSE\.CERN-OHL-P-2\.0|LICENSE\.Apache-2\.0)$/.test(path)),
|
||||
(allowed.test(path) ||
|
||||
/(?:^|\/)(?:sym-lib-table|fp-lib-table|MODEL-SOURCES\.md|LICENSE\.CERN-OHL-P-2\.0|LICENSE\.Apache-2\.0)$/.test(
|
||||
path,
|
||||
)),
|
||||
)
|
||||
.map(([path, content]) => ({ name: `${name}/${path.slice(prefix.length)}`, bytes: content }));
|
||||
files.push({
|
||||
@@ -85,13 +105,17 @@ export async function convertProject(
|
||||
};
|
||||
}
|
||||
if (!zip['project.json'])
|
||||
throw Error('当前文件不是可导入的 KiCad 或旧版 epro 工程;epro2 不能通过改名转换。');
|
||||
throw Error(
|
||||
'此工程使用新版嘉立创格式或缺少旧版工程目录。可下载原工程在嘉立创中打开,或导出旧版单板工程后导入。',
|
||||
);
|
||||
const metadata = JSON.parse(new TextDecoder().decode(zip['project.json']));
|
||||
if (
|
||||
Object.keys(metadata.pcbs || {}).length !== 1 ||
|
||||
Object.keys(metadata.schematics || {}).length !== 1
|
||||
)
|
||||
throw Error('目前只支持单 PCB、单原理图工程导入');
|
||||
throw Error(
|
||||
'此工程含多块板或多个原理图工程。请在嘉立创中选择目标电路板及配套原理图,单独导出后导入。',
|
||||
);
|
||||
await EMBEDDED_FILES.InitCodec();
|
||||
const io = new PCB_IO_EASYEDAPRO();
|
||||
io.SetFileReader(() => bytes);
|
||||
@@ -100,7 +124,7 @@ export async function convertProject(
|
||||
const enc = new TextEncoder(),
|
||||
files: StoredFile[] = [],
|
||||
put = (n: string, t: string) => files.push({ name: `${name}/${n}`, bytes: enc.encode(t) });
|
||||
put(`${name}.kicad_pcb`, FormatBoard(board, 'pcbnew'));
|
||||
let checks: ReturnType<typeof verifyAndLinkBoard> | undefined;
|
||||
put(`${name}.kicad_pro`, projectJson(name, null));
|
||||
const previous = PgmOrNull(),
|
||||
program = new PGM_BASE(null, new SETTINGS_MANAGER()),
|
||||
@@ -131,8 +155,50 @@ export async function convertProject(
|
||||
frame.SetScreen(schematic.RootScreen());
|
||||
sheet.SetFileName(`${name}.kicad_sch`);
|
||||
frame.GetScreen()!.SetFileName(`${folder}/${name}.kicad_sch`);
|
||||
if (editingCopy) excludeDrawingFrames(schematic, metadata.symbols ?? {});
|
||||
frame.RecalculateConnections(null, SCH_CLEANUP_FLAGS.GLOBAL_CLEANUP);
|
||||
frame.SetSheetNumberAndCount();
|
||||
if (editingCopy) {
|
||||
const pcbId = Object.keys(metadata.pcbs)[0]!;
|
||||
const sourceBoard = zip[`PCB/${pcbId}.epcb`];
|
||||
if (!sourceBoard) throw Error('嘉立创工程未包含项目指定的 PCB 源文件。原始交付包仍可下载。');
|
||||
checks = verifyAndLinkBoard(board, schematic, sourceBoard);
|
||||
const libraries = new Set<string>();
|
||||
const entries = new Map<string, string>();
|
||||
for (const fp of io.GetImportedCachedLibraryFootprints()) {
|
||||
const nick = fp.GetFPID().GetLibNickname(),
|
||||
part = fp.GetName();
|
||||
if (
|
||||
[nick, part].some((s) => !s || /[\u0000-\u001f/\\:]/.test(s) || s === '.' || s === '..')
|
||||
)
|
||||
throw Error('源工程的封装库名称不能用于编辑工程。原始交付包仍可下载。');
|
||||
libraries.add(nick);
|
||||
const path = `${nick}.pretty/${part}.kicad_mod`;
|
||||
const data = FormatFootprintForLibrary(fp);
|
||||
if (entries.has(path)) {
|
||||
if (entries.get(path) !== data)
|
||||
throw Error(`封装名 ${part} 对应多份定义,无法确定应使用哪一份。`);
|
||||
} else {
|
||||
entries.set(path, data);
|
||||
put(path, data);
|
||||
}
|
||||
}
|
||||
if (libraries.size) {
|
||||
put(
|
||||
'fp-lib-table',
|
||||
serializeFpLibTable(
|
||||
[...libraries].map((nick) => ({
|
||||
name: nick,
|
||||
type: 'KiCad',
|
||||
uri: '${KIPRJMOD}/' + nick + '.pretty',
|
||||
options: '',
|
||||
descr: '',
|
||||
})),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
put(`${name}.kicad_pcb`, FormatBoard(board, 'pcbnew'));
|
||||
const screens = new SCH_SCREENS(schematic.Root()),
|
||||
writer = new SCH_IO_KICAD_SEXPR('eeschema');
|
||||
for (let i = 0; i < screens.GetCount(); i++) {
|
||||
@@ -162,6 +228,7 @@ export async function convertProject(
|
||||
...source,
|
||||
editing_copy: true,
|
||||
validation_state: 'unverified',
|
||||
...(checks ? { conversion_checks: checks } : {}),
|
||||
note: 'Converted editing copy. Original manufacturing checks apply only to the frozen original revision.',
|
||||
},
|
||||
null,
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import { useState } from 'react';
|
||||
import { SiteIcon } from './SiteIcon.js';
|
||||
import { ProjectCover } from './ProjectCover.js';
|
||||
import { errorText, useTr } from './ui.js';
|
||||
import { aiTitle } from './ai-projects.js';
|
||||
import type { Session } from '../codex-pcb/workbench-types.js';
|
||||
import type { SessionApi } from '../codex-pcb/session-api.js';
|
||||
import type { PcbProject } from './types.js';
|
||||
import type { useAiProjects } from './useAiProjects.js';
|
||||
|
||||
export type AiProjectActions = ReturnType<typeof useAiProjects>;
|
||||
export function AiProjectCard({
|
||||
task,
|
||||
cloud,
|
||||
actions,
|
||||
client,
|
||||
open,
|
||||
manage,
|
||||
}: {
|
||||
task: Session;
|
||||
cloud?: PcbProject;
|
||||
actions: AiProjectActions;
|
||||
client: SessionApi;
|
||||
open: (p: PcbProject) => void;
|
||||
manage: (kind: 'rename' | 'delete', project: PcbProject) => void;
|
||||
}) {
|
||||
const tr = useTr();
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const bundle = task.delivery?.files.find((f) => f.kind === 'bundle');
|
||||
const editable = cloud?.hasDocument || task.editing_status === 'available';
|
||||
const preparing = actions.preparing === task.id;
|
||||
const copyError = actions.failures[task.id];
|
||||
const title = cloud?.name || aiTitle(task);
|
||||
const message = cloud?.hasDocument
|
||||
? tr('编辑副本已保存到云端', 'Editing copy saved to cloud')
|
||||
: preparing
|
||||
? tr('正在准备编辑副本…', 'Preparing editing copy…')
|
||||
: task.editing_reason ||
|
||||
(task.state === 'completed'
|
||||
? tr('已完成交付', 'Delivered')
|
||||
: task.state === 'review'
|
||||
? tr('等待确认方案', 'Awaiting approval')
|
||||
: task.busy
|
||||
? tr('AI 生成中', 'AI design in progress')
|
||||
: tr('查看任务进度', 'View task progress'));
|
||||
const act = async (action: () => Promise<void>) => {
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
await action();
|
||||
} catch (e) {
|
||||
setError(errorText(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
const detailUrl = `${import.meta.env.BASE_URL}?${new URLSearchParams({ ai: '1', aiTask: task.id })}`;
|
||||
return (
|
||||
<article className="cad-card" aria-label={title}>
|
||||
<a
|
||||
className="cad-card-art"
|
||||
href={detailUrl}
|
||||
aria-label={`${tr('查看 AI 设计', 'View AI design')} ${title}`}
|
||||
>
|
||||
<ProjectCover url={cloud?.coverUrl ?? null} />
|
||||
</a>
|
||||
<div className="cad-card-body">
|
||||
<h2>{title}</h2>
|
||||
<small>AI · {message}</small>
|
||||
{(error || copyError) && (
|
||||
<p className="vm-error" role="alert">
|
||||
{error || copyError}
|
||||
</p>
|
||||
)}
|
||||
<div className="cad-card-actions" style={{ flexWrap: 'wrap', gap: 8 }}>
|
||||
{editable && (
|
||||
<button
|
||||
className="btn btn-sm"
|
||||
disabled={busy || preparing}
|
||||
onClick={() =>
|
||||
void act(async () => open(cloud?.hasDocument ? cloud : await actions.prepare(task)))
|
||||
}
|
||||
>
|
||||
{preparing
|
||||
? tr('正在准备…', 'Preparing…')
|
||||
: copyError
|
||||
? tr('重试打开', 'Retry opening')
|
||||
: tr('打开编辑器', 'Open editor')}
|
||||
</button>
|
||||
)}
|
||||
<a className="btn btn-sm" href={detailUrl}>
|
||||
{task.state === 'completed'
|
||||
? tr('查看交付', 'View delivery')
|
||||
: tr('查看进度', 'View progress')}
|
||||
</a>
|
||||
{cloud && (
|
||||
<>
|
||||
{(['rename', 'delete'] as const).map((kind) => {
|
||||
const label =
|
||||
kind === 'rename'
|
||||
? tr('重命名', 'Rename')
|
||||
: tr('删除编辑副本', 'Delete editing copy');
|
||||
return (
|
||||
<button
|
||||
key={kind}
|
||||
className="btn btn-sm"
|
||||
aria-label={`${label} ${title}`}
|
||||
title={label}
|
||||
onClick={() => manage(kind, cloud)}
|
||||
>
|
||||
<SiteIcon name={kind === 'rename' ? 'edit' : 'trash'} />
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
)}
|
||||
{bundle && (
|
||||
<button
|
||||
className="btn btn-sm"
|
||||
disabled={busy}
|
||||
onClick={() => void act(() => client.download(task.id, bundle))}
|
||||
>
|
||||
{tr('下载原始交付包', 'Original delivery ZIP')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
@@ -13,6 +13,9 @@ import {
|
||||
} from 'react';
|
||||
import { PlatformAuthProvider, MOCK, usePlatformAuth } from './auth.js';
|
||||
import { HttpPcbProjectApi } from './api.js';
|
||||
import { SessionApi } from '../codex-pcb/session-api.js';
|
||||
import { aiMarker } from './ai-projects.js';
|
||||
import { useAiProjects } from './useAiProjects.js';
|
||||
import { ProjectList } from './ProjectList.js';
|
||||
import { PlatformHeader } from './PlatformHeader.js';
|
||||
import { SiteIcon } from './SiteIcon.js';
|
||||
@@ -157,6 +160,9 @@ function Workspace({
|
||||
requests = useRef<AbortController | null>(null);
|
||||
const currentAuth = useRef(auth);
|
||||
currentAuth.current = auth;
|
||||
const aiClient = useMemo(() => auth.record && auth.status === 'authenticated' && import.meta.env.VITE_ENABLE_PCB_AI !== 'false'
|
||||
? new SessionApi(auth.record, () => currentAuth.current.current()) : null, [auth.record, auth.status]);
|
||||
const aiProjects = useAiProjects(aiClient, api, BUILD);
|
||||
const ask = useCallback(
|
||||
(title: string, body: ReactNode, options: Choice['options']): Promise<string> =>
|
||||
new Promise((resolve) => {
|
||||
@@ -459,6 +465,9 @@ function Workspace({
|
||||
sizeBytes: document.sizeBytes,
|
||||
};
|
||||
}
|
||||
if (!metadata.hasDocument && aiMarker(metadata)) {
|
||||
throw new Error('AI 编辑副本尚未保存到云端,请返回项目列表查看准备进度或重试。');
|
||||
}
|
||||
const drafts = await listDrafts(identity.user.userCode, code).catch(() => []);
|
||||
valid();
|
||||
if (drafts.length) {
|
||||
@@ -726,8 +735,8 @@ function Workspace({
|
||||
{tr('正在加载工程…', 'Loading project…')}
|
||||
</div>
|
||||
) : (
|
||||
<ProjectList
|
||||
api={api}
|
||||
<ProjectList key={auth.record?.user.userCode}
|
||||
api={api} ai={aiProjects} client={aiClient}
|
||||
open={(project) =>
|
||||
void go({
|
||||
code: project.pcbProjectCode,
|
||||
@@ -738,13 +747,12 @@ function Workspace({
|
||||
importProject={create}
|
||||
/>
|
||||
)}
|
||||
{!projectLibrary &&
|
||||
(activeWorkbench || new URLSearchParams(location.search).get('ai') === '1') &&
|
||||
{!projectLibrary && aiClient && auth.record &&
|
||||
allowed &&
|
||||
api &&
|
||||
auth.status === 'authenticated' && (
|
||||
<Suspense fallback={null}>
|
||||
<CodexPcbDock key={auth.record?.user.userCode} />
|
||||
<CodexPcbDock key={auth.record.user.userCode} owner={auth.record.user.userCode} client={aiClient} onProjectsChanged={aiProjects.refresh} locale={locale} />
|
||||
</Suspense>
|
||||
)}
|
||||
{!allowed && (
|
||||
|
||||
@@ -4,16 +4,19 @@ import type { NativeProject, PcbProject, PcbProjectApi } from './types.js';
|
||||
import { Modal, NameForm, errorText, useTr } from './ui.js';
|
||||
import { CircuitIcon } from './CircuitIcon.js';
|
||||
import { ProjectCover } from './ProjectCover.js';
|
||||
import { AiProjectCard, type AiProjectActions } from './AiProjectCard.js';
|
||||
import { projectPage, type ProjectRow } from './ai-projects.js';
|
||||
import type { SessionApi } from '../codex-pcb/session-api.js';
|
||||
import { SiteIcon } from './SiteIcon.js';
|
||||
import '../assets/site-brand/css/cad.css';
|
||||
const CatalogImport = lazy(() => import('./CatalogImport.js'));
|
||||
export function ProjectList({
|
||||
api,
|
||||
api, ai, client,
|
||||
open,
|
||||
create,
|
||||
importProject,
|
||||
}: {
|
||||
api: PcbProjectApi;
|
||||
api: PcbProjectApi; ai?: AiProjectActions; client?: SessionApi | null;
|
||||
open: (p: PcbProject) => void;
|
||||
create: (name: string, requestId: string) => Promise<void>;
|
||||
importProject: (name: string, project: NativeProject, requestId: string) => Promise<void>;
|
||||
@@ -24,7 +27,7 @@ export function ProjectList({
|
||||
[search, setSearch] = useState(''),
|
||||
[keyword, setKeyword] = useState(''),
|
||||
[refresh, setRefresh] = useState(0);
|
||||
const [result, setResult] = useState<{ items: PcbProject[]; total: number } | null>(null),
|
||||
const [result, setResult] = useState<{ items: ProjectRow[]; total: number } | null>(null),
|
||||
[error, setError] = useState<unknown>(null),
|
||||
[loading, setLoading] = useState(true);
|
||||
const [dialog, setDialog] = useState<{
|
||||
@@ -43,13 +46,13 @@ export function ProjectList({
|
||||
}, 250);
|
||||
return () => clearTimeout(timer);
|
||||
}, [search]);
|
||||
const sessionIndex = JSON.stringify(ai?.sessions.map(s => [s.id, s.project_code, s.proposal?.title]) ?? []);
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: refresh explicitly retries the same list request after a mutation or failure.
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
void api
|
||||
.list(page, keyword)
|
||||
void projectPage(api, page, keyword, ai?.sessions ?? [])
|
||||
.then(
|
||||
(data) => {
|
||||
if (alive) {
|
||||
@@ -68,7 +71,7 @@ export function ProjectList({
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [api, page, keyword, refresh]);
|
||||
}, [api, page, keyword, refresh, sessionIndex]);
|
||||
const close = (): void => {
|
||||
setDialog(null);
|
||||
setImported(null);
|
||||
@@ -150,6 +153,7 @@ export function ProjectList({
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
{ai?.error && <p className="vm-error" role="status">{tr('AI 项目暂时无法加载', 'AI projects unavailable')} · {ai.error} <button className="btn btn-sm" onClick={ai.refresh}>{tr('重试', 'Retry')}</button></p>}
|
||||
{loading ? (
|
||||
<div
|
||||
className="cad-grid"
|
||||
@@ -200,7 +204,13 @@ export function ProjectList({
|
||||
) : (
|
||||
<>
|
||||
<div className="cad-grid">
|
||||
{result.items.map((project) => (
|
||||
{result.items.map(row => {
|
||||
const task = row.task && ai?.sessions.find(s => s.id === row.task!.id);
|
||||
if (task && ai && client) return <AiProjectCard key={task.id} task={task} cloud={row.cloud}
|
||||
actions={ai} client={client} open={open} manage={(kind, project) => setDialog({ kind, project, requestId: crypto.randomUUID() })}/>;
|
||||
const project = row.cloud;
|
||||
if (!project) return null;
|
||||
return (
|
||||
<article className="cad-card" key={project.pcbProjectCode}>
|
||||
<a
|
||||
className="cad-card-art"
|
||||
@@ -247,7 +257,8 @@ export function ProjectList({
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<nav className="cad-pagination" aria-label={tr('分页', 'Pagination')}>
|
||||
<button className="btn btn-sm" disabled={page === 1} onClick={() => setPage(page - 1)}>
|
||||
@@ -309,6 +320,9 @@ export function ProjectList({
|
||||
.remove(dialog.project!.pcbProjectCode)
|
||||
.then(
|
||||
() => {
|
||||
const code = dialog.project!.pcbProjectCode;
|
||||
const task = ai?.sessions.find(item => item.project_code === code);
|
||||
if (task) ai!.markDeleted(task.id, code);
|
||||
close();
|
||||
setRefresh((n) => n + 1);
|
||||
},
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import { sessionPath, type SessionApi } from '../codex-pcb/session-api.js';
|
||||
import type { Session } from '../codex-pcb/workbench-types.js';
|
||||
import { archiveOperation, packProject } from './archive-client.js';
|
||||
import type { NativeProject, PcbProject, PcbProjectApi } from './types.js';
|
||||
|
||||
export const aiTitle = (task: Session) => task.proposal?.title || task.request;
|
||||
export function missingProject(error: unknown): boolean {
|
||||
const e = error as { status?: number; code?: string };
|
||||
return e?.status === 404 || e?.code === 'PCB_PROJECT_NOT_FOUND';
|
||||
}
|
||||
export const aiMarker = (project: PcbProject) =>
|
||||
/^AI PCB · [0-9a-f]{32}$/.test(project.description);
|
||||
export type ProjectRow = { cloud?: PcbProject; task?: Session };
|
||||
export async function projectPage(
|
||||
api: PcbProjectApi,
|
||||
page: number,
|
||||
keyword: string,
|
||||
sessions: Session[],
|
||||
): Promise<{ items: ProjectRow[]; total: number }> {
|
||||
const unbound = sessions.filter(
|
||||
(s) => !s.project_code && aiTitle(s).toLowerCase().includes(keyword.toLowerCase()),
|
||||
);
|
||||
const bound = new Map(sessions.filter((s) => s.project_code).map((s) => [s.project_code!, s]));
|
||||
const start = (page - 1) * 20;
|
||||
const rows: ProjectRow[] = unbound.slice(start, start + 20).map((task) => ({ task }));
|
||||
const skipCloud = Math.max(0, start - unbound.length);
|
||||
const cloudPage = Math.floor(skipCloud / 20) + 1;
|
||||
const offset = skipCloud % 20;
|
||||
const first = await api.list(cloudPage, keyword);
|
||||
const remaining = 20 - rows.length;
|
||||
const cloud = first.items.slice(offset, offset + remaining);
|
||||
if (cloud.length < remaining && skipCloud + cloud.length < first.total) {
|
||||
const next = await api.list(cloudPage + 1, keyword);
|
||||
cloud.push(...next.items.slice(0, remaining - cloud.length));
|
||||
}
|
||||
rows.push(
|
||||
...cloud.map((project) => ({ cloud: project, task: bound.get(project.pcbProjectCode) })),
|
||||
);
|
||||
return { items: rows, total: first.total + unbound.length };
|
||||
}
|
||||
|
||||
export async function ensureEditingProject(
|
||||
client: SessionApi,
|
||||
api: PcbProjectApi,
|
||||
id: string,
|
||||
build: string,
|
||||
signal: AbortSignal,
|
||||
allowRecreate = false,
|
||||
): Promise<PcbProject> {
|
||||
const path = sessionPath(id);
|
||||
const task = await client.json<Session>(path, undefined, signal);
|
||||
if (task.project_code) {
|
||||
try {
|
||||
const existing = await api.get(task.project_code, signal);
|
||||
if (existing.hasDocument) return existing;
|
||||
} catch (error) {
|
||||
if (!allowRecreate || !missingProject(error)) throw error;
|
||||
}
|
||||
}
|
||||
const source = task.delivery?.files.find((f) => f.kind === 'project');
|
||||
if (
|
||||
task.state !== 'completed' ||
|
||||
task.editing_status !== 'available' ||
|
||||
!source ||
|
||||
!task.manifest_sha256
|
||||
)
|
||||
throw new Error(task.editing_reason || '工程尚未具备创建编辑副本所需的源文件。');
|
||||
const bytes = new Uint8Array(await (await client.file(id, source, signal)).arrayBuffer());
|
||||
const limits = await api.capabilities();
|
||||
const editing = await archiveOperation<NativeProject>(
|
||||
{
|
||||
operation: 'ai-copy',
|
||||
bytes,
|
||||
limits,
|
||||
idOfTask: id,
|
||||
manifestHash: task.manifest_sha256,
|
||||
},
|
||||
signal,
|
||||
);
|
||||
const packed = await packProject(editing, build, limits, signal);
|
||||
signal.throwIfAborted();
|
||||
const { project_code: code } = await client.json<{ project_code: string }>(
|
||||
path + '/editing-project',
|
||||
{},
|
||||
signal,
|
||||
);
|
||||
const metadata = await api.get(code, signal);
|
||||
if (metadata.hasDocument) return metadata;
|
||||
if (metadata.version !== 0) throw new Error('云端工程已有版本,请刷新项目列表。');
|
||||
try {
|
||||
const signature = await api.sign(code, {
|
||||
fileName: 'project.zip',
|
||||
sizeBytes: packed.bytes.length,
|
||||
sha256: packed.sha256,
|
||||
expectedVersion: 0,
|
||||
clientOperationId: crypto.randomUUID(),
|
||||
archiveFormat: 'vibemake-pcb-project+zip',
|
||||
manifestVersion: 1,
|
||||
});
|
||||
signal.throwIfAborted();
|
||||
await api.upload(signature, packed.bytes);
|
||||
signal.throwIfAborted();
|
||||
const receipt = await api.commit(code, signature.uploadCode);
|
||||
if (receipt.version !== 1 || receipt.pcbProjectCode !== code)
|
||||
throw new Error('云端未确认编辑副本,请刷新后重试。');
|
||||
} catch (error) {
|
||||
// A competing tab may have committed version one or our response may have been lost.
|
||||
if (signal.aborted || !(await api.get(code, signal)).hasDocument) throw error;
|
||||
}
|
||||
const saved = await api.get(code, signal);
|
||||
if (!saved.hasDocument) throw new Error('云端尚未确认编辑副本,请刷新后重试。');
|
||||
return saved;
|
||||
}
|
||||
@@ -325,7 +325,8 @@ export class HttpPcbProjectApi implements PcbProjectApi {
|
||||
const form = new FormData();
|
||||
for (const [key, value] of Object.entries(signature.formFields)) form.append(key, value);
|
||||
form.append('file', new Blob([copyBytes(bytes)], { type: 'application/zip' }), 'project.zip');
|
||||
const response = await fetch(objectUrl(signature.uploadUrl), {
|
||||
const uploadUrl = new URL(objectUrl(signature.uploadUrl));
|
||||
const response = await fetch(uploadUrl.href, {
|
||||
method: 'POST',
|
||||
body: form,
|
||||
signal: AbortSignal.any([this.signal, AbortSignal.timeout(120000)]),
|
||||
@@ -333,6 +334,9 @@ export class HttpPcbProjectApi implements PcbProjectApi {
|
||||
referrerPolicy: 'no-referrer',
|
||||
});
|
||||
this.assert();
|
||||
if (response.status === 410 && uploadUrl.origin === location.origin &&
|
||||
/\/storage-transfer\/[^/]+$/.test(uploadUrl.pathname))
|
||||
throw new WorkspaceError('PCB_UPLOAD_EXPIRED', '存储中继票据已过期。', response.status);
|
||||
if (response.status !== 200)
|
||||
throw new WorkspaceError('PCB_OSS_ERROR', 'Upload failed', response.status);
|
||||
}
|
||||
|
||||
@@ -1,12 +1,19 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import { createArchive, openArchive } from './archive.js';
|
||||
import { createArchive, openArchive, importFiles } from './archive.js';
|
||||
import type { Capabilities, NativeProject } from './types.js';
|
||||
type Message = { id: number; limits: Capabilities } & (
|
||||
| { operation: 'ai-copy'; bytes: Uint8Array; idOfTask: string; manifestHash: string }
|
||||
| { operation: 'pack'; project: NativeProject; build: string }
|
||||
| { operation: 'open'; bytes: Uint8Array; requireManifest: boolean }
|
||||
);
|
||||
self.onmessage = async ({ data }: MessageEvent<Message>) => {
|
||||
try {
|
||||
if (data.operation === 'ai-copy') {
|
||||
const { convertAiEditingProject } = await import('../pcb-service/import-project.js');
|
||||
const copy = await convertAiEditingProject(data.bytes, 'board', { task_id: data.idOfTask, manifest_sha256: data.manifestHash });
|
||||
self.postMessage({ id: data.id, value: importFiles(copy.files, data.limits) });
|
||||
return;
|
||||
}
|
||||
const value =
|
||||
data.operation === 'pack'
|
||||
? await createArchive(data.project, data.build, data.limits)
|
||||
|
||||
@@ -383,7 +383,9 @@ export class WorkspaceRuntime implements ProjectSnapshotHost {
|
||||
);
|
||||
await Promise.all(this.writes.values());
|
||||
for (const [, participant] of ordered) {
|
||||
await participant.flush();
|
||||
// A visibility-triggered draft still flushes pending editor writes, but
|
||||
// an untouched frame need not materialize native settings defaults.
|
||||
await participant.flush(localOnly && !this.dirty ? 'clean-draft' : 'snapshot');
|
||||
await Promise.all(this.writes.values());
|
||||
this.assertActive();
|
||||
}
|
||||
@@ -662,12 +664,10 @@ export class WorkspaceRuntime implements ProjectSnapshotHost {
|
||||
await this.acknowledge(p, receipt);
|
||||
return;
|
||||
} catch (error) {
|
||||
if (
|
||||
['PCB_UPLOAD_EXPIRED', 'PCB_FILE_SIZE_MISMATCH'].includes(
|
||||
(error as WorkspaceError).code,
|
||||
) &&
|
||||
attempt === 0
|
||||
) {
|
||||
const code = (error as WorkspaceError).code;
|
||||
const relayExpired = (uploadError as WorkspaceError | undefined)?.code === 'PCB_UPLOAD_EXPIRED';
|
||||
if (attempt === 0 && (['PCB_UPLOAD_EXPIRED', 'PCB_FILE_SIZE_MISMATCH'].includes(code) ||
|
||||
(code === 'PCB_FILE_MISSING' && relayExpired))) {
|
||||
await this.abandonPending();
|
||||
this.pending = {
|
||||
...p,
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import type { SessionApi } from '../codex-pcb/session-api.js';
|
||||
import type { Session } from '../codex-pcb/workbench-types.js';
|
||||
import type { PcbProject, PcbProjectApi } from './types.js';
|
||||
import { ensureEditingProject, missingProject } from './ai-projects.js';
|
||||
|
||||
export function useAiProjects(client: SessionApi | null, api: PcbProjectApi | null, build: string) {
|
||||
const [sessions, setSessions] = useState<Session[]>([]);
|
||||
const [sessionOwner, setSessionOwner] = useState(client);
|
||||
const [error, setError] = useState('');
|
||||
const [preparing, setPreparing] = useState<string | null>(null);
|
||||
const [failures, setFailures] = useState<Record<string, string>>({});
|
||||
const [deleted, setDeleted] = useState<Record<string, string>>({});
|
||||
const markDeleted = useCallback((id: string, code: string) => {
|
||||
setDeleted((current) => ({ ...current, [id]: code }));
|
||||
}, []);
|
||||
const [revision, setRevision] = useState(0);
|
||||
const active = useRef<AbortController | null>(null);
|
||||
const queue = useRef<Promise<unknown>>(Promise.resolve());
|
||||
const jobs = useRef(new Map<string, Promise<PcbProject>>());
|
||||
const attempted = useRef(new Map<string, string>());
|
||||
const refresh = useCallback(() => setRevision((n) => n + 1), []);
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
active.current = controller;
|
||||
setSessionOwner(client);
|
||||
setSessions([]);
|
||||
setDeleted({});
|
||||
setError('');
|
||||
setFailures({});
|
||||
setPreparing(null);
|
||||
queue.current = Promise.resolve();
|
||||
jobs.current.clear();
|
||||
attempted.current.clear();
|
||||
return () => controller.abort();
|
||||
}, [client, api]);
|
||||
useEffect(() => {
|
||||
if (!api || !client) return;
|
||||
const controller = new AbortController();
|
||||
let timer: number;
|
||||
const poll = async () => {
|
||||
try {
|
||||
const list = await client.list(controller.signal);
|
||||
if (!controller.signal.aborted) {
|
||||
setSessions(list);
|
||||
setError('');
|
||||
}
|
||||
} catch (e) {
|
||||
if (!controller.signal.aborted) setError(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
if (!controller.signal.aborted) timer = window.setTimeout(poll, 15000);
|
||||
}
|
||||
};
|
||||
void poll();
|
||||
return () => {
|
||||
controller.abort();
|
||||
clearTimeout(timer);
|
||||
};
|
||||
}, [api, client, revision]);
|
||||
const prepare = useCallback(
|
||||
(task: Session, manual = true): Promise<PcbProject> => {
|
||||
const existing = jobs.current.get(task.id);
|
||||
if (existing) return existing;
|
||||
const signal = active.current?.signal;
|
||||
if (!api || !client || !signal || signal.aborted)
|
||||
return Promise.reject(new Error('请重新登录。'));
|
||||
const job = queue.current
|
||||
.catch(() => {})
|
||||
.then(async () => {
|
||||
signal.throwIfAborted();
|
||||
setPreparing(task.id);
|
||||
setFailures((current) => ({ ...current, [task.id]: '' }));
|
||||
const result = await ensureEditingProject(client, api, task.id, build, signal, manual);
|
||||
if (!signal.aborted) {
|
||||
// Synchronize immediately with the first cloud revision, without ever reseeding it.
|
||||
attempted.current.set(task.id, result.pcbProjectCode);
|
||||
setSessions((current) =>
|
||||
current.map((s) =>
|
||||
s.id === task.id ? { ...s, project_code: result.pcbProjectCode } : s,
|
||||
),
|
||||
);
|
||||
if (!task.project_code) refresh();
|
||||
}
|
||||
return result;
|
||||
})
|
||||
.catch((e) => {
|
||||
if (!signal.aborted) {
|
||||
if (!manual && task.project_code && missingProject(e))
|
||||
markDeleted(task.id, task.project_code);
|
||||
else
|
||||
setFailures((current) => ({
|
||||
...current,
|
||||
[task.id]: e instanceof Error ? e.message : String(e),
|
||||
}));
|
||||
}
|
||||
throw e;
|
||||
})
|
||||
.finally(() => {
|
||||
if (!signal.aborted) {
|
||||
jobs.current.delete(task.id);
|
||||
setPreparing(null);
|
||||
}
|
||||
});
|
||||
queue.current = job;
|
||||
jobs.current.set(task.id, job);
|
||||
return job;
|
||||
},
|
||||
[api, client, build, refresh, markDeleted],
|
||||
);
|
||||
useEffect(() => {
|
||||
if (!api || !client) return;
|
||||
if (client !== sessionOwner) return;
|
||||
for (const task of sessions) {
|
||||
if (task.state !== 'completed' || task.editing_status !== 'available') continue;
|
||||
const key = task.project_code || task.manifest_sha256 || 'new';
|
||||
if (attempted.current.get(task.id) === key || deleted[task.id] === key) continue;
|
||||
attempted.current.set(task.id, key);
|
||||
void prepare(task, false).catch(() => {});
|
||||
}
|
||||
}, [sessions, sessionOwner, api, client, prepare, deleted]);
|
||||
const visibleSessions = (sessionOwner === client ? sessions : []).map((s) =>
|
||||
s.project_code && deleted[s.id] === s.project_code
|
||||
? { ...s, project_code: null, editing_reason: '编辑副本已删除,可重新打开生成。' }
|
||||
: s,
|
||||
);
|
||||
return { sessions: visibleSessions, error, preparing, failures, prepare, refresh, markDeleted };
|
||||
}
|
||||
@@ -68,7 +68,7 @@ const uploadMaps = telemetryEnabled && !!(SENTRY_ORG && SENTRY_PROJECT && SENTRY
|
||||
const APP_BASE = process.env.VITE_BASE ?? '/pcb/';
|
||||
function pcbProxy(): import('vite').ProxyOptions {
|
||||
return {
|
||||
target: process.env.PCB_API_TARGET || 'http://39.105.93.138:8003',
|
||||
target: process.env.PCB_API_TARGET || 'http://127.0.0.1:8003',
|
||||
changeOrigin: true,
|
||||
rewrite: (path: string) => '/api' + path.slice(`${APP_BASE}pcb-api`.length),
|
||||
configure: (proxy) => {
|
||||
|
||||
@@ -35,6 +35,16 @@
|
||||
|
||||
现有页面保留新建、导入、搜索、重命名、删除。封面在工程保存确认后自动生成,不增加手工封面编辑器。重命名不改变封面。
|
||||
|
||||
## AI 交付的网页编辑副本
|
||||
|
||||
登录用户在「我的 PCB 项目」中可以查看自己的 AI 任务。提交需求时绘板服务核验平台用户身份,历史任务的归属核实方法见 [绘板服务部署说明](../../codex_pcb/DEPLOY.md)。
|
||||
|
||||
登录后打开工作台,网页会为该用户已完成且兼容的任务准备编辑副本。原理图和板图通过转换核对后,网页用平台的云工程签名、上传和确认接口保存初始版本。重新打开已有副本将加载最新云版本。人工编辑仅更新这个云工程,任务卡上的「下载原始交付包」始终指向嘉立创的原始交付。
|
||||
|
||||
对于新版嘉立创归档、多板工程或网络核对不通过的工程,卡片会说明原因,用户仍可进入任务和下载原件。编辑副本沿用网页编辑器的保存和版本冲突处理流程。改变设计后,应针对修改后的版本重新检查。
|
||||
|
||||
自建网站若使用内网域名或 IP,且对象存储未允许该网页来源,可在静态服务器环境设置 `PCB_OBJECT_RELAY=1`。站点代理会为平台签发的上传和下载地址生成本站短时地址,文件仍保存到平台对象存储。通过 `PCB_OBJECT_ORIGINS` 限定该部署使用的 HTTPS 存储源站。直接连接对象存储的部署可继续使用原有 CORS 配置。
|
||||
|
||||
## 自动项目封面
|
||||
|
||||
- 从本次确认的原生 ZIP 重新解析并导出,不截取当前屏幕。PCB 有内容时使用完整二维顶视图;空板回退根原理图;两者都为空则恢复默认占位图。板外元件计入边界,默认不使用三维视角。
|
||||
|
||||
@@ -17,6 +17,12 @@ MIT 许可证随 `designer/public/licenses/driver.js-LICENSE.txt` 发布。
|
||||
“更多”中的复选框可以重新打开自动提示。这与当前 CAD 行为一致。
|
||||
- 同一账号一次页面访问仅自动提示一次,切换工程或重新挂载工作区不重复提示。
|
||||
|
||||
## AI 绘板工作台
|
||||
|
||||
首次打开 AI PCB 工作台时,欢迎框会邀请用户了解绘板流程。用户可跟随高亮依次查看新建设计、填写需求、审核方案、查看原理图和布线进度、处理暂停以及下载交付文件。任务处于待审核阶段时,引导还会指向当前版本的确认按钮。
|
||||
|
||||
顶部的「使用引导」可以随时重播。完成或选择「不再提示」后,该浏览器上的同一账号只会在手动重播时看到引导。「本次跳过」仅对当前访问生效。AI 工作台使用独立的账号偏好键 `vm.pcb.ai-onboarding.<encodeURIComponent(账号 ID)>`。
|
||||
|
||||
## 实现边界
|
||||
|
||||
- `designer/src/onboarding/preferences.ts`:校验、读写账号偏好。
|
||||
|
||||
@@ -858,6 +858,10 @@ export function SchematicEditor({
|
||||
docs: new Map(initial ? [[DEFAULT_FILE, initial]] : []),
|
||||
root: DEFAULT_FILE,
|
||||
});
|
||||
// Imported records may have a different canonical serialization from their cloud
|
||||
// bytes. Track the exact record held by the host for each sheet, including across
|
||||
// sheet switches, so a read-only view or an autosave flush preserves those bytes.
|
||||
const writtenSheets = useRef(new Map(project.current.docs));
|
||||
const [currentFile, setCurrentFile] = useState<string>(DEFAULT_FILE);
|
||||
// The active sheet *instance* (KiCad SCH_SHEET_PATH). Distinct from currentFile
|
||||
// so two instances of one shared document highlight/navigate independently.
|
||||
@@ -3741,6 +3745,7 @@ export function SchematicEditor({
|
||||
// Page numbers are made whole before anything reads the hierarchy
|
||||
// (files-io.cpp:439-446): a blank or duplicated page is reassigned
|
||||
// and, when that happened, the user is told the file needs saving.
|
||||
writtenSheets.current = new Map(docs);
|
||||
const pageRepair = repairPageNumbersOnLoad(docs, root);
|
||||
for (const [name, d] of pageRepair.docs) docs.set(name, d);
|
||||
if (pageRepair.repaired) setLoadRepairedMessage(LOAD_REPAIRED_MESSAGE);
|
||||
@@ -3860,44 +3865,39 @@ export function SchematicEditor({
|
||||
unsaved ? doc : undefined,
|
||||
);
|
||||
// Serialize the project's sheets (current sheet + resident others) for autosave.
|
||||
const serializeSheets = useCallback((): PickedFile[] => {
|
||||
if (!doc) return [];
|
||||
const writeChangedSheets = useCallback(() => {
|
||||
if (!doc || !onProjectChange) return;
|
||||
const docs = new Map(project.current.docs);
|
||||
docs.set(currentFile, doc);
|
||||
const files: PickedFile[] = [];
|
||||
for (const [file, d] of docs) {
|
||||
if (snapshotHost && writtenSheets.current.get(file) === d) continue;
|
||||
try {
|
||||
files.push({ name: file, text: serializeSchematic(d) });
|
||||
} catch (error) {
|
||||
if (snapshotHost) throw error;
|
||||
/* skip a bad sheet */
|
||||
}
|
||||
}
|
||||
return files;
|
||||
}, [doc, currentFile, snapshotHost]);
|
||||
if (!files.length) return;
|
||||
onProjectChange(files);
|
||||
if (snapshotHost) {
|
||||
for (const file of files) writtenSheets.current.set(file.name, docs.get(file.name)!);
|
||||
}
|
||||
}, [doc, currentFile, onProjectChange, snapshotHost]);
|
||||
|
||||
// Autosave: once edits settle, hand the sheets up (App debounces the write to
|
||||
// IndexedDB). Fires on sheet switch/load too, re-saving identical content.
|
||||
useEffect(() => {
|
||||
if (!doc || !onProjectChange) return;
|
||||
const t = setTimeout(() => {
|
||||
const files = serializeSheets();
|
||||
if (files.length) onProjectChange(files);
|
||||
}, 900);
|
||||
return () => clearTimeout(t);
|
||||
}, [doc, onProjectChange, serializeSheets]);
|
||||
const timer = setTimeout(writeChangedSheets, 900);
|
||||
return () => clearTimeout(timer);
|
||||
}, [writeChangedSheets]);
|
||||
|
||||
// Register a flush so the host can force the pending autosave out before the
|
||||
// project is reopened (the "edit → home → reopen" case).
|
||||
useEffect(() => {
|
||||
if (!registerAutosaveFlush) return;
|
||||
registerAutosaveFlush(() => {
|
||||
const files = serializeSheets();
|
||||
if (files.length) onProjectChange?.(files);
|
||||
writeChangedSheets();
|
||||
if (snapshotHost) setUnsaved(false);
|
||||
});
|
||||
return () => registerAutosaveFlush(null);
|
||||
}, [registerAutosaveFlush, onProjectChange, serializeSheets, snapshotHost]);
|
||||
}, [registerAutosaveFlush, writeChangedSheets, snapshotHost]);
|
||||
|
||||
// Switch the visible sheet (KiCad's Enter Sheet / hierarchy navigation): stash
|
||||
// the edited current sheet back into the project, swap in the target document
|
||||
@@ -3987,7 +3987,7 @@ export function SchematicEditor({
|
||||
// on every close.
|
||||
useUnsavedGuard(!autosaveActive && unsaved);
|
||||
useEffect(() => {
|
||||
if (dirtySkipRef.current) {
|
||||
if (dirtySkipRef.current || (snapshotHost && doc === writtenSheets.current.get(currentFile))) {
|
||||
dirtySkipRef.current = false;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ Environment=HOST=192.168.1.200
|
||||
Environment=PORT=15182
|
||||
Environment=PUBLIC_ORIGIN=https://192.168.1.200:15182
|
||||
Environment=PCB_API_TARGET=http://127.0.0.1:8003
|
||||
Environment=PCB_OBJECT_RELAY=1
|
||||
Environment=TLS_CERT=/home/wpz/auto_pcb/runtime/lan-https/server.crt
|
||||
Environment=TLS_KEY=/home/wpz/auto_pcb/runtime/lan-https/server.key
|
||||
ExecStart=/home/wpz/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/bin/node scripts/serve.mjs
|
||||
|
||||
@@ -3144,8 +3144,8 @@ export function PcbEditor({
|
||||
useProjectSnapshot(
|
||||
'pcb-safety',
|
||||
{
|
||||
flush: () => {
|
||||
if (snapshotHost) saveProjectLocalSettings();
|
||||
flush: (reason) => {
|
||||
if (snapshotHost && reason !== 'clean-draft') saveProjectLocalSettings();
|
||||
},
|
||||
isBusy: () =>
|
||||
platformImportBusy.current ||
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import { beforeEach, expect, it, vi } from 'vitest';
|
||||
import { ensureEditingProject, projectPage } from '../../../designer/src/platform/ai-projects.js';
|
||||
import { SessionApi } from '../../../designer/src/codex-pcb/session-api.js';
|
||||
import type { Session } from '../../../designer/src/codex-pcb/workbench-types.js';
|
||||
import {
|
||||
WorkspaceError,
|
||||
type PcbProject,
|
||||
type PcbProjectApi,
|
||||
} from '../../../designer/src/platform/types.js';
|
||||
import { archiveOperation, packProject } from '../../../designer/src/platform/archive-client.js';
|
||||
|
||||
vi.mock('../../../designer/src/platform/archive-client.js', () => ({
|
||||
archiveOperation: vi.fn(),
|
||||
packProject: vi.fn(),
|
||||
}));
|
||||
const cloud = (n: number): PcbProject => ({
|
||||
pcbProjectCode: `project-${n}`,
|
||||
name: `Project ${n}`,
|
||||
description: '',
|
||||
version: 0,
|
||||
hasDocument: false,
|
||||
fileName: '',
|
||||
sizeBytes: 0,
|
||||
savedAt: null,
|
||||
coverUrl: null,
|
||||
createdAt: '',
|
||||
updatedAt: '',
|
||||
});
|
||||
const task = (id: string, project_code: string | null = null): Session => ({
|
||||
id,
|
||||
project_code,
|
||||
editing_status: 'available',
|
||||
manifest_sha256: 'a'.repeat(64),
|
||||
state: 'completed',
|
||||
busy: false,
|
||||
request: `AI ${id}`,
|
||||
created_at: 0,
|
||||
cursor: 0,
|
||||
delivery: {
|
||||
notes: '',
|
||||
files: [
|
||||
{ kind: 'project', name: 'board.epro', bytes: 10, sha256: 'b'.repeat(64), label: 'source' },
|
||||
],
|
||||
},
|
||||
});
|
||||
const controller = () => new AbortController().signal;
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
it('pages cloud and unbound AI rows together without duplicates when tasks acquire a cloud project', async () => {
|
||||
const projects = Array.from({ length: 46 }, (_, i) => cloud(i));
|
||||
const api = {
|
||||
list: vi.fn(async (page: number) => ({
|
||||
items: projects.slice((page - 1) * 20, page * 20),
|
||||
total: projects.length,
|
||||
})),
|
||||
} as unknown as PcbProjectApi;
|
||||
const tasks = [task('draft'), task('existing', 'project-3')];
|
||||
const pages = await Promise.all([1, 2, 3].map((i) => projectPage(api, i, '', tasks)));
|
||||
expect(pages.map((p) => p.items.length)).toEqual([20, 20, 7]);
|
||||
expect(pages.map((p) => p.total)).toEqual([47, 47, 47]);
|
||||
const rows = pages.flatMap((p) => p.items);
|
||||
expect(rows.flatMap((r) => r.task?.id || [])).toEqual(['draft', 'existing']);
|
||||
expect(rows.flatMap((r) => r.cloud?.pcbProjectCode || [])).toEqual(
|
||||
projects.map((p) => p.pcbProjectCode),
|
||||
);
|
||||
});
|
||||
|
||||
it('opens an existing cloud version without reading or uploading the original delivery', async () => {
|
||||
const metadata = { ...cloud(5), version: 8, hasDocument: true };
|
||||
const client = {
|
||||
json: vi.fn(async () => task('hdmi', metadata.pcbProjectCode)),
|
||||
} as unknown as SessionApi;
|
||||
const api = { get: vi.fn(async () => metadata) } as unknown as PcbProjectApi;
|
||||
expect(await ensureEditingProject(client, api, 'hdmi', 'test', controller())).toEqual(metadata);
|
||||
expect(archiveOperation).not.toHaveBeenCalled();
|
||||
expect(client.json).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('only initializes version zero and accepts another browser winning the first save', async () => {
|
||||
const metadata = cloud(9),
|
||||
saved = { ...metadata, hasDocument: true, version: 1 };
|
||||
const item = task('hdmi');
|
||||
const client = {
|
||||
json: vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(item)
|
||||
.mockResolvedValueOnce({ project_code: metadata.pcbProjectCode }),
|
||||
file: vi.fn(async () => new Blob(['fixture'])),
|
||||
} as unknown as SessionApi;
|
||||
const api = {
|
||||
get: vi.fn().mockResolvedValueOnce(metadata).mockResolvedValue(saved),
|
||||
capabilities: vi.fn(async () => ({})),
|
||||
sign: vi.fn().mockResolvedValue({ uploadCode: 'upload-id' }),
|
||||
upload: vi.fn().mockResolvedValue(undefined),
|
||||
commit: vi.fn().mockRejectedValue(new WorkspaceError('PCB_VERSION_CONFLICT')),
|
||||
} as unknown as PcbProjectApi;
|
||||
vi.mocked(archiveOperation).mockResolvedValue({});
|
||||
vi.mocked(packProject).mockResolvedValue({
|
||||
bytes: new Uint8Array(23),
|
||||
sha256: 'hash',
|
||||
manifest: {} as never,
|
||||
});
|
||||
expect(await ensureEditingProject(client, api, item.id, 'test', controller())).toEqual(saved);
|
||||
expect(api.sign).toHaveBeenCalledWith(
|
||||
metadata.pcbProjectCode,
|
||||
expect.objectContaining({ expectedVersion: 0 }),
|
||||
);
|
||||
expect(api.upload).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('keeps unsupported and explicitly deleted cloud copies from creating empty projects automatically', async () => {
|
||||
const item = task('new-format');
|
||||
const client = {
|
||||
json: vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce({
|
||||
...item,
|
||||
editing_status: 'unsupported',
|
||||
editing_reason: '新版文件暂不支持',
|
||||
})
|
||||
.mockResolvedValueOnce({ ...item, project_code: 'deleted' }),
|
||||
} as unknown as SessionApi;
|
||||
const api = {
|
||||
get: vi.fn().mockRejectedValue(new WorkspaceError('PCB_PROJECT_NOT_FOUND', 'deleted', 404)),
|
||||
} as unknown as PcbProjectApi;
|
||||
await expect(ensureEditingProject(client, api, item.id, 'test', controller())).rejects.toThrow(
|
||||
'新版文件暂不支持',
|
||||
);
|
||||
await expect(ensureEditingProject(client, api, item.id, 'test', controller())).rejects.toThrow(
|
||||
'deleted',
|
||||
);
|
||||
expect(client.json).toHaveBeenCalledTimes(2);
|
||||
expect(archiveOperation).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('refuses to use a captured login after an account switch', async () => {
|
||||
const owner = { token: 'test-a', user: { userCode: 'a' }, expiresAt: Infinity };
|
||||
const other = { ...owner, token: 'test-b', user: { userCode: 'b' } };
|
||||
const client = new SessionApi(owner, () => other);
|
||||
await expect(client.list()).rejects.toThrow('登录账号已更换');
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
|
||||
import { afterEach, expect, it, vi } from 'vitest';
|
||||
import { useAiProjects } from '../../../designer/src/platform/useAiProjects.js';
|
||||
import type { SessionApi } from '../../../designer/src/codex-pcb/session-api.js';
|
||||
import type { Session } from '../../../designer/src/codex-pcb/workbench-types.js';
|
||||
import type { PcbProjectApi } from '../../../designer/src/platform/types.js';
|
||||
import { sessionClient } from './pcb_session_fixture.js';
|
||||
|
||||
afterEach(() => { cleanup(); vi.unstubAllGlobals(); });
|
||||
const planning = (id:string): Session => ({ id, request:id, busy:true, created_at:0, cursor:0,
|
||||
project_code:null, state:'planning', editing_status:'pending' });
|
||||
|
||||
it('discards an old account response even if it arrives after the new owner’s list', async () => {
|
||||
let finishList!: (items: Session[]) => void;
|
||||
const late = new Promise<Session[]>(resolve => { finishList = resolve; });
|
||||
const clientA = { list:vi.fn().mockResolvedValueOnce([planning('A-1')]).mockReturnValueOnce(late) } as unknown as SessionApi;
|
||||
const clientB = { list:vi.fn().mockResolvedValue([planning('B-1')]) } as unknown as SessionApi;
|
||||
const api = {} as PcbProjectApi;
|
||||
const hook = renderHook(({client}) => useAiProjects(client,api,'test'),{initialProps:{client:clientA}});
|
||||
await waitFor(() => expect(hook.result.current.sessions.map(s=>s.id)).toEqual(['A-1']));
|
||||
act(() => hook.result.current.refresh());
|
||||
await waitFor(() => expect(clientA.list).toHaveBeenCalledTimes(2));
|
||||
hook.rerender({client:clientB});
|
||||
expect(hook.result.current.sessions.some(s=>s.id.startsWith('A'))).toBe(false);
|
||||
await waitFor(() => expect(hook.result.current.sessions.map(s=>s.id)).toEqual(['B-1']));
|
||||
await act(async () => { finishList([planning('A-late')]); await late; });
|
||||
expect(hook.result.current.sessions.map(s=>s.id)).toEqual(['B-1']);
|
||||
});
|
||||
|
||||
it('does not display a global session list from an older AI service', async () => {
|
||||
vi.stubGlobal('fetch',vi.fn().mockResolvedValue(Response.json([{id:'other-owner'}])));
|
||||
await expect(sessionClient.list()).rejects.toThrow('账号归属');
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { sessionClient } from "./pcb_session_fixture.js";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { DeliveryModel3D } from '../../../designer/src/codex-pcb/DeliveryModel3D.js';
|
||||
@@ -9,7 +10,7 @@ vi.mock('../../../designer/src/codex-pcb/model-appearance.js', () => ({
|
||||
}));
|
||||
vi.mock('../../../designer/src/pcb-service/project-model-obj.js', () => ({ mountProjectObj: mocks.obj }));
|
||||
vi.mock('../../../designer/src/codex-pcb/delivery-step-viewer.js', () => ({ mountDeliveryStep: mocks.step }));
|
||||
const props = { url: '/board.step', sha256: 'step-sha', name: 'board.step', objUrl: '/board.zip', objSha256: 'obj-sha' };
|
||||
const props = { client: sessionClient, download: vi.fn(), url: '/board.step', sha256: 'step-sha', name: 'board.step', objUrl: '/board.zip', objSha256: 'obj-sha' };
|
||||
const viewer = () => ({ reset: vi.fn(), dispose: mocks.dispose });
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
@@ -24,10 +25,11 @@ describe('delivery 3D source recovery', () => {
|
||||
it('uses verified OBJ directly even for colored STEP, without downloading or parsing STEP', async () => {
|
||||
render(<DeliveryModel3D {...props} />);
|
||||
await ready();
|
||||
expect(mocks.read).toHaveBeenCalledWith('/board.zip', 'obj-sha', expect.any(AbortSignal), 64 * 1024 * 1024);
|
||||
expect(mocks.read).toHaveBeenCalledWith('/board.zip', 'obj-sha', expect.any(AbortSignal), 64 * 1024 * 1024, sessionClient.fetch);
|
||||
expect(mocks.read).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.step).not.toHaveBeenCalled();
|
||||
expect(screen.getByRole('link', { name: /下载 STEP/ }).getAttribute('href')).toBe('/board.step');
|
||||
fireEvent.click(screen.getByRole('button', { name: /下载 STEP/ }));
|
||||
expect(props.download).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('recovers from empty STEP geometry and permits a later STEP retry', async () => {
|
||||
@@ -64,7 +66,7 @@ describe('delivery 3D source recovery', () => {
|
||||
mocks.step.mockRejectedValueOnce(new Error('STEP 空网格'));
|
||||
render(<DeliveryModel3D {...props} />);
|
||||
await screen.findByText(/两种三维预览均未能加载/);
|
||||
expect(screen.getByRole('link', { name: /下载 STEP/ })).toBeTruthy();
|
||||
expect(screen.getByRole('button', { name: /下载 STEP/ })).toBeTruthy();
|
||||
fireEvent.click(screen.getByRole('button', { name: '重新加载模型' }));
|
||||
await ready();
|
||||
expect(mocks.obj).toHaveBeenCalledTimes(2);
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { expect, it } from 'vitest';
|
||||
import { zipSync } from 'fflate';
|
||||
import { loadKicadNetlist } from '@ziroeda/common/netlist_reader/kicad_netlist_reader.js';
|
||||
import { exportKicadNetlist } from '@ziroeda/eeschema/cross-probing.js';
|
||||
import { convertAiEditingProject } from '@ziroeda/designer/src/pcb-service/import-project.js';
|
||||
import { createArchive, importFiles, openArchive } from '@ziroeda/designer/src/platform/archive.js';
|
||||
import {
|
||||
FormatBoard,
|
||||
ParseBoard,
|
||||
ParseFootprintFile,
|
||||
} from '@ziroeda/pcbnew/pcb_io/kicad_sexpr/pcb_io_kicad_sexpr.js';
|
||||
|
||||
const source = { task_id: 'fixture', manifest_sha256: 'digest' };
|
||||
const enc = new TextEncoder(),
|
||||
dec = new TextDecoder();
|
||||
|
||||
it('explains why modern and ambiguous multi-board EasyEDA sources remain download-only', async () => {
|
||||
await expect(
|
||||
convertAiEditingProject(zipSync({ 'project2.json': enc.encode('{}') }), 'board', source),
|
||||
).rejects.toThrow('新版嘉立创格式');
|
||||
const project = { pcbs: { a: 'PCB1', b: 'PCB2' }, schematics: { sch: {} } };
|
||||
await expect(
|
||||
convertAiEditingProject(
|
||||
zipSync({ 'project.json': enc.encode(JSON.stringify(project)) }),
|
||||
'board',
|
||||
source,
|
||||
),
|
||||
).rejects.toThrow('多块板');
|
||||
});
|
||||
|
||||
it.runIf(!!process.env.HDMI_EDITING_FIXTURE)(
|
||||
'opens, moves, saves and reopens the HDMI board while keeping footprint links and all connector shell pads',
|
||||
async () => {
|
||||
const bytes = readFileSync(process.env.HDMI_EDITING_FIXTURE!);
|
||||
const hash = () => createHash('sha256').update(bytes).digest('hex');
|
||||
const original = hash();
|
||||
const { files } = await convertAiEditingProject(bytes, 'HDMI-edit', source);
|
||||
const p = importFiles(files);
|
||||
const boardFile = p.files.find((f) => f.name === p.roots.board)!;
|
||||
const b = ParseBoard(dec.decode(boardFile.bytes));
|
||||
const u1 = b.Footprints().find((f) => f.GetReference() === 'U1')!;
|
||||
const position = { ...u1.GetPosition(), x: u1.GetPosition().x + 1_000_000 };
|
||||
u1.SetPosition(position);
|
||||
boardFile.bytes = enc.encode(FormatBoard(b));
|
||||
const reopened = await openArchive((await createArchive(p, 'qa')).bytes);
|
||||
const read = (name: string) => dec.decode(reopened.files.find((f) => f.name === name)!.bytes);
|
||||
const saved = ParseBoard(read(reopened.roots.board!));
|
||||
expect(
|
||||
saved
|
||||
.Footprints()
|
||||
.find((f) => f.GetReference() === 'U1')!
|
||||
.GetPosition(),
|
||||
).toEqual(position);
|
||||
expect(hash()).toBe(original);
|
||||
expect(saved.GetCopperLayerCount()).toBe(4);
|
||||
expect(saved.Tracks()).toHaveLength(954);
|
||||
const nets = exportKicadNetlist(
|
||||
reopened.files.map((f) => ({ name: f.name, text: dec.decode(f.bytes) })),
|
||||
reopened.roots.schematic!,
|
||||
reopened.roots.project!,
|
||||
);
|
||||
if (!nets.ok) throw Error(nets.error);
|
||||
const parts = loadKicadNetlist(nets.netlistText);
|
||||
expect(parts.GetCount()).toBe(57);
|
||||
expect(saved.Footprints().filter((f) => f.IsBoardOnly())).toHaveLength(4);
|
||||
for (const fp of saved.Footprints().filter((f) => !f.IsBoardOnly())) {
|
||||
const part = parts.GetComponentByPath('/' + fp.GetPath().join('/'))!;
|
||||
expect(part.GetReference()).toBe(fp.GetReference());
|
||||
expect(part.GetFPID()).toBe(fp.GetFPIDAsString());
|
||||
for (const pad of fp.Pads().filter((p) => p.GetNetname()))
|
||||
expect(part.GetNet(pad.GetNumber()).netName).toBe(pad.GetNetname());
|
||||
}
|
||||
const shells = saved
|
||||
.Footprints()
|
||||
.find((f) => f.GetReference() === 'J3')!
|
||||
.Pads()
|
||||
.filter((p) => p.GetNumber() === '0');
|
||||
expect(shells.map((p) => p.GetNetname())).toEqual(Array(4).fill('/GND'));
|
||||
const libraries = reopened.files.filter((f) => f.name.endsWith('.kicad_mod'));
|
||||
expect(libraries).toHaveLength(20);
|
||||
for (const fp of libraries)
|
||||
expect(ParseFootprintFile(dec.decode(fp.bytes)).Pads().length).toBeGreaterThan(0);
|
||||
expect(read('fp-lib-table')).toContain('${KIPRJMOD}');
|
||||
expect(JSON.parse(read('AI-SOURCE.json')).conversion_checks).toMatchObject({
|
||||
linked_components: 57,
|
||||
connected_physical_pads: 224,
|
||||
connected_pad_numbers: 221,
|
||||
});
|
||||
},
|
||||
60_000,
|
||||
);
|
||||
@@ -0,0 +1,206 @@
|
||||
// @vitest-environment happy-dom
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
PcbOnboarding,
|
||||
type Config,
|
||||
type Driver,
|
||||
type PcbTourContext,
|
||||
} from '@ziroeda/designer/src/onboarding/pcb-onboarding.js';
|
||||
import { readTourPreferences } from '@ziroeda/designer/src/onboarding/preferences.js';
|
||||
|
||||
const steps = ['tasks', 'request', 'proposal', 'approve', 'preview', 'conversation', 'delivery'];
|
||||
let account = 0;
|
||||
const tours = new Set<PcbOnboarding>();
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
localStorage.clear();
|
||||
vi.stubGlobal('innerWidth', 1360);
|
||||
vi.stubGlobal('innerHeight', 900);
|
||||
vi.stubGlobal('matchMedia', () => ({ matches: true }));
|
||||
vi.stubGlobal('ResizeObserver', class {
|
||||
observe() {}
|
||||
disconnect() {}
|
||||
});
|
||||
vi.spyOn(document, 'hidden', 'get').mockReturnValue(false);
|
||||
vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue(new DOMRect(10, 10, 200, 120));
|
||||
vi.spyOn(HTMLDialogElement.prototype, 'showModal').mockImplementation(function () {
|
||||
this.setAttribute('open', '');
|
||||
});
|
||||
vi.spyOn(HTMLDialogElement.prototype, 'close').mockImplementation(function () {
|
||||
this.removeAttribute('open');
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const tour of tours) tour.dispose();
|
||||
tours.clear();
|
||||
document.body.replaceChildren();
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
function workbench() {
|
||||
const editor = document.createElement('section');
|
||||
editor.className = 'vm-workbench';
|
||||
editor.innerHTML = '<div data-pcb-editor><div data-pcb-tour="canvas"></div></div>';
|
||||
const portal = document.createElement('div');
|
||||
portal.className = 'cp-root';
|
||||
portal.dataset.pcbTourBlocked = 'true';
|
||||
portal.innerHTML = `
|
||||
<section class="cp-workbench cp-window">
|
||||
<select data-ai-pcb-tour="tasks"><option value="motor">电机控制板</option></select>
|
||||
<textarea data-ai-pcb-tour="request">保留这段需求</textarea>
|
||||
<button data-ai-pcb-tour="proposal">设计方案</button>
|
||||
<button data-ai-pcb-tour="approve">批准并开始绘制</button>
|
||||
<div data-ai-pcb-tour="preview">PCB</div>
|
||||
<button data-ai-pcb-tour="conversation">运行记录</button>
|
||||
<button data-ai-pcb-tour="delivery">交付文件</button>
|
||||
<button data-ai-pcb-tour-help>使用引导</button>
|
||||
</section>`;
|
||||
document.body.append(editor, portal);
|
||||
const root = portal.querySelector<HTMLElement>('.cp-workbench')!;
|
||||
return { root, portal, editor: editor.querySelector<HTMLElement>('[data-pcb-editor]')! };
|
||||
}
|
||||
|
||||
function mount(root: HTMLElement, owner: string, surface: 'ai' | 'editor' = 'ai') {
|
||||
const ctx: PcbTourContext = {
|
||||
...(surface === 'ai' ? { surface: 'ai' as const } : {}),
|
||||
owner,
|
||||
binding: surface + '-binding',
|
||||
locale: 'zh',
|
||||
available: true,
|
||||
source: { root, isReady: () => true, isBusy: () => false },
|
||||
};
|
||||
let config: Config = {};
|
||||
const driver = {
|
||||
drive: vi.fn(),
|
||||
destroy: vi.fn(),
|
||||
refresh: vi.fn(),
|
||||
getActiveElement: () => root.querySelector('[data-ai-pcb-tour="tasks"]'),
|
||||
} as unknown as Driver;
|
||||
const tour = new PcbOnboarding(() => ctx, vi.fn(), async () => (options = {}) => {
|
||||
config = options;
|
||||
return driver;
|
||||
});
|
||||
tours.add(tour);
|
||||
return { tour, config: () => config, driver };
|
||||
}
|
||||
|
||||
function unmount(tour: PcbOnboarding) {
|
||||
tour.dispose();
|
||||
tours.delete(tour);
|
||||
}
|
||||
|
||||
const welcome = () => document.querySelector<HTMLDialogElement>('.pcb-tour-welcome[open]');
|
||||
function clickWelcome(action: 'begin' | 'skip' | 'dismiss') {
|
||||
const button = welcome()?.querySelector<HTMLButtonElement>(`[data-pcb-tour-${action}]`);
|
||||
expect(button).toBeTruthy();
|
||||
button!.click();
|
||||
}
|
||||
|
||||
describe('AI PCB workbench onboarding', () => {
|
||||
it('opens inside the blocking AI portal and demonstrates the design flow without editing a task', async () => {
|
||||
const { root, editor } = workbench();
|
||||
const duplicate = document.createElement('button');
|
||||
duplicate.dataset.aiPcbTour = 'proposal';
|
||||
editor.append(duplicate);
|
||||
const { tour, config, driver } = mount(root, 'flow-' + ++account);
|
||||
const actions = vi.fn();
|
||||
const request = root.querySelector('textarea')!;
|
||||
const task = root.querySelector('select')!;
|
||||
root.addEventListener('click', actions);
|
||||
root.addEventListener('input', actions);
|
||||
root.addEventListener('change', actions);
|
||||
await vi.advanceTimersByTimeAsync(500);
|
||||
expect(welcome()?.querySelector('h2')?.textContent).toMatch(/AI/i);
|
||||
clickWelcome('begin');
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(driver.drive).toHaveBeenCalledOnce();
|
||||
const tourSteps = config().steps!;
|
||||
expect(tourSteps.map(step => step.data?.id)).toEqual(steps);
|
||||
tourSteps.forEach((step, index) => {
|
||||
expect(step.element).toBe(root.querySelector(`[data-ai-pcb-tour="${steps[index]}"]`));
|
||||
expect(step.popover?.description?.trim()).toBeTruthy();
|
||||
});
|
||||
expect(tourSteps.find(step => step.data?.id === 'proposal')?.popover?.description).toMatch(/方案|审核/);
|
||||
expect(tourSteps.find(step => step.data?.id === 'delivery')?.popover?.description).toMatch(/下载|交付/);
|
||||
expect(config().disableActiveInteraction).toBe(true);
|
||||
root.querySelector<HTMLButtonElement>('[data-ai-pcb-tour="approve"]')!.click();
|
||||
tour.finish('completed');
|
||||
expect(actions).not.toHaveBeenCalled();
|
||||
expect(request.value).toBe('保留这段需求');
|
||||
expect(task.value).toBe('motor');
|
||||
});
|
||||
|
||||
it('can skip and replay an active task with no approval action', async () => {
|
||||
const { root } = workbench();
|
||||
const owner = 'skip-' + ++account;
|
||||
root.querySelector('[data-ai-pcb-tour="approve"]')!.remove();
|
||||
const first = mount(root, owner);
|
||||
await vi.advanceTimersByTimeAsync(500);
|
||||
clickWelcome('skip');
|
||||
expect(readTourPreferences(localStorage, owner, 'ai').status).toBe('skipped');
|
||||
expect(first.tour.isActive()).toBe(false);
|
||||
unmount(first.tour);
|
||||
const next = mount(root, owner);
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(welcome()).toBeNull();
|
||||
next.tour.offer(true);
|
||||
clickWelcome('begin');
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(next.config().steps?.map(step => step.data?.id)).toEqual(steps.filter(id => id !== 'approve'));
|
||||
});
|
||||
|
||||
it('defers while typing or while another dialog is open, then offers without clearing the draft', async () => {
|
||||
const { root } = workbench();
|
||||
const field = root.querySelector('textarea')!;
|
||||
field.focus();
|
||||
const { tour } = mount(root, 'draft-' + ++account);
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(welcome()).toBeNull();
|
||||
field.blur();
|
||||
const dialog = document.createElement('dialog');
|
||||
document.body.append(dialog);
|
||||
dialog.showModal();
|
||||
tour.sync();
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(welcome()).toBeNull();
|
||||
expect(dialog.open).toBe(true);
|
||||
dialog.close();
|
||||
tour.sync();
|
||||
await vi.advanceTimersByTimeAsync(500);
|
||||
expect(welcome()).not.toBeNull();
|
||||
expect(field.value).toBe('保留这段需求');
|
||||
});
|
||||
|
||||
it('keeps the AI opt-out separate from the editor and from other accounts', async () => {
|
||||
const { root, portal, editor } = workbench();
|
||||
const owner = 'preferences-' + ++account;
|
||||
const first = mount(root, owner);
|
||||
await vi.advanceTimersByTimeAsync(500);
|
||||
clickWelcome('dismiss');
|
||||
expect(readTourPreferences(localStorage, owner, 'ai').enabled).toBe(false);
|
||||
expect(readTourPreferences(localStorage, owner).enabled).toBe(true);
|
||||
unmount(first.tour);
|
||||
const returning = mount(root, owner);
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(welcome()).toBeNull();
|
||||
unmount(returning.tour);
|
||||
|
||||
portal.hidden = true;
|
||||
delete portal.dataset.pcbTourBlocked;
|
||||
const native = mount(editor, owner, 'editor');
|
||||
await vi.advanceTimersByTimeAsync(500);
|
||||
expect(welcome()?.querySelector('h2')?.textContent).toContain('PCB 编辑器');
|
||||
unmount(native.tour);
|
||||
|
||||
portal.hidden = false;
|
||||
portal.dataset.pcbTourBlocked = 'true';
|
||||
mount(root, owner + '-other');
|
||||
await vi.advanceTimersByTimeAsync(500);
|
||||
expect(welcome()?.querySelector('h2')?.textContent).toMatch(/AI/i);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { sessionClient } from "./pcb_session_fixture.js";
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { afterEach, expect, it, vi } from 'vitest';
|
||||
import { CodexPcbDock } from '@ziroeda/designer/src/codex-pcb/CodexPcbDock.js';
|
||||
@@ -28,7 +29,7 @@ afterEach(() => {
|
||||
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 />);
|
||||
render(<CodexPcbDock client={sessionClient} owner="unit-user"/>);
|
||||
expect(screen.queryByLabelText('AI PCB 全屏工作台')).toBeNull();
|
||||
expect(fetch.mock.calls.map(([url]) => url)).toEqual(['/pcb-api/readiness']);
|
||||
fireEvent.click(screen.getByRole('button', { name: /Codex AI 自动绘板/ }));
|
||||
@@ -41,14 +42,14 @@ it('checks environment on project entry while keeping task history lazy until op
|
||||
it('preserves the local disable switch even with an explicit AI URL and saved session', () => {
|
||||
vi.stubEnv('VITE_ENABLE_PCB_AI', 'false');
|
||||
window.history.replaceState(null, '', '/?ai=1');
|
||||
localStorage.setItem('vibemake.pcb2.persistent-session', 'pcb-saved');
|
||||
localStorage.setItem('vibemake.pcb2.persistent-session.unit-user', 'pcb-saved');
|
||||
const fetch = vi.fn();
|
||||
vi.stubGlobal('fetch', fetch);
|
||||
render(<CodexPcbDock />);
|
||||
render(<CodexPcbDock client={sessionClient} owner="unit-user"/>);
|
||||
expect(screen.queryByLabelText('AI PCB 全屏工作台')).toBeNull();
|
||||
expect(screen.queryByRole('button', { name: /Codex AI 自动绘板/ })).toBeNull();
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
expect(localStorage.getItem('vibemake.pcb2.persistent-session')).toBe('pcb-saved');
|
||||
expect(localStorage.getItem('vibemake.pcb2.persistent-session.unit-user')).toBe('pcb-saved');
|
||||
});
|
||||
|
||||
it('uses the new session protocol without replaying the legacy task outbox', async () => {
|
||||
@@ -68,7 +69,7 @@ it('uses the new session protocol without replaying the legacy task outbox', asy
|
||||
response(url, init?.method === 'POST' || url.endsWith('/sessions/pcb-new') ? task : []),
|
||||
);
|
||||
vi.stubGlobal('fetch', fetch);
|
||||
render(<CodexPcbDock />);
|
||||
render(<CodexPcbDock client={sessionClient} owner="unit-user"/>);
|
||||
fireEvent.change(screen.getByLabelText('描述你的设计需求'), { target: { value: '测试电源板设计' } });
|
||||
await waitFor(() => expect((screen.getByRole('button', { name: '发送需求 →' }) as HTMLButtonElement).disabled).toBe(false));
|
||||
fireEvent.click(screen.getByRole('button', { name: '发送需求 →' }));
|
||||
@@ -86,7 +87,7 @@ it('uses the new session protocol without replaying the legacy task outbox', asy
|
||||
|
||||
it('keeps approval disabled while an unsubmitted proposal comment exists', async () => {
|
||||
window.history.replaceState(null, '', '/?ai=1');
|
||||
localStorage.setItem('vibemake.pcb2.persistent-session', 'pcb-review');
|
||||
localStorage.setItem('vibemake.pcb2.persistent-session.unit-user', 'pcb-review');
|
||||
const task = {
|
||||
id: 'pcb-review',
|
||||
request: '测试电源板设计',
|
||||
@@ -103,10 +104,10 @@ it('keeps approval disabled while an unsubmitted proposal comment exists', async
|
||||
};
|
||||
const fetch = vi.fn(
|
||||
async (url: string) =>
|
||||
response(url, url.endsWith('/sessions') ? [task] : url.includes('/events?') ? [] : task),
|
||||
response(url, url.endsWith('/sessions') ? [{ ...task, project_code: null, editing_status: 'pending' }] : url.includes('/events?') ? [] : task),
|
||||
);
|
||||
vi.stubGlobal('fetch', fetch);
|
||||
render(<CodexPcbDock />);
|
||||
render(<CodexPcbDock client={sessionClient} owner="unit-user"/>);
|
||||
const approve = await screen.findByRole('button', { name: '确认方案并开始' });
|
||||
await waitFor(() => expect((approve as HTMLButtonElement).disabled).toBe(false));
|
||||
fireEvent.change(screen.getByLabelText('补充要求或修改方案'), {
|
||||
@@ -120,7 +121,7 @@ it('keeps approval disabled while an unsubmitted proposal comment exists', async
|
||||
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/>);
|
||||
render(<CodexPcbDock client={sessionClient} owner="unit-user"/>);
|
||||
await screen.findByText('绘板环境未就绪,暂不能生成');
|
||||
expect(screen.queryByLabelText('AI PCB 全屏工作台')).toBeNull();
|
||||
expect(fetch.mock.calls.length).toBe(1);
|
||||
@@ -133,7 +134,7 @@ it.each(['checking', 'unavailable'])('prevents generation while runtime is %s',
|
||||
const fetch = vi.fn(async (url: string) => url.includes('/readiness')
|
||||
? Response.json({ ...unavailable, status }) : response(url, []));
|
||||
vi.stubGlobal('fetch', fetch);
|
||||
render(<CodexPcbDock/>);
|
||||
render(<CodexPcbDock client={sessionClient} owner="unit-user"/>);
|
||||
fireEvent.change(screen.getByLabelText('描述你的设计需求'), { target: { value: '测试电源板设计' } });
|
||||
await screen.findByRole('option', { name: /OpenAI · test-model/ });
|
||||
const create = screen.getByRole('button', { name: '发送需求 →' }) as HTMLButtonElement;
|
||||
@@ -150,7 +151,7 @@ it('enables generation only after a successful manual recheck', async () => {
|
||||
return response(url, []);
|
||||
});
|
||||
vi.stubGlobal('fetch', fetch);
|
||||
render(<CodexPcbDock/>);
|
||||
render(<CodexPcbDock client={sessionClient} owner="unit-user"/>);
|
||||
fireEvent.change(screen.getByLabelText('描述你的设计需求'), { target: { value: '测试电源板设计' } });
|
||||
const retry = await screen.findByRole('button', { name: '重新检查环境' });
|
||||
expect((screen.getByRole('button', { name: '发送需求 →' }) as HTMLButtonElement).disabled).toBe(true);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { sessionClient } from "./pcb_session_fixture.js";
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { afterEach, expect, it, vi } from 'vitest';
|
||||
import { DeliveryChat } from '@ziroeda/designer/src/codex-pcb/DeliveryChat.js';
|
||||
@@ -8,16 +9,16 @@ vi.mock('@ziroeda/ai/markdown.js', () => ({ Markdown: ({ text }: { text: string
|
||||
afterEach(() => { cleanup(); localStorage.clear(); window.history.replaceState(null, '', '/'); vi.unstubAllGlobals(); });
|
||||
it('keeps delivered board questions available even if EDA is offline', async () => {
|
||||
const task = { id: 'pcb-delivered', state: 'completed', busy: false, cursor: 1, created_at: 0, request: '电机板', delivery: { notes: '已交付', files: [] } };
|
||||
window.history.replaceState(null, '', '/?ai=1');localStorage.setItem('vibemake.pcb2.persistent-session', task.id);
|
||||
window.history.replaceState(null, '', '/?ai=1');localStorage.setItem('vibemake.pcb2.persistent-session.unit-user', task.id);
|
||||
const fetch = vi.fn(async (url: string, init?: RequestInit) => {
|
||||
if (url.includes('/readiness')) return Response.json({ ok: false, status: 'unavailable', checks: [] });
|
||||
if (url.endsWith('/providers')) return Response.json({ default_provider: 'openai', providers: [] });
|
||||
if (url.endsWith('/sessions')) return Response.json([task]);
|
||||
if (url.endsWith('/sessions')) return Response.json([{ ...task, project_code: null, editing_status: 'pending' }]);
|
||||
if (url.includes('/events?')) return Response.json([]);
|
||||
if (url.endsWith('/questions')) return Response.json({ busy: false, messages: [] });
|
||||
return Response.json(task);
|
||||
});vi.stubGlobal('fetch',fetch);
|
||||
render(<CodexPcbDock/>);
|
||||
render(<CodexPcbDock client={sessionClient} owner="unit-user"/>);
|
||||
fireEvent.click(await screen.findByRole('button',{name:'使用问答'}));
|
||||
const input=await screen.findByLabelText('询问板子的使用方法');
|
||||
await waitFor(()=>expect((screen.getByRole('button',{name:'发送问题 →'}) as HTMLButtonElement).disabled).toBe(true));
|
||||
@@ -32,7 +33,7 @@ it('loads durable history, prevents duplicate sending and shows server errors wi
|
||||
const history={busy:false,messages:[{id:'1',role:'user',text:'电源接哪里?',at:1},{id:'2',role:'assistant',text:'根据工程报告,请接 J1。',at:2}],error:'上次回答中断,可重试'};
|
||||
let finish: (r: Response) => void=()=>{};
|
||||
const fetch=vi.fn(async (_url:string,init?:RequestInit)=>init?.method==='POST'?await new Promise<Response>(resolve=>{finish=resolve;}):Response.json(history));vi.stubGlobal('fetch',fetch);
|
||||
render(<DeliveryChat taskId="pcb-one"/>);
|
||||
render(<DeliveryChat client={sessionClient} taskId="pcb-one"/>);
|
||||
expect(await screen.findByText('根据工程报告,请接 J1。')).toBeTruthy();expect(screen.getByRole('alert').textContent).toContain('中断');
|
||||
fireEvent.change(screen.getByLabelText('询问板子的使用方法'),{target:{value:'需要烧录吗?'}});
|
||||
fireEvent.click(screen.getByRole('button',{name:'发送问题 →'}));
|
||||
@@ -44,7 +45,7 @@ it('loads durable history, prevents duplicate sending and shows server errors wi
|
||||
});
|
||||
it('preserves a failed question for retry',async()=>{
|
||||
vi.stubGlobal('fetch',vi.fn(async (_url:string,init?:RequestInit)=>init?.method==='POST'?Response.json({detail:'问答暂不可用'},{status:503}):Response.json({busy:false,messages:[]})));
|
||||
render(<DeliveryChat taskId="pcb-failure"/>);
|
||||
render(<DeliveryChat client={sessionClient} taskId="pcb-failure"/>);
|
||||
await waitFor(()=>expect(screen.queryByText('正在读取问答记录…')).toBeNull());
|
||||
fireEvent.change(screen.getByLabelText('询问板子的使用方法'),{target:{value:'如何使用?'}});fireEvent.click(screen.getByRole('button',{name:'发送问题 →'}));
|
||||
await screen.findByRole('alert');expect((screen.getByLabelText('询问板子的使用方法') as HTMLTextAreaElement).value).toBe('如何使用?');
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { sessionClient } from "./pcb_session_fixture.js";
|
||||
import { act, cleanup, render, screen } from '@testing-library/react';
|
||||
import { afterEach, expect, it, vi } from 'vitest';
|
||||
import { DesignPreview } from '@ziroeda/designer/src/codex-pcb/DesignPreview.js';
|
||||
@@ -22,11 +23,12 @@ it('polls the existing session API and retains its image after a conditional 304
|
||||
} }, { headers: { ETag: '"snapshot"' } }))
|
||||
.mockResolvedValue(new Response(null, { status: 304 }));
|
||||
vi.stubGlobal('fetch', fetch);
|
||||
await act(async () => { render(<DesignPreview task={task}/>); });
|
||||
await act(async () => { render(<DesignPreview client={sessionClient} task={task}/>); });
|
||||
expect(fetch.mock.calls[0]?.[0]).toBe(`/pcb-api/sessions/${task.id}/preview?kind=auto`);
|
||||
expect(screen.getByRole('img').getAttribute('src')).toContain('c25hcHNob3Q=');
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(5000); });
|
||||
expect(fetch.mock.calls[1]?.[1].headers).toEqual({ 'If-None-Match': '"snapshot"' });
|
||||
expect(fetch.mock.calls[1]?.[1].headers.get('If-None-Match')).toBe('"snapshot"');
|
||||
expect(fetch.mock.calls[1]?.[1].headers.get('Authorization')).toBe('Bearer test-owner-token');
|
||||
expect(screen.getByRole('img').getAttribute('src')).toContain('c25hcHNob3Q=');
|
||||
expect(screen.queryByText('画面连接暂不可用,正在自动重试')).toBeNull();
|
||||
});
|
||||
@@ -34,9 +36,9 @@ it('polls the existing session API and retains its image after a conditional 304
|
||||
it('does not poll before approval or after delivery', async () => {
|
||||
const fetch = vi.fn();
|
||||
vi.stubGlobal('fetch', fetch);
|
||||
const view = render(<DesignPreview task={{ ...task, approval: undefined }}/>);
|
||||
const view = render(<DesignPreview client={sessionClient} task={{ ...task, approval: undefined }}/>);
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
view.rerender(<DesignPreview task={{ ...task, state: 'completed' }}/>);
|
||||
view.rerender(<DesignPreview client={sessionClient} task={{ ...task, state: 'completed' }}/>);
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -44,7 +46,7 @@ it('explains an HTML fallback instead of hiding it behind a generic connection e
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('<!doctype html><html>Home</html>', {
|
||||
headers: { 'Content-Type': 'text/html' },
|
||||
})));
|
||||
await act(async () => { render(<DesignPreview task={task}/>); });
|
||||
await act(async () => { render(<DesignPreview client={sessionClient} task={task}/>); });
|
||||
expect(screen.getByText(/返回了网页,请检查 \/pcb\/pcb-api\//)).toBeTruthy();
|
||||
expect(screen.queryByText('Home')).toBeNull();
|
||||
});
|
||||
@@ -57,7 +59,7 @@ it('clears a transient connection error when an unchanged snapshot returns 304',
|
||||
} }, { headers: { ETag: '"snapshot"' } }))
|
||||
.mockRejectedValueOnce(new TypeError('Failed to fetch'))
|
||||
.mockResolvedValue(new Response(null, { status: 304 })));
|
||||
await act(async () => { render(<DesignPreview task={task}/>); });
|
||||
await act(async () => { render(<DesignPreview client={sessionClient} task={task}/>); });
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(5000); });
|
||||
expect(screen.getByText(/Failed to fetch/)).toBeTruthy();
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(5000); });
|
||||
@@ -67,6 +69,6 @@ it('clears a transient connection error when an unchanged snapshot returns 304',
|
||||
|
||||
it('describes a stopped task without an image as missing history rather than a connection failure', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(Response.json({ taskId: task.id, frame: null, reason: 'waiting_for_canvas' })));
|
||||
await act(async () => { render(<DesignPreview task={{ ...task, state: 'cancelled', busy: false }}/>); });
|
||||
await act(async () => { render(<DesignPreview client={sessionClient} task={{ ...task, state: 'cancelled', busy: false }}/>); });
|
||||
expect(screen.getByText('任务已停止,暂无可用的历史画面')).toBeTruthy();
|
||||
});
|
||||
|
||||
@@ -450,6 +450,29 @@ describe('real HTTP save and recovery', () => {
|
||||
s.runtime.revoke();
|
||||
}
|
||||
});
|
||||
it('re-signs a missing upload after its same-origin object transfer ticket expires', async () => {
|
||||
const s = server();
|
||||
const serve = fetcher.getMockImplementation()!;
|
||||
let first = true;
|
||||
fetcher.mockImplementation(async (url, init) => {
|
||||
if (String(url).endsWith('/uploads/signature') && first) {
|
||||
await serve(url, init);
|
||||
return reply({ ...signature(), uploadCode: 'batch-1',
|
||||
uploadUrl: location.origin + '/pcb/storage-transfer/test-ticket' });
|
||||
}
|
||||
if (String(url).endsWith('/storage-transfer/test-ticket')) {
|
||||
first = false;
|
||||
return new Response(null, { status:410 });
|
||||
}
|
||||
return serve(url, init);
|
||||
});
|
||||
try {
|
||||
await s.runtime.save();
|
||||
expect(s.runtime.baseVersion).toBe(1);
|
||||
expect(s.counts()).toEqual({uploads:1,signs:2});
|
||||
expect(s.commitCodes).toEqual(['batch-1','batch-2']);
|
||||
} finally { s.runtime.revoke(); }
|
||||
});
|
||||
it('confirms the original batch when the OSS upload response disappears after storing the ZIP', async () => {
|
||||
const s = server();
|
||||
const upload = s.api.upload.bind(s.api);
|
||||
|
||||
@@ -233,6 +233,32 @@ describe('PCB native archive and path boundaries', () => {
|
||||
});
|
||||
|
||||
describe('mock persistence and save transactions', () => {
|
||||
it('does not turn clean cloud views into recovery drafts, while preserving a pending editor change', async () => {
|
||||
const owner = crypto.randomUUID(), api = new MockPcbProjectApi(owner);
|
||||
const project = { ...await api.create('Dirty flag', crypto.randomUUID()), hasDocument: true, version: 2 };
|
||||
const runtime = new WorkspaceRuntime(owner, project, fixture(), api, DEFAULT_LIMITS, 'test');
|
||||
let pendingEdit = false;
|
||||
const flush = vi.fn((reason?: string) => {
|
||||
if (reason === 'clean-draft') return;
|
||||
if (pendingEdit) {
|
||||
runtime.writeFile('layout-note.txt', bytes('saved user edit'));
|
||||
pendingEdit = false;
|
||||
}
|
||||
});
|
||||
runtime.register('board', { flush, isDirty: () => pendingEdit });
|
||||
try {
|
||||
await runtime.persistDraft(true);
|
||||
expect(flush).toHaveBeenLastCalledWith('clean-draft');
|
||||
expect(runtime.getSnapshot().phase).toBe('saved');
|
||||
expect(await listDrafts(owner, runtime.code)).toHaveLength(0);
|
||||
pendingEdit = true;
|
||||
await runtime.persistDraft(true);
|
||||
expect(flush).toHaveBeenLastCalledWith('snapshot');
|
||||
const [draft] = await listDrafts(owner, runtime.code);
|
||||
expect(decode(draft!.files.find(f => f.name === 'layout-note.txt')!.bytes)).toBe('saved user edit');
|
||||
} finally { runtime.revoke(); }
|
||||
});
|
||||
|
||||
it('rejects an active tool immediately without locking, preparing or uploading, and saves after it ends', async () => {
|
||||
const owner = crypto.randomUUID(),
|
||||
api = new MockPcbProjectApi(owner),
|
||||
|
||||
@@ -20,6 +20,7 @@ it('keeps account and AI APIs on separate upstreams with the appropriate headers
|
||||
mkdirSync(scripts, { recursive: true });
|
||||
mkdirSync(dist, { recursive: true });
|
||||
copyFileSync(resolve(__dirname, '../../../scripts/serve.mjs'), join(scripts, 'serve.mjs'));
|
||||
copyFileSync(resolve(__dirname, '../../../scripts/pcb-object-relay.mjs'), join(scripts, 'pcb-object-relay.mjs'));
|
||||
writeFileSync(join(dist, 'index.html'), '<h1>Platform fixture</h1>');
|
||||
writeFileSync(join(dist, 'pcb-service-config.json'), JSON.stringify({ base: '/pcb/' }));
|
||||
const seen: {
|
||||
@@ -92,10 +93,11 @@ it('keeps account and AI APIs on separate upstreams with the appropriate headers
|
||||
authorization: 'Bearer test-token',
|
||||
body: '{"name":"board"}',
|
||||
});
|
||||
expect(await (await fetch(base + '/pcb/pcb-api/v1/tasks')).json()).toEqual({ service: 'pcb' });
|
||||
expect(await (await fetch(base + '/pcb/pcb-api/sessions', { headers: { Authorization: 'Bearer pcb-user' } })).json()).toEqual({ service: 'pcb' });
|
||||
expect(seen[1]).toMatchObject({
|
||||
service: 'pcb',
|
||||
path: '/api/v1/tasks',
|
||||
path: '/api/sessions',
|
||||
authorization: 'Bearer pcb-user',
|
||||
origin: 'http://127.0.0.1:5173',
|
||||
});
|
||||
const rejected = await fetch(base + '/api/auth/logout', {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { sessionClient } from "./pcb_session_fixture.js";
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { afterEach, expect, it, vi } from 'vitest';
|
||||
import { CodexPcbDock } from '@ziroeda/designer/src/codex-pcb/CodexPcbDock.js';
|
||||
@@ -9,16 +10,16 @@ const base: Session = { id: 'pcb-blocked', request: 'HDMI capture board', state:
|
||||
proposal: { title: '采集板方案', markdown: '原方案', revision: 1, hash: 'v1' }, approval: { revision: 1, at: 100 } };
|
||||
function setup(task: Session = structuredClone(base), ready = true, reject = false) {
|
||||
window.history.replaceState(null, '', '/?ai=1');
|
||||
localStorage.setItem('vibemake.pcb2.persistent-session', task.id);
|
||||
localStorage.setItem('vibemake.pcb2.persistent-session.unit-user', task.id);
|
||||
const fetch = vi.fn(async (url: string, init?: RequestInit) => {
|
||||
if (url.includes('/readiness')) return Response.json({ ok: ready, status: ready ? 'ready' : 'unavailable', checks: [], checked_at: 100 });
|
||||
if (url.endsWith('/providers')) return Response.json({ default_provider: 'openai', providers: [{ id: 'openai', label: 'OpenAI', model: 'test', effort: 'high', configured: true }] });
|
||||
if (url.endsWith('/sessions')) return Response.json([task]);
|
||||
if (url.endsWith('/sessions')) return Response.json([{ ...task, project_code: null, editing_status: 'pending' }]);
|
||||
if (url.includes('/events?')) return Response.json([]);
|
||||
if (init?.method === 'POST' && reject) return Response.json({ detail: '模型连接暂时失败' }, { status: 503 });
|
||||
return Response.json(init?.method === 'POST' ? { ...task, busy: true, state: 'planning' } : task);
|
||||
});
|
||||
vi.stubGlobal('fetch', fetch); render(<CodexPcbDock/>); return fetch;
|
||||
vi.stubGlobal('fetch', fetch); render(<CodexPcbDock client={sessionClient} owner="unit-user"/>); return fetch;
|
||||
}
|
||||
afterEach(() => { cleanup(); localStorage.clear(); window.history.replaceState(null, '', '/'); vi.unstubAllGlobals(); });
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ it("serves /pcb/ assets and SPA routes, proxies the nested API and rejects forei
|
||||
const dir=mkdtempSync(join(tmpdir(),"vibemake-proxy-"));
|
||||
const scripts=join(dir,"scripts"),dist=join(dir,"designer/dist");mkdirSync(scripts,{recursive:true});mkdirSync(join(dist,"assets"),{recursive:true});
|
||||
copyFileSync(resolve(__dirname,"../../../scripts/serve.mjs"),join(scripts,"serve.mjs"));
|
||||
copyFileSync(resolve(__dirname,"../../../scripts/pcb-object-relay.mjs"),join(scripts,"pcb-object-relay.mjs"));
|
||||
writeFileSync(join(dist,"index.html"),"<h1>VibeMake fixture</h1>");writeFileSync(join(dist,"assets/app.js"),"window.fixture=true");writeFileSync(join(dist,"pcb-service-config.json"),JSON.stringify({base:"/pcb/"}));
|
||||
let forwarded=0;
|
||||
const upstream=createServer((req,res)=>{forwarded++;res.setHeader("Content-Type","application/json");res.end(JSON.stringify({path:req.url,origin:req.headers.origin}))});
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
import { SessionApi } from '../../../designer/src/codex-pcb/session-api.js';
|
||||
const identity = {
|
||||
token: 'test-owner-token',
|
||||
user: { userCode: 'unit-user' },
|
||||
expiresAt: Number.MAX_SAFE_INTEGER,
|
||||
};
|
||||
export const sessionClient = new SessionApi(identity, () => identity);
|
||||
@@ -0,0 +1,219 @@
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import https from 'node:https';
|
||||
import { pipeline, Transform } from 'node:stream';
|
||||
|
||||
const MIB = 1024 * 1024;
|
||||
const ARCHIVE_LIMIT = 256 * MIB;
|
||||
const METADATA_LIMIT = 65536;
|
||||
const TTL = 5 * 60 * 1000;
|
||||
const DEFAULT_ORIGIN = 'https://linkerbot.oss-cn-beijing.aliyuncs.com';
|
||||
const PRIVATE = {
|
||||
'Cache-Control': 'no-store',
|
||||
'Referrer-Policy': 'no-referrer',
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
'Content-Security-Policy': "default-src 'none'; sandbox",
|
||||
};
|
||||
|
||||
function endWithStatus(res, status) {
|
||||
if (res.headersSent) {
|
||||
res.destroy();
|
||||
return;
|
||||
}
|
||||
res.writeHead(status, PRIVATE);
|
||||
res.end();
|
||||
}
|
||||
|
||||
function byteLimit(maximum) {
|
||||
let size = 0;
|
||||
return new Transform({
|
||||
transform(chunk, _, cb) {
|
||||
size += chunk.length;
|
||||
cb(size > maximum ? Error('Storage transfer is too large') : null, chunk);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function routeKind(req, pathname) {
|
||||
if (!/^Bearer [^\s]+$/i.test(req.headers.authorization || '')) return null;
|
||||
if (req.method === 'GET' && /^\/api\/pcb\/workspace\/projects\/[^/]+\/document$/.test(pathname))
|
||||
return 'download';
|
||||
if (req.method !== 'POST') return null;
|
||||
if (/^\/api\/pcb\/workspace\/projects\/[^/]+\/uploads\/signature$/.test(pathname))
|
||||
return 'upload';
|
||||
return pathname === '/api/uploads/project-covers/signature' ? 'cover' : null;
|
||||
}
|
||||
|
||||
export function createObjectRelay(
|
||||
siteBase,
|
||||
origins = DEFAULT_ORIGIN,
|
||||
request = https.request,
|
||||
now = Date.now,
|
||||
) {
|
||||
const prefix = siteBase + 'storage-transfer/';
|
||||
const allowed = new Set(
|
||||
origins.split(',').map((item) => {
|
||||
const url = new URL(item.trim());
|
||||
if (
|
||||
url.protocol !== 'https:' ||
|
||||
url.username ||
|
||||
url.password ||
|
||||
url.pathname !== '/' ||
|
||||
url.hash ||
|
||||
url.search
|
||||
)
|
||||
throw Error('PCB_OBJECT_ORIGINS must contain only trusted HTTPS origins');
|
||||
return url.origin;
|
||||
}),
|
||||
);
|
||||
const tickets = new Map();
|
||||
|
||||
function issue(rawUrl, method, size, ttl, ownOrigin) {
|
||||
const url = new URL(rawUrl);
|
||||
if (url.username || url.password || url.hash || !allowed.has(url.origin))
|
||||
throw Error('Unexpected object storage endpoint');
|
||||
const stamp = now();
|
||||
for (const [key, item] of tickets) if (item.expires <= stamp) tickets.delete(key);
|
||||
if (tickets.size >= 16384) throw Error('Too many pending transfers');
|
||||
const token = randomBytes(24).toString('base64url');
|
||||
tickets.set(token, { url, method, size, expires: stamp + ttl });
|
||||
return new URL(prefix + token, ownOrigin).href;
|
||||
}
|
||||
|
||||
function prepare(req, pathname, ownOrigin) {
|
||||
const kind = routeKind(req, pathname);
|
||||
if (!kind) return null;
|
||||
// Observe just the small authenticated signature request, while the normal
|
||||
// platform proxy sends exactly the original bytes.
|
||||
const chunks = [];
|
||||
let total = 0;
|
||||
if (kind !== 'download')
|
||||
req.on('data', (chunk) => {
|
||||
total += chunk.length;
|
||||
if (total <= METADATA_LIMIT) chunks.push(chunk);
|
||||
});
|
||||
return async function rewrite(reply, res) {
|
||||
if (reply.headers['content-encoding'] && reply.headers['content-encoding'] !== 'identity') {
|
||||
reply.resume();
|
||||
return endWithStatus(res, 502);
|
||||
}
|
||||
try {
|
||||
const parts = [];
|
||||
let length = 0;
|
||||
for await (const chunk of reply) {
|
||||
length += chunk.length;
|
||||
if (length > MIB) throw Error('Invalid storage metadata');
|
||||
parts.push(chunk);
|
||||
}
|
||||
const body = JSON.parse(Buffer.concat(parts));
|
||||
const data = body?.data;
|
||||
if ((!body.code || body.code === 'OK') && data) {
|
||||
if (kind === 'download') {
|
||||
if (
|
||||
!Number.isSafeInteger(data.sizeBytes) ||
|
||||
data.sizeBytes < 1 ||
|
||||
data.sizeBytes > ARCHIVE_LIMIT
|
||||
)
|
||||
throw Error('Invalid project archive size');
|
||||
data.downloadUrl = issue(data.downloadUrl, 'GET', data.sizeBytes, TTL, ownOrigin);
|
||||
} else {
|
||||
if (total > METADATA_LIMIT || !data.formFields || typeof data.formFields !== 'object')
|
||||
throw Error('Invalid signature');
|
||||
const input = JSON.parse(Buffer.concat(chunks));
|
||||
const size = kind === 'cover' ? input.fileSize : input.sizeBytes;
|
||||
if (
|
||||
!Number.isSafeInteger(size) ||
|
||||
size < 1 ||
|
||||
size > (kind === 'cover' ? 5 * MIB : ARCHIVE_LIMIT)
|
||||
)
|
||||
throw Error('Invalid object upload size');
|
||||
// OSS enforces its own per-key signed policy, expiry, and file size.
|
||||
// This server additionally bounds the original file plus multipart overhead.
|
||||
data.uploadUrl = issue(data.uploadUrl, 'POST', size + METADATA_LIMIT, TTL, ownOrigin);
|
||||
}
|
||||
}
|
||||
res.writeHead(reply.statusCode, {
|
||||
...PRIVATE,
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
});
|
||||
res.end(JSON.stringify(body));
|
||||
} catch {
|
||||
endWithStatus(res, 502);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function transfer(req, res, url, ownOrigin) {
|
||||
if (!url.pathname.startsWith(prefix)) return false;
|
||||
const token = url.pathname.slice(prefix.length);
|
||||
const ticket = tickets.get(token);
|
||||
if (!/^[A-Za-z0-9_-]{32}$/.test(token) || url.search) {
|
||||
endWithStatus(res, 404);
|
||||
return true;
|
||||
}
|
||||
if (!ticket || ticket.expires <= now()) {
|
||||
endWithStatus(res, 410);
|
||||
return true;
|
||||
}
|
||||
if (req.method !== ticket.method) {
|
||||
endWithStatus(res, 405);
|
||||
return true;
|
||||
}
|
||||
if (
|
||||
(req.headers.origin && req.headers.origin !== ownOrigin) ||
|
||||
req.headers['sec-fetch-site'] === 'cross-site' ||
|
||||
(ticket.method === 'POST' && req.headers.origin !== ownOrigin)
|
||||
) {
|
||||
endWithStatus(res, 403);
|
||||
return true;
|
||||
}
|
||||
const headers = {};
|
||||
if (ticket.method === 'POST') {
|
||||
const contentType = req.headers['content-type'] || '';
|
||||
if (!/^multipart\/form-data;\s*boundary=/i.test(contentType)) {
|
||||
endWithStatus(res, 415);
|
||||
return true;
|
||||
}
|
||||
headers['content-type'] = contentType;
|
||||
const length = req.headers['content-length'];
|
||||
if (length !== undefined) {
|
||||
if (!/^\d+$/.test(length) || Number(length) > ticket.size) {
|
||||
endWithStatus(res, 413);
|
||||
return true;
|
||||
}
|
||||
headers['content-length'] = length;
|
||||
}
|
||||
}
|
||||
// Never forward a user bearer, Cookie, Host, Origin or arbitrary request
|
||||
// headers. The destination is fixed when the platform issues the ticket.
|
||||
const upstream = request(ticket.url, { method: ticket.method, headers }, (reply) => {
|
||||
const status = reply.statusCode || 502;
|
||||
if (status < 200 || status >= 300 || ticket.method === 'POST') {
|
||||
reply.resume();
|
||||
endWithStatus(res, status >= 300 && status < 400 ? 502 : status);
|
||||
return;
|
||||
}
|
||||
const length = reply.headers['content-length'];
|
||||
if (length !== undefined && (!/^\d+$/.test(length) || Number(length) > ticket.size)) {
|
||||
reply.destroy();
|
||||
endWithStatus(res, 502);
|
||||
return;
|
||||
}
|
||||
res.writeHead(status, {
|
||||
...PRIVATE,
|
||||
'Content-Type': 'application/octet-stream',
|
||||
'Content-Disposition': 'attachment; filename="project.zip"',
|
||||
...(length === undefined ? {} : { 'Content-Length': length }),
|
||||
});
|
||||
pipeline(reply, byteLimit(ticket.size), res, () => {});
|
||||
});
|
||||
upstream.setTimeout(120000, () => upstream.destroy(Error('Storage timed out')));
|
||||
upstream.on('error', () => {
|
||||
if (!res.destroyed) endWithStatus(res, 502);
|
||||
});
|
||||
res.on('close', () => upstream.destroy());
|
||||
if (ticket.method === 'POST') pipeline(req, byteLimit(ticket.size), upstream, () => {});
|
||||
else upstream.end();
|
||||
return true;
|
||||
}
|
||||
return { prepare, transfer };
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
import { strict as assert } from 'node:assert';
|
||||
import http from 'node:http';
|
||||
import { Readable } from 'node:stream';
|
||||
import { after, before, test } from 'node:test';
|
||||
import { createObjectRelay } from './pcb-object-relay.mjs';
|
||||
|
||||
let backend,
|
||||
web,
|
||||
origin,
|
||||
destination,
|
||||
relay,
|
||||
clock = 0,
|
||||
calls = [],
|
||||
uploaded,
|
||||
redirects = false;
|
||||
const bucket = 'https://example-bucket.oss.example.test';
|
||||
const signPath = '/api/pcb/workspace/projects/valid/uploads/signature';
|
||||
const docPath = '/api/pcb/workspace/projects/valid/document';
|
||||
const coverPath = '/api/uploads/project-covers/signature';
|
||||
let uploadUrl = bucket,
|
||||
downloadUrl = bucket + '/private.zip?signed=hidden';
|
||||
|
||||
async function listen(server) {
|
||||
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
|
||||
return 'http://127.0.0.1:' + server.address().port;
|
||||
}
|
||||
before(async () => {
|
||||
backend = http.createServer(async (req, res) => {
|
||||
const chunks = [];
|
||||
for await (const chunk of req) chunks.push(chunk);
|
||||
calls.push({ method: req.method, path: req.url, headers: req.headers });
|
||||
if (redirects) {
|
||||
res.writeHead(302, { Location: 'https://other.example/' });
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
if (req.method === 'POST') {
|
||||
uploaded = Buffer.concat(chunks);
|
||||
res.end('ok');
|
||||
return;
|
||||
}
|
||||
res.end(Buffer.from([1, 2, 3]));
|
||||
});
|
||||
destination = await listen(backend);
|
||||
relay = createObjectRelay(
|
||||
'/pcb/',
|
||||
bucket,
|
||||
(url, options, callback) => {
|
||||
assert.equal(url.origin, bucket);
|
||||
return http.request(new URL(url.pathname + url.search, destination), options, callback);
|
||||
},
|
||||
() => clock,
|
||||
);
|
||||
web = http.createServer(async (req, res) => {
|
||||
const url = new URL(req.url, origin);
|
||||
if (relay.transfer(req, res, url, origin)) return;
|
||||
const rewrite = relay.prepare(req, url.pathname, origin);
|
||||
for await (const _ of req) {
|
||||
/* stand in for the platform handling the request */
|
||||
}
|
||||
const data =
|
||||
url.pathname === docPath
|
||||
? { downloadUrl, sizeBytes: 3, expiresAt: null }
|
||||
: {
|
||||
uploadUrl,
|
||||
uploadCode: 'v1',
|
||||
formFields: { key: 'scoped/project.zip' },
|
||||
coverUrl: bucket + '/cover.webp',
|
||||
};
|
||||
const body = JSON.stringify({ code: 'OK', data });
|
||||
if (!rewrite) {
|
||||
res.end(body);
|
||||
return;
|
||||
}
|
||||
const stream = Readable.from([Buffer.from(body)]);
|
||||
stream.statusCode = 200;
|
||||
stream.headers = { 'content-type': 'application/json' };
|
||||
await rewrite(stream, res);
|
||||
});
|
||||
origin = await listen(web);
|
||||
});
|
||||
after(async () => {
|
||||
for (const srv of [web, backend]) {
|
||||
srv.closeAllConnections();
|
||||
await new Promise((resolve) => srv.close(resolve));
|
||||
}
|
||||
});
|
||||
async function issued(path = signPath, auth = true) {
|
||||
const post = path !== docPath;
|
||||
return fetch(origin + path, {
|
||||
method: post ? 'POST' : 'GET',
|
||||
headers: auth ? { Authorization: 'Bearer my-secret', 'Content-Type': 'application/json' } : {},
|
||||
...(post ? { body: JSON.stringify({ sizeBytes: 5, fileSize: 5 }) } : {}),
|
||||
});
|
||||
}
|
||||
test('auth-scoped signature returns an opaque local URL, keeps signed form and original cover URL', async () => {
|
||||
const { data } = await (await issued()).json();
|
||||
assert.match(data.uploadUrl, new RegExp('^' + origin + '/pcb/storage-transfer/[\\w-]{32}$'));
|
||||
assert.deepEqual(data.formFields, { key: 'scoped/project.zip' });
|
||||
assert.equal(data.coverUrl, bucket + '/cover.webp');
|
||||
assert.equal((await (await issued(coverPath)).json()).data.coverUrl, bucket + '/cover.webp');
|
||||
const type = 'multipart/form-data; boundary=testing';
|
||||
const original = Buffer.from('--testing\r\nline\r\n--testing--');
|
||||
const response = await fetch(data.uploadUrl, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Origin: origin,
|
||||
'Content-Type': type,
|
||||
Authorization: 'Bearer must-not-leak',
|
||||
Cookie: 'session=private',
|
||||
'X-Leak': 'private',
|
||||
},
|
||||
body: original,
|
||||
});
|
||||
assert.equal(response.status, 200);
|
||||
assert.deepEqual(uploaded, original);
|
||||
const forwarded = calls.at(-1);
|
||||
assert.equal(forwarded.path, '/');
|
||||
assert.equal(forwarded.headers['content-type'], type);
|
||||
for (const key of ['authorization', 'cookie', 'origin', 'x-leak', 'referer'])
|
||||
assert.equal(forwarded.headers[key], undefined);
|
||||
assert.equal((await fetch(data.uploadUrl)).status, 405);
|
||||
});
|
||||
test('download fetches only its exact key and hides storage headers; retry after redirect does not leave bucket', async () => {
|
||||
const { data } = await (await issued(docPath)).json();
|
||||
assert.equal(data.expiresAt, null);
|
||||
assert.ok(!data.downloadUrl.includes('signed') && !data.downloadUrl.includes('private.zip'));
|
||||
redirects = true;
|
||||
assert.equal((await fetch(data.downloadUrl)).status, 502);
|
||||
redirects = false;
|
||||
const response = await fetch(data.downloadUrl, {
|
||||
headers: { Cookie: 'no', Authorization: 'Bearer hidden' },
|
||||
});
|
||||
assert.equal(response.status, 200);
|
||||
assert.equal(response.headers.get('content-type'), 'application/octet-stream');
|
||||
assert.deepEqual(new Uint8Array(await response.arrayBuffer()), new Uint8Array([1, 2, 3]));
|
||||
assert.equal(calls.at(-1).path, '/private.zip?signed=hidden');
|
||||
assert.equal(calls.at(-1).headers.authorization, undefined);
|
||||
});
|
||||
test('foreign origin, excessive bytes, expired tickets, extra query strings, and foreign targets cannot transfer', async () => {
|
||||
const { data } = await (await issued()).json();
|
||||
const send = (headers, body) =>
|
||||
fetch(data.uploadUrl, {
|
||||
method: 'POST',
|
||||
headers: { Origin: origin, 'Content-Type': 'multipart/form-data; boundary=x', ...headers },
|
||||
body,
|
||||
});
|
||||
const beforeCalls = calls.length;
|
||||
assert.equal((await send({ Origin: 'https://other.test' }, 'bytes')).status, 403);
|
||||
assert.equal((await send({ 'Content-Type': 'text/plain' }, 'bytes')).status, 415);
|
||||
assert.equal((await send({}, Buffer.alloc(70000))).status, 413);
|
||||
assert.equal((await fetch(data.uploadUrl + '?url=https://evil.test')).status, 404);
|
||||
clock += 301000;
|
||||
assert.equal((await send({}, 'bytes')).status, 410);
|
||||
assert.equal(calls.length, beforeCalls);
|
||||
uploadUrl = 'https://not-trusted.example/object';
|
||||
assert.equal((await issued()).status, 502);
|
||||
uploadUrl = bucket;
|
||||
assert.equal((await (await issued(signPath, false)).json()).data.uploadUrl, bucket);
|
||||
assert.equal((await (await issued('/api/unrelated')).json()).data.uploadUrl, bucket);
|
||||
assert.throws(() => createObjectRelay('/pcb/', 'http://127.0.0.1'));
|
||||
});
|
||||
+14
-4
@@ -6,17 +6,20 @@ import { createReadStream } from 'node:fs';
|
||||
import { resolve, extname, sep } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { pipeline } from 'node:stream';
|
||||
import { createObjectRelay } from './pcb-object-relay.mjs';
|
||||
const root = resolve(fileURLToPath(new URL('../designer/dist/', import.meta.url)));
|
||||
const deployment = JSON.parse(await readFile(resolve(root, 'pcb-service-config.json'), 'utf8'));
|
||||
const siteBase = deployment.base;
|
||||
if (typeof siteBase !== 'string' || !siteBase.startsWith('/') || !siteBase.endsWith('/'))
|
||||
throw Error('Build base must be an absolute URL path ending in /');
|
||||
const objectRelay = process.env.PCB_OBJECT_RELAY === '1'
|
||||
? createObjectRelay(siteBase, process.env.PCB_OBJECT_ORIGINS) : null;
|
||||
const apiPrefix = `${siteBase}pcb-api/`;
|
||||
const libraryPrefix = `${siteBase}library-api/`;
|
||||
const libraryTarget = new URL(process.env.PCB_LIBRARY_TARGET || 'http://127.0.0.1:8004');
|
||||
if (!['http:', 'https:'].includes(libraryTarget.protocol) || libraryTarget.username || libraryTarget.password)
|
||||
throw Error('PCB_LIBRARY_TARGET must be an HTTP(S) address without embedded credentials');
|
||||
const target = new URL(process.env.PCB_API_TARGET || 'http://39.105.93.138:8003');
|
||||
const target = new URL(process.env.PCB_API_TARGET || 'http://127.0.0.1:8003');
|
||||
if (!['http:', 'https:'].includes(target.protocol) || target.username || target.password)
|
||||
throw Error('PCB_API_TARGET must be an HTTP(S) address without embedded credentials');
|
||||
const platformTarget = new URL(process.env.API_TARGET || 'https://dev-vibemake-api.robotquan.com');
|
||||
@@ -42,12 +45,13 @@ const mime = {
|
||||
const handler = async (req, res) => {
|
||||
try {
|
||||
const url = new URL(req.url, 'http://localhost');
|
||||
const ownOrigin =
|
||||
process.env.PUBLIC_ORIGIN ||
|
||||
`${process.env.TLS_CERT && process.env.TLS_KEY ? 'https' : 'http'}://${req.headers.host}`;
|
||||
if (objectRelay?.transfer(req, res, url, ownOrigin)) return;
|
||||
const pcbApi = url.pathname.startsWith(apiPrefix);
|
||||
const libraryApi = url.pathname.startsWith(libraryPrefix);
|
||||
if (pcbApi || libraryApi || url.pathname === '/api' || url.pathname.startsWith('/api/')) {
|
||||
const ownOrigin =
|
||||
process.env.PUBLIC_ORIGIN ||
|
||||
`${process.env.TLS_CERT && process.env.TLS_KEY ? 'https' : 'http'}://${req.headers.host}`;
|
||||
if (
|
||||
(req.headers.origin && req.headers.origin !== ownOrigin) ||
|
||||
(!['GET', 'HEAD', 'OPTIONS'].includes(req.method) && req.headers.origin !== ownOrigin)
|
||||
@@ -68,10 +72,16 @@ const handler = async (req, res) => {
|
||||
}
|
||||
const upstreamPrefix = pcbApi ? apiPrefix : libraryApi ? libraryPrefix : null;
|
||||
const upstreamPath = upstreamPrefix ? '/api/' + url.pathname.slice(upstreamPrefix.length) : url.pathname;
|
||||
const rewrite = !upstreamPrefix && objectRelay?.prepare(req, url.pathname, ownOrigin);
|
||||
if (rewrite) headers['accept-encoding'] = 'identity';
|
||||
const upstream = (upstreamTarget.protocol === 'https:' ? https : http).request(
|
||||
new URL(upstreamPath + url.search, upstreamTarget),
|
||||
{ method: req.method, headers },
|
||||
(reply) => {
|
||||
if (rewrite && reply.statusCode >= 200 && reply.statusCode < 300) {
|
||||
void rewrite(reply, res);
|
||||
return;
|
||||
}
|
||||
res.writeHead(reply.statusCode || 502, {
|
||||
...reply.headers,
|
||||
'cache-control': 'no-store',
|
||||
|
||||
Reference in New Issue
Block a user