Allow paused PCB tasks to discuss and reapprove revised proposals

This commit is contained in:
2026-11-17 16:58:19 +08:00
parent 24e5dda022
commit 3bd056b701
10 changed files with 446 additions and 32 deletions
+13
View File
@@ -269,3 +269,16 @@ networks:
新增空卷时入口会将 `/data/resources` 链接到镜像中的 `/opt/pcb-resources`,文档随镜像升级;如果迁移现有运行目录,则保留原有 `resources/` 并检查其文档和路由器路径。独立更改 `PCB_CODEX_HOME` 或 EDA 工程数据位置时,也要额外挂载相应数据。
参考:[1Panel 编排](https://1panel-dev.github.io/docs/v2/user_manual/containers/compose/)、[Docker 构建上下文](https://docs.docker.com/build/concepts/context/)、[嘉立创 CLI](https://prodocs.lceda.cn/cn/api/guide/cli.html)。
## 已批准任务遇阻后的沟通与修订
前后端需要同时部署本版本。未完成、未运行且已有批准记录的 `blocked / failed / interrupted / cancelled` 任务会开放“发送讨论”“生成修订方案”和(没有待审修订时的)“按原方案重试”。已有历史任务按状态直接获得入口,无需重新创建任务或修改既有批准。已完成任务仍只允许使用问答,不开放修改产出。
- `POST /api/sessions/{id}/feedback`:`text`、`intent`(`discuss` 或 `revise`)、当前 `revision`、`hash`。复用原 Codex thread 和原工作区。讨论不发布方案;修订发布完整新版本及“本次变更”说明。原方案、批准和 EDA session 保留。
- 沟通不依赖 EDA 就绪;这一轮为只读,禁用 Shell 和 MCP,保留模型服务支持的内置网页检索以核实原厂资料,并允许通过既有 `pcb_read_reference` 的 `workspace/...` 文本路径读取本任务证据。不能调用 EDA、检查、导出或交付;未取得的外部资料必须如实说明。已交付使用问答仍采用更严格的工具限制,不开放联网。
- 从请求修订开始,持久化 `recovery.requires_approval=true`。即使新方案尚未生成、讨论失败、停止或服务重启,旧批准和 `/resume` 也不能启动生产。`/approve` 必须匹配已发布的新版本和 hash;新批准存入 `approval`,旧批准保存在 `approval_history`,旧方案保存在 `proposal_history`。
- 单纯讨论结束后仍暂停。若约束未改且运行条件已恢复,用户可显式按原方案重试;供电、器件或需求变更应先生成修订并审核。生产恢复时保留已有工程,检查实际保存状态后局部修改。
- 重启恢复必须以 `recovery` 判断只读审核,不能仅凭历史 `approval` 判断生产授权。已存 `pending_prompt` 用于恢复同一轮讨论/修订。
- 发布前确认没有正在运行的任务,备份任务状态、事件及部署文件。源码指纹变化时,对获授权迁移的未完成任务记录迁移和验收失效信息,再更新冻结指纹;不要删除批准或绕过冻结检查。已完成任务状态和交付文件保持不变。
回归检查:`python -m unittest codex_pcb.tests.test_recovery_review`;前端 `qa/unittests/designer/pcb_recovery_review.test.tsx`。覆盖旧批准拒绝、新方案审批、只读工具限制、原会话保留、重启审核恢复、EDA 离线沟通和已交付设计不重开。
+95 -9
View File
@@ -1,5 +1,7 @@
import asyncio
import contextlib
import copy
from typing import Literal
import json
import shlex
import time
@@ -117,24 +119,38 @@ async def handle(t, method, p):
frozen(t)
if t['state'] == 'cancelled':
raise RuntimeError('Task cancelled')
if t.get('recovery') and name not in {'pcb_proposal','pcb_read_reference'}:
raise PermissionError('Production is paused for discussion/review. No EDA, checks, exports or delivery until explicit website approval or resume.')
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')
if t.get('approval') and t.get('recovery',{}).get('intent')!='revise':
raise ValueError('Use the website revision action before replacing an approved proposal')
markdown=a['markdown'].strip()
if len(markdown)<120:
raise ValueError('Proposal must describe circuit, board, assumptions and deliverables')
if t.get('approval') and '## 本次变更' not in markdown:
raise ValueError('Revised proposal must include a ## 本次变更 section explaining changes, retained work and affected checks')
if t.get('proposal'):
t.setdefault('proposal_history',[]).append({'proposal':copy.deepcopy(t['proposal']), 'approval':copy.deepcopy(t.get('approval')) if t.get('approval',{}).get('hash')==t['proposal']['hash'] and t.get('approval',{}).get('revision')==t['proposal']['revision'] else None})
revision=t.get('proposal',{}).get('revision',0)+1
t['proposal']={'revision':revision,'title':a['title'],'markdown':markdown,'hash':digest(markdown.encode()),'at':time.time()}
event(t,'proposal.published',t['proposal'])
result={'published':True,'revision':revision,'instruction':'Now finish your reply and wait for the website approval. Do not operate EDA.'}
elif name=='pcb_read_reference':
path=inside(ROOT/'resources',a['path'])
requested=a['path']
# Existing resumed threads retain their original tool catalogue. Reuse
# the text reader for bounded, task-local evidence during recovery.
if t.get('recovery') and requested.startswith('workspace/'):
path=inside(workspace(t),requested[len('workspace/'):])
else:
path=inside(ROOT/'resources',requested)
if path.suffix not in {'.md','.txt','.json'}:
raise ValueError('Reference text files only')
if path.stat().st_size>8*1024*1024:
raise ValueError('Reference file exceeds 8 MiB; use smaller saved evidence')
text=path.read_text()
start=max(0,a.get('offset',0));limit=min(40000,a.get('limit',18000))
result={'path':str(path),'text':text[start:start+limit],'total_chars':len(text),'next_offset':start+limit if start+limit<len(text) else None}
@@ -189,7 +205,8 @@ async def run_turn(t, prompt, production):
directory=workspace(t)
refresh_workspace_rules(directory)
prompt=POLICY_TEXT+'\n'+prompt
async with AppServer(directory, production, lambda m,p:handle(t,m,p), runtime=runtime) as client:
recovery_options={'read_only_tools':True,'allow_web':True} if t.get('recovery') and not production else {}
async with AppServer(directory, production, lambda m,p:handle(t,m,p), runtime=runtime, **recovery_options) as client:
CLIENTS[t['id']]=client
instructions=(SOURCE/'instructions.md').read_text()
if runtime.id=='doubao':
@@ -287,7 +304,7 @@ async def work(t, prompt, production):
if not report['ok']:
raise RuntimeError('生产环境预检未通过:' + ';'.join(
item['message'] for item in report['checks'] if not item['ok']))
else:
elif not t.get('recovery'):
await require_runtime_ready()
failures=0;no_progress=0
while True:
@@ -306,6 +323,10 @@ async def work(t, prompt, production):
prompt='Connection recovery. Continue the existing approved task from the full conversation and actual files/EDA state. Inspect uncertain mutations before replaying anything.' if production else t['pending_prompt']
continue
if not production:
if t.get('recovery'):
pending=t.get('proposal',{}).get('revision',0)>t['recovery'].get('after_revision',t.get('approval',{}).get('revision',0))
t['state']='review' if pending else 'needs_input' if t['recovery']['requires_approval'] else 'blocked'
save(t);break
if t.get('proposal'):
t['state']='review'
else:
@@ -336,6 +357,9 @@ async def work(t, prompt, production):
def schedule(t,prompt,production):
if t['id'] in JOBS:
raise HTTPException(409,'Task already running')
if production and t.get('recovery'):
raise HTTPException(409,'Review is paused; explicit approval or original-plan resume is required')
t['pending_prompt']=prompt
t['busy']=True
t['state']='running' if production else 'planning'
t.pop('error',None)
@@ -351,8 +375,9 @@ async def lifespan(app):
aftercare.recover(t)
if t['state'] not in {'completed','cancelled','blocked','failed'} and (t.get('busy') or t['state'] in {'running','planning','interrupted'}):
t['check_eda_session']=bool(t.get('eda_session'))
prompt=('Service restarted. Continue this approved task in the same session. Inspect live state and existing files before repeating uncertain actions.' if t.get('approval') else t.get('pending_prompt',t['request']))
schedule(t,prompt,bool(t.get('approval')))
production=bool(t.get('approval')) and not t.get('recovery')
prompt=('Service restarted. Continue this approved task in the same session. Inspect live state and existing files before repeating uncertain actions.' if production else t.get('pending_prompt',t['request']))
schedule(t,prompt,production)
yield
for job in list(JOBS.values()):
job.cancel()
@@ -471,26 +496,83 @@ async def comment(tid:str,req:Request):
schedule(t,'User review comment:\n'+req.text+'\nRevise the proposal in this same conversation and publish a replacement with pcb_proposal. This is not production authorization.',False)
return public(t)
class Feedback(BaseModel):
text:str=Field(min_length=1,max_length=16000)
intent:Literal['discuss','revise']
revision:int
hash:str
@app.post('/api/sessions/{tid}/feedback',status_code=202)
async def feedback(tid:str,req:Feedback):
t=get(tid)
if not t.get('approval') or t.get('busy') or t['state'] not in {'blocked','failed','interrupted','cancelled','review','needs_input'}:
raise HTTPException(409,'Only paused, unfinished approved tasks can discuss or revise their plan')
p=t.get('proposal',{})
if p.get('revision')!=req.revision or p.get('hash')!=req.hash:
raise HTTPException(409,'方案已更新,请刷新后再发送')
if not req.text.strip():raise HTTPException(422,'请输入问题或修改意见')
try:
frozen(t)
runtime=task_runtime(t)
if not provider_status(runtime)['configured']:
raise HTTPException(503,'模型服务未配置,请联系管理员')
except RuntimeError as exc:
raise HTTPException(409,str(exc)) from None
# Deliberately independent of EDA readiness: users must be able to discuss
# a failed EDA environment without first repairing that environment.
recovery=t.setdefault('recovery',{'reason':t.get('error','任务已暂停'),
'evidence':t.get('blocker_evidence',''),'started_at':time.time(),'requires_approval':False})
recovery['intent']=req.intent
if req.intent=='revise':
recovery['requires_approval']=True
recovery['after_revision']=p['revision']
event(t,'message',{'role':'user','text':req.text,'intent':req.intent})
event(t,'review.requested',{'intent':req.intent,'approved_revision':t['approval']['revision']})
instruction=('Publish a complete replacement proposal with pcb_proposal. Include a ## 本次变更 section describing changes from the approved plan, retained existing work, and checks to repeat. If essential information is missing, ask the user first. Do not assume approval.'
if req.intent=='revise' else 'Answer the question or assess supplied information. Do not publish or change a proposal. Explain options and what decision or evidence is still needed. The user must choose the revision action to request a new proposal.')
prompt=f"""PRODUCTION PAUSED: this turn is discussion/review only, in the SAME conversation. Earlier production authorization is suspended for this turn. Do not operate EDA, edit files, run checks, export or deliver. Never claim a repair was applied.
Current blocker: {recovery['reason']}
Saved evidence: {recovery['evidence']}
You may read existing task text evidence through pcb_read_reference with path workspace/evidence/<file>. API references remain available. Shell and MCP are disabled for this read-only turn. Use built-in web search if available to consult manufacturer references; do not invent external verification.
Approved revision: {t['approval']['revision']}; current proposal revision: {p['revision']}.
Current proposal:
{p['markdown']}
User message:
{req.text}
{instruction}
Finish your reply and wait for the website action. No automatic production resume."""
schedule(t,prompt,False)
return public(t)
@app.post('/api/sessions/{tid}/approve')
async def approve(tid:str,req:Approval):
t=get(tid)
p=t.get('proposal',{})
if t.get('approval'):
if t['approval']['hash']==req.hash:
revising=bool(t.get('recovery',{}).get('requires_approval'))
if t.get('approval') and not revising:
if t['approval']['hash']==req.hash and t['approval']['revision']==req.revision:
return public(t)
raise HTTPException(409,'Different proposal already approved')
if revising and req.revision<=max(t['approval']['revision'],t['recovery'].get('after_revision',0)):
raise HTTPException(409,'请先生成并审核新的方案版本')
if t['state']!='review' or t.get('busy') or p.get('revision')!=req.revision or p.get('hash')!=req.hash:
raise HTTPException(409,'Approve the latest completed proposal revision')
cursor=t['cursor']
await require_runtime_ready(force=True)
if t['cursor']!=cursor:
raise HTTPException(409,'Task changed during environment check; reload before approving')
if t.get('approval'):
t.setdefault('approval_history',[]).append(copy.deepcopy(t['approval']))
t['check_eda_session']=bool(t.get('eda_session'))
if t.get('recovery'):
t.setdefault('recovery_history',[]).append(t.pop('recovery'))
t['approval']={'revision':req.revision,'hash':req.hash,'at':time.time()}
t['frozen_source']=fingerprint(task_runtime(t))
t['design_policy']=DESIGN_POLICY
event(t,'proposal.approved',t['approval'])
prompt=f'''The user explicitly clicked APPROVE AND START for proposal revision {req.revision}, SHA256 {req.hash}.
This server-owned approval authorizes production of the accepted proposal in this same persistent session. Earlier requests to wait applied only to review.
Preserve existing native project and saved work from this conversation. Compare with the newly accepted plan, modify only affected parts, and rerun affected checks; do not recreate the project blindly.
Workspace: {workspace(t)}
Official API documentation: {workspace(t)}/api-reference/references/_index.md
{POLICY_TEXT}
@@ -520,6 +602,8 @@ async def resume(tid:str):
t=get(tid)
if t.get('busy') or t['state'] not in {'failed','blocked','interrupted','cancelled'}:
raise HTTPException(409,'Task is not resumable')
if t.get('recovery',{}).get('requires_approval'):
raise HTTPException(409,'方案正在修订,请审核新版本后确认开始;旧批准不能恢复生产')
try:
frozen(t)
except RuntimeError as e:
@@ -529,6 +613,8 @@ async def resume(tid:str):
if t['cursor']!=cursor:
raise HTTPException(409,'Task changed during environment check; reload before resuming')
t['check_eda_session']=bool(t.get('eda_session'))
if t.get('recovery'):
t.setdefault('recovery_history',[]).append(t.pop('recovery'))
event(t,'task.resume_requested',{})
schedule(t,'The user requests continuing this same task. Preserve the accepted design and inspect actual saved files and EDA state. Continue to verified delivery.' if t.get('approval') else 'Continue the proposal review and publish a complete proposal.',bool(t.get('approval')))
return public(t)
+2
View File
@@ -27,3 +27,5 @@ Shared delivery helpers and acceptance policy (native-errors-block-warnings-reco
- 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.
PAUSED RECOVERY: when the server says PRODUCTION PAUSED, stay in this same conversation but treat the turn as read-only discussion or proposal revision. Previous approval does not authorize EDA actions in this phase. In discussion mode, answer and clarify without publishing a proposal. In revision mode, publish the full revised proposal and include a `## 本次变更` section covering changed constraints, preserved work and affected verification. Do not silently relax requirements to remove a blocker. If key user decisions are missing, ask before proposing a definite solution. Only a subsequent server-owned revision/hash approval permits production again. Use existing task evidence via pcb_read_reference with `workspace/evidence/...` paths; acknowledge unavailable evidence. A paused task should end with clear user choices, not repeated attempts at the same infeasible plan.
+10 -6
View File
@@ -40,7 +40,7 @@ def api_key(runtime=None):
return key
def process_config(production, runtime=None, *, read_only_tools=False):
def process_config(production, runtime=None, *, read_only_tools=False, allow_web=False):
runtime = runtime or runtime_for()
if runtime.auth_mode not in {'apikey', 'chatgpt'}:
raise ValueError('PCB_CODEX_AUTH must be apikey or chatgpt')
@@ -69,9 +69,10 @@ def process_config(production, runtime=None, *, read_only_tools=False):
config['web_search'] = 'live'
config['features.standalone_web_search'] = True
if read_only_tools:
config.update({'sandbox_mode':'read-only', 'web_search':'disabled',
'features.shell_tool':False, 'features.multi_agent':False,
'features.standalone_web_search':False, 'mcp_servers':{}})
config.update({'sandbox_mode':'read-only',
'features.shell_tool':False, 'features.multi_agent':False, 'mcp_servers':{}})
if not allow_web:
config.update({'web_search':'disabled','features.standalone_web_search':False})
# Explicitly disable inherited named MCP servers as well as the root table.
config_file=CODEX_HOME/'config.toml'
if config_file.is_file():
@@ -84,7 +85,7 @@ def process_config(production, runtime=None, *, read_only_tools=False):
class AppServer:
def __init__(self, directory, production, handler, runtime=None, *, read_only_tools=False):
def __init__(self, directory, production, handler, runtime=None, *, read_only_tools=False, allow_web=False):
self.directory, self.production, self.handler = directory, production, handler
self.pending, self.requests, self.counter = {}, set(), 0
self.events = asyncio.Queue()
@@ -93,9 +94,12 @@ class AppServer:
self.err = None
self.runtime = runtime or runtime_for()
self.read_only_tools = read_only_tools
self.allow_web = allow_web
async def __aenter__(self):
args, env = process_config(self.production, self.runtime, read_only_tools=True) if self.read_only_tools else process_config(self.production, self.runtime)
options={'read_only_tools':True} if self.read_only_tools else {}
if self.allow_web:options['allow_web']=True
args, env = process_config(self.production, self.runtime, **options)
# Production excludes system temp directories from writable roots.
# Keep native shell/tool temporary files in this task's writable root.
temporary = self.directory / 'tmp'
+202
View File
@@ -0,0 +1,202 @@
"""Paused production can converse/revise without reusing old production consent."""
import asyncio
import copy
import json
import tempfile
import unittest
from pathlib import Path
from unittest.mock import AsyncMock, patch
from fastapi import HTTPException
from codex_pcb import app as service
class RecoveryReviewTest(unittest.IsolatedAsyncioTestCase):
def setUp(self):
self.tmp=tempfile.TemporaryDirectory(dir=Path(__file__).parent)
self.addCleanup(self.tmp.cleanup)
self.folder=Path(self.tmp.name)
(self.folder/'evidence').mkdir()
(self.folder/'evidence/blocker.md').write_text('manufacturer evidence')
self.task={'id':'test-recovery','state':'blocked','busy':False,'cursor':5,
'request':'test board','thread_id':'original-thread','eda_session':'original-eda',
'error':'Power constraint conflict','blocker_evidence':'evidence/blocker.md',
'proposal':{'revision':1,'title':'Original','markdown':'original approved circuit '*10,'hash':'v1'},
'approval':{'revision':1,'hash':'v1','at':1},'frozen_source':service.fingerprint()}
for name,kwargs in [('get',{'return_value':self.task}),('event',{}),('save',{}),
('workspace',{'return_value':self.folder}),
('provider_status',{'return_value':{'configured':True}})]:
p=patch.object(service,name,**kwargs);p.start();self.addCleanup(p.stop)
self.ready=patch.object(service,'require_runtime_ready',new_callable=AsyncMock).start()
self.addCleanup(patch.stopall)
def feedback_request(self,intent='discuss',text='What can we change?'):
p=self.task['proposal']
return service.Feedback(text=text,intent=intent,revision=p['revision'],hash=p['hash'])
async def start_feedback(self,intent='discuss'):
with patch.object(service,'schedule') as schedule:
await service.feedback(self.task['id'],self.feedback_request(intent))
self.assertFalse(schedule.call_args.args[2])
return schedule.call_args.args[1]
async def tool(self,name,args):
return await service.handle(self.task,'item/tool/call',{'tool':name,'arguments':args,'callId':'test'})
async def publish(self):
return await self.tool('pcb_proposal',{'title':'Revised','markdown':'## 本次变更\nUse external supply; retain interfaces and repeat power checks.\n'+('Complete revised proposal. '*12)})
async def test_discussion_needs_no_eda_and_cannot_publish_or_mutate(self):
before=copy.deepcopy(self.task)
prompt=await self.start_feedback()
self.ready.assert_not_awaited()
self.assertIn('PRODUCTION PAUSED',prompt)
with patch.object(service,'execute',new_callable=AsyncMock) as execute,patch.object(service,'verify_native',new_callable=AsyncMock) as check,patch.object(service,'prepare_delivery',new_callable=AsyncMock) as prepare,patch.object(service,'deliver',new_callable=AsyncMock) as deliver:
for name in ('pcb_eda','pcb_check','pcb_prepare_delivery','pcb_deliver','pcb_blocked','pcb_proposal'):
result=await self.tool(name,{})
self.assertFalse(result['success'],name)
for mock in (execute,check,prepare,deliver):mock.assert_not_awaited()
for key in ('approval','proposal','thread_id','eda_session'):
self.assertEqual(self.task[key],before[key])
with patch.object(service,'run_turn',new_callable=AsyncMock):
await service.work(self.task,prompt,False)
self.assertEqual(self.task['state'],'blocked')
self.assertFalse(self.task['busy'])
async def test_revision_requires_new_approval_and_keeps_original_sessions(self):
before=copy.deepcopy(self.task)
await self.start_feedback('revise')
with self.assertRaises(HTTPException):await service.resume(self.task['id'])
self.assertTrue((await self.publish())['success'])
self.assertEqual(self.task['proposal']['revision'],2)
self.assertEqual(self.task['proposal_history'][0],{'proposal':before['proposal'],'approval':before['approval']})
self.assertEqual(self.task['approval'],before['approval'])
self.task['state']='review'
with self.assertRaises(HTTPException):
await service.approve(self.task['id'],service.Approval(revision=1,hash='v1'))
with self.assertRaises(HTTPException):
await service.approve(self.task['id'],service.Approval(revision=2,hash='stale'))
with patch.object(service,'schedule') as schedule:
await service.approve(self.task['id'],service.Approval(revision=2,hash=self.task['proposal']['hash']))
self.assertTrue(schedule.call_args.args[2])
self.assertIn('Preserve existing native project',schedule.call_args.args[1])
self.assertNotIn('recovery',self.task)
self.assertEqual(self.task['approval']['revision'],2)
self.assertEqual(self.task['approval_history'],[before['approval']])
self.assertEqual(self.task['thread_id'],before['thread_id'])
self.assertEqual(self.task['eda_session'],before['eda_session'])
self.assertTrue(self.task['check_eda_session'])
async def test_missing_decision_does_not_make_old_proposal_approvable(self):
await self.start_feedback('revise')
with patch.object(service,'run_turn',new_callable=AsyncMock):
await service.work(self.task,'Ask user to choose supply',False)
self.assertEqual(self.task['state'],'needs_input')
with self.assertRaises(HTTPException):
await service.approve(self.task['id'],service.Approval(revision=1,hash='v1'))
with self.assertRaises(HTTPException):await service.resume(self.task['id'])
await self.start_feedback('discuss')
self.assertTrue(self.task['recovery']['requires_approval'])
with self.assertRaises(HTTPException):await service.resume(self.task['id'])
async def test_discussion_of_pending_revision_preserves_review_gate(self):
await self.start_feedback('revise');await self.publish()
self.task['state']='review'
await self.start_feedback('discuss')
with patch.object(service,'run_turn',new_callable=AsyncMock):
await service.work(self.task,'Explain revision',False)
self.assertEqual(self.task['state'],'review')
self.assertFalse((await self.publish())['success'])
self.task['state']='failed'
with self.assertRaises(HTTPException):await service.resume(self.task['id'])
async def test_original_plan_retry_after_discussion_is_explicit(self):
await self.start_feedback()
with patch.object(service,'schedule') as schedule:
await service.resume(self.task['id'])
self.assertTrue(schedule.call_args.args[2])
self.assertNotIn('recovery',self.task)
self.assertEqual(self.task['approval']['revision'],1)
self.assertEqual(self.task['thread_id'],'original-thread')
async def test_unanswered_followup_revision_cannot_approve_previous_draft(self):
await self.start_feedback('revise');await self.publish()
self.task['state']='review'
previous=copy.deepcopy(self.task['proposal'])
await self.start_feedback('revise')
with patch.object(service,'run_turn',new_callable=AsyncMock):
await service.work(self.task,'Ask user about additional changes',False)
self.assertEqual(self.task['state'],'needs_input')
await self.start_feedback('discuss')
with patch.object(service,'run_turn',new_callable=AsyncMock):
await service.work(self.task,'Explain missing decision',False)
self.assertEqual(self.task['state'],'needs_input')
with self.assertRaises(HTTPException):
await service.approve(self.task['id'],service.Approval(revision=previous['revision'],hash=previous['hash']))
async def test_stale_feedback_busy_and_completed_rejected(self):
req=self.feedback_request()
self.task['proposal']['revision']=2
with self.assertRaises(HTTPException):await service.feedback(self.task['id'],req)
self.assertNotIn('recovery',self.task)
for state,busy in [('running',True),('completed',False)]:
self.task.update(state=state,busy=busy)
with self.assertRaises(HTTPException):await service.feedback(self.task['id'],self.feedback_request())
async def test_read_only_evidence_blocks_escape_and_nontext(self):
await self.start_feedback()
result=await self.tool('pcb_read_reference',{'path':'workspace/evidence/blocker.md','offset':0,'limit':100})
self.assertTrue(result['success'])
self.assertIn('manufacturer evidence',result['contentItems'][0]['text'])
(self.folder/'evidence/model.step').write_text('geometry')
(self.folder/'evidence/escape.md').symlink_to(self.folder.parent/'secret.md')
for path in ('workspace/../secret.md','workspace/evidence/model.step','workspace/evidence/escape.md'):
self.assertFalse((await self.tool('pcb_read_reference',{'path':path}))['success'])
async def test_restart_keeps_pending_review_read_only(self):
await self.start_feedback('revise')
self.task.update(state='planning',busy=True,pending_prompt='PRODUCTION PAUSED: revise safely')
taskdir=self.folder/'tasks'/self.task['id'];taskdir.mkdir(parents=True)
(taskdir/'state.json').write_text(json.dumps(self.task))
with patch.object(service,'TASKS',self.folder/'tasks'),patch.object(service,'CACHE',{}),patch.object(service,'JOBS',{}),patch.object(service,'schedule') as schedule,patch.object(service.readiness,'start'),patch.object(service.readiness,'close',new_callable=AsyncMock),patch.object(service.aftercare,'recover'),patch.object(service.aftercare,'close',new_callable=AsyncMock):
async with service.lifespan(service.app):pass
self.assertFalse(schedule.call_args.args[2])
self.assertEqual(schedule.call_args.args[1],self.task['pending_prompt'])
async def test_review_turn_resumes_same_thread_with_tools_locked(self):
await self.start_feedback('revise')
calls=[];options=[]
class Server:
def __init__(self,*args,**kwargs):
options.append((args,kwargs));self.events=asyncio.Queue();self.requests=set()
async def __aenter__(self):return self
async def __aexit__(self,*args):pass
async def call(self,method,args):
calls.append((method,args))
if method=='thread/resume':return {'thread':{'id':'original-thread'}}
if method=='turn/start':
await self.events.put({'method':'turn/completed','params':{'turn':{'id':'review-turn','status':'completed'}}})
return {'turn':{'id':'review-turn'}}
raise AssertionError(method)
with patch.object(service,'AppServer',Server):
await service.run_turn(self.task,'PRODUCTION PAUSED',False)
service.CLIENTS.pop(self.task['id'],None)
self.assertFalse(options[0][0][1]);self.assertTrue(options[0][1]['read_only_tools'])
self.assertTrue(options[0][1]['allow_web'])
self.assertEqual(calls[0][1]['threadId'],'original-thread')
self.assertEqual(calls[1][1]['sandboxPolicy'],{'type':'readOnly','networkAccess':False})
async def test_schedule_cannot_bypass_review(self):
await self.start_feedback('revise')
with self.assertRaises(HTTPException):service.schedule(self.task,'produce',True)
def test_recovery_search_preserves_read_only_tool_lock(self):
from codex_pcb import rpc
with patch.object(rpc,'CODEX_HOME',self.folder):
(self.folder/'config.toml').write_text('[mcp_servers.eda]\ncommand="unused"\n')
runtime=service.runtime_for('openai')
args,_=rpc.process_config(False,runtime,read_only_tools=True,allow_web=True)
strict,_=rpc.process_config(False,runtime,read_only_tools=True)
self.assertIn('web_search="live"',args)
self.assertIn('web_search="disabled"',strict)
for item in ('features.shell_tool=false','mcp_servers.eda.enabled=false','sandbox_mode="read-only"'):
self.assertIn(item,args)
+22 -13
View File
@@ -13,7 +13,7 @@ type AiProvider = { id: string; label: string; model: string; effort: string; co
type ProviderConfig = { default_provider: string; providers: AiProvider[] };
const BASE = `${import.meta.env.BASE_URL}pcb-api`;
const ACTIVE = 'vibemake.pcb2.persistent-session';
const STATES: Record<string, string> = { planning: '正在制定方案', review: '等待审核方案', needs_input: '等待补充需求', running: '自主设计中', completed: '已完成交付', blocked: '遇到阻碍', failed: '运行失败', interrupted: '等待恢复', cancelled: '已停止' };
const STATES: Record<string, string> = { planning: '正在制定方案', review: '等待审核方案', needs_input: '等待补充需求', running: '自主设计中', completed: '已完成交付', blocked: '已暂停,等待你的决定', failed: '运行失败', interrupted: '等待恢复', cancelled: '已停止' };
async function api<T>(path: string, data?: unknown): Promise<T> {
const r = await fetch(BASE + path, { method: data === undefined ? 'GET' : 'POST', cache: 'no-store', headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, body: data === undefined ? undefined : JSON.stringify(data) });
return parseApiResponse<T>(r, BASE + path);
@@ -96,11 +96,17 @@ function ConnectedCodexPcbDock(): JSX.Element {
const create = () => action(async () => { const t = await api<Session>('/sessions', { text: request, provider: selectedProvider }); choose(t.id); setTask(t); setRequest(''); });
const updateTask = (next: Session) => { if (activeRef.current === next.id) setTask(next); };
const send = () => action(async () => { const id = active; const t = await api<Session>(`/sessions/${id}/comments`, { text: comment }); updateTask(t); if (activeRef.current === id) { setComment(''); setTab('activity'); } });
const feedback = (intent: 'discuss' | 'revise') => action(async () => { if (!task?.proposal) return; const id = active; const t = await api<Session>(`/sessions/${id}/feedback`, { text: comment, intent, revision: task.proposal.revision, hash: task.proposal.hash }); updateTask(t); if (activeRef.current === id) { setComment(''); setTab('activity'); } });
const approve = () => action(async () => { if (!task?.proposal) return; const id = active; updateTask(await api<Session>(`/sessions/${id}/approve`, { revision: task.proposal.revision, hash: task.proposal.hash })); if (activeRef.current === id) setTab('activity'); });
const cancel = () => action(async () => { updateTask(await api<Session>(`/sessions/${active}/cancel`, {})); });
const resume = () => action(async () => { const id = active; updateTask(await api<Session>(`/sessions/${id}/resume`, {})); if (activeRef.current === id) setTab('activity'); });
const downloadable = (f: Artifact) => `${BASE}/sessions/${active}/files/${encodeURIComponent(f.name)}`;
const canReview = task && !task.approval && !task.busy && ['review','needs_input','failed'].includes(task.state);
const canRecover = !!task?.approval && !task.busy && ['blocked','failed','cancelled','interrupted','review','needs_input'].includes(task.state);
const canCompose = canReview || canRecover;
const pendingRevision = task?.state === 'review' && !!task.recovery?.requires_approval && !!task.proposal && task.proposal.revision !== task.approval?.revision;
const canApprove = task?.state === 'review' && !task.busy && (canReview || pendingRevision);
const canResume = canRecover && !task?.recovery?.requires_approval && ['blocked','failed','cancelled','interrupted'].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 provider = providers.find(p => p.id === selectedProvider);
const taskProvider = providers.find(p => p.id === task?.ai_provider)?.label || task?.ai_provider || 'OpenAI';
@@ -123,33 +129,36 @@ function ConnectedCodexPcbDock(): JSX.Element {
<EnvironmentStatus report={runtime} checking={runtimeChecking} error={runtimeError} onRetry={recheckRuntime}/>
{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>}
{canRecover && <section className="cp-proposal-card" aria-label="暂停后的下一步"><strong>制作已暂停,已有方案和工程会保留</strong><p>{task.recovery?.reason || task.error || '当前任务没有继续运行。可以先沟通原因,再决定下一步。'}</p><p>在下方提问或补充资料;需要更换器件、供电等设计约束时,选择“生成修订方案”,审核后再恢复制作。</p>{task.recovery?.requires_approval && <p>修订尚未批准,原方案的批准不能启动生产。</p>}</section>}
{task.error && (!canRecover || (task.recovery && task.error !== task.recovery.reason)) && <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.proposal && (canReview || pendingRevision) && !task.busy && <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>模型:{taskProvider} · {task.model || '原会话模型'} · 方案与生产共用此会话</p></details>}
</div>}
{tab === 'qa' && task.state === 'completed' && <DeliveryChat key={task.id} taskId={task.id}/>}
{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 === 'plan' && <div className="cp-plan"><details><summary>原始需求</summary><p>{task.request}</p></details>{task.proposal ? <Markdown value={task.proposal.markdown}/> : <p className="cp-muted">AI 正在研究需求和制定方案。</p>}{task.approval && <div className="cp-approved">已批准版本:v{task.approval.revision}{task.recovery?.requires_approval ? ';制作已暂停,等待新方案确认。' : '。'}</div>}{!!task.proposal_history?.length && <details><summary>历史方案与批准记录</summary>{task.proposal_history.map(item => <details key={item.proposal.revision}><summary>v{item.proposal.revision} · {item.approval ? '曾批准' : '未批准'} · {item.proposal.title}</summary><Markdown value={item.proposal.markdown}/></details>)}</details>}</div>}
{tab === 'files' && <div className="cp-files">{!task.delivery ? <p className="cp-muted">完成设计和检查后,交付文件会显示在这里。生成过程可在左侧预览。</p> : <><p>{task.delivery.notes}</p><p className="cp-muted">交互式 3D 模型、原理图和布线图在左侧查看。</p>{task.delivery.files.map(f => <a className="cp-file" key={f.name} href={downloadable(f)} download><div><strong>{f.label}</strong><small>{f.name} · {(f.bytes / 1024).toFixed(1)} KB</small></div><span>下载 ↓</span></a>)}</>}</div>}
</>}
</main>
{task?.state === 'completed' ? <div className="cp-composer cp-completed-actions"><p>设计已交付,可继续询问使用方法。</p><div><button className="cp-primary" onClick={() => setTab('qa')}>询问这块板子</button><button onClick={() => choose(null)}>开始新设计</button></div></div> : <form className="cp-composer" onSubmit={event => { event.preventDefault(); if (busy || !environmentReady) return; if (!active && provider?.configured && request.trim().length >= 5) void create(); else if (canReview && comment.trim().length >= 5) void send(); }}>
{task?.state === 'completed' ? <div className="cp-composer cp-completed-actions"><p>设计已交付,可继续询问使用方法。</p><div><button className="cp-primary" onClick={() => setTab('qa')}>询问这块板子</button><button onClick={() => choose(null)}>开始新设计</button></div></div> : <form className="cp-composer" onSubmit={event => { event.preventDefault(); if (busy) return; if (canRecover && comment.trim()) { void feedback('discuss'); return; } if (!environmentReady) return; if (!active && provider?.configured && request.trim().length >= 5) void create(); else if (canReview && comment.trim().length >= 5) void send(); }}>
{!active && <div className="cp-provider"><label htmlFor="cp-provider">AI 服务</label><select id="cp-provider" value={selectedProvider} onChange={e => setSelectedProvider(e.target.value)} disabled={busy || !providers.length} aria-describedby="cp-provider-help">{!providers.length && <option value="">正在读取服务配置…</option>}{providers.map(p => <option key={p.id} value={p.id} disabled={!p.configured}>{p.label} · {p.model}{!p.configured ? '(未配置凭据)' : ''}</option>)}</select><small id="cp-provider-help">{provider && !provider.configured ? `${provider.label} 尚未配置服务端凭据,请先配置后端或选择其他服务。` : '所选服务及模型在本次设计中保持固定;新建设计时可以切换。'}</small></div>}
<label htmlFor="cp-compose">{!active ? '描述你的设计需求' : 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)}
<label htmlFor="cp-compose">{!active ? '描述你的设计需求' : canRecover ? '讨论阻碍或提出修改' : canReview ? '补充要求或修改方案' : '设计沟通'}</label>
<textarea id="cp-compose" rows={3} value={!active ? request : comment} disabled={busy || (!!active && !canCompose)} onChange={e => active ? setComment(e.target.value) : setRequest(e.target.value)}
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?.approval ? '正在按已确认方案制作,可在对话中查看最新进展。' : 'AI 正在处理,方案就绪后可继续沟通…'}/>
<div className="cp-compose-actions"><small>{!active || canReview ? '⌘ / Ctrl + Enter 发送' : '关闭页面,后台仍会继续'}</small><div>
placeholder={!active ? '例如:设计 ESP32 最小系统板,5V 供电,带下载接口…' : canRecover ? '可以询问原因、补充资料,或描述希望修改的方案。发送讨论不会自动恢复绘板。' : canReview ? '输入需要调整的地方,AI 会更新设计方案…' : task?.approval ? '正在按已确认方案制作,可在对话中查看最新进展。' : 'AI 正在处理,方案就绪后可继续沟通…'}/>
<div className="cp-compose-actions"><small>{canRecover ? '发送后只讨论或修订,确认后才恢复制作' : !active || canReview ? '⌘ / Ctrl + Enter 发送' : task?.busy ? '关闭页面,后台仍会继续' : '任务已暂停,等待操作'}</small><div>
{!active && <button type="submit" className="cp-primary" disabled={busy || !environmentReady || !provider?.configured || request.trim().length < 5}>{busy ? '正在提交…' : '发送需求 →'}</button>}
{canReview && <><button type="submit" disabled={busy || !environmentReady || comment.trim().length < 5}>发送修改意见</button><button type="button" className="cp-primary" disabled={busy || !environmentReady || task.state !== 'review' || !!comment.trim()} onClick={approve}>确认方案并开始</button></>}
{canReview && <button type="submit" disabled={busy || !environmentReady || comment.trim().length < 5}>发送修改意见</button>}
{canRecover && <><button type="submit" disabled={busy || !comment.trim()}>发送讨论</button><button type="button" disabled={busy || !comment.trim()} onClick={() => feedback('revise')}>生成修订方案</button></>}
{canApprove && <button type="button" className="cp-primary" disabled={busy || !environmentReady || !!comment.trim()} onClick={approve}>{pendingRevision ? '确认修订并继续制作' : '确认方案并开始'}</button>}
{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 || !environmentReady} onClick={resume}>继续此设计</button>}
</div></div>{canReview && comment.trim() && <small className="cp-muted">请先发送修改意见,待新方案生成后再确认。</small>}
{!environmentReady && <small id="cp-environment-help" className="cp-muted">绘板环境检查通过后才能提交需求、修改方案或开始绘板。</small>}
{canResume && <button type="button" disabled={busy || !environmentReady || !!comment.trim()} onClick={resume}>按原方案重试</button>}
</div></div>{canCompose && comment.trim() && <small className="cp-muted">请先发送输入内容;修订方案需要审核确认后才会制作。</small>}
{!environmentReady && <small id="cp-environment-help" className="cp-muted">{canRecover ? '绘板环境未就绪,仍可讨论和修订方案;恢复制作需要环境检查通过。' : '绘板环境检查通过后才能提交需求、修改方案或开始绘板。'}</small>}
</form>}
</section>
</div>
+3 -3
View File
@@ -21,7 +21,7 @@ export function TaskProgress({ task, entries, sessions }: {
const observed = useMemo(() => observedProductionStage(entries), [entries]);
const estimate = useMemo(() => productionEstimate(sessions, task.id), [sessions, task.id]);
const stage = progressStage(task, observed, remembered);
const paused = PAUSED_STATES.has(task.state);
const paused = PAUSED_STATES.has(task.state) || !!task.recovery;
const completed = task.state === 'completed';
const duration = useMemo(() => completedDuration(task, entries), [task, entries]);
useEffect(() => {
@@ -35,8 +35,8 @@ export function TaskProgress({ task, entries, sessions }: {
try { localStorage.setItem(`vibemake.pcb.progress.${task.id}`, String(observed)); } catch { /* Storage is optional. */ }
}, [task.id, task.approval, observed, remembered]);
const current = completed ? '已完成交付' : paused
? ({ blocked: '遇到阻碍', failed: '运行失败', interrupted: '等待恢复', cancelled: '已停止' }[task.state] || '等待恢复')
const current = completed ? '已完成交付' : task.recovery ? (task.busy ? task.recovery.intent === 'revise' ? '正在修订方案,制作暂停' : '正在讨论,制作暂停' : task.state === 'review' ? '等待确认修订方案' : '等待你的补充或决定') : paused
? ({ blocked: '已暂停,等待你的决定', failed: '运行失败', interrupted: '等待恢复', cancelled: '已停止' }[task.state] || '等待恢复')
: task.state === 'needs_input' ? '等待补充需求' : stage === 1 ? '等待你确认方案' : PROGRESS_STAGES[stage];
const end = completed || paused ? duration?.completedAt ?? task.updated_at ?? now : now;
const elapsed = elapsedLabel(end - (task.approval?.at ?? task.created_at));
+2
View File
@@ -7,6 +7,7 @@ export interface ProgressSession {
updated_at?: number;
approval?: { at?: number };
proposal?: { at?: number };
recovery?: { requires_approval: boolean; intent: 'discuss' | 'revise' };
}
export interface ProgressEvent {
type: string;
@@ -84,6 +85,7 @@ export function elapsedLabel(seconds: number): string {
export function remainingEstimate(task: ProgressSession, estimate: DurationEstimate | null, now: number): string {
if (task.state === 'completed') return '交付文件已就绪';
if (task.recovery) return task.recovery.requires_approval ? '制作已暂停,审核修订方案后再估算剩余时间' : '制作已暂停,讨论不会自动恢复绘板';
if (PAUSED_STATES.has(task.state)) return '恢复运行后再估算剩余时间';
if (task.state === 'needs_input') return '等待你补充需求后继续生成方案';
if (!task.approval) return task.state === 'review'
+2 -1
View File
@@ -1,3 +1,4 @@
export type Artifact = { name: string; kind: string; label: string; bytes: number; sha256: string };
export type Session = { id: string; request: string; state: string; busy: boolean; ai_provider?: string; model?: string; effort?: string; thread_id?: string; error?: string; cursor: number; created_at: number; updated_at?: number; proposal?: { title: string; markdown: string; revision: number; hash: string; at?: number }; approval?: { revision: number; at?: number }; delivery?: { files: Artifact[]; notes: string }; };
export type Proposal = { title: string; markdown: string; revision: number; hash: string; at?: number };
export type Session = { id: string; request: string; state: string; busy: boolean; ai_provider?: string; model?: string; effort?: string; thread_id?: string; error?: string; cursor: number; created_at: number; updated_at?: number; proposal?: Proposal; recovery?: { reason: string; evidence?: string; intent: 'discuss' | 'revise'; requires_approval: boolean }; proposal_history?: { proposal: Proposal; approval?: { revision: number; hash?: string; at?: number } | null }[]; approval?: { revision: number; at?: number }; delivery?: { files: Artifact[]; notes: string }; };
export type Entry = { seq: number; at: number; type: string; data: Record<string, unknown> };
@@ -0,0 +1,95 @@
// @vitest-environment happy-dom
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { afterEach, expect, it, vi } from 'vitest';
import { CodexPcbDock } from '@ziroeda/designer/src/codex-pcb/CodexPcbDock.js';
import type { Session } from '@ziroeda/designer/src/codex-pcb/workbench-types.js';
vi.mock('@ziroeda/designer/src/codex-pcb/DeliveryModel3D.js', () => ({ DeliveryModel3D: () => null }));
const base: Session = { id: 'pcb-blocked', request: 'HDMI capture board', state: 'blocked', busy: false, cursor: 1, created_at: 100,
error: '已批准的供电约束存在冲突', thread_id: 'original-thread',
proposal: { title: '采集板方案', markdown: '原方案', revision: 1, hash: 'v1' }, approval: { revision: 1, at: 100 } };
function setup(task: Session = structuredClone(base), ready = true, reject = false) {
window.history.replaceState(null, '', '/?ai=1');
localStorage.setItem('vibemake.pcb2.persistent-session', task.id);
const fetch = vi.fn(async (url: string, init?: RequestInit) => {
if (url.includes('/readiness')) return Response.json({ ok: ready, status: ready ? 'ready' : 'unavailable', checks: [], checked_at: 100 });
if (url.endsWith('/providers')) return Response.json({ default_provider: 'openai', providers: [{ id: 'openai', label: 'OpenAI', model: 'test', effort: 'high', configured: true }] });
if (url.endsWith('/sessions')) return Response.json([task]);
if (url.includes('/events?')) return Response.json([]);
if (init?.method === 'POST' && reject) return Response.json({ detail: '模型连接暂时失败' }, { status: 503 });
return Response.json(init?.method === 'POST' ? { ...task, busy: true, state: 'planning' } : task);
});
vi.stubGlobal('fetch', fetch); render(<CodexPcbDock/>); return fetch;
}
afterEach(() => { cleanup(); localStorage.clear(); window.history.replaceState(null, '', '/'); vi.unstubAllGlobals(); });
it('allows blocked discussion when EDA is unavailable without resuming production', async () => {
const fetch = setup(structuredClone(base), false);
const input = await screen.findByLabelText('讨论阻碍或提出修改') as HTMLTextAreaElement;
expect(input.disabled).toBe(false);
expect(screen.queryByText('关闭页面,后台仍会继续')).toBeNull();
expect(screen.getByLabelText('暂停后的下一步')).toBeTruthy();
expect((screen.getByRole('button', { name: '按原方案重试' }) as HTMLButtonElement).disabled).toBe(true);
fireEvent.change(input, { target: { value: '为什么这个约束无法满足?' } });
fireEvent.click(screen.getByRole('button', { name: '发送讨论' }));
await waitFor(() => expect(fetch.mock.calls.some(([url, init]) => url.endsWith('/feedback') && init?.method === 'POST')).toBe(true));
const [url, init] = fetch.mock.calls.find(([, init]) => init?.method === 'POST')!;
expect(url).toBe('/pcb-api/sessions/pcb-blocked/feedback');
expect(JSON.parse(String(init?.body))).toEqual({ text: '为什么这个约束无法满足?', intent: 'discuss', revision: 1, hash: 'v1' });
expect(fetch.mock.calls.some(([url]) => url.endsWith('/resume') || url.endsWith('/approve'))).toBe(false);
});
it('sends explicit revision intent and blocks accidental resume with unsent input', async () => {
const fetch = setup();
const input = await screen.findByLabelText('讨论阻碍或提出修改');
fireEvent.change(input, { target: { value: '请评估独立供电方案,并保留原接口。' } });
expect((screen.getByRole('button', { name: '按原方案重试' }) as HTMLButtonElement).disabled).toBe(true);
fireEvent.click(screen.getByRole('button', { name: '生成修订方案' }));
await waitFor(() => expect(fetch.mock.calls.some(([, init]) => init?.method === 'POST')).toBe(true));
const [, init] = fetch.mock.calls.find(([, init]) => init?.method === 'POST')!;
expect(JSON.parse(String(init?.body)).intent).toBe('revise');
});
it('requires explicit approval of v2, displays history and removes old-plan retry', async () => {
const task: Session = { ...structuredClone(base), state: 'review',
proposal: { ...base.proposal!, revision: 2, hash: 'v2', markdown: '## 本次变更\n更改供电方式' },
recovery: { intent: 'revise', requires_approval: true, reason: base.error! },
proposal_history: [{ proposal: base.proposal!, approval: base.approval }] };
const fetch = setup(task);
const approve = await screen.findByRole('button', { name: '确认修订并继续制作' }) as HTMLButtonElement;
await waitFor(() => expect(approve.disabled).toBe(false));
expect(screen.queryByRole('button', { name: '按原方案重试' })).toBeNull();
fireEvent.click(screen.getByRole('button', { name: '设计方案 · v2' }));
expect(screen.getByText('历史方案与批准记录')).toBeTruthy();
fireEvent.change(screen.getByLabelText('讨论阻碍或提出修改'), { target: { value: '还需要修改' } });
expect(approve.disabled).toBe(true);
fireEvent.change(screen.getByLabelText('讨论阻碍或提出修改'), { target: { value: '' } });
fireEvent.click(approve);
await waitFor(() => expect(fetch.mock.calls.some(([url]) => url.endsWith('/approve'))).toBe(true));
const [, init] = fetch.mock.calls.find(([url]) => url.endsWith('/approve'))!;
expect(JSON.parse(String(init?.body))).toEqual({ revision: 2, hash: 'v2' });
});
it('does not offer approval or old-plan retry before a revision has been published', async () => {
setup({ ...structuredClone(base), state: 'needs_input', recovery: { intent: 'revise', requires_approval: true, reason: base.error! } });
await screen.findByLabelText('讨论阻碍或提出修改');
expect(screen.queryByRole('button', { name: '确认修订并继续制作' })).toBeNull();
expect(screen.queryByRole('button', { name: '按原方案重试' })).toBeNull();
});
it('preserves typed feedback on a request failure so it can be retried', async () => {
setup(structuredClone(base), true, true);
const input = await screen.findByLabelText('讨论阻碍或提出修改') as HTMLTextAreaElement;
fireEvent.change(input, { target: { value: '补充原厂资料' } });
fireEvent.click(screen.getByRole('button', { name: '发送讨论' }));
await screen.findByRole('alert');
expect(input.value).toBe('补充原厂资料');
expect(input.disabled).toBe(false);
});
it('does not reopen production controls on completed tasks', async () => {
setup({ ...structuredClone(base), state: 'completed', delivery: { files: [], notes: '完成' } });
await screen.findByRole('button', { name: '询问这块板子' });
expect(screen.queryByRole('button', { name: '生成修订方案' })).toBeNull();
expect(screen.queryByRole('button', { name: '按原方案重试' })).toBeNull();
expect(screen.queryByLabelText('讨论阻碍或提出修改')).toBeNull();
});