dsh-cad-studio 0.4.1 → 0.6.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 +13 -0
  2. package/client.js +61 -2
  3. package/index.js +290 -20
  4. package/package.json +2 -2
package/README.md CHANGED
@@ -56,6 +56,19 @@ npm 包:<https://www.npmjs.com/package/dsh-cad-studio>(`dsh plugin` / DSH
56
56
 
57
57
  `autoOpen: 'session'` 的判据是宿主侧的两个信号:这个会话最近一次发布过场景(`lastSession`),或它拥有更早发布过的场景。也就是说——只有真正在这里建过模的对话,右栏才会自动让出位置;别的对话不受打扰。
58
58
 
59
+ ## 子形状选择器
60
+
61
+ `fillet` / `chamfer` 的 `edges`、`shell` 的 `faces` 接受**谓词**(不存 id,每次重建重新选):
62
+
63
+ ```json
64
+ {"kind": "fillet", "r": 3, "edges": {"axis": "Z", "mode": "parallel", "type": "line"}}
65
+ {"kind": "shell", "t": 2, "faces": {"axis": "Z", "mode": "aligned", "dir": "+", "type": "plane"}}
66
+ ```
67
+
68
+ 字段:`axis`(X/Y/Z 或 [x,y,z])、`mode`(`parallel` / `aligned` / `perpendicular`)、`dir`(`+`/`-`)、`type`(边 `line`/`circle`,面 `plane`/`cylinder`)、`radius`、`pick`(`max`/`min`)、`nth`、`near`(点)、`one`(要求恰好一个)、`tol`(默认 0.5 mm)。
69
+
70
+ 选不中会**报错并在面板标红**:`选择器没有选中任何边:{"axis":"Z","type":"circle"}(当前形状有 12 条边)`。设计取舍见 `docs/RESEARCH-SELECTORS.md`。
71
+
59
72
  ## 接口约定与踩过的坑
60
73
 
