Preserve native PCB workflow, delivery toolkit and local web changes before main sync

This commit is contained in:
2026-11-16 18:14:51 +08:00
parent 4af3866210
commit 6051e2f889
33 changed files with 1437 additions and 318 deletions
+38 -9
View File
@@ -12,6 +12,10 @@ from .storage import SOURCE, ROOT, TASKS, MODEL, EFFORT, task_dir, workspace, lo
from .rpc import AppServer
from .eda import execute
from .delivery import deliver
from .eda import verify_native
from .exports import prepare_delivery
from .checks import VALIDATION_POLICY
from .native_policy import DESIGN_POLICY, POLICY_TEXT, WORKSPACE_RULES, refresh_workspace_rules
CACHE, JOBS, CLIENTS = {}, {}, {}
@@ -23,9 +27,11 @@ def tool(name, description, properties, required=None):
STR={'type':'string'}
TOOLS=[
tool('pcb_check','Run the exact delivery electrical gate early and after edits. Accepts schematic container OR page ID and PCB document ID. All schematic pages checked. Explicit warnings are reported and accepted; errors block.',{'schematic_id':STR,'pcb_id':STR}),
tool('pcb_prepare_delivery','After pcb_check accepts, export native project/drawings/STEP/OBJ, render OBJ with installed Blender, and return a file list for pcb_deliver. Built-in chunk transfer, schematic SVG/PDF conversion, model ZIP extraction. No STEP cosmetic rebuilding; warnings are retained. Inspect outputs once before delivery.',{'schematic_id':STR,'pcb_id':STR}),
tool('pcb_proposal','Publish or replace the proposal for website review; not production authorization.',{'title':STR,'markdown':STR}),
tool('pcb_read_reference','Read official EDA API documentation. Relative path under api-reference, e.g. references/_index.md. Also available via shell during production.',{'path':STR,'offset':{'type':'integer','minimum':0},'limit':{'type':'integer','minimum':100,'maximum':40000}},['path']),
tool('pcb_eda','Execute YOUR JavaScript async function body in this task dedicated EasyEDA session. Only after website approval. Global eda and async pcb_export(file,relative_name) are available. Use code OR code_file (workspace-relative JS path). Full outputs preserved; uncertain writes must be inspected.',{'label':STR,'code':STR,'code_file':STR},['label']),
tool('pcb_eda','Operate native EasyEDA schematic/PCB objects in this task session after approval. External routing exchange (DSN/SES/auto-route JSON) is disabled. Global eda and pcb_export(file,relative_name) are available. Use code OR code_file. Full outputs preserved; uncertain writes must be inspected.',{'label':STR,'code':STR,'code_file':STR},['label']),
tool('pcb_deliver','Submit real exported files for independent validation. Rejected submission returns evidence so you can repair in the SAME session.',{'schematic_id':STR,'pcb_id':STR,'notes':STR,'files':{'type':'array','items':object_schema({'path':STR,'kind':{'type':'string','enum':['project','schematic','layout','step','render','bom','report','other']},'label':STR}), 'minItems':5}}),
tool('pcb_blocked','Record a concrete unrecoverable blocker and preserve draft. Do not use for ordinary tool errors; investigate and repair first.',{'reason':STR,'evidence':STR}),
]
@@ -63,7 +69,11 @@ async def handle(t, method, p):
frozen(t)
if t['state'] == 'cancelled':
raise RuntimeError('Task cancelled')
if name=='pcb_proposal':
if name=='pcb_check':
result=await verify_native(t,a['schematic_id'],a['pcb_id'],require_pass=False)
elif name=='pcb_prepare_delivery':
result=await prepare_delivery(t,a['schematic_id'],a['pcb_id'])
elif name=='pcb_proposal':
if t.get('approval'):
raise ValueError('Already approved; preserve accepted design and finish production')
markdown=a['markdown'].strip()
@@ -84,10 +94,25 @@ async def handle(t, method, p):
if bool(a.get('code'))==bool(a.get('code_file')):
raise ValueError('Specify exactly one of code or code_file')
code=a.get('code') or inside(workspace(t),a['code_file']).read_text()
result=await execute(t,code,a['label'])
# Backward-compatible access for resumed threads whose tool catalogue is fixed.
try: request=json.loads(code)
except ValueError: request=None
if isinstance(request,dict) and 'pcb_backend_tool' in request:
if set(request)!={'pcb_backend_tool','schematic_id','pcb_id'} or not all(isinstance(v,str) for v in request.values()):
raise ValueError('Invalid common-tool request')
operation=request['pcb_backend_tool']
if operation=='prepare_delivery':
result=await prepare_delivery(t,request['schematic_id'],request['pcb_id'])
elif operation=='check':
result=await verify_native(t,request['schematic_id'],request['pcb_id'],require_pass=False)
else:raise ValueError('Unknown common backend tool')
else:
result=await execute(t,code,a['label'])
raw=json.dumps(result,ensure_ascii=False)
if len(raw)>24000:
result={'output_path':str(workspace(t)/'evidence'/f'eda-{t["eda_calls"]:05d}.json'),'preview':raw[:18000],'truncated':True,'instruction':'Read the complete file using shell; do not guess omitted fields'}
output=workspace(t)/'evidence'/('tool-result-'+uuid.uuid4().hex+'.json')
write(output,result)
result={'output_path':str(output),'preview':raw[:18000],'truncated':True,'instruction':'Read the complete file using shell; do not guess omitted fields'}
elif name=='pcb_deliver':
if not t.get('approval') or t['state']!='running':
raise ValueError('Production approval required')
@@ -113,6 +138,9 @@ async def handle(t, method, p):
async def run_turn(t, prompt, production):
frozen(t)
directory=workspace(t)
# Reassert on every turn, including resumed histories with obsolete routing advice.
refresh_workspace_rules(directory)
prompt=POLICY_TEXT+'\n'+prompt
async with AppServer(directory, production, lambda m,p:handle(t,m,p)) as client:
CLIENTS[t['id']]=client
common={'model':MODEL,'modelProvider':'openai','cwd':str(directory),'approvalPolicy':'never','sandbox':'workspace-write' if production else 'read-only','developerInstructions':(SOURCE/'instructions.md').read_text(),'serviceTier':'default'}
@@ -248,7 +276,7 @@ class Approval(BaseModel):
@app.get('/api/health')
async def health():
return {'ok':True,'engine':'persistent-codex','model':MODEL,'effort':EFFORT,'source_hash':fingerprint(),'legacy_pipeline':False}
return {'ok':True,'engine':'persistent-codex','model':MODEL,'effort':EFFORT,'source_hash':fingerprint(),'legacy_pipeline':False,'design_policy':DESIGN_POLICY,'validation_policy':VALIDATION_POLICY,'delivery_toolkit':1}
@app.get('/api/sessions')
async def list_sessions():
@@ -257,12 +285,12 @@ async def list_sessions():
@app.post('/api/sessions',status_code=201)
async def create(req:Request):
tid='pcb-'+uuid.uuid4().hex[:24]
t={'id':tid,'request':req.text,'created_at':time.time(),'state':'planning','cursor':0,'model':MODEL,'effort':EFFORT,'busy':False}
t={'id':tid,'request':req.text,'created_at':time.time(),'state':'planning','cursor':0,'model':MODEL,'effort':EFFORT,'busy':False,'design_policy':DESIGN_POLICY}
directory=workspace(t);directory.mkdir(parents=True)
for name in ('artifacts','evidence','scripts','tmp'):
(directory/name).mkdir()
(directory/'api-reference').symlink_to(ROOT/'resources',target_is_directory=True)
(directory/'AGENTS.md').write_text('Use only this workspace for generated PCB scripts/files. Do not read or use legacy PCB pipelines. Official API references are under api-reference. Do not edit service code or unrelated projects. Do not spawn subagents.\n')
(directory/'AGENTS.md').write_text(WORKSPACE_RULES)
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)
@@ -298,13 +326,14 @@ async def approve(tid:str,req:Approval):
raise HTTPException(409,'Approve the latest completed proposal revision')
t['approval']={'revision':req.revision,'hash':req.hash,'at':time.time()}
t['frozen_source']=fingerprint()
t['design_policy']=DESIGN_POLICY
event(t,'proposal.approved',t['approval'])
prompt=f'''The user explicitly clicked APPROVE AND START for proposal revision {req.revision}, SHA256 {req.hash}.
This server-owned approval authorizes production of the accepted proposal in this same persistent session. Earlier requests to wait applied only to review.
Workspace: {workspace(t)}
Official API documentation: {workspace(t)}/api-reference/references/_index.md
External router launcher: python3 {SOURCE}/freerouting.py --input <board.dsn> --output <new-result.ses> --jar {ROOT}/resources/freerouting.jar --timeout 900 -- -mp 30 -mt 1
Use this launcher for Freerouting, including --help. It validates paths, skips the startup countdown and runs on a private virtual display. Choose routing options and timeout according to the board; do not invoke the JAR directly. Blender: /snap/bin/blender.
{POLICY_TEXT}
Blender: /snap/bin/blender (render exported native 3D geometry only).
Now use native Codex tools and pcb_eda to implement, inspect, fix, route, verify and export the real board. You write the design scripts yourself. No fixed backend design pipeline exists. Keep working until pcb_deliver accepts native project, schematic, layout, assembled STEP and real 3D render. Do not edit backend code or use legacy PCB flows. Backend source is frozen for this run.
Accepted proposal:\n{p['markdown']}'''
schedule(t,prompt,True)
+46
View File
@@ -0,0 +1,46 @@
"""Severity-aware native diagnostics: errors block; explicit warnings are retained."""
import json
VALIDATION_POLICY = 'native-errors-block-warnings-record-v1'
def classify_diagnostics(details, native_passed):
errors, warnings = [], []
if not isinstance(details, list) or not isinstance(native_passed, bool):
return {'passed': False, 'errors': [{'reason': 'Invalid native check response', 'details': details}], 'warnings': []}
def visit(item, inherited=None):
if not isinstance(item, dict):
errors.append({'reason': 'Unclassified native diagnostic', 'details': item});return
severity = str(item.get('severity', item.get('type', inherited or ''))).lower()
name = str(item.get('name', item.get('errorType', ''))).lower()
if severity in {'error','fatal'} or 'error' in name or '错误' in name:
severity = 'error'
elif severity in {'warn','warning'} or name in {'warning','warnings','警告'}:
severity = 'warning'
children = item.get('list')
if isinstance(children, list) and children:
for child in children:visit(child,severity)
elif severity == 'warning':
warnings.append(item)
else:
# Unknown categories are never silently converted to warnings.
errors.append(item)
for item in details:visit(item)
if not native_passed and not details:
errors.append({'reason': 'Native check returned false without diagnostic evidence'})
return {'passed': not errors, 'errors': errors, 'warnings': warnings, 'nativePassed':native_passed}
def evaluate_verification(result):
if not isinstance(result, dict):raise ValueError('Missing native verification result')
sch=classify_diagnostics(result.get('schErrors'), result.get('schPassed'))
pcb=classify_diagnostics(result.get('pcbErrors'), result.get('pcbPassed'))
result.update(validation_policy=VALIDATION_POLICY, accepted=sch['passed'] and pcb['passed'],
warnings={'schematic':sch['warnings'],'pcb':pcb['warnings']},
blockingErrors={'schematic':sch['errors'],'pcb':pcb['errors']})
if result.get('schematicParts',0)<2 or result.get('pcbParts',0)<2:
result['accepted']=False
result['blockingErrors']['design']=[{'reason':'Native design is empty or incomplete'}]
return result
+19 -8
View File
@@ -5,6 +5,8 @@ from pathlib import Path
from .storage import workspace, task_dir, inside, digest, write
from .eda import verify_native
from .step_colors import validate_step_colors
from .native_policy import DESIGN_POLICY
from .checks import VALIDATION_POLICY
REQUIRED = {'project','schematic','layout','step','render'}
@@ -13,10 +15,14 @@ def inspect(path, kind):
if len(data)<100:
raise ValueError(f'{kind}: file is empty or too small')
ext = path.suffix.lower()
warnings=[]
if kind == 'step':
if ext not in {'.stp','.step'} or not data.lstrip().startswith(b'ISO-10303-21;') or b'END-ISO-10303-21;' not in data or b'CARTESIAN_POINT' not in data or b'SHAPE_REPRESENTATION' not in data:
raise ValueError('STEP must be an extracted, real ISO10303 model')
validate_step_colors(data)
try:
validate_step_colors(data)
except ValueError as exc:
warnings.append({'type':'warning','code':'STEP_APPEARANCE','message':str(exc)})
elif kind == 'project':
if ext not in {'.epro','.epro2','.zip'}:
raise ValueError('Editable native EasyEDA project required')
@@ -33,10 +39,12 @@ def inspect(path, kind):
svg = b'<svg' in data[:2000]
if not (png or jpg or (kind != 'render' and (pdf or svg))):
raise ValueError(f'{kind}: native preview or real render required')
return {'bytes':len(data),'sha256':digest(data)}
return {'bytes':len(data),'sha256':digest(data),'warnings':warnings}
async def deliver(t, args):
files=args['files']
# Run the same gate as pcb_check before any packaging work.
verification=await verify_native(t,args['schematic_id'],args['pcb_id'])
if not REQUIRED <= {f['kind'] for f in files}:
raise ValueError('Missing required deliverables: '+', '.join(sorted(REQUIRED-{f['kind'] for f in files})))
checked=[]
@@ -45,7 +53,6 @@ async def deliver(t, args):
if not path.is_file() or path.is_symlink():
raise ValueError('Missing artifact: '+f['path'])
checked.append({**f,**inspect(path,f['kind']),'source':path})
verification=await verify_native(t,args['schematic_id'],args['pcb_id'])
folder=task_dir(t['id'])/'delivery'
folder.mkdir(exist_ok=True)
entries=[]
@@ -56,14 +63,18 @@ async def deliver(t, args):
# Recheck after copy: agent may still be doing work in the same filesystem.
if digest(target.read_bytes()) != f['sha256']:
raise ValueError('Artifact changed during delivery')
entries.append({'name':name,'kind':f['kind'],'label':f.get('label') or f['source'].name,'bytes':f['bytes'],'sha256':f['sha256']})
entries.append({'name':name,'kind':f['kind'],'label':f.get('label') or f['source'].name,'bytes':f['bytes'],'sha256':f['sha256'],'warnings':f['warnings']})
manifest={'task_id':t['id'],'thread_id':t['thread_id'],'approval':t['approval'],'source_hash':t['frozen_source'],'verification':verification,'files':entries,'notes':args['notes']}
manifest.update(design_policy=DESIGN_POLICY, source_migrations=t.get('source_migrations',[]), acceptance_run_invalidated=t.get('acceptance_run_invalidated',False))
warnings=[{'scope':scope,'diagnostic':w} for scope,items in verification['warnings'].items() for w in items]
warnings += [{'scope':f['name'],'diagnostic':w} for f in entries for w in f['warnings']]
manifest.update(validation_policy=VALIDATION_POLICY,warnings=warnings)
write(folder/'manifest.json',manifest)
shutil.copyfile(task_dir(t['id'])/'native-verification.json',folder/'native-verification.json')
bundle=folder/'delivery.zip'
with zipfile.ZipFile(bundle,'w',zipfile.ZIP_DEFLATED) as z:
for p in sorted(folder.iterdir()):
if p.is_file() and p != bundle:
z.write(p,p.name)
# Never include stale files left by an earlier submission attempt.
for name in [f['name'] for f in entries]+['manifest.json','native-verification.json']:
z.write(folder/name,name)
entries.append({'name':bundle.name,'kind':'bundle','label':'完整交付包','bytes':bundle.stat().st_size,'sha256':digest(bundle.read_bytes())})
return {'files':entries,'verification':verification,'notes':args['notes'],'schematic_id':args['schematic_id'],'pcb_id':args['pcb_id']}
return {'files':entries,'verification':verification,'warnings':warnings,'validation_policy':VALIDATION_POLICY,'notes':args['notes'],'schematic_id':verification['schematic_id'],'pcb_id':verification['pcb_id']}
+67 -30
View File
@@ -5,8 +5,12 @@ import fcntl
import json
import os
import time
import uuid
from pathlib import Path
from .storage import ROOT, workspace, task_dir, inside, save, write, event, digest
from .native_policy import guarded_script, validate_export_name
from .native_helpers import HELPERS_JS
from .checks import evaluate_verification
EDA_LOCK = asyncio.Lock()
@@ -67,22 +71,43 @@ async def execute(t, code, label='EDA script'):
prefix.parent.mkdir(parents=True,exist_ok=True)
prefix.with_suffix('.js').write_text(code)
event(t,'eda.started',{'call':n,'label':label})
wrapper = '''const __files = [];
const pcb_export = async (file,name) => {
if (!file || typeof file.arrayBuffer !== 'function') throw new Error('Native export returned no File/Blob');
const base64 = await new Promise((resolve,reject)=>{const r=new FileReader();r.onload=()=>resolve(String(r.result).split(',')[1]);r.onerror=reject;r.readAsDataURL(file);});
__files.push({name,base64});return {name,bytes:file.size};
transfer_key='pcb_export_'+uuid.uuid4().hex
wrapper = 'const __transferKey='+json.dumps(transfer_key)+';\n'+r'''const __files=[];
globalThis.__pcbBackendTransfers ??= Object.create(null);
globalThis.__pcbBackendTransfers[__transferKey]=[];
const pcb_export=async(file,name)=>{
if(/\.(dsn|ses)$/i.test(name))throw Error('easyeda-native-v1: DSN/SES routing exchange exports are disabled');
if(!file || typeof file.arrayBuffer!=='function')throw Error('Native export returned no File/Blob');
const index=__files.length;
globalThis.__pcbBackendTransfers[__transferKey].push(file);
__files.push({name,bytes:file.size,index});return {name,bytes:file.size};
};
const __result = await (async()=>{\n''' + code + '\n})(); return {result:__result,files:__files};'
const __result=await (async()=>{
''' + guarded_script(HELPERS_JS+'\n'+code) + '\n})(); return {result:__result,files:__files};'
try:
value = await cli(['invoke','--session',t['eda_session'],'--ext-uuid','eda','--code-file','-','--timeout','180000'],wrapper)
files = []
for item in value.get('files',[]):
dst = inside(workspace(t)/'artifacts',item['name'])
data = base64.b64decode(item['base64'],validate=True)
validate_export_name(item['name'])
dst=inside(workspace(t)/'artifacts',item['name'])
dst.parent.mkdir(parents=True,exist_ok=True)
dst.write_bytes(data)
files.append({'path':str(dst),'bytes':len(data),'sha256':digest(data)})
partial=dst.with_name(dst.name+'.'+transfer_key+'.partial')
try:
with partial.open('wb') as output:
for offset in range(0,item['bytes'],1024*1024):
chunk_code=f'''const f=globalThis.__pcbBackendTransfers?.[{json.dumps(transfer_key)}]?.[{int(item['index'])}];
if(!f || f.size!=={int(item['bytes'])})throw Error('Native export handle expired; retry export without editing the board');
const blob=f.slice({offset},{offset+1024*1024});
const base64=await new Promise((resolve,reject)=>{{const r=new FileReader();r.onload=()=>resolve(String(r.result).split(',')[1]);r.onerror=reject;r.readAsDataURL(blob);}});
return {{base64}};'''
chunk=await cli(['invoke','--session',t['eda_session'],'--ext-uuid','eda','--code-file','-','--timeout','30000'],chunk_code,timeout=40)
data=base64.b64decode(chunk['base64'],validate=True)
if len(data)!=min(1024*1024,item['bytes']-offset):raise ValueError('Truncated native export chunk')
output.write(data)
partial.replace(dst)
finally:
partial.unlink(missing_ok=True)
files.append({'path':str(dst),'bytes':dst.stat().st_size,'sha256':digest(dst.read_bytes())})
result = {'result':value.get('result'),'exports':files}
write(prefix.with_suffix('.json'),result)
event(t,'eda.completed',{'call':n,'label':label,'files':files})
@@ -91,33 +116,45 @@ const __result = await (async()=>{\n''' + code + '\n})(); return {result:__resul
write(prefix.with_suffix('.json'),{'error':str(e),'mutation_outcome':'inspect before retry'})
event(t,'eda.error',{'call':n,'message':str(e)})
raise
finally:
try:
await cli(['invoke','--session',t['eda_session'],'--ext-uuid','eda','--code-file','-','--timeout','10000'], 'delete globalThis.__pcbBackendTransfers?.['+json.dumps(transfer_key)+'];return true;', timeout=15)
except Exception:
pass
finally:
fcntl.flock(fd,fcntl.LOCK_UN)
fd.close()
async def verify_native(t, schematic_id, pcb_id):
# Native booleans must be true. Verbose arrays are retained only as diagnostics.
code = f'''const sch={json.dumps(schematic_id)}, pcb={json.dumps(pcb_id)};
async function focus(id) {{ const tab=await eda.dmt_EditorControl.openDocument(id); if(!tab || !await eda.dmt_EditorControl.activateDocument(tab)) throw new Error('Cannot focus requested document '+id); }}
await focus(sch); await eda.sch_Document.save();
const parts=await eda.sch_PrimitiveComponent.getAll('part');
const schPassed=await eda.sch_Drc.check(true,false,false);
const schErrors=schPassed ? [] : await eda.sch_Drc.check(true,false,true);
async def verify_native(t, schematic_id, pcb_id, *, require_pass=True):
code = f'''const resolved=await pcb_resolve({json.dumps(schematic_id)}, {json.dumps(pcb_id)});
const allParts=new Set(), allErrors=new Map(); let schPassed=true;
for(const page of resolved.schematic.page) {{
await pcb_focus(page.uuid);
if(await eda.sch_Document.save()===false)throw Error('Schematic save failed');
for(const part of await eda.sch_PrimitiveComponent.getAll('part'))allParts.add(page.uuid+':'+part.getState_PrimitiveId());
const ok=await eda.sch_Drc.check(true,false,false); if(typeof ok!=='boolean')throw Error('Invalid schematic check response');
schPassed=schPassed && ok;
const rows=await eda.sch_Drc.check(true,false,true); if(!Array.isArray(rows))throw Error('Missing schematic diagnostics');
for(const row of rows)allErrors.set(JSON.stringify(row),row);
}}
const schNet=await eda.sch_ManufactureData.getNetlistFile('verification');
if(!schNet)throw new Error('Schematic netlist export missing');
if(!schNet)throw Error('Schematic netlist export missing');
await pcb_export(schNet,'verification-schematic.net');
await focus(pcb); await eda.pcb_Document.save();
await pcb_focus(resolved.pcb.uuid);
if(await eda.pcb_Document.save()===false)throw Error('PCB save failed');
const components=await eda.pcb_PrimitiveComponent.getAll();
const pcbPassed=await eda.pcb_Drc.check(true,false,false);
const pcbErrors=pcbPassed ? [] : await eda.pcb_Drc.check(true,false,true);
const pcbErrors=await eda.pcb_Drc.check(true,false,true);
const pcbNet=await eda.pcb_ManufactureData.getNetlistFile('verification');
if(pcbNet)await pcb_export(pcbNet,'verification-pcb.net');
return {{schPassed,pcbPassed,schematicParts:parts.length,pcbParts:components.length,schErrors,pcbErrors}};'''
evidence = await execute(t,code,'Independent native delivery verification')
if(!pcbNet)throw Error('PCB netlist export missing');
await pcb_export(pcbNet,'verification-pcb.net');
return {{schPassed,pcbPassed,schematicParts:allParts.size,pcbParts:components.length,
schErrors:[...allErrors.values()],pcbErrors,schematic_id:resolved.schematic.uuid,
schematic_pages:resolved.schematic.page.map(p=>p.uuid),pcb_id:resolved.pcb.uuid}};'''
evidence=await execute(t,code,'Native error/warning verification across all schematic pages and PCB')
result=evaluate_verification(evidence['result'])
evidence['result']=result
write(task_dir(t['id'])/'native-verification.json',evidence)
r = evidence['result']
if not isinstance(r,dict) or r.get('schPassed') is not True or r.get('pcbPassed') is not True:
raise ValueError('Native checks failed: '+json.dumps(r,ensure_ascii=False)[:16000])
if r.get('schematicParts',0)<2 or r.get('pcbParts',0)<2:
raise ValueError('Native design is empty or incomplete')
return r
if require_pass and not result['accepted']:
raise ValueError('Native errors block delivery: '+json.dumps(result['blockingErrors'],ensure_ascii=False)[:16000])
return result
+120
View File
@@ -0,0 +1,120 @@
"""Reusable native exports, SVG conversion, OBJ rendering. No electrical design algorithms."""
import asyncio
import json
import os
from pathlib import Path
import shutil
import stat
import uuid
import zipfile
from .storage import SOURCE, workspace, inside, write, event
from .eda import execute, verify_native
def extract_archive(source, folder):
folder.mkdir(parents=True,exist_ok=True)
with zipfile.ZipFile(source) as archive:
if sum(i.file_size for i in archive.infolist())>1024*1024*1024:
raise ValueError('Native archive uncompressed size exceeds 1 GiB')
for item in archive.infolist():
target=inside(folder,item.filename)
if stat.S_ISLNK(item.external_attr>>16):raise ValueError('Archive symlinks not permitted')
if item.is_dir():target.mkdir(parents=True,exist_ok=True);continue
target.parent.mkdir(parents=True,exist_ok=True)
with archive.open(item) as src,target.open('wb') as dst:shutil.copyfileobj(src,dst)
return sorted(p for p in folder.rglob('*') if p.is_file())
def extract_step(source, folder):
if zipfile.is_zipfile(source):
paths=extract_archive(source,folder)
steps=[p for p in paths if p.suffix.lower() in {'.step','.stp'}]
if len(steps)!=1:raise ValueError('Expected one assembled STEP, found '+str(len(steps)))
return steps[0]
return source
def convert_schematic(source, folder):
# Native SVG retains labels that some native PDF exports omit.
import cairosvg
from pypdf import PdfWriter
paths=extract_archive(source,folder/'svg') if zipfile.is_zipfile(source) else [source]
svgs=[p for p in paths if p.suffix.lower()=='.svg' or b'<svg' in p.read_bytes()[:2000]]
if not svgs:raise ValueError('Native schematic SVG export contains no pages')
writer=PdfWriter();outputs=[]
for i,p in enumerate(svgs,1):
pdf=folder/f'schematic-{i}.pdf'
cairosvg.svg2pdf(bytestring=p.read_bytes(),write_to=str(pdf))
writer.append(str(pdf));outputs.append(pdf)
combined=folder/'schematic.pdf'
with combined.open('wb') as stream:writer.write(stream)
writer.close()
return combined,outputs
async def render_obj(t, source, folder):
paths=extract_archive(source,folder/'obj') if zipfile.is_zipfile(source) else [source]
objects=[p for p in paths if p.suffix.lower()=='.obj']
if len(objects)!=1:raise ValueError('Expected one native Outfit OBJ, found '+str(len(objects)))
output=folder/'assembly.png'
log=folder/'render.log'
blender=os.environ.get('PCB_BLENDER_BIN','/snap/bin/blender')
with log.open('wb') as stream:
proc=await asyncio.create_subprocess_exec(blender,'-b','-t','2','--python',str(SOURCE/'render_assembly.py'),'--',str(objects[0]),str(output),cwd=workspace(t),stdout=stream,stderr=stream)
try:await asyncio.wait_for(proc.wait(),180)
except (asyncio.TimeoutError,asyncio.CancelledError):
proc.kill();await proc.wait();raise
if proc.returncode or not output.is_file():raise ValueError('Native OBJ render failed; see '+str(log))
return output
async def prepare_delivery(t, schematic_id, pcb_id):
verification=await verify_native(t,schematic_id,pcb_id)
directory=workspace(t)/'artifacts'/('prepared-'+uuid.uuid4().hex[:10])
directory.mkdir(parents=True)
relative=directory.relative_to(workspace(t)/'artifacts').as_posix()
files=[];warnings=[]
def add(path,kind,label):files.append({'path':str(path.relative_to(workspace(t))),'kind':kind,'label':label})
async def export(expression,name,kind,label,doc):
result=await execute(t,'await pcb_focus('+json.dumps(doc)+');const file=await ('+expression+');return await pcb_export(file,'+json.dumps(relative+'/'+name)+');','Common export: '+label)
path=Path(result['exports'][0]['path'])
if kind:add(path,kind,label)
return path
# Fail before expensive exports if the circuit has errors; warnings are already accepted.
sch=verification['schematic_pages'][0];pcb=verification['pcb_id']
source=await export("eda.sch_ManufactureData.getSvgFile('schematic')",'schematic-source.zip',None,'原理图原生 SVG',sch)
try:
pdf,pages=await asyncio.to_thread(convert_schematic,source,directory)
add(pdf,'schematic','原理图 PDF')
except Exception as exc:
# SVG is an accepted final drawing; do not ask the agent to rebuild a PDF pipeline.
paths=extract_archive(source,directory/'svg-fallback') if zipfile.is_zipfile(source) else [source]
svgs=[p for p in paths if p.suffix.lower()=='.svg' or b'<svg' in p.read_bytes()[:2000]]
if not svgs:raise
for p in svgs:add(p,'schematic','原理图 SVG')
warnings.append({'type':'warning','code':'PDF_CONVERSION','message':str(exc),'fallback':'Native SVG supplied'})
await export("eda.sys_FileManager.getProjectFile('board',undefined,'epro')",'board.epro','project','可编辑原生工程',pcb)
# Native viewport is a supported layout image and avoids PDF compatibility work.
await execute(t,'const d=await pcb_focus('+json.dumps(pcb)+');await eda.dmt_EditorControl.zoomToAllPrimitives(d.tabId);return true;','Frame native PCB layout')
await export("eda.dmt_EditorControl.getCurrentRenderedAreaImage()",'layout.png','layout','PCB 原生布局图',pcb)
step=await export("eda.pcb_ManufactureData.get3DFile('assembly','step',['Component Model','Via','Silkscreen','Wire In Signal Layer'],'Outfit',false)",'assembly.step',None,'原生 STEP 装配',pcb)
step=await asyncio.to_thread(extract_step,step,directory/'step')
add(step,'step','原生 STEP(库模型完整性以原生导出为准)')
obj=await export("eda.pcb_ManufactureData.get3DFile('assembly','obj',['Component Model','Via','Silkscreen','Wire In Signal Layer'],'Outfit',false)",'assembled-3d-obj.zip','other','原生彩色 OBJ 装配包',pcb)
# Render this native assembly, never rebuild STEP meshes/colours to get a pass.
render=await render_obj(t,obj,directory)
add(render,'render','真实原生 OBJ 装配渲染')
warnings.append({'type':'warning','code':'NATIVE_MODEL_COVERAGE','message':'STEP 和 OBJ 由同一原生 PCB 导出;原生库可能缺失或简化部分器件模型,未逐件重建。OBJ 渲染不证明 STEP 每个器件完整。'})
for expr,name,kind,label in [
("eda.pcb_ManufactureData.getGerberFile('board')",'Gerber.zip','other','Gerber 制造文件'),
("eda.pcb_ManufactureData.getBomFile('BOM','csv')",'BOM.csv','bom','物料表')]:
try:await export(expr,name,kind,label,pcb)
except Exception as exc:warnings.append({'type':'warning','code':'OPTIONAL_EXPORT','message':label+': '+str(exc)})
report=directory/'export-report.json'
write(report,{'verification':verification,'warnings':warnings,'policy':'native export; no cosmetic repair loop'})
add(report,'report','检查与导出警告记录')
result={'files':files,'schematic_id':verification['schematic_id'],'pcb_id':pcb,'warnings':warnings,
'instruction':'Inspect the native drawings/render once, then pass these files to pcb_deliver. Explicit warnings do not block. Do not rebuild STEP or packaging scripts.'}
write(directory/'prepared.json',result)
event(t,'delivery.prepared',{'path':str(directory),'files':len(files),'warnings':warnings})
return result
+10 -118
View File
@@ -1,126 +1,18 @@
#!/usr/bin/env python3
"""Run the installed Freerouting 1.9.0 without interactive startup dialogs.
"""Retired compatibility entry point: never start an external router.
This is a process/argument adapter, not a PCB design or routing algorithm.
Kept so old conversation commands fail clearly without spawning Java/Xvfb.
"""
import argparse
import math
import os
from pathlib import Path
import shutil
import signal
import subprocess
import sys
import tempfile
MESSAGE = ("easyeda-native-v1: Freerouting is disabled. Use pcb_eda to operate "
"native EasyEDA lines, vias, copper and native routing APIs. "
"DSN/SES routing exchange is no longer supported.")
# Version-specific CLI contract. Never pass unknown/help/input/dialog switches
# through to Java: 1.9.0 silently ignores some of them and opens an idle GUI.
VALUE_OPTIONS = {'-mp', '-mt', '-oit', '-us', '-hr', '-is', '-inc', '-dr', '-l'}
FLAG_OPTIONS = {'-im', '-da'}
def router_options(values):
values = list(values)
if values[:1] == ['--']:
values.pop(0)
result = []
while values:
option = values.pop(0)
if option in FLAG_OPTIONS:
result.append(option)
elif option in VALUE_OPTIONS:
if not values or values[0].startswith('-'):
raise ValueError(f'{option} requires a value')
result.extend([option, values.pop(0)])
else:
raise ValueError(f'Unsupported router option: {option}; use wrapper --help')
return result
def stop_process(process):
# Java and the private Xvfb belong to this process group only.
try:
os.killpg(process.pid, signal.SIGTERM)
except ProcessLookupError:
return
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
pass
try:
os.killpg(process.pid, signal.SIGKILL)
except ProcessLookupError:
pass
process.wait()
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--input', required=True, type=Path, help='Existing DSN input')
parser.add_argument('--output', required=True, type=Path, help='New SES output; existing files are refused')
default_jar = Path(os.environ.get('PCB_SESSION_ROOT', '/home/wpz/auto_pcb_2/persistent-runtime')) / 'resources/freerouting.jar'
parser.add_argument('--jar', type=Path, default=os.environ.get('PCB_FREEROUTING_JAR', str(default_jar)))
parser.add_argument('--timeout', type=float, default=900, help='Maximum process seconds (default 900); partial output is not accepted')
parser.add_argument('--visible', action='store_true', help='Diagnostic only: use the current desktop instead of private Xvfb')
parser.add_argument('router_args', nargs=argparse.REMAINDER, help='After --: Freerouting options, e.g. -mp 30 -mt 1')
args = parser.parse_args(argv)
try:
options = router_options(args.router_args)
source, target, jar = args.input.resolve(), args.output.resolve(), args.jar.resolve()
if not math.isfinite(args.timeout) or args.timeout <= 0:
raise ValueError('--timeout must be a positive finite number')
if not source.is_file() or source.suffix.lower() != '.dsn':
raise ValueError('--input must be an existing .dsn file')
if target.suffix.lower() != '.ses' or target.exists() or args.output.is_symlink():
raise ValueError('--output must be a new .ses file (choose a new name for each attempt)')
if not jar.is_file():
raise ValueError(f'Freerouting JAR not found: {jar}')
java = shutil.which('java')
if not java:
raise ValueError('Java is not installed or not on PATH')
xvfb = shutil.which('xvfb-run')
if not args.visible and (not xvfb or not shutil.which('Xvfb') or not shutil.which('xauth')):
raise ValueError('Install xvfb and xauth for unattended routing; --visible is diagnostic only')
target.parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix='.freerouting-', dir=target.parent) as temporary:
temporary = Path(temporary)
home = temporary / 'home'
home.mkdir()
# Do not auto-load an adjacent old .rules/.bin snapshot and prompt
# for confirmation. Explicit -dr remains available to the agent.
isolated_source = temporary / 'board.dsn'
shutil.copyfile(source, isolated_source)
pending = temporary / 'result.ses'
command = [java, f'-Duser.home={home}', f'-Djava.io.tmpdir={temporary}', '-jar', str(jar),
'-de', str(isolated_source), '-do', str(pending), *options, '-dct', '0', '-da']
if not args.visible:
command = [xvfb, '-a', '-f', str(temporary / 'Xauthority'), '-s', '-screen 0 1280x1024x24 -nolisten tcp', *command]
env = dict(os.environ, TMPDIR=str(temporary))
print(f'Freerouting: {source} -> {target}; confirmation disabled; timeout={args.timeout:g}s', flush=True)
process = subprocess.Popen(command, env=env, start_new_session=True)
try:
code = process.wait(timeout=args.timeout)
except subprocess.TimeoutExpired:
stop_process(process)
print('Freerouting timed out; no output published. Inspect the log before choosing another attempt.', file=sys.stderr)
return 124
except KeyboardInterrupt:
stop_process(process)
return 130
if code:
print(f'Freerouting exited with {code}; no output published', file=sys.stderr)
return code if code > 0 else 1
if not pending.is_file() or pending.stat().st_size < 20 or not pending.read_bytes().lstrip().startswith(b'(session'):
raise ValueError('Freerouting did not produce a valid SES session file')
# Same filesystem, no overwrite race and no stale/partial SES success.
os.link(pending, target)
print(f'Saved {target} ({target.stat().st_size} bytes). Import and run native DRC; process success is not board validation.', flush=True)
return 0
except (ValueError, OSError) as error:
print(f'Freerouting launcher: {error}', file=sys.stderr)
return 2
def main():
print(MESSAGE, file=sys.stderr)
return 2
if __name__ == '__main__':
sys.exit(main())
raise SystemExit(main())
+13 -5
View File
@@ -10,12 +10,20 @@ EDA access: call pcb_eda with a JavaScript async function body. The server creat
The helper `await pcb_export(file, 'relative/name.ext')` inside pcb_eda stores a native File/Blob in workspace/artifacts and returns its filename and bytes. It is a transport convenience, not a fake exporter. `pcb_eda` also accepts code_file to execute a JS file you wrote under the workspace. Long raw results are saved to workspace/evidence for you to read with shell tools. Read API signatures from the supplied api-reference directory before guessing; use the class index and individual class docs. EDA native coordinate units are documented in the API. Always distinguish schematic page IDs, board IDs and editor TAB IDs. Focus the requested editor before global sch_/pcb_ calls, and read back. Schematic getAll('part') excludes drawing frames. Consult the native DRC documentation for exact return types and error groups.
External utilities: Java/Freerouting and Blender are installed. You may export DSN and import SES, use native routing APIs, or implement your own routing scripts. Decide from evidence; no website algorithm dictates routing. If external router output is partial, retain the best actual result and fix remaining connections. Use genuine exported OBJ/STEP geometry for renders. Never draw a substitute board picture or invent 3D components. STEP exports may be ZIP-wrapped: inspect, extract and independently validate them. Do not treat a successful export or empty DRC array as proof of electrical correctness.
Native-only design contract (easyeda-native-v1): schematic, placement, routing and electrical checks must remain in the native EasyEDA project. Use pcb_eda for every EDA read/write, including native schematic/PCB primitives, native routing APIs, save/reopen and sch_Drc/pcb_Drc. Do not call the EDA CLI directly or operate alternate sessions to bypass this tool. Do not use Freerouting, KiCad, another EDA or an external router; do not export DSN, import SES, or exchange auto-layout/auto-route JSON. The former Freerouting launcher is disabled. Earlier conversation instructions permitting it are superseded, including when resuming an old task. Read and repair the saved native project; never replay an old external-routing or SES-import script.
Freerouting deployment contract: use the Python freerouting.py launcher supplied in the production message for all external Freerouting runs. Its --help is handled locally and does not launch Java. The installed 1.9.0 JAR understands -help, NOT --help: the latter opens an idle file-selection window. Never invoke the JAR without an existing DSN input and a new SES output, and do not use raw java -jar probes. The launcher always supplies -dct 0 (no 20-second confirmation) and runs in private Xvfb; do not add -Djava.awt.headless=true because this GUI-based version throws HeadlessException. Keep logs in your workspace; after a timeout inspect evidence and choose a recovery rather than blindly retrying. Use a new output filename for each attempt. The launcher only controls process startup, not engineering decisions. SES existence or router exit zero does not prove full connectivity or native DRC success.
Planning and verification: Python/JavaScript may compute placement coordinates, route paths, current/thermal estimates and supplementary diagnostics from native object readbacks. Apply computed results directly through native component, line, via and copper primitives. Do not build a second authoritative PCB model in another CAD tool. Native ERC/DRC, schematic/PCB pin-net consistency and native geometry readback determine completion. Neither an offline geometry check nor an exported routing file substitutes for native validation. Inspect unconnected pads and their available escape/via space before fixing wide power copper; plan power paths and signal escapes together. Keep checkpoints and compare complete native-check results after repair batches; repeated non-improvement requires a different placement/routing strategy, not blind repetition. This does not prescribe a fixed backend routing algorithm.
Native operation recovery: a timeout means an uncertain mutation outcome. Read the live board and wait/check for ongoing native routing before retrying; do not start competing routing operations or fall back to external exchange. Keep all approved nets, functions, manufacturing rules and true native checks. If a concrete native-tool limitation prevents completion after investigation, retain the draft and report evidence with pcb_blocked; never hide errors to deliver.
Export and visualization utilities: final editable native project, schematic/layout images, netlists for comparison, manufacturing files, BOM, STEP and OBJ exports remain allowed. Blender and CAD utilities may render or inspect exported 3D assembly representation only; they must not change PCB electrical design or geometry or replace native electrical checks. Use genuine exported geometry, never substitute board pictures or invented components. STEP exports may be ZIP-wrapped: inspect, extract and independently validate them. An export or empty diagnostic array alone is not proof of electrical correctness.
Engineering: verify regulator pinout, supply limits/decoupling, reset/boot behavior, programming access and connector pin labeling. Check exact chip/module manufacturer's reference circuitry. Antenna keepout, plug access and component envelopes must be respected. Layout and routing must correspond to the actual schematic pin/net mapping. Never remove required nets/components, mask checks, disable DRC categories or weaken rules to obtain a pass. Use sensible manufacturing clearances and trace widths and leave unconnected pins intentionally marked, not accidentally unrouted. Save and reopen/check the native design when practical. Inspect schematic, top layout and genuine 3D views yourself before submission.
Model appearance: the final assembled STEP must retain the actual native board/component/face colors, not just geometry. If you rebuild or transform an assembly, preserve XCAF color/material attributes and instance/face associations alongside the shapes. Transferring bare TopoDS shapes into a new document loses these attributes even when STEPCAFControl_Writer is used. Export with color mode enabled, then reopen the exact final STEP and verify its applied surface colors and rendered appearance. A colored OBJ/MTL or PNG does not prove that STEP colors survived. Do not arbitrarily paint geometry or add unused color declarations to satisfy validation. If a conversion loses appearance, repair the model export in this same session without redesigning the circuit or weakening electrical checks. Also deliver the genuine final OBJ/MTL and referenced textures as a clearly named assembled-3d-obj.zip when available, matching the final board geometry; this supports an independent colored appearance preview.
Delivery: export native editable project, schematic image/PDF, routed layout image/PDF, assembled board STEP and a rendered 3D PNG/JPEG. Also include BOM, pin/net evidence and verification notes. Use pcb_deliver with those files and actual schematic/PCB document IDs. The service independently runs native checks and validates file formats and applied STEP surface colors. If rejected, inspect feedback and correct the design in this same session; do not claim completion before delivery succeeds. A failed design can be retained with pcb_blocked and exact evidence, but do not use this for ordinary recoverable mistakes. Real hardware testing is outside this software delivery; do not claim bench verification.
Shared delivery helpers and acceptance policy (native-errors-block-warnings-record-v1):
- Call pcb_check as soon as the schematic/PCB pair exists, and again before final exports. It resolves a schematic container or page ID, checks all pages and the selected PCB, and returns explicit warnings separately from blocking errors. Explicit warnings are permitted and included in delivery evidence. Do not change design rules, omit checks, or relabel errors to warnings. Unknown/missing diagnostics are not a pass. PCB DRC alone does not establish circuit functionality or real hardware performance.
- Use pcb_documents(), pcb_focus(id) and pcb_capabilities() inside pcb_eda instead of guessing document/tab IDs or APIs that the installed version may not support. pcb_export automatically transfers large File/Blob exports in chunks. Do not write your own transport/chunking scripts.
- After the circuit checks pass, use pcb_prepare_delivery for native project, schematic drawings, layout image, STEP/OBJ exports, shared installed rendering and standard file preparation. It returns files for pcb_deliver. Inspect drawings and the genuine rendered assembly once; do not regenerate an already valid deliverable for cosmetic perfection. The backend creates the manifest, checksums and delivery ZIP; do not write packaging scripts or install CAD/render dependencies per task.
- Native STEP may contain simplified/missing library components or limited colour. Retain the actual native export, provide native OBJ/MTL/render and record the limitations. These are non-blocking appearance warnings; do not rebuild tessellated STEP assemblies or manually transplant model geometry to satisfy colour checks. Invalid/empty files remain errors. Never invent replacement board pictures or claim model completeness you did not verify.
- If these helper tools are absent in a resumed older thread, call pcb_eda with code containing ONLY JSON: {"pcb_backend_tool":"prepare_delivery","schematic_id":"...","pcb_id":"..."} (or pcb_backend_tool="check"). This is dispatched by the backend to the exact same common tools. Normal JavaScript and automatic pcb_export still work. Do not recreate utility scripts.
- Deliver native editable project, schematic image/PDF/SVG, routed layout image/PDF, native assembled STEP and genuine 3D render, with BOM and engineering evidence when available. pcb_deliver runs the independent native gate and file checks. If rejected, repair the concrete error. Explicit warning-only results are accepted and must not trigger a warning-removal loop. Hardware bench verification remains outside software delivery.
+33
View File
@@ -0,0 +1,33 @@
"""Document resolution and capability helpers shared by verification and agent scripts."""
HELPERS_JS = r'''
const pcb_documents = async () => ({
schematics: await eda.dmt_Schematic.getAllSchematicsInfo(),
pcbs: await eda.dmt_Pcb.getAllPcbsInfo()
});
const pcb_capabilities = () => {
const out={};
for(const [group,names] of Object.entries({
pcb_Document:['autoRouting','getCalculatingRatlineStatus','getCanvasUpdateCalculationStatus','save'],
pcb_ManufactureData:['get3DFile','getPdfFile','getGerberFile'],
sch_ManufactureData:['getSvgFile','getNetlistFile'],
dmt_EditorControl:['openDocument','activateDocument']
}))out[group]=Object.fromEntries(names.map(n=>[n,typeof eda[group]?.[n]==='function']));
return out;
};
const pcb_focus = async (id) => {
const all=await eda.dmt_Schematic.getAllSchematicsInfo();
const container=all.find(s=>s.uuid===id);
const resolved=container?.page?.[0]?.uuid || id;
const tab=await eda.dmt_EditorControl.openDocument(resolved);
if(!tab || !await eda.dmt_EditorControl.activateDocument(tab))throw Error('Cannot focus native document '+id+' (resolved '+resolved+')');
return {documentId:resolved,tabId:tab};
};
const pcb_resolve = async (schematicId,pcbId) => {
const inventory=await pcb_documents();
const schematic=inventory.schematics.find(s=>s.uuid===schematicId || s.page?.some(p=>p.uuid===schematicId));
const pcb=inventory.pcbs.find(p=>p.uuid===pcbId);
if(!schematic?.page?.length || !pcb)throw Error('Unknown schematic/page or PCB ID. Read pcb_documents(); do not use tab IDs. '+JSON.stringify(inventory));
if(schematic.parentProjectUuid && pcb.parentProjectUuid && schematic.parentProjectUuid!==pcb.parentProjectUuid)throw Error('Schematic and PCB belong to different projects');
return {schematic,pcb};
};
'''
+58
View File
@@ -0,0 +1,58 @@
"""Native design workflow contract and EDA transport guard (not a shell sandbox)."""
import json
DESIGN_POLICY = 'easyeda-native-v1'
POLICY_TEXT = '''Design policy: easyeda-native-v1.
Create, edit, lay out, route, save and check the circuit only in the task's native EasyEDA project through pcb_eda.
Use native schematic/PCB primitives and native routing APIs. Do not use Freerouting, KiCad or any external EDA/router, export DSN, import SES, or exchange auto-layout/auto-route JSON files.
Local Python/JavaScript may calculate coordinates, paths and diagnostics from native object readbacks; apply their results by creating/modifying native EasyEDA objects, not by importing a converted design or routing file. Native ERC/DRC and actual native net/geometry readback are authoritative; offline checks are supplementary only.
Use pcb_eda for all EDA operations; do not bypass it with direct CLI, browser or alternate sessions. Keep the accepted circuit and manufacturing constraints. A native routing timeout has an unknown outcome: inspect the live board before another mutation. Never fall back to external routing after an error.
Validation policy: native-errors-block-warnings-record-v1. Explicit native warnings are allowed and must be recorded; actual errors and unknown/incomplete check results block delivery. Do not change electrical rules to silence errors. STEP colour/model-library appearance warnings are non-blocking: use the native STEP and native OBJ render, disclose limitations, and do not rebuild STEP geometry or spend repeated turns repairing cosmetic/library warnings. The server packages accepted delivery files; do not write packaging scripts. Call pcb_check early, then pcb_prepare_delivery when ready, then pcb_deliver. If helper tools are not present in an older session, use pcb_documents(), pcb_focus(id), pcb_capabilities() inside pcb_eda; pcb_export automatically transfers large files in chunks, and pcb_deliver applies the same warning-aware gate.
Earlier conversation instructions offering external routing are superseded. On resume, inspect the saved native board; do not replay old DSN/SES/import scripts. Existing native geometry may be retained and repaired after checking it.
Final native project, schematic/layout images, manufacturing outputs, STEP/OBJ and BOM exports remain allowed. Blender/CAD utilities may render or validate the exported 3D assembly only; they must not design, route or electrically validate the PCB instead of EasyEDA.
'''
WORKSPACE_RULES = '''Use only this workspace for generated PCB scripts/files. Do not read or use legacy PCB pipelines or other PCB tasks. Official API references are under api-reference. Do not edit service code or unrelated projects. Do not spawn subagents.
''' + POLICY_TEXT
BLOCKED_METHODS = {
'pcb_ManufactureData': ['getDsnFile', 'getAutoRouteJsonFile', 'getAutoRouteJsonFileForJRouter'],
'pcb_Document': ['importAutoRouteSesFile', 'importAutoRouteJsonFile', 'importAutoLayoutJsonFile'],
}
def refresh_workspace_rules(directory):
path = directory / 'AGENTS.md'
marker = '\n## Backend native design policy\n'
existing = path.read_text() if path.exists() else ''
# Preserve recovery notes and task-specific instructions before our section.
path.write_text(existing.split(marker)[0] + marker + WORKSPACE_RULES)
def guarded_script(code):
"""Shadow eda for the submitted script, including computed/aliased property access.
The outer invocation retains the real EDA object for the transport. This is
a workflow guard, not isolation from deliberately hostile JavaScript.
"""
return '''const __nativeOnly = (native) => {
const blocked = ''' + json.dumps(BLOCKED_METHODS) + ''';
const cache = new Map();
return new Proxy(native, {get(target, group) {
const api = Reflect.get(target, group);
if (!Object.prototype.hasOwnProperty.call(blocked, group)) return api;
if (!cache.has(group)) cache.set(group, new Proxy(api, {get(object, method) {
if (blocked[group].includes(method)) throw new Error('easyeda-native-v1: external layout/routing exchange is disabled: '+String(group)+'.'+String(method)+'. Use native primitives or native routing APIs.');
const value = Reflect.get(object, method);
return typeof value === 'function' ? value.bind(object) : value;
}}));
return cache.get(group);
}});
};
return await (async (eda) => {
''' + code + '\n})(__nativeOnly(eda));'
def validate_export_name(name):
if name.lower().endswith(('.dsn', '.ses')):
raise ValueError('easyeda-native-v1: DSN/SES routing exchange exports are disabled')
+32
View File
@@ -0,0 +1,32 @@
"""Run with installed Blender; render original OBJ/MTL geometry, no CAD rebuilding."""
import sys
import math
import bpy
from mathutils import Vector
source, output = sys.argv[sys.argv.index('--')+1:][:2]
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
bpy.ops.wm.obj_import(filepath=source, forward_axis='Y', up_axis='Z')
meshes=[o for o in bpy.context.scene.objects if o.type=='MESH' and len(o.data.polygons)]
if not meshes:raise RuntimeError('Native OBJ has no renderable geometry')
points=[o.matrix_world @ Vector(v) for o in meshes for v in o.bound_box]
lo=Vector([min(p[i] for p in points) for i in range(3)])
hi=Vector([max(p[i] for p in points) for i in range(3)])
center=(lo+hi)/2
size=max(hi-lo)
if not math.isfinite(size) or size<=0:raise RuntimeError('Invalid native assembly bounds')
def aim(o):o.rotation_euler=(center-o.location).to_track_quat('-Z','Y').to_euler()
bpy.ops.object.camera_add(location=center+Vector((1.1,-1.4,1.5))*size)
camera=bpy.context.object;aim(camera);camera.data.type='ORTHO';camera.data.ortho_scale=size*1.7
camera.data.clip_end=max(size*20,1000);camera.data.clip_start=max(size*.00001,.0001)
scene=bpy.context.scene;scene.camera=camera
for xyz,energy in [((1,-1,2),1.5),((-1,-.5,1),.8),((0,1,1.5),1.0)]:
bpy.ops.object.light_add(type='AREA',location=center+Vector(xyz)*size)
lamp=bpy.context.object;lamp.data.energy=energy*size*size;lamp.data.size=size;aim(lamp)
scene.render.engine='CYCLES';scene.cycles.samples=16
scene.world.use_nodes=True;scene.world.node_tree.nodes['Background'].inputs['Strength'].default_value=.7
scene.render.resolution_x=1400;scene.render.resolution_y=1100;scene.render.resolution_percentage=100
scene.view_settings.view_transform='Standard';scene.render.image_settings.file_format='PNG';scene.render.filepath=output
bpy.ops.render.render(write_still=True)
print('NATIVE_ASSEMBLY_RENDER',len(meshes),'meshes',len(points),'bounds points')
+10
View File
@@ -0,0 +1,10 @@
CairoSVG==2.7.1
pypdf==5.1.0
cairocffi==1.7.1
cffi==2.1.1
cssselect2==0.10.1
defusedxml==0.7.1
pillow==13.0.0
pycparser==3.12
tinycss2==1.5.1
webencodings==0.6.1
+82
View File
@@ -0,0 +1,82 @@
import asyncio
import base64
import json
from pathlib import Path
import re
import tempfile
import unittest
from unittest.mock import patch
import zipfile
from codex_pcb.checks import classify_diagnostics, evaluate_verification
from codex_pcb import eda
from codex_pcb.exports import extract_archive, convert_schematic
from codex_pcb.delivery import inspect
class WarningGate(unittest.TestCase):
def test_native_warning_false_is_accepted_and_retained(self):
warning={'type':'warn','rule':'ATTRMATCHCODE','primitives':[{'id':x} for x in ['JP1','JP2','J4','J5','J6']]}
r=evaluate_verification(dict(schPassed=False,pcbPassed=True,schErrors=[warning],pcbErrors=[],schematicParts=104,pcbParts=104))
self.assertTrue(r['accepted']);self.assertEqual(r['warnings']['schematic'],[warning])
def test_error_unknown_missing_and_inconsistent_results_block(self):
for rows,ok in [([{'type':'error'}],True),([{'type':'warn'},{'rule':'UNKNOWN'}],False),([],False),(None,True),([],None),([{'type':'warn','list':[{'type':'error'}]}],True)]:
with self.subTest(rows=rows,ok=ok):self.assertFalse(classify_diagnostics(rows,ok)['passed'])
def test_nested_warning_and_mixed_errors(self):
self.assertTrue(classify_diagnostics([{'type':'warning','list':[{'rule':'LIB'}]}],False)['passed'])
self.assertFalse(classify_diagnostics([{'type':'warn'},{'type':'error'}],False)['passed'])
def test_missing_geometry_still_blocks_but_step_appearance_does_not(self):
with tempfile.TemporaryDirectory(dir=Path(__file__).parent) as tmp:
p=Path(tmp)/'assembly.step'
p.write_text("ISO-10303-21;\nHEADER;ENDSEC;DATA;#1=CARTESIAN_POINT('',(0.,0.,0.));#2=SHAPE_REPRESENTATION('',(#1),#3);ENDSEC;END-ISO-10303-21;")
self.assertTrue(inspect(p,'step')['warnings'])
p.write_text('not a model'*30)
with self.assertRaises(ValueError):inspect(p,'step')
class ExportSafety(unittest.TestCase):
def test_zip_escape_rejected(self):
with tempfile.TemporaryDirectory(dir=Path(__file__).parent) as tmp:
root=Path(tmp);p=root/'evil.zip'
with zipfile.ZipFile(p,'w') as z:z.writestr('../escape','no')
with self.assertRaises(ValueError):extract_archive(p,root/'output')
self.assertFalse((root/'escape').exists())
def test_svg_pages_converted_to_multipage_pdf(self):
from pypdf import PdfReader
with tempfile.TemporaryDirectory(dir=Path(__file__).parent) as tmp:
root=Path(tmp);p=root/'pages.zip'
with zipfile.ZipFile(p,'w') as z:
for n in range(2):z.writestr(f'page-{n}.svg','<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><text x="10" y="20">R1 GND</text></svg>')
pdf,pages=convert_schematic(p,root/'output')
self.assertEqual(len(PdfReader(pdf).pages),2)
class ChunkTransport(unittest.IsolatedAsyncioTestCase):
async def test_large_transfer_and_truncation_preserve_existing_file(self):
for truncated in [False,True]:
with tempfile.TemporaryDirectory(dir=Path(__file__).parent) as tmp:
folder=Path(tmp);dst=folder/'artifacts/large.bin';dst.parent.mkdir();dst.write_bytes(b'previous')
payload=bytes([37])*(9*1024*1024+17);calls=[]
async def invoke(args,code=None,timeout=210):
calls.append(code)
if 'const __files=[]' in code:return {'result':True,'files':[{'name':'large.bin','bytes':len(payload),'index':0}]}
if code.startswith('delete '):return True
begin,end=map(int,re.search(r'f.slice\((\d+),(\d+)\)',code).groups())
data=payload[begin:end]
if truncated and begin:data=data[:-1]
return {'base64':base64.b64encode(data).decode()}
async def lock():return (folder/'lock').open('a+')
t={'approval':{'hash':'test'},'state':'running','eda_session':'test'}
with patch.object(eda,'workspace',return_value=folder),patch.object(eda,'event'),patch.object(eda,'host_lock',side_effect=lock),patch.object(eda,'cli',side_effect=invoke),patch.object(eda,'EDA_LOCK',asyncio.Lock()):
if truncated:
with self.assertRaisesRegex(ValueError,'Truncated'):await eda.execute(t,'return true')
self.assertEqual(dst.read_bytes(),b'previous')
else:
await eda.execute(t,'return true');self.assertEqual(dst.read_bytes(),payload)
self.assertTrue(calls[-1].startswith('delete '));self.assertFalse(list(dst.parent.glob('*.partial')))
class ResumedToolCompatibility(unittest.IsolatedAsyncioTestCase):
async def test_old_eda_tool_dispatches_shared_preparation(self):
from unittest.mock import AsyncMock
from codex_pcb import app
task={'state':'running','approval':{'hash':'x'}}
prepared={'files':[{'kind':'step','path':'artifacts/board.step'}]}
with patch.object(app,'event'),patch.object(app,'frozen'),patch.object(app,'prepare_delivery',new_callable=AsyncMock,return_value=prepared) as prepare,patch.object(app,'execute',new_callable=AsyncMock) as execute:
result=await app.handle(task,'item/tool/call',{'tool':'pcb_eda','callId':'test','arguments':{'label':'Common delivery','code':json.dumps({'pcb_backend_tool':'prepare_delivery','schematic_id':'sch','pcb_id':'pcb'})}})
self.assertTrue(result['success']);prepare.assert_awaited_once_with(task,'sch','pcb');execute.assert_not_called()
+15 -74
View File
@@ -1,5 +1,4 @@
"""Launcher boundaries; no live EDA application or real board is modified."""
import json
"""Old task commands must fail without spawning Java/Xvfb or changing files."""
import os
from pathlib import Path
import subprocess
@@ -9,75 +8,17 @@ import unittest
LAUNCHER = Path(__file__).resolve().parents[1] / 'freerouting.py'
class LauncherTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory(dir=Path(__file__).parent)
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.source = self.root / 'board.dsn'
self.source.write_text('(pcb test)')
self.jar = self.root / 'router.jar'
self.jar.touch()
self.output = self.root / 'result.ses'
java = self.root / 'java'
java.write_text(f'#!{sys.executable}\n' + '''import json,os,sys,time
from pathlib import Path
args=sys.argv[1:]
Path(os.environ['CALL_LOG']).write_text(json.dumps(args))
if os.environ.get('STALL'):time.sleep(30)
if not os.environ.get('NO_OUTPUT'):
Path(args[args.index('-do')+1]).write_text('(session board (routes (network)))')
''')
java.chmod(0o755)
self.env = dict(os.environ, PATH=str(self.root), CALL_LOG=str(self.root / 'calls.json'))
def run_cli(self, *extra, help_only=False):
args = [] if help_only else ['--input', str(self.source), '--output', str(self.output), '--jar', str(self.jar), '--visible']
return subprocess.run([sys.executable, str(LAUNCHER), *args, *extra], env=self.env, capture_output=True, text=True, timeout=10)
def test_help_never_starts_java(self):
r = self.run_cli('--help', help_only=True)
self.assertEqual(r.returncode, 0)
self.assertFalse((self.root / 'calls.json').exists())
def test_missing_input_does_not_open_file_picker(self):
self.source.unlink()
self.assertEqual(self.run_cli().returncode, 2)
self.assertFalse((self.root / 'calls.json').exists())
def test_unknown_help_and_dialog_override_are_rejected(self):
for args in [('--', '--help'), ('--', '-dct', '20')]:
self.assertEqual(self.run_cli(*args).returncode, 2)
self.assertFalse((self.root / 'calls.json').exists())
def test_route_publishes_ses_without_changing_source(self):
r = self.run_cli('--', '-mp', '7', '-mt', '1')
self.assertEqual(r.returncode, 0, r.stderr)
args = json.loads((self.root / 'calls.json').read_text())
self.assertEqual(args[args.index('-dct')+1], '0')
self.assertNotEqual(args[args.index('-de')+1], str(self.source))
self.assertEqual(self.source.read_text(), '(pcb test)')
self.assertTrue(self.output.read_text().startswith('(session'))
self.assertEqual(list(self.root.glob('.freerouting-*')), [])
def test_existing_output_is_preserved(self):
self.output.write_text('previous result')
self.assertEqual(self.run_cli().returncode, 2)
self.assertEqual(self.output.read_text(), 'previous result')
self.assertFalse((self.root / 'calls.json').exists())
def test_exit_zero_without_output_is_failure(self):
self.env['NO_OUTPUT'] = '1'
self.assertEqual(self.run_cli().returncode, 2)
self.assertFalse(self.output.exists())
def test_timeout_does_not_publish_partial_result(self):
self.env['STALL'] = '1'
self.assertEqual(self.run_cli('--timeout', '0.2').returncode, 124)
self.assertFalse(self.output.exists())
self.assertEqual(list(self.root.glob('.freerouting-*')), [])
if __name__ == '__main__':
unittest.main()
class RetiredLauncherTest(unittest.TestCase):
def test_old_commands_cannot_route_or_open_windows(self):
with tempfile.TemporaryDirectory(dir=Path(__file__).parent) as tmp:
root = Path(tmp)
source, output = root/'board.dsn', root/'result.ses'
source.write_text('(pcb original)')
output.write_text('previous result')
for args in [[], ['--help'], ['--input',str(source),'--output',str(output),'--visible']]:
r = subprocess.run([sys.executable,str(LAUNCHER),*args],env=dict(os.environ,PATH=str(root)),capture_output=True,text=True,timeout=5)
self.assertEqual(r.returncode,2)
self.assertIn('easyeda-native-v1',r.stderr)
self.assertEqual(source.read_text(),'(pcb original)')
self.assertEqual(output.read_text(),'previous result')
self.assertEqual(len(list(root.iterdir())),2)
+67
View File
@@ -0,0 +1,67 @@
import asyncio
import json
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
from unittest.mock import AsyncMock, patch
from codex_pcb.native_policy import BLOCKED_METHODS, guarded_script, validate_export_name, refresh_workspace_rules
from codex_pcb import eda
class NativePolicyTest(unittest.TestCase):
def run_js(self, code):
self.assertIsNotNone(shutil.which('node'), 'Node is required to verify the EDA guard')
r = subprocess.run(['node','-e',code],capture_output=True,text=True,timeout=10)
self.assertEqual(r.returncode,0,r.stderr)
return json.loads(r.stdout)
def test_native_edit_route_drc_and_delivery_exports_still_work(self):
result = self.run_js('''const eda={
pcb_PrimitiveLine:{create:async()=>({net:'GND'})},
pcb_Document:{flag:7,doLayout:async function(){return this.flag},doRoute:async function(){return this.flag},save:async()=>true,importChanges:async()=>true},
pcb_Drc:{check:async()=>true},sch_Drc:{check:async()=>true},
pcb_ManufactureData:{getStepFile:async()=> 'STEP',getNetlistFile:async()=> 'NET'}
};(async()=>{''' + guarded_script('''return [await eda.pcb_PrimitiveLine.create(),await eda.pcb_Document.doRoute(),await eda.pcb_Document.save(),await eda.pcb_Document.importChanges(),await eda.pcb_Drc.check(),await eda.sch_Drc.check(),await eda.pcb_ManufactureData.getStepFile(),await eda.pcb_ManufactureData.getNetlistFile()];''') + '''})().then(x=>console.log(JSON.stringify(x))).catch(e=>{console.error(e);process.exit(1)});''')
self.assertEqual(result,[{'net':'GND'},7,True,True,True,True,'STEP','NET'])
def test_exchange_calls_are_blocked_even_with_computed_names_and_aliases(self):
for group, methods in BLOCKED_METHODS.items():
for method in methods:
script = f'''const api=eda[{json.dumps(group)}]; return await api[{json.dumps(method)}]();'''
code = f'''let invoked=false;const eda={{{json.dumps(group)}:{{{json.dumps(method)}:()=>{{invoked=true;}}}}}};
(async()=>{{{guarded_script(script)}}})().then(()=>{{throw Error('allowed external exchange')}}).catch(e=>console.log(JSON.stringify({{invoked,message:e.message}})));'''
result = self.run_js(code)
self.assertFalse(result['invoked'])
self.assertIn('easyeda-native-v1',result['message'])
def test_file_guard_and_workspace_recovery_notes(self):
for name in ['route.dsn','a/route.SES']:
with self.assertRaises(ValueError):validate_export_name(name)
for name in ['board.epro2','board.step','board.obj','board.png','schematic.net','diagnostic.json']:
validate_export_name(name)
with tempfile.TemporaryDirectory(dir=Path(__file__).parent) as tmp:
p=Path(tmp);(p/'AGENTS.md').write_text('Recovery: open saved project.\n')
refresh_workspace_rules(p);refresh_workspace_rules(p)
text=(p/'AGENTS.md').read_text()
self.assertIn('Recovery: open saved project.',text)
self.assertEqual(text.count('## Backend native design policy'),1)
class NativeTransportTest(unittest.IsolatedAsyncioTestCase):
async def test_actual_transport_wrapper_executes_and_blocks_before_native_method(self):
with tempfile.TemporaryDirectory(dir=Path(__file__).parent) as tmp:
folder=Path(tmp)
async def invoke(args, code=None, timeout=210):
harness='''const eda={pcb_Document:{save:async()=>true,importAutoRouteSesFile:()=>{throw Error('UNGUARDED')}}};(async()=>{'''+code+'''})().then(x=>console.log(JSON.stringify(x))).catch(e=>{console.error(e.message);process.exit(1)});'''
r=subprocess.run(['node','-e',harness],capture_output=True,text=True,timeout=10)
if r.returncode:raise RuntimeError(r.stderr)
return json.loads(r.stdout)
async def lock():return (folder/'lock').open('a+')
t={'approval':{'hash':'test'},'state':'running','eda_session':'test'}
with patch.object(eda,'workspace',return_value=folder),patch.object(eda,'event'),patch.object(eda,'host_lock',side_effect=lock),patch.object(eda,'cli',side_effect=invoke),patch.object(eda,'EDA_LOCK',asyncio.Lock()):
result=await eda.execute(t,'return await eda.pcb_Document.save();')
self.assertTrue(result['result'])
with self.assertRaisesRegex(RuntimeError,'easyeda-native-v1'):
await eda.execute(t,'return await eda.pcb_Document.importAutoRouteSesFile();')
with self.assertRaisesRegex(RuntimeError,'DSN/SES'):
await eda.execute(t,"return await pcb_export({},'route.SES');")
+52
View File
@@ -0,0 +1,52 @@
import asyncio
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
from codex_pcb import app as service
from codex_pcb.native_policy import DESIGN_POLICY
class SessionPolicyTest(unittest.IsolatedAsyncioTestCase):
def setUp(self):
self.tmp=tempfile.TemporaryDirectory(dir=Path(__file__).parent)
self.addCleanup(self.tmp.cleanup)
self.folder=Path(self.tmp.name)
async def test_approval_has_no_external_launcher(self):
t={'id':'test','state':'review','proposal':{'revision':1,'hash':'approved','markdown':'accepted board'}}
with patch.object(service,'get',return_value=t),patch.object(service,'event'),patch.object(service,'workspace',return_value=self.folder),patch.object(service,'schedule') as schedule:
await service.approve('test',service.Approval(revision=1,hash='approved'))
prompt=schedule.call_args.args[1]
self.assertIn(DESIGN_POLICY,prompt)
self.assertNotIn('External router launcher',prompt)
self.assertNotIn('freerouting.py',prompt)
self.assertEqual(t['approval']['hash'],'approved')
self.assertEqual(t['design_policy'],DESIGN_POLICY)
async def test_resume_keeps_thread_and_reasserts_policy(self):
calls=[]
class FakeServer:
def __init__(self,*args):self.events=asyncio.Queue()
async def __aenter__(self):return self
async def __aexit__(self,*args):pass
async def call(self,method,args):
calls.append((method,args))
if method=='thread/resume':return {'thread':{'id':'existing-thread'},'model':service.MODEL}
if method=='turn/start':
await self.events.put({'method':'turn/completed','params':{'threadId':'existing-thread','turn':{'id':'next-turn','status':'completed'}}})
return {'turn':{'id':'next-turn'}}
raise AssertionError(method)
(self.folder/'evidence').mkdir()
(self.folder/'AGENTS.md').write_text('Recovery project identity retained.\n')
t={'id':'test','thread_id':'existing-thread','approval':{'hash':'accepted'},'frozen_source':service.fingerprint()}
with patch.object(service,'workspace',return_value=self.folder),patch.object(service,'event'),patch.object(service,'AppServer',FakeServer):
await service.run_turn(t,'Old external router advice in history',True)
service.CLIENTS.pop('test',None)
self.assertEqual([c[0]for c in calls],['thread/resume','turn/start'])
self.assertIn(DESIGN_POLICY,calls[0][1]['developerInstructions'])
self.assertTrue(calls[1][1]['input'][0]['text'].startswith('Design policy: '+DESIGN_POLICY))
self.assertIn('Recovery project identity retained.',(self.folder/'AGENTS.md').read_text())
def test_source_freeze_still_rejects_unapproved_backend_drift(self):
with self.assertRaisesRegex(RuntimeError,'Backend source changed'):
service.frozen({'approval':{'hash':'accepted'},'frozen_source':'unexpected'})
+60 -30
View File
@@ -1,14 +1,11 @@
import { useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import './codex-pcb.css';
import { DeliveryModel3D } from './DeliveryModel3D.js';
import { findObjArchive } from './model-appearance.js';
import { DesignPreview } from './DesignPreview.js';
import type { Artifact, Session, Entry } from './workbench-types.js';
import { TaskProgress } from './TaskProgress.js';
import { Markdown as RichMarkdown } from '@ziroeda/ai/markdown.js';
type Artifact = { name: string; kind: string; label: string; bytes: number; sha256: string };
type Session = { id: string; request: string; state: string; busy: boolean; thread_id?: string; error?: string; cursor: number; created_at: number; updated_at?: number; proposal?: { title: string; markdown: string; revision: number; hash: string; at?: number }; approval?: { revision: number; at?: number }; delivery?: { files: Artifact[]; notes: string }; };
type Entry = { seq: number; at: number; type: string; data: Record<string, unknown> };
const BASE = `${import.meta.env.BASE_URL}pcb-api`;
const ACTIVE = 'vibemake.pcb2.persistent-session';
const STATES: Record<string, string> = { planning: '正在制定方案', review: '等待审核方案', needs_input: '等待补充需求', running: '自主设计中', completed: '已完成交付', blocked: '遇到阻碍', failed: '运行失败', interrupted: '等待恢复', cancelled: '已停止' };
@@ -32,11 +29,14 @@ export function CodexPcbDock(): JSX.Element {
const [comment, setComment] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const [tab, setTab] = useState<'plan' | 'activity' | 'files'>('plan');
const [tab, setTab] = useState<'plan' | 'activity' | 'files'>('activity');
const cursor = useRef(0);
const activeRef = useRef(active);
const activity = useRef<HTMLDivElement>(null);
const choose = (id: string | null) => { setActive(id); setTask(null); setEntries([]); cursor.current = 0; activeRef.current = id; setTab('plan'); setError(''); if (id) localStorage.setItem(ACTIVE,id); else localStorage.removeItem(ACTIVE); };
const followChat = useRef(true);
const main = useRef<HTMLElement>(null);
// biome-ignore lint/correctness/useExhaustiveDependencies: changing the tab or task resets the content scroll position.
useEffect(() => { followChat.current = true; main.current?.scrollTo({ top: tab === 'activity' ? main.current.scrollHeight : 0 }); }, [tab, active]);
const choose = (id: string | null) => { setActive(id); setTask(null); setEntries([]); cursor.current = 0; activeRef.current = id; setTab('activity'); setComment(''); setError(''); if (id) localStorage.setItem(ACTIVE,id); else localStorage.removeItem(ACTIVE); };
useEffect(() => { if (!open) return; let cancelled = false; let timer: number;
const poll = async () => {
try {
@@ -47,37 +47,67 @@ export function CodexPcbDock(): JSX.Element {
setTask(next);
if (changes.length) { cursor.current = changes[changes.length - 1]!.seq; setEntries(prev => [...prev, ...changes].slice(-600)); }
}
} catch (e) { if (!cancelled) setError(String(e)); }
} 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]);
useEffect(() => { if (tab === 'activity') activity.current?.scrollTo({ top: activity.current.scrollHeight, behavior: 'smooth' }); }, [entries.length, tab]);
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 }); choose(t.id); setTask(t); setRequest(''); });
const send = () => action(async () => { const t = await api<Session>(`/sessions/${active}/comments`, { text: comment }); setTask(t); setComment(''); });
const approve = () => action(async () => { if (!task?.proposal) return; setTask(await api<Session>(`/sessions/${active}/approve`, { revision: task.proposal.revision, hash: task.proposal.hash })); setTab('activity'); });
const cancel = () => action(async () => { setTask(await api<Session>(`/sessions/${active}/cancel`, {})); });
const resume = () => action(async () => { setTask(await api<Session>(`/sessions/${active}/resume`, {})); setTab('activity'); });
const updateTask = (next: Session) => { if (activeRef.current === next.id) setTask(next); };
const send = () => action(async () => { const id = active; const t = await api<Session>(`/sessions/${id}/comments`, { text: comment }); updateTask(t); if (activeRef.current === id) { setComment(''); setTab('activity'); } });
const approve = () => action(async () => { if (!task?.proposal) return; const id = active; updateTask(await api<Session>(`/sessions/${id}/approve`, { revision: task.proposal.revision, hash: task.proposal.hash })); if (activeRef.current === id) setTab('activity'); });
const cancel = () => action(async () => { updateTask(await api<Session>(`/sessions/${active}/cancel`, {})); });
const resume = () => action(async () => { const id = active; updateTask(await api<Session>(`/sessions/${id}/resume`, {})); if (activeRef.current === id) setTab('activity'); });
const downloadable = (f: Artifact) => `${BASE}/sessions/${active}/files/${encodeURIComponent(f.name)}`;
const step = task?.delivery?.files.find(f => f.kind === 'step' && /\.(step|stp)$/i.test(f.name));
const objArchive = findObjArchive(task?.delivery?.files ?? []);
const canReview = task && !task.approval && !task.busy && ['review','needs_input','failed'].includes(task.state);
const interesting = entries.filter(e => ['message','activity','eda.started','eda.error','session.reconnecting','session.failed','production.blocked','delivery.completed','proposal.approved','session.resumed'].includes(e.type));
const messages = interesting.filter(e => e.type === 'message');
const logs = interesting.filter(e => e.type !== 'message');
const setOpened = (value: boolean) => { setOpen(value); const url = new URL(location.href); if (value) url.searchParams.set('ai', '1'); else url.searchParams.delete('ai'); history.replaceState(null, '', url); };
const view = <div className="cp-root" data-native-text-shortcuts="true">
{!open ? <button className="cp-launch" onClick={() => setOpen(true)}>✦ Codex AI 自动绘板</button> : <section className="cp-window" aria-label="Codex PCB 工作台">
<header className="cp-header"><div><strong>Codex PCB 工作台</strong><span>从方案到真实电路板</span></div><button className="cp-close" onClick={() => setOpen(false)} aria-label="关闭工作台">×</button></header>
<div className="cp-body"><aside className="cp-sidebar"><button className="cp-primary" onClick={() => choose(null)}>+ 新建设计</button><p className="cp-muted">设计记录</p>{sessions.map(s => <button key={s.id} className={`cp-session ${s.id === active ? 'selected' : ''}`} onClick={() => choose(s.id)}><strong>{s.proposal?.title || s.request.slice(0,36)}</strong><small>{STATES[s.state] || s.state}</small></button>)}<div className="cp-side-note">审核方案后开始设计。<br/>关闭网页,后台仍会继续。</div></aside>
<div className="cp-content">{active && task && <TaskProgress key={task.id} task={task} entries={entries} sessions={sessions}/>}
<main className="cp-main">{error && <div className="cp-error" role="alert">{error}<button onClick={() => setError('')}>×</button></div>}
{!active ? <div className="cp-intake"><div className="cp-eyebrow">让需求成为电路板</div><h1>你想设计什么?</h1><p>描述用途、供电、接口和尺寸要求。AI 会先提出方案,由你审核后再开始绘制。</p><textarea aria-label="设计需求" value={request} onChange={e => setRequest(e.target.value)} placeholder="例如:设计一块 ESP32 最小系统板,5V 供电,带下载接口、复位和 BOOT 按键,双层板……" rows={7}/><button className="cp-primary" disabled={busy || request.trim().length < 5} onClick={create}>{busy ? '正在提交…' : '生成设计方案 →'}</button><div className="cp-delivery-hint">最终交付:原理图 · Layout · 板子 STEP · 3D 渲染图 · 可编辑工程</div></div> : !task ? <p>正在加载设计…</p> : <>
<div className="cp-task-header"><div><h2>{task.proposal?.title || task.request.slice(0,60)}</h2><span className={`cp-status state-${task.state}`}>{task.busy && <i/>}{STATES[task.state] || task.state}</span></div>{task.busy && <button className="cp-stop" disabled={busy} onClick={cancel}>停止运行</button>}{!task.busy && task.approval && ['failed','blocked','cancelled','interrupted'].includes(task.state) && <button disabled={busy} onClick={resume}>继续此设计</button>}</div>
<nav className="cp-tabs"><button aria-selected={tab === 'plan'} onClick={() => setTab('plan')}>设计方案{task.proposal ? ` · v${task.proposal.revision}` : ''}</button><button aria-selected={tab === 'activity'} onClick={() => setTab('activity')}>运行记录</button><button aria-selected={tab === 'files'} onClick={() => setTab('files')}>交付文件{task.delivery ? ` · ${task.delivery.files.length}` : ''}</button></nav>
{task.error && <div className="cp-error">{task.error}</div>}
{tab === 'plan' && <div className="cp-plan"><details><summary>原始需求</summary><p>{task.request}</p></details>{task.proposal ? <Markdown value={task.proposal.markdown}/> : <p className="cp-muted">AI 正在研究需求和制定方案,可以在运行记录中查看进度。</p>}{task.approval && <div className="cp-approved">已确认方案 v{task.approval.revision},设计按此方案执行。</div>}{canReview && <div className="cp-review"><label htmlFor="cp-comment">对方案有修改意见?</label><textarea id="cp-comment" value={comment} onChange={e => setComment(e.target.value)} placeholder="补充要求或指出需要修改的地方…" rows={3}/><div className="cp-actions"><button disabled={busy || comment.trim().length < 5} onClick={send}>提交意见,修改方案</button><button className="cp-primary" disabled={busy || task.state !== 'review' || !!comment.trim()} onClick={approve}>同意此方案,开始运行</button></div>{comment.trim() && <small>请先提交修改意见,待新方案生成后再确认。</small>}</div>}</div>}
{tab === 'activity' && <div className="cp-activity" ref={activity}>{interesting.map(e => <article key={e.seq} className={e.type === 'message' ? `cp-message ${text(e.data.role)}` : 'cp-event'}><time>{new Date(e.at * 1000).toLocaleTimeString()}</time>{e.type === 'message' ? <Markdown value={text(e.data.text)}/> : <><strong>{e.type === 'eda.started' ? '嘉立创 EDA · ' + text(e.data.label) : e.type === 'activity' ? ({ commandExecution: '执行脚本', webSearch: '查阅资料', dynamicToolCall: '调用工具', fileChange: '编辑文件' }[text(e.data.kind)] || text(e.data.kind)) : ({ 'eda.error':'EDA 返回错误,AI 可继续处理', 'session.reconnecting':'正在恢复会话', 'session.failed':'会话失败', 'production.blocked':'遇到阻碍', 'delivery.completed':'交付校验通过', 'proposal.approved':'方案已确认,开始设计', 'session.resumed':'已继续原会话' }[e.type] || e.type)}</strong>{text(e.data.message) && <p>{text(e.data.message)}</p>}{text(e.data.command) && <details><summary>查看执行命令</summary><pre>{text(e.data.command)}</pre></details>}</>}</article>)}{task.busy && <p className="cp-muted">● AI 正在继续处理,请稍候…</p>}<details className="cp-session-info"><summary>会话信息</summary><code>{task.thread_id || '正在创建'}</code><p>模型:GPT-6.1 Sol · 方案与生产共用此会话</p></details></div>}
{tab === 'files' && <div className="cp-files">{!task.delivery ? <p className="cp-muted">完成设计和原生检查后,交付文件会显示在这里。</p> : <>{step && <DeliveryModel3D key={`${active}/${step.name}/${step.sha256}`} url={downloadable(step)} sha256={step.sha256} name={step.name} objUrl={objArchive ? downloadable(objArchive) : undefined} objSha256={objArchive?.sha256}/>}<p>{task.delivery.notes}</p>{task.delivery.files.filter(f => ['render','layout','schematic'].includes(f.kind) && /\.(png|jpe?g|svg)$/i.test(f.name)).map(f => <figure key={f.name}><img src={downloadable(f)} alt={f.label}/><figcaption>{f.label}</figcaption></figure>)}{task.delivery.files.map(f => <a className="cp-file" key={f.name} href={downloadable(f)} download><div><strong>{f.label}</strong><small>{f.name} · {(f.bytes / 1024).toFixed(1)} KB</small></div><span>下载 ↓</span></a>)}</>}</div>}
</>}
</main></div></div>
{!open ? <button className="cp-launch" onClick={() => setOpened(true)}>✦ Codex AI 自动绘板</button> : <section className="cp-window cp-workbench" aria-label="AI PCB 全屏工作台">
<header className="cp-header">
<div className="cp-brand"><strong>AI PCB <em>工作台</em></strong><span>从想法到真实电路板</span></div>
<div className="cp-workbench-actions"><select aria-label="选择设计任务" value={active ?? ''} disabled={busy} onChange={e => choose(e.target.value || null)}><option value="">新建设计</option>{sessions.map(s => <option key={s.id} value={s.id}>{s.proposal?.title || s.request.slice(0,36)} · {STATES[s.state] || s.state}</option>)}</select><button disabled={busy} onClick={() => choose(null)}>+ 新建设计</button><button className="cp-exit" onClick={() => setOpened(false)}>返回编辑器</button></div>
</header>
{active && task && <TaskProgress key={task.id} task={task} entries={entries} sessions={sessions}/>}
<div className="cp-workbench-body">
<DesignPreview key={active ?? 'new'} task={task}/>
<section className="cp-chat" aria-label="设计对话">
<header className="cp-chat-heading"><div><span className="cp-eyebrow">AI 设计助手</span><h2>{task?.proposal?.title || (task ? task.request.slice(0,60) : '一起设计你的电路板')}</h2></div>{task && <span className={`cp-status state-${task.state}`}>{task.busy && <i/>}{STATES[task.state] || task.state}</span>}</header>
<nav className="cp-tabs" aria-label="对话与交付"><button aria-selected={tab === 'activity'} onClick={() => setTab('activity')}>对话</button><button aria-selected={tab === 'plan'} onClick={() => setTab('plan')}>设计方案{task?.proposal ? ` · v${task.proposal.revision}` : ''}</button><button aria-selected={tab === 'files'} onClick={() => setTab('files')}>交付文件{task?.delivery ? ` · ${task.delivery.files.length}` : ''}</button></nav>
<main ref={main} className="cp-main" onScroll={e => { const el = e.currentTarget; followChat.current = el.scrollHeight - el.scrollTop - el.clientHeight < 80; }}>
{error && <div className="cp-error" role="alert">{error}<button onClick={() => setError('')} aria-label="关闭错误提示">×</button></div>}
{!active ? <div className="cp-chat-welcome"><div className="cp-assistant-avatar" aria-hidden="true">✦</div><h3>你想做一块怎样的电路板?</h3><p>告诉我用途、供电、接口和尺寸。我会先给出设计方案,确认后开始绘制。</p><ul><li>原理图与 PCB 布线过程在左侧自动更新</li><li>完成后查看 3D 模型,下载完整交付文件</li></ul></div> : !task ? <p className="cp-muted">正在加载设计…</p> : <>
{task.error && <div className="cp-error">{task.error}</div>}
{tab === 'activity' && <div className="cp-conversation">
{messages.map(e => <article key={e.seq} className={`cp-message ${text(e.data.role)}`}><header><strong>{e.data.role === 'user' ? '你' : 'AI 设计助手'}</strong><time>{new Date(e.at * 1000).toLocaleTimeString()}</time></header><Markdown value={text(e.data.text)}/></article>)}
{!messages.length && <article className="cp-message user"><header><strong>你</strong></header><p>{task.request}</p></article>}
{logs.length > 0 && <details className="cp-run-log"><summary>运行记录 · {logs.length} 条</summary>{logs.map(e => <article key={e.seq} className="cp-event"><time>{new Date(e.at * 1000).toLocaleTimeString()}</time><strong>{e.type === 'eda.started' ? '正在绘制 · ' + text(e.data.label) : e.type === 'activity' ? ({ commandExecution: '执行脚本', webSearch: '查阅资料', dynamicToolCall: '调用工具', fileChange: '编辑文件' }[text(e.data.kind)] || text(e.data.kind)) : ({ 'eda.error':'EDA 返回错误,AI 可继续处理', 'session.reconnecting':'正在恢复会话', 'session.failed':'会话失败', 'production.blocked':'遇到阻碍', 'delivery.completed':'交付校验通过', 'proposal.approved':'方案已确认,开始设计', 'session.resumed':'已继续原会话' }[e.type] || e.type)}</strong>{text(e.data.message) && <p>{text(e.data.message)}</p>}{text(e.data.command) && <details><summary>查看执行命令</summary><pre>{text(e.data.command)}</pre></details>}</article>)}</details>}
{task.proposal && !task.approval && <div className="cp-proposal-card"><strong>设计方案 v{task.proposal.revision} 已就绪</strong><p>先查看方案,在下方补充要求或确认开始绘制。</p><button onClick={() => setTab('plan')}>查看完整方案 →</button></div>}
{task.busy && <p className="cp-working" role="status"><i/>AI 正在继续处理,画面和消息会自动更新…</p>}
{task.approval && <details className="cp-session-info"><summary>会话信息</summary><code>{task.thread_id || '正在创建'}</code><p>模型:GPT-6.1 Sol · 方案与生产共用此会话</p></details>}
</div>}
{tab === 'plan' && <div className="cp-plan"><details><summary>原始需求</summary><p>{task.request}</p></details>{task.proposal ? <Markdown value={task.proposal.markdown}/> : <p className="cp-muted">AI 正在研究需求和制定方案。</p>}{task.approval && <div className="cp-approved">已确认方案 v{task.approval.revision},设计按此方案执行。</div>}</div>}
{tab === 'files' && <div className="cp-files">{!task.delivery ? <p className="cp-muted">完成设计和检查后,交付文件会显示在这里。生成过程可在左侧预览。</p> : <><p>{task.delivery.notes}</p><p className="cp-muted">交互式 3D 模型、原理图和布线图在左侧查看。</p>{task.delivery.files.map(f => <a className="cp-file" key={f.name} href={downloadable(f)} download><div><strong>{f.label}</strong><small>{f.name} · {(f.bytes / 1024).toFixed(1)} KB</small></div><span>下载 ↓</span></a>)}</>}</div>}
</>}
</main>
<form className="cp-composer" onSubmit={event => { event.preventDefault(); if (busy) return; if (!active && request.trim().length >= 5) void create(); else if (canReview && comment.trim().length >= 5) void send(); }}>
<label htmlFor="cp-compose">{!active ? '描述你的设计需求' : canReview ? '补充要求或修改方案' : '设计沟通'}</label>
<textarea id="cp-compose" rows={3} value={!active ? request : comment} disabled={busy || (!!active && !canReview)} onChange={e => active ? setComment(e.target.value) : setRequest(e.target.value)}
onKeyDown={event => { if ((event.ctrlKey || event.metaKey) && event.key === 'Enter' && !event.nativeEvent.isComposing) { event.preventDefault(); event.currentTarget.form?.requestSubmit(); } }}
placeholder={!active ? '例如:设计 ESP32 最小系统板,5V 供电,带下载接口…' : canReview ? '输入需要调整的地方,AI 会更新设计方案…' : task?.state === 'completed' ? '本次设计已完成,可查看交付文件或新建设计。' : task?.approval ? '正在按已确认方案制作,可在对话中查看最新进展。' : 'AI 正在处理,方案就绪后可继续沟通…'}/>
<div className="cp-compose-actions"><small>{!active || canReview ? '⌘ / Ctrl + Enter 发送' : '关闭页面,后台仍会继续'}</small><div>
{!active && <button type="submit" className="cp-primary" disabled={busy || request.trim().length < 5}>{busy ? '正在提交…' : '发送需求 →'}</button>}
{canReview && <><button type="submit" disabled={busy || comment.trim().length < 5}>发送修改意见</button><button type="button" className="cp-primary" disabled={busy || task.state !== 'review' || !!comment.trim()} onClick={approve}>确认方案并开始</button></>}
{task?.busy && <button type="button" className="cp-stop" disabled={busy} onClick={cancel}>停止运行</button>}
{task && !task.busy && task.approval && ['failed','blocked','cancelled','interrupted'].includes(task.state) && <button type="button" disabled={busy} onClick={resume}>继续此设计</button>}
{task?.state === 'completed' && <button type="button" onClick={() => choose(null)}>开始新设计</button>}
</div></div>{canReview && comment.trim() && <small className="cp-muted">请先发送修改意见,待新方案生成后再确认。</small>}
</form>
</section>
</div>
</section>}
</div>;
return createPortal(view, document.body);
+62 -39
View File
@@ -2,7 +2,10 @@
import { useEffect, useRef, useState } from 'react';
import { readVerifiedModel, stepHasColors, unpackColoredObj } from './model-appearance.js';
/** Preserve delivered colors; old colorless STEP can use its companion OBJ/MTL for appearance. */
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 }: {
url: string; sha256: string; name: string; objUrl?: string; objSha256?: string;
}) {
@@ -11,58 +14,74 @@ export function DeliveryModel3D({ url, sha256, name, objUrl, objSha256 }: {
const [retry, setRetry] = useState(0);
const [status, setStatus] = useState('正在加载 PCB 三维模型…');
const [failed, setFailed] = useState(false);
const [forceStep, setForceStep] = useState(false);
const [colorless, setColorless] = useState(false);
const [stepRequest, setStepRequest] = useState<string | null>(null);
const [shownSource, setShownSource] = useState<Source | null>(null);
const [appearance, setAppearance] = useState('');
const forceStep = stepRequest === url;
const hasObj = !!(objUrl && objSha256);
// biome-ignore lint/correctness/useExhaustiveDependencies: retry explicitly restarts the failed download and preview.
useEffect(() => {
const element = host.current;
if (!element) return;
const controller = new AbortController();
const { signal } = controller;
let dispose: (() => void) | undefined;
setStatus('正在加载 PCB 三维模型…');
setFailed(false);
setShownSource(null);
setAppearance('');
reset.current = null;
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);
if (signal.aborted) return null;
const files = unpackColoredObj(packed);
const { mountProjectObj } = await import('../pcb-service/project-model-obj.js');
if (signal.aborted) return null;
return { viewer: mountProjectObj(element, files), caption: '彩色外观来自已交付的 OBJ/MTL;机械尺寸请以原始 STEP 为准。' };
}
setStatus('正在解析装配模型,首次打开可能需要一些时间…');
const bytes = await readVerifiedModel(url, sha256, signal);
if (signal.aborted) return null;
const { mountDeliveryStep } = await import('./delivery-step-viewer.js');
if (signal.aborted) return null;
const viewer = await mountDeliveryStep(element, bytes, signal);
return viewer ? { viewer, caption: stepHasColors(bytes) ? 'STEP 原始颜色' : '原始 STEP 未包含颜色' } : null;
};
void (async () => {
try {
const bytes = await readVerifiedModel(url, sha256, controller.signal);
if (controller.signal.aborted) return;
const hasColors = stepHasColors(bytes);
setColorless(!hasColors);
let info = hasColors ? 'STEP 原始颜色' : '原始 STEP 未包含颜色';
if (!hasColors && !forceStep && objUrl && objSha256) {
setStatus('正在加载交付包中的彩色外观模型…');
let source: Source = hasObj && !forceStep ? 'obj' : 'step';
let result: Awaited<ReturnType<typeof mount>>;
let fallback = '';
try {
result = await mount(source);
} catch (firstError) {
if (signal.aborted) return;
if (!hasObj) throw firstError;
source = source === 'obj' ? 'step' : 'obj';
fallback = source === 'obj'
? '网页无法预览此 STEP,已切换到交付的彩色外观。'
: '彩色外观暂不可用,已切换到原始 STEP。';
try {
const packed = await readVerifiedModel(objUrl, objSha256, controller.signal, 64 * 1024 * 1024);
if (controller.signal.aborted) return;
const files = unpackColoredObj(packed);
const { mountProjectObj } = await import('../pcb-service/project-model-obj.js');
if (controller.signal.aborted) return;
const viewer = mountProjectObj(element, files);
dispose = viewer.dispose;
reset.current = viewer.reset;
setAppearance('彩色外观来自已交付的 OBJ/MTL;机械尺寸请以原始 STEP 为准。');
setStatus('');
return;
} catch {
if (controller.signal.aborted) return;
// An optional appearance preview must never hide the STEP or block downloads.
info = '彩色外观暂不可用,当前显示原始 STEP;可重新加载彩色外观。';
result = await mount(source);
} catch (secondError) {
const reason = (e: unknown) => e instanceof Error ? e.message : String(e);
throw new Error(`两种三维预览均未能加载:${reason(firstError)};${reason(secondError)}。仍可下载原始 STEP。`);
}
}
setStatus('正在解析装配模型,首次打开可能需要一些时间…');
const { mountDeliveryStep } = await import('./delivery-step-viewer.js');
if (controller.signal.aborted) return;
const viewer = await mountDeliveryStep(element, bytes, controller.signal);
if (!viewer) return;
if (controller.signal.aborted) { viewer.dispose(); return; }
dispose = viewer.dispose;
reset.current = viewer.reset;
setAppearance(info);
if (!result) return;
if (signal.aborted) { result.viewer.dispose(); return; }
dispose = result.viewer.dispose;
reset.current = result.viewer.reset;
setShownSource(source);
setAppearance(fallback + result.caption);
setStatus('');
} catch (error) {
if (!controller.signal.aborted) {
if (!signal.aborted) {
dispose?.();
setFailed(true);
setStatus(error instanceof Error ? error.message : '三维模型加载失败,请重试。');
@@ -74,17 +93,21 @@ export function DeliveryModel3D({ url, sha256, name, objUrl, objSha256 }: {
dispose?.();
reset.current = null;
};
}, [url, sha256, retry, forceStep, objUrl, objSha256]);
}, [url, sha256, retry, forceStep, hasObj, objUrl, objSha256]);
const reload = () => { setStatus('正在重新加载模型…'); setRetry(value => value + 1); };
const switchSource = () => { setStatus('正在切换模型…'); setForceStep(value => !value); };
const switchSource = () => {
setStatus('正在切换模型…');
setStepRequest(shownSource === 'step' ? null : url);
// A failed STEP may have fallen back to OBJ while STEP remains requested.
setRetry(value => value + 1);
};
return <section className="cp-model" aria-label="PCB 交互式三维模型">
<div className="cp-model-header">
<div><h3>PCB 3D 模型</h3><p>左键拖拽旋转 · 滚轮缩放 · 右键拖拽平移</p>{appearance && <small className="cp-model-source">{appearance}</small>}</div>
<div className="cp-model-actions">
{colorless && objUrl && <button disabled={!!status} onClick={switchSource}>{forceStep ? '查看彩色外观' : '查看原始 STEP'}</button>}
{colorless && objUrl && !forceStep && appearance.startsWith('彩色外观暂不可用') && <button disabled={!!status} onClick={reload}>重新加载彩色外观</button>}
{hasObj && <button disabled={!!status} onClick={switchSource}>{shownSource === 'step' ? '查看彩色外观' : '查看原始 STEP'}</button>}
<button disabled={!!status} onClick={() => reset.current?.()}>复位视角</button>
</div>
</div>
+79
View File
@@ -0,0 +1,79 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import { useEffect, useRef, useState } from 'react';
import { DeliveryModel3D } from './DeliveryModel3D.js';
import { findObjArchive } from './model-appearance.js';
import type { Artifact, Session } from './workbench-types.js';
type Mode = 'auto' | 'schematic' | 'layout' | '3d';
type Frame = { kind: Exclude<Mode, 'auto'>; image: string; capturedAt: number; source: 'canvas' | 'export' };
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);
const [position, setPosition] = useState({ x: 0, y: 0 });
const [failed, setFailed] = useState(false);
const drag = useRef<{ x: number; y: number; px: number; py: number } | null>(null);
useEffect(() => { setFailed(false); }, [url]);
return <div className="cp-image-viewer">
<div className="cp-image-tools"><span>拖拽平移 · 滚轮缩放</span><button aria-label="缩小画面" onClick={() => setScale(s => Math.max(.5, s / 1.25))}>−</button><span>{Math.round(scale * 100)}%</span><button aria-label="放大画面" onClick={() => setScale(s => Math.min(6, s * 1.25))}>+</button><button onClick={() => { setScale(1); setPosition({ x: 0, y: 0 }); }}>适应画面</button></div>
<div className="cp-image-surface" onWheel={event => setScale(s => Math.max(.5, Math.min(6, s * (event.deltaY < 0 ? 1.1 : 1 / 1.1))))}
onPointerDown={event => { if (event.button !== 0) return; event.currentTarget.setPointerCapture(event.pointerId); drag.current = { x: event.clientX, y: event.clientY, px: position.x, py: position.y }; }}
onPointerMove={event => { const d = drag.current; if (d) setPosition({ x: d.px + event.clientX - d.x, y: d.py + event.clientY - d.y }); }}
onPointerUp={() => { drag.current = null; }} onPointerCancel={() => { drag.current = null; }}>
{failed ? <p className="cp-preview-empty">此图片暂时无法显示,请稍后重试或在交付文件中下载。</p> : <img src={url} alt={label} draggable={false} onError={() => setFailed(true)} style={{ transform: `translate(${position.x}px, ${position.y}px) scale(${scale})` }}/>}
</div>
</div>;
}
export function DesignPreview({ task }: { task: Session | null }) {
const [mode, setMode] = useState<Mode>('auto');
const [frame, setFrame] = useState<Frame | null>(null);
const [notice, setNotice] = useState('正在连接设计画面…');
const [selectedFile, setSelectedFile] = useState('');
const id = task?.id;
const completed = task?.state === 'completed';
const approved = !!task?.approval;
useEffect(() => {
if (!id || completed || !approved) return;
const controller = new AbortController();
let timer: number;
let etag = '';
const poll = async () => {
try {
if (document.visibilityState === 'hidden') return;
const response = await fetch(`${import.meta.env.BASE_URL}pcb-preview/${id}?kind=${mode}`, { signal: controller.signal, cache: 'no-store', headers: etag ? { 'If-None-Match': etag } : {} });
if (response.status === 304) return;
if (!response.ok) throw new Error('preview unavailable');
const value = await response.json() as { taskId: string; frame: Frame | null; reason: string };
if (controller.signal.aborted || value.taskId !== id) return;
etag = response.headers.get('etag') || '';
if (value.frame) setFrame(value.frame);
setNotice(value.reason === 'eda_busy' ? '正在绘制,保留最近画面,空闲时自动更新' : value.frame?.source === 'export' ? '最近导出的设计快照 · 新画面就绪后自动更新' : value.frame ? '当前设计画布 · 每 5 秒自动刷新' : '等待原理图或 PCB 画布就绪…');
} catch { if (!controller.signal.aborted) setNotice('画面连接暂不可用,正在自动重试'); }
finally { if (!controller.signal.aborted) timer = window.setTimeout(poll, 5000); }
};
void poll();
return () => { controller.abort(); clearTimeout(timer); };
}, [id, completed, approved, mode]);
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 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>
<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 && 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>
<footer className="cp-preview-footer"><span>{completed ? '已验证的交付成果 · 可切换原理图、布线图与 3D 模型' : approved ? notice : '预览随生成阶段自动切换'}</span>{!completed && shownFrame && <time dateTime={new Date(shownFrame.capturedAt).toISOString()}>画面时间 {new Date(shownFrame.capturedAt).toLocaleTimeString()}</time>}</footer>
</section>;
}
+11 -3
View File
@@ -2,7 +2,7 @@
import { useEffect, useMemo, useState } from 'react';
import {
PAUSED_STATES, PROGRESS_STAGES, elapsedLabel, observedProductionStage,
productionEstimate, progressStage, remainingEstimate,
completedDuration, productionEstimate, progressStage, remainingEstimate,
type ProgressEvent, type ProgressSession,
} from './task-progress.js';
@@ -23,6 +23,7 @@ export function TaskProgress({ task, entries, sessions }: {
const stage = progressStage(task, observed, remembered);
const paused = PAUSED_STATES.has(task.state);
const completed = task.state === 'completed';
const duration = useMemo(() => completedDuration(task, entries), [task, entries]);
useEffect(() => {
if (completed || paused) return;
const timer = window.setInterval(() => setNow(Date.now() / 1000), 1000);
@@ -37,7 +38,7 @@ export function TaskProgress({ task, entries, sessions }: {
const current = completed ? '已完成交付' : paused
? ({ blocked: '遇到阻碍', failed: '运行失败', interrupted: '等待恢复', cancelled: '已停止' }[task.state] || '等待恢复')
: task.state === 'needs_input' ? '等待补充需求' : stage === 1 ? '等待你确认方案' : PROGRESS_STAGES[stage];
const end = completed || paused ? task.updated_at ?? now : now;
const end = completed || paused ? duration?.completedAt ?? task.updated_at ?? now : now;
const elapsed = elapsedLabel(end - (task.approval?.at ?? task.created_at));
const reference = completed ? '交付成果可在“交付文件”中查看' : estimate
? `确认后制作参考 ${Math.round(estimate.low / 60)}–${Math.round(estimate.high / 60)} 分钟 · ${estimate.samples} 个已完成设计`
@@ -54,7 +55,14 @@ export function TaskProgress({ task, entries, sessions }: {
<span><b>{index < stage ? '✓' : index + 1}</b>{label}</span>
</div>)}
</div>
<div className="cp-progress-timing"><strong>{remainingEstimate(task, estimate, now)}</strong><span>{reference}</span></div>
<div className="cp-progress-timing" aria-label={completed ? '生成耗时统计' : undefined}>
<strong>{duration ? `本次生成${duration.estimated ? '约用' : '共用'} ${duration.totalMinutes} 分钟` : remainingEstimate(task, estimate, now)}</strong>
<span>{duration?.productionMinutes !== null && duration?.productionMinutes !== undefined
? `其中方案确认后制作:${duration.productionMinutes} 分钟` : reference}</span>
</div>
{completed && <p className="cp-progress-note">{duration
? `总时间从提交需求计算至交付完成,包含方案修改、确认等待及中途等待。${duration.estimated ? '历史完成事件缺失,按最后更新时间估算。' : ''}`
: '该任务缺少有效的时间记录,暂无法统计生成耗时。'}</p>}
{!completed && <p className="cp-progress-note">阶段与耗时仅供参考,布局调整和校验修复可能延长制作时间。</p>}
</section>;
}
File diff suppressed because one or more lines are too long
+25
View File
@@ -38,6 +38,31 @@ export function progressStage(task: ProgressSession, observed: number, remembere
export interface DurationEstimate { low: number; high: number; samples: number }
export interface CompletedDuration {
completedAt: number;
totalMinutes: string;
productionMinutes: string | null;
estimated: boolean;
}
/** Stop at accepted delivery, not the later assistant summary or the browser's clock. */
export function completedDuration(task: ProgressSession, events: readonly ProgressEvent[]): CompletedDuration | null {
if (task.state !== 'completed' || !Number.isFinite(task.created_at)) return null;
const deliveries = events.filter(event => event.type === 'delivery.completed'
&& Number.isFinite(event.at) && event.at >= task.created_at).map(event => event.at);
const exact = deliveries.length ? Math.min(...deliveries) : undefined;
const end = exact ?? task.updated_at;
if (end === undefined || !Number.isFinite(end) || end < task.created_at) return null;
const approvedAt = task.approval?.at;
return {
completedAt: end,
totalMinutes: ((end - task.created_at) / 60).toFixed(1),
productionMinutes: approvedAt !== undefined && Number.isFinite(approvedAt)
&& approvedAt >= task.created_at && approvedAt <= end ? ((end - approvedAt) / 60).toFixed(1) : null,
estimated: exact === undefined,
};
}
/** Seconds after approval; deliberately exclude review waiting and unfinished jobs. */
export function productionEstimate(sessions: readonly ProgressSession[], currentId: string): DurationEstimate | null {
const durations = sessions.filter(task => task.id !== currentId && task.state === 'completed')
@@ -0,0 +1,3 @@
export type Artifact = { name: string; kind: string; label: string; bytes: number; sha256: string };
export type Session = { id: string; request: string; state: string; busy: boolean; thread_id?: string; error?: string; cursor: number; created_at: number; updated_at?: number; proposal?: { title: string; markdown: string; revision: number; hash: string; at?: number }; approval?: { revision: number; at?: number }; delivery?: { files: Artifact[]; notes: string }; };
export type Entry = { seq: number; at: number; type: string; data: Record<string, unknown> };
+18
View File
@@ -0,0 +1,18 @@
# 交付模型的网页预览
`DeliveryModel3D.tsx` 在交付清单同时提供 OBJ/MTL 时,优先使用经过 SHA-256 校验的 OBJ 包作为交互预览。原始 STEP 下载链接和文件内容不变;界面注明预览来源,机械尺寸以 STEP 为准。没有 OBJ 时使用 STEP。
用户可切换到 STEP 预览。任一预览源读取、校验或解析失败时,尝试另一来源;两者均失败则保留下载和重试入口。切换任务、关闭面板或异步加载取消后必须释放旧 viewer。
## 已复现的兼容问题(2026-11-12)
灵巧手 STM32F405 / CAN FD 交付的 STEP 为 66,170,410 字节,SHA-256 为 `8ec4a1d7cc94810d37f5f9b8b88cc04bc9a7bdc8329bba13d24ae7b8daf62bb3`。原生 CAD 内核可读取并渲染;网页使用的 `occt-import-js@0.0.23` 在当前细分参数下返回 `success: true` 和 2065 个网格,但所有顶点与索引数组均为空,总三角形数为 0。解析耗时约 4 分钟、进程内存峰值约 2.2 GiB。不要把解析器的 success 或 STEP 中存在颜色声明等同于网页可显示。
同一交付包中的原生 OBJ 包含 201171 个顶点和 849049 个面。优先直接加载此网格,避免每次打开完整装配都在浏览器中重新细分 STEP;不将静态渲染图片冒充可旋转模型。
## 验证与部署注意
- 单元回归:`qa/unittests/designer/delivery_model_3d.test.tsx` 覆盖默认预览源、空 STEP 回退、OBJ 校验失败、双重失败重试及取消时释放资源。
- 必须用实际交付文件打开网站,验证出现 canvas、旋转、缩放、复位和原始 STEP 下载。文件可下载、原生 DRC 通过或 CAD 内核可读取,都不能替代浏览器验证。
- 诊断完整装配解析、前端构建和浏览器测试应串行执行,并设进程内存上限,避免与 EDA 争用内存。
- 此修复只影响前端预览,不修改 PCB 工程、制造文件、交付哈希或后端验收结果。
@@ -0,0 +1,15 @@
# 公共交付工具验证记录
2026-11-16,嘉立创 EDA 4.1.78,服务器 192.168.1.200。
- 21 项自动测试全部通过,包含原有原生设计策略/源码冻结测试,以及新增警告分类、分块传输、截断保护、多页 PDF 和旧会话入口测试。
- 独立测试目录:`/home/wpz/auto_pcb_2/persistent-development/delivery-toolkit-20261116/validation-runtime`。
- 复用既有 24 V STM32 FOC 圆形演示板的原生工程:原理图 UUID `b49ba1486300188e`,PCB UUID `7c8026066be2fa61`。没有启动设计 agent,没有修改电路对象;保存、检查和导出在原生会话执行。原网站任务保持 cancelled。
- 原理图全部 5 页共 104 个器件,PCB 104 个器件。PCB 原生检查 true、诊断空。原理图原生检查 false,详细结果只有 ATTRMATCHCODE warn,涉及 JP1、JP2、J4、J5、J6。新验收 accepted=true,原始警告保留。
- 9,437,201 字节 Blob 经 1 MiB 分块传回,逐字节验证通过。
- 自动生成原生 epro、5 页原理图 PDF、原生布局 PNG、26,884,482 字节 STEP、原生 OBJ、Blender 真实装配 PNG、Gerber、BOM、报告及带校验和的交付 ZIP。
- PDF 5 页均可提取文字;布局及装配渲染人工查看有实际板子和器件。渲染保留原生外观,未逐件修模型或颜色。
- 全流程 189.99 秒,包含大文件传输测试和两次完整 ERC/DRC。单次检查约 11 秒,STEP 导出/传输 122 秒,OBJ 6 秒。此数据仅代表既有板子的交付阶段,不包含原理图绘制、布局、布线、AI 思考,不保证其他设计相同耗时。
- 原始证据:validation-runtime/validation-result.json、测试任务 events.jsonl、workspace/evidence、delivery/manifest.json。
限制:软件检查不等于实物功能/电气额定/温升验证;原生模型覆盖限制和 STEP 外观警告被保留,不宣称每个元件的 STEP 模型完整。旧会话通过原有 pcb_eda 的 JSON 公共工具入口使用相同能力,无需丢弃会话历史。
+44
View File
@@ -0,0 +1,44 @@
# 原生检查与公共交付工具(2026-11-16)
此工具层负责检查结果归类、原生导出、传输、渲染和打包。电路设计、原理图、布局、布线和 ERC/DRC 仍在嘉立创 EDA 中完成;不恢复 Freerouting、KiCad 或设计数据转换路线。
## 验收口径
`native-errors-block-warnings-record-v1`:原生诊断明确标记为 warn/warning 时记录并放行,即使原生检查总布尔值为 false。error/fatal、未知类别、缺失诊断、false 却无诊断、空工程均阻断。原始结果和分类结果均保存。不降低规则、不删除检查项目、不把错误改名为警告。
原生 PCB DRC 通过只说明所执行的规则检查通过,并不证明功能、额定功率、热设计、器件选型或实物测试通过。原理图 ERC 与 PCB DRC 都要检查;原理图按全部页面检查。库属性警告(例如 ATTRMATCHCODE)不再成为无休止修库的理由。
真实且有几何的原生 STEP 必须保留。颜色/部分库模型缺失记录为限制;不再逐件重建 STEP、修色或制造替代几何。原生 OBJ/MTL 用于真实装配渲染,不作为 STEP 每个器件完整的证明。空文件、错误文件类型、无可渲染几何仍然阻断。
## 可复用 API
- `pcb_check(schematic_id, pcb_id)`:设计中尽早调用,与最终交付采用相同门槛,返回 accepted、warnings、blockingErrors 和原始诊断。
- `pcb_prepare_delivery(schematic_id, pcb_id)`:先检查,再导出原生工程、原理图 SVG/PDF、PCB 布局 PNG、STEP、OBJ,并通过服务器安装的 Blender 渲染;返回 `pcb_deliver` 可用的文件列表。Gerber/BOM 导出失败记录警告;PDF 转换失败时回退到原生 SVG。
- `pcb_deliver`:独立重新检查原生工程,验证文件、生成校验和、manifest 和 ZIP。只收录本次提交文件,不混入上次失败遗留文件。
- `pcb_eda` 的公共 JavaScript:`pcb_documents()` 列出文档;`pcb_focus(id)` 将原理图容器 ID 解析到页面并激活;`pcb_resolve(schematicId, pcbId)` 校验文档配对;`pcb_capabilities()` 检查实际安装版本的方法;`pcb_export(file, relative_name)` 自动分块传输。
旧 Codex 会话的动态工具目录不能通过 thread/resume 新增工具(已核对本机 CLI schema)。无需换会话:向原有 `pcb_eda` 的 code 参数传入纯 JSON 即可调用相同工具:
```json
{"pcb_backend_tool":"prepare_delivery","schematic_id":"真实原理图容器或页面 UUID","pcb_id":"真实 PCB 文档 UUID"}
```
将 prepare_delivery 换成 check 可执行早期检查。正常 JavaScript 调用方式不变。
## 分块与超时
EDA CLI 单次 JSON 输出有限。导出先在 EDA 保存 Blob 引用,按 1 MiB 读取并校验长度,完成后原子替换目标文件、记录 SHA-256,最后释放临时引用。中断时删除部分文件并保留之前的完整文件;不可将导出超时理解为设计失败或重放设计写入。
单次原生操作 180 秒、每块传输 30 秒、Blender 渲染 180 秒上限。没有自动无限重试。原生工具超时后先确认现场状态,不盲目重复写入。3D 导出本身可能需要分钟级时间,公共工具并不能保证所有复杂板的导出耗时一致。
## 部署依赖
在后端虚拟环境安装 `codex_pcb/requirements-delivery.txt`。需要系统 Cairo 动态库,以及支持 `bpy.ops.wm.obj_import` 的 Blender;本服务器使用 `/snap/bin/blender`。其他服务器可设置 `PCB_BLENDER_BIN` 指向已验证的 Blender 可执行文件。不要让每个设计任务重新安装依赖或编写渲染器。
嘉立创版本本次为 4.1.78。API 方法存在性应通过 pcb_capabilities 和安装版本的官方 API 文档检查,不能假设较新文档中的接口已存在。桌面会话的 DISPLAY/XAUTHORITY 由传输层处理。
源码冻结继续有效。部署必须确认无运行任务,备份源代码及非完成任务状态,记录旧/新哈希和迁移原因;已完成历史任务不重写,已取消任务不自动恢复。迁移过的旧任务不再视为原始冻结代码的一次性验收。
## 验证
自动测试覆盖原生 warning-only false 放行、实际错误/未知诊断阻断、多页 SVG 转 PDF、ZIP 越界拒绝、9 MiB 分块传输及截断保护、旧会话公共工具兼容。实际工程验证与耗时记录见同目录工具验证记录;该验证复用已取消任务的原生工程并将输出写到独立诊断工作区,不改变原任务状态,不运行 Codex 设计任务。
+20
View File
@@ -0,0 +1,20 @@
# AI PCB full-screen workbench
The existing `/pcb/?ai=1` entry opens a full-viewport page. The left pane follows the current design canvas; the right pane contains conversation, proposal, delivery downloads and a persistent composer. Task history is in the top selector. On narrow screens the panes stack vertically. Review comments and approval retain the existing API rules; production does not accept mid-run design changes.
## Live preview
`GET /pcb/pcb-preview/{taskId}?kind=auto|schematic|layout|3d` is handled by the web service, outside the frozen `codex_pcb` sources. The frontend polls every five seconds while visible. This is a periodically refreshed snapshot, not a video stream. A completed task uses the existing verified files API and interactive STEP / OBJ viewer.
`capture-preview.py` reads the task's owned EDA session and invokes only `getCurrentDocumentInfo()` and `getCurrentRenderedAreaImage(tabId)`. It never opens, activates, saves or edits documents. It attempts the same EDA host lock non-blockingly: if generation holds the lock, capture is skipped. Invocation is bounded to three seconds (process timeout five seconds). Only running approved tasks are captured by the HTTP handler.
The most recent capture is cached under `persistent-runtime/web-previews/`. If capture is unavailable, the service can show a stable PNG/JPEG already exported into that task's `workspace/artifacts/`, labelled as an exported snapshot with its timestamp. No other task's canvas is substituted. If neither exists, the UI shows a waiting state. No EDA session is opened to service previews. View selection never changes the EDA editor's active document.
Requests coalesce and cache for five seconds. ETags avoid retransmitting unchanged image bodies. Paths and modes are constrained; symlinks are excluded from export scans; only valid PNG/JPEG signatures are returned. The endpoint is read-only and retains same-origin restrictions. Runtime root can be set using `PCB_SESSION_ROOT` on the web service and otherwise defaults to `/home/wpz/auto_pcb_2/persistent-runtime`.
## Validation and deployment
- Run the designer TypeScript check and Vite build.
- Run `PCB_PREVIEW_TEST_ROOT=<isolated task directory> node --test scripts/pcb-preview.test.mjs` for cache/coalescing, task isolation, busy capture, fallback, path/method rejection and conditional requests.
- Browser checks cover full viewport, layout, real file preview, model loading, responsive widths, proposal comment/approval with intercepted writes, auto-refresh and completed-state transition.
- Deploy the built `designer/dist` and keep old hashed assets for open pages. Updating `scripts/serve.mjs` requires restarting **only** `vibemake-pcb2-web.service`. Do not restart the generation service or modify frozen backend sources for this UI change.
+39
View File
@@ -0,0 +1,39 @@
# 嘉立创原生设计模式(easyeda-native-v1)
自 2026-11-16 起,生产任务的原理图、布局、布线和电气检查统一在嘉立创 EDA 原生工程内完成。Codex 仍在同一个持久会话中自主决定设计、诊断和修复方法;后端不提供固定布局或布线算法。
## 允许与禁止的边界
- 所有 EDA 操作通过 `pcb_eda` 完成;直接创建、修改器件、原理图导线、PCB 走线、过孔、铜区,以及调用原生布局/布线 API。
- 允许 Python/JavaScript 对原生读回数据计算坐标、路径和辅助诊断,计算结果通过原生对象 API 写回。离线计算不能替代原生 ERC/DRC、引脚网络对比和几何读回检查。
- 禁止 Freerouting、KiCad 或其他外部 EDA/布线器参与设计、布线或替代电气检查;禁止 DSN/SES 往返及外部自动布局/布线 JSON 交换。
- 可导出原生工程、网表(用于对照)、生产文件、原理图/Layout、BOM、STEP/OBJ。Blender 和 CAD 工具仅可用于导出的三维装配表示、渲染及模型核验,不得修改电路或 PCB 几何。
## 后端如何落实
1. `instructions.md` 和每次 `run_turn` 都声明当前政策。新建、审核批准、恢复和继续运行均覆盖,旧会话中允许外部布线的历史指令失效。
2. 工作目录 `AGENTS.md` 增加托管政策段,保留原有恢复说明。
3. `pcb_eda` 的 JavaScript 包装层通过代理阻止 `getDsnFile`、两种自动布线 JSON 导出、SES/JSON 布线导入和自动布局 JSON 导入;别名及计算属性访问同样被拦截。DSN/SES 导出文件名在前后端传输边界也被拒绝。
4. `freerouting.py` 保留为退役入口,任何参数(包括 `--help`)均直接退出并提示改用原生 API,不启动 Java 或 Xvfb。其他项目的 Java/JAR 不删除。
5. `/api/health` 返回 `design_policy`,新交付 manifest 记录该政策及源码迁移历史。原生交付检查仍强制执行。
这些是面向合作型 Codex 的生产约束和受支持接口防护,不是恶意代码隔离沙箱。终端仍供计算、数据手册查询、文件处理和渲染使用,因此不能宣称从操作系统层面禁止了任意自行下载或调用外部程序。不得绕过 `pcb_eda` 直接调用 CLI 或其他 EDA 会话。
## 部署及旧任务
- 修改前检查没有 busy/running/planning 任务,备份源码和待迁移任务状态,停止后端后部署、迁移,再启动。
- 保留源码冻结检查,不能简单删除 `frozen()`。此次部署仅将冻结哈希匹配部署前版本的未完成、已批准任务迁移到新版本;记录旧/新哈希、原因、时间,并标记原有冻结验收运行失效。已有批准方案、会话 ID、工程和文件保留。其他哈希不匹配的任务继续拒绝恢复。
- 已完成任务、交付包和原有 manifest 不改写。迁移不等于重新启动失败任务,恢复仍由网站发起。
- 恢复旧任务时只读回已保存的原生工程并继续修复,不执行旧 DSN/SES 导入脚本;遗留中间文件仅保留为历史证据。升级后的结果不能声称“从创建到交付从未修改后端”。
- 原生布线超时不等于操作未执行:先检查实时走线及运行状态,不能重复启动竞争任务,更不能回退外部布线。
- 多轮修复后比较完整原生检查结果;无改善应调整布局/路径策略。不得通过取消网络、降低规则或屏蔽检查来交付。
## 验证
在仓库根目录、Node 可用的环境下运行:
```sh
backend/.venv/bin/python -m unittest discover -s codex_pcb/tests -v
```
覆盖退役启动器、原生编辑/布线/检查及交付导出兼容、交换接口拒绝、实际 EDA 包装脚本执行、审核提示、同会话恢复政策、源码冻结和 STEP 颜色验证。单元测试使用模拟 EDA 对象;不能替代真实板卡完整生产验收。
@@ -0,0 +1,83 @@
// @vitest-environment happy-dom
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';
const mocks = vi.hoisted(() => ({ read: vi.fn(), obj: vi.fn(), step: vi.fn(), dispose: vi.fn() }));
vi.mock('../../../designer/src/codex-pcb/model-appearance.js', () => ({
readVerifiedModel: mocks.read, stepHasColors: () => true, unpackColoredObj: () => ({}),
}));
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 viewer = () => ({ reset: vi.fn(), dispose: mocks.dispose });
beforeEach(() => {
vi.resetAllMocks();
mocks.read.mockResolvedValue(new Uint8Array([1]));
mocks.obj.mockImplementation(viewer);
mocks.step.mockImplementation(async () => viewer());
});
afterEach(cleanup);
const ready = () => waitFor(() => expect((screen.getByRole('button', { name: '复位视角' }) as HTMLButtonElement).disabled).toBe(false));
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).toHaveBeenCalledTimes(1);
expect(mocks.step).not.toHaveBeenCalled();
expect(screen.getByRole('link', { name: /下载 STEP/ }).getAttribute('href')).toBe('/board.step');
});
it('recovers from empty STEP geometry and permits a later STEP retry', async () => {
mocks.step.mockRejectedValueOnce(new Error('模型没有可显示的三维几何。'));
render(<DeliveryModel3D {...props} />);
await ready();
fireEvent.click(screen.getByRole('button', { name: '查看原始 STEP' }));
await screen.findByText(/网页无法预览此 STEP/);
await ready();
expect(mocks.obj).toHaveBeenCalledTimes(2);
expect(mocks.dispose).toHaveBeenCalledTimes(1);
fireEvent.click(screen.getByRole('button', { name: '查看原始 STEP' }));
await screen.findByText('STEP 原始颜色');
expect(mocks.step).toHaveBeenCalledTimes(2);
fireEvent.click(screen.getByRole('button', { name: '查看彩色外观' }));
await ready();
expect(mocks.obj).toHaveBeenCalledTimes(3);
});
it('falls back to STEP when the OBJ checksum fails', async () => {
mocks.read.mockImplementation(async (url: string) => {
if (url.endsWith('.zip')) throw new Error('模型文件校验失败');
return new Uint8Array([1]);
});
render(<DeliveryModel3D {...props} />);
await screen.findByText(/彩色外观暂不可用,已切换到原始 STEP/);
await ready();
expect(mocks.obj).not.toHaveBeenCalled();
expect(mocks.step).toHaveBeenCalledTimes(1);
});
it('keeps download and retry available when both sources fail', async () => {
mocks.obj.mockImplementationOnce(() => { throw new Error('OBJ 损坏'); });
mocks.step.mockRejectedValueOnce(new Error('STEP 空网格'));
render(<DeliveryModel3D {...props} />);
await screen.findByText(/两种三维预览均未能加载/);
expect(screen.getByRole('link', { name: /下载 STEP/ })).toBeTruthy();
fireEvent.click(screen.getByRole('button', { name: '重新加载模型' }));
await ready();
expect(mocks.obj).toHaveBeenCalledTimes(2);
});
it('loads STEP-only deliveries and disposes a late result after unmount', async () => {
let resolve!: (v: ReturnType<typeof viewer>) => void;
mocks.step.mockImplementation(() => new Promise(r => { resolve = r; }));
const mounted = render(<DeliveryModel3D {...props} objUrl={undefined} objSha256={undefined} />);
await waitFor(() => expect(mocks.step).toHaveBeenCalledTimes(1));
mounted.unmount();
resolve(viewer());
await waitFor(() => expect(mocks.dispose).toHaveBeenCalledTimes(1));
expect(mocks.obj).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,28 @@
import { describe, expect, it } from 'vitest';
import { completedDuration, type ProgressSession } from '../../../designer/src/codex-pcb/task-progress.js';
const task: ProgressSession = { id: 'task', state: 'completed', busy: false, created_at: 1000, approval: { at: 1600 }, updated_at: 4720 };
const events = [{ type: 'delivery.completed', at: 4600, data: {} }];
describe('completed PCB generation duration', () => {
it('uses accepted delivery time, excluding later summary messages and saves', () => {
expect(completedDuration(task, events)).toEqual({ completedAt: 4600, totalMinutes: '60.0', productionMinutes: '50.0', estimated: false });
expect(completedDuration({ ...task, updated_at: 99999 }, events)).toEqual(completedDuration(task, events));
});
it('does not present running, failed or cancelled work as a completed generation', () => {
for (const state of ['running', 'failed', 'cancelled', 'review']) expect(completedDuration({ ...task, state }, events)).toBeNull();
});
it('labels the historical last-update fallback as an estimate and works without approval', () => {
expect(completedDuration(task, [])).toEqual({ completedAt: 4720, totalMinutes: '62.0', productionMinutes: '52.0', estimated: true });
expect(completedDuration({ ...task, approval: undefined }, events)?.productionMinutes).toBeNull();
});
it('reports decimal minutes and does not count unrelated or malformed events', () => {
expect(completedDuration(task, [{ type: 'message', at: 9000, data: {} }, { type: 'delivery.completed', at: NaN, data: {} }, { type: 'delivery.completed', at: 5, data: {} }, { type: 'delivery.completed', at: 4630, data: {} }])?.totalMinutes).toBe('60.5');
});
it('does not invent durations when dates are missing, reversed or non-finite', () => {
expect(completedDuration({ ...task, updated_at: undefined }, [])).toBeNull();
expect(completedDuration({ ...task, updated_at: 500 }, [])).toBeNull();
expect(completedDuration({ ...task, created_at: NaN }, events)).toBeNull();
expect(completedDuration({ ...task, approval: { at: 9000 } }, events)?.productionMinutes).toBeNull();
});
});
+61
View File
@@ -0,0 +1,61 @@
"""Read only the task-owned EDA canvas; never focus, save, open or edit a document."""
import base64
import fcntl
import json
import os
from pathlib import Path
import re
import subprocess
import sys
CODE = r'''const doc = await eda.dmt_SelectControl.getCurrentDocumentInfo();
if (!doc || ![1,3,12,15].includes(doc.documentType)) return {available:false};
const image = await eda.dmt_EditorControl.getCurrentRenderedAreaImage(doc.tabId);
if (!image || !image.size || image.size > 8*1024*1024) return {available:false};
const data = await new Promise((resolve,reject)=>{const reader=new FileReader();reader.onload=()=>resolve(reader.result);reader.onerror=reject;reader.readAsDataURL(image);});
return {available:true,kind:doc.documentType===1?'schematic':doc.documentType===15?'3d':'layout',image:data};'''
def capture(tid):
if not re.fullmatch(r'pcb-[0-9a-f]{24}', tid):
return {'available': False, 'reason': 'invalid_task'}
root = Path(os.environ.get('PCB_SESSION_ROOT', '/home/wpz/auto_pcb_2/persistent-runtime'))
task = json.loads((root / 'tasks' / tid / 'state.json').read_text())
session = task.get('eda_session', '')
if not task.get('approval') or not re.fullmatch(r'[0-9a-f-]{36}', session):
return {'available': False, 'reason': 'waiting_for_canvas'}
# Same host lock as generation, acquired without waiting. Production takes priority.
lock = Path.home()/'.local/state/ai-pcb-eda/locks/host.lock'
lock.parent.mkdir(parents=True, exist_ok=True)
with lock.open('a+') as fd:
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
return {'available': False, 'reason': 'eda_busy'}
env = dict(os.environ, DISPLAY=os.environ.get('DISPLAY', ':0'), XDG_RUNTIME_DIR=f'/run/user/{os.getuid()}')
if not env.get('XAUTHORITY'):
auth = list(Path(env['XDG_RUNTIME_DIR']).glob('.mutter-Xwaylandauth.*'))
if auth:
env['XAUTHORITY'] = str(auth[0])
result = subprocess.run(['/usr/local/bin/lceda-pro', 'invoke', '--session', session,
'--ext-uuid', 'eda', '--code-file', '-', '--timeout', '3000', '--no-sandbox'],
input=CODE, capture_output=True, text=True, env=env, timeout=5)
reply = json.loads(result.stdout)
if result.returncode or reply.get('ok') is not True:
return {'available': False, 'reason': 'canvas_unavailable'}
value = reply.get('value') or {}
image = value.get('image', '')
if not value.get('available'):
return {'available': False, 'reason': 'waiting_for_canvas'}
if not image.startswith('data:image/png;base64,'):
return {'available': False, 'reason': 'unsupported_image'}
raw = base64.b64decode(image.split(',', 1)[1], validate=True)
if not raw.startswith(b'\x89PNG\r\n\x1a\n') or len(raw) > 8*1024*1024:
return {'available': False, 'reason': 'invalid_image'}
return {'available': True, 'kind': value['kind'], 'image': image}
if __name__ == '__main__':
try:
answer = capture(sys.argv[1])
except Exception:
answer = {'available': False, 'reason': 'canvas_unavailable'}
print(json.dumps(answer))
+100
View File
@@ -0,0 +1,100 @@
/** Read-only preview bridge. Kept outside codex_pcb so approved jobs retain their source fingerprint. */
import { readFile, readdir, stat, realpath, mkdir, writeFile, rename } from 'node:fs/promises';
import { resolve, sep } from 'node:path';
import { fileURLToPath } from 'node:url';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import { createHash } from 'node:crypto';
const exec = promisify(execFile);
const captureScript = fileURLToPath(new URL('./capture-preview.py', import.meta.url));
const validTask = /^pcb-[0-9a-f]{24}$/;
const kindOf = name => /schematic|sch[-_.]|原理图/i.test(name) ? 'schematic' : /render|assembly|assembled|3d|三维/i.test(name) ? '3d' : /pcb|layout|routing|routed|copper|布线|布局/i.test(name) ? 'layout' : null;
async function exportedFrame(directory, requested) {
const base = await realpath(directory).catch(() => null);
if (!base || base !== resolve(directory)) return null;
const candidates = [];
let visited = 0;
async function walk(folder, depth) {
if (depth > 3) return;
for (const entry of await readdir(folder, { withFileTypes: true })) {
if (++visited > 2000) return;
const path = resolve(folder, entry.name);
if (entry.isDirectory()) await walk(path, depth + 1);
if (!entry.isFile() || !/\.(png|jpe?g)$/i.test(entry.name)) continue;
const kind = kindOf(entry.name);
if (!kind || (requested !== 'auto' && requested !== kind)) continue;
const info = await stat(path);
if (info.size > 0 && info.size <= 8 * 1024 * 1024) candidates.push({ path, kind, at: info.mtimeMs });
}
}
await walk(base, 0);
candidates.sort((a, b) => b.at - a.at);
for (const item of candidates.slice(0, 5)) {
// Recheck real path and file stability; never serve a link outside this task.
const path = await realpath(item.path);
if (!path.startsWith(base + sep)) continue;
const before = await stat(path), bytes = await readFile(path), after = await stat(path);
if (before.mtimeMs !== after.mtimeMs || bytes.length !== after.size) continue;
const png = bytes.subarray(0, 8).equals(Buffer.from([137,80,78,71,13,10,26,10]));
const jpg = bytes[0] === 255 && bytes[1] === 216 && bytes.at(-2) === 255 && bytes.at(-1) === 217;
if (!png && !jpg) continue;
return { kind: item.kind, capturedAt: after.mtimeMs, source: 'export', image: `data:image/${png ? 'png' : 'jpeg'};base64,${bytes.toString('base64')}` };
}
return null;
}
export function createPreviewHandler({ runtime = process.env.PCB_SESSION_ROOT || '/home/wpz/auto_pcb_2/persistent-runtime', capture = async tid => {
const { stdout } = await exec('python3', [captureScript, tid], { timeout: 6500, maxBuffer: 12 * 1024 * 1024 });
return JSON.parse(stdout);
} } = {}) {
const cache = new Map(), pending = new Map(), captureAfter = new Map();
let capturing = false;
async function preview(tid, kind) {
const task = JSON.parse(await readFile(resolve(runtime, 'tasks', tid, 'state.json'), 'utf8'));
let frame = null, reason = 'waiting_for_canvas';
const savedPath = resolve(runtime, 'web-previews', `${tid}.json`);
if (task.approval && task.eda_session && task.state === 'running' && !capturing && Date.now() >= (captureAfter.get(tid) || 0)) {
capturing = true;
if (captureAfter.size > 100) captureAfter.delete(captureAfter.keys().next().value);
captureAfter.set(tid, Date.now() + 5000);
try {
const value = await capture(tid);
reason = value.reason || '';
if (value.available && ['schematic', 'layout', '3d'].includes(value.kind) && /^data:image\/png;base64,/.test(value.image)) {
frame = { kind: value.kind, capturedAt: Date.now(), source: 'canvas', image: value.image };
await mkdir(resolve(runtime, 'web-previews'), { recursive: true });
await writeFile(savedPath + '.tmp', JSON.stringify(frame));
await rename(savedPath + '.tmp', savedPath);
}
} catch { reason = 'canvas_unavailable'; captureAfter.set(tid, Date.now() + 30000); }
finally { capturing = false; }
} else if (capturing) reason = 'eda_busy';
if (!frame) frame = await readFile(savedPath, 'utf8').then(JSON.parse).catch(() => null);
if (frame && kind !== 'auto' && frame.kind !== kind) frame = null;
const exported = await exportedFrame(resolve(runtime, 'tasks', tid, 'workspace', 'artifacts'), kind).catch(() => null);
if (exported && (!frame || exported.capturedAt > frame.capturedAt)) frame = exported;
return { taskId: tid, frame, reason, refreshSeconds: 5 };
}
return async function handle(req, res, path, searchParams) {
const tid = path, kind = searchParams.get('kind') || 'auto';
const reply = (code, body) => { res.writeHead(code, { 'content-type': 'application/json', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' }); res.end(JSON.stringify(body)); };
if (req.method !== 'GET') return reply(405, { message: '预览只支持读取' });
if (!validTask.test(tid) || !['auto', 'schematic', 'layout', '3d'].includes(kind)) return reply(400, { message: '无效的预览请求' });
const key = `${tid}/${kind}`;
try {
let entry = cache.get(key);
if (!entry || Date.now() - entry.at > 5000) {
if (!pending.has(key)) pending.set(key, preview(tid, kind).then(value => {
if (cache.size >= 12) cache.delete(cache.keys().next().value);
const body = JSON.stringify(value);
const result = { value, body, etag: '"' + createHash('sha256').update(body).digest('hex') + '"', at: Date.now() }; cache.set(key, result); return result;
}).finally(() => pending.delete(key)));
entry = await pending.get(key);
}
const headers = { 'content-type': 'application/json', 'cache-control': 'no-cache', 'x-content-type-options': 'nosniff', etag: entry.etag };
if (req.headers?.['if-none-match'] === entry.etag) { res.writeHead(304, headers); res.end(); return; }
res.writeHead(200, headers); res.end(entry.body);
} catch (error) { reply(error.code === 'ENOENT' ? 404 : 503, { message: '画面暂不可用,稍后自动重试' }); }
};
}
+40
View File
@@ -0,0 +1,40 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtemp, mkdir, writeFile, symlink, rm } from 'node:fs/promises';
import { resolve } from 'node:path';
import { createPreviewHandler } from './pcb-preview.mjs';
const tid='pcb-'+'a'.repeat(24), other='pcb-'+'b'.repeat(24);
const png='iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/l9sAAAAASUVORK5CYII=';
async function fixture(t){
const base=process.env.PCB_PREVIEW_TEST_ROOT; assert.ok(base,'Set PCB_PREVIEW_TEST_ROOT to an isolated task directory');
await mkdir(base,{recursive:true});const root=await mkdtemp(resolve(base,'preview-test-'));t.after(()=>rm(root,{recursive:true,force:true}));
for(const id of [tid,other]){await mkdir(resolve(root,'tasks',id,'workspace','artifacts'),{recursive:true});await writeFile(resolve(root,'tasks',id,'state.json'),JSON.stringify({id,state:'running',approval:{},eda_session:'owned-session',request:'PRIVATE REQUEST'}));}
return root;
}
async function request(handle,id,kind='auto',method='GET',headers={}){
let status,body,responseHeaders;await handle({method,headers},{writeHead(code,h){status=code;responseHeaders=h;},end(value){body=value?JSON.parse(value):null;}},id,new URLSearchParams({kind}));return{status,body,headers:responseHeaders};
}
test('concurrent polls coalesce, response is scoped to selected task and contains no task internals',async t=>{
const root=await fixture(t);let calls=0;const handle=createPreviewHandler({runtime:root,capture:async id=>{calls++;assert.equal(id,tid);return {available:true,kind:'layout',image:'data:image/png;base64,'+png};}});
const replies=await Promise.all([request(handle,tid),request(handle,tid)]);assert.equal(calls,1);assert.equal(replies[0].status,200);assert.equal(replies[0].body.taskId,tid);assert.equal(replies[0].body.frame.kind,'layout');assert.ok(!JSON.stringify(replies).includes('PRIVATE REQUEST'));
});
test('production busy retains previous canvas and never substitutes another task canvas',async t=>{
const root=await fixture(t);await mkdir(resolve(root,'web-previews'));await writeFile(resolve(root,'web-previews',tid+'.json'),JSON.stringify({kind:'schematic',source:'canvas',capturedAt:100,image:'data:image/png;base64,'+png}));
const handle=createPreviewHandler({runtime:root,capture:async()=>({available:false,reason:'eda_busy'})});
assert.equal((await request(handle,tid)).body.frame.capturedAt,100);assert.equal((await request(handle,other)).body.frame,null);
});
test('export fallback uses requested view, excludes symlinks and does not invoke cancelled tasks',async t=>{
const root=await fixture(t),dir=resolve(root,'tasks',tid,'workspace','artifacts');await writeFile(resolve(root,'tasks',tid,'state.json'),JSON.stringify({state:'cancelled',approval:{},eda_session:'owned-session'}));
await writeFile(resolve(dir,'schematic.png'),Buffer.from(png,'base64'));await writeFile(resolve(root,'pcb-private.png'),Buffer.from(png,'base64'));await symlink(resolve(root,'pcb-private.png'),resolve(dir,'pcb-symlink.png'));
const handle=createPreviewHandler({runtime:root,capture:async()=>{assert.fail('must not invoke stopped task');}});
assert.equal((await request(handle,tid,'schematic')).body.frame.kind,'schematic');assert.equal((await request(handle,tid,'layout')).body.frame,null);
});
test('invalid IDs, invalid views, missing tasks and writes are rejected',async t=>{
const root=await fixture(t),handle=createPreviewHandler({runtime:root});
assert.equal((await request(handle,'../state.json')).status,400);assert.equal((await request(handle,tid,'../../')).status,400);assert.equal((await request(handle,tid,'auto','POST')).status,405);assert.equal((await request(handle,'pcb-'+'c'.repeat(24))).status,404);
});
test('unchanged snapshots return 304 instead of retransmitting image bytes',async t=>{
const root=await fixture(t);const handle=createPreviewHandler({runtime:root,capture:async()=>({available:true,kind:'layout',image:'data:image/png;base64,'+png})});
const first=await request(handle,tid);const second=await request(handle,tid,'auto','GET',{'if-none-match':first.headers.etag});assert.equal(second.status,304);assert.equal(second.body,null);
});
+10
View File
@@ -1,5 +1,6 @@
/** Production static server + fixed-upstream task proxy. No provider credentials in the browser. */
import http from 'node:http';
import { createPreviewHandler } from './pcb-preview.mjs';
import https from 'node:https';
import { readFile, stat } from 'node:fs/promises';
import { createReadStream } from 'node:fs';
@@ -12,6 +13,8 @@ const siteBase = deployment.base;
if (typeof siteBase !== 'string' || !siteBase.startsWith('/') || !siteBase.endsWith('/'))
throw Error('Build base must be an absolute URL path ending in /');
const apiPrefix = `${siteBase}pcb-api/`;
const previewPrefix = `${siteBase}pcb-preview/`;
const preview = createPreviewHandler();
const target = new URL(process.env.PCB_API_TARGET || 'http://127.0.0.1:8002');
if (!['http:', 'https:'].includes(target.protocol) || target.username || target.password)
throw Error('PCB_API_TARGET must be an HTTP(S) address without embedded credentials');
@@ -31,6 +34,13 @@ const mime = {
const handler = async (req, res) => {
try {
const url = new URL(req.url, 'http://localhost');
if (url.pathname.startsWith(previewPrefix)) {
if (req.headers.origin && req.headers.origin !== (process.env.PUBLIC_ORIGIN || `${process.env.TLS_CERT ? 'https' : 'http'}://${req.headers.host}`)) {
res.writeHead(403); res.end(); return;
}
await preview(req, res, url.pathname.slice(previewPrefix.length), url.searchParams);
return;
}
if (url.pathname.startsWith('/api/')) {
const upstream = https.request(new URL(url.pathname + url.search, process.env.API_TARGET || 'https://dev-vibemake-api.robotquan.com'),
{ method: req.method, headers: Object.fromEntries(Object.entries(req.headers).filter(([key]) => !['host', 'origin', 'referer'].includes(key))) },