dsh-cad-studio 0.2.3 → 0.2.5

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/client.js +117 -73
  2. package/index.js +36 -12
  3. package/package.json +1 -1
package/client.js CHANGED
@@ -146,6 +146,8 @@ window.__ModuleLoader__.load({
146
146
  propLabel: { fontSize: 10.5, opacity: 0.62, flex: 'none', width: 34 },
147
147
  propValue: { marginLeft: 'auto', fontSize: 10, opacity: 0.75, fontVariantNumeric: 'tabular-nums', flex: 'none' },
148
148
  slider: { flex: '1 1 auto', minWidth: 0, height: 14, accentColor: '#4d6bfe', cursor: 'pointer' },
149
+ jointNum: { width: 52, flex: '0 0 auto', padding: '1px 3px', fontSize: 10.5, textAlign: 'right', color: 'inherit', background: 'rgba(125,135,155,0.12)', border: '1px solid transparent', borderRadius: 4, outline: 'none', fontVariantNumeric: 'tabular-nums' },
150
+ sliderRow: { display: 'flex', alignItems: 'center', gap: 6, padding: '0 8px 5px 8px' },
149
151
  propBtn: { font: 'inherit', fontSize: 10.5, padding: '3px 8px', borderRadius: 5, border: '1px solid', background: 'transparent', color: 'inherit', cursor: 'pointer', whiteSpace: 'nowrap' },
150
152
  propBtns: { display: 'flex', flexWrap: 'wrap', gap: 5, padding: '6px 2px 2px' },
151
153
  propEmpty: { padding: '10px 6px', fontSize: 10.5, opacity: 0.6, lineHeight: 1.7 },
@@ -970,7 +972,6 @@ window.__ModuleLoader__.load({
970
972
  /** Host config: 'session' | 'always' | 'off' — see index.js DEFAULTS.autoOpen. */
971
973
  let cadAutoOpen = 'session'
972
974
  /** Memo for "does this session own CAD work", keyed by session id. */
973
- let ownsCache = { id: '', owns: false, at: 0 }
974
975
 
975
976
  function Viewport({ payload, visibility, options, handleRef: externalHandle }) {
976
977
  const hostRef = useRef(null)
@@ -1641,21 +1642,52 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
1641
1642
  ...(assembly.joints || []).map((joint) => {
1642
1643
  const value = motionDraft[joint.id] !== undefined ? motionDraft[joint.id] : joint.value
1643
1644
  const unit = joint.type === 'linear' ? ' mm' : '°'
1644
- return h('div', { key: joint.id, style: styles.propRow, 'data-cad-joint': joint.id }, [
1645
- h('span', { key: 'l', style: jointLabel, title: `${joint.id} · ${joint.instance}` }, joint.instance),
1646
- h('span', { key: 'v', style: styles.propValue, 'data-cad-joint-value': joint.id }, `${Math.round(value * 10) / 10}${unit}`),
1647
- h('input', {
1648
- key: 's',
1649
- type: 'range',
1650
- style: styles.slider,
1651
- 'data-cad-joint-slider': joint.id,
1652
- min: joint.min,
1653
- max: joint.max,
1654
- step: 1,
1655
- value,
1656
- title: `${joint.id}(${joint.type === 'linear' ? '滑动 mm' : '旋转 °'})`,
1657
- onInput: (event) => driveJoint(joint.id, Number(event.target.value)),
1658
- }),
1645
+ const clamp = (raw) => Math.max(joint.min, Math.min(joint.max, Math.round(raw)))
1646
+ return h('div', { key: joint.id, 'data-cad-joint': joint.id }, [
1647
+ h('div', { key: 'r', style: styles.propRow }, [
1648
+ h('span', { key: 'l', style: jointLabel, title: `${joint.id} · ${joint.instance}` }, joint.instance),
1649
+ h('span', { key: 'v', style: styles.propValue, 'data-cad-joint-value': joint.id }, `${Math.round(value * 10) / 10}${unit}`),
1650
+ // Typing beats dragging for exact values: 180° across this narrow
1651
+ // slider makes a hand-hit 0° almost impossible.
1652
+ h('input', {
1653
+ key: 'n',
1654
+ type: 'number',
1655
+ style: styles.jointNum,
1656
+ 'data-cad-joint-input': joint.id,
1657
+ min: joint.min,
1658
+ max: joint.max,
1659
+ step: 1,
1660
+ value: String(Math.round(value * 10) / 10),
1661
+ title: '输入数值后回车',
1662
+ onChange: (event) => {
1663
+ const next = Number(event.target.value)
1664
+ if (Number.isFinite(next)) driveJoint(joint.id, clamp(next))
1665
+ },
1666
+ onKeyDown: (event) => { if (event.key === 'Enter') event.currentTarget.blur() },
1667
+ }),
1668
+ h('button', {
1669
+ key: 'z',
1670
+ type: 'button',
1671
+ style: styles.microBtn,
1672
+ 'data-cad-joint-zero': joint.id,
1673
+ title: `把 ${joint.id} 设回 0`,
1674
+ onClick: () => driveJoint(joint.id, 0),
1675
+ }, '归零'),
1676
+ ]),
1677
+ h('div', { key: 's', style: styles.sliderRow }, [
1678
+ h('input', {
1679
+ key: 'sl',
1680
+ type: 'range',
1681
+ style: styles.slider,
1682
+ 'data-cad-joint-slider': joint.id,
1683
+ min: joint.min,
1684
+ max: joint.max,
1685
+ step: 1,
1686
+ value,
1687
+ title: `${joint.id}(${joint.type === 'linear' ? '滑动 mm' : '旋转 °'})`,
1688
+ onInput: (event) => driveJoint(joint.id, Number(event.target.value)),
1689
+ }),
1690
+ ]),
1659
1691
  ])
1660
1692
  }),
1661
1693
  h('div', { key: 'eh', style: styles.treeHint }, '爆炸图'),
@@ -2525,40 +2557,11 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
2525
2557
  if (!id) id = readDomSession()
2526
2558
  if (typeof id === 'string' && id && id !== panelSession) {
2527
2559
  panelSession = id
2528
- ownsCache = { id: '', owns: false, at: 0 }
2529
2560
  }
2530
2561
  return panelSession
2531
2562
  }
2563
+ readSession()
2532
2564
 
2533
- // The host owns the policy and both "did CAD happen here" signals, so a
2534
- // single probe settles it: /state carries the mode plus the last session
2535
- // that published, /scenes carries who owns the older ones.
2536
- const sessionOwnsCad = async () => {
2537
- const id = panelSession || ''
2538
- if (id && ownsCache.id === id && Date.now() - ownsCache.at < 15000) return ownsCache.owns
2539
- let owns = false
2540
- try {
2541
- const [resState, resScenes] = await Promise.all([
2542
- fetch(`${ROUTE}/state`, { headers: { accept: 'application/json' } }),
2543
- fetch(`${ROUTE}/scenes`, { headers: { accept: 'application/json' } }),
2544
- ])
2545
- if (resState.ok) {
2546
- const st = await resState.json()
2547
- const mode = st && st.config && st.config.autoOpen
2548
- if (['session', 'always', 'off'].includes(mode)) cadAutoOpen = mode
2549
- if (id && st && st.lastSession === id) owns = true
2550
- }
2551
- if (!owns && id && resScenes.ok) {
2552
- const data = await resScenes.json()
2553
- owns = (data.scenes || []).some((sc) => sc && sc.session === id)
2554
- }
2555
- } catch (err) { /* a failed probe must not open the bar */ }
2556
- if (cadAutoOpen === 'off') return false
2557
- if (cadAutoOpen === 'always') return true
2558
- if (!id) return false
2559
- if (id) ownsCache = { id, owns, at: Date.now() }
2560
- return owns
2561
- }
2562
2565
  const AUTO_OPEN_DELAYS = [300, 900, 1800, 3000, 5000]
2563
2566
  const openPane = (index) => {
2564
2567
  const ctrl = ctx.get?.('sidebarRight')
@@ -2573,49 +2576,90 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
2573
2576
  }
2574
2577
  // Debug surface: `window.__cadStudioAutoOpen` answers "why did the pane
2575
2578
  // open / not open" without digging through the bundle.
2576
- const autoOpenTrace = { mode: '', session: '', owns: null, opened: 0, why: 'boot' }
2579
+ const autoOpenTrace = { mode: '', session: '', opened: 0, why: 'boot' }
2577
2580
  try {
2578
2581
  Object.defineProperty(window, '__cadStudioAutoOpen', {
2579
2582
  configurable: true,
2580
2583
  get: () => ({ ...autoOpenTrace, mode: cadAutoOpen, session: panelSession }),
2581
2584
  })
2582
2585
  } catch (err) { /* a stale definition from a previous apply is fine */ }
2583
- const maybeOpen = () => {
2586
+
2587
+ // Policy: never open because a session "has used CAD before", and never
2588
+ // on a conversation switch. The single trigger is live work — this
2589
+ // session publishes something while the pane is off screen — and then
2590
+ // it opens on the live (activity) tab. Everything else stays closed.
2591
+ const paneMounted = () => Boolean(document.querySelector('[data-cad-panel-root]'))
2592
+ let watchStamp = ''
2593
+ let watchBusy = false
2594
+ let ranRecently = false
2595
+ const watchOnce = async () => {
2584
2596
  readSession()
2585
- autoOpenTrace.why = 'probe'
2586
- sessionOwnsCad().then((owns) => {
2587
- autoOpenTrace.owns = owns
2588
- if (owns) { autoOpenTrace.opened += 1; autoOpenTrace.why = 'opened'; openPane(0) } else autoOpenTrace.why = 'gated'
2589
- }).catch(() => { autoOpenTrace.why = 'probe-failed' })
2597
+ if (cadAutoOpen === 'off') { autoOpenTrace.why = 'off'; return }
2598
+ if (paneMounted()) { watchStamp = ''; autoOpenTrace.why = 'shown'; return }
2599
+ const id = panelSession || ''
2600
+ if (!id || watchBusy) return
2601
+ watchBusy = true
2602
+ try {
2603
+ const res = await fetch(`${ROUTE}/state`, { headers: { accept: 'application/json' } })
2604
+ if (res.ok) {
2605
+ const st = await res.json()
2606
+ // A tool is executing for this session right now: that is the
2607
+ // trigger the policy asks for, so raise the pane on the live tab.
2608
+ const runningNow = Number(st && st.running) > 0
2609
+ && (!st.runningSession || st.runningSession === id)
2610
+ if (runningNow && !ranRecently) {
2611
+ ranRecently = true
2612
+ autoOpenTrace.opened += 1
2613
+ autoOpenTrace.why = 'running'
2614
+ openPane(0)
2615
+ return
2616
+ }
2617
+ if (!runningNow) ranRecently = false
2618
+ const latest = st && st.latest
2619
+ if (latest && latest.session === id) {
2620
+ const stamp = `${latest.id}@${latest.at || ''}`
2621
+ const prev = watchStamp
2622
+ watchStamp = stamp
2623
+ if (prev && prev !== stamp) {
2624
+ autoOpenTrace.opened += 1
2625
+ autoOpenTrace.why = 'activity'
2626
+ openPane(0)
2627
+ } else if (!prev) {
2628
+ autoOpenTrace.why = 'armed'
2629
+ }
2630
+ } else {
2631
+ watchStamp = ''
2632
+ autoOpenTrace.why = 'idle'
2633
+ }
2634
+ }
2635
+ } catch (err) {
2636
+ autoOpenTrace.why = 'probe-failed'
2637
+ } finally {
2638
+ watchBusy = false
2639
+ }
2640
+ }
2641
+ watchOnce()
2642
+ const watchTimer = setInterval(watchOnce, 3000)
2643
+ ctx.effect?.(() => () => clearInterval(watchTimer))
2644
+ // The session id still has to be tracked (the watcher only opens for the
2645
+ // session that is on screen), but a change merely re-arms the baseline.
2646
+ const rebase = () => {
2647
+ readSession()
2648
+ watchStamp = ''
2649
+ autoOpenTrace.session = panelSession
2590
2650
  }
2591
- maybeOpen()
2592
- // Every session carries its OWN rightbar layout, so entering a session
2593
- // replaces the bar with that session's tabs. Re-place ours whenever the
2594
- // route or the current session changes; a slow caught-up retry covers
2595
- // hosts that notify neither way.
2596
- const kick = () => maybeOpen()
2597
- const kickSoon = () => setTimeout(kick, 400)
2598
- try {
2599
- window.addEventListener('hashchange', kickSoon)
2600
- window.addEventListener('popstate', kickSoon)
2601
- ctx.effect?.(() => () => {
2602
- window.removeEventListener('hashchange', kickSoon)
2603
- window.removeEventListener('popstate', kickSoon)
2604
- })
2605
- } catch (err) { /* no window: nothing to stage against */ }
2606
- for (const delay of [2000, 5000, 9000, 14000]) setTimeout(kick, delay)
2607
2651
  if (current != null && typeof current.subscribe === 'function' && typeof current.getSnapshot === 'function') {
2608
2652
  try {
2609
- const unsubscribe = current.subscribe(() => { readSession(); maybeOpen() })
2653
+ const unsubscribe = current.subscribe(() => rebase())
2610
2654
  ctx.effect?.(() => unsubscribe)
2611
- } catch (err) { /* no session store on this host: boot-time placement is all */ }
2655
+ } catch (err) { /* no session store on this host */ }
2612
2656
  // Switching conversations rewrites that attribute without always
2613
2657
  // firing a store event, so watch it directly; the observer is cheap.
2614
2658
  try {
2615
- let lastSeen = ''
2659
+ let lastSeen = readDomSession()
2616
2660
  const observer = new MutationObserver(() => {
2617
2661
  const next = readDomSession()
2618
- if (next && next !== lastSeen) { lastSeen = next; readSession(); maybeOpen() }
2662
+ if (next && next !== lastSeen) { lastSeen = next; rebase() }
2619
2663
  })
2620
2664
  observer.observe(document.documentElement, {
2621
2665
  subtree: true,
package/index.js CHANGED
@@ -444,6 +444,18 @@ class FreeCadBridge {
444
444
  if (Array.isArray(pointer.modelsDirs)) this.modelsSeen = [...new Set([...this.modelsSeen, ...pointer.modelsDirs.filter((d) => typeof d === 'string' && d)])].slice(0, 12)
445
445
  if (!this.lastSession && typeof pointer.lastSession === 'string') this.lastSession = pointer.lastSession
446
446
  const disk = Array.isArray(pointer.history) ? pointer.history : []
447
+ const asmTitles = new Map()
448
+ for (const a of Array.isArray(pointer.assemblies) ? pointer.assemblies : []) {
449
+ if (a && typeof a.id === 'string' && typeof a.title === 'string') asmTitles.set(`asm:${a.id}`, a.title)
450
+ }
451
+ // Earlier builds appended the joint value / explode factor to the model
452
+ // name (`运动演示 · hinge 60`). Rewrite those rows to the plain title.
453
+ const SUFFIX = /\s·\s(?:合拢|爆炸\s-?\d+(?:\.\d+)?|[A-Za-z_][\w-]*\s-?\d+(?:\.\d+)?)$/
454
+ for (const row of [...this.history, ...disk]) {
455
+ if (!row || typeof row.title !== 'string') continue
456
+ const base = typeof row.docKey === 'string' && asmTitles.has(row.docKey) ? asmTitles.get(row.docKey) : row.title.replace(SUFFIX, '')
457
+ row.title = base
458
+ }
447
459
  const seen = new Set(this.history.map((h) => h.id))
448
460
  const merged = [...this.history, ...disk.filter((h) => !seen.has(h.id))]
449
461
  merged.sort((a, b) => String(b.at || '').localeCompare(String(a.at || '')))
@@ -573,9 +585,11 @@ class FreeCadBridge {
573
585
  }
574
586
 
575
587
  /** Recompute instance placements from base + joints + explode, then publish. */
576
- async republishAssembly(record, titleSuffix) {
588
+ async republishAssembly(record) {
577
589
  const scene = assembleScene(record)
578
- const title = titleSuffix ? `${record.title} · ${titleSuffix}` : record.title
590
+ // The title is the model's name, never its state: dragging a joint or
591
+ // changing the explode factor must not rename the model.
592
+ const title = record.title
579
593
  // In place: the assembly owns one scene id and one row in the models list.
580
594
  const published = await this.publishScene(scene, title, this.currentSession ?? '', {
581
595
  docKey: `asm:${record.id}`,
@@ -1012,8 +1026,18 @@ __out = {
1012
1026
  const tool = (definition) => ctx.effect(() => ctx.tools.register({
1013
1027
  ...definition,
1014
1028
  execute: async (args, exec) => {
1015
- bridge.currentSession = sessionOf(exec)
1016
- return definition.execute(args, exec)
1029
+ const session = sessionOf(exec)
1030
+ bridge.currentSession = session
1031
+ // A tool is working right now: the panel watches this to show itself on
1032
+ // the live tab (and only for the session that is actually running).
1033
+ bridge.running = (bridge.running || 0) + 1
1034
+ bridge.runningSession = session
1035
+ try {
1036
+ return await definition.execute(args, exec)
1037
+ } finally {
1038
+ bridge.running = Math.max(0, (bridge.running || 1) - 1)
1039
+ if (!bridge.running) bridge.runningSession = ''
1040
+ }
1017
1041
  },
1018
1042
  }))
1019
1043
 
@@ -1540,7 +1564,7 @@ if _TARGET:
1540
1564
  const before = record.joints.length
1541
1565
  record.joints = record.joints.filter((j) => j.id !== joint)
1542
1566
  if (record.joints.length === before) return { ok: false, error: `没有这个关节:${joint ?? '(未指定)'}` }
1543
- const published = await bridge.republishAssembly(record, '')
1567
+ const published = await bridge.republishAssembly(record)
1544
1568
  return { ok: true, assembly: record.id, removed: joint, sceneId: published.id, joints: record.joints.length }
1545
1569
  }
1546
1570
  let stored
@@ -1549,7 +1573,7 @@ if _TARGET:
1549
1573
  } catch (error) {
1550
1574
  return { ok: false, error: String(error?.message ?? error) }
1551
1575
  }
1552
- const published = await bridge.republishAssembly(record, `${stored.id} ${round6(stored.value)}`)
1576
+ const published = await bridge.republishAssembly(record)
1553
1577
  return {
1554
1578
  ok: true,
1555
1579
  assembly: record.id,
@@ -1588,7 +1612,7 @@ if _TARGET:
1588
1612
  const id = joint ?? record.joints[0].id
1589
1613
  const moved = bridge.driveJoint(record, id, value)
1590
1614
  if (!moved) return { ok: false, error: `没有这个关节:${id}(现有 ${record.joints.map((j) => j.id).join(', ')})` }
1591
- const published = await bridge.republishAssembly(record, `${id} ${round6(moved.value)}`)
1615
+ const published = await bridge.republishAssembly(record)
1592
1616
  return {
1593
1617
  ok: true,
1594
1618
  assembly: record.id,
@@ -1626,7 +1650,7 @@ if _TARGET:
1626
1650
  }
1627
1651
  const next = bridge.setExplode(record, factor ?? 1)
1628
1652
  if (next === null) return { ok: false, error: 'factor 必须是数字' }
1629
- const published = await bridge.republishAssembly(record, next ? `爆炸 ${round6(next)}` : '合拢')
1653
+ const published = await bridge.republishAssembly(record)
1630
1654
  return { ok: true, assembly: record.id, sceneId: published.id, explode: round6(next), instances: published.stats.instances }
1631
1655
  },
1632
1656
  })
@@ -2069,10 +2093,10 @@ if _TARGET:
2069
2093
  try {
2070
2094
  const parsed = JSON.parse(await readFile(join(dir, 'state.json'), 'utf8'))
2071
2095
  const setup = setupStatus(bridge, { withVersion: false })
2072
- return send(200, JSON.stringify({ runtime, setup, config: { autoOpen: resolved.autoOpen }, latest: parsed.latest ?? null, lastSession: parsed.lastSession ?? '', assemblies: parsed.assemblies ?? [] }))
2096
+ 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 || '' }))
2073
2097
  } catch {
2074
2098
  const setup = setupStatus(bridge, { withVersion: false })
2075
- return send(200, JSON.stringify({ runtime, setup, config: { autoOpen: resolved.autoOpen }, latest: null, lastSession: '' }))
2099
+ return send(200, JSON.stringify({ runtime, setup, config: { autoOpen: resolved.autoOpen }, latest: null, lastSession: '', running: bridge.running || 0, runningSession: bridge.runningSession || '' }))
2076
2100
  }
2077
2101
  }
2078
2102
  if (url.pathname === `${ROUTE_PREFIX}/scenes`) {
@@ -2197,12 +2221,12 @@ if _TARGET:
2197
2221
  const jointId = typeof body?.joint === 'string' ? body.joint : record.joints[0]?.id
2198
2222
  const moved = live.driveJoint(record, jointId, body?.value)
2199
2223
  if (!moved) return send(400, JSON.stringify({ error: 'bad joint or value' }))
2200
- const published = await live.republishAssembly(record, `${moved.id} ${round6(moved.value)}`)
2224
+ const published = await live.republishAssembly(record)
2201
2225
  return send(200, JSON.stringify({ ok: true, sceneId: published.id, at: published.stats.at, joint: moved.id, value: round6(moved.value) }))
2202
2226
  }
2203
2227
  const next = live.setExplode(record, body?.factor ?? 1)
2204
2228
  if (next === null) return send(400, JSON.stringify({ error: 'bad factor' }))
2205
- const published = await live.republishAssembly(record, next ? `爆炸 ${round6(next)}` : '合拢')
2229
+ const published = await live.republishAssembly(record)
2206
2230
  return send(200, JSON.stringify({ ok: true, sceneId: published.id, at: published.stats.at, explode: round6(next) }))
2207
2231
  }
2208
2232
  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.2.3",
3
+ "version": "0.2.5",
4
4
  "type": "module",
5
5
  "description": "CAD Studio — FreeCAD 桥(给 AI 的 14 个工具)+ Web 右栏 3D 面板:建模/装配/关节运动/出图/多页签查看",
6
6
  "exports": {