61
74
  - **导出只走 `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`。
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) {
@@ -1828,8 +1844,11 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
1828
1844
  for (const [key, value] of Object.entries(params || {})) {
1829
1845
  const path = base ? [...base, key] : [key]
1830
1846
  if (typeof value === 'number') out.push({ path, label: path.join('.'), kind: 'num', value })
1847
+ // Selector params are strings (axis/mode/dir/type). They must be
1848
+ // editable too, otherwise "dir: + -> -" needs a JSON edit.
1849
+ else if (typeof value === 'string') out.push({ path, label: path.join('.'), kind: 'text', value })
1831
1850
  else if (Array.isArray(value) && value.every((v) => typeof v === 'number')) out.push({ path, label: path.join('.'), kind: 'vec', value })
1832
- else if (value && typeof value === 'object' && !Array.isArray(value) && path.length < 2) {
1851
+ else if (value && typeof value === 'object' && !Array.isArray(value) && path.length < 3) {
1833
1852
  // A nested op (`cut.with` = a cylinder) is editable too: drop its
1834
1853
  // kind (you switch shapes by replacing the feature) and expose the
1835
1854
  // numbers that matter — r, h, at.
@@ -1881,6 +1900,25 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
1881
1900
  const paramsSection = paramKeys.length
1882
1901
  ? [h('div', { key: 'params-h', style: styles.treeHint }, `${featureModel} · 参数(改完即重建)`), ...paramsBody]
1883
1902
  : []
1903
+ useEffect(() => {
1904
+ const onKey = (event) => {
1905
+ const tag = (event.target && event.target.tagName) || ''
1906
+ if (/^(INPUT|TEXTAREA|SELECT)$/.test(tag)) return
1907
+ if (!(event.metaKey || event.ctrlKey) || !featureModel) return
1908
+ const key = String(event.key || '').toLowerCase()
1909
+ if (key === 'z') {
1910
+ event.preventDefault()
1911
+ postFeature({ action: event.shiftKey ? 'redo' : 'undo' })
1912
+ } else if (key === 'y') {
1913
+ event.preventDefault()
1914
+ postFeature({ action: 'redo' })
1915
+ }
1916
+ }
1917
+ window.addEventListener('keydown', onKey)
1918
+ return () => window.removeEventListener('keydown', onKey)
1919
+ }, [featureModel])
1920
+ const graphNodes = (payload && payload.graph && payload.graph.nodes) || []
1921
+ const graphTip = (payload && payload.graph && payload.graph.tip) || null
1884
1922
  const featureBody = paramsSection.length
1885
1923
  ? [...paramsSection, ...(!featureList.length
1886
1924
  ? [h('div', { key: 'script-hint', style: { ...styles.treeHint, whiteSpace: 'nowrap' }, title: '脚本模型:改参数会重跑脚本;逐条特征只适用于声明式模型' }, '脚本模型 · 改参数即重跑脚本')]
@@ -1918,6 +1956,10 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
1918
1956
  featError ? h('div', { key: 'e', style: styles.featError, 'data-cad-feat-error': '1' }, featError) : null,
1919
1957
  ...featureList.map((feature, index) => {
1920
1958
  const off = feature.enabled === false
1959
+ const node = graphNodes.find((n) => n.id === feature.id)
1960
+ const tone = node
1961
+ ? { ok: '#2ea043', failed: '#e5534b', blocked: '#e0a33a', skipped: '#8b949e' }[node.status] || '#8b949e'
1962
+ : '#8b949e'
1921
1963
  const fields = paramFields(feature.params || {}, [])
1922
1964
  return h('div', {
1923
1965
  key: feature.id,
@@ -1926,6 +1968,12 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
1926
1968
  }, [
1927
1969
  h('div', { key: 'r', style: styles.featHead }, [
1928
1970
  h('span', { key: 'i', style: styles.featId }, feature.id),
1971
+ h('span', {
1972
+ key: 's',
1973
+ style: styles.featDot(tone),
1974
+ 'data-cad-feat-status': node ? node.status : '',
1975
+ title: node && node.message ? node.message : (node ? `status: ${node.status}` : ''),
1976
+ }),
1929
1977
  h('span', { key: 'l', style: styles.featLabel, title: `${feature.id} · ${feature.kind}` }, `${feature.label || feature.kind}`),
1930
1978
  h('button', {
1931
1979
  key: 'e',
@@ -1953,6 +2001,17 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
1953
2001
  'data-cad-feat-down': feature.id,
1954
2002
  onClick: (event) => { event.stopPropagation(); postFeature({ action: 'move', id: feature.id, to: index + 1 }) },
1955
2003
  }, '↓'),
2004
+ h('button', {
2005
+ key: 't',
2006
+ type: 'button',
2007
+ style: { ...styles.microBtn, opacity: graphTip === feature.id ? 1 : 0.55 },
2008
+ title: graphTip === feature.id ? '清除回滚点(恢复算全部)' : '只算到这一步(回滚点)',
2009
+ 'data-cad-feat-tip': feature.id,
2010
+ onClick: (event) => {
2011
+ event.stopPropagation()
2012
+ postFeature({ action: 'tip', id: graphTip === feature.id ? null : feature.id })
2013
+ },
2014
+ }, graphTip === feature.id ? '◉' : '◌'),
1956
2015
  h('button', {
1957
2016
  key: 'x',
1958
2017
  type: 'button',
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)):
@@ -900,9 +900,113 @@ def _prim(op):
900
900
  return Part.Face(Part.makePolygon(ps + [ps[0]])).revolve(Vector(0.0, 0.0, 0.0), Vector(0.0, 0.0, 1.0), ang)
901
901
  raise RuntimeError("未知图元:" + str(k))
902
902
 
903
+ # ---- sub-shape selectors -------------------------------------------------
904
+ # Predicates over geometry, re-evaluated on every rebuild. No persistent ids:
905
+ # OCCT regenerates topology on each operation, so "the 7th face" is not a name.
906
+ # Failure is loud: an empty match raises with the spec and the item counts.
907
+ def _axis_of(_spec):
908
+ _a = _spec.get("axis", "Z")
909
+ if isinstance(_a, (list, tuple)):
910
+ return Vector(float(_a[0]), float(_a[1]), float(_a[2]))
911
+ _v = {"X": Vector(1.0, 0.0, 0.0), "Y": Vector(0.0, 1.0, 0.0), "Z": Vector(0.0, 0.0, 1.0)}.get(str(_a).upper())
912
+ if _v is None:
913
+ raise RuntimeError("选择器的 axis 只能是 X/Y/Z 或 [x,y,z]:%s" % str(_a))
914
+ return _v
915
+
916
+
917
+ def _unit(_v):
918
+ _n = (_v.x * _v.x + _v.y * _v.y + _v.z * _v.z) ** 0.5
919
+ if _n < 1e-12:
920
+ raise RuntimeError("选择器的方向长度为 0")
921
+ return Vector(_v.x / _n, _v.y / _n, _v.z / _n)
922
+
923
+
924
+ def _dot(_a, _b):
925
+ return float(_a.x * _b.x + _a.y * _b.y + _a.z * _b.z)
926
+
927
+
928
+ def _match_dir(_d, _ax, _mode, _sign):
929
+ _u = _unit(_d)
930
+ _a = _unit(_ax)
931
+ _c = _dot(_u, _a)
932
+ if _mode == "parallel":
933
+ return abs(abs(_c) - 1.0) < 1e-3
934
+ if _mode == "perpendicular":
935
+ return abs(_c) < 1e-3
936
+ return _c > 0.999 if _sign != "-" else _c < -0.999
937
+
938
+
939
+ def _center_of(_it):
940
+ _b = _it.BoundBox
941
+ return Vector((_b.XMin + _b.XMax) / 2.0, (_b.YMin + _b.YMax) / 2.0, (_b.ZMin + _b.ZMax) / 2.0)
942
+
943
+
944
+ def _sel(_shape, _kind, _spec):
945
+ if not _spec:
946
+ return []
947
+ if not isinstance(_spec, dict):
948
+ raise RuntimeError("选择器必须是对象:%s" % str(_spec))
949
+ _ax = _axis_of(_spec)
950
+ _mode = _spec.get("mode", "parallel")
951
+ _sign = _spec.get("dir", "+")
952
+ _tol = float(_spec.get("tol", 0.5))
953
+ _want = _spec.get("type")
954
+ _items = list(_shape.Edges) if _kind == "edge" else list(_shape.Faces)
955
+ _word = "条边" if _kind == "edge" else "个面"
956
+ _out = []
957
+ for _it in _items:
958
+ if _want:
959
+ _cls = (_it.Curve.__class__.__name__ if _kind == "edge" else _it.Surface.__class__.__name__).lower()
960
+ if str(_want).lower() not in _cls:
961
+ continue
962
+ if _kind == "edge":
963
+ try:
964
+ _d = _it.tangentAt(_it.FirstParameter)
965
+ except Exception:
966
+ _d = getattr(_it.Curve, "Direction", None)
967
+ if _d is None:
968
+ continue
969
+ else:
970
+ try:
971
+ _d = _it.normalAt(0.5, 0.5)
972
+ except Exception:
973
+ continue
974
+ if not _match_dir(_d, _ax, _mode, _sign):
975
+ continue
976
+ if _spec.get("radius") is not None and _kind == "edge":
977
+ _r = getattr(_it.Curve, "Radius", None)
978
+ if _r is None or abs(float(_r) - float(_spec["radius"])) > _tol:
979
+ continue
980
+ _out.append(_it)
981
+ if not _out:
982
+ raise RuntimeError("选择器没有选中任何%s:%s(当前形状有 %d %s)" % (
983
+ "边" if _kind == "edge" else "面", json.dumps(_spec, ensure_ascii=False), len(_items), _word))
984
+ if _spec.get("near") is not None:
985
+ _p = _v3(_spec["near"])
986
+ _out.sort(key=lambda _it: (_center_of(_it) - _p).Length)
987
+ elif _spec.get("pick") in ("max", "min"):
988
+ _a = _unit(_ax)
989
+ _rev = _spec["pick"] == "max"
990
+ _out.sort(key=lambda _it: _dot(_center_of(_it), _a), reverse=_rev)
991
+ if _spec.get("nth") is not None:
992
+ _i = int(_spec["nth"])
993
+ _out = _out[_i:_i + 1]
994
+ elif _spec.get("pick") in ("max", "min", "near"):
995
+ _out = _out[:1]
996
+ if _spec.get("one") and len(_out) != 1:
997
+ raise RuntimeError("选择器命中了 %d %s,但要求恰好 1 个:%s" % (
998
+ len(_out), _word, json.dumps(_spec, ensure_ascii=False)))
999
+ return _out
1000
+
1001
+
903
1002
  _shape = None
1003
+ _errors = []
1004
+ _executed = 0
904
1005
  for _idx, _op in enumerate(_OPS):
905
1006
  _k = _op.get("kind")
1007
+ if _k == "__skip__":
1008
+ continue
1009
+ _snap = _shape
906
1010
  try:
907
1011
  if _k in ("box", "cylinder", "sphere", "cone", "torus", "extrude", "revolve"):
908
1012
  _s = _prim(_op)
@@ -917,12 +1021,44 @@ for _idx, _op in enumerate(_OPS):
917
1021
  _s = _prim(_w)
918
1022
  _shape = _shape.fuse(_s) if _k == "fuse" else (_shape.cut(_s) if _k == "cut" else _shape.common(_s))
919
1023
  elif _k == "fillet":
920
- _shape = _shape.makeFillet(float(_op["r"]), _shape.Edges)
1024
+ _eds = _sel(_shape, "edge", _op.get("edges")) or list(_shape.Edges)
1025
+ _shape = _shape.makeFillet(float(_op["r"]), _eds)
921
1026
  elif _k == "chamfer":
922
- _shape = _shape.makeChamfer(float(_op["d"]), _shape.Edges)
1027
+ _eds = _sel(_shape, "edge", _op.get("edges")) or list(_shape.Edges)
1028
+ _shape = _shape.makeChamfer(float(_op["d"]), _eds)
923
1029
  elif _k == "shell":
924
1030
  _t = float(_op["t"])
925
1031
  _open = _op.get("open", "none")
1032
+ _open_faces = _sel(_shape, "face", _op.get("faces"))
1033
+ if _open_faces:
1034
+ # Hollow, then cut a prism outward from each chosen face. FreeCAD
1035
+ # 0.20's Part module has no makeThickSolid*; extruding the face
1036
+ # along its own normal is the portable equivalent and keeps the
1037
+ # opening exactly where the selector pointed.
1038
+ _hollow = _shape.makeOffsetShape(-_t, 1e-6)
1039
+ _shell = _shape.cut(_hollow)
1040
+ _far = (_shape.BoundBox.DiagonalLength or 100.0) * 2.0
1041
+ for _f in _open_faces:
1042
+ _cls = _f.Surface.__class__.__name__
1043
+ if _cls != "Plane":
1044
+ raise RuntimeError("shell 的 faces 选择器目前只支持平面(收到 %s)" % _cls)
1045
+ _nrm = _unit(_f.normalAt(0.5, 0.5))
1046
+ # Outward = away from the solid's centre of mass. A face's
1047
+ # stored orientation can point inward; cutting inward would
1048
+ # remove nothing (the interior is already hollow), and
1049
+ # cutting both ways would punch a hole clean through.
1050
+ _away = _center_of(_f) - _shape.CenterOfMass
1051
+ if _dot(_nrm, _away) < 0:
1052
+ _nrm = Vector(0.0 - _nrm.x, 0.0 - _nrm.y, 0.0 - _nrm.z)
1053
+ # Cut the wall itself: start a hair outside the plane and go
1054
+ # inward by exactly the wall thickness. Extruding *outward*
1055
+ # would graze the face and remove nothing.
1056
+ _inn = Vector(0.0 - _nrm.x, 0.0 - _nrm.y, 0.0 - _nrm.z)
1057
+ _pr = _f.translated(_nrm * 0.01).extrude(_inn * (_t + 0.02))
1058
+ _shell = _shell.cut(_pr)
1059
+ _shape = _shell
1060
+ _executed = _idx + 1
1061
+ continue
926
1062
  _inner = _shape.makeOffsetShape(-_t, 1e-6)
927
1063
  _shell = _shape.cut(_inner)
928
1064
  if _open in ("top", "bottom"):
@@ -957,13 +1093,22 @@ for _idx, _op in enumerate(_OPS):
957
1093
  else:
958
1094
  raise RuntimeError("未知特征:" + str(_k))
959
1095
  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))
1096
+ # A failing node must not roll the document back: record it, keep the
1097
+ # last good shape, and stop — every later node is blocked by it, which
1098
+ # is what a parametric CAD does (the bad feature is the one to fix).
1099
+ _shape = _snap
1100
+ _errors.append({
1101
+ "id": _op.get("_id", "?"),
1102
+ "step": _idx + 1,
1103
+ "kind": _k,
1104
+ "label": _op.get("_label") or "",
1105
+ "message": str(_e),
1106
+ })
1107
+ break
1108
+ _executed = _idx + 1
964
1109
 
965
1110
  if _shape is None:
966
- raise RuntimeError("ops 为空:至少给一个图元")
1111
+ raise RuntimeError(_errors[0]["message"] if _errors else "ops 为空:至少给一个图元")
967
1112
  _shape = _shape.removeSplitter()
968
1113
  scene = _shape
969
1114
  __out = {
@@ -973,6 +1118,8 @@ __out = {
973
1118
  "area": round(_shape.Area, 3),
974
1119
  "faces": len(_shape.Faces),
975
1120
  "bounds": _bounds(_shape),
1121
+ "errors": _errors,
1122
+ "executed": _executed,
976
1123
  }
977
1124
  if _EXPORT:
978
1125
  os.makedirs(os.path.dirname(_EXPORT) or ".", exist_ok=True)
@@ -1998,11 +2145,25 @@ if _TARGET:
1998
2145
  // a declarative feature list. Older files predate the field and are scripts.
1999
2146
  doc.kind = doc.kind === 'features' ? 'features' : 'script'
2000
2147
  doc.features = Array.isArray(doc.features) ? doc.features : []
2148
+ // Schema 2 keeps the list under `graph.nodes`; `features` stays the in-memory
2149
+ // name so every caller keeps working. Reading an old file migrates it.
2150
+ if (doc.graph && Array.isArray(doc.graph.nodes)) doc.features = doc.graph.nodes
2151
+ doc.schema = 2
2152
+ doc.tip = typeof doc.tip === 'string' && doc.tip ? doc.tip : null
2153
+ doc.undo = Array.isArray(doc.undo) ? doc.undo : []
2154
+ doc.redo = Array.isArray(doc.redo) ? doc.redo : []
2155
+ for (const f of doc.features) if (f && typeof f === 'object' && typeof f.suppressed === 'boolean') f.enabled = f.suppressed !== true
2001
2156
  return doc
2002
2157
  }
2003
2158
 
2004
2159
  const writeModel = async (doc, dir) => {
2005
2160
  await mkdir(dir, { recursive: true })
2161
+ doc.schema = 2
2162
+ // Only feature documents have a graph; a script document is code-not-data.
2163
+ if (Array.isArray(doc.features)) {
2164
+ doc.graph = { tip: doc.tip ?? null, nodes: doc.features }
2165
+ for (const f of doc.features) f.suppressed = f.enabled === false
2166
+ }
2006
2167
  const body = JSON.stringify(doc, null, 2)
2007
2168
  await writeFile(modelFile(doc.name, dir), body, 'utf8')
2008
2169
  return doc
@@ -2015,12 +2176,40 @@ if _TARGET:
2015
2176
  label: f.label ?? '',
2016
2177
  params: f.params ?? {},
2017
2178
  enabled: f.enabled !== false,
2179
+ suppressed: f.enabled === false,
2018
2180
  }))
2019
2181
 
2020
2182
  /** Feature objects to flat ops (`{kind, ...params}`) for the Python emitter. */
2021
- const featureOps = (doc) => doc.features
2022
- .filter((f) => f.enabled !== false)
2023
- .map((f) => ({ kind: f.kind, ...(f.params ?? {}), _id: f.id, _label: f.label || '' }))
2183
+ /**
2184
+ * Nodes to evaluate, in order, honouring `tip` (rollback bar) and suppression.
2185
+ *
2186
+ * A suppressed node is not "skip and keep going": everything after it was
2187
+ * built on a shape that no longer exists, so evaluation stops there and the
2188
+ * rest is reported as blocked. This mirrors FreeCAD/Onshape rather than
2189
+ * silently computing against the wrong shape.
2190
+ */
2191
+ const featureOps = (doc, { stopAtSuppressed = true } = {}) => {
2192
+ const list = Array.isArray(doc.features) ? doc.features : []
2193
+ const tipAt = doc.tip ? list.findIndex((f) => String(f.id) === String(doc.tip)) : -1
2194
+ const end = tipAt >= 0 ? tipAt + 1 : list.length
2195
+ const ops = []
2196
+ for (let i = 0; i < end; i += 1) {
2197
+ const f = list[i]
2198
+ if (!f) continue
2199
+ // Suppression skips the node. Until typed selectors land (Phase 2) we
2200
+ // cannot tell whether a later node depended on its outputs, so skipping
2201
+ // is the honest default: the graph shows it as skipped, and a node that
2202
+ // really needed it will fail loudly instead of silently reading something
2203
+ // else. (Stopping the whole chain would break the common "mute one fillet
2204
+ // and keep working" case.)
2205
+ if (f.enabled === false) {
2206
+ if (stopAtSuppressed) ops.push({ kind: '__skip__', _id: f.id, _label: f.label || '' })
2207
+ continue
2208
+ }
2209
+ ops.push({ kind: f.kind, ...(f.params ?? {}), _id: f.id, _label: f.label || '' })
2210
+ }
2211
+ return ops
2212
+ }
2024
2213
 
2025
2214
  const FEATURE_FIELDS = ['id', 'kind', 'label', 'params', 'enabled']
2026
2215
 
@@ -2092,12 +2281,39 @@ if _TARGET:
2092
2281
  * documents re-emit the whole feature list — which is why editing one feature
2093
2282
  * is cheap and cannot leave the model half-updated.
2094
2283
  */
2284
+ /**
2285
+ * Per-node status for the panel and for the caller: ok / failed / blocked /
2286
+ * skipped. Derived from what the kernel actually executed, not guessed.
2287
+ */
2288
+ const graphView = (doc, out) => {
2289
+ const list = Array.isArray(doc.features) ? doc.features : []
2290
+ const errors = Array.isArray(out?.errors) ? out.errors : []
2291
+ const failedAt = new Map(errors.map((e) => [String(e.id), e]))
2292
+ const executed = Number.isFinite(out?.executed) ? Number(out.executed) : null
2293
+ const tipAt = doc.tip ? list.findIndex((f) => String(f.id) === String(doc.tip)) : -1
2294
+ const end = tipAt >= 0 ? tipAt + 1 : list.length
2295
+ let why = ''
2296
+ const nodes = list.map((f, i) => {
2297
+ const base = { id: f.id, kind: f.kind, label: f.label ?? '', suppressed: f.enabled === false }
2298
+ if (i >= end) return { ...base, status: 'skipped', message: '在回滚点之后' }
2299
+ if (why) return { ...base, status: 'blocked', message: why }
2300
+ // Skipping is not a failure: the node is not evaluated, the tree keeps
2301
+ // building (see featureOps).
2302
+ if (base.suppressed) return { ...base, status: 'skipped', message: '被抑制(跳过)' }
2303
+ const err = failedAt.get(String(f.id))
2304
+ if (err) { why = `因为 ${f.id} 失败`; return { ...base, status: 'failed', message: err.message } }
2305
+ if (executed !== null && i >= executed) { why = `因为 ${f.id} 没有执行`; return { ...base, status: 'blocked', message: why } }
2306
+ return { ...base, status: 'ok', message: '' }
2307
+ })
2308
+ return { tip: doc.tip ?? null, nodes }
2309
+ }
2310
+
2095
2311
  const rebuild = async (doc, dir, { note } = {}) => {
2096
2312
  const isFeatures = doc.kind === 'features'
2097
2313
  const code = isFeatures
2098
2314
  ? featuresScript(featureOps(doc))
2099
2315
  : `${PRELUDE}\nP = ${JSON.stringify(doc.params ?? {})}\n${doc.script}`
2100
- const meta = isFeatures ? { model: doc.name, features: publicFeatures(doc) } : { model: doc.name, params: doc.params ?? {} }
2316
+ const meta = isFeatures ? { model: doc.name, features: publicFeatures(doc), tip: doc.tip ?? null } : { model: doc.name, params: doc.params ?? {} }
2101
2317
  doc.run = (doc.run ?? 0) + 1
2102
2318
  doc.updatedAt = new Date().toISOString()
2103
2319
  // One row per model: a rebuild rewrites the model's existing scene.
@@ -2107,7 +2323,7 @@ if _TARGET:
2107
2323
  docKey: `model:${doc.name}`,
2108
2324
  sceneId: doc.stats?.sceneId || '',
2109
2325
  })
2110
- if (out.ok === false) return { ...out, name: doc.name, params: doc.params }
2326
+ if (out.ok === false) return { ...out, name: doc.name, params: doc.params, graph: graphView(doc, out) }
2111
2327
  // run() returns volume/bounds but not triangle count, so read it back from
2112
2328
  // the row that was just published (a null here forced the panel to guess).
2113
2329
  const sceneId = out.sceneId ?? ''
@@ -2120,11 +2336,22 @@ if _TARGET:
2120
2336
  at: doc.updatedAt,
2121
2337
  }
2122
2338
  if (note) doc.note = note
2339
+ // The scene was published before the kernel reported which nodes failed, so
2340
+ // attach the statuses now: the panel paints dots from payload.graph.
2341
+ const graph = graphView(doc, out)
2342
+ const scene = sceneId ? bridge.scenes?.get(sceneId) : null
2343
+ if (scene) {
2344
+ scene.graph = graph
2345
+ try { await bridge.persist() } catch {}
2346
+ }
2123
2347
  await writeModel(doc, dir)
2124
2348
  return {
2125
2349
  ok: true,
2350
+ evaluated: !(Array.isArray(out.errors) && out.errors.length > 0),
2126
2351
  name: doc.name,
2127
2352
  dir,
2353
+ graph,
2354
+ errors: Array.isArray(out.errors) ? out.errors : [],
2128
2355
  run: doc.run,
2129
2356
  params: doc.params,
2130
2357
  volume: doc.stats.volume,
@@ -2193,9 +2420,15 @@ if _TARGET:
2193
2420
  throw new Error(`${doc.name} 是脚本模型,没有特征列表(用 cad_studio_doc update 改 params,或新建 kind="features" 的模型)`)
2194
2421
  }
2195
2422
  if (action === 'list') {
2196
- return { ok: true, model: doc.name, kind: doc.kind, features: publicFeatures(doc), stats: doc.stats ?? null }
2423
+ return { ok: true, model: doc.name, kind: doc.kind, features: publicFeatures(doc), graph: graphView(doc, { errors: [], executed: null }), stats: doc.stats ?? null }
2424
+ }
2425
+ const snapshot = () => JSON.parse(JSON.stringify({ features: doc.features, tip: doc.tip ?? null }))
2426
+ const restore = (snap) => {
2427
+ doc.features = JSON.parse(JSON.stringify(snap.features))
2428
+ doc.tip = snap.tip ?? null
2197
2429
  }
2198
2430
  const before = JSON.parse(JSON.stringify(doc.features))
2431
+ const undoSnap = snapshot()
2199
2432
  const feature = args.feature && typeof args.feature === 'object' ? args.feature : {}
2200
2433
  const wanted = String(args.id ?? feature.id ?? '')
2201
2434
  const findAt = () => doc.features.findIndex((f) => String(f.id) === wanted)
@@ -2224,21 +2457,53 @@ if _TARGET:
2224
2457
  const [item] = doc.features.splice(at, 1)
2225
2458
  const to = Number.isFinite(Number(args.to)) ? Math.max(0, Math.min(doc.features.length, Math.round(Number(args.to)))) : doc.features.length
2226
2459
  doc.features.splice(to, 0, item)
2227
- } else if (action === 'toggle') {
2460
+ } else if (action === 'toggle' || action === 'suppress') {
2228
2461
  const at = findAt()
2229
2462
  if (at < 0) throw new Error(`没有这个特征:${wanted || '(空)'}`)
2463
+ // Suppression is document state, not a delete: the feature keeps its
2464
+ // params and its place, and everything downstream reports as blocked.
2230
2465
  const want = feature.enabled !== undefined ? feature.enabled !== false : doc.features[at].enabled === false
2231
2466
  doc.features[at].enabled = want
2467
+ } else if (action === 'tip') {
2468
+ if (!wanted) doc.tip = null
2469
+ else if (findAt() < 0) throw new Error(`没有这个特征:${wanted}`)
2470
+ else doc.tip = wanted
2471
+ } else if (action === 'undo' || action === 'redo') {
2472
+ const from = action === 'undo' ? doc.undo : doc.redo
2473
+ const to = action === 'undo' ? doc.redo : doc.undo
2474
+ if (!from.length) throw new Error(action === 'undo' ? '没有可撤销的操作' : '没有可重做的操作')
2475
+ const entry = from.pop()
2476
+ to.push(entry)
2477
+ restore(action === 'undo' ? entry.before : entry.after)
2232
2478
  } else {
2233
2479
  throw new Error(`未知 action:${action}(可用 list / add / update / remove / move / toggle)`)
2234
2480
  }
2235
2481
  if (!doc.features.length) throw new Error('特征列表不能为空:至少留一个图元')
2236
2482
 
2237
- const result = await rebuild(doc, dir, { note: `${action} ${wanted || feature.kind || ''}`.trim() })
2483
+ const label = `${action} ${wanted || feature.kind || ''}`.trim()
2484
+ const result = await rebuild(doc, dir, { note: label })
2238
2485
  if (result.ok === false) {
2239
- doc.features = before
2486
+ // Keep the edit. A document that describes an unbuildable shape is more
2487
+ // useful than a silent rollback: the panel shows which node failed, and
2488
+ // undo is one keystroke away.
2240
2489
  await writeModel(doc, dir)
2241
- return { ...result, reverted: true, hint: '这次修改没跑通,特征列表已回退到上一版;改完再试。' }
2490
+ // "ok" answers "did the document accept the edit"; the geometry answer
2491
+ // lives in evaluated/errors/graph. A reorder can legitimately leave the
2492
+ // tree unevaluable (a fillet moved above its body) and that must stay
2493
+ // visible rather than being rejected — you fix it by reading the graph.
2494
+ return {
2495
+ ...result,
2496
+ ok: true,
2497
+ saved: true,
2498
+ evaluated: false,
2499
+ features: publicFeatures(doc),
2500
+ hint: '这条改动已存进文档,但求值失败——看 graph 里哪条是 failed,改好或撤销。',
2501
+ }
2502
+ }
2503
+ if (!['undo', 'redo'].includes(action)) {
2504
+ doc.undo.push({ at: new Date().toISOString(), action, target: wanted || feature.kind || '', before: undoSnap, after: snapshot() })
2505
+ doc.undo = doc.undo.slice(-50)
2506
+ doc.redo = []
2242
2507
  }
2243
2508
  doc.history.push({
2244
2509
  at: doc.updatedAt,
@@ -2252,10 +2517,15 @@ if _TARGET:
2252
2517
  await writeModel(doc, dir)
2253
2518
  return {
2254
2519
  ok: true,
2520
+ evaluated: result.ok !== false && (result.errors ?? []).length === 0,
2255
2521
  model: doc.name,
2256
2522
  kind: doc.kind,
2257
2523
  action,
2258
2524
  features: publicFeatures(doc),
2525
+ graph: result.graph,
2526
+ errors: result.errors ?? [],
2527
+ undo: doc.undo.length,
2528
+ redo: doc.redo.length,
2259
2529
  volume: doc.stats?.volume ?? null,
2260
2530
  triangles: doc.stats?.triangles ?? null,
2261
2531
  sceneId: doc.stats?.sceneId ?? '',
@@ -2265,12 +2535,12 @@ if _TARGET:
2265
2535
 
2266
2536
  tool({
2267
2537
  name: 'cad_studio_features',
2268
- 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.`,
2538
+ 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.`,
2269
2539
  parameters: {
2270
2540
  type: 'object',
2271
2541
  properties: {
2272
2542
  model: { type: 'string', description: 'Feature-list model name (created with cad_studio_doc kind="features").' },
2273
- action: { type: 'string', enum: ['list', 'add', 'update', 'remove', 'move', 'toggle'] },
2543
+ action: { type: 'string', enum: ['list', 'add', 'update', 'remove', 'move', 'toggle', 'suppress', 'tip', 'undo', 'redo'] },
2274
2544
  feature: { type: 'object', description: 'add: the feature to append. update/toggle: {id, ...fields to change}. remove/move: {id}.' },
2275
2545
  id: { type: 'string', description: 'Feature id (f1, f2 …); alternative to feature.id.' },
2276
2546
  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.1",
3
+ "version": "0.6.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
+ }