dsh-synapse 0.5.6 → 0.5.8

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
@@ -49,23 +49,29 @@ const CARD_HEIGHT = 276
49
49
  const CARD_GAP_Y = 42
50
50
  const CAMERA_INSET_X = 56
51
51
  const CAMERA_INSET_Y = 56
52
- // Cards outside the viewport (plus this world-space margin) are not mounted
53
- // into the DOM; the margin pre-mounts cards just before they scroll into view
54
- // so panning never flashes empty space.
55
- const VIEWPORT_MARGIN = 1400
52
+ // Fixed world-space margins do not expand to most of the map at 20% zoom.
53
+ const REGION_MARGIN = 360
54
+ const REGION_PREFETCH_MARGIN = 900
55
+ const REGION_TICK_MS = 90
56
+ const MAP_DETAIL_CARDS = 80
57
+ const MAP_OVERVIEW_CARDS = 320
58
+ const MAP_FACE_TEXT = 2400
59
+ const OVERVIEW_ZOOM = .55
60
+ const DETAIL_PAGE_MESSAGES = 40
56
61
  const state = {
57
62
  summaries: [], workspace: null, activeId: null, selectedCardId: null, mode: 'canvas', zoom: 1, currentDsh: null, sidebarCollapsed: false,
63
+ focusedThreadId: null, canvasFocusRevision: 0,
58
64
  dshWorkspaces: [], selectedDshWorkspaceId: null,
59
65
  historyBySession: new Map(), historyRequests: new Map(), pendingReplies: new Map(), pendingRpc: new Map(), liveReplies: new Map(),
60
66
  // Message bodies are not part of the workspace payload; they are fetched per
61
67
  // screenful and cached here (issue #42).
62
- bodies: new Map(), bodyRequests: new Set(), bodyFailures: new Set(), bodiesLoaded: new Set(),
68
+ bodyFailures: new Set(), mapVisible: window.parent === window,
63
69
  archivedSessionIds: new Set(),
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,
70
+ draft: null, error: '', workspaceLoad: 0, workspaceLoadOwner: null, workspaceLoadBusy: false, workspaceFingerprint: null, workspaceSummariesSignature: null, workspaceDshSignature: null, workspacesSignature: null, branchAnchors: new Map(savedBranchAnchors), cardPositions: new Map(savedCardPositions), collapsedCardIds: new Set(savedCollapsedCards), quickPhrases: savedQuickPhrases, quickPhraseEditorOpen: false,
65
71
  dragging: false, canvasGesture: false, canvasRefreshAfter: 0, canvasViewInitialized: false, canvasCamera: { x: 0, y: 0 }, mapCardSessionSwitches: new Set(),
66
72
  expandedMessageIds: new Set(),
67
73
  canvasCards: undefined, canvasCardsById: undefined, canvasGraph: undefined, mountedCardIds: new Set(), canvasNeedsCenter: false,
68
- detailScrollByThread: new Map(), detailThreadId: null, detailTargetCardId: null,
74
+ detailScrollByThread: new Map(), detailThreadId: null, detailTargetCardId: null, detailPageByThread: new Map(),
69
75
  inspectorCardId: null, inspectorOpening: false, inspectorScrollByCard: new Map(),
70
76
  }
71
77
 
