dsh-cad-studio 0.8.2 → 0.8.4

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 (3) hide show
  1. package/README.md +11 -1
  2. package/index.js +182 -3
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -4,7 +4,7 @@ DeepSeek Harness 的 CAD 插件:**把 FreeCAD 桥接成给 AI 用的工具**
4
4
 
5
5
  ![CAD 工作室面板](https://raw.githubusercontent.com/STofone/dsh-cad-studio/main/docs/preview.png)
6
6
 
7
- - Host 侧(`index.js`):16 个工具 + `/cad-studio/*` HTTP 路由 + `freecadcmd` 子进程桥
7
+ - Host 侧(`index.js`):18 个工具 + `/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
 
@@ -138,6 +138,16 @@ 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
+ | 层 | 覆盖 | 谁能用 |
144
+ |---|---|---|
145
+ | 文档 | 特征增删改、移动、抑制、回滚点、变量 | 面板 `Ctrl+Z` / 工具 `cad_studio_features {action:"undo"}` |
146
+ | 装配 | 关节值、关节增删、爆炸系数 | 工具 `cad_studio_undo` / `cad_studio_redo`(`scope: auto|assembly|doc`) |
147
+ | 外观 | 透明度、颜色、显隐、线框、隔离 | 面板 `Ctrl+Z` / 右下角 ↶↷(只活在这个浏览器页签里) |
148
+
149
+ `scope:auto` 先看装配栈,空则退回文档栈(文档栈要求给 `model`)。导出写文件、出工程图、删模型属于不可逆动作,不进任何栈。
150
+
141
151
  ### 视图撤销
142
152
 
143
153
  透明度、颜色、显隐、线框这些**外观改动**也进撤销栈(服务端 `doc.undo` 只管文档结构,管不到它们):同一目标 1.5 s 内的连续拖动合并成一条,切场景清空,最多 40 步。面板「活跃」时(焦点在面板内,或 8 s 内点过面板)按 `Ctrl/Cmd+Z` 撤销、`Shift+Ctrl/Cmd+Z` 或 `Ctrl+Y` 重做;视口右下角还有一对 ↶ / ↷ 按钮,没东西可撤销时是灰的。输入框里的 `Ctrl+Z` 不劫持,「特征」页签里仍归文档撤销。
package/index.js CHANGED
@@ -184,6 +184,15 @@ function diagnose(bridge, cfg = {}) {
184
184
  }
185
185
  }
186
186
 
187
+ const renderUndo = (v) => {
188
+ if (!v || v.ok === false) return `✗ ${v?.error ?? '没有可撤销的操作'}`
189
+ if (v.scope === 'assembly') {
190
+ const head = v.undone !== undefined ? `↶ 撤销了装配改动(${v.undone})` : `↷ 重做了装配改动(${v.redone})`
191
+ return `${head},还可撤销 ${v.remaining ?? 0} 步 / 可重做 ${v.redo ?? v.undo ?? 0} 步`
192
+ }
193
+ return `${v.undone !== undefined ? '↶ 撤销' : '↷ 重做'}:文档 ${v.model}${v.evaluated === false ? '(求值失败,见 graph)' : ''}`
194
+ }
195
+
187
196
  const renderDoctor = (v) => {
188
197
  const lines = [`ready: ${v.ready ? 'yes' : 'no'}`]
189
198
  if (v.kernel) lines.push(`kernel: ${v.kernel}`)
@@ -531,6 +540,8 @@ class FreeCadBridge {
531
540
  this.touched = new Set()
532
541
  /** Assemblies keep their base placements so joints can re-place instances. */
533
542
  this.assemblies = new Map()
543
+ this.sessionUndo = []
544
+ this.sessionRedo = []
534
545
  this.assemblySeq = 0
535
546
  /**
536
547
  * Models live in the session's workspace, but the panel posts without a
@@ -772,10 +783,27 @@ class FreeCadBridge {
772
783
  * otherwise only removable by editing state.json by hand — which is exactly
773
784
  * how a 28-row list happened in the first place.
774
785
  */
775
- async removeScene(id) {
786
+ async removeScene(id, opts = {}) {
776
787
  const key = String(id ?? '')
777
788
  const row = this.history.find((h) => h.id === key)
778
789
  if (!row) throw new Error(`没有这个场景:${key}(可用 ${this.history.map((h) => h.id).join(', ') || '(无)'})`)
790
+ const snapshot = JSON.parse(JSON.stringify(row))
791
+ let bytes = null
792
+ if (opts.journal !== false) {
793
+ try { bytes = await readFile(join(FreeCadBridge.dataDir, 'scenes', `${key}.json`)) } catch {}
794
+ this.journal({
795
+ kind: 'scene',
796
+ label: `delete ${key}`,
797
+ undo: async () => {
798
+ this.history = [snapshot, ...this.history.filter((h) => h.id !== key)]
799
+ if (bytes) await writeFile(join(FreeCadBridge.dataDir, 'scenes', `${key}.json`), bytes)
800
+ this.latest = { id: snapshot.id, title: snapshot.title, at: snapshot.at, scene: this.scenes.get(key) ?? null }
801
+ await this.persist()
802
+ return { scene: key }
803
+ },
804
+ redo: async () => { await this.removeScene(key, { journal: false }); return { scene: key } },
805
+ })
806
+ }
779
807
  this.history = this.history.filter((h) => h.id !== key)
780
808
  this.scenes.delete(key)
781
809
  for (const [asmId, rec] of [...this.assemblies]) if (rec.sceneId === key) this.assemblies.delete(asmId)
@@ -788,12 +816,21 @@ class FreeCadBridge {
788
816
  return { ok: true, removed: key, scenes: this.history.length, latest: this.latest ? this.latest.id : '' }
789
817
  }
790
818
 
791
- async renameScene(id, title) {
819
+ async renameScene(id, title, opts = {}) {
792
820
  const key = String(id ?? '')
793
821
  const row = this.history.find((h) => h.id === key)
794
822
  if (!row) throw new Error(`没有这个场景:${key}`)
795
823
  const name = String(title ?? '').trim()
796
824
  if (!name) throw new Error('新名字不能为空')
825
+ const old = row.title
826
+ if (opts.journal !== false && old !== name) {
827
+ this.journal({
828
+ kind: 'scene',
829
+ label: `rename ${key}`,
830
+ undo: async () => { await this.renameScene(key, old, { journal: false }); return { scene: key, title: old } },
831
+ redo: async () => { await this.renameScene(key, name, { journal: false }); return { scene: key, title: name } },
832
+ })
833
+ }
797
834
  row.title = name
798
835
  if (this.latest && this.latest.id === key) this.latest = { ...this.latest, title: name }
799
836
  await this.persist()
@@ -855,6 +892,63 @@ class FreeCadBridge {
855
892
  return record.explode
856
893
  }
857
894
 
895
+ // ---- 装配层撤销:关节值 / 关节增删 / 爆炸系数 ----
896
+ snapshotAssembly(record) {
897
+ return { id: record.id, joints: JSON.parse(JSON.stringify(record.joints ?? [])), explode: record.explode ?? 0 }
898
+ }
899
+
900
+ beginAssemblyEdit(record, label) {
901
+ return { label, assembly: record.id, before: this.snapshotAssembly(record), after: null }
902
+ }
903
+
904
+ endAssemblyEdit(entry, record) {
905
+ if (!entry) return
906
+ const before = entry.before
907
+ const after = this.snapshotAssembly(record)
908
+ this.journal({
909
+ kind: 'assembly',
910
+ label: entry.label,
911
+ undo: async () => this.applyAssemblySnapshot(before),
912
+ redo: async () => this.applyAssemblySnapshot(after),
913
+ })
914
+ }
915
+
916
+ /** One stack for every undoable mutation, in the order it happened. */
917
+ journal(entry) {
918
+ this.sessionUndo.push({ at: new Date().toISOString(), ...entry })
919
+ if (this.sessionUndo.length > 50) this.sessionUndo.shift()
920
+ this.sessionRedo = []
921
+ }
922
+
923
+ async applyAssemblySnapshot(snapshot) {
924
+ const record = await this.loadAssembly(snapshot.id)
925
+ if (!record) throw new Error(`没有这个装配:${snapshot.id}`)
926
+ record.joints = JSON.parse(JSON.stringify(snapshot.joints))
927
+ record.explode = Math.max(0, Math.min(4, Number(snapshot.explode) || 0))
928
+ const published = await this.republishAssembly(record)
929
+ return { record, published }
930
+ }
931
+
932
+ async undoSession(kind) {
933
+ const stack = kind ? this.sessionUndo.filter((e) => e.kind === kind) : this.sessionUndo
934
+ const entry = stack[stack.length - 1]
935
+ if (!entry) return null
936
+ this.sessionUndo = this.sessionUndo.filter((e) => e !== entry)
937
+ const out = await entry.undo()
938
+ this.sessionRedo.push(entry)
939
+ return { label: entry.label, kind: entry.kind, ...(out ?? {}) }
940
+ }
941
+
942
+ async redoSession(kind) {
943
+ const stack = kind ? this.sessionRedo.filter((e) => e.kind === kind) : this.sessionRedo
944
+ const entry = stack[stack.length - 1]
945
+ if (!entry) return null
946
+ this.sessionRedo = this.sessionRedo.filter((e) => e !== entry)
947
+ const out = await entry.redo()
948
+ this.sessionUndo.push(entry)
949
+ return { label: entry.label, kind: entry.kind, ...(out ?? {}) }
950
+ }
951
+
858
952
  /** Recompute instance placements from base + joints + explode, then publish. */
859
953
  async republishAssembly(record) {
860
954
  const scene = assembleScene(record)
@@ -1655,6 +1749,62 @@ __out = {
1655
1749
  },
1656
1750
  })
1657
1751
 
1752
+ tool({
1753
+ name: 'cad_studio_undo',
1754
+ description: 'Undo the last change. scope=auto prefers the assembly stack (joint value, joint add/remove, explode factor), otherwise falls back to the model document stack; pass model for doc scope.',
1755
+ parameters: {
1756
+ type: 'object',
1757
+ properties: {
1758
+ scope: { type: 'string', enum: ['auto', 'assembly', 'scene', 'doc'], description: 'default auto' },
1759
+ model: { type: 'string', description: 'document name, for doc scope' },
1760
+ },
1761
+ },
1762
+ output: { schema: { type: 'object' }, render: (args, value) => [{ type: 'text', text: renderUndo(value) }] },
1763
+ async execute(args, exec) {
1764
+ const scope = typeof args.scope === 'string' ? args.scope : 'auto'
1765
+ const kind = scope === 'auto' ? undefined : scope
1766
+ const undone = await bridge.undoSession(kind)
1767
+ if (undone) return { ok: true, scope: undone.kind, undone: undone.label, assembly: undone.assembly, scene: undone.scene, model: undone.model, remaining: bridge.sessionUndo.length, redo: bridge.sessionRedo.length }
1768
+ if (scope !== 'doc') return { ok: false, error: scope === 'assembly' ? '装配层没有可撤销的操作' : scope === 'scene' ? '场景列表没有可撤销的操作' : '没有可撤销的操作' }
1769
+ const target = typeof args.model === 'string' && args.model ? args.model : ''
1770
+ if (!target) return { ok: false, error: '文档撤销需要 model 名称(可用 cad_studio_doc list 查看)' }
1771
+ try {
1772
+ const out = await runFeatureAction({ model: target, action: 'undo' }, modelsDirFor(exec))
1773
+ return { ok: out?.ok !== false, scope: 'doc', model: target, undone: 'doc', ...out }
1774
+ } catch (error) {
1775
+ return { ok: false, error: `文档撤销失败:${String(error?.message ?? error)}(脚本模型请用 cad_studio_doc revert)` }
1776
+ }
1777
+ },
1778
+ })
1779
+
1780
+ tool({
1781
+ name: 'cad_studio_redo',
1782
+ description: 'Redo the last undone change, same scopes as cad_studio_undo.',
1783
+ parameters: {
1784
+ type: 'object',
1785
+ properties: {
1786
+ scope: { type: 'string', enum: ['auto', 'assembly', 'scene', 'doc'], description: 'default auto' },
1787
+ model: { type: 'string', description: 'document name, for doc scope' },
1788
+ },
1789
+ },
1790
+ output: { schema: { type: 'object' }, render: (args, value) => [{ type: 'text', text: renderUndo(value) }] },
1791
+ async execute(args, exec) {
1792
+ const scope = typeof args.scope === 'string' ? args.scope : 'auto'
1793
+ const kindR = scope === 'auto' ? undefined : scope
1794
+ const redone = await bridge.redoSession(kindR)
1795
+ if (redone) return { ok: true, scope: redone.kind, redone: redone.label, assembly: redone.assembly, scene: redone.scene, model: redone.model, remaining: bridge.sessionRedo.length, undo: bridge.sessionUndo.length }
1796
+ if (scope !== 'doc') return { ok: false, error: scope === 'assembly' ? '装配层没有可重做的操作' : '没有可重做的操作' }
1797
+ const target = typeof args.model === 'string' && args.model ? args.model : ''
1798
+ if (!target) return { ok: false, error: '文档重做需要 model 名称' }
1799
+ try {
1800
+ const out = await runFeatureAction({ model: target, action: 'redo' }, modelsDirFor(exec))
1801
+ return { ok: out?.ok !== false, scope: 'doc', model: target, redone: 'doc', ...out }
1802
+ } catch (error) {
1803
+ return { ok: false, error: `文档重做失败:${String(error?.message ?? error)}(脚本模型请用 cad_studio_doc revert)` }
1804
+ }
1805
+ },
1806
+ })
1807
+
1658
1808
  tool({
1659
1809
  name: 'cad_studio_scene',
1660
1810
  description: 'Maintain the model list the panel shows (the persisted scene history): action=list / delete / rename. Use delete to clear probe scenes that a measurement run left behind, and rename when a scene title is a file path or a part id.',
@@ -2356,6 +2506,7 @@ if _TARGET:
2356
2506
  const published = await bridge.republishAssembly(record)
2357
2507
  return { ok: true, assembly: record.id, removed: joint, sceneId: published.id, joints: record.joints.length }
2358
2508
  }
2509
+ const edit = bridge.beginAssemblyEdit(record, 'joint')
2359
2510
  let stored
2360
2511
  try {
2361
2512
  stored = bridge.setJoint(record, { ...spec, id: spec.id })
@@ -2363,6 +2514,7 @@ if _TARGET:
2363
2514
  return { ok: false, error: String(error?.message ?? error) }
2364
2515
  }
2365
2516
  const published = await bridge.republishAssembly(record)
2517
+ bridge.endAssemblyEdit(edit, record)
2366
2518
  return {
2367
2519
  ok: true,
2368
2520
  assembly: record.id,
@@ -2399,9 +2551,11 @@ if _TARGET:
2399
2551
  }
2400
2552
  if (!record.joints.length) return { ok: false, error: '这个装配还没有关节:先 cad_studio_joint set 建一个' }
2401
2553
  const id = joint ?? record.joints[0].id
2554
+ const edit = bridge.beginAssemblyEdit(record, 'drive')
2402
2555
  const moved = bridge.driveJoint(record, id, value)
2403
2556
  if (!moved) return { ok: false, error: `没有这个关节:${id}(现有 ${record.joints.map((j) => j.id).join(', ')})` }
2404
2557
  const published = await bridge.republishAssembly(record)
2558
+ bridge.endAssemblyEdit(edit, record)
2405
2559
  return {
2406
2560
  ok: true,
2407
2561
  assembly: record.id,
@@ -2437,9 +2591,11 @@ if _TARGET:
2437
2591
  } catch (error) {
2438
2592
  return { ok: false, error: String(error?.message ?? error) }
2439
2593
  }
2594
+ const edit = bridge.beginAssemblyEdit(record, 'explode')
2440
2595
  const next = bridge.setExplode(record, factor ?? 1)
2441
2596
  if (next === null) return { ok: false, error: 'factor 必须是数字' }
2442
2597
  const published = await bridge.republishAssembly(record)
2598
+ bridge.endAssemblyEdit(edit, record)
2443
2599
  return { ok: true, assembly: record.id, sceneId: published.id, explode: round6(next), instances: published.stats.instances }
2444
2600
  },
2445
2601
  })
@@ -3139,7 +3295,26 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
3139
3295
 
3140
3296
  if (action === 'delete') {
3141
3297
  const key = checkName(args.name)
3142
- await unlink(modelFile(key, dir)).catch(() => { throw new Error(`没有这个模型:${key}`) })
3298
+ const file = modelFile(key, dir)
3299
+ let bytes = null
3300
+ try { bytes = await readFile(file) } catch { throw new Error(`没有这个模型:${key}`) }
3301
+ const sceneRow = bridge.history.find((h) => h.title === key || (h.docKey === `model:${key}`))
3302
+ bridge.journal({
3303
+ kind: 'doc',
3304
+ label: `delete ${key}`,
3305
+ undo: async () => {
3306
+ await writeFile(file, bytes)
3307
+ const doc = await readModel(key, dir)
3308
+ try { await rebuild(doc, dir, { note: 'undo delete' }) } catch {}
3309
+ return { model: key }
3310
+ },
3311
+ redo: async () => {
3312
+ await unlink(file).catch(() => {})
3313
+ if (sceneRow) { try { await bridge.removeScene(sceneRow.id, { journal: false }) } catch {} }
3314
+ return { model: key }
3315
+ },
3316
+ })
3317
+ await unlink(file).catch(() => { throw new Error(`没有这个模型:${key}`) })
3143
3318
  return { ok: true, name: key, deleted: true, dir }
3144
3319
  }
3145
3320
 
@@ -3329,14 +3504,18 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
3329
3504
  if (!record) return send(404, JSON.stringify({ error: 'no assembly' }))
3330
3505
  if (url.pathname.endsWith('/drive')) {
3331
3506
  const jointId = typeof body?.joint === 'string' ? body.joint : record.joints[0]?.id
3507
+ const editLive = live.beginAssemblyEdit(record, 'drive')
3332
3508
  const moved = live.driveJoint(record, jointId, body?.value)
3333
3509
  if (!moved) return send(400, JSON.stringify({ error: 'bad joint or value' }))
3334
3510
  const published = await live.republishAssembly(record)
3511
+ live.endAssemblyEdit(editLive, record)
3335
3512
  return send(200, JSON.stringify({ ok: true, sceneId: published.id, at: published.stats.at, joint: moved.id, value: round6(moved.value) }))
3336
3513
  }
3514
+ const editLive = live.beginAssemblyEdit(record, 'explode')
3337
3515
  const next = live.setExplode(record, body?.factor ?? 1)
3338
3516
  if (next === null) return send(400, JSON.stringify({ error: 'bad factor' }))
3339
3517
  const published = await live.republishAssembly(record)
3518
+ live.endAssemblyEdit(editLive, record)
3340
3519
  return send(200, JSON.stringify({ ok: true, sceneId: published.id, at: published.stats.at, explode: round6(next) }))
3341
3520
  }
3342
3521
  if (url.pathname.startsWith(`${ROUTE_PREFIX}/scene/`)) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cad-studio",
3
- "version": "0.8.2",
3
+ "version": "0.8.4",
4
4
  "type": "module",
5
5
  "description": "CAD Studio — FreeCAD 桥(给 AI 的 14 个工具)+ Web 右栏 3D 面板:建模/装配/关节运动/出图/多页签查看",
6
6
  "exports": {