dsh-cad-studio 0.7.0 → 0.8.1

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 +55 -0
  2. package/client.js +196 -3
  3. package/index.js +321 -35
  4. package/package.json +1 -1
package/README.md CHANGED
@@ -138,6 +138,10 @@ npm 包:<https://www.npmjs.com/package/dsh-cad-studio>(`dsh plugin` / DSH
138
138
 
139
139
  `rot` 是行主序 3×3,`translate` 是 mm。几何按**逐面三角化**,平面与孔壁不共享顶点(避免法线平均出暗色扇形)。
140
140
 
141
+ ### 视图撤销
142
+
143
+ 透明度、颜色、显隐、线框这些**外观改动**也进撤销栈(服务端 `doc.undo` 只管文档结构,管不到它们):同一目标 1.5 s 内的连续拖动合并成一条,切场景清空,最多 40 步。面板「活跃」时(焦点在面板内,或 8 s 内点过面板)按 `Ctrl/Cmd+Z` 撤销、`Shift+Ctrl/Cmd+Z` 或 `Ctrl+Y` 重做;视口右下角还有一对 ↶ / ↷ 按钮,没东西可撤销时是灰的。输入框里的 `Ctrl+Z` 不劫持,「特征」页签里仍归文档撤销。
144
+
141
145
  ## 开发
142
146
 
