dsh-cad-studio 0.23.0 → 0.24.0

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.
Files changed (4) hide show
  1. package/README.md +1 -0
  2. package/client.js +84 -0
  3. package/index.js +271 -89
  4. package/package.json +1 -1
package/README.md CHANGED
@@ -18,6 +18,7 @@ DeepSeek Harness 的 CAD 插件:**把 FreeCAD 桥接成给 AI 用的工具**
18
18
  | 运动 | `cad_studio_joint`(revolute/linear)+ `cad_studio_drive` + `cad_studio_explode`,面板拖滑杆看运动 |
19
19
  | 出图 | `cad_studio_drawing` HLR → SVG(主/俯/左/等轴);`cad_studio_sheet` 正式图纸(图框 + 标题栏 + 三视图 + 尺寸,A4/A3/A2,可出 DXF) |
20
20
  | 装配 | `cad_studio_assembly` 多零件实例、`cad_studio_joint` 关节、`cad_studio_mate` 约束(同心/贴合/距离)、`cad_studio_drive` 驱动、`cad_studio_explode` 爆炸图 |
21
+ | 依赖 | `cad_studio_deps` 列出模型的来源 STEP(谁在用、还在不在),`relink` 换路径后原地重建;面板「信息」里能直接填新路径 |
21
22
  | 外观 | 面板里改的颜色/显隐/透明度/线框按模型保存(`POST /cad-studio/appearance`),刷新和重启后仍在 |
22
23
  | 其它 | `cad_studio_open`(STEP/STL/BREP/IGES 进来看)、`cad_studio_export`、`cad_studio_measure`、`cad_studio_env` |
23
24
  | 模型清单 | `cad_studio_scene`(`action: list / delete / rename`)——面板里那条列表就是它;探查脚本留下的卡片可以直接删 |
package/client.js CHANGED
@@ -1571,6 +1571,11 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
1571
1571
  // 'models' | 'info' | '' (closed). Same icon again closes it.
1572
1572
  const [panel, setPanel] = useState('')
1573
1573
  useEffect(() => { panelRef.current = panel }, [panel])
1574
+ // Dependencies are only interesting while the info drawer is open, and
1575
+ // they change only when a relink happens — so fetch on open, not on poll.
1576
+ useEffect(() => {
1577
+ if (panel === 'info') loadDeps()
1578
+ }, [panel, payload?.docKey])
1574
1579
  const theme = useTheme()
1575
1580
  // Colour overrides picked by hand in the tree. Two levels, because an
1576
1581
  // assembly can show one part many times: `inst` is one row, `part` is
@@ -1711,6 +1716,11 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
1711
1716
  const [featDraft, setFeatDraft] = useState({})
1712
1717
  const [featAdd, setFeatAdd] = useState(false)
1713
1718
  const [featError, setFeatError] = useState('')
1719
+ // Which files the model is made of (assemblies only), fetched when the
1720
+ // info drawer opens: a moved STEP is invisible until a rebuild fails.
1721
+ const [deps, setDeps] = useState(null)
1722
+ const [relinkFor, setRelinkFor] = useState({})
1723
+ const [relinkNote, setRelinkNote] = useState('')
1714
1724
  // Which document sketch is expanded in the 草图 section.
1715
1725
  const [openSketch, setOpenSketch] = useState('')
1716
1726
  const featTimer = useRef(null)
@@ -1769,6 +1779,31 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
1769
1779
  rememberView(tabKey, payloadRef.current)
1770
1780
  showScene(scene, { keepView: true, tabKey })
1771
1781
  }
