加入了一个进度条功能

This commit is contained in:
2026-11-11 11:40:28 +08:00
parent 9090d04e08
commit 980139b25f
5 changed files with 196 additions and 2 deletions
+4 -2
View File
@@ -2,10 +2,11 @@ import { useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import './codex-pcb.css';
import { DeliveryModel3D } from './DeliveryModel3D.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; proposal?: { title: string; markdown: string; revision: number; hash: string }; approval?: { revision: number }; delivery?: { files: Artifact[]; notes: 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';
@@ -64,6 +65,7 @@ export function CodexPcbDock(): JSX.Element {
{!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>
@@ -73,7 +75,7 @@ export function CodexPcbDock(): JSX.Element {
{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}/>}<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>
</main></div></div>
</section>}
</div>;
return createPortal(view, document.body);
+60
View File
@@ -0,0 +1,60 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import { useEffect, useMemo, useState } from 'react';
import {
PAUSED_STATES, PROGRESS_STAGES, elapsedLabel, observedProductionStage,
productionEstimate, progressStage, remainingEstimate,
type ProgressEvent, type ProgressSession,
} from './task-progress.js';
function rememberedStage(id: string): number {
try {
const value = Number(localStorage.getItem(`vibemake.pcb.progress.${id}`));
return Number.isInteger(value) && value >= 2 && value <= 4 ? value : 2;
} catch { return 2; }
}
export function TaskProgress({ task, entries, sessions }: {
task: ProgressSession; entries: readonly ProgressEvent[]; sessions: readonly ProgressSession[];
}) {
const [now, setNow] = useState(() => Date.now() / 1000);
const [remembered, setRemembered] = useState(() => rememberedStage(task.id));
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 completed = task.state === 'completed';
useEffect(() => {
if (completed || paused) return;
const timer = window.setInterval(() => setNow(Date.now() / 1000), 1000);
return () => clearInterval(timer);
}, [completed, paused]);
useEffect(() => {
if (!task.approval || observed <= remembered) return;
setRemembered(observed);
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] || '等待恢复')
: task.state === 'needs_input' ? '等待补充需求' : stage === 1 ? '等待你确认方案' : PROGRESS_STAGES[stage];
const end = completed || paused ? 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} 个已完成设计`
: '确认后将持续绘制至校验交付';
return <section className={`cp-progress${paused || stage === 1 || task.state === 'needs_input' ? ' is-paused' : ''}${completed ? ' is-complete' : ''}`} aria-label="设计任务进度">
<div className="cp-progress-heading">
<div><strong>{current}</strong><span>{completed ? '全部阶段完成' : `阶段 ${stage + 1} / ${PROGRESS_STAGES.length}`}</span></div>
<span className="cp-progress-elapsed">{task.approval ? '制作已用' : '任务已用'} {elapsed}</span>
</div>
<div className="cp-progress-track" role="progressbar" aria-label="设计阶段" aria-valuemin={0} aria-valuemax={5} aria-valuenow={stage} aria-valuetext={completed ? '全部阶段完成' : `${current},阶段 ${stage + 1} / 5`}>
{PROGRESS_STAGES.map((label, index) => <div key={label} className={`cp-progress-step ${index < stage ? 'is-done' : index === stage ? 'is-current' : ''}`} aria-current={index === stage ? 'step' : undefined}>
<div className="cp-progress-segment"><i /></div>
<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>
{!completed && <p className="cp-progress-note">阶段与耗时仅供参考,布局调整和校验修复可能延长制作时间。</p>}
</section>;
}
+2
View File
@@ -3,3 +3,5 @@
.cp-markdown{white-space:normal}.cp-markdown table{border-collapse:collapse;width:100%;margin:16px 0;font-size:13px}.cp-markdown th,.cp-markdown td{border:1px solid #354b61;text-align:left;padding:9px 12px}.cp-markdown th{background:#1b3146}.cp-markdown a{color:#8dd0ff}.cp-markdown code{background:#21354a;border-radius:4px;padding:2px 4px}.cp-markdown pre{white-space:pre-wrap;background:#0c1520;padding:15px;border-radius:8px}.cp-markdown p{margin:12px 0}.cp-markdown li{margin:5px 0}
.cp-model{border:1px solid var(--cp-border);border-radius:12px;overflow:hidden;margin-bottom:24px;background:#142233}.cp-model-header{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:16px 20px}.cp-model-header h3{font-size:17px;margin:0}.cp-model-header p{color:var(--cp-muted);font-size:12px;margin:4px 0 0}.cp-model-header button{flex-shrink:0}.cp-model-stage{position:relative;height:clamp(320px,52vh,600px)}.cp-model-canvas{width:100%;height:100%;background:#101a27}.cp-model-canvas canvas{display:block;touch-action:none}.cp-model-message{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;padding:24px;text-align:center;background:#101a27;color:var(--cp-muted)}.cp-model-footer{display:flex;justify-content:space-between;gap:16px;padding:12px 20px;color:var(--cp-muted);font-size:12px;border-top:1px solid var(--cp-border)}.cp-model-footer span{overflow-wrap:anywhere;min-width:0}.cp-model-footer a{color:var(--cp-blue);white-space:nowrap;text-decoration:none}.cp-model-footer a:hover{text-decoration:underline}@media(max-width:550px){.cp-model-header{padding:12px;flex-wrap:wrap}.cp-model-footer{padding:12px;flex-wrap:wrap}.cp-model-stage{height:340px}}
.cp-content{display:flex;flex-direction:column;flex:1;min-width:0;min-height:0}.cp-progress{flex-shrink:0;padding:18px 34px 14px;border-bottom:1px solid var(--cp-border);background:#142233}.cp-progress-heading,.cp-progress-timing{display:flex;justify-content:space-between;align-items:center;gap:10px;flex-wrap:wrap}.cp-progress-heading strong{color:#b7e2ff;font-size:15px}.cp-progress-heading>div>span{margin-left:12px;color:var(--cp-muted);font-size:12px}.cp-progress-elapsed{font-variant-numeric:tabular-nums;color:var(--cp-muted);font-size:12px}.cp-progress-track{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:8px;margin:14px 0}.cp-progress-segment{height:5px;overflow:hidden;border-radius:4px;background:var(--cp-border);margin-bottom:9px}.cp-progress-segment i{display:block;height:100%;width:0;background:var(--cp-blue);border-radius:inherit}.cp-progress-step.is-done .cp-progress-segment i{width:100%;background:#78d7b1}.cp-progress-step.is-current .cp-progress-segment i{width:45%;animation:cp-pulse 1.8s infinite}.cp-progress-step>span{color:var(--cp-muted);font-size:12px;display:flex;align-items:center;gap:6px}.cp-progress-step b{font-size:11px;font-weight:500;display:inline-flex;justify-content:center;align-items:center;width:18px;height:18px;border:1px solid var(--cp-border);border-radius:50%;flex-shrink:0}.cp-progress-step.is-done>span{color:#a3dfc5}.cp-progress-step.is-current>span{color:#c7eaff;font-weight:600}.cp-progress-step.is-current b{border-color:var(--cp-blue);color:var(--cp-blue)}.cp-progress-timing strong{font-size:13px;font-weight:500;color:#c7eaff}.cp-progress-timing>span{font-size:11px;color:var(--cp-muted)}.cp-progress-note{font-size:11px;margin:7px 0 0;color:var(--cp-muted)}.cp-progress.is-paused .is-current .cp-progress-segment i{animation:none;background:#e4b875}.cp-progress.is-paused .cp-progress-heading strong{color:#e4b875}.cp-progress.is-complete .cp-progress-heading strong{color:#a3dfc5}@media(max-width:850px){.cp-progress{padding:14px 18px 12px}.cp-progress-track{gap:5px}.cp-progress-step>span{font-size:11px;gap:4px}}@media(max-width:550px){.cp-progress{padding:12px}.cp-progress-heading>div>span{margin-left:7px}.cp-progress-track{margin:10px 0}.cp-progress-step>span{flex-direction:column;align-items:flex-start;gap:4px}.cp-progress-note{font-size:10px}}@media(prefers-reduced-motion:reduce){.cp-progress-step.is-current .cp-progress-segment i{animation:none}}
+73
View File
@@ -0,0 +1,73 @@
// SPDX-License-Identifier: GPL-3.0-or-later
export interface ProgressSession {
id: string;
state: string;
busy: boolean;
created_at: number;
updated_at?: number;
approval?: { at?: number };
proposal?: { at?: number };
}
export interface ProgressEvent {
type: string;
at: number;
data: Record<string, unknown>;
}
export const PROGRESS_STAGES = ['生成方案', '确认方案', '绘制原理图', 'PCB Layout', '校验与交付'] as const;
export const PAUSED_STATES = new Set(['blocked', 'failed', 'interrupted', 'cancelled']);
/** Only actual tool activity counts; proposals and chat may describe future work. */
export function observedProductionStage(events: readonly ProgressEvent[]): number {
let stage = 2;
for (const event of events) {
if (event.type === 'tool.started' && event.data.tool === 'pcb_deliver') stage = 4;
if (event.type !== 'eda.started' || typeof event.data.label !== 'string') continue;
const label = event.data.label;
if (/independent native delivery verification|(?:最终|交付).*(?:导出|打包|渲染)|(?:导出|保存|打包|渲染).*(?:最终|交付)|\b(?:final|delivery)\b.*\b(?:export|render|packag|bundle|verification)\w*|\b(?:export|render|package)\w*\b.*\b(?:final|delivery)\b/i.test(label)) stage = 4;
else if (/\b(?:pcb|layout|routing|route|placement|dsn|ses|copper)\b|\b(?:place|placing)\b.*\bboard\b|布局|布线|走线|焊盘|覆铜|板框|铜层|铺铜/i.test(label)) stage = Math.max(stage, 3);
}
return stage;
}
/** Stage milestones never advance merely because time passes. */
export function progressStage(task: ProgressSession, observed: number, remembered = 2): number {
if (task.state === 'completed') return 5;
if (!task.approval) return task.state === 'review' ? 1 : 0;
return Math.min(4, Math.max(2, observed, remembered));
}
export interface DurationEstimate { low: number; high: number; samples: number }
/** 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')
.map(task => task.approval?.at && task.updated_at ? task.updated_at - task.approval.at : 0)
.filter(value => Number.isFinite(value) && value > 0);
if (!durations.length) return null;
const low = Math.min(...durations), high = Math.max(...durations);
// A single observation is not a precise prediction; give it a wider band.
const lower = durations.length === 1 ? low * 0.75 : low;
const upper = durations.length === 1 ? high * 1.5 : high;
return { low: Math.max(60, Math.floor(lower / 300) * 300), high: Math.max(300, Math.ceil(upper / 300) * 300), samples: durations.length };
}
export function elapsedLabel(seconds: number): string {
const minutes = Math.max(0, Math.floor(seconds / 60));
if (!minutes) return '不到 1 分钟';
return minutes < 60 ? `${minutes} 分钟` : `${Math.floor(minutes / 60)} 小时${minutes % 60 ? ` ${minutes % 60} 分钟` : ''}`;
}
export function remainingEstimate(task: ProgressSession, estimate: DurationEstimate | null, now: number): string {
if (task.state === 'completed') return '交付文件已就绪';
if (PAUSED_STATES.has(task.state)) return '恢复运行后再估算剩余时间';
if (task.state === 'needs_input') return '等待你补充需求后继续生成方案';
if (!task.approval) return task.state === 'review'
? '等待你确认方案后开始绘制,等待时间不计入制作预估'
: '正在研究需求与生成方案,确认方案后开始计算制作时间';
if (!estimate || !task.approval.at) return '历史样本不足,暂无法估算剩余时间';
const elapsed = Math.max(0, now - task.approval.at);
if (elapsed >= estimate.high) return '已超出历史耗时参考,仍在继续处理';
const lower = Math.max(1, Math.ceil((estimate.low - elapsed) / 60));
const upper = Math.max(lower, Math.ceil((estimate.high - elapsed) / 60));
return `预计还需约 ${lower === upper ? upper : `${lower}–${upper}`} 分钟`;
}
@@ -0,0 +1,57 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import { describe, expect, it } from 'vitest';
import { observedProductionStage, progressStage, productionEstimate, remainingEstimate, type ProgressSession } from '../../../designer/src/codex-pcb/task-progress.js';
const running: ProgressSession = { id: 'running', state: 'running', busy: true, created_at: 100, approval: { at: 1000 } };
const event = (label: string) => ({ type: 'eda.started', at: 1100, data: { label } });
describe('PCB task progress from observed work', () => {
it('does not interpret future work in proposals or chat as completed milestones', () => {
expect(observedProductionStage([{ type: 'message', at: 101, data: { text: '接下来完成 layout、导出最终STEP与交付' } }])).toBe(2);
expect(progressStage({ ...running, approval: undefined, state: 'planning' }, 4, 4)).toBe(0);
expect(progressStage({ ...running, approval: undefined, state: 'review' }, 4)).toBe(1);
expect(progressStage({ ...running, approval: undefined, state: 'needs_input' }, 4)).toBe(0);
});
it('recognizes Chinese and English layout work but not early schematic/library setup', () => {
expect(observedProductionStage([event('select exact BOM and initialize schematic')])).toBe(2);
expect(observedProductionStage([event('read footprint library identities')])).toBe(2);
expect(observedProductionStage([event('place board components with bottom male headers'), event('inspect placement after outline API error')])).toBe(3);
expect(observedProductionStage([event('完成55×28mm原生板框与器件布局')])).toBe(3);
});
it('does not mistake intermediate STEP export for final delivery', () => {
expect(observedProductionStage([event('导出装配几何与工程BOM')])).toBe(2);
expect(observedProductionStage([event('导出最终装配几何')])).toBe(4);
expect(observedProductionStage([event('Independent native delivery verification')])).toBe(4);
});
it('retains reached milestones through repairs and truncated event windows', () => {
expect(observedProductionStage([event('导出最终原理图'), event('修正原理图网络标签')])).toBe(4);
expect(progressStage(running, 2, 3)).toBe(3);
expect(progressStage({ ...running, state: 'failed' }, 4)).toBe(4);
expect(progressStage({ ...running, state: 'completed' }, 2)).toBe(5);
});
it('does not mark delivery completed just because the agent called the delivery tool', () => {
expect(progressStage(running, observedProductionStage([{ type: 'tool.started', at: 1200, data: { tool: 'pcb_deliver' } }]))).toBe(4);
});
});
describe('PCB duration reference', () => {
const history: ProgressSession[] = [
{ id: 'a', state: 'completed', busy: false, created_at: 1, approval: { at: 20000 }, updated_at: 24300 },
{ id: 'b', state: 'completed', busy: false, created_at: 1, approval: { at: 40000 }, updated_at: 49200 },
];
it('uses completed production only, excluding review delay, active jobs and this job', () => {
expect(productionEstimate([...history, running, { ...history[0]!, id: 'bad', updated_at: 5 }], 'running')).toEqual({ low: 4200, high: 9300, samples: 2 });
expect(productionEstimate(history, 'a')?.samples).toBe(1);
expect(productionEstimate([running], 'running')).toBeNull();
});
it('pauses the forecast for review/failure and never counts down past zero', () => {
const estimate = { low: 4200, high: 9300, samples: 2 };
expect(remainingEstimate(running, estimate, 1600)).toBe('预计还需约 60–145 分钟');
expect(remainingEstimate(running, estimate, 11000)).toContain('已超出历史耗时参考');
expect(remainingEstimate({ ...running, state: 'review', approval: undefined }, estimate, 11000)).toContain('等待你确认方案');
expect(remainingEstimate({ ...running, state: 'needs_input', approval: undefined }, estimate, 11000)).toContain('补充需求');
expect(remainingEstimate({ ...running, state: 'failed' }, estimate, 11000)).toContain('恢复运行后');
expect(remainingEstimate({ ...running, state: 'completed' }, estimate, 11000)).toBe('交付文件已就绪');
expect(remainingEstimate(running, null, 1600)).toContain('历史样本不足');
});
});