143
147
  ```bash
@@ -168,3 +172,54 @@ node scripts/shots.mjs --url http://127.0.0.1:3201 --token-file /tmp/dev-token.t
168
172
  ## License
169
173
 
170
174
  MIT
175
+
176
+ ## 安装即用 与 环境自检
177
+
178
+ 插件本体零依赖(只有 JS + three.js),但**几何内核是外部程序**:`freecadcmd`(约 213 MB,
179
+ 按平台编译,LGPL)。这是唯一一个「不能安装即用」的必要依赖,所以它必须有引导:
180
+
181
+ - **面板内引导**:内核缺失时,面板主体不是空白视口,而是三步卡片——① 点「安装 FreeCAD」
182
+ (apt/dnf/pacman/brew 自动识别,非 root 会显示原因与手抄命令)② 装完点「重新检测」
183
+ ③ 装在非标准位置就配 `freecadPath`。装好后面板自动恢复,无需重启。
184
+ - **给 AI 的自检**:`cad_studio_doctor` 返回每一项前置条件的 `ok / detail / fix` 与
185
+ 当前能力开关(modeling / assembly / drawing / measure / export / incremental);
186
+ `cad_studio_setup` 负责实际安装。**报错先自检**,别把环境问题当成模型问题。
187
+ - **可选能力**:全部随内核可用,没有第二个需要单独安装的可选项;出图(HLR→SVG)、
188
+ 测量、STEP/STL 导出都在进程内完成。若将来引入外部可选件,同样走「状态检测 + 安装引导」。
189
+
190
+ ## 特征挂在面上(`at.ref`)
191
+
192
+ 图元的位置可以写成一个面选择器加偏移,而不是绝对坐标:
193
+
194
+ ```json
195
+ {"kind": "fuse", "with": {"kind": "cylinder", "r": 10, "h": 12,
196
+ "at": {"ref": {"axis": "Z", "mode": "aligned", "dir": "+", "type": "plane"},
197
+ "offset": [0, 0, -6]}}}
198
+ ```
199
+
200
+ 板子从 16 厚改到 30 厚,凸台跟着顶面走(实测总面积增量恒为 100×80×14 = 112000 mm³)。
201
+ 选择器选不中时会**明确报错**(`at.ref 没有选中任何面:{…}(当前形状有 6 个面)`),
202
+ 不会静默落到原点。
203
+
204
+ ## 变量与表达式
205
+
206
+ 文档可以带一组命名的尺寸,特征的数值可以写表达式:
207
+
208
+ ```json
209
+ {"vars": {"w": 100, "d": 80, "t": 10},
210
+ "features": [
211
+ {"kind": "box", "size": ["w", "d", "t"]},
212
+ {"kind": "cut", "with": {"kind": "cylinder", "r": "w/10", "h": "t*3",
213
+ "at": ["w/2", "d/2", "-t"]}}]}
214
+ ```
215
+
216
+ 改 `w` 只需 `cad_studio_doc {"action":"update","vars":{"w":200}}`,所有依赖它的尺寸一起变
217
+ (100→200 实测体积 76858.41→147433.63 mm³)。表达式由 60 行 shunting-yard 在 JS 里算,
218
+ **绝不用 `eval`、也不交给 FreeCAD**:只接受 `数字 / 变量名 / + - * / ( ) / 一元负号`,
219
+ 出现引号或函数调用的字符串一律当字面量并随后被类型校验拒掉。
220
+
221
+ ## 依赖关系(哪些东西会互相影响)
222
+
223
+ `cad_studio_features {action:"list"}` 与 `cad_studio_doc {action:"show"}` 返回的 `graph.nodes`
224
+ 里,每个节点带 `dependsOn / dependents / anchored`:特征是顺序求值链(`f3` 依赖 `f2`),
225
+ `anchored: true` 表示它还跟着某个面走。这是如实的表示——我们不假装有一个比实际更复杂的图。
package/client.js CHANGED
@@ -61,6 +61,13 @@ window.__ModuleLoader__.load({
61
61
  boxShadow: '6px 0 18px rgba(0,0,0,.16)',
62
62
  },
63
63
  headBtn: { font: 'inherit', fontSize: 11, padding: '2px 7px', borderRadius: 5, border: '1px solid rgba(120,130,145,.45)', background: 'transparent', cursor: 'pointer', flex: 'none', lineHeight: 1.5 },
64
+ undoPair: { position: 'absolute', right: 8, bottom: 8, display: 'flex', gap: 4, zIndex: 12 },
65
+ undoBtn: (active) => ({
66
+ width: 24, height: 24, borderRadius: 6, border: '1px solid rgba(140,150,165,.34)',
67
+ background: active ? 'rgba(120,130,145,.16)' : 'transparent', color: 'inherit',
68
+ opacity: active ? 0.9 : 0.28, cursor: active ? 'pointer' : 'default',
69
+ fontSize: 14, padding: 0, display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
70
+ }),
64
71
  stats: { position: 'absolute', left: 8, bottom: 6, zIndex: 10, fontSize: 10, opacity: 0.62, pointerEvents: 'none', whiteSpace: 'nowrap', fontVariantNumeric: 'tabular-nums' },
65
72
  menu: { position: 'absolute', right: 6, top: 30, zIndex: 40, minWidth: 132, padding: 4, borderRadius: 6, border: '1px solid', boxShadow: '0 10px 26px rgba(0,0,0,.3)' },
66
73
  menuRow: { display: 'flex', gap: 4, padding: '3px 4px', flexWrap: 'wrap' },
@@ -80,6 +87,13 @@ window.__ModuleLoader__.load({
80
87
  modelRow: (active) => ({ display: 'flex', flexDirection: 'column', gap: 1, width: '100%', textAlign: 'left', padding: '5px 9px', border: 'none', background: active ? 'rgba(77,107,254,0.14)' : 'transparent', color: 'inherit', cursor: 'pointer', font: 'inherit', borderRadius: 0 }),
81
88
  modelName: { fontSize: 11.5, fontWeight: active => (active ? 600 : 400), overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
82
89
  modelMeta: { fontSize: 9.5, opacity: 0.55, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' },
90
+ guide: { display: 'flex', flexDirection: 'column', gap: 8, padding: '14px 12px', fontSize: 12, lineHeight: 1.6, overflowY: 'auto' },
91
+ guideTitle: { fontSize: 13, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 6 },
92
+ guideStep: { display: 'flex', gap: 7, alignItems: 'flex-start' },
93
+ guideNum: { flex: '0 0 auto', width: 16, height: 16, borderRadius: 8, marginTop: 2, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 10, fontWeight: 700, background: 'rgba(120,130,145,.18)' },
94
+ guideCode: { fontFamily: 'ui-monospace, monospace', fontSize: 11, padding: '3px 6px', borderRadius: 4, background: 'rgba(120,130,145,.14)', display: 'inline-block', marginTop: 2, userSelect: 'all', wordBreak: 'break-all' },
95
+ guideRow: { display: 'flex', gap: 6, alignItems: 'center', flexWrap: 'wrap', marginTop: 2 },
96
+ guideDot: (ok, required) => ({ flex: '0 0 auto', width: 6, height: 6, borderRadius: 3, marginTop: 6, background: ok ? '#2ea043' : (required ? '#e5534b' : '#e0a33a') }),
83
97
  installBox: { margin: '8px 9px 6px', padding: '8px 9px', borderRadius: 8, border: '1px solid rgba(224,163,58,.45)', background: 'rgba(224,163,58,.10)', fontSize: 11, lineHeight: 1.5 },
84
98
  installBtn: { marginTop: 6, width: '100%', padding: '5px 8px', borderRadius: 6, border: '1px solid rgba(77,107,254,.5)', background: 'rgba(77,107,254,.16)', color: 'inherit', fontSize: 11, cursor: 'pointer' },
85
99
  installHint: { opacity: 0.72, marginTop: 4, wordBreak: 'break-all' },
@@ -1246,6 +1260,7 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
1246
1260
  const [visibility, setVisibility] = useState({})
1247
1261
  const [error, setError] = useState('')
1248
1262
  const [installing, setInstalling] = useState('')
1263
+ const [installMsg, setInstallMsg] = useState('')
1249
1264
  // The visible scene, and the identity the per-scene view state is keyed
1250
1265
  // on: republishing one assembly (drive / explode) keeps its colours,
1251
1266
  // switching to another scene does not.
@@ -1545,6 +1560,7 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
1545
1560
  // One floating panel at a time, opened from the rail: 'parts' | 'view' |
1546
1561
  // 'models' | 'info' | '' (closed). Same icon again closes it.
1547
1562
  const [panel, setPanel] = useState('')
1563
+ useEffect(() => { panelRef.current = panel }, [panel])
1548
1564
  const theme = useTheme()
1549
1565
  // Colour overrides picked by hand in the tree. Two levels, because an
1550
1566
  // assembly can show one part many times: `inst` is one row, `part` is
@@ -1557,11 +1573,94 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
1557
1573
  const [opacities, setOpacities] = useState({})
1558
1574
  const [wireframes, setWireframes] = useState({})
1559
1575
 
1576
+ // ---- 视图撤销:透明度 / 颜色 / 显隐 / 线框 ----
1577
+ // 这些是纯客户端的外观改动,服务端的 doc.undo 管不到。用快照栈记录整组
1578
+ // 外观状态(JSON 串比较),同一目标 700 ms 内连续变动合并成一条,切场景清空。
1579
+ const panelRootRef = useRef(null)
1580
+ const panelRef = useRef('')
1581
+ const panelTouchRef = useRef(0)
1582
+ const lookSnap = JSON.stringify({ v: visibility, o: overrides, a: opacities, w: wireframes })
1583
+ const histRef = useRef({ undo: [], redo: [], last: lookSnap, scene: '', quiet: false, at: 0 })
1584
+ const [histTick, setHistTick] = useState(0)
1585
+ const applyLook = (snap) => {
1586
+ try {
1587
+ const parsed = JSON.parse(snap)
1588
+ histRef.current.quiet = true
1589
+ setVisibility(parsed.v || {})
1590
+ setOverrides(parsed.o || { inst: {}, part: {} })
1591
+ setOpacities(parsed.a || {})
1592
+ setWireframes(parsed.w || {})
1593
+ } catch (err) { /* 坏快照不该拖垮面板 */ }
1594
+ }
1595
+ const doUndo = () => {
1596
+ const h = histRef.current
1597
+ const entry = h.undo.pop()
1598
+ if (!entry) return
1599
+ h.redo.push(entry)
1600
+ applyLook(entry.before)
1601
+ setHistTick((t) => t + 1)
1602
+ }
1603
+ const doRedo = () => {
1604
+ const h = histRef.current
1605
+ const entry = h.redo.pop()
1606
+ if (!entry) return
1607
+ h.undo.push(entry)
1608
+ applyLook(entry.after)
1609
+ setHistTick((t) => t + 1)
1610
+ }
1611
+
1560
1612
  // Async callbacks (the 1.5 s poller) close over the render they were
1561
1613
  // created in, so the live look has to be read from a ref, not from state.
1562
1614
  // Declared after the states it mirrors: reading them earlier would put
1563
1615
  // `overrides` in its temporal dead zone during the first render.
1564
1616
  const visibleIdRef = useRef('')
1617
+ useEffect(() => {
1618
+ const h = histRef.current
1619
+ const now = Date.now()
1620
+ if (h.scene !== sceneKey) {
1621
+ h.scene = sceneKey
1622
+ h.undo = []
1623
+ h.redo = []
1624
+ h.last = lookSnap
1625
+ h.at = 0
1626
+ setHistTick((t) => t + 1)
1627
+ return
1628
+ }
1629
+ if (h.quiet) { h.quiet = false; h.last = lookSnap; return }
1630
+ if (lookSnap === h.last) return
1631
+ const top = h.undo[h.undo.length - 1]
1632
+ if (top && now - h.at < 1500) top.after = lookSnap
1633
+ else {
1634
+ h.undo.push({ before: h.last, after: lookSnap })
1635
+ if (h.undo.length > 40) h.undo.shift()
1636
+ }
1637
+ h.redo = []
1638
+ h.last = lookSnap
1639
+ h.at = now
1640
+ setHistTick((t) => t + 1)
1641
+ }, [lookSnap, sceneKey])
1642
+
1643
+ useEffect(() => {
1644
+ const onKey = (event) => {
1645
+ const key = String(event.key || '').toLowerCase()
1646
+ if (!(event.ctrlKey || event.metaKey)) return
1647
+ if (key !== 'z' && key !== 'y') return
1648
+ const target = event.target
1649
+ const tag = target && target.tagName ? target.tagName.toLowerCase() : ''
1650
+ if (tag === 'input' || tag === 'textarea' || tag === 'select' || (target && target.isContentEditable)) return
1651
+ if (panelRef.current === 'features') return
1652
+ const host = panelRootRef.current
1653
+ const focused = document.activeElement
1654
+ const touched = Date.now() - panelTouchRef.current < 8000
1655
+ const inPanel = touched || Boolean(host && (host.contains(focused) || host.contains(target)))
1656
+ if (!inPanel) return
1657
+ event.preventDefault()
1658
+ if (key === 'y' || event.shiftKey) doRedo()
1659
+ else doUndo()
1660
+ }
1661
+ window.addEventListener('keydown', onKey)
1662
+ return () => window.removeEventListener('keydown', onKey)
1663
+ }, [])
1565
1664
  const lookRef = useRef({ visibility: {}, overrides: { inst: {}, part: {} }, opacities: {}, wireframes: {} })
1566
1665
  useEffect(() => { visibleIdRef.current = visibleId }, [visibleId])
1567
1666
  useEffect(() => {
@@ -2147,6 +2246,78 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
2147
2246
  }
2148
2247
  }
2149
2248
 
2249
+ const redetect = async () => {
2250
+ setInstallMsg('正在检测…')
2251
+ try {
2252
+ const res = await fetch(`${ROUTE}/state`, { headers: { accept: 'application/json' } })
2253
+ if (res.ok) setState(await res.json())
2254
+ const doc = await fetch(`${ROUTE}/doctor`, { headers: { accept: 'application/json' } })
2255
+ if (doc.ok) {
2256
+ const d = await doc.json()
2257
+ const bad = (d.checks || []).filter((c) => !c.ok)
2258
+ setInstallMsg(d.ready ? '检测通过,可以用了。' : (bad.length ? `${bad[0].label}:${bad[0].detail}` : '仍未就绪'))
2259
+ } else setInstallMsg('')
2260
+ } catch (e) {
2261
+ setInstallMsg(`检测失败:${String(e).slice(0, 120)}`)
2262
+ }
2263
+ }
2264
+
2265
+ const installNow = async () => {
2266
+ setInstallMsg('')
2267
+ await installFreecad()
2268
+ setInstallMsg(installing || '')
2269
+ try {
2270
+ const doc = await fetch(`${ROUTE}/doctor`, { headers: { accept: 'application/json' } })
2271
+ if (doc.ok) {
2272
+ const d = await doc.json()
2273
+ setInstallMsg(d.ready ? '装好了,正在重新读取模型…' : ((d.checks || []).filter((c) => !c.ok)[0] || {}).fix || '装完但仍未就绪')
2274
+ }
2275
+ } catch {}
2276
+ }
2277
+
2278
+ // Install-and-run promise: when the kernel is missing, the panel is a
2279
+ // three-step guide, not an empty viewport with a red dot somewhere else.
2280
+ const diagChecks = (state && state.diag && state.diag.checks) || []
2281
+ const guideNode = h('div', { key: 'guide', style: styles.guide, 'data-cad-guide': '1' }, [
2282
+ h('div', { key: 't', style: styles.guideTitle }, [h('span', { style: styles.guideDot(false, true) }), '需要 FreeCAD(唯一的外部依赖)']),
2283
+ h('div', { key: 'why', style: { opacity: 0.75, fontSize: 11 } }, `几何内核不随插件分发(约 213 MB,按平台编译)。装好之后这个面板就能用,无需再配置。`),
2284
+ h('div', { key: 's1', style: styles.guideStep }, [
2285
+ h('span', { key: 'n', style: styles.guideNum }, '1'),
2286
+ h('div', { key: 'b' }, [
2287
+ h('div', { key: 'l' }, setup.canInstall ? `点下面的按钮自动安装(${setup.packageManager || '系统包管理器'})` : '用系统的包管理器安装'),
2288
+ setup.command ? h('div', { key: 'c', style: styles.guideCode }, setup.reason ? `${setup.command} # ${setup.reason}` : setup.command) : null,
2289
+ ]),
2290
+ ]),
2291
+ h('div', { key: 's2', style: styles.guideStep }, [
2292
+ h('span', { key: 'n', style: styles.guideNum }, '2'),
2293
+ h('div', { key: 'b' }, [h('div', { key: 'l' }, '装完点「重新检测」;也可以直接装好再来,面板每次打开都会自检'),]),
2294
+ ]),
2295
+ h('div', { key: 's3', style: styles.guideStep }, [
2296
+ h('span', { key: 'n', style: styles.guideNum }, '3'),
2297
+ h('div', { key: 'b' }, [
2298
+ h('div', { key: 'l' }, '装在非标准位置?配置 freecadPath 指到 freecadcmd 即可(探测顺序:配置 → /usr/bin → /usr/local/bin → /opt/freecad → macOS app)'),
2299
+ ]),
2300
+ ]),
2301
+ h('div', { key: 'row', style: styles.guideRow }, [
2302
+ h('button', {
2303
+ key: 'install',
2304
+ type: 'button',
2305
+ style: styles.installBtn,
2306
+ 'data-cad-install': '1',
2307
+ disabled: installing !== '' || !setup.canInstall,
2308
+ onClick: installNow,
2309
+ }, installing || (setup.canInstall ? '安装 FreeCAD' : '需要 root 才能自动安装')),
2310
+ h('button', {
2311
+ key: 'recheck',
2312
+ type: 'button',
2313
+ style: styles.microBtn,
2314
+ 'data-cad-recheck': '1',
2315
+ onClick: () => { redetect() },
2316
+ }, '重新检测'),
2317
+ ]),
2318
+ installMsg ? h('div', { key: 'msg', style: { fontSize: 11, opacity: 0.8, whiteSpace: 'pre-wrap' }, 'data-cad-install-msg': '1' }, installMsg) : null,
2319
+ ])
2320
+
2150
2321
  const installNode = runtime.available