1782
+ const loadDeps = async () => {
1783
+ try {
1784
+ const res = await fetch(`${ROUTE}/deps`, { headers: { accept: 'application/json' } })
1785
+ if (res.ok) setDeps(await res.json())
1786
+ } catch {}
1787
+ }
1788
+ const doRelink = async (assembly, part) => {
1789
+ const path = (relinkFor[part] ?? '').trim()
1790
+ if (!path) return setRelinkNote('先填新的文件路径')
1791
+ setRelinkNote(`重新读取 ${part}…`)
1792
+ try {
1793
+ const res = await fetch(`${ROUTE}/relink`, {
1794
+ method: 'POST',
1795
+ headers: { 'content-type': 'application/json' },
1796
+ body: JSON.stringify({ assembly, part, path }),
1797
+ })
1798
+ const out = await res.json()
1799
+ if (!out || out.ok === false) return setRelinkNote(String((out && out.error) || `HTTP ${res.status}`))
1800
+ setRelinkNote(`${part} 已指向 ${path}`)
1801
+ await loadDeps()
1802
+ if (out.sceneId) await applyScene(out.sceneId, out.at)
1803
+ } catch (error) {
1804
+ setRelinkNote(String(error?.message ?? error))
1805
+ }
1806
+ }
1772
1807
  const postMotion = async (path, body) => {
1773
1808
  try {
1774
1809
  const res = await fetch(`${ROUTE}${path}`, {
@@ -2441,6 +2476,11 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
2441
2476
  : []
2442
2477
 
2443
2478
  const panelTitle = { parts: '零件', features: '特征', props: '选中项', motion: '运动', view: '视图', models: '模型', info: '信息' }[panel] || ''
2479
+ // The scene carries `asm:<id>` for an assembly, which is how the deps list
2480
+ // is matched to what is on screen.
2481
+ const depsModel = deps && payload && typeof payload.docKey === 'string' && payload.docKey.startsWith('asm:')
2482
+ ? (deps.models || []).find((m) => `asm:${m.assembly}` === payload.docKey) || null
2483
+ : null
2444
2484
  // --- inspector: the properties of the one selected instance ----------
2445
2485
  const pickedInst = payload ? (payload.instances || []).find((i) => i.name === picked) : null
2446
2486
  const pickedPart = pickedInst ? (payload.parts || []).find((p) => p.id === pickedInst.part) : null
@@ -2680,6 +2720,50 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
2680
2720
  h('span', { key: 'v', style: { ...styles.infoVal, maxWidth: '52%', whiteSpace: 'normal' }, title: chk.fix || chk.detail }, chk.ok ? chk.detail : (chk.fix || chk.detail)),
2681
2721
  ])),
2682
2722
  ...(installNode ? [installNode] : []),
2723
+ ...(depsModel ? [
2724
+ h('div', { key: 'deps-head', style: { ...styles.infoRow, marginTop: 6 } }, [
2725
+ h('span', { key: 'k', style: styles.infoKey }, '来源文件'),
2726
+ h('span', { key: 'v', style: { ...styles.infoVal, color: depsModel.missingParts?.length ? '#d9534f' : undefined } },
2727
+ depsModel.missingParts?.length ? `缺 ${depsModel.missingParts.length}` : `${depsModel.files.length} 个`),
2728
+ ]),
2729
+ ...depsModel.files.map((f) => h('div', {
2730
+ key: `dep-${f.part}`,
2731
+ style: { display: 'flex', flexDirection: 'column', gap: 3, padding: '4px 0', borderTop: '1px solid rgba(127,127,127,.16)' },
2732
+ 'data-cad-dep': f.part,
2733
+ }, [
2734
+ h('div', { key: 'row', style: { display: 'flex', alignItems: 'center', gap: 6 } }, [
2735
+ h('span', { key: 'dot', style: styles.guideDot(f.exists, true), 'data-cad-dep-state': f.exists ? 'ok' : 'missing' }),
2736
+ h('span', { key: 'n', style: { ...styles.infoKey, flex: '0 0 auto' } }, f.part),
2737
+ h('span', {
2738
+ key: 'p',
2739
+ style: { ...styles.infoVal, flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', opacity: 0.72, fontSize: 10.5 },
2740
+ title: f.path,
2741
+ }, f.path),
2742
+ ]),
2743
+ f.exists ? null : h('div', { key: 'fix', style: { display: 'flex', gap: 4 } }, [
2744
+ h('input', {
2745
+ key: 'in',
2746
+ type: 'text',
2747
+ placeholder: '新的文件路径…',
2748
+ value: relinkFor[f.part] ?? '',
2749
+ 'data-cad-relink-input': f.part,
2750
+ style: { flex: 1, minWidth: 0, fontSize: 11, padding: '3px 5px', borderRadius: 4, border: '1px solid rgba(127,127,127,.35)', background: 'transparent', color: 'inherit' },
2751
+ onChange: (event) => setRelinkFor((prev) => ({ ...prev, [f.part]: event.target.value })),
2752
+ onKeyDown: (event) => { if (event.key === 'Enter') doRelink(depsModel.assembly, f.part) },
2753
+ }),
2754
+ h('button', {
2755
+ key: 'go',
2756
+ type: 'button',
2757
+ 'data-cad-relink': f.part,
2758
+ style: { flex: '0 0 auto', padding: '2px 8px', fontSize: 11, cursor: 'pointer', borderRadius: 4, border: '1px solid rgba(77,107,254,.5)', background: 'rgba(77,107,254,.16)', color: 'inherit' },
2759
+ onClick: () => doRelink(depsModel.assembly, f.part),
2760
+ }, '重定位'),
2761
+ ]),
2762
+ ])),
2763
+ relinkNote ? h('div', { key: 'note', style: { ...styles.treeHint, whiteSpace: 'normal', paddingTop: 4 }, 'data-cad-relink-note': '1' }, relinkNote) : null,
2764
+ ] : payload && payload.docKey && String(payload.docKey).startsWith('model:')
2765
+ ? [h('div', { key: 'deps-na', style: { ...styles.treeHint, whiteSpace: 'normal', paddingTop: 6 } }, '这个模型是特征建的,没有外部文件依赖')]
2766
+ : []),
2683
2767
  ]
2684
2768
  : null
2685
2769
 
package/index.js CHANGED
@@ -652,6 +652,101 @@ function normalizeLook(raw) {
652
652
  }
653
653
  }
