dsh-cad-studio 0.4.0 → 0.5.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 +50 -7
  2. package/client.js +61 -2
  3. package/index.js +159 -18
  4. package/package.json +2 -2
package/README.md CHANGED
@@ -2,9 +2,9 @@
2
2
 
3
3
  DeepSeek Harness 的 CAD 插件:**把 FreeCAD 桥接成给 AI 用的工具**,并在 Web 右栏提供一个只读+轻交互的 3D 面板。
4
4
 
5
- ![面板](docs/preview.png)
5
+ ![CAD 工作室面板](https://raw.githubusercontent.com/STofone/dsh-cad-studio/main/docs/preview.png)
6
6
 
7
- - Host 侧(`index.js`):14 个工具 + `/cad-studio/*` HTTP 路由 + `freecadcmd` 子进程桥
7
+ - Host 侧(`index.js`):16 个工具 + `/cad-studio/*` HTTP 路由 + `freecadcmd` 子进程桥
8
8
  - 客户端侧(`client.js`):右栏页签「CAD 工作室」,three.js 视口 + 图标条浮层(零件 / 特征 / 选中项 / 运动 / 视图 / 模型 / 信息)
9
9
  - 数据:`<modelsDir>/<名字>.json` 存模型工程(脚本或声明式特征 + 参数 + 20 条历史);场景网格落 `$TMPDIR/dsh-cad-studio/{state.json,scenes/*.json}`
10
10
 
@@ -14,7 +14,7 @@ DeepSeek Harness 的 CAD 插件:**把 FreeCAD 桥接成给 AI 用的工具**
14
14
  |---|---|
15
15
  | 建模 | `cad_studio_feature` 声明式特征(box/cylinder/sphere/cone/torus/extrude/revolve/fuse/cut/common/fillet/chamfer/shell/pattern/translate/rotate/mirror);`cad_studio_run` 跑任意 FreeCAD Python |
16
16
  | 工程文件 | `cad_studio_doc` 存 `script` 或 `features` 两种模型;`cad_studio_features` 改一条特征→整表重算(0.2–0.6 s),失败整表回滚 |
17
- | 装配 | `cad_studio_assembly` 读 manifest,`App::Link` 语义的实例位姿;零件是 STEP 文件级引用(改零件重开即跟随) |
17
+ | 装配 | `cad_studio_assembly` 读 manifest,`App::Link` 语义的实例位姿;零件是 STEP 文件级引用(改零件重开即跟随);`measure:true` 回每实例体积/包围盒,`interference:true` 回真正重叠的实例对 |
18
18
  | 运动 | `cad_studio_joint`(revolute/linear)+ `cad_studio_drive` + `cad_studio_explode`,面板拖滑杆看运动 |
19
19
  | 出图 | `cad_studio_drawing` HLR → SVG(主/俯/左/等轴) |
20
20
  | 其它 | `cad_studio_open`(STEP/STL/BREP/IGES 进来看)、`cad_studio_export`、`cad_studio_measure`、`cad_studio_env` |
@@ -56,7 +56,7 @@ npm 包:<https://www.npmjs.com/package/dsh-cad-studio>(`dsh plugin` / DSH
56
56
 
57
57
  `autoOpen: 'session'` 的判据是宿主侧的两个信号:这个会话最近一次发布过场景(`lastSession`),或它拥有更早发布过的场景。也就是说——只有真正在这里建过模的对话,右栏才会自动让出位置;别的对话不受打扰。
58
58
 
59
- ## 两个容易踩的接口约定
59
+ ## 接口约定与踩过的坑
60
60
 
61
61
  - **导出只走 `cad_studio_export`**。在 `cad_studio_run` 里直接 `Part.export([compound], path)` 会写出一个 1.6 KB 的 STEP 壳子,读回来是空形状,而脚本本身不报错。要么用 `cad_studio_export`,要么给 `cad_studio_run` 传 `check: ["/path/out.step"]`——它会在跑完后把这个文件读回来,回报 `{bytes, solids, volume, valid}`,壳子会显示 `valid:false`。
62
62
  - **探查脚本别发布场景**。`cad_studio_run` 默认会把绑定的 `scene` 发布成面板里的一行;只是量体积/查干涉的脚本传 `publish: false`,否则模型列表会被探针卡片塞满(实测一次会话攒到 28 行)。已经混进去的用 `cad_studio_scene {action:"delete", id:"scene-12"}` 清。
@@ -67,6 +67,38 @@ npm 包:<https://www.npmjs.com/package/dsh-cad-studio>(`dsh plugin` / DSH
67
67
  - 特征参数在 `normalizeFeature` 阶段就校验,报错带行号与名字:`特征 f10(倒角_左后) cut:需要 with 子图元(…)`——不会再从 FreeCAD 里冒出一句 `第 10 步(cut)失败:'with'`。
68
68
  - 删掉的面板行不会被下一次发布「复活」:`persist()` 会跟磁盘对账,只保留磁盘上还有的、或本进程发布过的行。
69
69
 
70
+ ## 截图
71
+
72
+ 都来自一个**测试实例**(合成的 `体验_特征 / 体验_参数化 / 体验_装配` 三个演示模型),并且**只截取面板元素**——图里没有真实工作区、会话或文件路径。
73
+
74
+ **装配 + 视口**:零件按实例配色,左侧图标条、页签、坐标轴、网格、等轴视图。
75
+
76
+ ![装配与视口](https://raw.githubusercontent.com/STofone/dsh-cad-studio/main/docs/preview.png)
77
+
78
+ **选中项**:视口点选 ↔ 列表联动;改色、显隐、透明度、隔离、线框、副本同透明度、重置。
79
+
80
+ ![选中项](https://raw.githubusercontent.com/STofone/dsh-cad-studio/main/docs/props.png)
81
+
82
+ **声明式特征**:一条特征一行,改数值即整表重算;眼睛跳过该步,↑↓ 调顺序,× 删除。
83
+
84
+ ![特征列表](https://raw.githubusercontent.com/STofone/dsh-cad-studio/main/docs/features.png)
85
+
86
+ **参数化脚本**:改 `params` 就重跑脚本,原地更新同一个场景(不新增模型行)。
87
+
88
+ ![参数](https://raw.githubusercontent.com/STofone/dsh-cad-studio/main/docs/params.png)
89
+
90
+ **关节与爆炸**:每个关节都有数值框(可精确输入 0°)、归零按钮和滑杆;爆炸图一个滑杆。
91
+
92
+ ![关节与爆炸](https://raw.githubusercontent.com/STofone/dsh-cad-studio/main/docs/motion.png)
93
+
94
+ **多页签**:最多 5 个模型页签,各自记住相机与配色;`+` 新增页签,文件夹图标切换当前页签。
95
+
96
+ ![多页签](https://raw.githubusercontent.com/STofone/dsh-cad-studio/main/docs/tabs.png)
97
+
98
+ 图标条(4× 放大):立方体=零件、台阶=特征、滑杆=选中项、环形箭头=运动、相机=视图、文件夹=模型、ⓘ=信息。
99
+
100
+ <img src="https://raw.githubusercontent.com/STofone/dsh-cad-studio/main/docs/rail.png" width="58" alt="图标条">
101
+
70
102
  ## 场景 JSON 协议
71
103
 
72
104
  ```jsonc
@@ -84,11 +116,22 @@ npm 包:<https://www.npmjs.com/package/dsh-cad-studio>(`dsh plugin` / DSH
84
116
  ## 开发
85
117
 
86
118
  ```bash
87
- node test/harness.mjs # 133 条回归:无浏览器,stub cordis ctx 直接调工具
88
- node test/stale-bridge.mjs # 热重载后旧 bridge 实例自愈
119
+ # 165 条回归:无浏览器,stub cordis ctx 直接调工具
120
+ rm -rf /tmp/cad-h && mkdir -p /tmp/cad-h && TMPDIR=/tmp/cad-h node test/harness.mjs
121
+ node test/stale-bridge.mjs # 热重载后旧 bridge 实例自愈
122
+
123
+ # 在一台测试实例上造三个"什么都能试"的模型(体验_特征 / 体验_参数化 / 体验_装配)
124
+ node scripts/dev-playground.mjs
125
+ # 把这条实例的模型列表收敛回这几个演示模型(探针跑多了会攒出几十行)
126
+ node scripts/dev-keep-demos.mjs --dry # 先看要删哪些
127
+ node scripts/dev-keep-demos.mjs
128
+ # 重截 README 的截图(只截 [data-cad-panel-root],需要能访问测试实例)
129
+ node scripts/shots.mjs --url http://127.0.0.1:3201 --token-file /tmp/dev-token.txt
89
130
  ```
90
131
 
91
- `test/replicate.mjs`、`scripts/*.mjs` 是我自己造场景/验证用的夹具,按需改路径。
132
+ > `TMPDIR` 必须指到临时目录:harness 会清空 `$TMPDIR/dsh-cad-studio`,指到默认位置就会把线上实例的场景缓存一起删掉。
133
+
134
+ `test/replicate.mjs`、`scripts/*.mjs` 是造场景/验证用的夹具,按需改路径。截图脚本用 `window.__cadStudioAutoOpen.open()` 打开面板——宿主的页签启动器在不同版本里位置会变,这个钩子稳定些。
92
135
 
93
136
  ## 已知限制
94
137
 
package/client.js CHANGED
@@ -154,6 +154,15 @@ window.__ModuleLoader__.load({
154
154
  // Feature list: dense rows, each step a small block with its own numbers.
155
155
  featBlock: { padding: '3px 0 5px', borderBottom: '1px solid rgba(120,130,145,.16)' },
156
156
  featHead: { display: 'flex', alignItems: 'center', gap: 4, minWidth: 0 },
157
+ featDot: (tone) => ({
158
+ width: 6,
159
+ height: 6,
160
+ borderRadius: '50%',
161
+ flex: '0 0 auto',
162
+ background: tone,
163
+ boxShadow: '0 0 0 2px rgba(0,0,0,0.18)',
164
+ }),
165
+ featTip: { flex: '0 0 auto', fontSize: 10, opacity: 0.8, marginLeft: 2 },
157
166
  featId: { width: 18, flex: 'none', textAlign: 'center', fontSize: 9.5, lineHeight: '14px', borderRadius: 3, background: 'rgba(120,130,145,.14)', opacity: 0.8, fontVariantNumeric: 'tabular-nums' },
158
167
  featLabel: { fontSize: 11, fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', flex: '1 1 auto', minWidth: 0 },
159
168
  microBtn: { font: 'inherit', fontSize: 10, lineHeight: 1, padding: '2px 3px', border: 0, borderRadius: 4, background: 'transparent', color: 'inherit', opacity: 0.55, cursor: 'pointer', flex: 'none' },
@@ -1770,7 +1779,14 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
1770
1779
  setFeatError(String((out && out.error) || `HTTP ${res.status}`))
1771
1780
  return null
1772
1781
  }
1773
- setFeatError('')
1782
+ // A saved-but-unevaluable edit is not an HTTP failure: say which node
1783
+ // broke instead of pretending the click did nothing.
1784
+ if (out.evaluated === false) {
1785
+ const first = (out.errors && out.errors[0]) || null
1786
+ setFeatError(`${first ? `${first.id} 求值失败:${first.message}` : '求值失败'}`)
1787
+ } else {
1788
+ setFeatError('')
1789
+ }
1774
1790
  if (out.sceneId) await applyScene(out.sceneId, out.at)
1775
1791
  return out
1776
1792
  } catch (error) {
@@ -1881,6 +1897,25 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
1881
1897
  const paramsSection = paramKeys.length
1882
1898
  ? [h('div', { key: 'params-h', style: styles.treeHint }, `${featureModel} · 参数(改完即重建)`), ...paramsBody]
1883
1899
  : []
1900
+ useEffect(() => {
1901
+ const onKey = (event) => {
1902
+ const tag = (event.target && event.target.tagName) || ''
1903
+ if (/^(INPUT|TEXTAREA|SELECT)$/.test(tag)) return
1904
+ if (!(event.metaKey || event.ctrlKey) || !featureModel) return
1905
+ const key = String(event.key || '').toLowerCase()
1906
+ if (key === 'z') {
1907
+ event.preventDefault()
1908
+ postFeature({ action: event.shiftKey ? 'redo' : 'undo' })
1909
+ } else if (key === 'y') {
1910
+ event.preventDefault()
1911
+ postFeature({ action: 'redo' })
1912
+ }
1913
+ }
1914
+ window.addEventListener('keydown', onKey)
1915
+ return () => window.removeEventListener('keydown', onKey)
1916
+ }, [featureModel])
1917
+ const graphNodes = (payload && payload.graph && payload.graph.nodes) || []
1918
+ const graphTip = (payload && payload.graph && payload.graph.tip) || null
1884
1919
  const featureBody = paramsSection.length
1885
1920
  ? [...paramsSection, ...(!featureList.length
1886
1921
  ? [h('div', { key: 'script-hint', style: { ...styles.treeHint, whiteSpace: 'nowrap' }, title: '脚本模型:改参数会重跑脚本;逐条特征只适用于声明式模型' }, '脚本模型 · 改参数即重跑脚本')]
@@ -1918,6 +1953,10 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
1918
1953
  featError ? h('div', { key: 'e', style: styles.featError, 'data-cad-feat-error': '1' }, featError) : null,
1919
1954
  ...featureList.map((feature, index) => {
1920
1955
  const off = feature.enabled === false
1956
+ const node = graphNodes.find((n) => n.id === feature.id)
1957
+ const tone = node
1958
+ ? { ok: '#2ea043', failed: '#e5534b', blocked: '#e0a33a', skipped: '#8b949e' }[node.status] || '#8b949e'
1959
+ : '#8b949e'
1921
1960
  const fields = paramFields(feature.params || {}, [])
1922
1961
  return h('div', {
1923
1962
  key: feature.id,
@@ -1926,6 +1965,12 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
1926
1965
  }, [
1927
1966
  h('div', { key: 'r', style: styles.featHead }, [
1928
1967
  h('span', { key: 'i', style: styles.featId }, feature.id),
1968
+ h('span', {
1969
+ key: 's',
1970
+ style: styles.featDot(tone),
1971
+ 'data-cad-feat-status': node ? node.status : '',
1972
+ title: node && node.message ? node.message : (node ? `status: ${node.status}` : ''),
1973
+ }),
1929
1974
  h('span', { key: 'l', style: styles.featLabel, title: `${feature.id} · ${feature.kind}` }, `${feature.label || feature.kind}`),
1930
1975
  h('button', {
1931
1976
  key: 'e',
@@ -1953,6 +1998,17 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
1953
1998
  'data-cad-feat-down': feature.id,
1954
1999
  onClick: (event) => { event.stopPropagation(); postFeature({ action: 'move', id: feature.id, to: index + 1 }) },
1955
2000
  }, '↓'),
2001
+ h('button', {
2002
+ key: 't',
2003
+ type: 'button',
2004
+ style: { ...styles.microBtn, opacity: graphTip === feature.id ? 1 : 0.55 },
2005
+ title: graphTip === feature.id ? '清除回滚点(恢复算全部)' : '只算到这一步(回滚点)',
2006
+ 'data-cad-feat-tip': feature.id,
2007
+ onClick: (event) => {
2008
+ event.stopPropagation()
2009
+ postFeature({ action: 'tip', id: graphTip === feature.id ? null : feature.id })
2010
+ },
2011
+ }, graphTip === feature.id ? '◉' : '◌'),
1956
2012
  h('button', {
1957
2013
  key: 'x',
1958
2014
  type: 'button',
@@ -2668,7 +2724,10 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
2668
2724
  try {
2669
2725
  Object.defineProperty(window, '__cadStudioAutoOpen', {
2670
2726
  configurable: true,
2671
- get: () => ({ ...autoOpenTrace, mode: cadAutoOpen, session: panelSession }),
2727
+ // `open()` is for tooling: it is how a screenshot script (or a user
2728
+ // who closed the pane) brings the tab back without hunting for the
2729
+ // host's own launcher.
2730
+ get: () => ({ ...autoOpenTrace, mode: cadAutoOpen, session: panelSession, open: () => openPane(0) }),
2672
2731
  })
2673
2732
  } catch (err) { /* a stale definition from a previous apply is fine */ }
2674
2733
 
package/index.js CHANGED
@@ -857,7 +857,7 @@ def describe(path):
857
857
  */
858
858
  const featuresScript = (ops, exportPath) => `${PRELUDE}
859
859
  import os
860
- _OPS = ${JSON.stringify(ops)}
860
+ _OPS = json.loads(${JSON.stringify(JSON.stringify(Array.isArray(ops) ? ops : []))})
861
861
  _EXPORT = ${exportPath ? JSON.stringify(exportPath) : 'None'}
862
862
 
863
863
  def _v3(x, d=(0.0, 0.0, 0.0)):
@@ -901,8 +901,13 @@ def _prim(op):
901
901
  raise RuntimeError("未知图元:" + str(k))
902
902
 
903
903
  _shape = None
904
+ _errors = []
905
+ _executed = 0
904
906
  for _idx, _op in enumerate(_OPS):
905
907
  _k = _op.get("kind")
908
+ if _k == "__skip__":
909
+ continue
910
+ _snap = _shape
906
911
  try:
907
912
  if _k in ("box", "cylinder", "sphere", "cone", "torus", "extrude", "revolve"):
908
913
  _s = _prim(_op)
@@ -957,13 +962,22 @@ for _idx, _op in enumerate(_OPS):
957
962
  else:
958
963
  raise RuntimeError("未知特征:" + str(_k))
959
964
  except Exception as _e:
960
- # Name the feature, not just its position: "step 10 (cut) failed: 'with'"
961
- # told the caller nothing about which row to fix.
962
- raise RuntimeError("第 %d 步 · 特征 %s(%s,%s)失败:%s" % (
963
- _idx + 1, _op.get("_id", "?"), _op.get("_label") or "-", _k, _e))
965
+ # A failing node must not roll the document back: record it, keep the
966
+ # last good shape, and stop — every later node is blocked by it, which
967
+ # is what a parametric CAD does (the bad feature is the one to fix).
968
+ _shape = _snap
969
+ _errors.append({
970
+ "id": _op.get("_id", "?"),
971
+ "step": _idx + 1,
972
+ "kind": _k,
973
+ "label": _op.get("_label") or "",
974
+ "message": str(_e),
975
+ })
976
+ break
977
+ _executed = _idx + 1
964
978
 
965
979
  if _shape is None:
966
- raise RuntimeError("ops 为空:至少给一个图元")
980
+ raise RuntimeError(_errors[0]["message"] if _errors else "ops 为空:至少给一个图元")
967
981
  _shape = _shape.removeSplitter()
968
982
  scene = _shape
969
983
  __out = {
@@ -973,6 +987,8 @@ __out = {
973
987
  "area": round(_shape.Area, 3),
974
988
  "faces": len(_shape.Faces),
975
989
  "bounds": _bounds(_shape),
990
+ "errors": _errors,
991
+ "executed": _executed,
976
992
  }
977
993
  if _EXPORT:
978
994
  os.makedirs(os.path.dirname(_EXPORT) or ".", exist_ok=True)
@@ -1215,6 +1231,9 @@ __out = {
1215
1231
  },
1216
1232
  execute: async ({ action, id, title }) => {
1217
1233
  const kind = String(action ?? 'list')
1234
+ // A fresh process starts with an empty in-memory list; the rows live in
1235
+ // state.json until the next publish hydrates them.
1236
+ await bridge.hydrateHistory()
1218
1237
  if (kind === 'list') {
1219
1238
  const rows = bridge.listSceneRows()
1220
1239
  return { ok: true, scenes: rows.length, latest: bridge.latest ? bridge.latest.id : '', items: rows }
@@ -1995,11 +2014,25 @@ if _TARGET:
1995
2014
  // a declarative feature list. Older files predate the field and are scripts.
1996
2015
  doc.kind = doc.kind === 'features' ? 'features' : 'script'
1997
2016
  doc.features = Array.isArray(doc.features) ? doc.features : []
2017
+ // Schema 2 keeps the list under `graph.nodes`; `features` stays the in-memory
2018
+ // name so every caller keeps working. Reading an old file migrates it.
2019
+ if (doc.graph && Array.isArray(doc.graph.nodes)) doc.features = doc.graph.nodes
2020
+ doc.schema = 2
2021
+ doc.tip = typeof doc.tip === 'string' && doc.tip ? doc.tip : null
2022
+ doc.undo = Array.isArray(doc.undo) ? doc.undo : []
2023
+ doc.redo = Array.isArray(doc.redo) ? doc.redo : []
2024
+ for (const f of doc.features) if (f && typeof f === 'object' && typeof f.suppressed === 'boolean') f.enabled = f.suppressed !== true
1998
2025
  return doc
1999
2026
  }
2000
2027
 
2001
2028
  const writeModel = async (doc, dir) => {
2002
2029
  await mkdir(dir, { recursive: true })
2030
+ doc.schema = 2
2031
+ // Only feature documents have a graph; a script document is code-not-data.
2032
+ if (Array.isArray(doc.features)) {
2033
+ doc.graph = { tip: doc.tip ?? null, nodes: doc.features }
2034
+ for (const f of doc.features) f.suppressed = f.enabled === false
2035
+ }
2003
2036
  const body = JSON.stringify(doc, null, 2)
2004
2037
  await writeFile(modelFile(doc.name, dir), body, 'utf8')
2005
2038
  return doc
@@ -2012,12 +2045,40 @@ if _TARGET:
2012
2045
  label: f.label ?? '',
2013
2046
  params: f.params ?? {},
2014
2047
  enabled: f.enabled !== false,
2048
+ suppressed: f.enabled === false,
2015
2049
  }))
2016
2050
 
2017
2051
  /** Feature objects to flat ops (`{kind, ...params}`) for the Python emitter. */
2018
- const featureOps = (doc) => doc.features
2019
- .filter((f) => f.enabled !== false)
2020
- .map((f) => ({ kind: f.kind, ...(f.params ?? {}), _id: f.id, _label: f.label || '' }))
2052
+ /**
2053
+ * Nodes to evaluate, in order, honouring `tip` (rollback bar) and suppression.
2054
+ *
2055
+ * A suppressed node is not "skip and keep going": everything after it was
2056
+ * built on a shape that no longer exists, so evaluation stops there and the
2057
+ * rest is reported as blocked. This mirrors FreeCAD/Onshape rather than
2058
+ * silently computing against the wrong shape.
2059
+ */
2060
+ const featureOps = (doc, { stopAtSuppressed = true } = {}) => {
2061
+ const list = Array.isArray(doc.features) ? doc.features : []
2062
+ const tipAt = doc.tip ? list.findIndex((f) => String(f.id) === String(doc.tip)) : -1
2063
+ const end = tipAt >= 0 ? tipAt + 1 : list.length
2064
+ const ops = []
2065
+ for (let i = 0; i < end; i += 1) {
2066
+ const f = list[i]
2067
+ if (!f) continue
2068
+ // Suppression skips the node. Until typed selectors land (Phase 2) we
2069
+ // cannot tell whether a later node depended on its outputs, so skipping
2070
+ // is the honest default: the graph shows it as skipped, and a node that
2071
+ // really needed it will fail loudly instead of silently reading something
2072
+ // else. (Stopping the whole chain would break the common "mute one fillet
2073
+ // and keep working" case.)
2074
+ if (f.enabled === false) {
2075
+ if (stopAtSuppressed) ops.push({ kind: '__skip__', _id: f.id, _label: f.label || '' })
2076
+ continue
2077
+ }
2078
+ ops.push({ kind: f.kind, ...(f.params ?? {}), _id: f.id, _label: f.label || '' })
2079
+ }
2080
+ return ops
2081
+ }
2021
2082
 
2022
2083
  const FEATURE_FIELDS = ['id', 'kind', 'label', 'params', 'enabled']
2023
2084
 
@@ -2089,12 +2150,39 @@ if _TARGET:
2089
2150
  * documents re-emit the whole feature list — which is why editing one feature
2090
2151
  * is cheap and cannot leave the model half-updated.
2091
2152
  */
2153
+ /**
2154
+ * Per-node status for the panel and for the caller: ok / failed / blocked /
2155
+ * skipped. Derived from what the kernel actually executed, not guessed.
2156
+ */
2157
+ const graphView = (doc, out) => {
2158
+ const list = Array.isArray(doc.features) ? doc.features : []
2159
+ const errors = Array.isArray(out?.errors) ? out.errors : []
2160
+ const failedAt = new Map(errors.map((e) => [String(e.id), e]))
2161
+ const executed = Number.isFinite(out?.executed) ? Number(out.executed) : null
2162
+ const tipAt = doc.tip ? list.findIndex((f) => String(f.id) === String(doc.tip)) : -1
2163
+ const end = tipAt >= 0 ? tipAt + 1 : list.length
2164
+ let why = ''
2165
+ const nodes = list.map((f, i) => {
2166
+ const base = { id: f.id, kind: f.kind, label: f.label ?? '', suppressed: f.enabled === false }
2167
+ if (i >= end) return { ...base, status: 'skipped', message: '在回滚点之后' }
2168
+ if (why) return { ...base, status: 'blocked', message: why }
2169
+ // Skipping is not a failure: the node is not evaluated, the tree keeps
2170
+ // building (see featureOps).
2171
+ if (base.suppressed) return { ...base, status: 'skipped', message: '被抑制(跳过)' }
2172
+ const err = failedAt.get(String(f.id))
2173
+ if (err) { why = `因为 ${f.id} 失败`; return { ...base, status: 'failed', message: err.message } }
2174
+ if (executed !== null && i >= executed) { why = `因为 ${f.id} 没有执行`; return { ...base, status: 'blocked', message: why } }
2175
+ return { ...base, status: 'ok', message: '' }
2176
+ })
2177
+ return { tip: doc.tip ?? null, nodes }
2178
+ }
2179
+
2092
2180
  const rebuild = async (doc, dir, { note } = {}) => {
2093
2181
  const isFeatures = doc.kind === 'features'
2094
2182
  const code = isFeatures
2095
2183
  ? featuresScript(featureOps(doc))
2096
2184
  : `${PRELUDE}\nP = ${JSON.stringify(doc.params ?? {})}\n${doc.script}`
2097
- const meta = isFeatures ? { model: doc.name, features: publicFeatures(doc) } : { model: doc.name, params: doc.params ?? {} }
2185
+ const meta = isFeatures ? { model: doc.name, features: publicFeatures(doc), tip: doc.tip ?? null } : { model: doc.name, params: doc.params ?? {} }
2098
2186
  doc.run = (doc.run ?? 0) + 1
2099
2187
  doc.updatedAt = new Date().toISOString()
2100
2188
  // One row per model: a rebuild rewrites the model's existing scene.
@@ -2104,7 +2192,7 @@ if _TARGET:
2104
2192
  docKey: `model:${doc.name}`,
2105
2193
  sceneId: doc.stats?.sceneId || '',
2106
2194
  })
2107
- if (out.ok === false) return { ...out, name: doc.name, params: doc.params }
2195
+ if (out.ok === false) return { ...out, name: doc.name, params: doc.params, graph: graphView(doc, out) }
2108
2196
  // run() returns volume/bounds but not triangle count, so read it back from
2109
2197
  // the row that was just published (a null here forced the panel to guess).
2110
2198
  const sceneId = out.sceneId ?? ''
@@ -2117,11 +2205,21 @@ if _TARGET:
2117
2205
  at: doc.updatedAt,
2118
2206
  }
2119
2207
  if (note) doc.note = note
2208
+ // The scene was published before the kernel reported which nodes failed, so
2209
+ // attach the statuses now: the panel paints dots from payload.graph.
2210
+ const graph = graphView(doc, out)
2211
+ const scene = sceneId ? bridge.scenes?.get(sceneId) : null
2212
+ if (scene) {
2213
+ scene.graph = graph
2214
+ try { await bridge.persist() } catch {}
2215
+ }
2120
2216
  await writeModel(doc, dir)
2121
2217
  return {
2122
2218
  ok: true,
2123
2219
  name: doc.name,
2124
2220
  dir,
2221
+ graph,
2222
+ errors: Array.isArray(out.errors) ? out.errors : [],
2125
2223
  run: doc.run,
2126
2224
  params: doc.params,
2127
2225
  volume: doc.stats.volume,
@@ -2190,9 +2288,15 @@ if _TARGET:
2190
2288
  throw new Error(`${doc.name} 是脚本模型,没有特征列表(用 cad_studio_doc update 改 params,或新建 kind="features" 的模型)`)
2191
2289
  }
2192
2290
  if (action === 'list') {
2193
- return { ok: true, model: doc.name, kind: doc.kind, features: publicFeatures(doc), stats: doc.stats ?? null }
2291
+ return { ok: true, model: doc.name, kind: doc.kind, features: publicFeatures(doc), graph: graphView(doc, { errors: [], executed: null }), stats: doc.stats ?? null }
2292
+ }
2293
+ const snapshot = () => JSON.parse(JSON.stringify({ features: doc.features, tip: doc.tip ?? null }))
2294
+ const restore = (snap) => {
2295
+ doc.features = JSON.parse(JSON.stringify(snap.features))
2296
+ doc.tip = snap.tip ?? null
2194
2297
  }
2195
2298
  const before = JSON.parse(JSON.stringify(doc.features))
2299
+ const undoSnap = snapshot()
2196
2300
  const feature = args.feature && typeof args.feature === 'object' ? args.feature : {}
2197
2301
  const wanted = String(args.id ?? feature.id ?? '')
2198
2302
  const findAt = () => doc.features.findIndex((f) => String(f.id) === wanted)
@@ -2221,21 +2325,53 @@ if _TARGET:
2221
2325
  const [item] = doc.features.splice(at, 1)
2222
2326
  const to = Number.isFinite(Number(args.to)) ? Math.max(0, Math.min(doc.features.length, Math.round(Number(args.to)))) : doc.features.length
2223
2327
  doc.features.splice(to, 0, item)
2224
- } else if (action === 'toggle') {
2328
+ } else if (action === 'toggle' || action === 'suppress') {
2225
2329
  const at = findAt()
2226
2330
  if (at < 0) throw new Error(`没有这个特征:${wanted || '(空)'}`)
2331
+ // Suppression is document state, not a delete: the feature keeps its
2332
+ // params and its place, and everything downstream reports as blocked.
2227
2333
  const want = feature.enabled !== undefined ? feature.enabled !== false : doc.features[at].enabled === false
2228
2334
  doc.features[at].enabled = want
2335
+ } else if (action === 'tip') {
2336
+ if (!wanted) doc.tip = null
2337
+ else if (findAt() < 0) throw new Error(`没有这个特征:${wanted}`)
2338
+ else doc.tip = wanted
2339
+ } else if (action === 'undo' || action === 'redo') {
2340
+ const from = action === 'undo' ? doc.undo : doc.redo
2341
+ const to = action === 'undo' ? doc.redo : doc.undo
2342
+ if (!from.length) throw new Error(action === 'undo' ? '没有可撤销的操作' : '没有可重做的操作')
2343
+ const entry = from.pop()
2344
+ to.push(entry)
2345
+ restore(action === 'undo' ? entry.before : entry.after)
2229
2346
  } else {
2230
2347
  throw new Error(`未知 action:${action}(可用 list / add / update / remove / move / toggle)`)
2231
2348
  }
2232
2349
  if (!doc.features.length) throw new Error('特征列表不能为空:至少留一个图元')
2233
2350
 
2234
- const result = await rebuild(doc, dir, { note: `${action} ${wanted || feature.kind || ''}`.trim() })
2351
+ const label = `${action} ${wanted || feature.kind || ''}`.trim()
2352
+ const result = await rebuild(doc, dir, { note: label })
2235
2353
  if (result.ok === false) {
2236
- doc.features = before
2354
+ // Keep the edit. A document that describes an unbuildable shape is more
2355
+ // useful than a silent rollback: the panel shows which node failed, and
2356
+ // undo is one keystroke away.
2237
2357
  await writeModel(doc, dir)
2238
- return { ...result, reverted: true, hint: '这次修改没跑通,特征列表已回退到上一版;改完再试。' }
2358
+ // "ok" answers "did the document accept the edit"; the geometry answer
2359
+ // lives in evaluated/errors/graph. A reorder can legitimately leave the
2360
+ // tree unevaluable (a fillet moved above its body) and that must stay
2361
+ // visible rather than being rejected — you fix it by reading the graph.
2362
+ return {
2363
+ ...result,
2364
+ ok: true,
2365
+ saved: true,
2366
+ evaluated: false,
2367
+ features: publicFeatures(doc),
2368
+ hint: '这条改动已存进文档,但求值失败——看 graph 里哪条是 failed,改好或撤销。',
2369
+ }
2370
+ }
2371
+ if (!['undo', 'redo'].includes(action)) {
2372
+ doc.undo.push({ at: new Date().toISOString(), action, target: wanted || feature.kind || '', before: undoSnap, after: snapshot() })
2373
+ doc.undo = doc.undo.slice(-50)
2374
+ doc.redo = []
2239
2375
  }
2240
2376
  doc.history.push({
2241
2377
  at: doc.updatedAt,
@@ -2249,10 +2385,15 @@ if _TARGET:
2249
2385
  await writeModel(doc, dir)
2250
2386
  return {
2251
2387
  ok: true,
2388
+ evaluated: result.ok !== false && (result.errors ?? []).length === 0,
2252
2389
  model: doc.name,
2253
2390
  kind: doc.kind,
2254
2391
  action,
2255
2392
  features: publicFeatures(doc),
2393
+ graph: result.graph,
2394
+ errors: result.errors ?? [],
2395
+ undo: doc.undo.length,
2396
+ redo: doc.redo.length,
2256
2397
  volume: doc.stats?.volume ?? null,
2257
2398
  triangles: doc.stats?.triangles ?? null,
2258
2399
  sceneId: doc.stats?.sceneId ?? '',
@@ -2262,12 +2403,12 @@ if _TARGET:
2262
2403
 
2263
2404
  tool({
2264
2405
  name: 'cad_studio_features',
2265
- description: `Edit a feature-list model one feature at a time (the "边画边改" path): change one feature's parameters and the whole list is re-derived in ~0.2–0.6 s. Actions: list / add / update / remove / move / toggle. Feature kinds: ${FEATURE_KINDS.join(', ')}. A feature is {kind, label?, params} — params hold that kind's fields (box: size:[dx,dy,dz], at?; cylinder: r,h,at?,axis?; cut/fuse/common: with:<primitive>; fillet: r; chamfer: d; shell: t,open?; pattern_linear: delta,count; rotate: axis?,at?,deg; mirror: normal?,at?). Flat form ({kind:'box', size:[…]}) is accepted too.`,
2406
+ description: `Edit a feature-list model one feature at a time (the "边画边改" path): change one feature's parameters and the whole list is re-derived in ~0.2–0.6 s. Actions: list / add / update / remove / move / toggle (alias suppress) / tip / undo / redo. Feature kinds: ${FEATURE_KINDS.join(', ')}. A feature is {kind, label?, params} — params hold that kind's fields (box: size:[dx,dy,dz], at?; cylinder: r,h,at?,axis?; cut/fuse/common: with:<primitive>; fillet: r; chamfer: d; shell: t,open?; pattern_linear: delta,count; rotate: axis?,at?,deg; mirror: normal?,at?). Flat form ({kind:'box', size:[…]}) is accepted too.`,
2266
2407
  parameters: {
2267
2408
  type: 'object',
2268
2409
  properties: {
2269
2410
  model: { type: 'string', description: 'Feature-list model name (created with cad_studio_doc kind="features").' },
2270
- action: { type: 'string', enum: ['list', 'add', 'update', 'remove', 'move', 'toggle'] },
2411
+ action: { type: 'string', enum: ['list', 'add', 'update', 'remove', 'move', 'toggle', 'suppress', 'tip', 'undo', 'redo'] },
2271
2412
  feature: { type: 'object', description: 'add: the feature to append. update/toggle: {id, ...fields to change}. remove/move: {id}.' },
2272
2413
  id: { type: 'string', description: 'Feature id (f1, f2 …); alternative to feature.id.' },
2273
2414
  to: { type: 'integer', description: 'move: target index (0-based). Default: to the end.' },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cad-studio",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "type": "module",
5
5
  "description": "CAD Studio — FreeCAD 桥(给 AI 的 14 个工具)+ Web 右栏 3D 面板:建模/装配/关节运动/出图/多页签查看",
6
6
  "exports": {
@@ -47,4 +47,4 @@
47
47
  "name": "stofone"
48
48
  },
49
49
  "license": "MIT"
50
- }
50
+ }