dsh-synapse 0.5.4 → 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
@@ -1435,14 +1480,29 @@ function morphKeyOf(node) {
1435
1480
  return null
1436
1481
  }
1437
1482
 
1438
- /** An element that owns the caret keeps its children untouched. */
1439
- function morphHoldsCaret(node) {
1440
- if (!(node instanceof Element)) return false
1441
- if (node === document.activeElement) return true
1442
- const selection = typeof window.getSelection === 'function' ? window.getSelection() : null
1443
- if (selection === null || selection.rangeCount === 0) return false
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
1444
1493
  const anchor = selection.anchorNode
1445
- return anchor !== null && node.contains(anchor)
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
1446
1506
  }
1447
1507
 
1448
1508
  function morphNode(from, to) {
@@ -1454,14 +1514,17 @@ function morphNode(from, to) {
1454
1514
  if (!(from instanceof Element) || !(to instanceof Element) || from.tagName !== to.tagName) {
1455
1515
  return replaceMorphed(from, to)
1456
1516
  }
1457
- if (morphHoldsCaret(from)) return from
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.
1458
1521
  for (const attribute of [...from.attributes]) {
1459
1522
  if (!to.hasAttribute(attribute.name)) from.removeAttribute(attribute.name)
1460
1523
  }
1461
1524
  for (const attribute of [...to.attributes]) {
1462
1525
  if (from.getAttribute(attribute.name) !== attribute.value) from.setAttribute(attribute.name, attribute.value)
1463
1526
  }
1464
- morphChildren(from, to)
1527
+ if (!morphKeepsChildren(from)) morphChildren(from, to)
1465
1528
  return from
1466
1529
  }
1467
1530
 
@@ -1503,7 +1566,15 @@ function morphChildren(from, to) {
1503
1566
  function morphInto(container, html) {
1504
1567
  const template = document.createElement('template')
1505
1568
  template.innerHTML = html
1506
- morphChildren(container, template.content)
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
+ }
1507
1578
  }
1508
1579
 
1509
1580
  function bindDragHandle(handle) {
@@ -1824,6 +1895,10 @@ app.addEventListener('click', async event => {
1824
1895
  state.error = ''
1825
1896
  if (state.workspace !== null) revealConversationThread(conversationCards(state.workspace.threads), thread.id)
1826
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() })
1827
1902
  void loadThreadHistory(thread)
1828
1903
  // Bidirectional current-session sync: switch DSH's current session
1829
1904
  // without closing the map; the client confirms via synapse:current-session.
@@ -1841,12 +1916,18 @@ app.addEventListener('click', async event => {
1841
1916
  const visibleIds = new Set(visibleCards.map(card => card.id))
1842
1917
  const draftParentId = draftPlacement(allCards)?.parent.id
1843
1918
  if (draftParentId !== undefined && !visibleIds.has(draftParentId)) return setError('请先完成或取消正在编辑的追问或分支')
1844
- 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.
1845
1923
  }
1846
1924
  collapsing ? state.collapsedCardIds.add(cardId) : state.collapsedCardIds.delete(cardId)
1847
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.
1848
1929
  render()
1849
- 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)
1850
1931
  }
1851
1932
  if (button.dataset.action === 'open-continue' && thread !== undefined) openContinue(thread, button.dataset.card)
1852
1933
  if (button.dataset.action === 'open-branch' && thread !== undefined) {
@@ -1885,7 +1966,7 @@ app.addEventListener('change', event => {
1885
1966
  if (choice?.source === 'dsh') {
1886
1967
  // Map → native sync: switching workspaces moves DSH's current session to
1887
1968
  // the workspace's most recently updated session, keeping both sides in step.
1888
- void openDshWorkspace(choice.id).then(opened => {
1969
+ void openDshWorkspace(choice.id, { userInitiated: true }).then(opened => {
1889
1970
  if (!opened) return
1890
1971
  const threads = state.workspace?.threads ?? []
1891
1972
  const latest = threads
@@ -1926,10 +2007,19 @@ window.addEventListener('message', event => {
1926
2007
  document.documentElement.dataset.theme = data.dark === true ? 'dark' : 'light'
1927
2008
  }
1928
2009
  if (data.type === 'synapse:workspaces') {
1929
- 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)) : []
1930
2011
  // DSH owns the archive set; mirror it so an archived session stops drawing
1931
2012
  // cards here too (issue #21 / #19).
1932
- 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
1933
2023
  const current = currentDshWorkspace()
1934
2024
  if (current !== undefined && current.id !== state.selectedDshWorkspaceId) void openDshWorkspace(current.id).catch(setError)
1935
2025
  else if (state.selectedDshWorkspaceId !== null) void openDshWorkspace(state.selectedDshWorkspaceId).catch(setError)
@@ -1937,7 +2027,9 @@ window.addEventListener('message', event => {
1937
2027
  }
1938
2028
  if (data.type === 'synapse:current-session') {
1939
2029
  const previousId = state.currentDsh?.id
2030
+ const previousSignature = sessionSignature(state.currentDsh)
1940
2031
  state.currentDsh = data.session
2032
+ const nextSignature = sessionSignature(data.session)
1941
2033
  const preserveCanvasCamera = previousId !== data.session?.id && state.mapCardSessionSwitches.delete(data.session?.id)
1942
2034
  const thread = currentDshThread()
1943
2035
  if (thread !== undefined) {
@@ -1961,7 +2053,10 @@ window.addEventListener('message', event => {
1961
2053
  }
1962
2054
  }).catch(setError)
1963
2055
  }
1964
- 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()
1965
2060
  }
1966
2061
  if (data.type === 'synapse:live-reply' && typeof data.sessionId === 'string') {
1967
2062
  const thread = state.workspace?.threads.find(item => item.dshSessionId === data.sessionId)
@@ -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.4",
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; }