dsh-synapse 0.5.3 → 0.5.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.
package/app.js CHANGED
@@ -61,7 +61,7 @@ const state = {
61
61
  // screenful and cached here (issue #42).
62
62
  bodies: new Map(), bodyRequests: new Set(), bodyFailures: new Set(), bodiesLoaded: new Set(),
63
63
  archivedSessionIds: new Set(),
64
- draft: null, error: '', workspaceLoad: 0, branchAnchors: new Map(savedBranchAnchors), cardPositions: new Map(savedCardPositions), collapsedCardIds: new Set(savedCollapsedCards), quickPhrases: savedQuickPhrases, quickPhraseEditorOpen: false,
64
+ draft: null, error: '', workspaceLoad: 0, workspaceLoadOwner: null, workspaceLoadBusy: false, workspaceFingerprint: null, workspacesSignature: null, branchAnchors: new Map(savedBranchAnchors), cardPositions: new Map(savedCardPositions), collapsedCardIds: new Set(savedCollapsedCards), quickPhrases: savedQuickPhrases, quickPhraseEditorOpen: false,
65
65
  dragging: false, canvasGesture: false, canvasRefreshAfter: 0, canvasViewInitialized: false, canvasCamera: { x: 0, y: 0 }, mapCardSessionSwitches: new Set(),
66
66
  expandedMessageIds: new Set(),
67
67
  canvasCards: undefined, canvasCardsById: undefined, canvasGraph: undefined, mountedCardIds: new Set(), canvasNeedsCenter: false,
@@ -181,6 +181,12 @@ function currentDshThread(threads = state.workspace?.threads ?? []) {
181
181
  return typeof id === 'string' ? threads.find(thread => thread.dshSessionId === id) : undefined
182
182
  }
183
183
 
184
+ /** Only the session fields the canvas actually draws; used to skip no-op renders. */
185
+ function sessionSignature(session) {
186
+ if (session === null || session === undefined) return ''
187
+ return [session.id ?? '', session.title ?? session.displayTitle ?? '', session.cwd ?? '', session.running === true ? '1' : '0'].join('|')
188
+ }
189
+
184
190
  function workspaceChoices() {
185
191
  if (state.dshWorkspaces.length > 0) return state.dshWorkspaces.map(workspace => ({ ...workspace, source: 'dsh' }))
186
192
  return state.summaries.map(workspace => ({ id: workspace.id, title: workspace.title, path: workspace.cwd, sessionIds: [], source: 'projection' }))
@@ -193,23 +199,38 @@ async function threadsForDshWorkspace(workspace) {
193
199
  return projections.flatMap(projection => projection.workspace.threads.filter(thread => requested.has(thread.dshSessionId)))
194
200
  }
195
201
 
196
- async function openDshWorkspace(id, { renderAfter = true, preserveCanvasCamera = false } = {}) {
202
+ async function openDshWorkspace(id, { renderAfter = true, preserveCanvasCamera = false, userInitiated = false } = {}) {
197
203
  const workspace = state.dshWorkspaces.find(item => item.id === id)
198
204
  if (workspace === undefined) return false
205
+ // A background poll must never cancel or pre-empt a workspace the user just
206
+ // picked, and two polls must never run at once: the 1s poll used to open a
207
+ // fresh whole-workspace load every tick, each one cancelling the previous
208
+ // ticket, so nothing ever rendered (16 loads / 12 cancellations in 19s).
209
+ if (!userInitiated && (state.workspaceLoadOwner === 'user' || state.workspaceLoadBusy)) return false
199
210
  const load = ++state.workspaceLoad
200
- state.selectedDshWorkspaceId = id
201
- const threads = await threadsForDshWorkspace(workspace)
202
- if (load !== state.workspaceLoad) return true
203
- const nextWorkspaceId = `dsh:${workspace.id}`
204
- if (state.workspace?.id !== nextWorkspaceId && !preserveCanvasCamera) resetCanvasCamera()
205
- state.workspace = { id: nextWorkspaceId, title: workspace.title, cwd: workspace.path, threads }
206
- const currentThread = currentDshThread(state.workspace.threads)
207
- state.activeId = currentThread?.id ?? (state.workspace.threads.some(thread => thread.id === state.activeId) ? state.activeId : state.workspace.threads[0]?.id ?? null)
208
- if (currentThread !== undefined) revealConversationThread(conversationCards(state.workspace.threads), currentThread.id)
209
- if (renderAfter && canReplaceView()) render()
210
- await Promise.all(state.workspace.threads.map(thread => loadThreadHistory(thread, false)))
211
- if (renderAfter && load === state.workspaceLoad && canReplaceView()) render()
212
- return true
211
+ if (userInitiated) state.workspaceLoadOwner = 'user'
212
+ state.workspaceLoadBusy = true
213
+ try {
214
+ state.selectedDshWorkspaceId = id
215
+ const threads = await threadsForDshWorkspace(workspace)
216
+ if (load !== state.workspaceLoad) return true
217
+ const nextWorkspaceId = `dsh:${workspace.id}`
218
+ if (state.workspace?.id !== nextWorkspaceId && !preserveCanvasCamera) resetCanvasCamera()
219
+ state.workspace = { id: nextWorkspaceId, title: workspace.title, cwd: workspace.path, threads }
220
+ state.workspaceFingerprint = JSON.stringify(state.workspace)
221
+ const currentThread = currentDshThread(state.workspace.threads)
222
+ state.activeId = currentThread?.id ?? (state.workspace.threads.some(thread => thread.id === state.activeId) ? state.activeId : state.workspace.threads[0]?.id ?? null)
223
+ if (currentThread !== undefined) revealConversationThread(conversationCards(state.workspace.threads), currentThread.id)
224
+ if (renderAfter && canReplaceView()) render()
225
+ await Promise.all(state.workspace.threads.map(thread => loadThreadHistory(thread, false)))
226
+ if (renderAfter && load === state.workspaceLoad && canReplaceView()) render()
227
+ // After a user switch, bring that workspace's active conversation on screen.
228
+ if (userInitiated && load === state.workspaceLoad) window.requestAnimationFrame(() => { if (state.mode === 'canvas') focusActiveCard() })
229
+ return true
230
+ } finally {
231
+ state.workspaceLoadBusy = false
232
+ if (userInitiated && load === state.workspaceLoad) state.workspaceLoadOwner = null
233
+ }
213
234
  }
214
235
 
215
236
  async function openCurrentWorkspace({ preserveCanvasCamera = false } = {}) {
@@ -238,15 +259,39 @@ async function openWorkspace(id, { renderAfter = true } = {}) {
238
259
  if (load !== state.workspaceLoad) return
239
260
  if (state.workspace?.id !== body.workspace.id) resetCanvasCamera()
240
261
  state.workspace = body.workspace
262
+ state.workspaceFingerprint = JSON.stringify(state.workspace)
241
263
  state.activeId = state.workspace.threads.some(thread => thread.id === state.activeId) ? state.activeId : state.workspace.threads[0]?.id ?? null
242
264
  if (renderAfter && canReplaceView()) render()
243
265
  await Promise.all(state.workspace.threads.map(thread => loadThreadHistory(thread, false)))
244
266
  if (renderAfter && load === state.workspaceLoad && canReplaceView()) render()
245
267
  }
246
268
 
269
+ /**
270
+ * Quiet refresh of the workspace already on screen: re-fetch its payload and only
271
+ * rebuild the canvas when the payload really changed. The poll used to call
272
+ * `openDshWorkspace` every second, which re-ran the whole load (and its ticket)
273
+ * just to discover nothing had changed.
274
+ */
275
+ async function refreshCurrentWorkspace() {
276
+ const current = state.workspace
277
+ if (current === null || typeof current.id !== 'string' || !current.id.startsWith('dsh:')) return false
278
+ const body = await api(`/synapse/api/workspaces/${current.id.slice(4)}`)
279
+ if (state.workspace !== current) return false
280
+ const fingerprint = JSON.stringify(body.workspace)
281
+ if (state.workspaceFingerprint === fingerprint) return false
282
+ state.workspaceFingerprint = fingerprint
283
+ state.workspace = body.workspace
284
+ if (!state.workspace.threads.some(thread => thread.id === state.activeId)) {
285
+ state.activeId = state.workspace.threads[0]?.id ?? null
286
+ }
287
+ if (canReplaceView()) render()
288
+ return true
289
+ }
290
+
247
291
  async function refreshProjection() {
248
292
  const summariesChanged = await refreshSummaries({ renderAfter: false })
249
293
  if (!summariesChanged || state.workspace === null || !canReplaceView()) return summariesChanged
294
+ if (state.workspace.id.startsWith('dsh:')) return (await refreshCurrentWorkspace()) || summariesChanged
250
295
  if (state.selectedDshWorkspaceId !== null) await openDshWorkspace(state.selectedDshWorkspaceId)
251
296
  else await openWorkspace(state.workspace.id)
252
297
  return true
@@ -1268,7 +1313,7 @@ function render() {
1268
1313
  const canvasControls = state.mode === 'canvas' && (threads.length > 0 || state.draft?.kind === 'new') ? `<div class="canvas-controls"><button data-action="layout" title="整理节点" aria-label="整理节点"><svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linejoin="round"><rect x="2.5" y="2.5" width="4.5" height="4.5" rx="1"/><rect x="9" y="2.5" width="4.5" height="4.5" rx="1"/><rect x="2.5" y="9" width="4.5" height="4.5" rx="1"/><rect x="9" y="9" width="4.5" height="4.5" rx="1"/></svg>整理</button><button data-action="focus-active" title="定位到当前会话" aria-label="定位到当前会话"><svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"><circle cx="8" cy="8" r="3.2"/><path d="M8 1.5v2.6M8 11.9v2.6M1.5 8h2.6M11.9 8h2.6"/></svg>定位</button><button data-action="zoom-out" aria-label="缩小" title="缩小"><svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"><path d="M3.5 8h9"/></svg></button><span>${Math.round(state.zoom * 100)}%</span><button data-action="zoom-in" aria-label="放大" title="放大"><svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"><path d="M8 3.5v9M3.5 8h9"/></svg></button></div>` : ''
1269
1314
  const detailAvailable = currentThread() !== null
1270
1315
  const canvasTabs = `<nav class="canvas-tabs" aria-label="会话地图视图"><button class="${state.mode === 'canvas' ? 'active' : ''}" data-action="show-canvas">地图</button><button class="${state.mode === 'thread' ? 'active' : ''}" data-action="show-thread" data-thread="${state.activeId ?? ''}" ${detailAvailable ? '' : 'disabled'}>详情</button></nav>`
1271
- app.innerHTML = `<main class="synapse-shell ${state.sidebarCollapsed ? 'sidebar-collapsed' : ''}"><aside class="sidebar"><div class="sidebar-brand-row"><div class="brand" aria-label="Synapse"><svg class="brand-mark" aria-hidden="true" viewBox="0 0 32 32" fill="none"><path d="M9 10.5 16 7l7 3.5M9 10.5v8L16 22m0-15v15m7-11.5v8L16 22"/><circle cx="9" cy="10" r="2.5"/><circle cx="23" cy="10" r="2.5"/><circle cx="16" cy="23" r="2.5"/></svg><strong>Synapse</strong></div><button class="sidebar-toggle" type="button" data-action="toggle-sidebar" aria-label="${state.sidebarCollapsed ? '展开侧边栏' : '收起侧边栏'}" title="${state.sidebarCollapsed ? '展开侧边栏' : '收起侧边栏'}"><svg viewBox="0 0 16 16" aria-hidden="true"><rect x="1.75" y="1.75" width="12.5" height="12.5" rx="2.25"/><path d="M6 2v12"/></svg></button></div><button class="new-workspace" type="button" data-action="create-session" ${state.draft !== null ? 'disabled' : ''}><svg class="new-session-icon" viewBox="0 0 16 16" aria-hidden="true"><circle cx="8" cy="8" r="6.25"/><path d="M8 4.75v6.5M4.75 8h6.5"/></svg><span>新会话</span></button><label class="workspace-label"><span>工作区</span><span class="workspace-select"><svg aria-hidden="true" viewBox="0 0 16 16"><path d="M2.5 4.75h3l1.2 1.5h6.8v5.5a1 1 0 0 1-1 1h-9a1 1 0 0 1-1-1v-6a1 1 0 0 1 1-1Z"/></svg><select data-action="select-workspace" aria-label="选择工作区" ${state.draft !== null ? 'disabled' : ''}>${choices.map(item => `<option value="${item.id}" title="${escapeHtml(item.path ?? item.title)}" ${item.id === selectedWorkspaceId ? 'selected' : ''}>${escapeHtml(item.title)}</option>`).join('')}</select></span></label><div class="sidebar-heading"><span>会话</span></div><nav class="thread-tree">${threads.map(thread => `<button class="tree-row ${thread.id === state.activeId ? 'active' : ''}" data-action="select-thread" data-thread="${thread.id}" style="--thread-color:#374151"><span class="tree-dot"></span><span>${escapeHtml(threadListTitle(thread))}</span>${thread.parentId === null ? '' : '<i>分支</i>'}</button>`).join('') || '<p class="tree-empty">暂未同步会话</p>'}</nav></aside><header class="topbar">${canvasControls}</header><section class="main-stage">${state.error ? `<div class="status-message" role="alert"><span>${escapeHtml(state.error)}</span><button data-action="dismiss-error" aria-label="关闭" title="关闭">×</button></div>` : ''}${canvasTabs}${view}${selectionFollowupButton()}</section></main>`
1316
+ morphInto(app, `<main class="synapse-shell ${state.sidebarCollapsed ? 'sidebar-collapsed' : ''}"><aside class="sidebar"><div class="sidebar-brand-row"><div class="brand" aria-label="Synapse"><svg class="brand-mark" aria-hidden="true" viewBox="0 0 32 32" fill="none"><path d="M9 10.5 16 7l7 3.5M9 10.5v8L16 22m0-15v15m7-11.5v8L16 22"/><circle cx="9" cy="10" r="2.5"/><circle cx="23" cy="10" r="2.5"/><circle cx="16" cy="23" r="2.5"/></svg><strong>Synapse</strong></div><button class="sidebar-toggle" type="button" data-action="toggle-sidebar" aria-label="${state.sidebarCollapsed ? '展开侧边栏' : '收起侧边栏'}" title="${state.sidebarCollapsed ? '展开侧边栏' : '收起侧边栏'}"><svg viewBox="0 0 16 16" aria-hidden="true"><rect x="1.75" y="1.75" width="12.5" height="12.5" rx="2.25"/><path d="M6 2v12"/></svg></button></div><button class="new-workspace" type="button" data-action="create-session" ${state.draft !== null ? 'disabled' : ''}><svg class="new-session-icon" viewBox="0 0 16 16" aria-hidden="true"><circle cx="8" cy="8" r="6.25"/><path d="M8 4.75v6.5M4.75 8h6.5"/></svg><span>新会话</span></button><label class="workspace-label"><span>工作区</span><span class="workspace-select"><svg aria-hidden="true" viewBox="0 0 16 16"><path d="M2.5 4.75h3l1.2 1.5h6.8v5.5a1 1 0 0 1-1 1h-9a1 1 0 0 1-1-1v-6a1 1 0 0 1 1-1Z"/></svg><select data-action="select-workspace" aria-label="选择工作区" ${state.draft !== null ? 'disabled' : ''}>${choices.map(item => `<option value="${item.id}" title="${escapeHtml(item.path ?? item.title)}" ${item.id === selectedWorkspaceId ? 'selected' : ''}>${escapeHtml(item.title)}</option>`).join('')}</select></span></label><div class="sidebar-heading"><span>会话</span></div><nav class="thread-tree">${threads.map(thread => `<button class="tree-row ${thread.id === state.activeId ? 'active' : ''}" data-action="select-thread" data-thread="${thread.id}" style="--thread-color:#374151"><span class="tree-dot"></span><span>${escapeHtml(threadListTitle(thread))}</span>${thread.parentId === null ? '' : '<i>分支</i>'}</button>`).join('') || '<p class="tree-empty">暂未同步会话</p>'}</nav></aside><header class="topbar">${canvasControls}</header><section class="main-stage">${state.error ? `<div class="status-message" role="alert"><span>${escapeHtml(state.error)}</span><button data-action="dismiss-error" aria-label="关闭" title="关闭">×</button></div>` : ''}${canvasTabs}${view}${selectionFollowupButton()}</section></main>`)
1272
1317
  installDragging()
1273
1318
  cacheCardConnectors()
1274
1319
  // The initial camera from renderCanvas is inset (viewport not laid out yet);
@@ -1416,7 +1461,126 @@ function applyCanvasTransform() {
1416
1461
  if (content instanceof HTMLElement) content.style.transform = `translate(${state.canvasCamera.x}px, ${state.canvasCamera.y}px) scale(${state.zoom})`
1417
1462
  }
1418
1463
 
1464
+ // --- DOM morphing ---------------------------------------------------------
1465
+ // The canvas re-renders on every projection tick and on every streamed chunk.
1466
+ // Assigning `app.innerHTML` destroys the exact node the user is pressing, and a
1467
+ // click is only dispatched when mousedown and mouseup share a target, so a
1468
+ // rebuild in between silently swallows the click (W3C uievents #141). Morph the
1469
+ // new markup into the live tree instead: matching nodes are patched in place and
1470
+ // whatever sits under the pointer stays alive.
1471
+
1472
+ const MORPH_KEY_ATTRIBUTES = ['data-morph-key', 'data-card-id', 'data-thread', 'id']
1473
+
1474
+ function morphKeyOf(node) {
1475
+ if (!(node instanceof Element)) return null
1476
+ for (const attribute of MORPH_KEY_ATTRIBUTES) {
1477
+ const value = node.getAttribute(attribute)
1478
+ if (value !== null && value !== '') return `${node.tagName}|${attribute}|${value}`
1479
+ }
1480
+ return null
1481
+ }
1482
+
1483
+ // Only the node that actually owns the caret/selection is frozen — never its
1484
+ // ancestors. Freezing every ancestor of the anchor froze the entire shell (a
1485
+ // caret in a card's answer made `.canvas-view` and `main` un-morphable), so the
1486
+ // inspector never appeared and the sidebar never refreshed after a switch.
1487
+ let morphFrozenRoot = null
1488
+
1489
+ function morphFrozenRootOfDocument() {
1490
+ if (typeof window.getSelection !== 'function') return null
1491
+ const selection = window.getSelection()
1492
+ if (selection === null || selection.rangeCount === 0) return null
1493
+ const anchor = selection.anchorNode
1494
+ if (anchor === null) return null
1495
+ const element = anchor.nodeType === 1 ? anchor : anchor.parentElement
1496
+ if (element === null) return null
1497
+ return element.closest('.thread-answer, .card-inspector-answer, .message-body, [data-draft], input, textarea, [contenteditable="true"]')
1498
+ }
1499
+
1500
+ /** Elements whose children must survive a render: they own the caret, or a selection. */
1501
+ function morphKeepsChildren(node) {
1502
+ if (!(node instanceof Element)) return false
1503
+ if (node instanceof HTMLInputElement || node instanceof HTMLTextAreaElement) return true
1504
+ if (node.isContentEditable === true) return true
1505
+ return node === morphFrozenRoot
1506
+ }
1507
+
1508
+ function morphNode(from, to) {
1509
+ if (from.nodeType !== to.nodeType) return replaceMorphed(from, to)
1510
+ if (from.nodeType === Node.TEXT_NODE || from.nodeType === Node.COMMENT_NODE) {
1511
+ if (from.nodeValue !== to.nodeValue) from.nodeValue = to.nodeValue
1512
+ return from
1513
+ }
1514
+ if (!(from instanceof Element) || !(to instanceof Element) || from.tagName !== to.tagName) {
1515
+ return replaceMorphed(from, to)
1516
+ }
1517
+ // Attributes are always patched, even on the node the user just clicked: a
1518
+ // pressed button becomes document.activeElement, and treating that as "owns
1519
+ // the caret" used to freeze its whole subtree — the clicked sidebar row never
1520
+ // received its `active` class, so no row looked selected after a switch.
1521
+ for (const attribute of [...from.attributes]) {
1522
+ if (!to.hasAttribute(attribute.name)) from.removeAttribute(attribute.name)
1523
+ }
1524
+ for (const attribute of [...to.attributes]) {
1525
+ if (from.getAttribute(attribute.name) !== attribute.value) from.setAttribute(attribute.name, attribute.value)
1526
+ }
1527
+ if (!morphKeepsChildren(from)) morphChildren(from, to)
1528
+ return from
1529
+ }
1530
+
1531
+ /** Swap one node for a copy of another and hand back the node now in the tree. */
1532
+ function replaceMorphed(from, to) {
1533
+ const next = to.cloneNode(true)
1534
+ from.replaceWith(next)
1535
+ return next
1536
+ }
1537
+
1538
+ function morphChildren(from, to) {
1539
+ const keyed = new Map()
1540
+ for (const child of [...from.childNodes]) {
1541
+ const key = morphKeyOf(child)
1542
+ if (key !== null && !keyed.has(key)) keyed.set(key, child)
1543
+ }
1544
+ const matched = new Set()
1545
+ let cursor = from.firstChild
1546
+ for (const next of [...to.childNodes]) {
1547
+ const key = morphKeyOf(next)
1548
+ let match = key === null ? null : keyed.get(key) ?? null
1549
+ if (match === null && cursor !== null && morphKeyOf(cursor) === null) match = cursor
1550
+ if (match === null) {
1551
+ const inserted = next.cloneNode(true)
1552
+ from.insertBefore(inserted, cursor)
1553
+ matched.add(inserted)
1554
+ continue
1555
+ }
1556
+ if (match !== cursor) from.insertBefore(match, cursor)
1557
+ matched.add(morphNode(match, next))
1558
+ cursor = match.nextSibling
1559
+ }
1560
+ for (const child of [...from.childNodes]) {
1561
+ if (!matched.has(child)) from.removeChild(child)
1562
+ }
1563
+ }
1564
+
1565
+ /** Patch `container`'s children to match `html` without discarding live nodes. */
1566
+ function morphInto(container, html) {
1567
+ const template = document.createElement('template')
1568
+ template.innerHTML = html
1569
+ // Computed once per pass: the one subtree that must not be rebuilt because the
1570
+ // caret/selection lives in it. Everything else (inspector, sidebar rows, cards)
1571
+ // keeps updating normally.
1572
+ morphFrozenRoot = morphFrozenRootOfDocument()
1573
+ try {
1574
+ morphChildren(container, template.content)
1575
+ } finally {
1576
+ morphFrozenRoot = null
1577
+ }
1578
+ }
1579
+
1419
1580
  function bindDragHandle(handle) {
1581
+ // Cards now survive a render, so bind each drag handle once.
1582
+ if (handle.dataset.dragBound === '1') return
1583
+ handle.dataset.dragBound = '1'
1420
1584
  handle.addEventListener('pointerdown', event => {
1421
1585
  const cardId = event.currentTarget.dataset.dragCard
1422
1586
  const card = event.currentTarget.closest('.thread-card')
@@ -1731,6 +1895,10 @@ app.addEventListener('click', async event => {
1731
1895
  state.error = ''
1732
1896
  if (state.workspace !== null) revealConversationThread(conversationCards(state.workspace.threads), thread.id)
1733
1897
  render()
1898
+ // The state switch is instant, so the map has to show it: without this the
1899
+ // camera stayed on the previous conversation's cards (often thousands of
1900
+ // pixels away), and a click that worked looked like a dead button.
1901
+ window.requestAnimationFrame(() => { if (state.mode === 'canvas') focusActiveCard() })
1734
1902
  void loadThreadHistory(thread)
1735
1903
  // Bidirectional current-session sync: switch DSH's current session
1736
1904
  // without closing the map; the client confirms via synapse:current-session.
@@ -1748,12 +1916,18 @@ app.addEventListener('click', async event => {
1748
1916
  const visibleIds = new Set(visibleCards.map(card => card.id))
1749
1917
  const draftParentId = draftPlacement(allCards)?.parent.id
1750
1918
  if (draftParentId !== undefined && !visibleIds.has(draftParentId)) return setError('请先完成或取消正在编辑的追问或分支')
1751
- if (state.activeId !== null && !visibleCards.some(card => card.dshThreadId === state.activeId)) return setError('当前会话位于这个后续分支中,请先切换会话')
1919
+ // Collapsing is a view operation, so it is never refused: it used to be
1920
+ // blocked whenever the active conversation would be hidden, which made
1921
+ // "−" look dead on exactly the newest card people press it on. Keep the
1922
+ // camera useful instead, by re-focusing after the collapse below.
1752
1923
  }
1753
1924
  collapsing ? state.collapsedCardIds.add(cardId) : state.collapsedCardIds.delete(cardId)
1754
1925
  persistCollapsedCards()
1926
+ // Keep the viewport exactly where it is: folding is about hiding a
1927
+ // subtree, not about re-framing the canvas (moving the camera on every
1928
+ // fold is disorienting). Focus the handle without scrolling for a11y.
1755
1929
  render()
1756
- window.setTimeout(() => document.querySelector(`[data-action="toggle-card-children"][data-card="${selectorValue(cardId)}"]`)?.focus(), 0)
1930
+ window.setTimeout(() => document.querySelector(`[data-action="toggle-card-children"][data-card="${selectorValue(cardId)}"]`)?.focus({ preventScroll: true }), 0)
1757
1931
  }
1758
1932
  if (button.dataset.action === 'open-continue' && thread !== undefined) openContinue(thread, button.dataset.card)
1759
1933
  if (button.dataset.action === 'open-branch' && thread !== undefined) {
@@ -1792,7 +1966,7 @@ app.addEventListener('change', event => {
1792
1966
  if (choice?.source === 'dsh') {
1793
1967
  // Map → native sync: switching workspaces moves DSH's current session to
1794
1968
  // the workspace's most recently updated session, keeping both sides in step.
1795
- void openDshWorkspace(choice.id).then(opened => {
1969
+ void openDshWorkspace(choice.id, { userInitiated: true }).then(opened => {
1796
1970
  if (!opened) return
1797
1971
  const threads = state.workspace?.threads ?? []
1798
1972
  const latest = threads
@@ -1833,10 +2007,19 @@ window.addEventListener('message', event => {
1833
2007
  document.documentElement.dataset.theme = data.dark === true ? 'dark' : 'light'
1834
2008
  }
1835
2009
  if (data.type === 'synapse:workspaces') {
1836
- state.dshWorkspaces = Array.isArray(data.workspaces) ? data.workspaces.filter(workspace => typeof workspace?.id === 'string' && typeof workspace.title === 'string' && Array.isArray(workspace.sessionIds)) : []
2010
+ const nextWorkspaces = Array.isArray(data.workspaces) ? data.workspaces.filter(workspace => typeof workspace?.id === 'string' && typeof workspace.title === 'string' && Array.isArray(workspace.sessionIds)) : []
1837
2011
  // DSH owns the archive set; mirror it so an archived session stops drawing
1838
2012
  // cards here too (issue #21 / #19).
1839
- state.archivedSessionIds = new Set(Array.isArray(data.archivedSessionIds) ? data.archivedSessionIds.filter(id => typeof id === 'string') : [])
2013
+ const nextArchived = new Set(Array.isArray(data.archivedSessionIds) ? data.archivedSessionIds.filter(id => typeof id === 'string') : [])
2014
+ // The parent re-sends this on every session-list change, i.e. on every
2015
+ // streamed chunk. Acting on an unchanged payload re-ran a whole workspace
2016
+ // load and rebuilt the canvas several times a second, which is what made
2017
+ // clicking feel unresponsive and switching workspaces feel stalled.
2018
+ const signature = JSON.stringify([nextWorkspaces, [...nextArchived].sort()])
2019
+ if (signature === state.workspacesSignature) return
2020
+ state.workspacesSignature = signature
2021
+ state.dshWorkspaces = nextWorkspaces
2022
+ state.archivedSessionIds = nextArchived
1840
2023
  const current = currentDshWorkspace()
1841
2024
  if (current !== undefined && current.id !== state.selectedDshWorkspaceId) void openDshWorkspace(current.id).catch(setError)
1842
2025
  else if (state.selectedDshWorkspaceId !== null) void openDshWorkspace(state.selectedDshWorkspaceId).catch(setError)
@@ -1844,7 +2027,9 @@ window.addEventListener('message', event => {
1844
2027
  }
1845
2028
  if (data.type === 'synapse:current-session') {
1846
2029
  const previousId = state.currentDsh?.id
2030
+ const previousSignature = sessionSignature(state.currentDsh)
1847
2031
  state.currentDsh = data.session
2032
+ const nextSignature = sessionSignature(data.session)
1848
2033
  const preserveCanvasCamera = previousId !== data.session?.id && state.mapCardSessionSwitches.delete(data.session?.id)
1849
2034
  const thread = currentDshThread()
1850
2035
  if (thread !== undefined) {
@@ -1868,7 +2053,10 @@ window.addEventListener('message', event => {
1868
2053
  }
1869
2054
  }).catch(setError)
1870
2055
  }
1871
- else if (canReplaceView()) render()
2056
+ // Only the fields the canvas draws matter here: the parent re-sends this
2057
+ // message for every streamed chunk, and re-rendering on each one queued a
2058
+ // full rebuild behind every click.
2059
+ else if (previousSignature !== nextSignature && canReplaceView()) render()
1872
2060
  }
1873
2061
  if (data.type === 'synapse:live-reply' && typeof data.sessionId === 'string') {
1874
2062
  const thread = state.workspace?.threads.find(item => item.dshSessionId === data.sessionId)
@@ -1925,9 +2113,11 @@ function applyLiveReplyToCard(sessionId) {
1925
2113
  const answer = card.querySelector('.thread-answer')
1926
2114
  if (!(answer instanceof HTMLElement)) return
1927
2115
  const text = live.text
1928
- answer.innerHTML = text.trim() === ''
2116
+ // Morph instead of replacing the subtree: the answer keeps its nodes, so a
2117
+ // pointer that went down inside it still resolves to a click on release.
2118
+ morphInto(answer, text.trim() === ''
1929
2119
  ? '<p class="thread-answer-pending">正在回复</p>'
1930
- : `${renderMarkdown(text)}<p class="thread-answer-pending">正在回复</p>`
2120
+ : `${renderMarkdown(text)}<p class="thread-answer-pending">正在回复</p>`)
1931
2121
  }
1932
2122
  function scheduleLiveRender() {
1933
2123
  if (liveRenderTimer !== 0 || !canReplaceView()) return
@@ -80,7 +80,7 @@ Only a turn a person typed becomes a card. The harness also writes its own `user
80
80
 
81
81
  Projected messages keep only a preview (280 characters), not the body. The body already lives in the DSH session log, and a workspace file full of copies is what made one workspace reach several megabytes and stall the canvas (issue #42). The canvas asks the Host for the bodies of the cards it actually mounts (`GET /synapse/api/threads/:id/full`), and the detail view asks for a whole thread at once; when a session is archived or gone from DSH the previews stay and the card is marked unavailable instead of rendering blank.
82
82
 
83
- Projected card text is capped at 8000 characters on the detail fetch, while the preview stays short.
83
+ Bodies returned by the detail fetch are capped at 200 000 characters (`MAX_BODY_CHARS`), while the preview stays at 280; a truncated body carries a marker so the card can say the rest lives in DSH.
84
84
 
85
85
  Projection writes are coalesced during event bursts, and live updates reuse cached Markdown and patch the active card instead of rebuilding the complete canvas. Card coordinates remain visual metadata only and never determine conversation lineage.
86
86
 
package/index.js CHANGED
@@ -280,7 +280,16 @@ export class WorkspaceStore {
280
280
  await this.save()
281
281
  }
282
282
  } catch (error) {
283
- if (error?.code !== 'ENOENT') throw new Error(`synapse: cannot read ${this.dataFile}: ${error.message}`)
283
+ if (error?.code !== 'ENOENT') {
284
+ // Never "repair" this file. An unreadable workspaces.json is the only
285
+ // copy of the canvas; restoring a backup over it (which an earlier
286
+ // revision did) both discarded whatever the file still held and silently
287
+ // rolled the map back to a snapshot of unknown age. Fail instead: the
288
+ // store stays unloaded, `ready` rejects, every mutation refuses to run,
289
+ // and the HTTP layer reports this exact message so the user learns which
290
+ // file to repair.
291
+ throw new Error(`synapse: cannot read ${this.dataFile}: ${error.message}`)
292
+ }
284
293
  this.state = { version: 5, hiddenSessionIds: [], workspaces: [] }
285
294
  await this.save()
286
295
  }
@@ -1123,7 +1132,11 @@ export function apply(ctx, config) {
1123
1132
  if (error instanceof InputError) return sendJson(res, 400, { error: error.message })
1124
1133
  if (error instanceof NotFoundError) return sendJson(res, 404, { error: error.message })
1125
1134
  ctx.logger.error(error instanceof Error ? error : new Error(String(error)))
1126
- return sendJson(res, 500, { error: 'Synapse 数据暂时不可用' })
1135
+ // A store that cannot read its file carries the only actionable detail —
1136
+ // the path. Passing it through beats a generic banner the user cannot act
1137
+ // on, and it is the one failure the canvas must never paper over.
1138
+ const unreadable = error instanceof Error && error.message.startsWith('synapse: cannot read')
1139
+ return sendJson(res, 500, { error: unreadable ? error.message : 'Synapse 数据暂时不可用' })
1127
1140
  }
1128
1141
  }
1129
1142
  ctx.effect(() => ctx.webServer.register({ kind: 'exact', path: '/synapse', handler: (_req, res) => { res.writeHead(302, { location: '/synapse/' }); res.end() } }), 'synapse: redirect')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-synapse",
3
- "version": "0.5.3",
3
+ "version": "0.5.5",
4
4
  "description": "A visual, non-linear conversation workspace plugin for DeepSeek Harness.",
5
5
  "type": "module",
6
6
  "main": "index.js",
package/styles.css CHANGED
@@ -81,7 +81,12 @@ button.primary:hover { border-color: #000; background: #000; color: #fff; }
81
81
  .connectors .draft-connector { stroke: #3478f6; stroke-dasharray: 5 4; }
82
82
  .cards-layer { position: absolute; inset: 0; }
83
83
  .thread-card { position: absolute; display: grid; width: 310px; height: 276px; grid-template-rows: auto auto minmax(0, 1fr) auto; border: 1px solid #d8e0e8; border-radius: 7px; background: #fff; box-shadow: 0 3px 11px rgba(33,48,67,.08); overflow: visible; }
84
- .thread-card:hover { border-color: #9ca3af; box-shadow: 0 8px 20px rgba(33,48,67,.13); }
84
+ /* The graph buttons hang 12px outside the card (`right: -12px`), so a card that
85
+ comes later in DOM order used to paint its own body over that overhang and
86
+ steal the click — folding worked on some cards and silently did nothing on
87
+ others. The hovered/focused card is lifted above its siblings so the whole
88
+ button stays hit-testable. */
89
+ .thread-card:hover, .thread-card:focus-within { z-index: 3; border-color: #9ca3af; box-shadow: 0 8px 20px rgba(33,48,67,.13); }
85
90
  .thread-card.selected { box-shadow: 0 0 0 2px rgba(17,24,39,.16), 0 8px 20px rgba(33,48,67,.13); }
86
91
  .node-handle { position: absolute; top: -8px; left: 50%; display: grid; width: 28px; height: 15px; min-height: 15px; place-items: center; transform: translateX(-50%); border: 1px solid #d8e0e8; border-radius: 4px; background: #fff; cursor: grab; padding: 0; }
87
92
  .node-handle::after { content: '...'; display: block; margin: -5px 0 0 2px; color: #94a3b8; font-size: 11px; letter-spacing: 1.5px; line-height: 1; }