661 lines
24 KiB
TypeScript
661 lines
24 KiB
TypeScript
// SPDX-License-Identifier: GPL-3.0-or-later
|
||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||
import { createPortal } from 'react-dom';
|
||
import {
|
||
ApiError,
|
||
artifactUrl,
|
||
base,
|
||
canAccept,
|
||
command,
|
||
request,
|
||
requestId,
|
||
stateLabel,
|
||
terminal,
|
||
type Artifact,
|
||
type Operation,
|
||
type Progress,
|
||
type Task,
|
||
} from './client.js';
|
||
import './pcb-service.css';
|
||
|
||
const ACTIVE = 'vibemake.pcb-service.active',
|
||
PENDING = 'vibemake.pcb-service.operation';
|
||
const OUTBOX = 'vibemake.pcb-service.outbox';
|
||
type Queued = { action: string; payload: Record<string, unknown>; request_id: string };
|
||
function queuedCommand(): Queued | null {
|
||
try {
|
||
return JSON.parse(stored(OUTBOX) || 'null');
|
||
} catch {
|
||
return null;
|
||
}
|
||
}
|
||
function stored(key: string) {
|
||
try {
|
||
return localStorage.getItem(key);
|
||
} catch {
|
||
return null;
|
||
}
|
||
}
|
||
function remember(key: string, value: string | null) {
|
||
try {
|
||
if (value) localStorage.setItem(key, value);
|
||
else localStorage.removeItem(key);
|
||
} catch {
|
||
/* Server history remains authoritative. */
|
||
}
|
||
}
|
||
const eventNames: Record<string, string> = {
|
||
'agent.started': '模型开始处理',
|
||
'agent.completed': '模型完成当前步骤',
|
||
'design.round': '设计检查点',
|
||
'design.fallback_started': '执行固定绘图流程',
|
||
'schematic.wiring_verified': '引脚连接已核对',
|
||
'pcb.component_created': '导入 PCB 器件',
|
||
'pcb.placement_completed': '完成布局',
|
||
'pcb.routing_progress': '正在布线',
|
||
'delivery.ready': '检查通过,成果已打包',
|
||
'delivery.draft': '草稿已保存',
|
||
'manufacturing.released': 'PCB 交付包已开放下载',
|
||
'auto.recover': '正在自动恢复',
|
||
'operation.finished': '本次操作结束',
|
||
};
|
||
const kindNames: Record<string, string> = {
|
||
native: '可编辑原生工程',
|
||
editor_native: '编辑器兼容工程',
|
||
schematic: '原理图',
|
||
schematic_vector: '矢量原理图',
|
||
pcb: 'PCB 图纸',
|
||
pcb_preview: 'PCB 预览',
|
||
render: '三维渲染',
|
||
bom: 'BOM 物料表',
|
||
model: '三维模型',
|
||
manufacturing_package: 'PCB 交付包',
|
||
review_package: '检查与成果压缩包',
|
||
fabrication_info: '工艺信息',
|
||
};
|
||
|
||
export function PcbServiceDock({
|
||
onImport,
|
||
}: {
|
||
onImport: (bytes: Uint8Array, task: Task) => Promise<void>;
|
||
}) {
|
||
const [open, setOpen] = useState(true),
|
||
[tasks, setTasks] = useState<Task[]>([]),
|
||
[id, setId] = useState<string | null>(() => stored(ACTIVE));
|
||
const [queued, setQueued] = useState<Queued | null>(queuedCommand);
|
||
const [task, setTask] = useState<Task | null>(null),
|
||
[pending, setPending] = useState<string | null>(() => stored(PENDING)),
|
||
[events, setEvents] = useState<Progress[]>([]);
|
||
const [connected, setConnected] = useState(false),
|
||
[error, setError] = useState(''),
|
||
[text, setText] = useState(''),
|
||
[answer, setAnswer] = useState(''),
|
||
[sending, setSending] = useState(false);
|
||
const [attachments, setAttachments] = useState<{ upload_id: string; name: string }[]>([]),
|
||
[uploading, setUploading] = useState(false);
|
||
const [preview, setPreview] = useState<Artifact | null>(null),
|
||
[bom, setBom] = useState<{ columns: string[]; rows: string[][] } | null>(null);
|
||
const idRef = useRef(id),
|
||
downloadFor = useRef<string | null>(null),
|
||
cursor = useRef(0),
|
||
fileRef = useRef<HTMLInputElement>(null);
|
||
idRef.current = id;
|
||
const refresh = useCallback(async () => {
|
||
const data = await request<{ items: Task[] }>('/tasks');
|
||
setTasks(data.items);
|
||
setConnected(true);
|
||
}, []);
|
||
useEffect(() => {
|
||
let alive = true;
|
||
void request('/session')
|
||
.then(() => refresh())
|
||
.catch(() => {
|
||
if (alive) {
|
||
setConnected(false);
|
||
setError('暂时无法连接 PCB 后台。请检查启动终端中的 PCB_API_TARGET 配置。');
|
||
}
|
||
});
|
||
return () => {
|
||
alive = false;
|
||
};
|
||
}, [refresh]);
|
||
useEffect(() => {
|
||
remember(ACTIVE, id);
|
||
setTask(null);
|
||
setEvents([]);
|
||
setPreview(null);
|
||
setBom(null);
|
||
cursor.current = 0;
|
||
if (!id) return;
|
||
let alive = true;
|
||
const poll = async () => {
|
||
try {
|
||
const t = await request<Task>('/tasks/' + encodeURIComponent(id));
|
||
if (alive) {
|
||
setTask(t);
|
||
setConnected(true);
|
||
}
|
||
} catch (e) {
|
||
if (alive) {
|
||
if (e instanceof ApiError && e.status === 404) {
|
||
remember(ACTIVE, null);
|
||
setId(null);
|
||
setConnected(true);
|
||
setError('先前任务记录已清理,可以新建设计。');
|
||
} else {
|
||
setConnected(false);
|
||
setError((e as Error).message);
|
||
}
|
||
}
|
||
}
|
||
};
|
||
void poll();
|
||
const timer = setInterval(() => void poll(), 5000);
|
||
return () => {
|
||
alive = false;
|
||
clearInterval(timer);
|
||
};
|
||
}, [id]);
|
||
useEffect(() => {
|
||
if (!id) return;
|
||
let stopped = false,
|
||
source: EventSource | null = null,
|
||
timer: ReturnType<typeof setTimeout> | undefined;
|
||
const connect = () => {
|
||
source = new EventSource(
|
||
`${base}/events?task_id=${encodeURIComponent(id)}&after=${cursor.current}`,
|
||
);
|
||
source.addEventListener('progress', (event) => {
|
||
try {
|
||
const e = JSON.parse((event as MessageEvent).data) as Progress;
|
||
cursor.current = e.seq;
|
||
setEvents((old) => [...old.filter((x) => x.seq !== e.seq), e].slice(-80));
|
||
} catch {
|
||
/* A later snapshot restores the state. */
|
||
}
|
||
});
|
||
source.onerror = () => {
|
||
source?.close();
|
||
if (!stopped)
|
||
timer = setTimeout(() => {
|
||
void request('/session')
|
||
.then(() => {
|
||
if (!stopped) connect();
|
||
})
|
||
.catch(() => {
|
||
if (!stopped) timer = setTimeout(connect, 5000);
|
||
});
|
||
}, 3000);
|
||
};
|
||
};
|
||
connect();
|
||
return () => {
|
||
stopped = true;
|
||
source?.close();
|
||
if (timer) clearTimeout(timer);
|
||
};
|
||
}, [id]);
|
||
useEffect(() => {
|
||
remember(PENDING, pending);
|
||
if (!pending) return;
|
||
let stopped = false;
|
||
const poll = async () => {
|
||
try {
|
||
const op = await request<Operation>('/operations/' + encodeURIComponent(pending));
|
||
if (stopped) return;
|
||
if (op.task_id && !idRef.current) setId(op.task_id);
|
||
if (!['queued', 'running'].includes(op.state)) {
|
||
setPending(null);
|
||
await refresh();
|
||
if (op.result?.task_id) {
|
||
if (idRef.current === op.result.task_id || !idRef.current) {
|
||
setId(op.result.task_id);
|
||
setTask(op.result);
|
||
}
|
||
if (
|
||
downloadFor.current === op.result.task_id &&
|
||
op.result.state === 'completed' &&
|
||
op.result.manufacturing_package
|
||
) {
|
||
downloadFor.current = null;
|
||
const a = document.createElement('a');
|
||
a.href = artifactUrl(op.result.manufacturing_package);
|
||
a.download = op.result.manufacturing_package.name;
|
||
document.body.appendChild(a);
|
||
a.click();
|
||
a.remove();
|
||
}
|
||
}
|
||
if (
|
||
op.state === 'failed' ||
|
||
op.state === 'outcome_unknown' ||
|
||
(op.result?.error && op.result.state !== 'failed')
|
||
)
|
||
setError(
|
||
op.result?.message || op.result?.error || '操作结果尚未确认,请查看任务状态。',
|
||
);
|
||
}
|
||
} catch (e) {
|
||
if (!stopped) {
|
||
if (e instanceof ApiError && e.status === 404) {
|
||
remember(PENDING, null);
|
||
setPending(null);
|
||
setConnected(true);
|
||
setError('先前操作记录已清理,可以新建设计。');
|
||
} else setError((e as Error).message);
|
||
}
|
||
}
|
||
};
|
||
void poll();
|
||
const timer = setInterval(() => void poll(), 1500);
|
||
return () => {
|
||
stopped = true;
|
||
clearInterval(timer);
|
||
};
|
||
}, [pending, refresh]);
|
||
useEffect(() => {
|
||
if (!queued) return;
|
||
let stopped = false;
|
||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||
const send = async () => {
|
||
try {
|
||
const op = await command(queued.action, queued.payload, queued.request_id);
|
||
if (stopped) return;
|
||
remember(PENDING, op.operation_id);
|
||
setPending(op.operation_id);
|
||
if (op.task_id) setId(op.task_id);
|
||
remember(OUTBOX, null);
|
||
setQueued(null);
|
||
setError('');
|
||
} catch (e) {
|
||
if (stopped) return;
|
||
setError(`请求尚未确认,正在用同一请求身份重连:${(e as Error).message}`);
|
||
timer = setTimeout(() => void send(), 5000);
|
||
}
|
||
};
|
||
void send();
|
||
return () => {
|
||
stopped = true;
|
||
if (timer) clearTimeout(timer);
|
||
};
|
||
}, [queued]);
|
||
const invoke = async (action: string, payload: Record<string, unknown>) => {
|
||
if (sending || pending || queued) return;
|
||
const next = { action, payload, request_id: requestId() };
|
||
remember(OUTBOX, JSON.stringify(next));
|
||
setQueued(next);
|
||
setError('');
|
||
};
|
||
const upload = async (files: FileList | null) => {
|
||
if (!files) return;
|
||
setUploading(true);
|
||
setError('');
|
||
try {
|
||
for (const f of files) {
|
||
const form = new FormData();
|
||
form.append('file', f);
|
||
form.append(
|
||
'kind',
|
||
/\.(png|jpe?g|dxf|step|stp)$/i.test(f.name) ? 'mechanical' : 'datasheet',
|
||
);
|
||
const a = await request<{ upload_id: string; name: string }>('/uploads', {
|
||
method: 'POST',
|
||
body: form,
|
||
});
|
||
setAttachments((old) => [...old, a]);
|
||
}
|
||
} catch (e) {
|
||
setError((e as Error).message);
|
||
} finally {
|
||
setUploading(false);
|
||
if (fileRef.current) fileRef.current.value = '';
|
||
}
|
||
};
|
||
const importCopy = async (a: Artifact) => {
|
||
if (!task) return;
|
||
setSending(true);
|
||
setError('');
|
||
try {
|
||
const response = await fetch(artifactUrl(a), { credentials: 'same-origin' });
|
||
if (!response.ok) throw Error('工程下载失败,请重连后重试');
|
||
const bytes = new Uint8Array(await response.arrayBuffer());
|
||
const digest = Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)))
|
||
.map((v) => v.toString(16).padStart(2, '0'))
|
||
.join('');
|
||
if (digest !== a.sha256) throw Error('工程摘要不匹配,拒绝导入');
|
||
await onImport(bytes, task);
|
||
setOpen(false);
|
||
} catch (e) {
|
||
setError((e as Error).message);
|
||
} finally {
|
||
setSending(false);
|
||
}
|
||
};
|
||
const show = async (a: Artifact) => {
|
||
setPreview(a);
|
||
setBom(null);
|
||
if (a.kind === 'bom' && task)
|
||
try {
|
||
setBom(await request(`/tasks/${task.task_id}/artifacts/${a.artifact_id}/table`));
|
||
} catch (e) {
|
||
setError((e as Error).message);
|
||
}
|
||
};
|
||
const artifacts = task?.delivery?.artifacts ?? [],
|
||
busy = sending || !!pending || !!queued;
|
||
return createPortal(
|
||
<div className="ze-app pcb-service-root">
|
||
<button className="pcb-service-launch" onClick={() => setOpen((v) => !v)}>
|
||
AI 自动绘板
|
||
</button>
|
||
{open && (
|
||
<section className="pcb-service-window" role="dialog" aria-label="AI PCB 设计工作台">
|
||
<header>
|
||
<div>
|
||
<strong>AI PCB 设计工作台</strong>
|
||
<small>
|
||
{connected ? '已连接服务端 · 后台生成' : '连接后台中'} · 关闭此窗口不会取消任务
|
||
</small>
|
||
</div>
|
||
<button aria-label="关闭 PCB 工作台" onClick={() => setOpen(false)}>
|
||
关闭
|
||
</button>
|
||
</header>
|
||
<div className="pcb-service-body">
|
||
<aside>
|
||
<button
|
||
disabled={busy}
|
||
onClick={() => {
|
||
setId(null);
|
||
setTask(null);
|
||
setError('');
|
||
setAttachments([]);
|
||
}}
|
||
>
|
||
+ 新建设计
|
||
</button>
|
||
<button onClick={() => void refresh().catch((e) => setError(String(e)))}>
|
||
刷新任务列表
|
||
</button>
|
||
{tasks.map((t) => (
|
||
<button
|
||
className={t.task_id === id ? 'selected' : ''}
|
||
key={t.task_id}
|
||
onClick={() => setId(t.task_id)}
|
||
>
|
||
<strong>{t.title || t.task_id}</strong>
|
||
<small>
|
||
{stateLabel[t.state] || t.state} · {t.revision || 'RevA'}
|
||
</small>
|
||
</button>
|
||
))}
|
||
</aside>
|
||
<main>
|
||
{error && (
|
||
<div role="alert" className="pcb-service-warning">
|
||
{error}
|
||
</div>
|
||
)}
|
||
{!id ? (
|
||
<>
|
||
<h2>描述你需要的 PCB</h2>
|
||
<p>需求明确并选定方案后,设计由服务器继续执行。服务器需保持联网。</p>
|
||
<textarea
|
||
aria-label="PCB 设计需求"
|
||
value={text}
|
||
onChange={(e) => setText(e.target.value)}
|
||
placeholder="例如:12V 转 5V、输出 1A 的电源板,40×30mm,无安装孔,两个电源接口。"
|
||
/>
|
||
<input
|
||
ref={fileRef}
|
||
type="file"
|
||
multiple
|
||
hidden
|
||
onChange={(e) => void upload(e.target.files)}
|
||
/>
|
||
<div className="pcb-service-actions">
|
||
<button disabled={uploading || busy} onClick={() => fileRef.current?.click()}>
|
||
{uploading ? '上传中…' : '添加手册或图片'}
|
||
</button>
|
||
<button
|
||
disabled={!text.trim() || busy || uploading || !connected}
|
||
onClick={() =>
|
||
void invoke('create', {
|
||
description: text,
|
||
selection_policy: 'propose',
|
||
attachments: attachments.map((a) => ({ upload_id: a.upload_id })),
|
||
})
|
||
}
|
||
>
|
||
开始分析
|
||
</button>
|
||
</div>
|
||
{attachments.map((a) => (
|
||
<span className="pcb-service-attachment" key={a.upload_id}>
|
||
{a.name}
|
||
<button onClick={() => setAttachments((old) => old.filter((v) => v !== a))}>
|
||
移除
|
||
</button>
|
||
</span>
|
||
))}
|
||
</>
|
||
) : !task ? (
|
||
<p>正在读取任务…</p>
|
||
) : (
|
||
<>
|
||
<h2>{task.title || 'PCB 设计任务'}</h2>
|
||
<p>
|
||
<strong>{stateLabel[task.state] || task.state}</strong> · {task.revision} ·{' '}
|
||
<code>{task.task_id}</code>
|
||
</p>
|
||
{task.simulation && (
|
||
<p className="pcb-service-warning">模拟环境:文件不能用于制造。</p>
|
||
)}
|
||
{task.state === 'needs_input' && (
|
||
<>
|
||
<ul>
|
||
{task.questions?.map((q) => (
|
||
<li key={q}>{q}</li>
|
||
))}
|
||
</ul>
|
||
<textarea
|
||
aria-label="补充需求"
|
||
value={answer}
|
||
onChange={(e) => setAnswer(e.target.value)}
|
||
/>
|
||
<button
|
||
disabled={!answer.trim() || busy}
|
||
onClick={() => {
|
||
void invoke('message', { task_id: id, text: answer });
|
||
setAnswer('');
|
||
}}
|
||
>
|
||
提交补充
|
||
</button>
|
||
</>
|
||
)}
|
||
{task.state === 'awaiting_selection' &&
|
||
task.proposal?.options.map((o) => (
|
||
<article key={o.id}>
|
||
<h3>{o.summary}</h3>
|
||
<p>{o.implementation}</p>
|
||
<ul>
|
||
{o.advantages.map((v) => (
|
||
<li key={v}>{v}</li>
|
||
))}
|
||
</ul>
|
||
<p>{o.disadvantages.join(';')}</p>
|
||
<button
|
||
disabled={busy}
|
||
onClick={() =>
|
||
void invoke('select', {
|
||
task_id: id,
|
||
proposal_hash: task.proposal_hash,
|
||
option_id: o.id,
|
||
})
|
||
}
|
||
>
|
||
采用这个方案
|
||
</button>
|
||
</article>
|
||
))}
|
||
{!terminal.has(task.state) && (
|
||
<p>服务器正在执行,可稍后重新打开查看。中途异常由服务端核对恢复。</p>
|
||
)}
|
||
{task.state === 'failed' && (
|
||
<p className="pcb-service-warning">
|
||
服务未能完成本次设计,已保留执行记录。
|
||
{task.error && (
|
||
<details>
|
||
<summary>查看诊断</summary>
|
||
{task.error}
|
||
</details>
|
||
)}
|
||
</p>
|
||
)}
|
||
{(task.state === 'draft_ready' || !!task.manufacturing_blockers?.length) && (
|
||
<div className="pcb-service-warning">
|
||
<strong>当前结果为草稿,不能作为检查通过的制造文件。</strong>
|
||
<ul>
|
||
{task.manufacturing_blockers?.map((v) => (
|
||
<li key={v}>{v}</li>
|
||
))}
|
||
</ul>
|
||
</div>
|
||
)}
|
||
{canAccept(task) && (
|
||
<article>
|
||
<h3>检查已通过,审核后即可下载 PCB</h3>
|
||
<p>
|
||
交付包已在服务端准备好,包含原生工程、Gerber、钻孔、BOM
|
||
和检查记录。软件检查不代替实板功能验证。
|
||
</p>
|
||
<button
|
||
disabled={busy}
|
||
onClick={() => {
|
||
downloadFor.current = id;
|
||
void invoke('accept', {
|
||
task_id: id,
|
||
manifest_sha256: task.delivery!.manifest_sha256,
|
||
accepted: true,
|
||
});
|
||
}}
|
||
>
|
||
审核通过并下载 PCB
|
||
</button>
|
||
</article>
|
||
)}
|
||
{task.state === 'completed' && task.manufacturing_package && (
|
||
<a
|
||
className="pcb-service-download"
|
||
href={artifactUrl(task.manufacturing_package)}
|
||
>
|
||
下载 PCB 交付包
|
||
</a>
|
||
)}
|
||
{artifacts.length > 0 && (
|
||
<>
|
||
<h3>设计成果</h3>
|
||
<div className="pcb-service-gallery">
|
||
{artifacts
|
||
.filter(
|
||
(a) =>
|
||
['pcb_preview', 'render', 'schematic'].includes(a.kind) &&
|
||
a.mime_type.startsWith('image/'),
|
||
)
|
||
.map((a) => (
|
||
<button key={a.artifact_id} onClick={() => void show(a)}>
|
||
<img src={artifactUrl(a, true)} alt={kindNames[a.kind] || a.name} />
|
||
{kindNames[a.kind] || a.kind}
|
||
</button>
|
||
))}
|
||
</div>
|
||
<p>
|
||
原生工程由后台 EDA 生成;兼容 epro
|
||
工程可导入为新的编辑副本;原制造检查不适用于转换或修改后的副本。
|
||
</p>
|
||
{artifacts.find((a) => a.kind === 'editor_native') && (
|
||
<button
|
||
disabled={busy}
|
||
onClick={() =>
|
||
void importCopy(artifacts.find((a) => a.kind === 'editor_native')!)
|
||
}
|
||
>
|
||
导入编辑器副本(需重新校验)
|
||
</button>
|
||
)}
|
||
{artifacts.map((a) => (
|
||
<div className="pcb-service-artifact" key={a.artifact_id}>
|
||
<span>
|
||
{kindNames[a.kind] || a.kind} · {a.name}
|
||
</span>
|
||
<button onClick={() => void show(a)}>查看</button>
|
||
<a href={artifactUrl(a)}>下载</a>
|
||
</div>
|
||
))}
|
||
</>
|
||
)}
|
||
{events.length > 0 && (
|
||
<details open>
|
||
<summary>执行记录</summary>
|
||
<ol>
|
||
{events.slice(-16).map((e) => (
|
||
<li key={e.seq}>
|
||
<time>{new Date(e.created * 1000).toLocaleTimeString()}</time>{' '}
|
||
{e.data.message || eventNames[e.kind] || e.kind}
|
||
</li>
|
||
))}
|
||
</ol>
|
||
</details>
|
||
)}
|
||
{!terminal.has(task.state) && (
|
||
<button disabled={busy} onClick={() => void invoke('cancel', { task_id: id })}>
|
||
取消此任务
|
||
</button>
|
||
)}
|
||
</>
|
||
)}
|
||
{preview && (
|
||
<section className="pcb-service-preview">
|
||
<button onClick={() => setPreview(null)}>关闭预览</button>
|
||
<h3>{kindNames[preview.kind] || preview.name}</h3>
|
||
{bom ? (
|
||
<div className="pcb-service-table">
|
||
<table>
|
||
<thead>
|
||
<tr>
|
||
{bom.columns.map((v, i) => (
|
||
<th key={i}>{v}</th>
|
||
))}
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
{bom.rows.map((r, i) => (
|
||
<tr key={i}>
|
||
{r.map((v, j) => (
|
||
<td key={j}>{v}</td>
|
||
))}
|
||
</tr>
|
||
))}
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
) : preview.mime_type.startsWith('image/') ? (
|
||
<img src={artifactUrl(preview, true)} alt={preview.name} />
|
||
) : preview.mime_type === 'application/pdf' ? (
|
||
<iframe title={preview.name} src={artifactUrl(preview, true)} />
|
||
) : (
|
||
<p>该格式请下载后使用对应 EDA 软件打开。</p>
|
||
)}
|
||
<a href={artifactUrl(preview)}>下载文件</a>
|
||
</section>
|
||
)}
|
||
</main>
|
||
</div>
|
||
</section>
|
||
)}
|
||
</div>,
|
||
document.body,
|
||
);
|
||
}
|