2151
2322
  ? null
2152
2323
  : h('div', { key: 'install', style: styles.installBox, 'data-cad-install-box': '1' }, [
@@ -2412,6 +2583,11 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
2412
2583
  h('span', { key: 'k', style: styles.infoKey }, key),
2413
2584
  h('span', { key: 'v', style: { ...styles.infoVal, maxWidth: '65%', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }, title: value }, value),
2414
2585
  ])),
2586
+ ...diagChecks.map((chk) => h('div', { key: `diag-${chk.id}`, style: { ...styles.infoRow, alignItems: 'flex-start' }, 'data-cad-diag': chk.id }, [
2587
+ h('span', { key: 'd', style: styles.guideDot(chk.ok, chk.required) }),
2588
+ h('span', { key: 'k', style: { ...styles.infoKey, maxWidth: '46%', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }, title: chk.label }, chk.label),
2589
+ h('span', { key: 'v', style: { ...styles.infoVal, maxWidth: '52%', whiteSpace: 'normal' }, title: chk.fix || chk.detail }, chk.ok ? chk.detail : (chk.fix || chk.detail)),
2590
+ ])),
2415
2591
  ...(installNode ? [installNode] : []),
2416
2592
  ]
2417
2593
  : null
@@ -2426,7 +2602,7 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
2426
2602
  { id: 'info', label: '模型信息' },
2427
2603
  ]
2428
2604
 
