@huaqiu/dsh-tool-kicad-schematic-gen 0.7.3 → 0.7.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/client.js +221 -4
- package/package.json +3 -3
- package/src/client/index.ts +51 -4
- package/src/client/open-in-eda.ts +137 -0
package/lib/client.js
CHANGED
|
@@ -1075,6 +1075,117 @@
|
|
|
1075
1075
|
};
|
|
1076
1076
|
}
|
|
1077
1077
|
//#endregion
|
|
1078
|
+
//#region src/client/open-in-eda.ts
|
|
1079
|
+
const IMPORT_PATH = "/api/v1/import/kicad-b64";
|
|
1080
|
+
const DIRECTORY_PATH = "/api/v1/import/directory";
|
|
1081
|
+
/** Only our own immutable snapshots may be uploaded — never an arbitrary URL. */
|
|
1082
|
+
const SNAPSHOT = /^\/api\/v1\/kicad-schematic-overview\/[0-9a-f-]{36}\/project\.zip$/;
|
|
1083
|
+
/** Mark the upload as a generated (not human-authored) design. */
|
|
1084
|
+
const SOURCE_VENDOR = "circuit_agent";
|
|
1085
|
+
const SOURCE_FORMAT = "kicad";
|
|
1086
|
+
const MAX_BYTES = 67108864;
|
|
1087
|
+
/** The host, when it can carry a request; undefined keeps the action hidden. */
|
|
1088
|
+
function importingHost(get) {
|
|
1089
|
+
try {
|
|
1090
|
+
const host = get?.();
|
|
1091
|
+
return host?.api?.request ? { api: host.api } : null;
|
|
1092
|
+
} catch {
|
|
1093
|
+
return null;
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
/**
|
|
1097
|
+
* Base64 in bounded chunks: `String.fromCharCode(...bytes)` on a 64 MiB
|
|
1098
|
+
* snapshot overflows the call stack, and a per-byte loop is needlessly slow.
|
|
1099
|
+
*/
|
|
1100
|
+
function toBase64(bytes) {
|
|
1101
|
+
let binary = "";
|
|
1102
|
+
for (let i = 0; i < bytes.length; i += 32768) binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
|
|
1103
|
+
return btoa(binary);
|
|
1104
|
+
}
|
|
1105
|
+
/**
|
|
1106
|
+
* Upload `downloadUrl`'s snapshot and open it in KiCad.
|
|
1107
|
+
*
|
|
1108
|
+
* `sessionId` is the conversation that produced the design: HQ Edge forks it
|
|
1109
|
+
* into the new project's workspace before the project is announced, so the AI
|
|
1110
|
+
* panel there opens on the design discussion instead of a blank chat.
|
|
1111
|
+
*/
|
|
1112
|
+
async function openInKiCad(host, options, request = fetch) {
|
|
1113
|
+
if (!SNAPSHOT.test(options.downloadUrl)) throw new Error("无效的工程快照地址。");
|
|
1114
|
+
let bytes;
|
|
1115
|
+
try {
|
|
1116
|
+
const response = await request(options.downloadUrl);
|
|
1117
|
+
if (!response.ok) throw new Error(String(response.status));
|
|
1118
|
+
const buffer = await response.arrayBuffer();
|
|
1119
|
+
if (buffer.byteLength === 0) throw new Error("empty snapshot");
|
|
1120
|
+
if (buffer.byteLength > MAX_BYTES) throw new Error("snapshot too large");
|
|
1121
|
+
bytes = new Uint8Array(buffer);
|
|
1122
|
+
} catch (error) {
|
|
1123
|
+
throw new Error(`工程快照不可用,请重新生成后再打开(${message(error)})。`);
|
|
1124
|
+
}
|
|
1125
|
+
const sessionId = options.sessionId?.trim() ?? "";
|
|
1126
|
+
const payload = {
|
|
1127
|
+
zip_b64: toBase64(bytes),
|
|
1128
|
+
filename: `${options.projectName || "design"}.zip`,
|
|
1129
|
+
project_name: options.projectName || "design",
|
|
1130
|
+
source_vendor: SOURCE_VENDOR,
|
|
1131
|
+
source_format: SOURCE_FORMAT
|
|
1132
|
+
};
|
|
1133
|
+
if (sessionId.length > 0) payload.session_id = sessionId;
|
|
1134
|
+
let response;
|
|
1135
|
+
try {
|
|
1136
|
+
response = await host.api.request({
|
|
1137
|
+
method: "POST",
|
|
1138
|
+
path: IMPORT_PATH,
|
|
1139
|
+
body: payload
|
|
1140
|
+
});
|
|
1141
|
+
} catch (error) {
|
|
1142
|
+
throw new Error(`打开失败:HQ Edge 未响应(${message(error)})。`);
|
|
1143
|
+
}
|
|
1144
|
+
const body = response ?? {};
|
|
1145
|
+
if (typeof body.project_dir !== "string" || body.project_dir.length === 0) throw new Error(`打开失败:${describe(body)}`);
|
|
1146
|
+
return {
|
|
1147
|
+
projectDir: body.project_dir,
|
|
1148
|
+
projectName: typeof body.project_name === "string" && body.project_name.length > 0 ? body.project_name : options.projectName,
|
|
1149
|
+
sessionForked: body.session_forked === true,
|
|
1150
|
+
projectsDir: typeof body.projects_dir === "string" && body.projects_dir.length > 0 ? body.projects_dir : void 0
|
|
1151
|
+
};
|
|
1152
|
+
}
|
|
1153
|
+
/** Where the NEXT project will be placed (and what the default would be). */
|
|
1154
|
+
async function readProjectsDirectory(host) {
|
|
1155
|
+
return directoryOf(await host.api.request({
|
|
1156
|
+
method: "GET",
|
|
1157
|
+
path: DIRECTORY_PATH
|
|
1158
|
+
}));
|
|
1159
|
+
}
|
|
1160
|
+
/** Change (or reset with `null`) the directory new projects are placed in. */
|
|
1161
|
+
async function changeProjectsDirectory(host, directory) {
|
|
1162
|
+
try {
|
|
1163
|
+
return directoryOf(await host.api.request({
|
|
1164
|
+
method: "PUT",
|
|
1165
|
+
path: DIRECTORY_PATH,
|
|
1166
|
+
body: { directory }
|
|
1167
|
+
}));
|
|
1168
|
+
} catch (error) {
|
|
1169
|
+
throw new Error(`无法使用该目录:${message(error)}`);
|
|
1170
|
+
}
|
|
1171
|
+
}
|
|
1172
|
+
function directoryOf(response) {
|
|
1173
|
+
const body = response ?? {};
|
|
1174
|
+
if (typeof body.directory !== "string" || body.directory.length === 0) throw new Error("目录设置不可用。");
|
|
1175
|
+
return {
|
|
1176
|
+
directory: body.directory,
|
|
1177
|
+
defaultDirectory: typeof body.default_directory === "string" ? body.default_directory : body.directory,
|
|
1178
|
+
isDefault: body.is_default === true
|
|
1179
|
+
};
|
|
1180
|
+
}
|
|
1181
|
+
function describe(body) {
|
|
1182
|
+
const text = typeof body.error === "string" && body.error.length > 0 ? body.error : typeof body.detail === "string" ? body.detail : "";
|
|
1183
|
+
return text.length > 0 ? text : "HQ Edge 未返回工程目录。";
|
|
1184
|
+
}
|
|
1185
|
+
function message(error) {
|
|
1186
|
+
return error instanceof Error ? error.message : String(error);
|
|
1187
|
+
}
|
|
1188
|
+
//#endregion
|
|
1078
1189
|
//#region src/client/index.ts
|
|
1079
1190
|
window.__ModuleLoader__.load({
|
|
1080
1191
|
id: "@huaqiu/dsh-tool-kicad-schematic-gen",
|
|
@@ -1085,6 +1196,19 @@
|
|
|
1085
1196
|
const chat = props.useChat?.((snapshot) => snapshot);
|
|
1086
1197
|
const state = chat ? overviewForTurn(props.turn, chat) : NO_OVERVIEW, result = state.result;
|
|
1087
1198
|
const [page, setPage] = useState(0), [zoom, setZoom] = useState(1), [message, setMessage] = useState(""), [busy, setBusy] = useState(false);
|
|
1199
|
+
const [directory, setDirectory] = useState(void 0);
|
|
1200
|
+
const [editing, setEditing] = useState(false), [draft, setDraft] = useState("");
|
|
1201
|
+
useEffect(() => {
|
|
1202
|
+
const bridge = importingHost(getHost);
|
|
1203
|
+
if (!bridge) return;
|
|
1204
|
+
let live = true;
|
|
1205
|
+
readProjectsDirectory(bridge).then((d) => {
|
|
1206
|
+
if (live) setDirectory(d);
|
|
1207
|
+
}).catch(() => {});
|
|
1208
|
+
return () => {
|
|
1209
|
+
live = false;
|
|
1210
|
+
};
|
|
1211
|
+
}, []);
|
|
1088
1212
|
useEffect(() => {
|
|
1089
1213
|
setPage(0);
|
|
1090
1214
|
setZoom(1);
|
|
@@ -1096,7 +1220,7 @@
|
|
|
1096
1220
|
style: { padding: 12 }
|
|
1097
1221
|
}, state.message);
|
|
1098
1222
|
const current = result.pages[page] ?? result.pages[0];
|
|
1099
|
-
const host = placementHost(getHost);
|
|
1223
|
+
const host = placementHost(getHost), bridge = importingHost(getHost);
|
|
1100
1224
|
async function place() {
|
|
1101
1225
|
const currentHost = placementHost(getHost);
|
|
1102
1226
|
if (!currentHost || !result || busy) return;
|
|
@@ -1111,6 +1235,45 @@
|
|
|
1111
1235
|
setBusy(false);
|
|
1112
1236
|
}
|
|
1113
1237
|
}
|
|
1238
|
+
async function openInEda() {
|
|
1239
|
+
const bridge = importingHost(getHost);
|
|
1240
|
+
if (!bridge || !result || busy) return;
|
|
1241
|
+
setBusy(true);
|
|
1242
|
+
setMessage("正在打开到 KiCad…");
|
|
1243
|
+
try {
|
|
1244
|
+
const opened = await openInKiCad(bridge, {
|
|
1245
|
+
downloadUrl: result.downloadUrl,
|
|
1246
|
+
projectName: result.title,
|
|
1247
|
+
sessionId: props.sessionId
|
|
1248
|
+
});
|
|
1249
|
+
setMessage(`已在 KiCad 中打开:${opened.projectDir}${opened.sessionForked ? "(已接续生成该设计的对话)" : ""}`);
|
|
1250
|
+
if (opened.projectsDir) setDirectory((d) => d === void 0 ? d : {
|
|
1251
|
+
...d,
|
|
1252
|
+
directory: opened.projectsDir,
|
|
1253
|
+
isDefault: opened.projectsDir === d.defaultDirectory
|
|
1254
|
+
});
|
|
1255
|
+
} catch (error) {
|
|
1256
|
+
setMessage(error instanceof Error ? error.message : String(error));
|
|
1257
|
+
} finally {
|
|
1258
|
+
setBusy(false);
|
|
1259
|
+
}
|
|
1260
|
+
}
|
|
1261
|
+
async function saveDirectory(directory) {
|
|
1262
|
+
const bridge = importingHost(getHost);
|
|
1263
|
+
if (!bridge || busy) return;
|
|
1264
|
+
setBusy(true);
|
|
1265
|
+
setMessage("");
|
|
1266
|
+
try {
|
|
1267
|
+
const next = await changeProjectsDirectory(bridge, directory);
|
|
1268
|
+
setDirectory(next);
|
|
1269
|
+
setEditing(false);
|
|
1270
|
+
setMessage(`新的工程将保存到:${next.directory}`);
|
|
1271
|
+
} catch (error) {
|
|
1272
|
+
setMessage(error instanceof Error ? error.message : String(error));
|
|
1273
|
+
} finally {
|
|
1274
|
+
setBusy(false);
|
|
1275
|
+
}
|
|
1276
|
+
}
|
|
1114
1277
|
async function download() {
|
|
1115
1278
|
if (!result) return;
|
|
1116
1279
|
setBusy(true);
|
|
@@ -1211,18 +1374,72 @@
|
|
|
1211
1374
|
marginTop: 12,
|
|
1212
1375
|
display: "flex",
|
|
1213
1376
|
gap: 12,
|
|
1214
|
-
alignItems: "center"
|
|
1377
|
+
alignItems: "center",
|
|
1378
|
+
flexWrap: "wrap"
|
|
1215
1379
|
} }, h("button", {
|
|
1216
1380
|
type: "button",
|
|
1217
1381
|
style: buttonStyle,
|
|
1218
1382
|
onClick: download,
|
|
1219
1383
|
disabled: busy
|
|
1220
|
-
}, "下载工程 ZIP"),
|
|
1384
|
+
}, "下载工程 ZIP"), bridge ? h("button", {
|
|
1385
|
+
type: "button",
|
|
1386
|
+
style: buttonStyle,
|
|
1387
|
+
onClick: openInEda,
|
|
1388
|
+
disabled: busy
|
|
1389
|
+
}, busy ? "处理中…" : "打开到 KiCad") : null, host ? h("button", {
|
|
1221
1390
|
type: "button",
|
|
1222
1391
|
style: buttonStyle,
|
|
1223
1392
|
onClick: place,
|
|
1224
1393
|
disabled: busy
|
|
1225
|
-
}, busy ? "处理中…" : "放置到编辑器") : null, h("span", { style: { fontSize: 12 } }, `${result.fileCount} 个工程和库文件`)), result.status !== "ok" ? h("p", null, "存在未渲染页面或预览警告,请结合工具结果检查。") : null,
|
|
1394
|
+
}, busy ? "处理中…" : "放置到编辑器") : null, h("span", { style: { fontSize: 12 } }, `${result.fileCount} 个工程和库文件`)), result.status !== "ok" ? h("p", null, "存在未渲染页面或预览警告,请结合工具结果检查。") : null, directory ? h("div", { style: {
|
|
1395
|
+
marginTop: 10,
|
|
1396
|
+
fontSize: 12,
|
|
1397
|
+
display: "flex",
|
|
1398
|
+
gap: 8,
|
|
1399
|
+
alignItems: "center",
|
|
1400
|
+
flexWrap: "wrap"
|
|
1401
|
+
} }, editing ? h("input", {
|
|
1402
|
+
type: "text",
|
|
1403
|
+
value: draft,
|
|
1404
|
+
placeholder: directory.defaultDirectory,
|
|
1405
|
+
"aria-label": "工程保存目录",
|
|
1406
|
+
onChange: (event) => setDraft(event.target.value),
|
|
1407
|
+
style: {
|
|
1408
|
+
flex: "1 1 260px",
|
|
1409
|
+
padding: "5px 8px",
|
|
1410
|
+
border: "1px solid #aaa",
|
|
1411
|
+
borderRadius: 6,
|
|
1412
|
+
background: "transparent",
|
|
1413
|
+
color: "inherit"
|
|
1414
|
+
}
|
|
1415
|
+
}) : h("span", null, `工程保存目录:${directory.directory}${directory.isDefault ? "(默认)" : ""}`), editing ? h("button", {
|
|
1416
|
+
type: "button",
|
|
1417
|
+
style: buttonStyle,
|
|
1418
|
+
onClick: () => void saveDirectory(draft.trim() === "" ? null : draft.trim()),
|
|
1419
|
+
disabled: busy
|
|
1420
|
+
}, "保存") : h("button", {
|
|
1421
|
+
type: "button",
|
|
1422
|
+
style: buttonStyle,
|
|
1423
|
+
onClick: () => {
|
|
1424
|
+
setDraft(directory.isDefault ? "" : directory.directory);
|
|
1425
|
+
setEditing(true);
|
|
1426
|
+
setMessage("");
|
|
1427
|
+
},
|
|
1428
|
+
disabled: busy
|
|
1429
|
+
}, "更改"), editing ? h("button", {
|
|
1430
|
+
type: "button",
|
|
1431
|
+
style: buttonStyle,
|
|
1432
|
+
onClick: () => void saveDirectory(null),
|
|
1433
|
+
disabled: busy || directory.isDefault
|
|
1434
|
+
}, "恢复默认") : null, editing ? h("button", {
|
|
1435
|
+
type: "button",
|
|
1436
|
+
style: buttonStyle,
|
|
1437
|
+
onClick: () => {
|
|
1438
|
+
setEditing(false);
|
|
1439
|
+
setMessage("");
|
|
1440
|
+
},
|
|
1441
|
+
disabled: busy
|
|
1442
|
+
}, "取消") : null) : null, message ? h("p", { role: "alert" }, message) : null);
|
|
1226
1443
|
}
|
|
1227
1444
|
return {
|
|
1228
1445
|
inject: ["slots", "inputTriggers"],
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@huaqiu/dsh-tool-kicad-schematic-gen",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.5",
|
|
4
4
|
"description": "KiCad 原理图设计:电路模块搜索、器件模型与手册、符号导入、编辑预览、脚本构建及设计技能",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./lib/index.js",
|
|
@@ -32,8 +32,8 @@
|
|
|
32
32
|
"pdfjs-dist": "6.3.289",
|
|
33
33
|
"sharp": "0.35.4",
|
|
34
34
|
"undici": "^8.10.0",
|
|
35
|
-
"@huaqiu/dsh-plugin-log": "0.7.
|
|
36
|
-
"@huaqiu/dsh-sidebar-entry": "0.7.
|
|
35
|
+
"@huaqiu/dsh-plugin-log": "0.7.5",
|
|
36
|
+
"@huaqiu/dsh-sidebar-entry": "0.7.5"
|
|
37
37
|
},
|
|
38
38
|
"peerDependencies": {
|
|
39
39
|
"@deepseek-ai/cordis": "^4.0.2",
|
package/src/client/index.ts
CHANGED
|
@@ -5,6 +5,7 @@ import {placementHost,placeOverview,type PlacementHost} from './place.ts'
|
|
|
5
5
|
import {registerSchematicGenSourceWhenReady} from './schematic-ref.ts'
|
|
6
6
|
import {mountSchematicGenSidebarEntry} from './sidebar-entry.ts'
|
|
7
7
|
import {insertSchematicChip,currentSessionId,resolveSessionScope,type ChipInserterDeps,type ConversationLike,type SessionsLike} from './composer-chip.ts'
|
|
8
|
+
import {importingHost,openInKiCad,readProjectsDirectory,changeProjectsDirectory,type ImportHost,type ProjectsDirectory} from './open-in-eda.ts'
|
|
8
9
|
|
|
9
10
|
interface ClientContext {
|
|
10
11
|
get?:(name:string)=>unknown
|
|
@@ -14,24 +15,54 @@ interface ClientContext {
|
|
|
14
15
|
const loader=(window as unknown as {__ModuleLoader__:{load:(options:unknown)=>void}}).__ModuleLoader__
|
|
15
16
|
loader.load({id:'@huaqiu/dsh-tool-kicad-schematic-gen',factory:(require:(name:string)=>typeof ReactTypes)=>{
|
|
16
17
|
const React=require('react'),{createElement:h,useState,useEffect}=React
|
|
17
|
-
|
|
18
|
+
// One service, two capabilities: placement (editor-side) and the hq-edge API
|
|
19
|
+
// bridge (project import + settings). Both read it lazily.
|
|
20
|
+
type HqEdgeHost=PlacementHost&ImportHost
|
|
21
|
+
let getHost:(()=>HqEdgeHost|undefined)|undefined
|
|
18
22
|
function Card(props:{turn?:OverviewTurn;sessionId?:string;useChat?:<T>(select:(snapshot:OverviewChat)=>T)=>T}){
|
|
19
23
|
// The hook belongs to this slot's session binding. Read synchronously so history replay,
|
|
20
24
|
// session switches and completion cannot race a separate watcher/effect cache.
|
|
21
25
|
const chat=props.useChat?.(snapshot=>snapshot)
|
|
22
26
|
const state=chat?overviewForTurn(props.turn,chat):NO_OVERVIEW,result=state.result
|
|
23
27
|
const [page,setPage]=useState(0),[zoom,setZoom]=useState(1),[message,setMessage]=useState(''),[busy,setBusy]=useState(false)
|
|
28
|
+
// Where the NEXT project lands. Read once per mount from HQ Edge (the owner
|
|
29
|
+
// of that setting) so the user can see and change it before opening.
|
|
30
|
+
const [directory,setDirectory]=useState<ProjectsDirectory|undefined>(undefined)
|
|
31
|
+
const [editing,setEditing]=useState(false),[draft,setDraft]=useState('')
|
|
32
|
+
useEffect(()=>{const bridge=importingHost(getHost);if(!bridge)return;let live=true
|
|
33
|
+
readProjectsDirectory(bridge).then(d=>{if(live)setDirectory(d)}).catch(()=>{/* optional: the action still works */})
|
|
34
|
+
return()=>{live=false}},[])
|
|
24
35
|
useEffect(()=>{setPage(0);setZoom(1);setMessage('')},[result?.downloadUrl])
|
|
25
36
|
if(state.kind==='review'||state.kind==='running'||(state.kind==='error'&&!state.formal))return null
|
|
26
37
|
if(state.kind!=='delivery'||!result)return h('div',{role:'alert',style:{padding:12}},state.message)
|
|
27
38
|
const current=result.pages[page]??result.pages[0]!
|
|
28
|
-
const host=placementHost(getHost)
|
|
39
|
+
const host=placementHost(getHost),bridge=importingHost(getHost)
|
|
29
40
|
async function place(){
|
|
30
41
|
const currentHost=placementHost(getHost);if(!currentHost||!result||busy)return
|
|
31
42
|
setBusy(true);setMessage('')
|
|
32
43
|
try{await placeOverview(currentHost,result.downloadUrl);setMessage('已发送到 KiCad,请在原理图编辑器中完成放置。')}
|
|
33
44
|
catch(error){setMessage(error instanceof Error?error.message:String(error))}finally{setBusy(false)}
|
|
34
45
|
}
|
|
46
|
+
// Open the delivered project in KiCad: HQ Edge extracts the same immutable
|
|
47
|
+
// snapshot the card shows, moves it into the projects directory and asks the
|
|
48
|
+
// EDA to open it. `props.sessionId` is the conversation that generated the
|
|
49
|
+
// design — HQ Edge forks it into the new project's workspace, so the AI panel
|
|
50
|
+
// there continues this conversation instead of starting blank.
|
|
51
|
+
async function openInEda(){
|
|
52
|
+
const bridge=importingHost(getHost);if(!bridge||!result||busy)return
|
|
53
|
+
setBusy(true);setMessage('正在打开到 KiCad…')
|
|
54
|
+
try{
|
|
55
|
+
const opened=await openInKiCad(bridge,{downloadUrl:result.downloadUrl,projectName:result.title,sessionId:props.sessionId})
|
|
56
|
+
setMessage(`已在 KiCad 中打开:${opened.projectDir}${opened.sessionForked?'(已接续生成该设计的对话)':''}`)
|
|
57
|
+
if(opened.projectsDir)setDirectory(d=>d===undefined?d:{...d,directory:opened.projectsDir!,isDefault:opened.projectsDir===d.defaultDirectory})
|
|
58
|
+
}catch(error){setMessage(error instanceof Error?error.message:String(error))}finally{setBusy(false)}
|
|
59
|
+
}
|
|
60
|
+
async function saveDirectory(directory:string|null){
|
|
61
|
+
const bridge=importingHost(getHost);if(!bridge||busy)return
|
|
62
|
+
setBusy(true);setMessage('')
|
|
63
|
+
try{const next=await changeProjectsDirectory(bridge,directory);setDirectory(next);setEditing(false);setMessage(`新的工程将保存到:${next.directory}`)}
|
|
64
|
+
catch(error){setMessage(error instanceof Error?error.message:String(error))}finally{setBusy(false)}
|
|
65
|
+
}
|
|
35
66
|
async function download(){
|
|
36
67
|
if(!result)return
|
|
37
68
|
setBusy(true);setMessage('')
|
|
@@ -52,12 +83,28 @@ loader.load({id:'@huaqiu/dsh-tool-kicad-schematic-gen',factory:(require:(name:st
|
|
|
52
83
|
h('button',{type:'button',style:buttonStyle,onClick:()=>setZoom(z=>Math.min(4,z+.5)),disabled:zoom===4,'aria-label':'放大'},'+'),
|
|
53
84
|
h('button',{type:'button',style:buttonStyle,onClick:()=>setZoom(1)},'适合窗口')),
|
|
54
85
|
h('div',{style:{overflow:'auto',maxHeight:540,background:'#fff',borderRadius:6}},h('img',{key:current.imageUrl,src:current.imageUrl,alt:`${result.title} — ${current.name}`,onError:()=>setMessage('预览图片不可用,请检查本地正式预览。'),style:{display:'block',width:`${zoom*100}%`,maxWidth:'none',height:zoom===1?480:'auto',objectFit:'contain'}})),
|
|
55
|
-
h('div',{style:{marginTop:12,display:'flex',gap:12,alignItems:'center'
|
|
86
|
+
h('div',{style:{marginTop:12,display:'flex',gap:12,alignItems:'center',flexWrap:'wrap'}},
|
|
87
|
+
h('button',{type:'button',style:buttonStyle,onClick:download,disabled:busy},'下载工程 ZIP'),
|
|
88
|
+
// Opening the design needs HQ Edge (it owns the project directory and the
|
|
89
|
+
// EDA hand-off); placement needs an editor that accepts schematic content.
|
|
90
|
+
bridge?h('button',{type:'button',style:buttonStyle,onClick:openInEda,disabled:busy},busy?'处理中…':'打开到 KiCad'):null,
|
|
91
|
+
host?h('button',{type:'button',style:buttonStyle,onClick:place,disabled:busy},busy?'处理中…':'放置到编辑器'):null,
|
|
92
|
+
h('span',{style:{fontSize:12}},`${result.fileCount} 个工程和库文件`)),
|
|
56
93
|
result.status!=='ok'?h('p',null,'存在未渲染页面或预览警告,请结合工具结果检查。'):null,
|
|
94
|
+
// The projects directory is HQ Edge's setting, not this card's: it is shown
|
|
95
|
+
// and changed here because this is where the user decides to open a project.
|
|
96
|
+
directory?h('div',{style:{marginTop:10,fontSize:12,display:'flex',gap:8,alignItems:'center',flexWrap:'wrap'}},
|
|
97
|
+
editing?h('input',{type:'text',value:draft,placeholder:directory.defaultDirectory,'aria-label':'工程保存目录',onChange:(event:ReactTypes.ChangeEvent<HTMLInputElement>)=>setDraft(event.target.value),style:{flex:'1 1 260px',padding:'5px 8px',border:'1px solid #aaa',borderRadius:6,background:'transparent',color:'inherit'}})
|
|
98
|
+
:h('span',null,`工程保存目录:${directory.directory}${directory.isDefault?'(默认)':''}`),
|
|
99
|
+
editing?h('button',{type:'button',style:buttonStyle,onClick:()=>void saveDirectory(draft.trim()===''?null:draft.trim()),disabled:busy},'保存')
|
|
100
|
+
:h('button',{type:'button',style:buttonStyle,onClick:()=>{setDraft(directory.isDefault?'':directory.directory);setEditing(true);setMessage('')},disabled:busy},'更改'),
|
|
101
|
+
editing?h('button',{type:'button',style:buttonStyle,onClick:()=>void saveDirectory(null),disabled:busy||directory.isDefault},'恢复默认'):null,
|
|
102
|
+
editing?h('button',{type:'button',style:buttonStyle,onClick:()=>{setEditing(false);setMessage('')},disabled:busy},'取消'):null
|
|
103
|
+
):null,
|
|
57
104
|
message?h('p',{role:'alert'},message):null)
|
|
58
105
|
}
|
|
59
106
|
return {inject:['slots','inputTriggers'],apply:(ctx:ClientContext)=>{
|
|
60
|
-
getHost=()=>ctx.get?.('hqEdge') as
|
|
107
|
+
getHost=()=>ctx.get?.('hqEdge') as HqEdgeHost|undefined
|
|
61
108
|
// Trace the two things that decide whether the plugin is visible at all:
|
|
62
109
|
// the trigger registry (the `@` menu) and the mounted sidebar row. When the
|
|
63
110
|
// node half fails to import, DSH never loads this file — so silence here
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* "Open in KiCad": hand a delivery snapshot to HQ Edge's import pipeline.
|
|
3
|
+
*
|
|
4
|
+
* The card owns no project directory and no KiCad knowledge: it posts the same
|
|
5
|
+
* immutable ZIP it shows (and lets the user download) to
|
|
6
|
+
* `/api/v1/import/kicad-b64`, and HQ Edge extracts it, moves it into the user's
|
|
7
|
+
* projects directory and asks the EDA to open it. Everything the user needs to
|
|
8
|
+
* see afterwards — where the project landed, whether the generating
|
|
9
|
+
* conversation was carried into the project's workspace — comes back in the
|
|
10
|
+
* response.
|
|
11
|
+
*
|
|
12
|
+
* The bridge's request proxy serializes object bodies to JSON, so the upload is
|
|
13
|
+
* base64 rather than multipart (same reason the route exists in that shape).
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/** The subset of the `hqEdge` browser service this module needs. */
|
|
17
|
+
export interface ImportHost {
|
|
18
|
+
api?:{request?:(request:{method:string;path:string;body?:unknown})=>Promise<unknown>}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface ImportResult {
|
|
22
|
+
/** Absolute directory KiCad was asked to open. */
|
|
23
|
+
projectDir:string
|
|
24
|
+
projectName:string
|
|
25
|
+
/** True when the generating conversation now lives in the project workspace. */
|
|
26
|
+
sessionForked:boolean
|
|
27
|
+
/** The projects directory HQ Edge used (the user's configured one). */
|
|
28
|
+
projectsDir?:string
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface ProjectsDirectory {
|
|
32
|
+
directory:string
|
|
33
|
+
defaultDirectory:string
|
|
34
|
+
isDefault:boolean
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const IMPORT_PATH='/api/v1/import/kicad-b64'
|
|
38
|
+
const DIRECTORY_PATH='/api/v1/import/directory'
|
|
39
|
+
/** Only our own immutable snapshots may be uploaded — never an arbitrary URL. */
|
|
40
|
+
const SNAPSHOT=/^\/api\/v1\/kicad-schematic-overview\/[0-9a-f-]{36}\/project\.zip$/
|
|
41
|
+
/** Mark the upload as a generated (not human-authored) design. */
|
|
42
|
+
const SOURCE_VENDOR='circuit_agent', SOURCE_FORMAT='kicad'
|
|
43
|
+
const MAX_BYTES=64*1024*1024
|
|
44
|
+
|
|
45
|
+
/** The host, when it can carry a request; undefined keeps the action hidden. */
|
|
46
|
+
export function importingHost(get:(()=>ImportHost|undefined)|undefined):Required<ImportHost>|null {
|
|
47
|
+
try{const host=get?.();return host?.api?.request?{api:host.api as Required<ImportHost>['api']}:null}catch{return null}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Base64 in bounded chunks: `String.fromCharCode(...bytes)` on a 64 MiB
|
|
52
|
+
* snapshot overflows the call stack, and a per-byte loop is needlessly slow.
|
|
53
|
+
*/
|
|
54
|
+
export function toBase64(bytes:Uint8Array):string{
|
|
55
|
+
let binary=''
|
|
56
|
+
for(let i=0;i<bytes.length;i+=0x8000)
|
|
57
|
+
binary+=String.fromCharCode(...bytes.subarray(i,i+0x8000))
|
|
58
|
+
return btoa(binary)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Upload `downloadUrl`'s snapshot and open it in KiCad.
|
|
63
|
+
*
|
|
64
|
+
* `sessionId` is the conversation that produced the design: HQ Edge forks it
|
|
65
|
+
* into the new project's workspace before the project is announced, so the AI
|
|
66
|
+
* panel there opens on the design discussion instead of a blank chat.
|
|
67
|
+
*/
|
|
68
|
+
export async function openInKiCad(
|
|
69
|
+
host:Required<ImportHost>,
|
|
70
|
+
options:{downloadUrl:string;projectName:string;sessionId?:string},
|
|
71
|
+
request:typeof fetch=fetch,
|
|
72
|
+
):Promise<ImportResult>{
|
|
73
|
+
if(!SNAPSHOT.test(options.downloadUrl))throw new Error('无效的工程快照地址。')
|
|
74
|
+
let bytes:Uint8Array
|
|
75
|
+
try{
|
|
76
|
+
const response=await request(options.downloadUrl)
|
|
77
|
+
if(!response.ok)throw new Error(String(response.status))
|
|
78
|
+
const buffer=await response.arrayBuffer()
|
|
79
|
+
if(buffer.byteLength===0)throw new Error('empty snapshot')
|
|
80
|
+
if(buffer.byteLength>MAX_BYTES)throw new Error('snapshot too large')
|
|
81
|
+
bytes=new Uint8Array(buffer)
|
|
82
|
+
}catch(error){throw new Error(`工程快照不可用,请重新生成后再打开(${message(error)})。`)}
|
|
83
|
+
|
|
84
|
+
const sessionId=options.sessionId?.trim()??''
|
|
85
|
+
const payload:Record<string,unknown>={
|
|
86
|
+
zip_b64:toBase64(bytes),
|
|
87
|
+
filename:`${options.projectName||'design'}.zip`,
|
|
88
|
+
project_name:options.projectName||'design',
|
|
89
|
+
source_vendor:SOURCE_VENDOR,
|
|
90
|
+
source_format:SOURCE_FORMAT,
|
|
91
|
+
}
|
|
92
|
+
if(sessionId.length>0)payload.session_id=sessionId
|
|
93
|
+
|
|
94
|
+
let response:unknown
|
|
95
|
+
try{response=await host.api.request!({method:'POST',path:IMPORT_PATH,body:payload})}
|
|
96
|
+
catch(error){throw new Error(`打开失败:HQ Edge 未响应(${message(error)})。`)}
|
|
97
|
+
|
|
98
|
+
const body=(response??{}) as {project_dir?:unknown;project_name?:unknown;session_forked?:unknown;projects_dir?:unknown;error?:unknown;detail?:unknown}
|
|
99
|
+
if(typeof body.project_dir!=='string'||body.project_dir.length===0)throw new Error(`打开失败:${describe(body)}`)
|
|
100
|
+
return {
|
|
101
|
+
projectDir:body.project_dir,
|
|
102
|
+
projectName:typeof body.project_name==='string'&&body.project_name.length>0?body.project_name:options.projectName,
|
|
103
|
+
sessionForked:body.session_forked===true,
|
|
104
|
+
projectsDir:typeof body.projects_dir==='string'&&body.projects_dir.length>0?body.projects_dir:undefined,
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Where the NEXT project will be placed (and what the default would be). */
|
|
109
|
+
export async function readProjectsDirectory(host:Required<ImportHost>):Promise<ProjectsDirectory>{
|
|
110
|
+
const response=await host.api.request!({method:'GET',path:DIRECTORY_PATH})
|
|
111
|
+
return directoryOf(response)
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Change (or reset with `null`) the directory new projects are placed in. */
|
|
115
|
+
export async function changeProjectsDirectory(host:Required<ImportHost>,directory:string|null):Promise<ProjectsDirectory>{
|
|
116
|
+
try{
|
|
117
|
+
const response=await host.api.request!({method:'PUT',path:DIRECTORY_PATH,body:{directory}})
|
|
118
|
+
return directoryOf(response)
|
|
119
|
+
}catch(error){throw new Error(`无法使用该目录:${message(error)}`)}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function directoryOf(response:unknown):ProjectsDirectory{
|
|
123
|
+
const body=(response??{}) as {directory?:unknown;default_directory?:unknown;is_default?:unknown}
|
|
124
|
+
if(typeof body.directory!=='string'||body.directory.length===0)throw new Error('目录设置不可用。')
|
|
125
|
+
return {
|
|
126
|
+
directory:body.directory,
|
|
127
|
+
defaultDirectory:typeof body.default_directory==='string'?body.default_directory:body.directory,
|
|
128
|
+
isDefault:body.is_default===true,
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function describe(body:{error?:unknown;detail?:unknown}):string{
|
|
133
|
+
const text=typeof body.error==='string'&&body.error.length>0?body.error:typeof body.detail==='string'?body.detail:''
|
|
134
|
+
return text.length>0?text:'HQ Edge 未返回工程目录。'
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function message(error:unknown):string{return error instanceof Error?error.message:String(error)}
|