654
654
 
655
+ /**
656
+ * The assembly script: read each part file once, tessellate it, place one copy
657
+ * per instance. Shared by `cad_studio_assembly` and by a relink, which re-runs
658
+ * it against a corrected path so the model keeps its identity.
659
+ */
660
+ function assemblyScript(parts, instances, target, measure, interference) {
661
+ return `${PRELUDE}
662
+ ` + `
663
+ import os
664
+ _PART_FILES = ${JSON.stringify(parts.map((p) => (p.color ? { name: p.name, path: p.path, color: p.color } : { name: p.name, path: p.path })))}
665
+ _INSTS = ${JSON.stringify(instances.map((i) => ({ name: i.name, part: i.part, at: i.at ?? [0, 0, 0], rot: i.rot ?? [0, 0, 0] })))}
666
+ _TARGET = ${target ? JSON.stringify(target) : 'None'}
667
+
668
+ _shapes = {}
669
+ _parts = []
670
+ for _p in _PART_FILES:
671
+ if not os.path.isfile(_p["path"]):
672
+ raise RuntimeError("part file not found: " + _p["path"])
673
+ _s = Part.Shape()
674
+ _s.read(_p["path"])
675
+ _shapes[_p["name"]] = _s
676
+ _m = _mesh(_s)
677
+ _part = {"id": _p["name"], "verts": _m["verts"], "tris": _m["tris"], "volume": round(_s.Volume, 3)}
678
+ if "color" in _p and _p["color"]:
679
+ _part["color"] = _p["color"]
680
+ _parts.append(_part)
681
+
682
+ _placed = []
683
+ _instances = []
684
+ for _i in _INSTS:
685
+ if _i["part"] not in _shapes:
686
+ raise RuntimeError("instance '" + _i["name"] + "' references unknown part '" + _i["part"] + "'")
687
+ _rx, _ry, _rz = _i["rot"]
688
+ _R = FreeCAD.Rotation(FreeCAD.Vector(0, 0, 1), _rz) * FreeCAD.Rotation(FreeCAD.Vector(0, 1, 0), _ry) * FreeCAD.Rotation(FreeCAD.Vector(1, 0, 0), _rx)
689
+ _ax = _R.multVec(FreeCAD.Vector(1, 0, 0))
690
+ _ay = _R.multVec(FreeCAD.Vector(0, 1, 0))
691
+ _az = _R.multVec(FreeCAD.Vector(0, 0, 1))
692
+ _rot = [_ax.x, _ay.x, _az.x, _ax.y, _ay.y, _az.y, _ax.z, _ay.z, _az.z]
693
+ _instances.append({"name": _i["name"], "part": _i["part"], "rot": _rot, "translate": [float(c) for c in _i["at"]]})
694
+ _copy = _shapes[_i["part"]].copy()
695
+ _copy.Placement = FreeCAD.Placement(FreeCAD.Vector(*_i["at"]), _R)
696
+ _placed.append(_copy)
697
+
698
+ _MEASURE = ${measure ? 'True' : 'False'}
699
+ _INTERF = ${interference ? 'True' : 'False'}
700
+
701
+ __out = {"ok": True, "instances": len(_instances), "parts": len(_parts),
702
+ "scene": {"parts": _parts, "instances": _instances}}
703
+
704
+ if _MEASURE:
705
+ # Per-instance numbers, so "how big is this part, and does it fit" is one
706
+ # call instead of an export plus a re-import.
707
+ _rows = []
708
+ for _k, _inst in enumerate(_INSTS):
709
+ _s = _placed[_k]
710
+ _bb = _s.BoundBox
711
+ _rows.append({
712
+ "name": _inst["name"], "part": _inst["part"],
713
+ "volume": round(float(_s.Volume), 3), "solids": len(_s.Solids),
714
+ "bounds": {"min": [round(_bb.XMin, 3), round(_bb.YMin, 3), round(_bb.ZMin, 3)],
715
+ "max": [round(_bb.XMax, 3), round(_bb.YMax, 3), round(_bb.ZMax, 3)]},
716
+ })
717
+ _box = Part.makeCompound(_placed).BoundBox
718
+ __out["measure"] = {
719
+ "instances": _rows,
720
+ "totalVolume": round(sum(r["volume"] for r in _rows), 3),
721
+ "bounds": {"min": [round(_box.XMin, 3), round(_box.YMin, 3), round(_box.ZMin, 3)],
722
+ "max": [round(_box.XMax, 3), round(_box.YMax, 3), round(_box.ZMax, 3)]},
723
+ }
724
+
725
+ if _INTERF:
726
+ # Bounding boxes first: a boolean common on every pair of a 30-solid
727
+ # assembly is minutes of work for answers that are mostly zero.
728
+ _pairs = []
729
+ for _i in range(len(_placed)):
730
+ for _j in range(_i + 1, len(_placed)):
731
+ _a, _b = _placed[_i], _placed[_j]
732
+ if not _a.BoundBox.intersect(_b.BoundBox):
733
+ continue
734
+ try:
735
+ _c = _a.common(_b)
736
+ _v = float(_c.Volume) if (_c is not None and not _c.isNull()) else 0.0
737
+ except Exception:
738
+ _v = 0.0
739
+ if _v > 1e-3:
740
+ _pairs.append({"a": _INSTS[_i]["name"], "b": _INSTS[_j]["name"], "volume": round(_v, 3)})
741
+ __out["interference"] = _pairs
742
+ if _TARGET:
743
+ os.makedirs(os.path.dirname(_TARGET) or ".", exist_ok=True)
744
+ Part.makeCompound(_placed).exportStep(_TARGET)
745
+ __out["exported"] = _TARGET
746
+ __out["bytes"] = os.path.getsize(_TARGET)
747
+ `
748
+ }
749
+
655
750
  class FreeCadBridge {
656
751
  constructor(getConfig, log) {
657
752
  this.getConfig = getConfig
@@ -792,6 +887,7 @@ class FreeCadBridge {
792
887
  center: a.center,
793
888
  joints: a.joints.map((j) => ({ id: j.id, instance: j.instance, type: j.type, value: j.value, min: j.min, max: j.max, axis: j.axis, origin: j.origin })),
794
889
  mates: a.mates ?? [],
890
+ spec: a.spec ?? null,
795
891
  explode: a.explode,
796
892
  })),
