dsh-synapse 0.5.4 → 0.5.6

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/README.md CHANGED
@@ -54,11 +54,28 @@ corepack pnpm dsh web
54
54
  | 保留真实分支 | 按 DSH 原生 fork 关系连接卡片,不制造另一套会话历史。 |
55
55
  | 追问更顺手 | 选中回答中的文字可直接带入新的追问;常用补充词可编辑。 |
56
56
  | 双向同步 | 在地图或 DSH 原生对话中切换会话,当前上下文保持一致。 |
57
+ | 过程不挡路 | 工具调用与结果按 `callId` 折叠进对应回答,只显示「工具 N」。 |
58
+ | 可移动入口 | 顶部「对话 / 会话地图」开关可拖动、记忆位置、双击复位。 |
59
+ | 详情侧栏 | 点卡片在右侧展开整轮详情:完整回答、工具过程、追问 / 分支 / 打开 DSH。 |
60
+ | 归档一致 | 归档在地图与 DSH 侧栏之间共用同一份集合,不会各记一套。 |
61
+
62
+ ## 最近更新
63
+
64
+ **0.5.6**
65
+
66
+ - 顶部开关可拖动、记忆位置(按浏览器)、双击复位、方向键微调,并保证不会被拖到屏幕外。
67
+ - 交互与渲染一致性修正:切会话会把该会话带入视野;折叠卡片不再移动画布;正文里有选区时侧栏与详情仍能更新;卡片右侧折叠 / 分支按钮不再被相邻卡片遮住。
68
+ - 工作区加载竞态修正:切换工作区不再被后台轮询顶掉;画布只在数据真变化时重建(此前每秒重建数次)。
69
+ - `workspaces.json` 读不出来时改为**明确报错并保持只读**,不再用旧备份覆盖原文件。
70
+
71
+ 历史版本见[提交记录](https://github.com/liangmianya/dsh-synapse/commits/main)。
57
72
 
58
73
  ## 从原生对话进入
59
74
 
60
75
  在 DSH 原生对话中,通过顶部的 **会话地图** 进入 Synapse;返回 **对话** 后,仍是同一个 DSH 会话。
61
76
 
77
+ 这个开关挡着内容时可以挪走:**按住左侧六点手柄拖动**,位置按浏览器记住;**双击手柄**复位;手柄聚焦后可用方向键微调。
78
+
62
79
  ![DSH 原生对话与会话地图入口](docs/images/native-webui.jpg)
63
80
 
64
81
  ## 文档
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)
package/client.js CHANGED
@@ -39,6 +39,42 @@ window.__ModuleLoader__.load({
39
39
  return Array.isArray(snapshot.archivedSessionIds) ? snapshot.archivedSessionIds.map(String) : []
40
40
  }
41
41
 
42
+ // The pill can be dragged anywhere it stays reachable; the position survives
43
+ // reloads. Kept next to the module so the drag arithmetic is testable without
44
+ // a DOM (see test/switch-drag.test.js).
45
+ const SWITCH_POSITION_KEY = 'dsh-synapse:switch-position:v1'
46
+ const SWITCH_MARGIN = 8
47
+ const SWITCH_STEP = 8
48
+
49
+ /** Keep the pill fully inside the viewport, with a margin to grab it again. */
50
+ function clampSwitchPosition(position, viewport, size) {
51
+ const maxLeft = Math.max(SWITCH_MARGIN, viewport.width - size.width - SWITCH_MARGIN)
52
+ const maxTop = Math.max(SWITCH_MARGIN, viewport.height - size.height - SWITCH_MARGIN)
53
+ return {
54
+ left: Math.min(Math.max(SWITCH_MARGIN, Math.round(position.left)), maxLeft),
55
+ top: Math.min(Math.max(SWITCH_MARGIN, Math.round(position.top)), maxTop),
56
+ }
57
+ }
58
+
59
+ function readSwitchPosition(storage) {
60
+ try {
61
+ const value = JSON.parse(storage.getItem(SWITCH_POSITION_KEY) ?? 'null')
62
+ if (value === null || typeof value !== 'object') return null
63
+ if (!Number.isFinite(value.left) || !Number.isFinite(value.top)) return null
64
+ return { left: Math.round(value.left), top: Math.round(value.top) }
65
+ } catch {
66
+ return null
67
+ }
68
+ }
69
+
70
+ function writeSwitchPosition(storage, position) {
71
+ try { storage.setItem(SWITCH_POSITION_KEY, JSON.stringify(position)) } catch { /* private mode */ }
72
+ }
73
+
74
+ function clearSwitchPosition(storage) {
75
+ try { storage.removeItem(SWITCH_POSITION_KEY) } catch { /* private mode */ }
76
+ }
77
+
42
78
  module.exports.inject = ['sessions', 'workspaces', 'uiWorkspace', 'uiConversation']
43
79
  module.exports.apply = ctx => {
44
80
  const prompt = async (sessionId, text) => {
@@ -77,11 +113,11 @@ window.__ModuleLoader__.load({
77
113
  // rightward (title, lineage and agent-preset chips). Half the sidebar
78
114
  // width puts the pill over the centre of the content area instead of
79
115
  // the window; `min()` pulls it back in on narrow windows.
80
- style.textContent = '.dsh-synapse-switch{position:fixed;z-index:200;top:calc(var(--dsh-frame-chrome-top,var(--dsh-frame-top-clearance,0px)) + 12px);left:min(calc(50% + 130px),calc(100% - 96px));display:flex;gap:2px;transform:translateX(-50%);border:1px solid #d1d5db;border-radius:999px;background:rgba(255,255,255,.96);padding:3px;backdrop-filter:blur(10px);-webkit-app-region:no-drag;box-shadow:0 2px 8px rgba(17,24,39,.1)}.dsh-synapse-switch button{height:28px;border:0;border-radius:999px;background:transparent;padding:0 11px;color:#6b7280;font:600 12px Inter,system-ui,sans-serif;cursor:pointer;white-space:nowrap;-webkit-app-region:no-drag}.dsh-synapse-switch button:hover{background:#f3f4f6;color:#111827}.dsh-synapse-switch button.active{background:#111827;color:#fff}.dsh-synapse-switch button:focus-visible{outline:2px solid #111827;outline-offset:2px}.dsh-synapse-overlay{position:fixed;z-index:100;inset:var(--dsh-frame-chrome-top,var(--dsh-frame-top-clearance,0px)) 0 0 0;background:#f5f7fa}.dsh-synapse-overlay.is-opening{visibility:hidden}.dsh-synapse-overlay[hidden]{display:none}.dsh-synapse-overlay iframe{display:block;width:100%;height:100%;border:0}html[data-fullscreen] .dsh-synapse-overlay{top:0}html[data-fullscreen] .dsh-synapse-switch{top:12px}'
116
+ style.textContent = '.dsh-synapse-switch{position:fixed;z-index:200;top:calc(var(--dsh-frame-chrome-top,var(--dsh-frame-top-clearance,0px)) + 12px);left:min(calc(50% + 130px),calc(100% - 96px));display:flex;gap:2px;transform:translateX(-50%);border:1px solid #d1d5db;border-radius:999px;background:rgba(255,255,255,.96);padding:3px;backdrop-filter:blur(10px);-webkit-app-region:no-drag;box-shadow:0 2px 8px rgba(17,24,39,.1)}.dsh-synapse-switch button{height:28px;border:0;border-radius:999px;background:transparent;padding:0 11px;color:#6b7280;font:600 12px Inter,system-ui,sans-serif;cursor:pointer;white-space:nowrap;-webkit-app-region:no-drag}.dsh-synapse-switch button:hover{background:#f3f4f6;color:#111827}.dsh-synapse-switch button.active{background:#111827;color:#fff}.dsh-synapse-switch button:focus-visible{outline:2px solid #111827;outline-offset:2px}.dsh-synapse-overlay{position:fixed;z-index:100;inset:var(--dsh-frame-chrome-top,var(--dsh-frame-top-clearance,0px)) 0 0 0;background:#f5f7fa}.dsh-synapse-overlay.is-opening{visibility:hidden}.dsh-synapse-overlay[hidden]{display:none}.dsh-synapse-overlay iframe{display:block;width:100%;height:100%;border:0}html[data-fullscreen] .dsh-synapse-overlay{top:0}html[data-fullscreen] .dsh-synapse-switch{top:12px}.dsh-synapse-grip{display:grid;width:16px;height:28px;place-items:center;border-radius:999px;color:#9ca3af;background:transparent;cursor:grab;touch-action:none;-webkit-app-region:no-drag}.dsh-synapse-grip:hover{background:#f3f4f6;color:#4b5563}.dsh-synapse-grip:focus-visible{outline:2px solid #111827;outline-offset:2px}.dsh-synapse-grip svg{width:8px;height:14px;fill:currentColor}.dsh-synapse-switch.is-dragging .dsh-synapse-grip{cursor:grabbing}'
81
117
  document.head.append(style)
82
118
  const host = document.createElement('div')
83
119
  host.className = 'dsh-synapse-host'
84
- host.innerHTML = '<div class="dsh-synapse-switch" role="group" aria-label="视图切换"><button type="button" data-view="dialog" class="active" aria-pressed="true">对话</button><button type="button" data-view="map" aria-pressed="false">会话地图</button></div><section class="dsh-synapse-overlay" hidden><iframe title="会话地图" src="/synapse/"></iframe></section>'
120
+ host.innerHTML = '<div class="dsh-synapse-switch" role="group" aria-label="视图切换"><span class="dsh-synapse-grip" role="button" tabindex="0" aria-label="拖动位置" title="拖动位置(双击复位,方向键微调)"><svg aria-hidden="true" viewBox="0 0 8 14"><circle cx="2" cy="2" r="1.3"/><circle cx="6" cy="2" r="1.3"/><circle cx="2" cy="7" r="1.3"/><circle cx="6" cy="7" r="1.3"/><circle cx="2" cy="12" r="1.3"/><circle cx="6" cy="12" r="1.3"/></svg></span><button type="button" data-view="dialog" class="active" aria-pressed="true">对话</button><button type="button" data-view="map" aria-pressed="false">会话地图</button></div><section class="dsh-synapse-overlay" hidden><iframe title="会话地图" src="/synapse/"></iframe></section>'
85
121
  document.body.append(host)
86
122
  const switchEl = host.querySelector('.dsh-synapse-switch')
87
123
  // Two live instances (a bundle loaded twice, or a sibling that outlived a
@@ -107,6 +143,77 @@ window.__ModuleLoader__.load({
107
143
  const mapButton = host.querySelector('[data-view="map"]')
108
144
  const overlay = host.querySelector('.dsh-synapse-overlay')
109
145
  const frame = host.querySelector('iframe')
146
+ const grip = host.querySelector('.dsh-synapse-grip')
147
+
148
+ // --- dragging the pill -------------------------------------------------
149
+ // A stored position switches the pill from its CSS seat (centred, under the
150
+ // window chrome) to explicit viewport coordinates; `transform` has to be
151
+ // dropped with it or the pill would stay half a width to the left.
152
+ const switchSize = () => ({ width: switchEl.offsetWidth, height: switchEl.offsetHeight })
153
+ const viewportSize = () => ({ width: window.innerWidth, height: window.innerHeight })
154
+ const applySwitchPosition = position => {
155
+ if (position === null) {
156
+ switchEl.style.removeProperty('left')
157
+ switchEl.style.removeProperty('top')
158
+ switchEl.style.removeProperty('transform')
159
+ return
160
+ }
161
+ switchEl.style.left = `${position.left}px`
162
+ switchEl.style.top = `${position.top}px`
163
+ switchEl.style.transform = 'none'
164
+ }
165
+ const storedSwitchPosition = readSwitchPosition(window.localStorage)
166
+ if (storedSwitchPosition !== null) {
167
+ applySwitchPosition(clampSwitchPosition(storedSwitchPosition, viewportSize(), switchSize()))
168
+ }
169
+ let switchDrag = null
170
+ const finishSwitchDrag = event => {
171
+ if (switchDrag === null) return
172
+ const drag = switchDrag
173
+ switchDrag = null
174
+ switchEl.classList.remove('is-dragging')
175
+ try { grip.releasePointerCapture(event.pointerId) } catch { /* already released */ }
176
+ if (drag.moved && drag.position !== null) writeSwitchPosition(window.localStorage, drag.position)
177
+ }
178
+ grip.addEventListener('pointerdown', event => {
179
+ if (event.button !== 0) return
180
+ event.preventDefault()
181
+ const rect = switchEl.getBoundingClientRect()
182
+ switchDrag = { x: event.clientX, y: event.clientY, left: rect.left, top: rect.top, moved: false, position: null }
183
+ switchEl.classList.add('is-dragging')
184
+ try { grip.setPointerCapture(event.pointerId) } catch { /* capture is best effort */ }
185
+ })
186
+ grip.addEventListener('pointermove', event => {
187
+ if (switchDrag === null) return
188
+ const dx = event.clientX - switchDrag.x
189
+ const dy = event.clientY - switchDrag.y
190
+ if (!switchDrag.moved && Math.hypot(dx, dy) < 3) return
191
+ switchDrag.moved = true
192
+ switchDrag.position = clampSwitchPosition({ left: switchDrag.left + dx, top: switchDrag.top + dy }, viewportSize(), switchSize())
193
+ applySwitchPosition(switchDrag.position)
194
+ })
195
+ grip.addEventListener('pointerup', finishSwitchDrag)
196
+ grip.addEventListener('pointercancel', finishSwitchDrag)
197
+ // Double-click resets the pill to its shipped seat.
198
+ grip.addEventListener('dblclick', () => {
199
+ clearSwitchPosition(window.localStorage)
200
+ applySwitchPosition(null)
201
+ })
202
+ // Keyboard path: arrows nudge, so the control is usable without a pointer.
203
+ grip.addEventListener('keydown', event => {
204
+ const step = { ArrowLeft: [-SWITCH_STEP, 0], ArrowRight: [SWITCH_STEP, 0], ArrowUp: [0, -SWITCH_STEP], ArrowDown: [0, SWITCH_STEP] }[event.key]
205
+ if (step === undefined) return
206
+ event.preventDefault()
207
+ const rect = switchEl.getBoundingClientRect()
208
+ const position = clampSwitchPosition({ left: rect.left + step[0], top: rect.top + step[1] }, viewportSize(), switchSize())
209
+ applySwitchPosition(position)
210
+ writeSwitchPosition(window.localStorage, position)
211
+ })
212
+ const keepSwitchInView = () => {
213
+ const stored = readSwitchPosition(window.localStorage)
214
+ if (stored !== null) applySwitchPosition(clampSwitchPosition(stored, viewportSize(), switchSize()))
215
+ }
216
+ window.addEventListener('resize', keepSwitchInView)
110
217
 
111
218
  const setView = view => {
112
219
  const showingMap = view === 'map'
@@ -385,6 +492,7 @@ window.__ModuleLoader__.load({
385
492
  frame.removeEventListener('load', onFrameLoad)
386
493
  window.removeEventListener('message', onMessage)
387
494
  window.removeEventListener('keydown', onKeyDown)
495
+ window.removeEventListener('resize', keepSwitchInView)
388
496
  themeObserver?.disconnect()
389
497
  unsubscribeSessions()
390
498
  unsubscribeWorkspaces()
@@ -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/docs/en/README.md CHANGED
@@ -104,6 +104,22 @@ The canvas supports:
104
104
  - Smooth card scrolling and Markdown table rendering.
105
105
  - Folding tool calls and results into the related assistant answer by `callId`.
106
106
 
107
+ The **Dialogue / Session Map** switch can be moved too:
108
+
109
+ - Drag it by the six-dot grip on its left edge; the position is remembered per browser.
110
+ - Double-click the grip to return it to its shipped seat (centred under the window chrome).
111
+ - With the grip focused, the arrow keys nudge it by 8px.
112
+ - It always keeps an 8px grab margin from the viewport edges, so shrinking the window cannot strand it off screen.
113
+
114
+ ## Recent changes
115
+
116
+ **0.5.6**
117
+
118
+ - The top switch is draggable, remembers where you left it, and resets on a double-click (new).
119
+ - Interaction and rendering consistency: switching a conversation now brings it into view; folding a card no longer moves the canvas; a text selection in an answer no longer freezes the sidebar and the details panel; the fold/branch buttons on a card's right edge are no longer covered by the neighbouring card.
120
+ - Workspace switching no longer races the background poll, and the canvas is rebuilt only when data actually changes instead of several times a second.
121
+ - An unreadable `workspaces.json` now fails loudly and read-only instead of restoring an old backup over it (the 0.5.5 fallback was reverted).
122
+
107
123
  ## Configuration
108
124
 
109
125
  The plugin is inserted through the profile's `cordis.patch.yml`. Override it in your own patch by targeting the row id `synapse`.
@@ -104,6 +104,22 @@ corepack pnpm dsh web --port 0
104
104
  - 卡片内部平滑滚动和 Markdown 表格渲染。
105
105
  - 将工具调用和结果按 `callId` 折叠到对应助手回答中。
106
106
 
107
+ 顶部「对话 / 会话地图」开关也可以挪位置:
108
+
109
+ - 按住开关左侧的**六点手柄**拖动,鬆手即记忆(存在浏览器本地,按浏览器各自独立);
110
+ - **双击手柄**复位到默认位置(标题栏下方居中);
111
+ - 手柄获得焦点后可用**方向键**微调,每次 8px;
112
+ - 开关始终保留离屏幕边缘 8px 的余量,缩小窗口也不会被挤到看不见的地方。
113
+
114
+ ## 最近更新
115
+
116
+ **0.5.6**
117
+
118
+ - 顶部开关可以拖动、记忆位置、双击复位(本次新增)。
119
+ - 修正交互与渲染一致性:切换会话会把该会话带到视野内;折叠卡片不再移动画布;选区落在正文时侧栏与详情仍能更新;卡片右侧的折叠/分支按钮不再被相邻卡片遮住而点不到。
120
+ - 修正工作区加载竞态:切换工作区不会再被后台轮询顶掉,画布重建次数从「每秒数次」降到「仅在数据变化时一次」。
121
+ - `workspaces.json` 读不出来时改为**明确报错并保持只读**,不再用旧备份覆盖原文件(0.5.5 引入的回退已撤销)。
122
+
107
123
  ## 配置
108
124
 
109
125
  插件通过 profile 的 `cordis.patch.yml` 注入。可以在自己的 patch 中通过行 id `synapse` 覆盖配置。
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.6",
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; }