@@ -74,7 +80,115 @@ const formatTime = value => new Date(value).toLocaleString('zh-CN', { month: 'nu
74
80
  const currentThread = () => state.workspace?.threads.find(thread => thread.id === state.activeId) ?? state.workspace?.threads[0] ?? null
75
81
  const threadListTitle = thread => thread.dshSessionTitle ?? thread.title ?? questionFor(thread)
76
82
 
83
+ const bodyCache = new SynapseCache.BodyCache()
84
+ const bodyLoader = new SynapseCache.BodyLoader({
85
+ cache: bodyCache,
86
+ request: (path, signal) => api(path, { signal }),
87
+ onUpdate: entries => {
88
+ if (!state.mapVisible || document.hidden) return
89
+ if (state.mode === 'thread') render()
90
+ else refreshLoadedBodies(entries)
91
+ },
92
+ })
93
+ state.bodyFailures = bodyLoader.failures
94
+ let cacheWorkspaceId = null
95
+ let cacheThreadIds = new Set()
96
+
97
+ function bodyRevision(message) {
98
+ // Source messages are immutable; tools may finish or be added afterward.
99
+ // Use only projection metadata, never hydrated arguments/results.
100
+ return message.bodyRevision ?? JSON.stringify([
101
+ message.text, message.length, message.kind, message.at,
102
+ (message.process ?? []).slice(0, 12).map(entry => [entry.callId, entry.name, entry.status]),
103
+ message.process?.length ?? 0,
104
+ ])
105
+ }
106
+
107
+ function hydratedMessage(thread, message) {
108
+ if (message === null || message === undefined) return message
109
+ const revision = bodyRevision(message)
110
+ const body = bodyCache.get(thread.id, message.sourceSeq, revision)
111
+ return body === undefined ? message : { ...message, ...body, bodyRevision: revision, hydrated: true }
112
+ }
113
+
114
+ function hydratedCard(card) {
115
+ const thread = canvasGraphCache?.threadById.get(card.dshThreadId) ?? state.workspace?.threads.find(item => item.id === card.dshThreadId)
116
+ if (thread === undefined) return card
117
+ const question = hydratedMessage(thread, card.questionMessage)
118
+ return { ...card, question: question?.text ?? card.question, questionMessage: question,
119
+ answer: hydratedMessage(thread, card.answer), error: hydratedMessage(thread, card.error) }
120
+ }
121
+
122
+ function clearViewCaches() {
123
+ cancelRegionWork()
124
+ invalidateCanvasGraph()
125
+ bodyLoader.pause({ clearCache: true })
126
+ markdownCache.clear()
127
+ state.canvasCards = undefined
128
+ state.canvasCardsById = undefined
129
+ state.canvasGraph = undefined
130
+ canvasGraphCache = null
131
+ regionView = null
132
+ regionElements.clear()
133
+ state.mountedCardIds.clear()
134
+ connectorPathsByCard.clear()
135
+ }
136
+
137
+ function prepareWorkspaceCaches(id) {
138
+ if (state.workspace?.id === id) return
139
+ clearViewCaches()
140
+ }
141
+
142
+ function pruneWorkspaceCaches() {
143
+ invalidateCanvasGraph()
144
+ const threads = visibleThreads(state.workspace?.threads ?? [])
145
+ const ids = new Set(threads.map(thread => thread.id))
146
+ const sessions = new Set(threads.map(thread => thread.dshSessionId))
147
+ const switched = cacheWorkspaceId !== (state.workspace?.id ?? null)
148
+ reconcileCanvasFocus(threads, switched)
149
+ const removed = switched || [...cacheThreadIds].some(id => !ids.has(id))
150
+ const belongs = key => ids.has(key.slice(0, key.indexOf(':')))
151
+ if (switched) clearViewCaches()
152
+ else bodyLoader.retainThreads(ids)
153
+ if (removed) {
154
+ markdownCache.clear()
155
+ for (const key of state.expandedMessageIds) if (switched || !belongs(key)) state.expandedMessageIds.delete(key)
156
+ for (const map of [state.detailScrollByThread, state.detailPageByThread]) {
157
+ for (const key of map.keys()) if (switched || !ids.has(key)) map.delete(key)
158
+ }
159
+ for (const key of state.inspectorScrollByCard.keys()) if (switched || !belongs(key)) state.inspectorScrollByCard.delete(key)
160
+ state.canvasCards = undefined
161
+ state.canvasCardsById = undefined
162
+ state.canvasGraph = undefined
163
+ state.mountedCardIds.clear()
164
+ connectorPathsByCard.clear()
165
+ if (switched) {
166
+ state.inspectorCardId = null; state.inspectorOpening = false; state.detailThreadId = null
167
+ }
168
+ }
169
+ for (const map of [state.historyBySession, state.liveReplies]) for (const id of map.keys()) if (!sessions.has(id)) map.delete(id)
170
+ cacheWorkspaceId = state.workspace?.id ?? null
171
+ cacheThreadIds = ids
172
+ }
173
+
174
+ function pauseMapBodies() {
175
+ state.mapVisible = false
176
+ clearViewCaches()
177
+ state.liveReplies.clear()
178
+ hideSelectionFollowup()
179
+ releaseRenderedBodies()
180
+ }
181
+
182
+ function releaseRenderedBodies() {
183
+ // An iframe hidden by the host still retains its DOM. Drop the content,
184
+ // keeping the viewport shell so camera measurements work on reopening.
185
+ document.querySelector('.canvas-viewport')?.replaceChildren()
186
+ document.querySelector('.detail-scroll')?.replaceChildren()
187
+ document.querySelector('.card-inspector')?.remove()
188
+ }
189
+
77
190
  function rememberBranchAnchor(sessionId, cardId) {
191
+ invalidateCanvasGraph()
78
192
  state.branchAnchors.set(sessionId, cardId)
79
193
  try { localStorage.setItem('dsh-synapse:branch-anchors', JSON.stringify([...state.branchAnchors])) } catch { /* Private browsing may disable local storage. */ }
80
194
  }
@@ -84,6 +198,7 @@ function persistCardPositions() {
84
198
  }
85
199
 
86
200
  function persistCollapsedCards() {
201
+ invalidateCanvasGraph()
87
202
  try { localStorage.setItem(COLLAPSED_CARDS_KEY, JSON.stringify([...state.collapsedCardIds])) } catch { /* Private browsing may disable local storage. */ }
88
203
  }
89
204
 
@@ -98,6 +213,7 @@ function rememberCardPosition(cardId, position, aliases = []) {
98
213
  }
99
214
 
100
215
  function resetCardPositions() {
216
+ invalidateCanvasGraph()
101
217
  state.cardPositions.clear()
102
218
  persistCardPositions()
103
219
  try {
@@ -112,9 +228,12 @@ function resetCanvasCamera() {
112
228
  }
113
229
 
114
230
  async function api(path, options = {}) {
115
- const response = await fetch(path, { ...options, headers: { 'content-type': 'application/json', ...(options.headers ?? {}) } })
231
+ // Call sites use the server's logical /synapse namespace. Resolve requests
232
+ // inside this map document so a prefix-stripping proxy keeps its public path.
233
+ const url = new URL(path.replace(/^\/synapse\//, ''), document.baseURI)
234
+ const response = await fetch(url, { ...options, headers: { 'content-type': 'application/json', ...(options.headers ?? {}) } })
116
235
  const body = await response.json().catch(() => ({}))
117
- if (!response.ok) throw new Error(body.error ?? '请求失败')
236
+ if (!response.ok) throw Object.assign(new Error(body.error ?? '请求失败'), { status: response.status })
118
237
  return body
119
238
  }
120
239
 
@@ -151,8 +270,11 @@ function messagesFromEvents(events) {
151
270
  return events.flatMap(event => {
152
271
  const content = event?.data?.message?.content ?? event?.data?.content
153
272
  const text = Array.isArray(content) ? content.filter(block => block?.type === 'text').map(block => block.text).filter(Boolean).join('\n') : ''
154
- if (event?.type === 'user/message' && text && !text.startsWith('Current runtime context. This snapshot supersedes earlier runtime-context snapshots.')) return [{ kind: 'user', text, at: event.time, sourceSeq: event.seq }]
155
- if (event?.type === 'assistant/message' && text) return [{ kind: 'assistant', text, at: event.time, sourceSeq: event.seq }]
273
+ const sourceKind = event?.data?.source?.kind
274
+ const injected = typeof sourceKind === 'string' ? sourceKind !== 'user'
275
+ : text.trimStart().startsWith('Current runtime context. This snapshot supersedes earlier runtime-context snapshots.')
276
+ if (event?.type === 'user/message' && text.trim() && !injected) return [{ kind: 'user', text, at: event.time, sourceSeq: event.seq, ...(typeof sourceKind === 'string' ? { sourceKind } : {}) }]
277
+ if (event?.type === 'assistant/message') return [{ kind: 'assistant', text, at: event.time, sourceSeq: event.seq, turn: event.data?.turn, step: event.data?.step }]
156
278
  return []
157
279
  })
158
280
  }
@@ -194,9 +316,35 @@ function workspaceChoices() {
194
316
 
195
317
  async function threadsForDshWorkspace(workspace) {
196
318
  if (workspace.sessionIds.length === 0) return []
197
- const requested = new Set(workspace.sessionIds)
198
- const projections = await Promise.all(state.summaries.map(summary => api(`/synapse/api/workspaces/${summary.id}`)))
199
- return projections.flatMap(projection => projection.workspace.threads.filter(thread => requested.has(thread.dshSessionId)))
319
+ // Stay within the API's 32 KiB request limit even for large DSH groups.
320
+ // These batches contain selectors only, never unrelated workspace payloads.
321
+ const batches = []
322
+ const encoder = new TextEncoder()
323
+ let batch = []
324
+ let bytes = encoder.encode('{"sessionIds":[]}').length
325
+ for (const id of new Set(workspace.sessionIds)) {
326
+ const size = encoder.encode(JSON.stringify(id)).length + 1
327
+ if (bytes + size > 32 * 1024) {
328
+ if (batch.length === 0) throw new Error('会话编号过长')
329
+ batches.push(batch)
330
+ batch = []
331
+ bytes = encoder.encode('{"sessionIds":[]}').length
332
+ }
333
+ if (bytes + size > 32 * 1024) throw new Error('会话编号过长')
334
+ batch.push(id)
335
+ bytes += size
336
+ }
337
+ if (batch.length > 0) batches.push(batch)
338
+ const threads = []
339
+ for (const sessionIds of batches) {
340
+ const body = await api('/synapse/api/threads/query', { method: 'POST', body: JSON.stringify({ sessionIds }) })
341
+ threads.push(...body.threads)
342
+ }
343
+ return threads
344
+ }
345
+
346
+ function dshWorkspaceProjection(workspace, threads) {
347
+ return { id: `dsh:${workspace.id}`, title: workspace.title, cwd: workspace.path, threads }
200
348
  }
201
349
 
202
350
  async function openDshWorkspace(id, { renderAfter = true, preserveCanvasCamera = false, userInitiated = false } = {}) {
@@ -210,26 +358,34 @@ async function openDshWorkspace(id, { renderAfter = true, preserveCanvasCamera =
210
358
  const load = ++state.workspaceLoad
211
359
  if (userInitiated) state.workspaceLoadOwner = 'user'
212
360
  state.workspaceLoadBusy = true
361
+ prepareWorkspaceCaches(`dsh:${id}`)
213
362
  try {
214
363
  state.selectedDshWorkspaceId = id
364
+ const summariesSignature = JSON.stringify(state.summaries)
215
365
  const threads = await threadsForDshWorkspace(workspace)
216
- if (load !== state.workspaceLoad) return true
366
+ if (load !== state.workspaceLoad || workspace !== selectedDshWorkspace()) return false
217
367
  const nextWorkspaceId = `dsh:${workspace.id}`
218
368
  if (state.workspace?.id !== nextWorkspaceId && !preserveCanvasCamera) resetCanvasCamera()
219
- state.workspace = { id: nextWorkspaceId, title: workspace.title, cwd: workspace.path, threads }
369
+ state.workspace = dshWorkspaceProjection(workspace, threads)
370
+ pruneWorkspaceCaches()
220
371
  state.workspaceFingerprint = JSON.stringify(state.workspace)
372
+ state.workspaceSummariesSignature = summariesSignature
373
+ state.workspaceDshSignature = JSON.stringify(workspace)
221
374
  const currentThread = currentDshThread(state.workspace.threads)
222
375
  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)
376
+ if (currentThread !== undefined && state.focusedThreadId === null) revealConversationThread(conversationCards(state.workspace.threads), currentThread.id)
224
377
  if (renderAfter && canReplaceView()) render()
225
378
  await Promise.all(state.workspace.threads.map(thread => loadThreadHistory(thread, false)))
226
379
  if (renderAfter && load === state.workspaceLoad && canReplaceView()) render()
227
380
  // 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() })
381
+ if (userInitiated && load === state.workspaceLoad) queueActiveCardFocus()
229
382
  return true
230
383
  } finally {
231
- state.workspaceLoadBusy = false
232
- if (userInitiated && load === state.workspaceLoad) state.workspaceLoadOwner = null
384
+ if (load === state.workspaceLoad) {
385
+ state.workspaceLoadOwner = null
386
+ state.workspaceLoadBusy = false
387
+ void hydrateBodies()
388
+ }
233
389
  }
234
390
  }
235
391
 
@@ -239,13 +395,14 @@ async function openCurrentWorkspace({ preserveCanvasCamera = false } = {}) {
239
395
  return openDshWorkspace(workspace.id, { preserveCanvasCamera })
240
396
  }
241
397
 
242
- async function refreshSummaries({ renderAfter = true } = {}) {
398
+ async function refreshSummaries({ renderAfter = true, loadWorkspace = true } = {}) {
243
399
  const before = JSON.stringify(state.summaries)
244
400
  const body = await api('/synapse/api/workspaces')
245
401
  state.summaries = body.workspaces
246
402
  const changed = before !== JSON.stringify(state.summaries)
403
+ if (!loadWorkspace) return changed
247
404
  const current = state.workspace?.id
248
- if (state.selectedDshWorkspaceId === null && current !== null && !state.summaries.some(item => item.id === current)) state.workspace = null
405
+ if (state.selectedDshWorkspaceId === null && current !== null && !state.summaries.some(item => item.id === current)) { state.workspace = null; pruneWorkspaceCaches() }
249
406
  const selected = selectedDshWorkspace()
250
407
  if (selected !== undefined && (changed || state.workspace === null)) await openDshWorkspace(selected.id, { renderAfter })
251
408
  else if (state.workspace === null && state.summaries.length > 0) await openWorkspace(state.summaries[0].id)
@@ -255,15 +412,28 @@ async function refreshSummaries({ renderAfter = true } = {}) {
255
412
 
256
413
  async function openWorkspace(id, { renderAfter = true } = {}) {
257
414
  const load = ++state.workspaceLoad
258
- const body = await api(`/synapse/api/workspaces/${id}`)
259
- if (load !== state.workspaceLoad) return
260
- if (state.workspace?.id !== body.workspace.id) resetCanvasCamera()
261
- state.workspace = body.workspace
262
- state.workspaceFingerprint = JSON.stringify(state.workspace)
263
- state.activeId = state.workspace.threads.some(thread => thread.id === state.activeId) ? state.activeId : state.workspace.threads[0]?.id ?? null
264
- if (renderAfter && canReplaceView()) render()
265
- await Promise.all(state.workspace.threads.map(thread => loadThreadHistory(thread, false)))
266
- if (renderAfter && load === state.workspaceLoad && canReplaceView()) render()
415
+ state.workspaceLoadBusy = true
416
+ prepareWorkspaceCaches(id)
417
+ try {
418
+ const summariesSignature = JSON.stringify(state.summaries)
419
+ const body = await api(`/synapse/api/workspaces/${id}`)
420
+ if (load !== state.workspaceLoad) return
421
+ if (state.workspace?.id !== body.workspace.id) resetCanvasCamera()
422
+ state.workspace = body.workspace
423
+ pruneWorkspaceCaches()
424
+ state.workspaceFingerprint = JSON.stringify(state.workspace)
425
+ state.workspaceSummariesSignature = summariesSignature
426
+ state.activeId = state.workspace.threads.some(thread => thread.id === state.activeId) ? state.activeId : state.workspace.threads[0]?.id ?? null
427
+ if (renderAfter && canReplaceView()) render()
428
+ await Promise.all(state.workspace.threads.map(thread => loadThreadHistory(thread, false)))
429
+ if (renderAfter && load === state.workspaceLoad && canReplaceView()) render()
430
+ } finally {
431
+ if (load === state.workspaceLoad) {
432
+ state.workspaceLoadOwner = null
433
+ state.workspaceLoadBusy = false
434
+ void hydrateBodies()
435
+ }
436
+ }
267
437
  }
268
438
 
269
439
  /**
@@ -274,13 +444,23 @@ async function openWorkspace(id, { renderAfter = true } = {}) {
274
444
  */
275
445
  async function refreshCurrentWorkspace() {
276
446
  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)
447
+ if (current === null || state.workspaceLoadBusy || state.workspaceLoadOwner === 'user') return false
448
+ const load = state.workspaceLoad
449
+ const selected = selectedDshWorkspace()
450
+ const summariesSignature = JSON.stringify(state.summaries)
451
+ const workspace = current.id.startsWith('dsh:')
452
+ ? (selected === undefined ? null : dshWorkspaceProjection(selected, await threadsForDshWorkspace(selected)))
453
+ : (await api(`/synapse/api/workspaces/${current.id}`)).workspace
454
+ if (workspace === null || state.workspace !== current || load !== state.workspaceLoad || state.workspaceLoadBusy || selected !== selectedDshWorkspace() || !canReplaceView()) return false
455
+ // A failed fetch never advances this signature: the next poll must retry
456
+ // even if the server's summaries have stopped changing.
457
+ state.workspaceSummariesSignature = summariesSignature
458
+ state.workspaceDshSignature = JSON.stringify(selected)
459
+ const fingerprint = JSON.stringify(workspace)
281
460
  if (state.workspaceFingerprint === fingerprint) return false
282
461
  state.workspaceFingerprint = fingerprint
283
- state.workspace = body.workspace
462
+ state.workspace = workspace
463
+ pruneWorkspaceCaches()
284
464
  if (!state.workspace.threads.some(thread => thread.id === state.activeId)) {
285
465
  state.activeId = state.workspace.threads[0]?.id ?? null
286
466
  }
@@ -289,16 +469,35 @@ async function refreshCurrentWorkspace() {
289
469
  }
290
470
 
291
471
  async function refreshProjection() {
292
- const summariesChanged = await refreshSummaries({ renderAfter: false })
293
- if (!summariesChanged || state.workspace === null || !canReplaceView()) return summariesChanged
294
- if (state.workspace.id.startsWith('dsh:')) return (await refreshCurrentWorkspace()) || summariesChanged
295
- if (state.selectedDshWorkspaceId !== null) await openDshWorkspace(state.selectedDshWorkspaceId)
296
- else await openWorkspace(state.workspace.id)
297
- return true
472
+ if (state.workspaceLoadBusy || state.workspaceLoadOwner === 'user') return false
473
+ const summariesChanged = await refreshSummaries({ renderAfter: false, loadWorkspace: false })
474
+ if (state.workspaceLoadBusy || state.workspaceLoadOwner === 'user' || !canReplaceView()) return false
475
+ const selected = selectedDshWorkspace()
476
+ let viewRemoved = false
477
+ if ((state.selectedDshWorkspaceId !== null && selected === undefined) ||
478
+ (state.selectedDshWorkspaceId === null && state.workspace !== null && !state.summaries.some(item => item.id === state.workspace.id))) {
479
+ state.selectedDshWorkspaceId = null
480
+ state.workspace = null
481
+ pruneWorkspaceCaches()
482
+ state.activeId = null
483
+ viewRemoved = true
484
+ }
485
+ if (state.workspace === null || (selected !== undefined && state.workspace.id !== `dsh:${selected.id}`)) {
486
+ const next = selected ?? currentDshWorkspace() ?? state.dshWorkspaces[0]
487
+ if (next !== undefined) return openDshWorkspace(next.id)
488
+ if (state.summaries.length > 0) { await openWorkspace(state.summaries[0].id); return true }
489
+ if (summariesChanged || viewRemoved) render()
490
+ return summariesChanged || viewRemoved
491
+ }
492
+ if (state.workspaceSummariesSignature !== JSON.stringify(state.summaries) ||
493
+ (selected !== undefined && state.workspaceDshSignature !== JSON.stringify(selected))) return refreshCurrentWorkspace()
494
+ if (summariesChanged) render()
495
+ return summariesChanged
298
496
  }
299
497
 
300
498
  function openNewSession() {
301
499
  if (state.draft !== null) return
500
+ setCanvasFocus(null)
302
501
  state.mode = 'canvas'
303
502
  state.activeId = null
304
503
  state.selectedCardId = null
@@ -325,6 +524,7 @@ async function archiveThread(thread) {
325
524
  return
326
525
  }
327
526
  state.archivedSessionIds.add(thread.dshSessionId)
527
+ pruneWorkspaceCaches()
328
528
  state.activeId = state.activeId === thread.id ? (state.workspace?.threads.find(item => item.id !== thread.id)?.id ?? null) : state.activeId
329
529
  if (state.inspectorCardId !== null && state.canvasCardsById?.get(state.inspectorCardId)?.dshThreadId === thread.id) state.inspectorCardId = null
330
530
  render()
@@ -348,6 +548,7 @@ async function archiveThread(thread) {
348
548
  }
349
549
  }
350
550
  state.workspace.threads = state.workspace.threads.filter(item => !removed.has(item.id))
551
+ pruneWorkspaceCaches()
351
552
  for (const key of [...state.cardPositions.keys()]) {
352
553
  if ([...removed].some(id => key.startsWith(`${id}:`))) state.cardPositions.delete(key)
353
554
  }
@@ -398,6 +599,7 @@ async function sendMessage(thread, text) {
398
599
  if (thread.dshSessionId === null) throw new Error('该节点没有关联的 DSH 会话')
399
600
  if (state.pendingReplies.has(thread.dshSessionId)) throw new Error('该会话正在回复,请稍后再发送')
400
601
  state.pendingReplies.set(thread.dshSessionId, { text, at: Date.now() })
602
+ invalidateCanvasGraph()
401
603
  state.error = ''
402
604
  render()
403
605
  try {
@@ -405,6 +607,7 @@ async function sendMessage(thread, text) {
405
607
  void loadThreadHistory(thread)
406
608
  } catch (error) {
407
609
  state.pendingReplies.delete(thread.dshSessionId)
610
+ invalidateCanvasGraph()
408
611
  render()
409
612
  throw error
410
613
  }
@@ -443,6 +646,7 @@ async function submitDraft() {
443
646
  state.activeId = result.thread.id
444
647
  state.draft = null
445
648
  state.pendingReplies.set(result.thread.dshSessionId, { text, at: Date.now() })
649
+ invalidateCanvasGraph()
446
650
  render()
447
651
  await dshRpc('synapse:send-message', { sessionId: result.thread.dshSessionId, text })
448
652
  void loadThreadHistory(result.thread)
@@ -450,6 +654,7 @@ async function submitDraft() {
450
654
  } catch (error) {
451
655
  if (draft.kind === 'branch') {
452
656
  state.pendingReplies.delete(state.workspace?.threads.find(thread => thread.id === state.activeId)?.dshSessionId)
657
+ invalidateCanvasGraph()
453
658
  if (state.draft !== null) state.draft = { ...draft, sending: false }
454
659
  } else {
455
660
  state.draft = { ...draft, sending: false }
@@ -484,24 +689,16 @@ function settlePendingReply(thread, messages) {
484
689
  const pending = state.pendingReplies.get(thread.dshSessionId)
485
690
  if (pending === undefined) return false
486
691
  const userIndex = pendingUserIndex(messages, pending)
487
- if (userIndex === -1 || !messages.slice(userIndex + 1).some(message => message.kind === 'assistant')) return false
692
+ if (userIndex === -1 || !messages.slice(userIndex + 1).some(message => message.kind === 'error' || message.kind === 'assistant' && message.text?.trim())) return false
488
693
  state.pendingReplies.delete(thread.dshSessionId)
489
694
  return true
490
695
  }
491
696
 
492
- function messagesFor(thread) {
493
- // A runtime-context snapshot is internal DSH state, never a user turn.
494
- // Filter here as well as during persistence so existing saved workspaces
495
- // immediately render one question and its answer as one card.
496
- const stored = persistedMessagesFor(thread).filter(message => !(message.kind === 'user' && typeof message.text === 'string' && message.text.trimStart().startsWith('Current runtime context. This snapshot supersedes earlier runtime-context snapshots.')))
697
+ function messagesFor(thread, hydrate = true) {
698
+ // Old rows without provenance are repaired against the original log.
699
+ const stored = persistedMessagesFor(thread).filter(message => !(message.kind === 'user' && typeof message.sourceKind === 'string' && message.sourceKind !== 'user'))
497
700
  // Swap in hydrated bodies where present: the stored text is only a preview.
498
- const bodies = state.bodies.get(thread.id)
499
- const messages = bodies === undefined || bodies.size === 0
500
- ? stored
501
- : stored.map(message => {
502
- const body = bodies.get(message.sourceSeq)
503
- return body === undefined ? message : { ...message, text: body.text, process: Array.isArray(body.process) ? body.process : message.process, truncated: body.truncated === true, hydrated: true }
504
- })
701
+ const messages = hydrate ? stored.map(message => hydratedMessage(thread, message)) : stored
505
702
  const pending = state.pendingReplies.get(thread.dshSessionId)
506
703
  if (pending === undefined) return messages
507
704
  if (settlePendingReply(thread, messages)) {
@@ -515,7 +712,7 @@ function messagesFor(thread) {
515
712
  return [...messages, { kind: 'user', text: pending.text, pending: true, at: new Date(pending.at).toISOString() }, liveAssistant]
516
713
  }
517
714
 
518
- function latestMessage(thread, kind) { return [...messagesFor(thread)].reverse().find(message => message.kind === kind) }
715
+ function latestMessage(thread, kind) { return hydratedMessage(thread, [...messagesFor(thread, false)].reverse().find(message => message.kind === kind && (kind !== 'assistant' || message.text?.trim()))) }
519
716
  function questionFor(thread) { return latestMessage(thread, 'user')?.text ?? thread.dshSessionTitle ?? '等待用户提问' }
520
717
  function answerFor(thread) { return latestMessage(thread, 'assistant') ?? null }
521
718
 
@@ -587,19 +784,19 @@ function markdownBlock(text) {
587
784
 
588
785
  // Markdown parsing is pure CPU and repeats for every card on every canvas
589
786
  // rebuild; cache the rendered HTML by input text so stable answers are never
590
- // re-parsed. Bounded: streaming partial texts churn keys, so evict oldest.
591
- const markdownCache = new Map()
592
- const MARKDOWN_CACHE_LIMIT = 5000
593
- function renderMarkdown(text) {
787
+ // re-parsed. Count the input key and HTML, not just the number of entries.
788
+ const MARKDOWN_CACHE_LIMIT = SynapseCache.LIMITS.markdownEntries
789
+ const markdownCache = new SynapseCache.ByteLru(SynapseCache.LIMITS.markdownBytes, MARKDOWN_CACHE_LIMIT)
790
+ function renderMarkdown(text, cache = true) {
594
791
  const key = String(text)
595
- const cached = markdownCache.get(key)
792
+ const cached = cache ? markdownCache.get(key) : undefined
596
793
  if (cached !== undefined) return cached
597
794
  const parts = key.split(/```/)
598
795
  const rendered = parts.map((part, index) => index % 2 === 1
599
796
  ? `<pre><code>${escapeHtml(part.replace(/^\w*\n/, ''))}</code></pre>`
600
797
  : markdownBlock(part)).join('')
601
- if (markdownCache.size >= MARKDOWN_CACHE_LIMIT) markdownCache.delete(markdownCache.keys().next().value)
602
- markdownCache.set(key, rendered)
798
+ const bytes = SynapseCache.textBytes(key) + SynapseCache.textBytes(rendered) + 128
799
+ if (cache && bytes <= SynapseCache.LIMITS.markdownEntryBytes) markdownCache.set(key, rendered, SynapseCache.textBytes(rendered))
603
800
  return rendered
604
801
  }
605
802
 
@@ -695,15 +892,24 @@ function placeConversationCards(cards) {
695
892
  const position = state.cardPositions.get(card.id) ?? state.cardPositions.get(card.positionKey)
696
893
  return position === undefined ? [] : [[card.id, { x: position.x, y: position.y }]]
697
894
  }))
698
- const occupied = []
895
+ const occupied = new SynapseCache.RegionIndex()
699
896
  for (const card of cards) {
700
897
  const position = saved.get(card.id)
701
898
  if (position !== undefined) {
702
899
  card.position = position
703
900
  continue
704
901
  }
705
- card.position = firstAvailableCardPosition(card.naturalPosition ?? card.position, occupied)
706
- occupied.push(card.position)
902
+ const candidate = { ...(card.naturalPosition ?? card.position) }
903
+ candidate.x = Math.round(candidate.x)
904
+ candidate.y = Math.max(82, Math.round(candidate.y))
905
+ while (true) {
906
+ const collisions = occupied.query({ left: candidate.x, right: candidate.x + CARD_WIDTH, top: candidate.y, bottom: candidate.y + CARD_HEIGHT })
907
+ .filter(other => overlapsCard(candidate, other.position))
908
+ if (collisions.length === 0) break
909
+ candidate.y = Math.max(...collisions.map(other => other.position.y + CARD_HEIGHT + CARD_GAP_Y))
910
+ }
911
+ card.position = candidate
912
+ occupied.set(card)
707
913
  }
708
914
  return cards
709
915
  }
@@ -718,28 +924,38 @@ function layoutConversationGraph(cards, threads) {
718
924
  }
719
925
  const laneByThread = new Map()
720
926
  const visitThread = threadId => {
721
- if (laneByThread.has(threadId)) return
722
- laneByThread.set(threadId, laneByThread.size)
723
- for (const childId of childrenByThread.get(threadId) ?? []) visitThread(childId)
927
+ const stack = [threadId]
928
+ while (stack.length > 0) {
929
+ const id = stack.pop()
930
+ if (laneByThread.has(id)) continue
931
+ laneByThread.set(id, laneByThread.size)
932
+ const children = childrenByThread.get(id) ?? []
933
+ for (let index = children.length - 1; index >= 0; index--) stack.push(children[index])
934
+ }
724
935
  }
725
936
  for (const thread of threads) if (thread.parentId === null) visitThread(thread.id)
726
937
  for (const thread of threads) visitThread(thread.id)
727
938
 
728
939
  const byId = new Map(cards.map(card => [card.id, card]))
729
940
  const positioned = new Map()
730
- const positionFor = (card, visiting = new Set()) => {
731
- if (positioned.has(card.id)) return positioned.get(card.id)
732
- if (visiting.has(card.id)) return { x: 86, y: 82 + (laneByThread.get(card.dshThreadId) ?? 0) * (CARD_HEIGHT + CARD_GAP_Y) }
733
- visiting.add(card.id)
734
- const parent = card.parentId === null ? undefined : byId.get(card.parentId)
735
- const parentPosition = parent === undefined ? undefined : positionFor(parent, visiting)
736
- const position = {
737
- x: parentPosition === undefined ? 86 : parentPosition.x + 365,
738
- y: 82 + (laneByThread.get(card.dshThreadId) ?? 0) * (CARD_HEIGHT + CARD_GAP_Y),
941
+ const positionFor = card => {
942
+ const chain = []
943
+ const visiting = new Set()
944
+ let current = card
945
+ while (current !== undefined && !positioned.has(current.id) && !visiting.has(current.id)) {
946
+ visiting.add(current.id)
947
+ chain.push(current)
948
+ current = current.parentId === null ? undefined : byId.get(current.parentId)
949
+ }
950
+ let parentPosition = current === undefined ? undefined : positioned.get(current.id)
951
+ while (chain.length > 0) {
952
+ const next = chain.pop()
953
+ const position = { x: parentPosition === undefined ? 86 : parentPosition.x + 365,
954
+ y: 82 + (laneByThread.get(next.dshThreadId) ?? 0) * (CARD_HEIGHT + CARD_GAP_Y) }
955
+ positioned.set(next.id, position)
956
+ parentPosition = position
739
957
  }
740
- visiting.delete(card.id)
741
- positioned.set(card.id, position)
742
- return position
958
+ return positioned.get(card.id)
743
959
  }
744
960
  for (const card of cards) {
745
961
  card.naturalPosition = positionFor(card)
@@ -751,24 +967,29 @@ function layoutConversationGraph(cards, threads) {
751
967
  function conversationCards(threads) {
752
968
  const cards = []
753
969
  const cardsByThread = new Map()
970
+ const threadIndex = new Map(threads.map(thread => [thread.id, thread]))
754
971
  for (const thread of threads) {
755
- const messages = messagesFor(thread)
972
+ // Retained graph cards contain previews only. Hydrate an ephemeral card
973
+ // for rendering, so cache eviction really releases body references.
974
+ const messages = messagesFor(thread, false)
756
975
  const turns = []
757
976
  for (let messageIndex = 0; messageIndex < messages.length; messageIndex++) {
758
977
  const question = messages[messageIndex]
759
978
  if (question.kind !== 'user') continue
760
979
  const replies = []
761
980
  const errors = []
981
+ const turnMessages = [question]
762
982
  let processCount = 0
763
983
  for (let replyIndex = messageIndex + 1; replyIndex < messages.length; replyIndex++) {
764
984
  const reply = messages[replyIndex]
765
985
  if (reply.kind === 'user') break
986
+ turnMessages.push(reply)
766
987
  if (reply.kind === 'assistant') replies.push(reply)
767
988
  if (reply.kind === 'error') errors.push(reply)
768
989
  if (Array.isArray(reply.process)) processCount += reply.process.length
769
990
  else if (reply.kind === 'tool') processCount += 1
770
991
  }
771
- const answer = replies.at(-1) ?? null
992
+ const answer = replies.findLast(reply => reply.text?.trim()) ?? null
772
993
  const error = errors.at(-1) ?? null
773
994
  const turnIndex = turns.length
774
995
  const id = `${thread.id}:turn:${question.sourceSeq ?? messageIndex}`
@@ -791,6 +1012,7 @@ function conversationCards(threads) {
791
1012
  positionLocked,
792
1013
  question: question.text,
793
1014
  questionMessage: question,
1015
+ turnMessages,
794
1016
  answer,
795
1017
  error,
796
1018
  processCount,
@@ -800,6 +1022,11 @@ function conversationCards(threads) {
800
1022
  const latestTurn = turns.at(-1)
801
1023
  if (liveReply?.running && latestTurn !== undefined && (latestTurn.answer === null || latestTurn.answer.pending === true)) latestTurn.answer = { kind: 'assistant', text: liveReply.text, pending: true, at: new Date().toISOString() }
802
1024
  if (turns.length === 0) {
1025
+ // A DSH session containing only execution/context has no user turn.
1026
+ if (typeof thread.dshSessionId === 'string') {
1027
+ cardsByThread.set(thread.id, turns)
1028
+ continue
1029
+ }
803
1030
  const id = `${thread.id}:turn:empty`
804
1031
  const positionKey = `${thread.id}:turn-index:0`
805
1032
  const naturalPosition = { x: 86, y: 82 }
@@ -831,7 +1058,7 @@ function conversationCards(threads) {
831
1058
  if (card.turnIndex > 0) card.parentId = siblings[card.turnIndex - 1].id
832
1059
  else {
833
1060
  const parentCards = cardsByThread.get(card.sourceParentId)
834
- const sourceThread = threads.find(thread => thread.id === card.dshThreadId)
1061
+ const sourceThread = threadIndex.get(card.dshThreadId)
835
1062
  const firstChildQuestion = siblings?.[0]
836
1063
  const seedLength = sourceThread?.sourceSeedLength ?? firstChildQuestion?.sourceSeq
837
1064
  // A fork inherits every parent event before DSH's durable seed boundary.
@@ -846,6 +1073,31 @@ function conversationCards(threads) {
846
1073
  return layoutConversationGraph(cards, threads)
847
1074
  }
848
1075
 
1076
+ function conversationThreadScope(threads, rootId) {
1077
+ if (rootId === null || rootId === undefined) return null
1078
+ const children = new Map()
1079
+ for (const thread of threads) {
1080
+ if (!children.has(thread.parentId)) children.set(thread.parentId, [])
1081
+ children.get(thread.parentId).push(thread.id)
1082
+ }
1083
+ // Thread lineage also covers forks whose intermediate session has no turns.
1084
+ // Iteration and the visited set handle deep trees and malformed cycles.
1085
+ const ids = new Set()
1086
+ const pending = threads.some(thread => thread.id === rootId) ? [rootId] : []
1087
+ while (pending.length > 0) {
1088
+ const id = pending.pop()
1089
+ if (ids.has(id)) continue
1090
+ ids.add(id)
1091
+ for (const childId of children.get(id) ?? []) if (!ids.has(childId)) pending.push(childId)
1092
+ }
1093
+ return ids
1094
+ }
1095
+
1096
+ function scopedConversationCards(cards, threads, rootId = state.focusedThreadId) {
1097
+ const ids = conversationThreadScope(threads, rootId)
1098
+ return ids === null ? cards : cards.filter(card => ids.has(card.dshThreadId))
1099
+ }
1100
+
849
1101
  function conversationGraphView(cards, collapsedCardIds = state.collapsedCardIds) {
850
1102
  const cardIds = new Set(cards.map(card => card.id))
851
1103
  const childrenByParent = new Map()
@@ -857,23 +1109,25 @@ function conversationGraphView(cards, collapsedCardIds = state.collapsedCardIds)
857
1109
  }
858
1110
 
859
1111
  const hiddenIds = new Set()
1112
+ const cyclicCollapsedIds = new Set()
860
1113
  for (const rootId of collapsedCardIds) {
861
1114
  if (!cardIds.has(rootId)) continue
862
1115
  const visited = new Set([rootId])
863
- const visit = parentId => {
864
- for (const childId of childrenByParent.get(parentId) ?? []) {
1116
+ const pending = [rootId]
1117
+ while (pending.length > 0) {
1118
+ for (const childId of childrenByParent.get(pending.pop()) ?? []) {
1119
+ if (childId === rootId) cyclicCollapsedIds.add(rootId)
865
1120
  if (visited.has(childId)) continue
866
1121
  visited.add(childId)
867
1122
  hiddenIds.add(childId)
868
- visit(childId)
1123
+ pending.push(childId)
869
1124
  }
870
1125
  }
871
- visit(rootId)
872
1126
  }
873
1127
 
874
- // Persisted collapse roots must remain visible even if malformed metadata
875
- // contains a cycle where two collapsed nodes otherwise hide each other.
876
- for (const rootId of collapsedCardIds) hiddenIds.delete(rootId)
1128
+ // A collapsed child still belongs to its ancestor's hidden subtree.
1129
+ // Only actual parent cycles need an exception to keep their controls usable.
1130
+ for (const rootId of cyclicCollapsedIds) hiddenIds.delete(rootId)
877
1131
 
878
1132
  // Post-order accumulation: each card's descendant count is 1 + the sum of
879
1133
  // its children's subtree sizes, so the whole graph is O(n) instead of a BFS
@@ -968,7 +1222,8 @@ function canvasConnectors(cards) {
968
1222
  return links.join('')
969
1223
  }
970
1224
 
971
- function conversationCard(card, graph) {
1225
+ function conversationCard(card, graph, overview = false) {
1226
+ if (!overview) card = hydratedCard(card)
972
1227
  const selected = card.id === state.selectedCardId ? 'selected' : ''
973
1228
  const source = card.parentId === null ? 'DSH 会话' : card.turnIndex === 0 ? 'DSH 分支' : '追问'
974
1229
  const continueButton = card.canContinue === true
@@ -979,12 +1234,18 @@ function conversationCard(card, graph) {
979
1234
  const foldLabel = collapsed ? '展开后续对话' : '折叠后续对话'
980
1235
  const foldButton = childCount === 0 || card.canContinue === true ? '' : `<button class="graph-fold-button${collapsed ? ' collapsed' : ''}" data-action="toggle-card-children" data-card="${escapeHtml(card.id)}" aria-expanded="${collapsed ? 'false' : 'true'}" aria-label="${foldLabel}" title="${foldLabel}"><svg aria-hidden="true" viewBox="0 0 16 16"><path d="M3.5 8h9"/>${collapsed ? '<path d="M8 3.5v9"/>' : ''}</svg></button>`
981
1236
  const branchButton = childCount === 0 || card.canContinue === true || !Number.isInteger(card.answer?.sourceSeq) ? '' : `<button class="graph-branch-button" data-action="open-branch" data-thread="${card.dshThreadId}" data-card="${escapeHtml(card.id)}" data-seq="${card.answer.sourceSeq}" aria-label="在新对话中分支" title="在新对话中分支"><svg aria-hidden="true" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M13.0762 1.37207C14.0846 1.37228 14.9021 2.19077 14.9023 3.19922C14.9022 4.20772 14.0847 5.02518 13.0762 5.02539C12.2967 5.02539 11.6325 4.53691 11.3701 3.84961H4.35547C4.79397 4.26458 5.15861 4.7644 5.41699 5.33496L7.10645 9.06738C7.88526 10.7875 9.55104 11.9228 11.4189 12.0371C11.7085 11.4109 12.3411 10.9756 13.0762 10.9756C14.0843 10.9759 14.9023 11.7936 14.9023 12.8018C14.9023 13.81 14.0843 14.6277 13.0762 14.6279C12.2534 14.6279 11.5574 14.0832 11.3291 13.335C8.9868 13.1879 6.89981 11.7612 5.92285 9.60352L4.23242 5.87109C3.67503 4.64033 2.44878 3.84961 1.09766 3.84961V2.54883C1.10665 2.54883 1.11601 2.54975 1.125 2.5498L11.3701 2.54883C11.6326 1.86151 12.2969 1.37207 13.0762 1.37207ZM13.0762 12.2764C12.7858 12.2764 12.5508 12.5114 12.5508 12.8018C12.5508 13.0921 12.7858 13.3281 13.0762 13.3281C13.3664 13.3279 13.6025 13.092 13.6025 12.8018C13.6025 12.5115 13.3664 12.2766 13.0762 12.2764ZM13.0762 2.67285C12.7855 2.67285 12.55 2.90861 12.5498 3.19922C12.5499 3.48987 12.7855 3.72559 13.0762 3.72559C13.3667 3.72538 13.6024 3.48975 13.6025 3.19922C13.6023 2.90874 13.3666 2.67306 13.0762 2.67285Z" fill="currentColor"/></svg></button>`
982
- return `<article class="thread-card ${selected}" data-card-id="${escapeHtml(card.id)}" data-position-key="${escapeHtml(card.positionKey)}" data-thread="${card.dshThreadId}" style="left:${card.position.x}px;top:${card.position.y}px;--thread-color:#3478f6">
983
- <button class="node-handle" data-drag-card="${card.id}" aria-label="拖动 ${escapeHtml(card.question)}" title="拖动卡片"></button>
1237
+ const answerText = String(card.answer?.text ?? '')
1238
+ const faceAnswer = overview
1239
+ ? `<p class="card-overview-summary">${escapeHtml(answerText.slice(0, 180) || (card.error === null ? '等待助手回复' : '本轮未完成'))}</p>`
1240
+ : card.answer === null ? (card.error === null ? '<p class="thread-answer-empty">等待助手回复</p>' : '')
1241
+ : `${renderMarkdown(answerText.slice(0, MAP_FACE_TEXT), !card.answer.pending)}${answerText.length > MAP_FACE_TEXT ? '<p class="card-face-notice">点击卡片查看完整回答</p>' : ''}${card.answer.pending ? '<p class="thread-answer-pending">正在回复</p>' : ''}`
1242
+ const question = String(card.question ?? '').slice(0, 800)
1243
+ return `<article class="thread-card ${selected}${overview ? ' card-overview' : ''}" data-card-id="${escapeHtml(card.id)}" data-position-key="${escapeHtml(card.positionKey)}" data-thread="${card.dshThreadId}" style="left:${card.position.x}px;top:${card.position.y}px;--thread-color:#3478f6">
1244
+ <button class="node-handle" data-drag-card="${card.id}" aria-label="拖动 ${escapeHtml(question)}" title="拖动卡片"></button>
984
1245
  ${continueButton}${foldButton}${branchButton}
985
- <div class="thread-card-head"><span class="topic-dot"></span><button class="thread-title" data-action="show-thread" data-thread="${card.dshThreadId}" data-card="${escapeHtml(card.id)}" title="查看完整会话:${escapeHtml(card.question)}">${escapeHtml(card.question)}</button></div>
1246
+ <div class="thread-card-head"><span class="topic-dot"></span><button class="thread-title" data-action="show-thread" data-thread="${card.dshThreadId}" data-card="${escapeHtml(card.id)}" title="查看完整会话:${escapeHtml(question)}">${escapeHtml(question)}</button></div>
986
1247
  <div class="thread-meta"><span>${source}</span><span>第 ${card.turnIndex + 1} 轮</span>${card.error === null ? '' : '<span class="card-error-status">失败</span>'}${card.processCount > 0 ? `<span class="card-process-count">工具 ${card.processCount}</span>` : ''}</div>
987
- <div class="thread-answer">${card.answer === null ? (card.error === null ? '<p class="thread-answer-empty">等待助手回复</p>' : '') : card.answer.pending && card.answer.text === '' ? '<p class="thread-answer-pending">正在回复</p>' : `${renderMarkdown(card.answer.text)}${card.answer.pending ? '<p class="thread-answer-pending">正在回复</p>' : ''}`}${card.error === null ? '' : `<p class="thread-answer-error" title="${escapeHtml(card.error.text)}">本轮失败:${escapeHtml(card.error.text)}</p>`}</div>
1248
+ <div class="thread-answer">${faceAnswer}${card.error === null ? '' : `<p class="thread-answer-error">本轮失败:${escapeHtml(String(card.error.text ?? '').slice(0, 300))}</p>`}</div>
988
1249
  <footer><button data-action="show-thread" data-thread="${card.dshThreadId}" data-card="${escapeHtml(card.id)}" title="查看完整会话" aria-label="查看完整会话"><svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linejoin="round"><path d="M2 8.5 8 2.5l6 6V13.5a.5.5 0 0 1-.5.5h-11a.5.5 0 0 1-.5-.5Z"/><path d="M6.2 14v-3.6a1.8 1.8 0 0 1 3.6 0V14" /></svg>详情</button><button data-action="open-dsh" data-thread="${card.dshThreadId}" data-seq="${Number.isInteger(card.sourceSeq) ? card.sourceSeq : ''}" title="在 DSH 中打开" aria-label="在 DSH 中打开"><svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"><path d="M7 3.5H4.5A1.5 1.5 0 0 0 3 5v6.5A1.5 1.5 0 0 0 4.5 13H11a1.5 1.5 0 0 0 1.5-1.5V9"/><path d="M9.5 3.5h3v3M12.4 3.6 7.5 8.5"/></svg>DSH</button><button data-action="archive-thread" data-thread="${card.dshThreadId}" title="归档此会话" aria-label="归档此会话"><svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"><path d="M2.5 5h11M5.5 7v5.5a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1V7"/><path d="M4 5 5 2.8a.7.7 0 0 1 .6-.4h4.8a.7.7 0 0 1 .6.4L12 5M6 9.5h4"/></svg>归档</button></footer>
989
1250
  </article>`
990
1251
  }
@@ -1077,63 +1338,279 @@ function selectionFollowupButton() {
1077
1338
  return `<button class="selection-followup" type="button" data-action="follow-selection" hidden aria-label="基于所选内容创建追问" title="基于所选内容追问"><svg aria-hidden="true" viewBox="0 0 16 16"><path d="M3 3.5h10v6.25H7.2L4 12.5V9.75H3Z"/><path d="M8 4.9v3.4M6.3 6.6h3.4"/></svg><span>追问</span></button>`
1078
1339
  }
1079
1340
 
1080
- // Cards are mounted into the DOM only when they intersect the viewport
1081
- // (inflated by VIEWPORT_MARGIN) in world coordinates. The camera transform is
1082
- // translate(camera) scale(zoom), so screen = world * zoom + camera.
1083
- function visibleCardIds(cards) {
1341
+ let canvasGraphRevision = 0
1342
+ let canvasGraphCache = null
1343
+ let regionTimer = 0
1344
+ let regionWorkTimer = 0
1345
+ let regionGeneration = 0
1346
+ let regionView = null
1347
+ const regionElements = new Map()
1348
+ const regionDirtyCards = new Set()
1349
+ let inspectorBodyTimer = 0
1350
+
1351
+ function invalidateCanvasGraph() { canvasGraphRevision++ }
1352
+ function cancelRegionWork() {
1353
+ window.clearTimeout(regionTimer)
1354
+ window.clearTimeout(regionWorkTimer)
1355
+ window.clearTimeout(inspectorBodyTimer)
1356
+ regionTimer = regionWorkTimer = inspectorBodyTimer = 0
1357
+ regionGeneration++
1358
+ regionDirtyCards.clear()
1359
+ }
1360
+
1361
+ function ensureCanvasGraph(threads) {
1362
+ if (canvasGraphCache?.workspace === state.workspace && canvasGraphCache.revision === canvasGraphRevision
1363
+ && canvasGraphCache.focusedThreadId === state.focusedThreadId) return
1364
+ // Lay out the complete workspace before filtering, so focusing never moves
1365
+ // automatically positioned cards or changes the saved drag coordinates.
1366
+ const allCards = conversationCards(threads)
1367
+ const scopedCards = scopedConversationCards(allCards, threads)
1368
+ const graph = conversationGraphView(scopedCards)
1369
+ const index = new SynapseCache.RegionIndex()
1370
+ const children = new Map()
1371
+ const byMessage = new Map()
1372
+ const latestByThread = new Map()
1373
+ for (const card of allCards) latestByThread.set(card.dshThreadId, card)
1374
+ for (const card of graph.cards) {
1375
+ index.set(card)
1376
+ if (card.parentId !== null) {
1377
+ if (!children.has(card.parentId)) children.set(card.parentId, [])
1378
+ children.get(card.parentId).push(card.id)
1379
+ }
1380
+ for (const message of [card.questionMessage, card.answer, card.error]) {
1381
+ if (Number.isInteger(message?.sourceSeq)) byMessage.set(`${card.dshThreadId}:${message.sourceSeq}`, card.id)
1382
+ }
1383
+ }
1384
+ canvasGraphCache = { workspace: state.workspace, revision: canvasGraphRevision, focusedThreadId: state.focusedThreadId, graph, index, children, byMessage,
1385
+ allById: new Map(allCards.map(card => [card.id, card])), scopeCardIds: new Set(scopedCards.map(card => card.id)), latestByThread,
1386
+ threadById: new Map(threads.map(thread => [thread.id, thread])) }
1387
+ state.canvasCards = graph.cards
1388
+ state.canvasCardsById = new Map(graph.cards.map(card => [card.id, card]))
1389
+ state.canvasGraph = graph
1390
+ }
1391
+
1392
+ function canvasWorldBounds(margin = 0) {
1084
1393
  const viewport = document.querySelector('.canvas-viewport')
1085
- if (!(viewport instanceof HTMLElement)) return new Set(cards.map(card => card.id))
1086
- const bounds = viewport.getBoundingClientRect()
1087
- const left = (-state.canvasCamera.x - VIEWPORT_MARGIN) / state.zoom
1088
- const right = (bounds.width - state.canvasCamera.x + VIEWPORT_MARGIN) / state.zoom
1089
- const top = (-state.canvasCamera.y - VIEWPORT_MARGIN) / state.zoom
1090
- const bottom = (bounds.height - state.canvasCamera.y + VIEWPORT_MARGIN) / state.zoom
1091
- const visible = new Set()
1092
- for (const card of cards) {
1093
- const { x, y } = card.position
1094
- if (x + CARD_WIDTH < left || x > right || y + CARD_HEIGHT < top || y > bottom) continue
1095
- visible.add(card.id)
1394
+ if (!(viewport instanceof HTMLElement)) return null
1395
+ const width = viewport.clientWidth
1396
+ const height = viewport.clientHeight
1397
+ if (width === 0 || height === 0) return null
1398
+ return { left: -state.canvasCamera.x / state.zoom - margin,
1399
+ right: (width - state.canvasCamera.x) / state.zoom + margin,
1400
+ top: -state.canvasCamera.y / state.zoom - margin,
1401
+ bottom: (height - state.canvasCamera.y) / state.zoom + margin }
1402
+ }
1403
+
1404
+ function cardIntersects(card, bounds) {
1405
+ return card.position.x + CARD_WIDTH >= bounds.left && card.position.x <= bounds.right
1406
+ && card.position.y + CARD_HEIGHT >= bounds.top && card.position.y <= bounds.bottom
1407
+ }
1408
+
1409
+ // Throttle region planning independently of the camera's animation frame.
1410
+ // Each pending plan reads the latest camera, so rapid panning drops old work.
1411
+ function syncCanvasViewport({ immediate = false } = {}) {
1412
+ if (state.mode !== 'canvas' || !state.mapVisible || document.hidden || !canvasGraphCache) return
1413
+ if (immediate) {
1414
+ window.clearTimeout(regionTimer)
1415
+ regionTimer = 0
1416
+ planCanvasRegion()
1417
+ } else if (regionTimer === 0) {
1418
+ regionTimer = window.setTimeout(() => { regionTimer = 0; planCanvasRegion() }, REGION_TICK_MS)
1419
+ }
1420
+ }
1421
+
1422
+ function planCanvasRegion() {
1423
+ if (state.mode !== 'canvas' || !state.mapVisible || document.hidden || state.dragging) return
1424
+ const bounds = canvasWorldBounds()
1425
+ const layer = document.querySelector('.cards-layer')
1426
+ if (!bounds || !(layer instanceof HTMLElement) || !canvasGraphCache) return
1427
+ const planKey = [canvasGraphCache.revision, state.zoom < OVERVIEW_ZOOM, state.selectedCardId, state.activeId,
1428
+ state.inspectorCardId, state.canvasGesture, state.draft?.kind, state.draft?.anchorId,
1429
+ ...['left', 'right', 'top', 'bottom'].map(side => Math.floor(bounds[side] / 128))].join('|')
1430
+ if (regionView?.planKey === planKey && regionDirtyCards.size === 0) {
1431
+ hydrateBodies()
1432
+ updateRegionStatus()
1433
+ return
1434
+ }
1435
+ window.clearTimeout(regionWorkTimer)
1436
+ regionWorkTimer = 0
1437
+ const generation = ++regionGeneration
1438
+ const expanded = { left: bounds.left - REGION_MARGIN, right: bounds.right + REGION_MARGIN,
1439
+ top: bounds.top - REGION_MARGIN, bottom: bounds.bottom + REGION_MARGIN }
1440
+ const nearby = canvasGraphCache.index.query(expanded)
1441
+ const cx = (bounds.left + bounds.right) / 2
1442
+ const cy = (bounds.top + bounds.bottom) / 2
1443
+ const distance = card => (card.position.x + CARD_WIDTH / 2 - cx) ** 2 + (card.position.y + CARD_HEIGHT / 2 - cy) ** 2
1444
+ nearby.sort((a, b) => Number(cardIntersects(b, bounds)) - Number(cardIntersects(a, bounds)) || distance(a) - distance(b))
1445
+ const overview = state.zoom < OVERVIEW_ZOOM
1446
+ const limit = overview ? MAP_OVERVIEW_CARDS : MAP_DETAIL_CARDS
1447
+ const wanted = nearby.slice(0, limit)
1448
+ const ids = new Set(wanted.map(card => card.id))
1449
+ regionView = { planKey, overview, cards: wanted, ids, bounds, total: nearby.length, queue: [], prefetch: [] }
1450
+ for (const [id, element] of regionElements) {
1451
+ if (!element.isConnected || !ids.has(id)) {
1452
+ element.remove()
1453
+ regionElements.delete(id)
1454
+ state.mountedCardIds.delete(id)
1455
+ regionDirtyCards.delete(id)
1456
+ }
1457
+ }
1458
+ // Reuse live DOM after shell renders and discard references from old views.
1459
+ for (const element of layer.querySelectorAll('.thread-card[data-thread]')) {
1460
+ const id = element.dataset.cardId
1461
+ if (!ids.has(id)) { element.remove(); state.mountedCardIds.delete(id); continue }
1462
+ regionElements.set(id, element)
1463
+ state.mountedCardIds.add(id)
1464
+ }
1465
+ for (const card of wanted) {
1466
+ const element = regionElements.get(card.id)
1467
+ const stamp = `${canvasGraphCache.revision}:${overview}:${card.id === state.selectedCardId}`
1468
+ if (!element || element.dataset.regionStamp !== stamp || regionDirtyCards.has(card.id)) regionView.queue.push(card.id)
1096
1469
  }
1097
- return visible
1470
+ if (!overview && !state.canvasGesture) {
1471
+ const prefetchBounds = { left: bounds.left - REGION_PREFETCH_MARGIN, right: bounds.right + REGION_PREFETCH_MARGIN,
1472
+ top: bounds.top - REGION_PREFETCH_MARGIN, bottom: bounds.bottom + REGION_PREFETCH_MARGIN }
1473
+ regionView.prefetch = canvasGraphCache.index.query(prefetchBounds).filter(card => !ids.has(card.id))
1474
+ .sort((a, b) => distance(a) - distance(b)).slice(0, 12)
1475
+ }
1476
+ refreshRegionConnectors()
1477
+ hydrateBodies()
1478
+ updateRegionStatus()
1479
+ regionWorkTimer = window.setTimeout(() => mountRegionBatch(generation), 0)
1480
+ }
1481
+
1482
+ function patchElementHtml(element, html) {
1483
+ const template = document.createElement('template')
1484
+ template.innerHTML = html
1485
+ const next = template.content.firstElementChild
1486
+ morphFrozenRoot = morphFrozenRootOfDocument()
1487
+ try { return morphNode(element, next) } finally { morphFrozenRoot = null }
1098
1488
  }
1099
1489
 
1100
- // Incrementally mount cards entering the viewport and unmount cards leaving
1101
- // it, without rebuilding the canvas. Called after pan/zoom/focus camera moves.
1102
- function syncCanvasViewport() {
1103
- if (state.mode !== 'canvas' || state.canvasCards === undefined) return
1490
+ function mountRegionBatch(generation) {
1491
+ if (generation !== regionGeneration || !regionView || state.mode !== 'canvas' || !state.mapVisible || document.hidden) return
1492
+ regionWorkTimer = 0
1104
1493
  const layer = document.querySelector('.cards-layer')
1105
1494
  if (!(layer instanceof HTMLElement)) return
1106
- const visible = visibleCardIds(state.canvasCards)
1107
- for (const cardId of [...state.mountedCardIds]) {
1108
- if (visible.has(cardId)) continue
1109
- const element = layer.querySelector(`[data-card-id="${selectorValue(cardId)}"]`)
1110
- if (element instanceof HTMLElement) element.remove()
1111
- state.mountedCardIds.delete(cardId)
1112
- }
1113
- for (const card of state.canvasCards) {
1114
- if (!visible.has(card.id) || state.mountedCardIds.has(card.id)) continue
1115
- const wrapper = document.createElement('div')
1116
- wrapper.innerHTML = conversationCard(card, state.canvasGraph)
1117
- const element = wrapper.firstElementChild
1118
- if (element instanceof HTMLElement) {
1495
+ const started = performance.now()
1496
+ let count = 0
1497
+ while (regionView.queue.length > 0 && count < (regionView.overview ? 20 : 6)) {
1498
+ if (count > 0 && performance.now() - started >= 6) break
1499
+ const id = regionView.queue.shift()
1500
+ const card = state.canvasCardsById.get(id)
1501
+ if (!card) continue
1502
+ const html = conversationCard(card, state.canvasGraph, regionView.overview)
1503
+ let element = regionElements.get(id)
1504
+ if (element?.isConnected) {
1505
+ const scroll = element.querySelector('.thread-answer')?.scrollTop ?? 0
1506
+ element = patchElementHtml(element, html)
1507
+ const answer = element.querySelector('.thread-answer')
1508
+ if (answer) answer.scrollTop = scroll
1509
+ } else {
1510
+ const template = document.createElement('template')
1511
+ template.innerHTML = html
1512
+ element = template.content.firstElementChild
1119
1513
  layer.appendChild(element)
1120
- const handle = element.querySelector('[data-drag-card]')
1121
- if (handle instanceof HTMLElement) bindDragHandle(handle)
1122
1514
  }
1123
- state.mountedCardIds.add(card.id)
1515
+ element.dataset.regionStamp = `${canvasGraphCache.revision}:${regionView.overview}:${card.id === state.selectedCardId}`
1516
+ regionElements.set(id, element)
1517
+ state.mountedCardIds.add(id)
1518
+ regionDirtyCards.delete(id)
1519
+ const handle = element.querySelector('[data-drag-card]')
1520
+ if (handle instanceof HTMLElement) bindDragHandle(handle)
1521
+ count++
1522
+ }
1523
+ updateRegionStatus()
1524
+ if (regionView.queue.length > 0) regionWorkTimer = window.setTimeout(() => mountRegionBatch(generation), 16)
1525
+ }
1526
+
1527
+ function refreshRegionConnectors() {
1528
+ const svg = document.querySelector('.connectors')
1529
+ if (!svg || !regionView) return
1530
+ const placement = draftPlacement(state.canvasCards)
1531
+ const linksKey = [canvasGraphCache.revision, state.activeId, ...regionView.ids,
1532
+ placement?.parent.position.x, placement?.parent.position.y, placement?.position.x, placement?.position.y].join('|')
1533
+ if (svg.dataset.regionLinksKey === linksKey) return
1534
+ svg.dataset.regionLinksKey = linksKey
1535
+ const edges = new Set()
1536
+ const links = []
1537
+ const add = id => {
1538
+ if (edges.has(id) || links.length >= 640) return
1539
+ edges.add(id)
1540
+ const card = state.canvasCardsById.get(id)
1541
+ const parent = state.canvasCardsById.get(card?.parentId)
1542
+ if (!card || !parent) return
1543
+ const active = card.dshThreadId === state.activeId && parent.dshThreadId === state.activeId
1544
+ links.push(`<path data-morph-key="${escapeHtml(card.id)}" class="${active ? 'active-connector' : ''}" data-from="${escapeHtml(parent.id)}" data-to="${escapeHtml(card.id)}" d="${connectorPath(parent.position, card.position)}"></path>`)
1545
+ }
1546
+ for (const card of regionView.cards) {
1547
+ add(card.id)
1548
+ for (const child of canvasGraphCache.children.get(card.id) ?? []) {
1549
+ if (regionView.ids.has(child)) add(child)
1550
+ if (links.length >= 640) break
1551
+ }
1552
+ }
1553
+ if (placement) links.push(`<path class="draft-connector" data-from="${escapeHtml(placement.parent.id)}" data-to="draft" d="${connectorPath(placement.parent.position, placement.position)}"></path>`)
1554
+ // SVG parsing needs the SVG namespace, which a bare HTML template lacks.
1555
+ const template = document.createElement('template')
1556
+ template.innerHTML = `<svg>${links.join('')}</svg>`
1557
+ morphChildren(svg, template.content.firstElementChild)
1558
+ cacheCardConnectors()
1559
+ }
1560
+
1561
+ function updateRegionStatus() {
1562
+ const status = document.querySelector('.region-status')
1563
+ if (!status || !regionView) return
1564
+ let pending = 0
1565
+ let unavailable = 0
1566
+ for (const entry of bodyLoader.wanted.values()) {
1567
+ if (entry.priority === 2 || bodyCache.get(entry.threadId, entry.seq, entry.revision) !== undefined) continue
1568
+ if (bodyLoader.unavailable(entry.threadId, entry.seq, entry.revision)) unavailable++
1569
+ else pending++
1570
+ }
1571
+ const mounting = regionView.queue.length
1572
+ const limited = regionView.total > regionView.cards.length
1573
+ const loading = mounting > 0 || pending > 0
1574
+ status.hidden = !loading && !unavailable && !limited && !regionView.overview
1575
+ status.classList.toggle('is-loading', loading)
1576
+ status.querySelector('span').textContent = loading ? `正在加载此区域 · ${mounting ? `${mounting} 张卡片` : `${pending} 条正文`}`
1577
+ : unavailable ? '部分正文暂未加载,当前显示预览'
1578
+ : limited ? `当前区域显示 ${regionView.cards.length} 张卡片,请放大查看`
1579
+ : '概览模式 · 点击卡片查看完整回答'
1580
+ status.querySelector('button').hidden = unavailable === 0
1581
+ }
1582
+
1583
+ function syncCanvasDraft() {
1584
+ const layer = document.querySelector('.cards-layer')
1585
+ if (!layer) return
1586
+ const previous = layer.querySelector('.draft-card')
1587
+ const html = draftCard(state.canvasCards ?? [])
1588
+ if (!html) { previous?.remove(); return }
1589
+ if (previous) patchElementHtml(previous, html)
1590
+ else {
1591
+ const template = document.createElement('template')
1592
+ template.innerHTML = html
1593
+ layer.appendChild(template.content)
1124
1594
  }
1125
1595
  }
1126
1596
 
1597
+ function canvasScopeControls(threads) {
1598
+ const focused = state.focusedThreadId !== null
1599
+ const canFocus = threads.some(thread => thread.id === state.activeId)
1600
+ return `<div class="canvas-scope-controls" role="group" aria-label="地图显示范围"><button type="button" data-action="show-workspace" aria-pressed="${!focused}" ${state.draft !== null ? 'disabled' : ''}>全工作区</button><button type="button" data-action="focus-thread" aria-pressed="${focused}" title="只显示选中会话及其派生分支" ${!canFocus || state.draft !== null ? 'disabled' : ''}>聚焦会话</button></div>`
1601
+ }
1602
+
1127
1603
  function renderCanvas() {
1128
1604
  const threads = visibleThreads(state.workspace?.threads ?? [])
1129
- if (threads.length === 0 && state.draft?.kind !== 'new') return `<section class="empty-canvas"><strong>当前工作目录还没有 DSH 对话。</strong><p>点击新会话,在画布中输入第一条消息。</p><div><button class="primary" type="button" data-action="create-session">新建会话</button></div></section>`
1130
- const allCards = conversationCards(threads)
1131
- const graph = conversationGraphView(allCards)
1132
- const cards = graph.cards
1133
- state.canvasCards = cards
1134
- state.canvasCardsById = new Map(cards.map(card => [card.id, card]))
1135
- state.canvasGraph = graph
1136
- if (state.inspectorCardId !== null && !state.canvasCardsById.has(state.inspectorCardId)) {
1605
+ if (threads.length === 0 && state.draft?.kind !== 'new') {
1606
+ clearViewCaches()
1607
+ state.inspectorCardId = null
1608
+ state.inspectorOpening = false
1609
+ return `<section class="empty-canvas"><strong>当前工作目录还没有 DSH 对话。</strong><p>点击新会话,在画布中输入第一条消息。</p><div><button class="primary" type="button" data-action="create-session">新建会话</button></div></section>`
1610
+ }
1611
+ ensureCanvasGraph(threads)
1612
+ const cards = state.canvasCards
1613
+ if (state.inspectorCardId !== null && !canvasGraphCache.scopeCardIds.has(state.inspectorCardId)) {
1137
1614
  state.inspectorCardId = null
1138
1615
  state.inspectorOpening = false
1139
1616
  }
@@ -1144,11 +1621,11 @@ function renderCanvas() {
1144
1621
  // center the focused card once the DOM is mounted (render tail).
1145
1622
  state.canvasNeedsCenter = true
1146
1623
  }
1147
- const visible = visibleCardIds(cards)
1148
- state.mountedCardIds = new Set(visible)
1149
- const mounted = cards.filter(card => visible.has(card.id))
1150
- const inspector = state.inspectorCardId === null ? '' : renderCardInspector(state.canvasCardsById.get(state.inspectorCardId))
1151
- return `<section class="canvas-view"><div class="canvas-viewport"><div class="canvas-content" style="transform:translate(${state.canvasCamera.x}px, ${state.canvasCamera.y}px) scale(${state.zoom})"><svg class="connectors">${canvasConnectors(cards)}</svg><div class="cards-layer">${mounted.map(card => conversationCard(card, graph)).join('')}${draftCard(cards)}</div></div></div>${inspector}</section>`
1624
+ const inspector = state.inspectorCardId === null ? '' : renderCardInspector(canvasGraphCache.allById.get(state.inspectorCardId))
1625
+ const focusedThread = threads.find(thread => thread.id === state.focusedThreadId)
1626
+ const focusLabel = focusedThread === undefined ? '' : `<div class="canvas-focus-label" title="${escapeHtml(threadListTitle(focusedThread))}"><strong>聚焦:${escapeHtml(threadListTitle(focusedThread))}</strong><span>含派生分支</span></div>`
1627
+ const focusEmpty = focusedThread !== undefined && cards.length === 0 ? '<div class="canvas-focus-empty">该会话及其分支还没有可显示的对话。</div>' : ''
1628
+ return `<section class="canvas-view" data-morph-key="canvas"><div class="canvas-viewport"><div class="canvas-content" style="transform:translate(${state.canvasCamera.x}px, ${state.canvasCamera.y}px) scale(${state.zoom})"><svg class="connectors" data-morph-key="links:${escapeHtml(state.workspace?.id ?? '')}" data-region-layer></svg><div class="cards-layer" data-morph-key="cards:${escapeHtml(state.workspace?.id ?? '')}" data-region-layer></div></div></div>${focusLabel}${focusEmpty}<div class="region-status" role="status" hidden><i aria-hidden="true"></i><span></span><button type="button" data-action="retry-bodies" hidden>重试</button></div>${inspector}</section>`
1152
1629
  }
1153
1630
 
1154
1631
  function isProcessMessage(message) {
@@ -1160,6 +1637,13 @@ function processSummary(text) {
1160
1637
  return text.replace(/\s+/g, ' ').trim().slice(0, 140) || '工具调用记录'
1161
1638
  }
1162
1639
 
1640
+ function bodyNotice(thread, message) {
1641
+ if (bodyLoader.unavailable(thread.id, message.sourceSeq, bodyRevision(message))) return '<p class="body-notice">当前显示预览。<button type="button" data-action="retry-bodies">重新加载正文</button></p>'
1642
+ if (message.previewOnly && !message.hydrated) return '<p class="body-notice">正在加载正文,当前显示预览。</p>'
1643
+ if ((message.hydrated && message.truncated) || message.processTruncated || message.process?.length > 12) return '<p class="body-notice">内容较长,已显示部分正文或工具记录。请在 DSH 中查看完整内容。</p>'
1644
+ return ''
1645
+ }
1646
+
1163
1647
  function threadMessage(thread, message) {
1164
1648
  const isUser = message.kind === 'user'
1165
1649
  const label = isUser ? '你' : message.kind === 'assistant' ? 'DSH' : message.kind === 'error' ? '错误' : '记录'
@@ -1172,7 +1656,7 @@ function threadMessage(thread, message) {
1172
1656
  const fold = collapsible ? `<button class="message-fold" data-action="toggle-message" data-message="${escapeHtml(messageId)}" aria-label="${expanded ? '收起过程记录' : '展开过程记录'}" title="${expanded ? '收起' : '展开'}"><svg viewBox="0 0 16 16" aria-hidden="true"><path d="m6 3.5 4.5 4.5L6 12.5"/></svg></button>` : ''
1173
1657
  const process = Array.isArray(message.process) && message.process.length > 0 ? message.process : null
1174
1658
  const body = message.pending && message.text === '' ? '<p class="message-streaming"><span class="streaming-dot"></span>正在回复</p>'
1175
- : `${collapsible && !expanded ? `<p class="message-summary">${escapeHtml(processSummary(message.text))}</p>` : renderMarkdown(message.text)}${message.pending ? '<p class="message-streaming"><span class="streaming-dot"></span>正在回复</p>' : ''}${process === null ? '' : processRecords(process, messageId)}`
1659
+ : `${collapsible && !expanded ? `<p class="message-summary">${escapeHtml(processSummary(message.text))}</p>` : renderMarkdown(message.text, !message.pending)}${message.pending ? '<p class="message-streaming"><span class="streaming-dot"></span>正在回复</p>' : ''}${process === null ? '' : processRecords(process, messageId)}${bodyNotice(thread, message)}`
1176
1660
  const avatar = isUser ? '' : '<span class="message-avatar" aria-hidden="true"></span>'
1177
1661
  return `<article class="message message-${message.kind}${message.pending ? ' message-pending' : ''}${collapsible ? ' message-collapsible' : ''}${expanded ? ' expanded' : ''}" data-message-seq="${Number.isInteger(message.sourceSeq) ? message.sourceSeq : ''}"><header>${avatar}<span class="message-role">${label}</span><time>${formatTime(message.at)}</time>${branch}${fold}</header><div class="message-body">${body}</div></article>`
1178
1662
  }
@@ -1195,25 +1679,27 @@ function processState(entry) {
1195
1679
  function processRecords(process, messageId) {
1196
1680
  const key = `${messageId}:process`
1197
1681
  const expanded = state.expandedMessageIds.has(key)
1198
- const entries = process.map((entry, index) => {
1682
+ const entries = expanded ? process.slice(0, 12).map((entry, index) => {
1199
1683
  const entryKey = `${key}:${index}`
1200
1684
  const entryExpanded = state.expandedMessageIds.has(entryKey)
1201
1685
  const state_ = processState(entry)
1202
1686
  const status = state_ === 'failed' ? '失败' : state_ === 'pending' ? '等待结果' : '完成'
1203
1687
  const statusClass = state_ === 'failed' ? ' process-status-error' : state_ === 'pending' ? ' process-status-pending' : ' process-status-done'
1204
- const argumentsHtml = typeof entry.arguments === 'string' && entry.arguments !== '' ? `<pre class="process-args">${escapeHtml(entry.arguments)}</pre>` : ''
1205
- const outcomeHtml = state_ === 'failed' && typeof entry.error === 'string' && entry.error !== ''
1206
- ? `<pre class="process-error">${escapeHtml(entry.error)}</pre>`
1207
- : typeof entry.result === 'string' && entry.result !== '' ? `<pre class="process-result">${escapeHtml(entry.result)}</pre>` : ''
1208
- return `<div class="process-entry${entryExpanded ? ' expanded' : ''}"><button class="process-entry-fold" data-action="toggle-message" data-message="${escapeHtml(entryKey)}"><span class="process-entry-name">${escapeHtml(entry.name)}</span><span class="process-status${statusClass}">${status}</span></button>${entryExpanded ? `<div class="process-entry-body">${argumentsHtml}${outcomeHtml}</div>` : ''}</div>`
1209
- }).join('')
1688
+ const argumentsHtml = entryExpanded && typeof entry.arguments === 'string' && entry.arguments !== '' ? `<pre class="process-args">${escapeHtml(entry.arguments.slice(0, 8192))}</pre>` : ''
1689
+ const outcomeHtml = !entryExpanded ? '' : state_ === 'failed' && typeof entry.error === 'string' && entry.error !== ''
1690
+ ? `<pre class="process-error">${escapeHtml(entry.error.slice(0, 8192))}</pre>`
1691
+ : typeof entry.result === 'string' && entry.result !== '' ? `<pre class="process-result">${escapeHtml(entry.result.slice(0, 8192))}</pre>` : ''
1692
+ const truncated = entry.truncated || ['arguments', 'result', 'error'].some(field => typeof entry[field] === 'string' && entry[field].length > 8192)
1693
+ return `<div class="process-entry${entryExpanded ? ' expanded' : ''}"><button class="process-entry-fold" data-action="toggle-message" data-message="${escapeHtml(entryKey)}"><span class="process-entry-name">${escapeHtml(entry.name)}</span><span class="process-status${statusClass}">${status}</span></button>${entryExpanded ? `<div class="process-entry-body">${argumentsHtml}${outcomeHtml}${truncated ? '<p class="body-notice">工具内容已截断,请在 DSH 中查看完整记录。</p>' : ''}</div>` : ''}</div>`
1694
+ }).join('') : ''
1210
1695
  return `<section class="process-records${expanded ? ' expanded' : ''}"><button class="process-records-fold" data-action="toggle-message" data-message="${escapeHtml(key)}"><span>${expanded ? '收起过程记录' : '过程记录'}</span><span class="process-count">${process.length}</span></button>${expanded ? entries : ''}</section>`
1211
1696
  }
1212
1697
 
1213
1698
  function messagesForCard(card) {
1214
- const thread = state.workspace?.threads.find(item => item.id === card.dshThreadId)
1699
+ const thread = canvasGraphCache?.threadById.get(card.dshThreadId) ?? state.workspace?.threads.find(item => item.id === card.dshThreadId)
1215
1700
  if (thread === undefined) return { thread: null, messages: [] }
1216
- const messages = messagesFor(thread)
1701
+ if (card.turnMessages) return { thread, messages: card.turnMessages.map(message => hydratedMessage(thread, message)) }
1702
+ const messages = messagesFor(thread, false)
1217
1703
  let turnIndex = -1
1218
1704
  let start = -1
1219
1705
  for (let index = 0; index < messages.length; index++) {
@@ -1226,14 +1712,15 @@ function messagesForCard(card) {
1226
1712
  }
1227
1713
  if (start === -1) return { thread, messages: [] }
1228
1714
  const end = messages.findIndex((message, index) => index > start && message.kind === 'user')
1229
- return { thread, messages: messages.slice(start, end === -1 ? undefined : end) }
1715
+ return { thread, messages: messages.slice(start, end === -1 ? undefined : end).map(message => hydratedMessage(thread, message)) }
1230
1716
  }
1231
1717
 
1232
1718
  function inspectorProcessEntries(messages) {
1233
1719
  const entries = []
1234
1720
  for (const message of messages) {
1721
+ if (entries.length >= 12) break
1235
1722
  if (Array.isArray(message.process)) {
1236
- entries.push(...message.process.map(entry => ({ ...entry })))
1723
+ entries.push(...message.process.slice(0, 12 - entries.length).map(entry => ({ ...entry })))
1237
1724
  continue
1238
1725
  }
1239
1726
  if (message.kind === 'tool') {
@@ -1253,12 +1740,13 @@ function inspectorProcessEntries(messages) {
1253
1740
 
1254
1741
  function renderCardInspector(card) {
1255
1742
  if (card === undefined) return ''
1743
+ card = hydratedCard(card)
1256
1744
  const { thread, messages } = messagesForCard(card)
1257
1745
  if (thread === null) return ''
1258
- const process = inspectorProcessEntries(messages)
1746
+ const process = inspectorProcessEntries(messages).slice(0, 12)
1259
1747
  const answer = card.answer === null
1260
1748
  ? card.error === null ? '<p class="card-inspector-pending">等待助手回复</p>' : ''
1261
- : `<article class="card-inspector-answer">${renderMarkdown(card.answer.text)}${card.answer.pending ? '<p class="card-inspector-pending">正在回复</p>' : ''}</article>`
1749
+ : `<article class="card-inspector-answer">${renderMarkdown(card.answer.text, !card.answer.pending)}${card.answer.pending ? '<p class="card-inspector-pending">正在回复</p>' : ''}</article>`
1262
1750
  const error = card.error === null ? '' : `<section class="card-inspector-error" role="alert"><strong>本轮未完成</strong><p>${escapeHtml(card.error.text)}</p></section>`
1263
1751
  const processRecordsHtml = process.length === 0 ? '' : processRecords(process, `${thread.id}:${card.id}:inspector`)
1264
1752
  const continueAction = card.canContinue === true ? `<button type="button" data-action="open-continue" data-thread="${thread.id}" data-card="${escapeHtml(card.id)}"><svg aria-hidden="true" viewBox="0 0 16 16"><path d="M2.5 3.5h11v7h-6l-3.5 2.5v-2.5h-1.5Z"/><path d="M8 5.5v3M6.5 7h3"/></svg>继续追问</button>` : ''
@@ -1266,19 +1754,62 @@ function renderCardInspector(card) {
1266
1754
  ? `<button type="button" data-action="open-branch" data-thread="${thread.id}" data-card="${escapeHtml(card.id)}" data-seq="${card.answer.sourceSeq}"><svg aria-hidden="true" viewBox="0 0 16 16"><circle cx="4" cy="3.5" r="1.5"/><circle cx="12" cy="3.5" r="1.5"/><circle cx="12" cy="12.5" r="1.5"/><path d="M5.5 3.5h2A2.5 2.5 0 0 1 10 6v5"/></svg>创建分支</button>`
1267
1755
  : ''
1268
1756
  const openDshAction = `<button class="primary" type="button" data-action="open-dsh" data-thread="${thread.id}" data-seq="${Number.isInteger(card.answer?.sourceSeq) ? card.answer.sourceSeq : ''}"><svg aria-hidden="true" viewBox="0 0 16 16"><path d="M7 3.5H4.5A1.5 1.5 0 0 0 3 5v6.5A1.5 1.5 0 0 0 4.5 13H11a1.5 1.5 0 0 0 1.5-1.5V9"/><path d="M9.5 3.5h3v3M12.4 3.6 7.5 8.5"/></svg>在 DSH 中打开</button>`
1269
- return `<aside class="card-inspector${state.inspectorOpening ? ' is-opening' : ''}" aria-label="卡片详情" data-inspector-card="${escapeHtml(card.id)}"><header class="card-inspector-head"><div><div class="card-inspector-meta"><span>第 ${card.turnIndex + 1} 轮</span>${card.error === null ? '' : '<span class="card-inspector-error-status">失败</span>'}${process.length > 0 ? `<span>工具 ${process.length}</span>` : ''}</div><h2 title="${escapeHtml(card.question)}">${escapeHtml(card.question)}</h2></div><button class="card-inspector-close" type="button" data-action="close-card-inspector" aria-label="关闭卡片详情" title="关闭"><svg aria-hidden="true" viewBox="0 0 16 16"><path d="m4.5 4.5 7 7m0-7-7 7"/></svg></button></header><div class="card-inspector-scroll">${error}${answer}${processRecordsHtml}</div><footer class="card-inspector-actions">${continueAction}${branch}${openDshAction}</footer></aside>`
1757
+ const notices = messages.map(message => bodyNotice(thread, message)).filter(Boolean)
1758
+ return `<aside class="card-inspector${state.inspectorOpening ? ' is-opening' : ''}" aria-label="卡片详情" data-inspector-card="${escapeHtml(card.id)}"><header class="card-inspector-head"><div><div class="card-inspector-meta"><span>第 ${card.turnIndex + 1} 轮</span>${card.error === null ? '' : '<span class="card-inspector-error-status">失败</span>'}${process.length > 0 ? `<span>工具 ${process.length}</span>` : ''}</div><h2 title="${escapeHtml(card.question)}">${escapeHtml(card.question)}</h2></div><button class="card-inspector-close" type="button" data-action="close-card-inspector" aria-label="关闭卡片详情" title="关闭"><svg aria-hidden="true" viewBox="0 0 16 16"><path d="m4.5 4.5 7 7m0-7-7 7"/></svg></button></header><div class="card-inspector-scroll">${error}${answer}${processRecordsHtml}${notices[0] ?? ''}</div><footer class="card-inspector-actions">${continueAction}${branch}${openDshAction}</footer></aside>`
1759
+ }
1760
+
1761
+ function detailPage(thread) {
1762
+ const all = messagesFor(thread, false)
1763
+ const lastStart = Math.max(0, Math.floor((all.length - 1) / DETAIL_PAGE_MESSAGES) * DETAIL_PAGE_MESSAGES)
1764
+ const target = state.detailTargetCardId
1765
+ if (target?.startsWith(`${thread.id}:turn:`)) {
1766
+ const seq = Number(target.slice(target.lastIndexOf(':') + 1))
1767
+ const index = all.findIndex(message => message.sourceSeq === seq)
1768
+ if (index !== -1) state.detailPageByThread.set(thread.id, Math.floor(index / DETAIL_PAGE_MESSAGES) * DETAIL_PAGE_MESSAGES)
1769
+ }
1770
+ const saved = state.detailPageByThread.get(thread.id)
1771
+ const start = saved === null || saved === undefined ? lastStart : Math.min(saved, lastStart)
1772
+ return { messages: all.slice(start, start + DETAIL_PAGE_MESSAGES).map(message => hydratedMessage(thread, message)), start, total: all.length, lastStart }
1773
+ }
1774
+
1775
+ function changeDetailPage(thread, direction) {
1776
+ const page = detailPage(thread)
1777
+ const start = Math.max(0, Math.min(page.lastStart, page.start + direction * DETAIL_PAGE_MESSAGES))
1778
+ state.detailPageByThread.set(thread.id, start === page.lastStart ? null : start)
1779
+ state.detailTargetCardId = null
1780
+ state.detailScrollByThread.set(thread.id, 0)
1781
+ state.detailThreadId = null
1782
+ render()
1270
1783
  }
1271
1784
 
1272
1785
  function renderThread() {
1273
1786
  const thread = currentThread()
1274
1787
  if (thread === null) return renderCanvas()
1275
- const messages = messagesFor(thread)
1788
+ const page = detailPage(thread)
1789
+ const messages = page.messages
1276
1790
  const waiting = state.pendingReplies.has(thread.dshSessionId)
1277
1791
  const latestAssistantSeq = [...messages].reverse().find(message => Number.isInteger(message.sourceSeq))?.sourceSeq
1278
- return `<section class="detail-view"><header class="detail-head"><div class="detail-head-title"><div class="detail-head-meta"><span class="detail-badge">${thread.parentId === null ? '会话' : '分支'}</span>${thread.dshSessionTitle ?? thread.title ? `<span class="detail-subtitle">${escapeHtml(thread.dshSessionTitle ?? thread.title)}</span>` : ''}</div><h1>${escapeHtml(questionFor(thread))}</h1></div><div class="detail-head-actions"><button data-action="open-dsh" data-thread="${thread.id}" data-seq="${Number.isInteger(latestAssistantSeq) ? latestAssistantSeq : ''}" title="在原生对话中打开此会话">在 DSH 中打开</button><button data-action="open-branch" data-thread="${thread.id}" title="基于最新回答创建分支">创建分支</button><button class="primary" data-action="show-canvas">返回画布</button></div></header><div class="detail-scroll">${messages.map(message => threadMessage(thread, message)).join('') || '<div class="note-empty">等待这条会话的第一条消息。</div>'}</div><form class="message-composer" data-compose="${thread.id}"><textarea maxlength="4000" placeholder="继续当前会话…" ${waiting ? 'disabled' : ''}></textarea><button class="primary" type="submit" ${waiting ? 'disabled' : ''}>${waiting ? '等待回复' : '发送'}</button></form></section>`
1792
+ const pager = `<nav class="detail-pages" aria-label="会话历史翻页"><button data-action="detail-prev" data-thread="${thread.id}" ${page.start === 0 ? 'disabled' : ''}>上一页</button><span>${page.total === 0 ? '暂无消息' : `${page.start + 1}–${page.start + messages.length} / ${page.total} 条消息`}</span><button data-action="detail-next" data-thread="${thread.id}" ${page.start >= page.lastStart ? 'disabled' : ''}>下一页</button></nav>`
1793
+ return `<section class="detail-view">
1794
+ <header class="detail-head">
1795
+ <div class="detail-head-title">
1796
+ <div class="detail-head-meta"><span class="detail-badge">${thread.parentId === null ? '会话' : '分支'}</span>${thread.dshSessionTitle ?? thread.title ? `<span class="detail-subtitle">${escapeHtml(thread.dshSessionTitle ?? thread.title)}</span>` : ''}</div>
1797
+ <h1 title="${escapeHtml(questionFor(thread))}">${escapeHtml(questionFor(thread))}</h1>
1798
+ </div>
1799
+ <div class="detail-head-actions">
1800
+ <button type="button" data-action="open-dsh" data-thread="${thread.id}" data-seq="${Number.isInteger(latestAssistantSeq) ? latestAssistantSeq : ''}" title="在原生对话中打开此会话"><svg aria-hidden="true" viewBox="0 0 16 16"><path d="M7 3.5H4.5A1.5 1.5 0 0 0 3 5v6.5A1.5 1.5 0 0 0 4.5 13H11a1.5 1.5 0 0 0 1.5-1.5V9"/><path d="M9.5 3.5h3v3M12.4 3.6 7.5 8.5"/></svg>在 DSH 中打开</button>
1801
+ <button type="button" data-action="open-branch" data-thread="${thread.id}" title="基于最新回答创建分支"><svg aria-hidden="true" viewBox="0 0 16 16"><circle cx="4" cy="3.5" r="1.5"/><circle cx="12" cy="3.5" r="1.5"/><circle cx="12" cy="12.5" r="1.5"/><path d="M5.5 3.5h2A2.5 2.5 0 0 1 10 6v5"/></svg>创建分支</button>
1802
+ <button type="button" class="primary" data-action="show-canvas"><svg aria-hidden="true" viewBox="0 0 16 16"><path d="m6.5 3.5-4 4.5 4 4.5M3 8h10"/></svg>返回画布</button>
1803
+ </div>
1804
+ </header>
1805
+ ${pager}
1806
+ <div class="detail-scroll">${messages.map(message => threadMessage(thread, message)).join('') || '<div class="note-empty">等待这条会话的第一条消息。</div>'}</div>
1807
+ <form class="message-composer" data-compose="${thread.id}"><textarea maxlength="4000" aria-label="继续当前会话" placeholder="继续当前会话…" ${waiting ? 'disabled' : ''}></textarea><button class="primary" type="submit" ${waiting ? 'disabled' : ''}>${waiting ? '等待回复' : '发送'}</button></form>
1808
+ </section>`
1279
1809
  }
1280
1810
 
1281
1811
  function render() {
1812
+ if (!state.mapVisible || document.hidden) return
1282
1813
  // Remember the departing thread's scroll position per thread id, so
1283
1814
  // switching sessions restores each conversation's own place instead of
1284
1815
  // smearing one session's position onto another.
@@ -1310,17 +1841,25 @@ function render() {
1310
1841
  const view = state.mode === 'thread' ? renderThread() : renderCanvas()
1311
1842
  const choices = workspaceChoices()
1312
1843
  const selectedWorkspaceId = state.selectedDshWorkspaceId ?? workspace?.id
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>` : ''
1844
+ const canvasControls = state.mode === 'canvas' && (threads.length > 0 || state.draft?.kind === 'new') ? `<div class="canvas-controls">${canvasScopeControls(threads)}<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 class="canvas-zoom-label">${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>` : ''
1314
1845
  const detailAvailable = currentThread() !== null
1315
1846
  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>`
1316
1847
  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>`)
1848
+ if (state.mode === 'canvas' && document.querySelector('.cards-layer')) {
1849
+ syncCanvasDraft()
1850
+ syncCanvasViewport({ immediate: true })
1851
+ } else {
1852
+ cancelRegionWork()
1853
+ regionView = null
1854
+ regionElements.clear()
1855
+ state.mountedCardIds.clear()
1856
+ }
1317
1857
  installDragging()
1318
- cacheCardConnectors()
1319
1858
  // The initial camera from renderCanvas is inset (viewport not laid out yet);
1320
1859
  // center it on the focused card once the canvas DOM is mounted.
1321
1860
  if (state.canvasNeedsCenter) {
1322
1861
  state.canvasNeedsCenter = false
1323
- window.requestAnimationFrame(() => { if (state.mode === 'canvas') focusActiveCard() })
1862
+ queueActiveCardFocus()
1324
1863
  }
1325
1864
  for (const [cardId, scrollTop] of cardScrollTops) {
1326
1865
  const answer = app.querySelector(`.thread-card[data-card-id="${CSS.escape(cardId)}"] .thread-answer`)
@@ -1353,7 +1892,7 @@ function render() {
1353
1892
  }
1354
1893
  // Card faces and the detail view only hold previews: pull the real bodies for
1355
1894
  // whatever is on screen right now (issue #42).
1356
- void hydrateBodies()
1895
+ if (state.mode !== 'canvas') hydrateBodies()
1357
1896
  }
1358
1897
 
1359
1898
  /**
@@ -1361,64 +1900,71 @@ function render() {
1361
1900
  * workspace payload carries previews only, so each newly mounted card and each
1362
1901
  * opened detail view hydrates from the DSH session log.
1363
1902
  */
1364
- async function hydrateBodies() {
1365
- const wanted = new Map()
1366
- const add = (threadId, message) => {
1903
+ function hydrateBodies() {
1904
+ if (!state.mapVisible || document.hidden || state.workspaceLoadBusy) {
1905
+ bodyLoader.pause(); return
1906
+ }
1907
+ const wanted = []
1908
+ const add = (threadId, message, priority = 1) => {
1367
1909
  if (threadId === undefined || message === null || message === undefined) return
1368
1910
  if (!Number.isInteger(message.sourceSeq)) return
1369
- if (state.bodies.get(threadId)?.has(message.sourceSeq) === true) return
1370
- const key = `${threadId}:${message.sourceSeq}`
1371
- if (state.bodyRequests.has(key) || state.bodyFailures.has(key)) return
1372
- const seqs = wanted.get(threadId) ?? new Set()
1373
- seqs.add(message.sourceSeq)
1374
- wanted.set(threadId, seqs)
1375
- }
1376
- const addCard = card => {
1911
+ wanted.push({ threadId, seq: message.sourceSeq, revision: bodyRevision(message), priority })
1912
+ }
1913
+ const addCard = (card, priority = 1) => {
1377
1914
  if (card === undefined) return
1378
- add(card.dshThreadId, card.questionMessage)
1379
- add(card.dshThreadId, card.answer)
1380
- add(card.dshThreadId, card.error)
1915
+ add(card.dshThreadId, card.questionMessage, priority)
1916
+ add(card.dshThreadId, card.answer, priority)
1917
+ add(card.dshThreadId, card.error, priority)
1381
1918
  }
1919
+ // An inspector wins admission when an unusually large canvas viewport
1920
+ // contains more than the bounded wanted-message set.
1921
+ if (state.mode === 'canvas' && state.inspectorCardId !== null) addCard(canvasGraphCache?.allById.get(state.inspectorCardId), 0)
1382
1922
  if (state.mode === 'thread' && state.activeId !== null) {
1383
1923
  const thread = currentThread()
1384
- if (thread !== null && !state.bodiesLoaded.has(thread.id)) {
1385
- for (const message of persistedMessagesFor(thread)) add(thread.id, message)
1924
+ if (thread !== null) {
1925
+ for (const message of detailPage(thread).messages) add(thread.id, message)
1386
1926
  }
1387
- } else if (state.mode === 'canvas') {
1388
- for (const cardId of state.mountedCardIds) addCard(state.canvasCardsById?.get(cardId))
1927
+ } else if (state.mode === 'canvas' && regionView && !regionView.overview) {
1928
+ for (const card of regionView.cards) addCard(card)
1929
+ for (const card of regionView.prefetch) addCard(card, 2)
1389
1930
  }
1390
- if (state.inspectorCardId !== null) addCard(state.canvasCardsById?.get(state.inspectorCardId))
1391
- for (const [threadId, seqs] of wanted) void fetchBodies(threadId, [...seqs])
1931
+ const viewKey = state.mode === 'thread'
1932
+ ? `thread:${state.activeId}:${currentThread() === null ? 0 : detailPage(currentThread()).start}`
1933
+ : `canvas:${state.focusedThreadId ?? ''}:${state.inspectorCardId ?? ''}`
1934
+ bodyLoader.sync(wanted, viewKey)
1392
1935
  }
1393
1936
 
1394
- async function fetchBodies(threadId, seqs) {
1395
- if (seqs.length === 0) return
1396
- const keys = seqs.map(seq => `${threadId}:${seq}`)
1397
- for (const key of keys) state.bodyRequests.add(key)
1398
- try {
1399
- const body = await api(`/synapse/api/threads/${threadId}/full?seqs=${seqs.join(',')}`)
1400
- const cached = state.bodies.get(threadId) ?? new Map()
1401
- for (const [seq, payload] of Object.entries(body.messages ?? {})) {
1402
- if (payload === null || typeof payload !== 'object') continue
1403
- cached.set(Number(seq), payload)
1404
- }
1405
- state.bodies.set(threadId, cached)
1406
- if (state.mode === 'thread' && state.activeId === threadId) state.bodiesLoaded.add(threadId)
1407
- if (body.unavailable === true) {
1408
- // Archived or already removed from DSH: keep the previews, stop asking.
1409
- for (const message of persistedMessagesFor(currentThread() ?? { messages: [] })) {
1410
- if (Number.isInteger(message.sourceSeq)) state.bodyFailures.add(`${threadId}:${message.sourceSeq}`)
1411
- }
1412
- state.bodiesLoaded.add(threadId)
1413
- }
1414
- if (state.mode === 'thread' || state.inspectorCardId !== null) render()
1415
- else if (canReplaceView()) render()
1416
- else deferCanvasRefresh(400)
1417
- } catch {
1418
- for (const key of keys) state.bodyFailures.add(key)
1419
- } finally {
1420
- for (const key of keys) state.bodyRequests.delete(key)
1937
+ function refreshLoadedBodies(entries = []) {
1938
+ const inspectorCard = canvasGraphCache?.allById.get(state.inspectorCardId)
1939
+ let inspectorChanged = false
1940
+ for (const entry of entries) {
1941
+ const id = canvasGraphCache?.byMessage.get(`${entry.threadId}:${entry.seq}`)
1942
+ if (id && regionElements.has(id)) regionDirtyCards.add(id)
1943
+ if (inspectorCard?.dshThreadId === entry.threadId
1944
+ && [inspectorCard.questionMessage, inspectorCard.answer, inspectorCard.error].some(message => message?.sourceSeq === entry.seq)) inspectorChanged = true
1945
+ }
1946
+ if (inspectorChanged && inspectorBodyTimer === 0) {
1947
+ inspectorBodyTimer = window.setTimeout(() => { inspectorBodyTimer = 0; refreshCardInspector() }, 100)
1421
1948
  }
1949
+ if (regionDirtyCards.size > 0) syncCanvasViewport()
1950
+ updateRegionStatus()
1951
+ }
1952
+
1953
+ function refreshCardInspector() {
1954
+ if (!state.mapVisible || document.hidden || state.mode !== 'canvas' || state.inspectorCardId === null) return
1955
+ const inspector = document.querySelector('.card-inspector')
1956
+ // Loading must not undo a user's in-progress close animation.
1957
+ if (!(inspector instanceof HTMLElement) || inspector.classList.contains('is-closing')) return
1958
+ if (state.dragging || state.canvasGesture) {
1959
+ if (inspectorBodyTimer === 0) inspectorBodyTimer = window.setTimeout(() => { inspectorBodyTimer = 0; refreshCardInspector() }, 100)
1960
+ return
1961
+ }
1962
+ const card = canvasGraphCache?.allById.get(state.inspectorCardId)
1963
+ if (!card) return
1964
+ const scroll = inspector.querySelector('.card-inspector-scroll')?.scrollTop ?? 0
1965
+ const next = patchElementHtml(inspector, renderCardInspector(card))
1966
+ const body = next.querySelector('.card-inspector-scroll')
1967
+ if (body) body.scrollTop = scroll
1422
1968
  }
1423
1969
 
1424
1970
  function renderPreservingDetailScroll() {
@@ -1469,13 +2015,13 @@ function applyCanvasTransform() {
1469
2015
  // new markup into the live tree instead: matching nodes are patched in place and
1470
2016
  // whatever sits under the pointer stays alive.
1471
2017
 
1472
- const MORPH_KEY_ATTRIBUTES = ['data-morph-key', 'data-card-id', 'data-thread', 'id']
2018
+ const MORPH_KEY_ATTRIBUTES = ['data-morph-key', 'data-card-id', 'data-inspector-card', 'data-thread', 'id']
1473
2019
 
1474
2020
  function morphKeyOf(node) {
1475
2021
  if (!(node instanceof Element)) return null
1476
2022
  for (const attribute of MORPH_KEY_ATTRIBUTES) {
1477
2023
  const value = node.getAttribute(attribute)
1478
- if (value !== null && value !== '') return `${node.tagName}|${attribute}|${value}`
2024
+ if (value !== null && value !== '') return `${node.tagName}|${attribute}|${value}|${node.getAttribute('data-action') ?? ''}`
1479
2025
  }
1480
2026
  return null
1481
2027
  }
@@ -1502,6 +2048,9 @@ function morphKeepsChildren(node) {
1502
2048
  if (!(node instanceof Element)) return false
1503
2049
  if (node instanceof HTMLInputElement || node instanceof HTMLTextAreaElement) return true
1504
2050
  if (node.isContentEditable === true) return true
2051
+ // Regional layers own their incremental DOM. Shell/inspector changes must
2052
+ // not recreate every mounted card or discard the region queue.
2053
+ if (node.hasAttribute('data-region-layer')) return true
1505
2054
  return node === morphFrozenRoot
1506
2055
  }
1507
2056
 
@@ -1539,13 +2088,16 @@ function morphChildren(from, to) {
1539
2088
  const keyed = new Map()
1540
2089
  for (const child of [...from.childNodes]) {
1541
2090
  const key = morphKeyOf(child)
1542
- if (key !== null && !keyed.has(key)) keyed.set(key, child)
2091
+ if (key !== null) {
2092
+ if (!keyed.has(key)) keyed.set(key, [])
2093
+ keyed.get(key).push(child)
2094
+ }
1543
2095
  }
1544
2096
  const matched = new Set()
1545
2097
  let cursor = from.firstChild
1546
2098
  for (const next of [...to.childNodes]) {
1547
2099
  const key = morphKeyOf(next)
1548
- let match = key === null ? null : keyed.get(key) ?? null
2100
+ let match = key === null ? null : keyed.get(key)?.shift() ?? null
1549
2101
  if (match === null && cursor !== null && morphKeyOf(cursor) === null) match = cursor
1550
2102
  if (match === null) {
1551
2103
  const inserted = next.cloneNode(true)
@@ -1577,10 +2129,11 @@ function morphInto(container, html) {
1577
2129
  }
1578
2130
  }
1579
2131
 
2132
+ const boundDragHandles = new WeakSet()
1580
2133
  function bindDragHandle(handle) {
1581
2134
  // Cards now survive a render, so bind each drag handle once.
1582
- if (handle.dataset.dragBound === '1') return
1583
- handle.dataset.dragBound = '1'
2135
+ if (boundDragHandles.has(handle)) return
2136
+ boundDragHandles.add(handle)
1584
2137
  handle.addEventListener('pointerdown', event => {
1585
2138
  const cardId = event.currentTarget.dataset.dragCard
1586
2139
  const card = event.currentTarget.closest('.thread-card')
@@ -1619,8 +2172,15 @@ function bindDragHandle(handle) {
1619
2172
  if (frame !== 0) { window.cancelAnimationFrame(frame); frame = 0 }
1620
2173
  apply()
1621
2174
  rememberCardPosition(cardId, position, aliases)
2175
+ const dataCard = state.canvasCardsById?.get(cardId)
2176
+ if (dataCard) {
2177
+ dataCard.positionLocked = true
2178
+ canvasGraphCache?.index.set(dataCard)
2179
+ }
2180
+ if (regionView) regionView.planKey = null
1622
2181
  state.dragging = false
1623
2182
  deferCanvasRefresh(120)
2183
+ syncCanvasViewport({ immediate: true })
1624
2184
  // No full render: only the dragged card's inline position and its
1625
2185
  // connectors changed; rebuilding the whole canvas on drop is the jank.
1626
2186
  }
@@ -1662,7 +2222,7 @@ function zoomCanvas(viewport, nextZoom, clientX, clientY) {
1662
2222
  applyCanvasTransform()
1663
2223
  syncCanvasViewport()
1664
2224
  }
1665
- const label = document.querySelector('.canvas-controls span')
2225
+ const label = document.querySelector('.canvas-zoom-label')
1666
2226
  if (label !== null) label.textContent = `${Math.round(state.zoom * 100)}%`
1667
2227
  }
1668
2228
 
@@ -1673,6 +2233,46 @@ function zoomCanvasAtCenter(delta) {
1673
2233
  zoomCanvas(viewport, state.zoom + delta, bounds.left + bounds.width / 2, bounds.top + bounds.height / 2)
1674
2234
  }
1675
2235
 
2236
+ function setCanvasFocus(threadId) {
2237
+ if (threadId === state.focusedThreadId) return false
2238
+ if (threadId !== null && !visibleThreads(state.workspace?.threads ?? []).some(thread => thread.id === threadId)) return false
2239
+ // Both scopes share the current camera and zoom. Switching only changes
2240
+ // visibility; invalidate queued centering from earlier navigation as well.
2241
+ state.focusedThreadId = threadId
2242
+ state.canvasFocusRevision++
2243
+ state.canvasNeedsCenter = false
2244
+ state.selectedCardId = null
2245
+ state.inspectorCardId = null
2246
+ state.inspectorOpening = false
2247
+ cancelRegionWork()
2248
+ regionView = null
2249
+ bodyLoader.pause()
2250
+ invalidateCanvasGraph()
2251
+ return true
2252
+ }
2253
+
2254
+ function reconcileCanvasFocus(threads, switched = false) {
2255
+ if (switched) {
2256
+ // A different workspace starts in its own all-conversation view.
2257
+ state.focusedThreadId = null
2258
+ state.canvasFocusRevision++
2259
+ state.canvasNeedsCenter = false
2260
+ } else if (state.focusedThreadId !== null && state.focusedThreadId !== undefined
2261
+ && !threads.some(thread => thread.id === state.focusedThreadId)) {
2262
+ setCanvasFocus(null)
2263
+ }
2264
+ }
2265
+
2266
+ function queueActiveCardFocus() {
2267
+ const revision = state.canvasFocusRevision
2268
+ const workspaceId = state.workspace?.id
2269
+ const activeId = state.activeId
2270
+ window.requestAnimationFrame(() => {
2271
+ if (state.mode === 'canvas' && state.canvasFocusRevision === revision
2272
+ && state.workspace?.id === workspaceId && state.activeId === activeId) focusActiveCard()
2273
+ })
2274
+ }
2275
+
1676
2276
  function focusActiveCard() {
1677
2277
  const viewport = document.querySelector('.canvas-viewport')
1678
2278
  if (!(viewport instanceof HTMLElement)) return
@@ -1779,6 +2379,7 @@ app.addEventListener('pointerdown', event => {
1779
2379
  apply()
1780
2380
  state.canvasGesture = false
1781
2381
  deferCanvasRefresh(120)
2382
+ syncCanvasViewport({ immediate: true })
1782
2383
  }
1783
2384
  document.addEventListener('pointermove', move)
1784
2385
  document.addEventListener('pointerup', stop)
@@ -1883,27 +2484,40 @@ app.addEventListener('click', async event => {
1883
2484
  }
1884
2485
  if (button.dataset.action === 'close') post('synapse:close')
1885
2486
  if (button.dataset.action === 'close-card-inspector') { closeCardInspector(); return }
2487
+ if (button.dataset.action === 'retry-bodies') {
2488
+ bodyLoader.retry()
2489
+ refreshCardInspector()
2490
+ updateRegionStatus()
2491
+ return
2492
+ }
1886
2493
  if (button.dataset.action === 'toggle-sidebar') { state.sidebarCollapsed = !state.sidebarCollapsed; render() }
1887
2494
  if (button.dataset.action === 'create-session') openNewSession()
1888
2495
  if (button.dataset.action === 'open-current' && state.currentDsh !== null) post('synapse:open-session', { sessionId: state.currentDsh.id })
1889
2496
  if (button.dataset.action === 'select-thread' && thread !== undefined) {
2497
+ if (state.focusedThreadId !== null && state.draft !== null) return setError('请先完成或取消正在编辑的追问或分支')
1890
2498
  state.mapCardSessionSwitches.clear()
1891
2499
  state.activeId = thread.id
1892
2500
  state.selectedCardId = null
1893
2501
  state.inspectorCardId = null
1894
2502
  state.inspectorOpening = false
1895
2503
  state.error = ''
1896
- if (state.workspace !== null) revealConversationThread(conversationCards(state.workspace.threads), thread.id)
2504
+ if (state.focusedThreadId !== null) setCanvasFocus(thread.id)
2505
+ else if (state.workspace !== null) revealConversationThread(conversationCards(state.workspace.threads), thread.id)
1897
2506
  render()
1898
2507
  // The state switch is instant, so the map has to show it: without this the
1899
2508
  // camera stayed on the previous conversation's cards (often thousands of
1900
2509
  // pixels away), and a click that worked looked like a dead button.
1901
- window.requestAnimationFrame(() => { if (state.mode === 'canvas') focusActiveCard() })
2510
+ queueActiveCardFocus()
1902
2511
  void loadThreadHistory(thread)
1903
2512
  // Bidirectional current-session sync: switch DSH's current session
1904
2513
  // without closing the map; the client confirms via synapse:current-session.
1905
- if (thread.dshSessionId !== null) post('synapse:activate-session', { sessionId: thread.dshSessionId })
2514
+ if (thread.dshSessionId !== null) {
2515
+ if (thread.dshSessionId !== state.currentDsh?.id) state.mapCardSessionSwitches.add(thread.dshSessionId)
2516
+ post('synapse:activate-session', { sessionId: thread.dshSessionId })
2517
+ }
1906
2518
  }
2519
+ if (button.dataset.action === 'detail-prev' && thread !== undefined) changeDetailPage(thread, -1)
2520
+ if (button.dataset.action === 'detail-next' && thread !== undefined) changeDetailPage(thread, 1)
1907
2521
  if (button.dataset.action === 'show-thread' && thread !== undefined) { state.activeId = thread.id; state.mode = 'thread'; state.detailTargetCardId = button.dataset.card ?? null; render(); void loadThreadHistory(thread) }
1908
2522
  if (button.dataset.action === 'show-canvas') { state.mode = 'canvas'; render() }
1909
2523
  if (button.dataset.action === 'toggle-card-children' && button.dataset.card !== undefined) {
@@ -1912,14 +2526,12 @@ app.addEventListener('click', async event => {
1912
2526
  if (collapsing && state.workspace !== null) {
1913
2527
  const allCards = conversationCards(state.workspace.threads)
1914
2528
  const nextCollapsed = new Set(state.collapsedCardIds).add(cardId)
1915
- const visibleCards = conversationGraphView(allCards, nextCollapsed).cards
2529
+ const visibleCards = conversationGraphView(scopedConversationCards(allCards, visibleThreads(state.workspace.threads)), nextCollapsed).cards
1916
2530
  const visibleIds = new Set(visibleCards.map(card => card.id))
1917
2531
  const draftParentId = draftPlacement(allCards)?.parent.id
1918
2532
  if (draftParentId !== undefined && !visibleIds.has(draftParentId)) 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.
2533
+ // The active session may be hidden too; only an unfinished draft
2534
+ // requires its source card to remain visible.
1923
2535
  }
1924
2536
  collapsing ? state.collapsedCardIds.add(cardId) : state.collapsedCardIds.delete(cardId)
1925
2537
  persistCollapsedCards()
@@ -1943,6 +2555,11 @@ app.addEventListener('click', async event => {
1943
2555
  if (button.dataset.action === 'zoom-in') zoomCanvasAtCenter(.1)
1944
2556
  if (button.dataset.action === 'zoom-out') zoomCanvasAtCenter(-.1)
1945
2557
  if (button.dataset.action === 'focus-active') focusActiveCard()
2558
+ if (button.dataset.action === 'focus-thread' || button.dataset.action === 'show-workspace') {
2559
+ if (state.draft !== null) return setError('请先完成或取消正在编辑的追问或分支')
2560
+ if (button.dataset.action === 'focus-thread' && state.focusedThreadId !== null) return
2561
+ if (setCanvasFocus(button.dataset.action === 'show-workspace' ? null : state.activeId)) render()
2562
+ }
1946
2563
  if (button.dataset.action === 'dismiss-error') { state.error = ''; render() }
1947
2564
  if (button.dataset.action === 'layout' && state.workspace !== null) {
1948
2565
  resetCardPositions()
@@ -1995,6 +2612,7 @@ window.addEventListener('message', event => {
1995
2612
  if (event.origin !== window.location.origin || event.data?.source !== 'dsh-synapse') return
1996
2613
  const data = event.data
1997
2614
  if (data.type === 'synapse:map-opened') {
2615
+ state.mapVisible = true
1998
2616
  // Do NOT reset the camera here: toggling dialog<->map for the same
1999
2617
  // session must keep the user's viewport. A fresh canvas (canvasView
2000
2618
  // not initialized) still centers via renderCanvas; a real session switch
@@ -2003,6 +2621,8 @@ window.addEventListener('message', event => {
2003
2621
  render()
2004
2622
  window.requestAnimationFrame(() => post('synapse:map-ready'))
2005
2623
  }
2624
+ if (data.type === 'synapse:map-closed') pauseMapBodies()
2625
+ if (data.type === 'synapse:map-visible') { state.mapVisible = true; render() }
2006
2626
  if (data.type === 'synapse:theme') {
2007
2627
  document.documentElement.dataset.theme = data.dark === true ? 'dark' : 'light'
2008
2628
  }
@@ -2020,6 +2640,7 @@ window.addEventListener('message', event => {
2020
2640
  state.workspacesSignature = signature
2021
2641
  state.dshWorkspaces = nextWorkspaces
2022
2642
  state.archivedSessionIds = nextArchived
2643
+ pruneWorkspaceCaches()
2023
2644
  const current = currentDshWorkspace()
2024
2645
  if (current !== undefined && current.id !== state.selectedDshWorkspaceId) void openDshWorkspace(current.id).catch(setError)
2025
2646
  else if (state.selectedDshWorkspaceId !== null) void openDshWorkspace(state.selectedDshWorkspaceId).catch(setError)
@@ -2032,7 +2653,9 @@ window.addEventListener('message', event => {
2032
2653
  const nextSignature = sessionSignature(data.session)
2033
2654
  const preserveCanvasCamera = previousId !== data.session?.id && state.mapCardSessionSwitches.delete(data.session?.id)
2034
2655
  const thread = currentDshThread()
2035
- if (thread !== undefined) {
2656
+ // A status update for the old host session can arrive while a map click is
2657
+ // opening another session. Only actual navigation reconciles selection.
2658
+ if (thread !== undefined && previousId !== data.session?.id) {
2036
2659
  const preserveSelectedCard = state.activeId === thread.id
2037
2660
  state.activeId = thread.id
2038
2661
  if (!preserveSelectedCard) {
@@ -2040,7 +2663,10 @@ window.addEventListener('message', event => {
2040
2663
  state.inspectorCardId = null
2041
2664
  state.inspectorOpening = false
2042
2665
  }
2043
- if (state.workspace !== null) revealConversationThread(conversationCards(state.workspace.threads), thread.id)
2666
+ if (state.focusedThreadId !== null) {
2667
+ const scope = conversationThreadScope(visibleThreads(state.workspace?.threads ?? []), state.focusedThreadId)
2668
+ if (!preserveCanvasCamera && state.draft === null && !scope.has(thread.id)) setCanvasFocus(thread.id)
2669
+ } else if (state.workspace !== null) revealConversationThread(conversationCards(state.workspace.threads), thread.id)
2044
2670
  }
2045
2671
  if (previousId !== data.session?.id) {
2046
2672
  // A real session switch: re-center on the new session's latest turn,
@@ -2061,7 +2687,7 @@ window.addEventListener('message', event => {
2061
2687
  if (data.type === 'synapse:live-reply' && typeof data.sessionId === 'string') {
2062
2688
  const thread = state.workspace?.threads.find(item => item.dshSessionId === data.sessionId)
2063
2689
  if (thread !== undefined) {
2064
- if (data.running === true) {
2690
+ if (data.running === true && state.mapVisible && !document.hidden) {
2065
2691
  state.liveReplies.set(data.sessionId, { running: true, text: typeof data.text === 'string' ? data.text : '' })
2066
2692
  // Streaming: patch the live card's answer in place instead of
2067
2693
  // rebuilding the whole canvas on every chunk; a full render reconciles
@@ -2071,6 +2697,7 @@ window.addEventListener('message', event => {
2071
2697
  else if (canReplaceView()) scheduleLiveRender()
2072
2698
  } else {
2073
2699
  state.liveReplies.delete(data.sessionId)
2700
+ invalidateCanvasGraph()
2074
2701
  if (canReplaceView() || state.pendingReplies.has(data.sessionId)) renderPreservingDetailScroll()
2075
2702
  }
2076
2703
  }
@@ -2081,8 +2708,19 @@ window.addEventListener('message', event => {
2081
2708
  })
2082
2709
 
2083
2710
  post('synapse:request-current')
2084
- refreshSummaries().catch(setError)
2711
+ document.addEventListener('visibilitychange', () => {
2712
+ if (document.hidden) { clearViewCaches(); state.liveReplies.clear(); hideSelectionFollowup(); releaseRenderedBodies() }
2713
+ else if (state.mapVisible) { post('synapse:request-current'); render() }
2714
+ })
2715
+ window.addEventListener('pagehide', pauseMapBodies)
2716
+ window.addEventListener('pageshow', event => {
2717
+ if (event.persisted && window.parent === window) { state.mapVisible = true; render() }
2718
+ })
2085
2719
  let polling = false
2720
+ let projectionPollFailures = 0
2721
+ let projectionPollAfter = 0
2722
+ let projectionPollWorkspaceId = null
2723
+ let projectionPollError = ''
2086
2724
  let liveRenderTimer = 0
2087
2725
  let liveCardFrame = 0
2088
2726
  let liveCardSessionId = null
@@ -2107,17 +2745,18 @@ function applyLiveReplyToCard(sessionId) {
2107
2745
  if (thread === undefined) return
2108
2746
  const live = state.liveReplies.get(sessionId)
2109
2747
  if (live?.running !== true) return
2110
- const cards = app.querySelectorAll(`.thread-card[data-thread="${CSS.escape(thread.id)}"]`)
2111
- const card = cards[cards.length - 1]
2112
- if (!(card instanceof HTMLElement)) return
2113
- const answer = card.querySelector('.thread-answer')
2114
- if (!(answer instanceof HTMLElement)) return
2115
- const text = live.text
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() === ''
2119
- ? '<p class="thread-answer-pending">正在回复</p>'
2120
- : `${renderMarkdown(text)}<p class="thread-answer-pending">正在回复</p>`)
2748
+ const dataCard = canvasGraphCache?.latestByThread.get(thread.id)
2749
+ if (!dataCard || dataCard.answer !== null && !dataCard.answer.pending) return
2750
+ dataCard.answer = { kind: 'assistant', text: live.text, pending: true }
2751
+ if (dataCard.id === state.inspectorCardId && inspectorBodyTimer === 0) {
2752
+ inspectorBodyTimer = window.setTimeout(() => { inspectorBodyTimer = 0; refreshCardInspector() }, 100)
2753
+ }
2754
+ // Overview cards use previews and never parse a full streamed response.
2755
+ if (regionView?.overview) return
2756
+ if (regionElements.has(dataCard.id)) {
2757
+ regionDirtyCards.add(dataCard.id)
2758
+ syncCanvasViewport()
2759
+ }
2121
2760
  }
2122
2761
  function scheduleLiveRender() {
2123
2762
  if (liveRenderTimer !== 0 || !canReplaceView()) return
@@ -2127,10 +2766,42 @@ function scheduleLiveRender() {
2127
2766
  }, 120)
2128
2767
  }
2129
2768
  async function pollProjection() {
2130
- if (polling || document.hidden || !canReplaceView()) return
2769
+ if (polling || !state.mapVisible || document.hidden || state.workspaceLoadBusy || !canReplaceView()) return
2770
+ const targetWorkspaceId = () => state.selectedDshWorkspaceId ?? currentDshWorkspace()?.id ?? state.workspace?.id ?? state.dshWorkspaces[0]?.id ?? null
2771
+ const workspaceId = targetWorkspaceId()
2772
+ if (workspaceId !== projectionPollWorkspaceId) {
2773
+ projectionPollWorkspaceId = workspaceId
2774
+ projectionPollFailures = 0
2775
+ projectionPollAfter = 0
2776
+ }
2777
+ if (Date.now() < projectionPollAfter) return
2131
2778
  polling = true
2132
2779
  try {
2133
2780
  await refreshProjection()
2781
+ projectionPollFailures = 0
2782
+ projectionPollAfter = 0
2783
+ if (projectionPollError !== '' && state.error === projectionPollError) {
2784
+ state.error = ''
2785
+ if (canReplaceView()) render()
2786
+ }
2787
+ projectionPollError = ''
2788
+ } catch (error) {
2789
+ projectionPollFailures += 1
2790
+ projectionPollAfter = Date.now() + Math.min(30_000, 1_000 * 2 ** Math.min(projectionPollFailures, 5))
2791
+ // An old workspace request cannot put an error over a newer user choice.
2792
+ if (workspaceId === targetWorkspaceId()) {
2793
+ const message = `自动刷新失败:${error instanceof Error ? error.message : String(error)}`
2794
+ if (projectionPollError !== message) {
2795
+ const mayShowError = state.error === '' || state.error === projectionPollError
2796
+ projectionPollError = message
2797
+ if (mayShowError) {
2798
+ state.error = message
2799
+ if (canReplaceView()) render()
2800
+ }
2801
+ }
2802
+ }
2134
2803
  } finally { polling = false }
2135
2804
  }
2805
+ void pollProjection()
2136
2806
  window.setInterval(() => { void pollProjection() }, 1_000)
2807
+ window.addEventListener('resize', () => syncCanvasViewport({ immediate: true }))