797
893
  }
@@ -1010,7 +1106,7 @@ class FreeCadBridge {
1010
1106
  }
1011
1107
 
1012
1108
  /** Register the base placements of a published assembly so joints can move it. */
1013
- registerAssembly({ title, sceneId, scene, joints, id: givenId }) {
1109
+ registerAssembly({ title, sceneId, scene, joints, id: givenId, spec = null }) {
1014
1110
  const id = givenId ?? `asm-${++this.assemblySeq}`
1015
1111
  const seq = /^asm-(\d+)$/.exec(id)
1016
1112
  if (seq) this.assemblySeq = Math.max(this.assemblySeq, Number(seq[1]))
@@ -1029,6 +1125,9 @@ class FreeCadBridge {
1029
1125
  center: bboxCenterOfInstances(scene.parts, scene.instances),
1030
1126
  joints: joints ?? [],
1031
1127
  mates: [],
1128
+ // What was asked for (part files + placements), so a relink can re-run the
1129
+ // same build against a corrected path.
1130
+ spec: spec ?? null,
1032
1131
  explode: 0,
1033
1132
  }
1034
1133
  this.assemblies.set(id, record)
@@ -1218,6 +1317,24 @@ class FreeCadBridge {
1218
1317
  * scene file (geometry never changes when a joint moves, so any scene of
1219
1318
  * this assembly carries the right parts).
1220
1319
  */
1320
+ /** Load every assembly the pointer knows about. Assembly records are otherwise
1321
+ * lazy (they load when a tool or route names one), so a dependency listing
1322
+ * would show an empty table after a restart without this. */
1323
+ async hydrateAssemblies() {
1324
+ let pointer
1325
+ try {
1326
+ pointer = JSON.parse(await readFile(join(FreeCadBridge.dataDir, 'state.json'), 'utf8'))
1327
+ } catch {
1328
+ return this.assemblies
1329
+ }
1330
+ for (const meta of Array.isArray(pointer.assemblies) ? pointer.assemblies : []) {
1331
+ if (meta?.id && !this.assemblies.has(meta.id)) {
1332
+ try { await this.loadAssembly(meta.id) } catch {}
1333
+ }
1334
+ }
1335
+ return this.assemblies
1336
+ }
1337
+
1221
1338
  async loadAssembly(id) {
1222
1339
  if (id && this.assemblies.has(id)) return this.assemblies.get(id)
1223
1340
  let pointer
@@ -1987,7 +2104,7 @@ if _EXPORT:
1987
2104
  */
1988
2105
  const BRIDGE_API = [
1989
2106
  'run', 'publishScene', 'hydrateHistory', 'registerAssembly', 'loadAssembly',
1990
- 'setJoint', 'driveJoint', 'setExplode', 'republishAssembly', 'status', 'refresh',
2107
+ 'setJoint', 'driveJoint', 'setExplode', 'republishAssembly', 'hydrateAssemblies', 'status', 'refresh',
1991
2108
  ]
1992
2109
 
1993
2110
  function sharedState(resolved, logger) {
@@ -3300,92 +3417,7 @@ else:
3300
3417
  const missing = [...referenced].filter((name) => !parts.some((p) => p.name === name))
3301
3418
  if (missing.length) return { ok: false, error: `instances reference unknown parts: ${missing.slice(0, 5).join(', ')}` }
3302
3419
  const used = parts.filter((p) => referenced.has(p.name))
3303
- const py = `${PRELUDE}
3304
- import os
3305
- _PART_FILES = ${JSON.stringify(used.map((p) => (p.color ? { name: p.name, path: p.path, color: p.color } : { name: p.name, path: p.path })))}
3306
- _INSTS = ${JSON.stringify(instances.map((i) => ({ name: i.name, part: i.part, at: i.at ?? [0, 0, 0], rot: i.rot ?? [0, 0, 0] })))}
3307
- _TARGET = ${target ? JSON.stringify(target) : 'None'}
3308
-
3309
- _shapes = {}
3310
- _parts = []
3311
- for _p in _PART_FILES:
3312
- if not os.path.isfile(_p["path"]):
3313
- raise RuntimeError("part file not found: " + _p["path"])
3314
- _s = Part.Shape()
3315
- _s.read(_p["path"])
3316
- _shapes[_p["name"]] = _s
3317
- _m = _mesh(_s)
3318
- _part = {"id": _p["name"], "verts": _m["verts"], "tris": _m["tris"], "volume": round(_s.Volume, 3)}
3319
- if "color" in _p and _p["color"]:
3320
- _part["color"] = _p["color"]
3321
- _parts.append(_part)
3322
-
3323
- _placed = []
3324
- _instances = []
3325
- for _i in _INSTS:
3326
- if _i["part"] not in _shapes:
3327
- raise RuntimeError("instance '" + _i["name"] + "' references unknown part '" + _i["part"] + "'")
3328
- _rx, _ry, _rz = _i["rot"]
3329
- _R = FreeCAD.Rotation(FreeCAD.Vector(0, 0, 1), _rz) * FreeCAD.Rotation(FreeCAD.Vector(0, 1, 0), _ry) * FreeCAD.Rotation(FreeCAD.Vector(1, 0, 0), _rx)
3330
- _ax = _R.multVec(FreeCAD.Vector(1, 0, 0))
3331
- _ay = _R.multVec(FreeCAD.Vector(0, 1, 0))
3332
- _az = _R.multVec(FreeCAD.Vector(0, 0, 1))
3333
- _rot = [_ax.x, _ay.x, _az.x, _ax.y, _ay.y, _az.y, _ax.z, _ay.z, _az.z]
3334
- _instances.append({"name": _i["name"], "part": _i["part"], "rot": _rot, "translate": [float(c) for c in _i["at"]]})
3335
- _copy = _shapes[_i["part"]].copy()
3336
- _copy.Placement = FreeCAD.Placement(FreeCAD.Vector(*_i["at"]), _R)
3337
- _placed.append(_copy)
3338
-
3339
- _MEASURE = ${measure ? 'True' : 'False'}
3340
- _INTERF = ${interference ? 'True' : 'False'}
3341
-
3342
- __out = {"ok": True, "instances": len(_instances), "parts": len(_parts),
3343
- "scene": {"parts": _parts, "instances": _instances}}
3344
-
3345
- if _MEASURE:
3346
- # Per-instance numbers, so "how big is this part, and does it fit" is one
3347
- # call instead of an export plus a re-import.
3348
- _rows = []
3349
- for _k, _inst in enumerate(_INSTS):
3350
- _s = _placed[_k]
3351
- _bb = _s.BoundBox
3352
- _rows.append({
3353
- "name": _inst["name"], "part": _inst["part"],
3354
- "volume": round(float(_s.Volume), 3), "solids": len(_s.Solids),
3355
- "bounds": {"min": [round(_bb.XMin, 3), round(_bb.YMin, 3), round(_bb.ZMin, 3)],
3356
- "max": [round(_bb.XMax, 3), round(_bb.YMax, 3), round(_bb.ZMax, 3)]},
3357
- })
3358
- _box = Part.makeCompound(_placed).BoundBox
3359
- __out["measure"] = {
3360
- "instances": _rows,
3361
- "totalVolume": round(sum(r["volume"] for r in _rows), 3),
3362
- "bounds": {"min": [round(_box.XMin, 3), round(_box.YMin, 3), round(_box.ZMin, 3)],
3363
- "max": [round(_box.XMax, 3), round(_box.YMax, 3), round(_box.ZMax, 3)]},
3364
- }
3365
-
3366
- if _INTERF:
3367
- # Bounding boxes first: a boolean common on every pair of a 30-solid
3368
- # assembly is minutes of work for answers that are mostly zero.
3369
- _pairs = []
3370
- for _i in range(len(_placed)):
3371
- for _j in range(_i + 1, len(_placed)):
3372
- _a, _b = _placed[_i], _placed[_j]
3373
- if not _a.BoundBox.intersect(_b.BoundBox):
3374
- continue
3375
- try:
3376
- _c = _a.common(_b)
3377
- _v = float(_c.Volume) if (_c is not None and not _c.isNull()) else 0.0
3378
- except Exception:
3379
- _v = 0.0
3380
- if _v > 1e-3:
3381
- _pairs.append({"a": _INSTS[_i]["name"], "b": _INSTS[_j]["name"], "volume": round(_v, 3)})
3382
- __out["interference"] = _pairs
3383
- if _TARGET:
3384
- os.makedirs(os.path.dirname(_TARGET) or ".", exist_ok=True)
3385
- Part.makeCompound(_placed).exportStep(_TARGET)
3386
- __out["exported"] = _TARGET
3387
- __out["bytes"] = os.path.getsize(_TARGET)
3388
- `
3420
+ const py = assemblyScript(used, instances, target, measure, interference)
3389
3421
  // Allocate the assembly id before publishing: the scene carries `asm:<id>`
3390
3422
  // so later joint moves rewrite this same entry instead of adding one.
3391
3423
  // Re-running with `assembly` rebuilds THAT assembly in place: same id, so
@@ -3405,7 +3437,14 @@ if _TARGET:
3405
3437
  if (!scene) return out
3406
3438
  const record = reuse
3407
3439
  ? bridge.rebaseAssembly(reuse, { title: title || reuse.title, sceneId: out.sceneId, scene })
3408
- : bridge.registerAssembly({ id: asmId, title: assembly || title || 'assembly', sceneId: out.sceneId, scene, joints: [] })
3440
+ : bridge.registerAssembly({
3441
+ id: asmId,
3442
+ title: assembly || title || 'assembly',
3443
+ sceneId: out.sceneId,
3444
+ scene,
3445
+ joints: [],
3446
+ spec: { parts: used.map((p) => ({ name: p.name, path: p.path, ...(p.color ? { color: p.color } : {}) })), instances },
3447
+ })
3409
3448
  for (const spec of joints ?? []) {
3410
3449
  try {
3411
3450
  bridge.setJoint(record, spec)
@@ -3445,6 +3484,118 @@ if _TARGET:
3445
3484
  return all[all.length - 1]
3446
3485
  }
3447
3486
 
3487
+ // ---- Dependencies: which files a model is made of, and relinking them ---
3488
+ // An assembly stores the part files it read. Moving or re-exporting a STEP
3489
+ // breaks the next rebuild, and the failure only surfaces deep in a Python
3490
+ // traceback, so the files are listed with their state and can be repointed.
3491
+
3492
+ const specRows = (record) => (record.spec?.parts ?? []).map((p) => {
3493
+ let exists = false
3494
+ let bytes = 0
3495
+ let modified = ''
3496
+ try {
3497
+ const st = statSync(p.path)
3498
+ exists = st.isFile()
3499
+ bytes = st.size
3500
+ modified = new Date(st.mtimeMs).toISOString()
3501
+ } catch {}
3502
+ return {
3503
+ part: p.name,
3504
+ path: p.path,
3505
+ exists,
3506
+ bytes,
3507
+ modified,
3508
+ color: Array.isArray(p.color) ? p.color : null,
3509
+ instances: (record.spec?.instances ?? []).filter((i) => i.part === p.name).map((i) => i.name),
3510
+ }
3511
+ })
3512
+
3513
+ // relink: swap one part's file, then re-run the same build so the model keeps
3514
+ // its id, joints, mates and saved look. Shared by the tool and the panel route.
3515
+ // relink: swap one part's file, then re-run the same build so the model keeps
3516
+ // its id, joints, mates and saved look. Shared by the tool and the panel route.
3517
+ const relinkPart = async ({ assembly, part, path }) => {
3518
+ let record
3519
+ try { record = findAssembly(assembly) } catch (error) { return { ok: false, error: String(error?.message ?? error) } }
3520
+ if (!record.spec) return { ok: false, error: `${record.id} 没有记录来源文件(不是用 cad_studio_assembly 建的)` }
3521
+ const name = String(part ?? '').trim()
3522
+ const next = String(path ?? '').trim()
3523
+ if (!name) return { ok: false, error: 'relink 需要 part(零件名)' }
3524
+ if (!next) return { ok: false, error: 'relink 需要 path(新的文件路径)' }
3525
+ const idx = record.spec.parts.findIndex((p) => p.name === name)
3526
+ if (idx < 0) return { ok: false, error: `这个装配里没有零件:${name}(有 ${record.spec.parts.map((p) => p.name).join(', ')})` }
3527
+ if (!existsSync(next)) return { ok: false, error: `文件不存在:${next}` }
3528
+ const before = { ...record.spec.parts[idx] }
3529
+ record.spec.parts[idx] = { ...before, path: next }
3530
+ const py = assemblyScript(record.spec.parts, record.spec.instances, '', false, false)
3531
+ const out = await bridge.run(py, { title: record.title, docKey: `asm:${record.id}` })
3532
+ if (!out.ok || !out.sceneId) {
3533
+ record.spec.parts[idx] = before // a bad file must not leave the model pointing at it
3534
+ return { ok: false, error: out.error ?? '重新读取文件失败', stderr: out.stderr ?? '' }
3535
+ }
3536
+ const scene = bridge.scenes.get(out.sceneId)
3537
+ if (!scene) {
3538
+ record.spec.parts[idx] = before
3539
+ return { ok: false, error: '重新读取后没有拿到场景' }
3540
+ }
3541
+ bridge.rebaseAssembly(record, { title: record.title, sceneId: out.sceneId, scene })
3542
+ const published = await bridge.republishAssembly(record)
3543
+ return {
3544
+ ok: true,
3545
+ assembly: record.id,
3546
+ sceneId: published.id,
3547
+ part: name,
3548
+ from: before.path,
3549
+ to: next,
3550
+ instances: record.spec.instances.length,
3551
+ volume: round6(Number(scene.parts.find((p) => p.id === name)?.volume ?? 0)),
3552
+ missingParts: specRows(record).filter((f) => !f.exists).map((f) => f.part),
3553
+ }
3554
+ }
3555
+
3556
+ tool({
3557
+ name: 'cad_studio_deps',
3558
+ description: 'List the part files a model was built from (existence, size, mtime, which instances use each) or repoint one of them with relink and rebuild the model in place. Only assemblies record their sources; a feature-built part has none.',
3559
+ parameters: {
3560
+ type: 'object',
3561
+ properties: {
3562
+ action: { type: 'string', enum: ['list', 'relink'], description: 'Default: list.' },
3563
+ assembly: { type: 'string', description: 'Assembly id (asm-1) or unique title. Omitted: every assembly for `list`, newest for `relink`.' },
3564
+ part: { type: 'string', description: 'Part name to repoint (relink).' },
3565
+ path: { type: 'string', description: 'New file path for that part (relink).' },
3566
+ },
3567
+ additionalProperties: false,
3568
+ },
3569
+ output: {
3570
+ schema: { type: 'object', properties: { ok: { type: 'boolean' }, models: { type: 'array' }, missing: { type: 'number' } } },
3571
+ render: (_a, v) => [{ type: 'text', text: JSON.stringify(v, null, 2) }],
3572
+ },
3573
+ execute: async ({ action, assembly, part, path }) => {
3574
+ const mode = action ?? 'list'
3575
+ if (mode === 'list') {
3576
+ if (!assembly) await bridge.hydrateAssemblies()
3577
+ const records = assembly
3578
+ ? [(() => { try { return findAssembly(assembly) } catch { return null } })()].filter(Boolean)
3579
+ : [...bridge.assemblies.values()]
3580
+ if (!records.length) return { ok: false, error: assembly ? `没有这个装配:${assembly}` : '还没有装配' }
3581
+ const models = records.map((r) => {
3582
+ const files = specRows(r)
3583
+ return {
3584
+ assembly: r.id,
3585
+ title: r.title,
3586
+ sceneId: r.sceneId,
3587
+ tracked: Boolean(r.spec),
3588
+ files,
3589
+ missingParts: files.filter((f) => !f.exists).map((f) => f.part),
3590
+ }
3591
+ })
3592
+ const missing = models.reduce((n, m) => n + m.missingParts.length, 0)
3593
+ return { ok: true, models, missing }
3594
+ }
3595
+ return relinkPart({ assembly, part, path })
3596
+ },
3597
+ })
3598
+
3448
3599
  tool({
3449
3600
  name: 'cad_studio_joint',
3450
3601
  description: 'Declare, list or remove joints on a published assembly. A revolute joint rotates its instance about (axis, origin); a linear joint slides it along axis. Driving a joint republishes the scene.',
@@ -4744,6 +4895,37 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
4744
4895
  return send(200, JSON.stringify({ ok: false, error: String(error?.message ?? error) }))
4745
4896
  }
4746
4897
  }
4898
+ if (url.pathname === `${ROUTE_PREFIX}/deps`) {
4899
+ // What the panel shows under "来源文件": which STEP each part came from
4900
+ // and whether it is still there.
4901
+ const records = [...(await bridge.hydrateAssemblies()).values()]
4902
+ const models = records.map((r) => {
4903
+ const files = (r.spec?.parts ?? []).map((p) => {
4904
+ let exists = false
4905
+ let bytes = 0
4906
+ let modified = ''
4907
+ try {
4908
+ const st = statSync(p.path)
4909
+ exists = st.isFile()
4910
+ bytes = st.size
4911
+ modified = new Date(st.mtimeMs).toISOString()
4912
+ } catch {}
4913
+ return { part: p.name, path: p.path, exists, bytes, modified }
4914
+ })
4915
+ return { assembly: r.id, title: r.title, tracked: Boolean(r.spec), files, missingParts: files.filter((f) => !f.exists).map((f) => f.part) }
4916
+ })
4917
+ return send(200, JSON.stringify({ ok: true, models }))
4918
+ }
4919
+ if (url.pathname === `${ROUTE_PREFIX}/relink` && req.method === 'POST') {
4920
+ const body = await bodyOf()
4921
+ if (!body || typeof body.part !== 'string' || typeof body.path !== 'string') return send(400, JSON.stringify({ error: 'bad request' }))
4922
+ try {
4923
+ const out = await relinkPart({ assembly: body.assembly, part: body.part, path: body.path })
4924
+ return send(200, JSON.stringify(out))
4925
+ } catch (error) {
4926
+ return send(200, JSON.stringify({ ok: false, error: String(error?.message ?? error) }))
4927
+ }
4928
+ }
4747
4929
  if (url.pathname === `${ROUTE_PREFIX}/doctor`) {
4748
4930
  bridge.refresh()
4749
4931
  return send(200, JSON.stringify(diagnose(bridge, resolved)))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cad-studio",
3
- "version": "0.23.0",
3
+ "version": "0.24.0",
4
4
  "type": "module",
5
5
  "description": "CAD Studio — FreeCAD 桥(给 AI 的 14 个工具)+ Web 右栏 3D 面板:建模/装配/关节运动/出图/多页签查看",
6
6
  "exports": {