2429
- return h('div', { style: styles.root, 'data-cad-panel-root': '1' }, [
2605
+ return h('div', { style: styles.root, 'data-cad-panel-root': '1', onMouseDown: () => { panelTouchRef.current = Date.now() } }, [
2430
2606
  h('div', {
2431
2607
  key: 'head',
2432
2608
  style: styles.head,
@@ -2538,8 +2714,25 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
2538
2714
  onClick: () => { setAddOpen(false); setPanel((p) => (p === item.id ? '' : item.id)) },
2539
2715
  }, h(RailIcon, { name: item.id })))),
2540
2716
  h('div', { key: 'main', style: { flex: '1 1 auto', minWidth: 0, position: 'relative', display: 'flex', flexDirection: 'column' } }, [
2541
- payload
2542
- ? h('div', { key: 'stage', style: styles.stage }, h(Viewport, { payload, visibility, options: { ...display, overrides, opacities, wireframes, restoreCamera: pendingCameraRef.current, onPick: pickInViewport }, handleRef: viewportRef }))
2717
+ !runtime.available
2718
+ ? guideNode
2719
+ : payload
2720
+ ? h('div', { key: 'stage', style: styles.stage }, [
2721
+ h(Viewport, { payload, visibility, options: { ...display, overrides, opacities, wireframes, restoreCamera: pendingCameraRef.current, onPick: pickInViewport }, handleRef: viewportRef }),
2722
+ h('div', { key: 'undo', style: styles.undoPair, ref: panelRootRef }, [
2723
+ h('button', {
2724
+ key: 'u', type: 'button', style: styles.undoBtn(histRef.current.undo.length > 0),
2725
+ title: histRef.current.undo.length ? '撤销上一次外观改动' : '没有可撤销的改动',
2726
+ 'aria-label': '撤销外观改动', 'data-cad-undo': histRef.current.undo.length,
2727
+ onClick: doUndo,
2728
+ }, '↶'),
2729
+ h('button', {
2730
+ key: 'r', type: 'button', style: styles.undoBtn(histRef.current.redo.length > 0),
2731
+ title: '重做外观改动', 'aria-label': '重做外观改动', 'data-cad-redo': histRef.current.redo.length,
2732
+ onClick: doRedo,
2733
+ }, '↷'),
2734
+ ]),
2735
+ ])
2543
2736
  : h('div', { key: 'empty', style: styles.empty }, '还没有模型。让 AI 跑一次 FreeCAD 脚本或打开一个 STEP 文件,这里会自动显示。'),
2544
2737
  picked && panel !== 'parts'
2545
2738
  ? h('button', {
package/index.js CHANGED
@@ -14,7 +14,7 @@
14
14
  * GET /cad-studio/client.js the panel bundle (dev-mode serving)
15
15
  */
16
16
  import { spawn, spawnSync } from 'node:child_process'
17
- import { existsSync, readdirSync, statSync, rmSync } from 'node:fs'
17
+ import { existsSync, mkdirSync, readdirSync, rmSync, statSync, statfsSync, writeFileSync } from 'node:fs'
18
18
  import crypto from 'node:crypto'
19
19
  import { mkdtemp, mkdir, readdir, readFile, rm, stat, unlink, writeFile } from 'node:fs/promises'
20
20
  import { tmpdir } from 'node:os'
@@ -110,6 +110,89 @@ function setupStatus(bridge, { withVersion = true } = {}) {
110
110
  }
111
111
 
112
112
  /** Install FreeCAD through the detected packager; returns a plain outcome. */
113
+ /**
114
+ * "Install and it works" is the product promise; this is the function that
115
+ * tells the truth about whether we can keep it. Every check says what is wrong
116
+ * AND what to do about it, so the panel never shows a dead end.
117
+ */
118
+ function diagnose(bridge, cfg = {}) {
119
+ const kernel = setupStatus(bridge, { withVersion: true })
120
+ const dir = FreeCadBridge.dataDir
121
+ const checks = []
122
+ checks.push({
123
+ id: 'kernel',
124
+ label: '几何内核(FreeCAD / OCCT)',
125
+ required: true,
126
+ ok: kernel.available === true,
127
+ detail: kernel.available ? [kernel.binary, kernel.version].filter(Boolean).join(' · ') : '没有找到 freecadcmd',
128
+ fix: kernel.available ? '' : (kernel.canInstall
129
+ ? '点「安装 FreeCAD」自动装(需要 root),或手动执行:' + (kernel.command || 'apt install freecad')
130
+ : (kernel.reason || '请手动安装 FreeCAD,再把 freecadPath 指到 freecadcmd')),
131
+ action: kernel.available ? '' : (kernel.canInstall ? 'install' : ''),
132
+ packageManager: kernel.packageManager || '',
133
+ })
134
+ let writable = false
135
+ try {
136
+ mkdirSync(dir, { recursive: true })
137
+ const probe = join(dir, '.write-probe')
138
+ writeFileSync(probe, '1')
139
+ rmSync(probe, { force: true })
140
+ writable = true
141
+ } catch {}
142
+ checks.push({
143
+ id: 'datadir',
144
+ label: '数据目录(场景与缓存)',
145
+ required: true,
146
+ ok: writable,
147
+ detail: writable ? dir : `${dir}(不可写)`,
148
+ fix: writable ? '' : '把这个目录改成可写,或用环境变量 TMPDIR 指到可写位置',
149
+ })
150
+ let freeMB = null
151
+ try { const st = statfsSync(dir); freeMB = Math.round((st.bavail * st.bsize) / 1048576) } catch {}
152
+ checks.push({
153
+ id: 'disk',
154
+ label: '可用磁盘',
155
+ required: false,
156
+ ok: freeMB === null || freeMB > 500,
157
+ detail: freeMB === null ? '无法读取' : `${freeMB} MB`,
158
+ fix: freeMB !== null && freeMB <= 500 ? '剩余空间不足 500 MB,重建大模型可能失败' : '',
159
+ })
160
+ const modelsDir = cfg.modelsDir || ''
161
+ checks.push({
162
+ id: 'models',
163
+ label: '模型目录',
164
+ required: false,
165
+ ok: true,
166
+ detail: modelsDir || '跟随会话工作区(<cwd>/cad-models)',
167
+ fix: '',
168
+ })
169
+ const ready = checks.filter((c) => c.required).every((c) => c.ok)
170
+ return {
171
+ ready,
172
+ kernel,
173
+ checks,
174
+ // What the plugin can actually do right now. The panel greys out the rest
175
+ // instead of letting a click fail deep inside a spawn.
176
+ capabilities: {
177
+ modeling: ready,
178
+ assembly: ready,
179
+ drawing: ready,
180
+ measure: ready,
181
+ export: ready,
182
+ incremental: ready,
183
+ },
184
+ }
185
+ }
186
+
187
+ const renderDoctor = (v) => {
188
+ const lines = [`ready: ${v.ready ? 'yes' : 'no'}`]
189
+ if (v.kernel) lines.push(`kernel: ${v.kernel}`)
190
+ for (const c of v.checks || []) lines.push(`- ${c}`)
191
+ const caps = Object.entries(v.capabilities || {}).map(([k, ok]) => `${k}=${ok ? 'yes' : 'no'}`).join(' ')
192
+ if (caps) lines.push(`capabilities: ${caps}`)
193
+ return lines.join('\n')
194
+ }
195
+
113
196
  function installFreeCad(bridge, { timeoutMs = 900000 } = {}) {
114
197
  const before = setupStatus(bridge)
115
198
  if (before.available) return { ok: true, alreadyInstalled: true, ...before, log: '' }
@@ -271,19 +354,130 @@ function bboxCenterOfInstances(parts, instances) {
271
354
  function normalizeJoint(record, spec) {
272
355
  const inst = record.base.find((b) => b.name === spec.instance)
273
356
  if (!inst) throw new Error(`装配里没有这个实例:${spec.instance}`)
274
- const type = spec.type === 'linear' ? 'linear' : 'revolute'
275
- const fallbackAxis = type === 'linear' ? [1, 0, 0] : [0, 0, 1]
357
+ // Five declared joint kinds, all driven along their single declared axis.
358
+ // This is deliberately not a constraint solver: a joint states which DOF the
359
+ // AI/user may drive, and the panel exposes exactly that one number.
360
+ // revolute rotate about axis linear slide along axis
361
+ // cylindrical rotate about axis planar slide in the plane
362
+ // ball rotate about axis (free direction, single driven angle)
363
+ const JOINTS = ['revolute', 'linear', 'cylindrical', 'planar', 'ball']
364
+ const type = JOINTS.includes(spec.type) ? spec.type : 'revolute'
365
+ const slidey = type === 'linear' || type === 'planar'
366
+ const fallbackAxis = slidey ? [1, 0, 0] : [0, 0, 1]
276
367
  const axis = normVec(Array.isArray(spec.axis) && spec.axis.length === 3 ? spec.axis : fallbackAxis)
277
368
  // Rotating about the instance's own centre is the useful default (a spinning
278
369
  // wheel); a hinge passes an explicit origin on the edge.
279
370
  const origin = Array.isArray(spec.origin) && spec.origin.length === 3 ? spec.origin.map(Number) : inst.center.slice()
280
- const min = Number.isFinite(spec.min) ? Number(spec.min) : type === 'linear' ? -1000 : -180
281
- const max = Number.isFinite(spec.max) ? Number(spec.max) : type === 'linear' ? 1000 : 180
371
+ const min = Number.isFinite(spec.min) ? Number(spec.min) : slidey ? -1000 : -180
372
+ const max = Number.isFinite(spec.max) ? Number(spec.max) : slidey ? 1000 : 180
282
373
  const value = Math.min(max, Math.max(min, Number.isFinite(spec.value) ? Number(spec.value) : 0))
374
+ // A cylindrical joint has two DOF but we drive one number; the other is a
375
+ // fixed second parameter so the geometry stays deterministic.
376
+
283
377
  const id = typeof spec.id === 'string' && spec.id.trim() ? spec.id.trim() : `${type}-${record.joints.length + 1}`
284
378
  return { id, instance: spec.instance, type, axis, origin, min, max, value }
285
379
  }
286
380
 
381
+ /**
382
+ * Variables and expressions (DESIGN §7 Phase 4).
383
+ *
384
+ * Dimensions are allowed to be expressions over the document's `vars`, e.g.
385
+ * `"w*2 + 10"`. They are evaluated here, in JS, with a 60-line shunting-yard —
386
+ * deliberately NOT by handing the string to FreeCAD or to `eval`: a model file
387
+ * that arrives from someone else must not be able to execute anything.
388
+ */
389
+ /** `vars` is a flat bag of named dimensions; anything else is ignored. */
390
+ function normalizeVars(raw, base = {}) {
391
+ const out = { ...base }
392
+ if (raw === null) return {}
393
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return out
394
+ for (const [k, v] of Object.entries(raw)) {
395
+ if (!/^[A-Za-z_]\w{0,40}$/.test(k)) continue
396
+ if (v === null) { delete out[k]; continue }
397
+ if (Number.isFinite(Number(v))) out[k] = Number(v)
398
+ }
399
+ return out
400
+ }
401
+
402
+ const EXPR_OK = /^[0-9A-Za-z_+\-*/(). \t]*$/
403
+
404
+ function evalExpression(src, vars) {
405
+ const text = String(src).trim()
406
+ if (!EXPR_OK.test(text)) throw new Error(`表达式里有不支持的字符:${text}`)
407
+ const tokens = text.match(/\d+\.?\d*|[A-Za-z_]\w*|[+\-*/()]/g) || []
408
+ const out = []
409
+ const ops = []
410
+ const prec = { '+': 1, '-': 1, '*': 2, '/': 2 }
411
+ const apply = (op) => {
412
+ const b = out.pop()
413
+ const a = out.pop()
414
+ if (a === undefined || b === undefined) throw new Error(`表达式不完整:${text}`)
415
+ out.push(op === '+' ? a + b : op === '-' ? a - b : op === '*' ? a * b : a / b)
416
+ }
417
+ let prev = ''
418
+ for (const tk of tokens) {
419
+ if (tk === '-' && (prev === '' || prev === '(' || prec[prev])) {
420
+ // Unary minus: "−t" is 0 − t, not a syntax error.
421
+ out.push(0)
422
+ ops.push('-')
423
+ prev = '-'
424
+ continue
425
+ }
426
+ if (/^\d/.test(tk)) out.push(Number(tk))
427
+ else if (/^[A-Za-z_]/.test(tk)) {
428
+ const v = vars?.[tk]
429
+ if (!Number.isFinite(v)) throw new Error(`表达式里的变量没有定义或不是数字:${tk}`)
430
+ out.push(Number(v))
431
+ } else if (tk === '(') ops.push(tk)
432
+ else if (tk === ')') {
433
+ while (ops.length && ops[ops.length - 1] !== '(') apply(ops.pop())
434
+ if (ops.pop() !== '(') throw new Error(`括号不配对:${text}`)
435
+ prev = tk
436
+ } else {
437
+ while (ops.length && prec[ops[ops.length - 1]] >= prec[tk]) apply(ops.pop())
438
+ ops.push(tk)
439
+ }
440
+ }
441
+ while (ops.length) {
442
+ const op = ops.pop()
443
+ if (op === '(') throw new Error(`括号不配对:${text}`)
444
+ apply(op)
445
+ }
446
+ if (out.length !== 1 || !Number.isFinite(out[0])) throw new Error(`表达式算不出数值:${text}`)
447
+ return out[0]
448
+ }
449
+
450
+ // Keys whose strings are vocabulary, not arithmetic: a `kind: "cylinder"` or a
451
+ // selector's `axis: "Z"` must never be mistaken for an expression.
452
+ const EXPR_SKIP_KEYS = new Set(['kind', 'type', 'axis', 'mode', 'dir', 'pick', 'label', 'name', 'ref'])
453
+
454
+ /** Deep-walk feature params and resolve any expression string. */
455
+ function resolveParams(value, vars, where) {
456
+ if (typeof value === 'string') {
457
+ // A string is an expression only when it is plain arithmetic AND every
458
+ // identifier in it is a declared var. Selectors ("Z", "aligned", "+") and
459
+ // enums therefore pass through untouched.
460
+ const text = value.trim()
461
+ if (!text || !/^[\w.\s+\-*/()]+$/.test(text)) return value
462
+ const ids = text.match(/[A-Za-z_]\w*/g) || []
463
+ const known = ids.filter((id) => Number.isFinite(vars?.[id]))
464
+ if (ids.length && !known.length) return value
465
+ if (!ids.length && !/[+\-*/]/.test(text)) return /^\d+(\.\d+)?$/.test(text) ? Number(text) : value
466
+ try { return evalExpression(text, vars) } catch (error) {
467
+ throw new Error(`${where}:${error.message}`)
468
+ }
469
+ }
470
+ if (Array.isArray(value)) return value.map((v) => resolveParams(v, vars, where))
471
+ if (value && typeof value === 'object') {
472
+ const out = {}
473
+ for (const [k, v] of Object.entries(value)) {
474
+ out[k] = EXPR_SKIP_KEYS.has(k) ? v : resolveParams(v, vars, where)
475
+ }
476
+ return out
477
+ }
478
+ return value
479
+ }
480
+
287
481
  /** Base placements + joints + explode → a scene payload ready to publish. */
288
482
  function assembleScene(record) {
289
483
  const explode = record.explode ?? 0
@@ -293,7 +487,7 @@ function assembleScene(record) {
293
487
  for (const joint of record.joints) {
294
488
  if (joint.instance !== base.name) continue
295
489
  const axis = normVec(joint.axis)
296
- if (joint.type === 'linear') {
490
+ if (joint.type === 'linear' || joint.type === 'planar') {
297
491
  translate = addVec(translate, scaleVec(axis, joint.value))
298
492
  } else {
299
493
  const R = axisAngle(axis, joint.value)
@@ -365,6 +559,13 @@ class FreeCadBridge {
365
559
 
366
560
  refresh() {
367
561
  this.bin = probeBinary(this.getConfig().freecadPath)
562
+ // Version costs a spawn, so ask once per binary rather than every poll
563
+ // (the panel polls /state every 1.5 s).
564
+ if (this.bin && this.versionOf !== this.bin) {
565
+ this.versionOf = this.bin
566
+ try { this.kernelVersion = freecadVersion(this.bin) } catch { this.kernelVersion = '' }
567
+ }
568
+ if (!this.bin) { this.kernelVersion = ''; this.versionOf = '' }
368
569
  return this.bin
369
570
  }
370
571
 
@@ -421,7 +622,7 @@ class FreeCadBridge {
421
622
  const latest = this.latest
422
623
  if (latest) await writeFile(join(dir, 'scenes', `${latest.id}.json`), JSON.stringify(latest.scene), 'utf8')
423
624
  const pointer = {
424
- runtime: this.status(),
625
+ runtime: { ...this.status(), version: this.kernelVersion || '' },
425
626
  latest: latest ? { id: latest.id, title: latest.title, at: latest.at } : null,
426
627
  // Newest first, trimmed: the panel's model switcher reads this list.
427
628
  history: this.history.slice(0, 30),
@@ -918,9 +1119,28 @@ def _dir(x, d=(0.0, 0.0, 1.0)):
918
1119
  v = _v3(x, d)
919
1120
  return v if v.Length > 1e-9 else _v3(d, (0.0, 0.0, 1.0))
920
1121
 
921
- def _prim(op):
1122
+ def _anchor(_spec, _cur):
1123
+ # A feature can hang off a face instead of absolute coordinates:
1124
+ # "at": {"ref": {"axis":"Z","mode":"aligned","dir":"+","type":"plane"},
1125
+ # "offset": [10, 0, 0]}
1126
+ # The point is the face's centre plus the offset in world axes, so changing
1127
+ # the thickness upstream moves the hole with the face instead of leaving it
1128
+ # floating at the old Z.
1129
+ if not isinstance(_spec, dict) or "ref" not in _spec:
1130
+ return None
1131
+ if _cur is None:
1132
+ raise RuntimeError("at.ref 需要前面至少有一个已建好的实体")
1133
+ _hits = _sel(_cur, "face", _spec.get("ref") or {})
1134
+ if not _hits:
1135
+ raise RuntimeError("at.ref 没有选中任何面:%s" % json.dumps(_spec.get("ref"), ensure_ascii=False))
1136
+ _off = _spec.get("offset")
1137
+ return _center_of(_hits[0]) + (_v3(_off) if _off else Vector(0.0, 0.0, 0.0))
1138
+
1139
+ def _prim(op, _cur=None):
922
1140
  k = op.get("kind")
923
- at = _v3(op.get("at"))
1141
+ _at_spec = op.get("at")
1142
+ _anchored = _anchor(_at_spec, _cur) if isinstance(_at_spec, dict) else None
1143
+ at = _anchored if _anchored is not None else _v3(_at_spec)
924
1144
  if k == "box":
925
1145
  s = op.get("size") or [10, 10, 10]
926
1146
  return Part.makeBox(float(s[0]), float(s[1]), float(s[2]), at)
@@ -1089,7 +1309,7 @@ for _idx, _op in enumerate(_OPS):
1089
1309
  _snap = _shape
1090
1310
  try:
1091
1311
  if _k in ("box", "cylinder", "sphere", "cone", "torus", "extrude", "revolve"):
1092
- _s = _prim(_op)
1312
+ _s = _prim(_op, _shape)
1093
1313
  _shape = _s if _shape is None else _shape.fuse(_s)
1094
1314
  elif _k in ("fuse", "cut", "common"):
1095
1315
  # A U-shaped wall is one feature, not two: with takes a list, and
@@ -1098,7 +1318,7 @@ for _idx, _op in enumerate(_OPS):
1098
1318
  if not isinstance(_ws, (list, tuple)):
1099
1319
  _ws = [_ws]
1100
1320
  for _w in _ws:
1101
- _s = _prim(_w)
1321
+ _s = _prim(_w, _shape)
1102
1322
  _shape = _shape.fuse(_s) if _k == "fuse" else (_shape.cut(_s) if _k == "cut" else _shape.common(_s))
1103
1323
  elif _k == "fillet":
1104
1324
  _eds = _sel(_shape, "edge", _op.get("edges")) or list(_shape.Edges)
@@ -1466,6 +1686,26 @@ __out = {
1466
1686
  },
1467
1687
  })
1468
1688
 
1689
+ tool({
1690
+ name: 'cad_studio_doctor',
1691
+ description: 'Environment self-check for CAD Studio: reports every prerequisite (FreeCAD/OCCT kernel, data directory, disk space, model directory) with what is wrong, what to do about it, and which capabilities are currently available. Run this before blaming a modelling failure on the model.',
1692
+ parameters: {
1693
+ type: 'object',
1694
+ properties: {},
1695
+ additionalProperties: false,
1696
+ },
1697
+ output: { schema: { type: 'object' }, render: (args, value) => [{ type: 'text', text: renderDoctor(value) }] },
1698
+ execute: async () => {
1699
+ const diag = diagnose(bridge, bridge.getConfig())
1700
+ return {
1701
+ ready: diag.ready,
1702
+ kernel: diag.kernel.available ? [diag.kernel.binary, diag.kernel.version].filter(Boolean).join(' · ') : '',
1703
+ checks: diag.checks.map((c) => `${c.ok ? 'ok' : (c.required ? 'FAIL' : 'warn')} ${c.label}: ${c.detail}${c.fix ? ` — ${c.fix}` : ''}`),
1704
+ capabilities: diag.capabilities,
1705
+ }
1706
+ },
1707
+ })
1708
+
1469
1709
  tool({
1470
1710
  name: 'cad_studio_setup',
1471
1711
  description: 'Check whether freecadcmd is installed and, when it is missing, install FreeCAD through the system package manager (apt/dnf/pacman/brew). action=check reports binary, version, package manager and the exact command; action=install runs it (needs root on apt) and re-probes afterwards.',
@@ -1899,13 +2139,13 @@ ${pair ? ` __out["distance"] = round((FreeCAD.Vector(${JSON.stringify(from)})
1899
2139
  assembly: { type: 'string', description: 'Assembly label for cad_studio_joint / cad_studio_drive / cad_studio_explode (defaults to the title).' },
1900
2140
  joints: {
1901
2141
  type: 'array',
1902
- description: 'Joints to declare up front: [{id?, instance, type:"revolute"|"linear", axis?, origin?, value?, min?, max?}]. Rotating about the instance centre is the default; pass origin for a hinge.',
2142
+ description: 'Joints to declare up front: [{id?, instance, type:"revolute"|"linear"|"cylindrical"|"planar"|"ball", axis?, origin?, value?, min?, max?}]. Rotating about the instance centre is the default; pass origin for a hinge.',
1903
2143
  items: {
1904
2144
  type: 'object',
1905
2145
  properties: {
1906
2146
  id: { type: 'string' },
1907
2147
  instance: { type: 'string' },
1908
- type: { type: 'string', enum: ['revolute', 'linear'] },
2148
+ type: { type: 'string', enum: ['revolute', 'linear', 'cylindrical', 'planar', 'ball'] },
1909
2149
  axis: { type: 'array', items: { type: 'number' } },
1910
2150
  origin: { type: 'array', items: { type: 'number' } },
1911
2151
  value: { type: 'number' },
@@ -2077,7 +2317,7 @@ if _TARGET:
2077
2317
  assembly: { type: 'string', description: 'Assembly id (asm-1) or its label. Default: newest.' },
2078
2318
  joint: { type: 'string', description: 'Joint id for remove.' },
2079
2319
  instance: { type: 'string', description: 'Instance name the joint moves (set).' },
2080
- type: { type: 'string', enum: ['revolute', 'linear'], description: 'Default: revolute.' },
2320
+ type: { type: 'string', enum: ['revolute', 'linear', 'cylindrical', 'planar', 'ball'], description: 'Default: revolute. cylindrical rotates and holds a fixed slide; planar/ball drive one number too (documented limitation).' },
2081
2321
  axis: { type: 'array', items: { type: 'number' }, description: 'Rotation/slide axis in world space. Default [0,0,1] revolute / [1,0,0] linear.' },
2082
2322
  origin: { type: 'array', items: { type: 'number' }, description: 'Point the rotation axis passes through. Default: the instance centre.' },
2083
2323
  value: { type: 'number', description: 'Current value in degrees (revolute) or mm (linear).' },
@@ -2240,6 +2480,10 @@ if _TARGET:
2240
2480
  // name so every caller keeps working. Reading an old file migrates it.
2241
2481
  if (doc.graph && Array.isArray(doc.graph.nodes)) doc.features = doc.graph.nodes
2242
2482
  doc.schema = 2
2483
+ // Named dimensions/expressions (schema 2): only finite numbers survive.
2484
+ doc.vars = doc.vars && typeof doc.vars === 'object' && !Array.isArray(doc.vars)
2485
+ ? Object.fromEntries(Object.entries(doc.vars).filter(([, v]) => Number.isFinite(v)))
2486
+ : {}
2243
2487
  doc.tip = typeof doc.tip === 'string' && doc.tip ? doc.tip : null
2244
2488
  doc.undo = Array.isArray(doc.undo) ? doc.undo : []
2245
2489
  doc.redo = Array.isArray(doc.redo) ? doc.redo : []
@@ -2303,7 +2547,8 @@ if _TARGET:
2303
2547
  if (stopAtSuppressed) ops.push({ kind: '__skip__', _id: f.id, _label: f.label || '' })
2304
2548
  continue
2305
2549
  }
2306
- ops.push({ kind: f.kind, ...(f.params ?? {}), _id: f.id, _label: f.label || '' })
2550
+ const where = `特征 ${f.id}${f.label ? `(${f.label})` : ''} ${f.kind}`
2551
+ ops.push({ kind: f.kind, ...resolveParams(f.params ?? {}, doc.vars, where), _id: f.id, _label: f.label || '' })
2307
2552
  }
2308
2553
  return ops
2309
2554
  }
@@ -2339,31 +2584,39 @@ if _TARGET:
2339
2584
  if (!cond) throw new Error(`${where}:${hint}`)
2340
2585
  }
2341
2586
  const tool = (v) => v && typeof v === 'object' && ['box', 'cylinder', 'sphere', 'cone', 'torus', 'extrude', 'revolve'].includes(String(v.kind))
2342
- const withs = params.with
2343
- if (kind === 'box') need(triple(params.size) && params.size.every(pos), '需要 size:[dx,dy,dz](三个正数)')
2344
- else if (kind === 'cylinder') need(pos(params.r) && pos(params.h), '需要 r>0 与 h>0')
2345
- else if (kind === 'sphere') need(pos(params.r), '需要 r>0')
2346
- else if (kind === 'cone') need(num(params.r1) && num(params.r2) && pos(params.h), '需要 r1 / r2 / h>0')
2347
- else if (kind === 'torus') need(pos(params.r1) && pos(params.r2), '需要 r1>0(主半径)与 r2>0(管半径)')
2587
+ // Expressions are legal in the document, numbers at validation time.
2588
+ let probe = params
2589
+ try { probe = resolveParams(params, doc.vars, where) } catch (error) { throw new Error(`${where}:${error.message}`) }
2590
+ // `at` is either a point or an anchor on a face ({ref, offset}).
2591
+ if (probe.at && typeof params.at === 'object' && !Array.isArray(probe.at)) {
2592
+ need(probe.at.ref && typeof params.at.ref === 'object', 'at.ref 需要一个面选择器(如 {axis:"Z",mode:"aligned",dir:"+",type:"plane"})')
2593
+ need(probe.at.offset === undefined || triple(probe.at.offset), 'at.offset 需要 [x,y,z]')
2594
+ }
2595
+ const withs = probe.with
2596
+ if (kind === 'box') need(triple(probe.size) && probe.size.every(pos), '需要 size:[dx,dy,dz](三个正数)')
2597
+ else if (kind === 'cylinder') need(pos(probe.r) && pos(probe.h), '需要 r>0 与 h>0')
2598
+ else if (kind === 'sphere') need(pos(probe.r), '需要 r>0')
2599
+ else if (kind === 'cone') need(num(probe.r1) && num(probe.r2) && pos(probe.h), '需要 r1 / r2 / h>0')
2600
+ else if (kind === 'torus') need(pos(probe.r1) && pos(probe.r2), '需要 r1>0(主半径)与 r2>0(管半径)')
2348
2601
  else if (kind === 'extrude') {
2349
- const points = Array.isArray(params.points) ? params.points : []
2602
+ const points = Array.isArray(probe.points) ? probe.points : []
2350
2603
  need(points.length >= 3, '需要 points(至少 3 个 [x,y] 或 [x,y,z] 剖面点)')
2351
2604
  need(points.every((q) => Array.isArray(q) && q.length >= 2 && q.slice(0, 3).every(num)), 'points 的每个点都要是数字数组')
2352
- need(pos(params.h) || triple(params.dir), '需要 h>0(沿 +Z 挤出)或 dir:[dx,dy,dz](任意方向)')
2605
+ need(pos(probe.h) || triple(probe.dir), '需要 h>0(沿 +Z 挤出)或 dir:[dx,dy,dz](任意方向)')
2353
2606
  } else if (kind === 'revolve') {
2354
- const points = Array.isArray(params.points) ? params.points : []
2607
+ const points = Array.isArray(probe.points) ? probe.points : []
2355
2608
  need(points.length >= 2, '需要 points(至少 2 个 [x,z] 剖面点)')
2356
2609
  } else if (kind === 'fuse' || kind === 'cut' || kind === 'common') {
2357
2610
  const list = Array.isArray(withs) ? withs : withs ? [withs] : []
2358
2611
  need(list.length > 0, `需要 with 子图元({kind:"box",size:[…]},或用数组一次减/并多个)`)
2359
2612
  need(list.every(tool), 'with 里的每一项都要是图元(box/cylinder/sphere/cone/torus/extrude/revolve),且带 kind')
2360
- } else if (kind === 'fillet') need(pos(params.r), '需要 r>0')
2361
- else if (kind === 'chamfer') need(pos(params.d), '需要 d>0')
2362
- else if (kind === 'shell') need(pos(params.t), '需要 t>0(壁厚)')
2363
- else if (kind === 'pattern_linear') need(triple(params.delta) && num(params.count) && params.count >= 2, '需要 delta:[dx,dy,dz] 与 count>=2')
2364
- else if (kind === 'pattern_circular') need(num(params.count) && params.count >= 2, '需要 count>=2')
2365
- else if (kind === 'translate') need(triple(params.v), '需要 v:[dx,dy,dz]')
2366
- else if (kind === 'rotate') need(num(params.deg), '需要 deg(角度)')
2613
+ } else if (kind === 'fillet') need(pos(probe.r), '需要 r>0')
2614
+ else if (kind === 'chamfer') need(pos(probe.d), '需要 d>0')
2615
+ else if (kind === 'shell') need(pos(probe.t), '需要 t>0(壁厚)')
2616
+ else if (kind === 'pattern_linear') need(triple(probe.delta) && num(probe.count) && probe.count >= 2, '需要 delta:[dx,dy,dz] 与 count>=2')
2617
+ else if (kind === 'pattern_circular') need(num(probe.count) && probe.count >= 2, '需要 count>=2')
2618
+ else if (kind === 'translate') need(triple(probe.v), '需要 v:[dx,dy,dz]')
2619
+ else if (kind === 'rotate') need(num(probe.deg), '需要 deg(角度)')
2367
2620
  return {
2368
2621
  id,
2369
2622
  kind,
@@ -2382,6 +2635,15 @@ if _TARGET:
2382
2635
  * Per-node status for the panel and for the caller: ok / failed / blocked /
2383
2636
  * skipped. Derived from what the kernel actually executed, not guessed.
2384
2637
  */
2638
+ // True when this step hangs off a face (`at.ref`) instead of absolute XYZ.
2639
+ const anchoredOn = (params) => {
2640
+ if (!params || typeof params !== 'object') return false
2641
+ const has = (v) => Boolean(v && typeof v === 'object' && v.ref)
2642
+ if (has(params.at)) return true
2643
+ const w = params.with
2644
+ return Array.isArray(w) ? w.some((x) => has(x?.at)) : has(w?.at)
2645
+ }
2646
+
2385
2647
  const graphView = (doc, out) => {
2386
2648
  const list = Array.isArray(doc.features) ? doc.features : []
2387
2649
  const errors = Array.isArray(out?.errors) ? out.errors : []
@@ -2402,7 +2664,19 @@ if _TARGET:
2402
2664
  if (executed !== null && i >= executed) { why = `因为 ${f.id} 没有执行`; return { ...base, status: 'blocked', message: why } }
2403
2665
  return { ...base, status: 'ok', message: '' }
2404
2666
  })
2405
- return { tip: doc.tip ?? null, nodes }
2667
+ // Dependencies are a chain, not a secret: features are evaluated in order
2668
+ // and each one consumes the shape the previous one produced. Saying so
2669
+ // out loud is what lets the panel answer "what breaks if I change this?"
2670
+ // without inventing a graph we do not have.
2671
+ const withDeps = nodes.map((n, i) => ({
2672
+ ...n,
2673
+ dependsOn: i > 0 ? [String(nodes[i - 1].id)] : [],
2674
+ dependents: i + 1 < nodes.length ? [String(nodes[i + 1].id)] : [],
2675
+ // An anchored primitive (`at.ref`) also follows the face it names, which
2676
+ // is the only non-sequential edge we support today.
2677
+ anchored: anchoredOn(list[i]?.params),
2678
+ }))
2679
+ return { tip: doc.tip ?? null, nodes: withDeps }
2406
2680
  }
2407
2681
 
2408
2682
  const rebuild = async (doc, dir, { note } = {}) => {
@@ -2752,7 +3026,7 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
2752
3026
  kind: doc.kind,
2753
3027
  params: doc.params,
2754
3028
  ...(typeof doc.script === 'string' ? { script: doc.script } : {}),
2755
- ...(doc.kind === 'features' ? { features: publicFeatures(doc) } : {}),
3029
+ ...(doc.kind === 'features' ? { features: publicFeatures(doc), graph: graphView(doc, { errors: [], executed: null }), tip: doc.tip ?? null, vars: doc.vars ?? {} } : {}),
2756
3030
  runs: doc.run ?? 0,
2757
3031
  updatedAt: doc.updatedAt ?? '',
2758
3032
  stats: doc.stats ?? null,
@@ -2777,6 +3051,9 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
2777
3051
  name: key,
2778
3052
  kind: 'features',
2779
3053
  features: [],
3054
+ // Vars must exist before the first feature is validated: dimensions
3055
+ // are allowed to be expressions over them.
3056
+ vars: normalizeVars(args.vars),
2780
3057
  params: args.params && typeof args.params === 'object' ? args.params : {},
2781
3058
  run: 0,
2782
3059
  createdAt: new Date().toISOString(),
@@ -2810,6 +3087,7 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
2810
3087
 
2811
3088
  if (action === 'update') {
2812
3089
  const doc = await readModel(args.name, dir)
3090
+ if (args.vars !== undefined) doc.vars = normalizeVars(args.vars, doc.vars)
2813
3091
  const before = {
2814
3092
  script: doc.script,
2815
3093
  params: JSON.parse(JSON.stringify(doc.params)),
@@ -2893,10 +3171,14 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
2893
3171
  try {
2894
3172
  const parsed = JSON.parse(await readFile(join(dir, 'state.json'), 'utf8'))
2895
3173
  const setup = setupStatus(bridge, { withVersion: false })
2896
- return send(200, JSON.stringify({ runtime, setup, config: { autoOpen: resolved.autoOpen }, latest: parsed.latest ?? null, lastSession: parsed.lastSession ?? '', assemblies: parsed.assemblies ?? [], running: bridge.running || 0, runningSession: bridge.runningSession || '' }))
3174
+ const diag = diagnose(bridge, resolved)
3175
+ diag.checks = diag.checks.map((c) => (c.id === 'kernel' ? { ...c, detail: runtime.available ? [runtime.binary, runtime.version].filter(Boolean).join(' · ') : c.detail } : c))
3176
+ return send(200, JSON.stringify({ runtime, setup, diag, config: { autoOpen: resolved.autoOpen }, latest: parsed.latest ?? null, lastSession: parsed.lastSession ?? '', assemblies: parsed.assemblies ?? [], running: bridge.running || 0, runningSession: bridge.runningSession || '' }))
2897
3177
  } catch {
2898
3178
  const setup = setupStatus(bridge, { withVersion: false })
2899
- return send(200, JSON.stringify({ runtime, setup, config: { autoOpen: resolved.autoOpen }, latest: null, lastSession: '', running: bridge.running || 0, runningSession: bridge.runningSession || '' }))
3179
+ const diag = diagnose(bridge, resolved)
3180
+ diag.checks = diag.checks.map((c) => (c.id === 'kernel' ? { ...c, detail: runtime.available ? [runtime.binary, runtime.version].filter(Boolean).join(' · ') : c.detail } : c))
3181
+ return send(200, JSON.stringify({ runtime, setup, diag, config: { autoOpen: resolved.autoOpen }, latest: null, lastSession: '', running: bridge.running || 0, runningSession: bridge.runningSession || '' }))
2900
3182
  }
2901
3183
  }
2902
3184
  if (url.pathname === `${ROUTE_PREFIX}/scenes`) {
@@ -2921,6 +3203,10 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
2921
3203
  try { return JSON.parse(raw) } catch { return null }
2922
3204
  }
2923
3205
 
3206
+ if (url.pathname === `${ROUTE_PREFIX}/doctor`) {
3207
+ bridge.refresh()
3208
+ return send(200, JSON.stringify(diagnose(bridge, resolved)))
3209
+ }
2924
3210
  if (url.pathname === `${ROUTE_PREFIX}/setup`) {
2925
3211
  // The panel's "install FreeCAD" button; same code path as the tool so
2926
3212
  // both report identical fields.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cad-studio",
3
- "version": "0.7.0",
3
+ "version": "0.8.1",
4
4
  "type": "module",
5
5
  "description": "CAD Studio — FreeCAD 桥(给 AI 的 14 个工具)+ Web 右栏 3D 面板:建模/装配/关节运动/出图/多页签查看",
6
6
  "exports": {