dsh-session-branch 0.0.0-stage → 1.3.0

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/lib/client.js ADDED
@@ -0,0 +1,2082 @@
1
+ /**
2
+ * `dsh-session-lineage` browser half.
3
+ *
4
+ * Renders the inferred lineage into the sidebar: session rows are ordered with
5
+ * CSS `order` (never moved), indented by depth, collapsible (default expanded,
6
+ * state persisted) and reorderable inside one sibling group from the Session
7
+ * 「…」menu. One session can also be detached from its parent in the display
8
+ * tree (rendered as a sibling of the parent) without touching the inference.
9
+ * Native drag reordering is intentionally not adopted (v1): the sidebar keeps
10
+ * its durable order while this plugin owns the displayed order.
11
+ *
12
+ * Integration surface is the official row-key DOM contract only:
13
+ * [role="tree"] the session list root
14
+ * [data-row-key="workspace:<id>"] a workspace header (inside its HoverCard wrapper)
15
+ * [data-row-key="session:<id>"] a session row (inside a HoverCard wrapper)
16
+ * [data-row-key="overflow:<key>"] the "show more" row
17
+ * Hashed CSS-module class names are never used.
18
+ */
19
+
20
+ /** Root group key shared by the pure display helpers and the client state. */
21
+ const ROOT_KEY = 'root'
22
+
23
+ /** Register the browser bundle; a no-op when evaluated outside the page (tests). */
24
+ const register = typeof window !== 'undefined' && window.__ModuleLoader__ !== undefined
25
+ ? (bundle) => window.__ModuleLoader__.load(bundle)
26
+ : () => {}
27
+
28
+ register({
29
+ id: 'dsh-session-lineage',
30
+ factory() {
31
+ const MARK = 'dsh-session-lineage'
32
+ const TREE_PATH = '/api/session-lineage'
33
+ const STATE_PATH = '/api/session-lineage.state'
34
+ const INDENT_STEP = 14
35
+ // DSH renders its ungrouped bucket with an empty workspace id; the host
36
+ // accepts this key and takes the loose sessions from the request instead.
37
+ const UNGROUPED_ID = 'ungrouped'
38
+ const OVERFLOW_ORDER = 100000
39
+ const APPLY_DEBOUNCE_MS = 150
40
+ const SAVE_DEBOUNCE_MS = 300
41
+ const REFETCH_DELAY_MS = 600
42
+ const FOCUS_REFRESH_MS = 60000
43
+ // A fork made from the sidebar never opens a window of its own, so the new
44
+ // row would stay invisible under a collapsed parent. Branches created this
45
+ // recently are revealed (ancestors expanded, row flashed) once.
46
+ const REVEAL_WINDOW_MS = 5 * 60 * 1000
47
+
48
+ /** Localized labels for the controls this plugin adds. */
49
+ const UI_TEXT = {
50
+ zh: {
51
+ moveUp: '同级上移',
52
+ moveDown: '同级下移',
53
+ moveFirst: '移到最前',
54
+ moveLast: '移到最后',
55
+ openParent: '打开父会话',
56
+ detach: '与父级并列显示',
57
+ attach: '恢复为子会话',
58
+ showNumbers: '显示层级编号',
59
+ hideNumbers: '隐藏层级编号',
60
+ expand: '展开分支',
61
+ collapse: '收起分支',
62
+ forkBranch: '分支对话',
63
+ },
64
+ en: {
65
+ moveUp: 'Move up',
66
+ moveDown: 'Move down',
67
+ moveFirst: 'Move to top',
68
+ moveLast: 'Move to bottom',
69
+ openParent: 'Open parent session',
70
+ detach: 'Detach from parent',
71
+ attach: 'Attach to parent',
72
+ showNumbers: 'Show hierarchy numbers',
73
+ hideNumbers: 'Hide hierarchy numbers',
74
+ expand: 'Expand branch',
75
+ collapse: 'Collapse branch',
76
+ forkBranch: 'Branch chat',
77
+ },
78
+ }
79
+
80
+ /**
81
+ * Labels for the current interface language.
82
+ *
83
+ * @returns `{ moveUp, moveDown, moveFirst, moveLast, detach, attach, expand, collapse }`.
84
+ */
85
+ function uiText() {
86
+ const language = document.documentElement.lang || navigator.language || 'zh'
87
+ return language.toLowerCase().startsWith('zh') ? UI_TEXT.zh : UI_TEXT.en
88
+ }
89
+
90
+ /**
91
+ * Write one inline style only when it actually changes.
92
+ *
93
+ * @param element - target element.
94
+ * @param property - CSS property name.
95
+ * @param value - desired value.
96
+ */
97
+ function setStyle(element, property, value) {
98
+ if (element.style.getPropertyValue(property) !== value) element.style.setProperty(property, value)
99
+ }
100
+
101
+ /**
102
+ * Remove one inline style only when it is present.
103
+ *
104
+ * @param element - target element.
105
+ * @param property - CSS property name.
106
+ */
107
+ function removeStyle(element, property) {
108
+ if (element.style.getPropertyValue(property) !== '') element.style.removeProperty(property)
109
+ }
110
+
111
+ const CSS = `
112
+ [data-dsl-section] { display: flex !important; flex-direction: column; }
113
+ [data-row-key^="session:"] {
114
+ padding-inline-start: calc(
115
+ var(--dsh-sidebar-row-padding, 12px) - var(--dsh-sidebar-paint-inset, 3px) +
116
+ var(--dsh-workspace-indent, 0px) + var(--dsl-indent, 0px)
117
+ ) !important;
118
+ }
119
+ .dsl-toggle {
120
+ flex: none;
121
+ display: inline-flex;
122
+ align-items: center;
123
+ justify-content: center;
124
+ width: 16px;
125
+ height: 16px;
126
+ margin-inline-end: 2px;
127
+ padding: 0;
128
+ border: 0;
129
+ border-radius: 4px;
130
+ background: transparent;
131
+ color: var(--dsw-alias-label-secondary, #5f6368);
132
+ font: 12px/1 var(--dsw-font-family, system-ui, sans-serif);
133
+ cursor: pointer;
134
+ }
135
+ .dsl-toggle:hover {
136
+ color: var(--dsw-alias-state-business-primary, #2563eb);
137
+ background: var(--dsw-alias-interactive-bg-hover, rgba(0,0,0,0.06));
138
+ }
139
+ .dsl-number {
140
+ flex: none;
141
+ margin-inline-end: 4px;
142
+ color: var(--dsw-alias-label-tertiary, #8a8f98);
143
+ font-variant-numeric: tabular-nums;
144
+ white-space: nowrap;
145
+ }
146
+ .dsl-toggle-ghost { visibility: hidden; pointer-events: none; }
147
+ /* D: hovering a descendant lights up its whole ancestor chain. */
148
+ .dsl-ancestor {
149
+ background-color: color-mix(in srgb, var(--dsw-alias-state-business-primary, #2563eb) 12%, transparent);
150
+ }
151
+ /* E: a branch that appeared while the sidebar was open pulses once. */
152
+ @keyframes dsl-branch-in {
153
+ from { background-color: color-mix(in srgb, var(--dsw-alias-state-business-primary, #2563eb) 30%, transparent); }
154
+ to { background-color: transparent; }
155
+ }
156
+ .dsl-new-branch {
157
+ animation: dsl-branch-in 1.8s ease-out;
158
+ }
159
+ /* F: the message-level branch button this plugin adds to a finished answer. */
160
+ .dsl-chat-branch {
161
+ display: inline-flex;
162
+ align-items: center;
163
+ justify-content: center;
164
+ width: 24px;
165
+ height: 24px;
166
+ padding: 0;
167
+ border: 0;
168
+ border-radius: 6px;
169
+ background: transparent;
170
+ color: var(--dsw-alias-label-tertiary, #8a8f98);
171
+ cursor: pointer;
172
+ }
173
+ .dsl-chat-branch:hover {
174
+ background: var(--dsw-alias-interactive-bg-hover, rgba(0,0,0,0.06));
175
+ color: var(--dsw-alias-label-secondary, #5f6368);
176
+ }
177
+ .dsl-chat-branch:disabled { cursor: default; opacity: 0.45; }
178
+ .dsl-chat-branch svg { width: 14px; height: 14px; }
179
+
180
+ .dsl-toast {
181
+ position: fixed;
182
+ inset-inline: 0;
183
+ bottom: 72px;
184
+ margin-inline: auto;
185
+ width: fit-content;
186
+ max-width: min(78vw, 520px);
187
+ padding: 8px 14px;
188
+ border-radius: 10px;
189
+ background: var(--dsw-alias-bg-elevated, rgb(32 33 36 / 96%));
190
+ color: var(--dsw-alias-text-primary, #f8fafc);
191
+ font-size: 13px;
192
+ line-height: 1.45;
193
+ box-shadow: 0 8px 24px rgb(0 0 0 / 28%);
194
+ z-index: 2147483000;
195
+ pointer-events: none;
196
+ }
197
+ `
198
+
199
+ let disposed = false
200
+ let applying = false
201
+ let queued = false
202
+ let observer = null
203
+ let styleEl = null
204
+ let applyTimer = 0
205
+ let saveTimer = 0
206
+ let stateLoaded = false
207
+ /**
208
+ * Whether this launch already folded every parent once.
209
+ *
210
+ * The first apply collapses each session that has children, so the sidebar
211
+ * opens as a plain list and branches are expanded on demand. Later applies
212
+ * keep whatever the user expanded in this visit.
213
+ */
214
+ let launchFolded = false
215
+ let state = { version: 1, order: {}, collapsed: [], detached: [], forks: {}, display: { numbers: true } }
216
+ let hoveredSession = null
217
+ let highlightedRows = []
218
+ let lastFocusRefresh = 0
219
+ let uiWorkspace = null
220
+ let workspaces = null
221
+ const trees = new Map()
222
+ const refetching = new Set()
223
+ /** Sessions the tree has already shown; used to spot a branch born now. */
224
+ const seenSessions = new Set()
225
+ let seeded = false
226
+ /** Sessions service face (`ctx.sessions`); forks a precise prefix from a message. */
227
+ let sessions = null
228
+ /** Live chat observer and debounce for the message-level branch button. */
229
+ let chatObserver = null
230
+ let chatTimer = 0
231
+ let chatSyncPending = false
232
+ /** One fork at a time: double clicks must not create two branches. */
233
+ let chatBranching = false
234
+
235
+ /**
236
+ * Log one degradation without throwing at the caller.
237
+ *
238
+ * @param message - diagnostic text.
239
+ * @param error - optional failure.
240
+ */
241
+ function warn(message, error) {
242
+ console.warn(`[${MARK}] ${message}`, error === undefined ? '' : error)
243
+ }
244
+
245
+ /**
246
+ * Show one short message near the bottom of the viewport.
247
+ *
248
+ * Fork failures used to be console-only, so a click the Host rejected looked
249
+ * exactly like a click that did nothing. The plugin owns no toast service, so
250
+ * it renders and disposes its own strip.
251
+ *
252
+ * @param message - user-facing sentence.
253
+ */
254
+ function notify(message) {
255
+ try {
256
+ const toast = document.createElement('div')
257
+ toast.className = 'dsl-toast'
258
+ toast.textContent = message
259
+ document.body.append(toast)
260
+ setTimeout(() => {
261
+ toast.remove()
262
+ }, 4200)
263
+ } catch (error) {
264
+ warn('notify failed', error)
265
+ }
266
+ }
267
+
268
+ /**
269
+ * Turn one fork failure into a short user-facing sentence.
270
+ *
271
+ * @param error - rejection from the Host.
272
+ * @returns the sentence to show.
273
+ */
274
+ function forkFailureText(error) {
275
+ const code = error?.code ?? error?.data?.code ?? ''
276
+ if (code === 'session/migration-required') return '请先打开原会话完成迁移,再创建分支'
277
+ if (code === 'session/fork-unavailable') return '这个会话还没有完成一轮对话,暂时不能分叉'
278
+ const message = error?.message ?? String(error)
279
+ return '分支对话失败:' + message
280
+ }
281
+
282
+ /**
283
+ * Discover workspace sections from their header rows.
284
+ *
285
+ * @returns `{ section, header, workspaceId }` per workspace header.
286
+ */
287
+ function workspaceSections() {
288
+ const sections = []
289
+ for (const header of document.querySelectorAll('[data-row-key^="workspace:"]')) {
290
+ // Workspace headers may sit in a HoverCard span while the ungrouped
291
+ // header does not; the section is always the tree/group child that owns
292
+ // the header and its session rows.
293
+ const section = sectionOfElement(header)
294
+ if (section === null) continue
295
+ const rawId = header.getAttribute('data-row-key')?.slice('workspace:'.length) ?? ''
296
+ sections.push({ section, header, workspaceId: rawId === '' ? UNGROUPED_ID : rawId })
297
+ }
298
+ return sections
299
+ }
300
+
301
+ /**
302
+ * The section an element belongs to: the node whose parent is the tree or a
303
+ * nested workspace group.
304
+ *
305
+ * @param element - any sidebar element.
306
+ * @returns section element or null.
307
+ */
308
+ function sectionOfElement(element) {
309
+ let node = element.parentElement
310
+ for (let depth = 0; node && depth < 6; depth += 1) {
311
+ const parent = node.parentElement
312
+ if (!parent) return node
313
+ const role = parent.getAttribute('role')
314
+ if (role === 'tree' || role === 'group') return node
315
+ node = parent
316
+ }
317
+ return null
318
+ }
319
+
320
+ /**
321
+ * Session rows that belong to exactly this section (nested workspaces excluded).
322
+ *
323
+ * @param section - workspace section element.
324
+ * @returns session row elements in DOM order.
325
+ */
326
+ function sessionRowsIn(section) {
327
+ return Array.from(section.querySelectorAll('[data-row-key^="session:"]')).filter(
328
+ (row) => sectionOfElement(row) === section,
329
+ )
330
+ }
331
+
332
+ /**
333
+ * The flex item carrying `order` for one session row.
334
+ *
335
+ * @param row - session row element.
336
+ * @param section - owning section.
337
+ * @returns wrapper element (the row itself when it is a direct child).
338
+ */
339
+ function wrapperOf(row, section) {
340
+ const parent = row.parentElement
341
+ if (!parent || parent === section) return row
342
+ return parent
343
+ }
344
+
345
+ /**
346
+ * Session id encoded in a row's data attribute.
347
+ *
348
+ * @param row - session row element.
349
+ * @returns session id or ''.
350
+ */
351
+ function sessionIdOf(row) {
352
+ const key = row.getAttribute('data-row-key') ?? ''
353
+ return key.startsWith('session:') ? key.slice('session:'.length) : ''
354
+ }
355
+
356
+ /**
357
+ * Workspace id of one workspace section element.
358
+ *
359
+ * @param section - element carrying `data-dsl-section`.
360
+ * @returns workspace id or null.
361
+ */
362
+ function workspaceIdOfSection(section) {
363
+ const header = section.querySelector('[data-row-key^="workspace:"]')
364
+ const key = header?.getAttribute('data-row-key') ?? ''
365
+ if (!key.startsWith('workspace:')) return null
366
+ const id = key.slice('workspace:'.length)
367
+ return id === '' ? UNGROUPED_ID : id
368
+ }
369
+
370
+ /**
371
+ * Session id carried by one removed DOM node, if any.
372
+ *
373
+ * @param node - removed node.
374
+ * @returns session id or null.
375
+ */
376
+ function sessionIdInNode(node) {
377
+ if (!(node instanceof Element)) return null
378
+ const row = node.matches('[data-row-key^="session:"]')
379
+ ? node
380
+ : node.querySelector('[data-row-key^="session:"]')
381
+ return row === null ? null : sessionIdOf(row) || null
382
+ }
383
+
384
+ /**
385
+ * Load one section's lineage once and cache it. The ungrouped bucket has no
386
+ * backing workspace, so it carries the loose session ids the caller renders
387
+ * and refetches when that rendered set changes.
388
+ *
389
+ * @param workspaceId - DSH workspace id or the ungrouped key.
390
+ * @param sessionIds - rendered loose ids for the ungrouped bucket.
391
+ * @returns `{ sessions, byId }`.
392
+ */
393
+ async function ensureTree(workspaceId, sessionIds) {
394
+ const cached = trees.get(workspaceId)
395
+ const idsKey = sessionIds === undefined ? null : [...sessionIds].sort().join(',')
396
+ if (cached !== undefined && (cached.idsKey ?? null) === idsKey) return cached
397
+ const params = new URLSearchParams({ workspaceId })
398
+ if (sessionIds !== undefined) params.set('ids', sessionIds.join(','))
399
+ const response = await fetch(`${TREE_PATH}?${params.toString()}`, {
400
+ credentials: 'same-origin',
401
+ })
402
+ if (!response.ok) throw new Error(`lineage HTTP ${response.status}`)
403
+ const body = await response.json()
404
+ const sessions = Array.isArray(body?.sessions) ? body.sessions : []
405
+ const entry = { sessions, byId: new Map(sessions.map((item) => [item.id, item])), idsKey }
406
+ trees.set(workspaceId, entry)
407
+ return entry
408
+ }
409
+
410
+ /**
411
+ * Drop one cached tree and apply again after the debounce delay, so a fresh
412
+ * fork (a row the cached tree does not know yet) ends up under its parent.
413
+ *
414
+ * @param workspaceId - workspace whose cache is stale.
415
+ */
416
+ function refetchWorkspace(workspaceId) {
417
+ if (refetching.has(workspaceId)) return
418
+ refetching.add(workspaceId)
419
+ setTimeout(() => {
420
+ trees.delete(workspaceId)
421
+ refetching.delete(workspaceId)
422
+ scheduleApply()
423
+ }, REFETCH_DELAY_MS)
424
+ }
425
+
426
+ /**
427
+ * Fork a session from the session menu and make the new child visible.
428
+ *
429
+ * DSH's own fork action creates the child without opening it and without
430
+ * changing the selection, which reads as "the click did nothing" — the only
431
+ * visible trace would be a row somewhere further down the sidebar. This
432
+ * entry point re-inserts the child right before its parent (asking the Host
433
+ * to republish the Workspace row when the fork's own increment did not
434
+ * reach this client), refreshes the lineage tree and flashes the new row.
435
+ *
436
+ * The child is deliberately NOT opened: repeated forks of the same session
437
+ * must yield siblings (5.1, 5.2, …), and switching the current session
438
+ * after every fork turns the next click into a fork of the child.
439
+ *
440
+ * @param sessionId - source session id.
441
+ */
442
+ async function branchFromHere(sessionId) {
443
+ const workspace = uiWorkspace
444
+ if (workspace === null || typeof workspace.forkSession !== 'function') {
445
+ notify('分支对话不可用:工作区服务未就绪')
446
+ return
447
+ }
448
+ try {
449
+ await ensureState()
450
+ } catch (error) {
451
+ warn('branch state load failed', error)
452
+ }
453
+ let childId
454
+ try {
455
+ childId = await workspace.forkSession(sessionId, undefined)
456
+ } catch (error) {
457
+ warn('branch failed', error)
458
+ notify(forkFailureText(error))
459
+ return
460
+ }
461
+ if (typeof childId !== 'string' || childId === '') return
462
+ try {
463
+ recordForkLink(childId, sessionId)
464
+ await ensureBranchRowVisible(sessionId, childId)
465
+ trees.clear()
466
+ refetching.clear()
467
+ scheduleApply()
468
+ revealBranchWhenReady(childId, 0)
469
+ } catch (error) {
470
+ // The child exists even when the sidebar could not be updated; say so
471
+ // instead of leaving the click looking dead.
472
+ warn('branch created but the sidebar was not refreshed', error)
473
+ notify('分支已创建,但侧栏刷新失败,请点「分支对话」旁边的刷新')
474
+ }
475
+ }
476
+
477
+ /**
478
+ * Section that currently renders one session row.
479
+ *
480
+ * @param sessionId - session id.
481
+ * @returns owning section element or null.
482
+ */
483
+ function sectionOfSession(sessionId) {
484
+ for (const entry of workspaceSections()) {
485
+ if (sessionRowsIn(entry.section).some((row) => sessionIdOf(row) === sessionId)) return entry
486
+ }
487
+ return null
488
+ }
489
+
490
+ /**
491
+ * Ask the Host to republish the fork's row right next to its parent.
492
+ *
493
+ * DSH's fork attaches the child to the Workspace but does not republish the
494
+ * membership to every client, and the sidebar only mounts the first few rows
495
+ * of a group, so an appended child can stay invisible. Re-inserting the child
496
+ * right before the parent (or before the first mounted session when the parent
497
+ * row itself is below the sidebar's visible cutoff) makes the Host broadcast
498
+ * the change and keeps the new row inside the mounted window.
499
+ *
500
+ * @param parentId - source session id.
501
+ * @param childId - forked session id.
502
+ */
503
+ async function ensureBranchRowVisible(parentId, childId) {
504
+ if (workspaces === null || typeof workspaces.insertSessionBefore !== 'function') return
505
+ let workspaceId = null
506
+ let beforeId = null
507
+ const entry = sectionOfSession(parentId)
508
+ if (entry !== null) {
509
+ workspaceId = entry.workspaceId
510
+ const rows = sessionRowsIn(entry.section)
511
+ if (rows.some((row) => sessionIdOf(row) === parentId)) beforeId = parentId
512
+ else if (rows.length > 0) beforeId = sessionIdOf(rows[0]) || null
513
+ }
514
+ if (workspaceId === null || workspaceId === UNGROUPED_ID) {
515
+ for (const [id, tree] of trees) {
516
+ if (id === UNGROUPED_ID || !tree.byId.has(parentId)) continue
517
+ workspaceId = id
518
+ break
519
+ }
520
+ }
521
+ if (workspaceId === null || workspaceId === UNGROUPED_ID) return
522
+ // The parent row can be below the sidebar's mounted window: fall back to the
523
+ // first mounted row of the same group so the new child is still on screen.
524
+ if (beforeId === null) {
525
+ const mounted = workspaceSections().find((item) => item.workspaceId === workspaceId)
526
+ if (mounted !== undefined) {
527
+ const rows = sessionRowsIn(mounted.section)
528
+ if (rows.length > 0) beforeId = sessionIdOf(rows[0]) || null
529
+ }
530
+ }
531
+ try {
532
+ await (beforeId === null
533
+ ? workspaces.insertSessionBefore(workspaceId, childId)
534
+ : workspaces.insertSessionBefore(workspaceId, childId, beforeId))
535
+ } catch (error) {
536
+ warn('branch: could not republish sidebar membership', error)
537
+ }
538
+ }
539
+
540
+ /**
541
+ * Flash the new row as soon as the sidebar mounts it, retrying briefly.
542
+ *
543
+ * The row cannot be flashed before DSH renders it, and the Host publishes the
544
+ * republished membership asynchronously.
545
+ *
546
+ * @param childId - forked session id.
547
+ * @param attempt - retry index.
548
+ */
549
+ function revealBranchWhenReady(childId, attempt) {
550
+ const delays = [250, 600, 1200, 2400]
551
+ if (attempt >= delays.length) {
552
+ warn('branch: child row never mounted', childId)
553
+ return
554
+ }
555
+ setTimeout(() => {
556
+ if (disposed) return
557
+ void applyAll().then(() => {
558
+ if (rowOfSession(childId) === null) {
559
+ revealBranchWhenReady(childId, attempt + 1)
560
+ return
561
+ }
562
+ flashBranch(childId)
563
+ }, (error) => warn('branch: apply failed', error))
564
+ }, delays[attempt])
565
+ }
566
+
567
+ /**
568
+ * Reveal branches that appeared after the sidebar was already rendered.
569
+ *
570
+ * DSH's fork action creates the child session without opening it, and this
571
+ * plugin hides descendants of a collapsed parent, so a fork made from the
572
+ * sidebar used to look like a click that did nothing. Every session the
573
+ * first render already knew is only recorded (`seeding`); a session that
574
+ * shows up later with a parent, created within the reveal window, gets its
575
+ * whole collapsed ancestor chain expanded and is returned so the caller can
576
+ * flash it.
577
+ *
578
+ * @param sections - mounted sections whose tree has been loaded.
579
+ * @param collapsed - live collapsed set, mutated with the revealed ancestors.
580
+ * @returns session ids to flash after the rows were ordered.
581
+ */
582
+ function revealNewBranches(sections, collapsed) {
583
+ const now = Date.now()
584
+ const detached = detachedIds()
585
+ const known = new Map()
586
+ const displayParent = new Map()
587
+ for (const entry of sections) {
588
+ const tree = trees.get(entry.workspaceId)
589
+ if (tree === undefined) continue
590
+ // Expand the chain the rows actually render through, so a detached
591
+ // session is revealed next to its parent's siblings.
592
+ const parents = displayParents(tree.sessions, detached, forkLinkMap())
593
+ for (const session of tree.sessions) {
594
+ known.set(session.id, session)
595
+ displayParent.set(session.id, parents.get(session.id) ?? null)
596
+ }
597
+ }
598
+ if (!seeded) {
599
+ for (const id of known.keys()) seenSessions.add(id)
600
+ if (known.size > 0) seeded = true
601
+ return []
602
+ }
603
+ const sessions = [...known.values()]
604
+ const fresh = revealableBranches(sessions, seenSessions, { now, windowMs: REVEAL_WINDOW_MS })
605
+ if (fresh.length === 0) return fresh
606
+ let changed = false
607
+ for (const id of fresh) {
608
+ if (expandChain(id, displayParent, collapsed)) changed = true
609
+ }
610
+ if (changed) {
611
+ state = { ...state, collapsed: [...collapsed] }
612
+ scheduleSave()
613
+ }
614
+ return fresh
615
+ }
616
+
617
+ /**
618
+ * Point at one branch row: pulse it and bring it into view.
619
+ *
620
+ * @param sessionId - the session that was just revealed.
621
+ */
622
+ function flashBranch(sessionId) {
623
+ const row = rowOfSession(sessionId)
624
+ if (row === null) return
625
+ row.classList.remove('dsl-new-branch')
626
+ // Restart the animation even when the class was still attached.
627
+ void row.offsetWidth
628
+ row.classList.add('dsl-new-branch')
629
+ try {
630
+ row.scrollIntoView({ block: 'nearest' })
631
+ } catch {
632
+ /* scrolling is a courtesy, never a failure */
633
+ }
634
+ }
635
+
636
+ /**
637
+ * Interval (ms) for noticing a branch DSH's own fork action created.
638
+ */
639
+ const BRANCH_POLL_MS = 3000
640
+
641
+ let branchTimer = null
642
+ let branchPolling = false
643
+ const branchSignatures = new Map()
644
+
645
+ /**
646
+ * Keep the sidebar honest after a fork that the plugin did not initiate.
647
+ *
648
+ * DSH's own fork action (session menu, composer button, shortcut) creates
649
+ * the child and leaves the selection alone, so the only visible answer to
650
+ * the click used to be nothing. Polling the lineage tree notices the new
651
+ * member and flashes it in place, without switching the current session.
652
+ *
653
+ * The same poll repairs a row that was rendered as a root because its
654
+ * parent's fingerprint was still behind when the tree was fetched: once the
655
+ * parentage changes, the plan is applied again and the row drops into its
656
+ * parent instead of waiting for a page reload. The first poll only records
657
+ * what already exists.
658
+ */
659
+ async function pollBranches() {
660
+ if (disposed || branchPolling) return
661
+ if (document.visibilityState === 'hidden') return
662
+ const sections = workspaceSections()
663
+ if (sections.length === 0) return
664
+ branchPolling = true
665
+ try {
666
+ await ensureState()
667
+ let parentageChanged = false
668
+ for (const entry of sections) {
669
+ const ids = entry.workspaceId === UNGROUPED_ID
670
+ ? sessionRowsIn(entry).map(sessionIdOf).filter((id) => id !== '')
671
+ : undefined
672
+ const previous = trees.get(entry.workspaceId)
673
+ trees.delete(entry.workspaceId)
674
+ try {
675
+ await ensureTree(entry.workspaceId, ids)
676
+ } catch (error) {
677
+ // Keep the last good tree: dropping it would render every row as a
678
+ // root until the next successful fetch.
679
+ if (previous !== undefined) trees.set(entry.workspaceId, previous)
680
+ warn('branch watch: could not load the lineage tree', error)
681
+ continue
682
+ }
683
+ const tree = trees.get(entry.workspaceId)
684
+ if (tree === undefined) continue
685
+ const signature = tree.sessions.map((session) => `${session.id}>${session.parentId ?? ''}`).join(',')
686
+ if (branchSignatures.get(entry.workspaceId) !== signature) {
687
+ if (branchSignatures.has(entry.workspaceId)) parentageChanged = true
688
+ branchSignatures.set(entry.workspaceId, signature)
689
+ }
690
+ }
691
+ const collapsed = new Set(state.collapsed)
692
+ const revealed = revealNewBranches(sections, collapsed)
693
+ if (revealed.length === 0 && !parentageChanged) return
694
+ await applyAll()
695
+ for (const id of revealed) flashBranch(id)
696
+ } finally {
697
+ branchPolling = false
698
+ }
699
+ }
700
+
701
+ /** Attribute marking the branch button this plugin adds to a chat answer. */
702
+ const CHAT_ATTR = 'data-session-lineage-branch'
703
+ /** Fallback rescan (ms): a reused chat row can appear without a mutation. */
704
+ const CHAT_SYNC_MS = 2000
705
+
706
+ /**
707
+ * The split glyph shown in the chat action row. It is intentionally not
708
+ * DSH's branch icon: this control branches the conversation at that answer
709
+ * but never switches the open conversation.
710
+ *
711
+ * @returns an `<svg>` element.
712
+ */
713
+ function chatBranchIcon() {
714
+ const ns = 'http://www.w3.org/2000/svg'
715
+ const svg = document.createElementNS(ns, 'svg')
716
+ svg.setAttribute('viewBox', '0 0 16 16')
717
+ svg.setAttribute('fill', 'none')
718
+ svg.setAttribute('stroke', 'currentColor')
719
+ svg.setAttribute('stroke-width', '1.4')
720
+ svg.setAttribute('stroke-linecap', 'round')
721
+ svg.setAttribute('aria-hidden', 'true')
722
+ const stem = document.createElementNS(ns, 'path')
723
+ stem.setAttribute('d', 'M4 12.5V11a2 2 0 0 1 2-2h1.5')
724
+ const up = document.createElementNS(ns, 'path')
725
+ up.setAttribute('d', 'M7.5 9 11 5.5')
726
+ const down = document.createElementNS(ns, 'path')
727
+ down.setAttribute('d', 'M7.5 9 11 12.5')
728
+ const dot = document.createElementNS(ns, 'circle')
729
+ dot.setAttribute('cx', '4')
730
+ dot.setAttribute('cy', '13')
731
+ dot.setAttribute('r', '1.3')
732
+ dot.setAttribute('fill', 'currentColor')
733
+ dot.setAttribute('stroke', 'none')
734
+ svg.append(stem, up, down, dot)
735
+ return svg
736
+ }
737
+
738
+ /**
739
+ * Conversation session shown by one chat action row.
740
+ *
741
+ * @param tail - a `[data-chat-flow-kind="turn-tail"]` node.
742
+ * @returns session id or null.
743
+ */
744
+ function chatSessionOf(tail) {
745
+ const host = tail.closest('[data-conversation-session]')
746
+ const id = host?.getAttribute('data-conversation-session') ?? ''
747
+ return id === '' ? null : id
748
+ }
749
+
750
+ /**
751
+ * The action row of one finished answer (icons under the message).
752
+ *
753
+ * DSH marks this row with `data-clock` (its class names are hashed CSS
754
+ * modules), and the turn-tail wrapper carries `data-turn-tail`.
755
+ *
756
+ * @param tail - a turn-tail node.
757
+ * @returns action row element or null.
758
+ */
759
+ function chatActionRow(tail) {
760
+ return tail.querySelector('[data-clock="end"]')
761
+ ?? tail.querySelector('[data-turn-tail] [data-clock]')
762
+ ?? tail.querySelector('[data-clock]')
763
+ }
764
+
765
+ /**
766
+ * Whether the session is producing an answer right now.
767
+ *
768
+ * @param sessionId - session id.
769
+ * @returns true while running.
770
+ */
771
+ function chatSessionRunning(sessionId) {
772
+ try {
773
+ const binding = sessions?.binding?.(sessionId)
774
+ return binding?.session?.getSnapshot?.()?.running === true
775
+ } catch {
776
+ return false
777
+ }
778
+ }
779
+
780
+ /**
781
+ * Resolve the inclusive fork boundary seq of one conversation turn.
782
+ *
783
+ * DSH's fork accepts an exact event seq; the sidebar row carries the turn
784
+ * number only, so the boundary is the last `assistant/message` seq of that
785
+ * turn in the retained event window.
786
+ *
787
+ * @param sessionId - session id.
788
+ * @param turn - 1-based conversation turn.
789
+ * @returns the seq, or null when the turn is not loaded.
790
+ */
791
+ function chatTurnSeq(sessionId, turn) {
792
+ try {
793
+ const window = sessions?.binding?.(sessionId)?.eventSource?.getSnapshot?.()
794
+ return turnSeqFromEvents(window?.entries ?? [], turn)
795
+ } catch {
796
+ return null
797
+ }
798
+ }
799
+
800
+ /**
801
+ * Fork the conversation at one answer, then make the branch visible.
802
+ *
803
+ * Behaviour matches the sidebar `分支对话` item: the child is created under
804
+ * the current session, linked explicitly and revealed in place; the open
805
+ * conversation never switches, so the next click yields a sibling.
806
+ *
807
+ * @param sessionId - source session id.
808
+ * @param turn - 1-based turn the button belongs to (null forks the latest
809
+ * completed turn).
810
+ */
811
+ async function branchFromMessage(sessionId, turn) {
812
+ if (chatBranching) return
813
+ if (sessions === null || typeof sessions.fork !== 'function') {
814
+ notify('分支对话不可用:会话服务未就绪')
815
+ return
816
+ }
817
+ chatBranching = true
818
+ try {
819
+ try {
820
+ await ensureState()
821
+ } catch (error) {
822
+ warn('message branch state load failed', error)
823
+ }
824
+ // A running turn has no final answer yet: fork the latest completed turn
825
+ // instead of seeding a half-written one.
826
+ const running = chatSessionRunning(sessionId)
827
+ const seq = turn === null || running ? null : chatTurnSeq(sessionId, turn)
828
+ let childId
829
+ try {
830
+ childId = await sessions.fork({
831
+ sessionId,
832
+ ...(seq === null ? {} : { atSeq: seq }),
833
+ increaseTitle: true,
834
+ })
835
+ } catch (error) {
836
+ warn('message branch failed', error)
837
+ notify(forkFailureText(error))
838
+ return
839
+ }
840
+ if (typeof childId !== 'string' || childId === '') return
841
+ try {
842
+ recordForkLink(childId, sessionId)
843
+ await ensureBranchRowVisible(sessionId, childId)
844
+ trees.clear()
845
+ refetching.clear()
846
+ scheduleApply()
847
+ revealBranchWhenReady(childId, 0)
848
+ } catch (error) {
849
+ warn('message branch created but the sidebar was not refreshed', error)
850
+ notify('分支已创建,但侧栏刷新失败,请手动刷新一次页面')
851
+ }
852
+ } finally {
853
+ chatBranching = false
854
+ }
855
+ }
856
+
857
+ /**
858
+ * Mount the branch button on every finished answer of the open conversation.
859
+ */
860
+ function syncChatButtons() {
861
+ if (disposed) return
862
+ chatSyncPending = false
863
+ const labels = uiText()
864
+ for (const tail of document.querySelectorAll('[data-chat-flow-kind="turn-tail"]')) {
865
+ const sessionId = chatSessionOf(tail)
866
+ if (sessionId === null) continue
867
+ const row = chatActionRow(tail)
868
+ if (row === null) continue
869
+ let button = row.querySelector(`:scope > [${CHAT_ATTR}]`)
870
+ if (button === null) {
871
+ button = document.createElement('button')
872
+ button.type = 'button'
873
+ button.setAttribute(CHAT_ATTR, '')
874
+ button.className = 'dsl-chat-branch'
875
+ button.append(chatBranchIcon())
876
+ button.addEventListener('click', (event) => {
877
+ event.preventDefault()
878
+ event.stopPropagation()
879
+ const raw = tail.getAttribute('data-chat-turn') ?? ''
880
+ const turn = Number.parseInt(raw, 10)
881
+ void branchFromMessage(sessionId, Number.isFinite(turn) ? turn : null)
882
+ })
883
+ row.append(button)
884
+ }
885
+ // Only one fork in flight at a time; a running answer is fine because
886
+ // branchFromMessage falls back to the latest completed turn.
887
+ button.disabled = chatBranching
888
+ button.title = labels.forkBranch
889
+ button.setAttribute('aria-label', labels.forkBranch)
890
+ }
891
+ }
892
+
893
+ /**
894
+ * Coalesce chat DOM changes into one button sync.
895
+ */
896
+ function scheduleChatSync() {
897
+ if (disposed || chatSyncPending) return
898
+ chatSyncPending = true
899
+ setTimeout(() => {
900
+ chatSyncPending = false
901
+ syncChatButtons()
902
+ }, 120)
903
+ }
904
+
905
+ /**
906
+ * Notice chat rows React mounts, replaces, or reuses.
907
+ */
908
+ function observeChat() {
909
+ if (chatObserver !== null) return
910
+ chatObserver = new MutationObserver((records) => {
911
+ if (disposed) return
912
+ for (const record of records) {
913
+ if (record.type !== 'childList') continue
914
+ const nodes = [...record.addedNodes]
915
+ if (nodes.length === 0) continue
916
+ for (const node of nodes) {
917
+ if (!(node instanceof Element)) continue
918
+ if (node.matches('[data-chat-flow-kind="turn-tail"]')
919
+ || node.querySelector('[data-chat-flow-kind="turn-tail"]') !== null) {
920
+ scheduleChatSync()
921
+ return
922
+ }
923
+ }
924
+ }
925
+ })
926
+ chatObserver.observe(document.body, { childList: true, subtree: true })
927
+ }
928
+
929
+ /**
930
+ * Load the persisted display state once.
931
+ */
932
+ async function ensureState() {
933
+ if (stateLoaded) return
934
+ stateLoaded = true
935
+ try {
936
+ const response = await fetch(STATE_PATH, { credentials: 'same-origin' })
937
+ if (!response.ok) throw new Error(`state HTTP ${response.status}`)
938
+ const body = await response.json()
939
+ if (body && typeof body === 'object') {
940
+ state = {
941
+ version: 1,
942
+ order: body.order && typeof body.order === 'object' ? body.order : {},
943
+ collapsed: Array.isArray(body.collapsed) ? body.collapsed : [],
944
+ detached: Array.isArray(body.detached) ? body.detached : [],
945
+ forks: body.forks && typeof body.forks === 'object' && !Array.isArray(body.forks) ? body.forks : {},
946
+ display: { numbers: body.display?.numbers !== false },
947
+ }
948
+ }
949
+ } catch (error) {
950
+ warn('could not load display state', error)
951
+ }
952
+ }
953
+
954
+ /**
955
+ * Persist the display state.
956
+ */
957
+ async function saveState() {
958
+ try {
959
+ const response = await fetch(STATE_PATH, {
960
+ method: 'POST',
961
+ credentials: 'same-origin',
962
+ headers: { 'content-type': 'application/json' },
963
+ body: JSON.stringify({ state }),
964
+ })
965
+ if (!response.ok) throw new Error(`state HTTP ${response.status}`)
966
+ } catch (error) {
967
+ warn('could not save display state', error)
968
+ }
969
+ }
970
+
971
+ /**
972
+ * Schedule one debounced state save.
973
+ */
974
+ function scheduleSave() {
975
+ if (disposed) return
976
+ clearTimeout(saveTimer)
977
+ saveTimer = setTimeout(() => void saveState(), SAVE_DEBOUNCE_MS)
978
+ }
979
+
980
+ /**
981
+ * Sessions whose edge to their inferred parent is ignored in the display
982
+ * tree (they render one level higher, next to that parent).
983
+ *
984
+ * @returns detached session ids.
985
+ */
986
+ function detachedIds() {
987
+ return new Set(Array.isArray(state.detached) ? state.detached : [])
988
+ }
989
+
990
+ /**
991
+ * Explicit child-to-parent links recorded when this plugin forked a session.
992
+ *
993
+ * DSH's fork core copies the source prefix into the child log and records no
994
+ * parent id, so the inferred lineage can only recognize the parent while the
995
+ * parent's fingerprint still ends at (or before) the child's cut. A parent
996
+ * that keeps chatting grows past that cut and the child falls back to a root
997
+ * row. The plugin forks through its own menu action, so it already knows the
998
+ * exact parent and keeps that edge here.
999
+ *
1000
+ * @returns child id to parent id map.
1001
+ */
1002
+ function forkLinkMap() {
1003
+ const links = new Map()
1004
+ const source = state.forks !== null && typeof state.forks === 'object' && !Array.isArray(state.forks)
1005
+ ? state.forks
1006
+ : {}
1007
+ for (const [childId, parentId] of Object.entries(source)) {
1008
+ if (typeof parentId !== 'string' || parentId === '' || parentId === childId) continue
1009
+ links.set(childId, parentId)
1010
+ }
1011
+ return links
1012
+ }
1013
+
1014
+ /**
1015
+ * Remember one exact fork edge and persist it.
1016
+ *
1017
+ * @param childId - forked session id.
1018
+ * @param parentId - source session id.
1019
+ */
1020
+ function recordForkLink(childId, parentId) {
1021
+ if (typeof childId !== 'string' || childId === '' || typeof parentId !== 'string' || parentId === '') return
1022
+ if (childId === parentId) return
1023
+ const forks = state.forks !== null && typeof state.forks === 'object' && !Array.isArray(state.forks) ? state.forks : {}
1024
+ state = { ...state, forks: { ...forks, [childId]: parentId } }
1025
+ scheduleSave()
1026
+ }
1027
+
1028
+ /**
1029
+ * Ensure the collapse control slot of one row. Every row gets one slot so
1030
+ * sibling text starts in the same column; rows without children get an
1031
+ * invisible, non-interactive placeholder instead of a toggle.
1032
+ *
1033
+ * @param row - session row element.
1034
+ * @param sessionId - session id.
1035
+ * @param hasChildren - whether the lineage gives this session children.
1036
+ * @param isCollapsed - whether this session's subtree is collapsed.
1037
+ */
1038
+ function ensureToggle(row, sessionId, hasChildren, isCollapsed) {
1039
+ const labels = uiText()
1040
+ const glyph = isCollapsed ? '▸' : '▾'
1041
+ let element = row.querySelector(':scope > .dsl-toggle')
1042
+ const isButton = element !== null && element !== undefined && element.tagName === 'BUTTON'
1043
+ if (element !== null && element !== undefined && hasChildren === isButton) {
1044
+ if (hasChildren) {
1045
+ element.textContent = glyph
1046
+ element.setAttribute('aria-expanded', isCollapsed ? 'false' : 'true')
1047
+ element.setAttribute('aria-label', isCollapsed ? labels.expand : labels.collapse)
1048
+ }
1049
+ return
1050
+ }
1051
+ element?.remove()
1052
+ element = document.createElement(hasChildren ? 'button' : 'span')
1053
+ element.className = hasChildren ? 'dsl-toggle' : 'dsl-toggle dsl-toggle-ghost'
1054
+ if (hasChildren) {
1055
+ element.type = 'button'
1056
+ element.textContent = glyph
1057
+ element.setAttribute('aria-expanded', isCollapsed ? 'false' : 'true')
1058
+ element.setAttribute('aria-label', isCollapsed ? labels.expand : labels.collapse)
1059
+ const stop = (event) => {
1060
+ event.preventDefault()
1061
+ event.stopPropagation()
1062
+ }
1063
+ element.addEventListener('mousedown', stop)
1064
+ element.addEventListener('dblclick', stop)
1065
+ element.addEventListener('click', (event) => {
1066
+ stop(event)
1067
+ toggleCollapsed(sessionId)
1068
+ })
1069
+ } else {
1070
+ element.setAttribute('aria-hidden', 'true')
1071
+ }
1072
+ const first = row.firstElementChild
1073
+ if (first === null) row.append(element)
1074
+ else first.after(element)
1075
+ }
1076
+
1077
+ /**
1078
+ * Whether hierarchy numbers are currently displayed.
1079
+ *
1080
+ * @returns true when numbers are on (the default).
1081
+ */
1082
+ function numbersEnabled() {
1083
+ return state.display?.numbers !== false
1084
+ }
1085
+
1086
+ /**
1087
+ * Ensure the hierarchy number prefix of one row (`1.` / `3.1` / `3.1.1`).
1088
+ *
1089
+ * @param row - session row element.
1090
+ * @param number - number to display, or null to remove the prefix.
1091
+ */
1092
+ function ensureNumber(row, number) {
1093
+ let element = row.querySelector(':scope > .dsl-number')
1094
+ if (number === null) {
1095
+ element?.remove()
1096
+ return
1097
+ }
1098
+ if (element !== null && element !== undefined) {
1099
+ if (element.textContent !== number) element.textContent = number
1100
+ return
1101
+ }
1102
+ element = document.createElement('span')
1103
+ element.className = 'dsl-number'
1104
+ element.textContent = number
1105
+ const toggle = row.querySelector(':scope > .dsl-toggle')
1106
+ if (toggle !== null && toggle !== undefined) {
1107
+ toggle.after(element)
1108
+ return
1109
+ }
1110
+ const first = row.firstElementChild
1111
+ if (first === null) row.append(element)
1112
+ else first.after(element)
1113
+ }
1114
+
1115
+ /**
1116
+ * Toggle one session's subtree visibility.
1117
+ *
1118
+ * @param sessionId - session id.
1119
+ */
1120
+ function toggleCollapsed(sessionId) {
1121
+ const collapsed = new Set(state.collapsed)
1122
+ if (collapsed.has(sessionId)) collapsed.delete(sessionId)
1123
+ else collapsed.add(sessionId)
1124
+ state = { ...state, collapsed: [...collapsed] }
1125
+ scheduleSave()
1126
+ void applyAll()
1127
+ }
1128
+
1129
+ /**
1130
+ * Toggle the hierarchy-number prefix for every row.
1131
+ */
1132
+ function toggleNumbers() {
1133
+ state = { ...state, display: { numbers: !numbersEnabled() } }
1134
+ scheduleSave()
1135
+ void applyAll()
1136
+ }
1137
+
1138
+ /**
1139
+ * Toggle one session's display-level detachment: detached rows render as a
1140
+ * sibling of their parent, and their subtree follows them.
1141
+ *
1142
+ * @param sessionId - session id.
1143
+ */
1144
+ function toggleDetached(sessionId) {
1145
+ const detached = detachedIds()
1146
+ const wasDetached = detached.has(sessionId)
1147
+ if (wasDetached) detached.delete(sessionId)
1148
+ else detached.add(sessionId)
1149
+ let order = state.order
1150
+ if (!wasDetached) {
1151
+ const placement = detachPlacement(sessionId, detached)
1152
+ if (placement !== null) order = { ...state.order, [placement.parentKey]: placement.ids }
1153
+ }
1154
+ state = { ...state, order, detached: [...detached] }
1155
+ scheduleSave()
1156
+ void applyAll()
1157
+ }
1158
+
1159
+ /**
1160
+ * Order every direct child of one section, indent rows, apply collapse and
1161
+ * ensure toggles. Hierarchy numbers are assigned from the rows the sidebar
1162
+ * actually renders, so an archived (hidden) session leaves no gap.
1163
+ *
1164
+ * @param sectionEntry - `{ section, header, workspaceId }`.
1165
+ * @param plan - display plan for the workspace.
1166
+ * @param collapsed - set of collapsed session ids.
1167
+ * @returns session ids found in the DOM but missing from the plan.
1168
+ */
1169
+ function applySection(sectionEntry, plan, collapsed) {
1170
+ const { section, header } = sectionEntry
1171
+ // A HoverCard wraps real Workspace headers; the ungrouped header is a
1172
+ // direct child of the section and orders itself.
1173
+ const parent = header.parentElement
1174
+ const headerWrapper = parent === null || parent === section ? header : parent
1175
+ let fallbackOrder = plan.size + 10
1176
+ const unknown = []
1177
+ const rendered = []
1178
+ for (const child of Array.from(section.children)) {
1179
+ if (child === headerWrapper) {
1180
+ setStyle(child, 'order', '0')
1181
+ continue
1182
+ }
1183
+ if (child.getAttribute('role') === 'group') {
1184
+ setStyle(child, 'order', '1')
1185
+ continue
1186
+ }
1187
+ const row = child.getAttribute('data-row-key')?.startsWith('session:')
1188
+ ? child
1189
+ : child.querySelector('[data-row-key^="session:"]')
1190
+ if (row) {
1191
+ const id = sessionIdOf(row)
1192
+ const planned = plan.get(id)
1193
+ const wrapper = wrapperOf(row, section)
1194
+ if (planned === undefined) {
1195
+ setStyle(wrapper, 'order', String(fallbackOrder))
1196
+ fallbackOrder += 1
1197
+ removeStyle(wrapper, 'display')
1198
+ removeStyle(row, '--dsl-indent')
1199
+ ensureToggle(row, id, false, false)
1200
+ ensureNumber(row, null)
1201
+ unknown.push(id)
1202
+ continue
1203
+ }
1204
+ rendered.push({ id, planned, row, wrapper })
1205
+ continue
1206
+ }
1207
+ if (child.querySelector('[data-row-key^="overflow:"]')) {
1208
+ setStyle(child, 'order', String(OVERFLOW_ORDER))
1209
+ continue
1210
+ }
1211
+ setStyle(child, 'order', '5')
1212
+ }
1213
+ const mounted = new Set(rendered.map((item) => item.id))
1214
+ const numbers = visibleNumbers(plan, mounted)
1215
+ const collapsible = parentsWithMountedChildren(plan, mounted)
1216
+ for (const { id, planned, row, wrapper } of rendered) {
1217
+ setStyle(wrapper, 'order', String(10 + planned.orderIndex))
1218
+ setStyle(row, '--dsl-indent', `${planned.depth * INDENT_STEP}px`)
1219
+ if (planned.hidden) setStyle(wrapper, 'display', 'none')
1220
+ else removeStyle(wrapper, 'display')
1221
+ ensureToggle(row, id, collapsible.has(id), collapsed.has(id))
1222
+ ensureNumber(row, numbersEnabled() ? numbers.get(id) ?? null : null)
1223
+ }
1224
+ section.setAttribute('data-dsl-section', '')
1225
+ return unknown
1226
+ }
1227
+
1228
+ /**
1229
+ * Find one session's display sibling group across cached trees. The group
1230
+ * is keyed by the display parent, so a detached session sits with its
1231
+ * parent's siblings.
1232
+ *
1233
+ * @param sessionId - session id.
1234
+ * @param detached - set of detached session ids.
1235
+ * @returns `{ entry, node, parentKey, inferredParent, siblings, index }` or null.
1236
+ */
1237
+ function locateSiblings(sessionId, detached = detachedIds()) {
1238
+ for (const entry of trees.values()) {
1239
+ const node = entry.byId.get(sessionId)
1240
+ if (node === undefined) continue
1241
+ const parents = displayParents(entry.sessions, detached, forkLinkMap())
1242
+ const parentKey = parents.get(sessionId) ?? ROOT_KEY
1243
+ const siblings = entry.sessions.filter((item) => (parents.get(item.id) ?? ROOT_KEY) === parentKey)
1244
+ siblings.sort(siblingComparator(parentKey, new Map(), state.order))
1245
+ const index = siblings.findIndex((item) => item.id === sessionId)
1246
+ const inferredParent = typeof node.parentId === 'string' && entry.byId.has(node.parentId)
1247
+ ? node.parentId
1248
+ : null
1249
+ return { entry, node, parentKey, inferredParent, siblings, index }
1250
+ }
1251
+ return null
1252
+ }
1253
+
1254
+ /**
1255
+ * Sibling order to persist when a session is detached, so it renders
1256
+ * directly after the parent it just left even when that group already has
1257
+ * a manual order.
1258
+ *
1259
+ * @param sessionId - session being detached.
1260
+ * @param detached - detached set that already contains the session.
1261
+ * @returns `{ parentKey, ids }`, or null when the parent is not in the group.
1262
+ */
1263
+ function detachPlacement(sessionId, detached) {
1264
+ const located = locateSiblings(sessionId, detached)
1265
+ if (located === null || located.inferredParent === null) return null
1266
+ const ids = located.siblings.map((item) => item.id).filter((id) => id !== sessionId)
1267
+ const parentIndex = ids.indexOf(located.inferredParent)
1268
+ if (parentIndex < 0) return null
1269
+ ids.splice(parentIndex + 1, 0, sessionId)
1270
+ return { parentKey: located.parentKey, ids }
1271
+ }
1272
+
1273
+ /**
1274
+ * Move one session one place inside its sibling group.
1275
+ *
1276
+ * @param sessionId - session id to move.
1277
+ * @param delta - -1 for up, +1 for down.
1278
+ */
1279
+ function moveSibling(sessionId, delta) {
1280
+ const located = locateSiblings(sessionId)
1281
+ if (located === null) return
1282
+ const { parentKey, siblings, index } = located
1283
+ const target = index + delta
1284
+ if (index < 0 || target < 0 || target >= siblings.length) return
1285
+ const ids = siblings.map((item) => item.id)
1286
+ const moved = ids[index]
1287
+ ids[index] = ids[target]
1288
+ ids[target] = moved
1289
+ state = { ...state, order: { ...state.order, [parentKey]: ids } }
1290
+ scheduleSave()
1291
+ void applyAll()
1292
+ }
1293
+
1294
+ /**
1295
+ * Move one session to a fixed index inside its sibling group.
1296
+ *
1297
+ * @param sessionId - session id to move.
1298
+ * @param targetIndex - destination index in the sibling group.
1299
+ */
1300
+ function moveSiblingTo(sessionId, targetIndex) {
1301
+ const located = locateSiblings(sessionId)
1302
+ if (located === null) return
1303
+ const { parentKey, siblings, index } = located
1304
+ if (index < 0 || targetIndex < 0 || targetIndex >= siblings.length || targetIndex === index) return
1305
+ const ids = siblings.map((item) => item.id)
1306
+ const [moved] = ids.splice(index, 1)
1307
+ ids.splice(targetIndex, 0, moved)
1308
+ state = { ...state, order: { ...state.order, [parentKey]: ids } }
1309
+ scheduleSave()
1310
+ void applyAll()
1311
+ }
1312
+
1313
+ /**
1314
+ * Actions for the Session 「…」/right-click menu.
1315
+ *
1316
+ * @param sessionId - clicked session id.
1317
+ * @returns menu actions (empty when the session is not in a cached tree).
1318
+ */
1319
+ function siblingActions(sessionId) {
1320
+ const located = locateSiblings(sessionId)
1321
+ if (located === null) return []
1322
+ const labels = uiText()
1323
+ const actions = []
1324
+ const parentId = located.inferredParent
1325
+ const workspace = uiWorkspace
1326
+ if (parentId !== null && workspace !== null && typeof workspace.openSession === 'function') {
1327
+ actions.push({
1328
+ id: 'lineage.open-parent',
1329
+ label: labels.openParent,
1330
+ run: () => {
1331
+ try {
1332
+ workspace.openSession(parentId)
1333
+ } catch (error) {
1334
+ warn('could not open parent session', error)
1335
+ }
1336
+ },
1337
+ })
1338
+ }
1339
+ if (located.inferredParent !== null) {
1340
+ const isDetached = detachedIds().has(sessionId)
1341
+ actions.push({
1342
+ id: isDetached ? 'lineage.attach' : 'lineage.detach',
1343
+ label: isDetached ? labels.attach : labels.detach,
1344
+ run: () => toggleDetached(sessionId),
1345
+ })
1346
+ }
1347
+ const last = located.siblings.length - 1
1348
+ if (last >= 1) {
1349
+ actions.push(
1350
+ {
1351
+ id: 'lineage.move-first',
1352
+ label: labels.moveFirst,
1353
+ disabled: located.index <= 0,
1354
+ run: () => moveSiblingTo(sessionId, 0),
1355
+ },
1356
+ {
1357
+ id: 'lineage.move-up',
1358
+ label: labels.moveUp,
1359
+ disabled: located.index <= 0,
1360
+ run: () => moveSibling(sessionId, -1),
1361
+ },
1362
+ {
1363
+ id: 'lineage.move-down',
1364
+ label: labels.moveDown,
1365
+ disabled: located.index >= last,
1366
+ run: () => moveSibling(sessionId, 1),
1367
+ },
1368
+ {
1369
+ id: 'lineage.move-last',
1370
+ label: labels.moveLast,
1371
+ disabled: located.index >= last,
1372
+ run: () => moveSiblingTo(sessionId, last),
1373
+ },
1374
+ )
1375
+ }
1376
+ actions.push({
1377
+ id: 'lineage.toggle-numbers',
1378
+ label: numbersEnabled() ? labels.hideNumbers : labels.showNumbers,
1379
+ run: toggleNumbers,
1380
+ })
1381
+ return actions
1382
+ }
1383
+
1384
+ /**
1385
+ * Escape one session id for a CSS attribute selector.
1386
+ *
1387
+ * @param value - raw id.
1388
+ * @returns escaped id.
1389
+ */
1390
+ function cssEscape(value) {
1391
+ if (typeof CSS !== 'undefined' && typeof CSS.escape === 'function') return CSS.escape(value)
1392
+ return String(value).replace(/["\\]/g, '\\$&')
1393
+ }
1394
+
1395
+ /**
1396
+ * Row element of one session id.
1397
+ *
1398
+ * @param sessionId - session id.
1399
+ * @returns row element or null.
1400
+ */
1401
+ function rowOfSession(sessionId) {
1402
+ return document.querySelector(`[data-row-key="session:${cssEscape(sessionId)}"]`)
1403
+ }
1404
+
1405
+ /**
1406
+ * Ancestor session ids of one session on the display tree.
1407
+ *
1408
+ * @param sessionId - session id.
1409
+ * @returns ancestor ids from parent upward.
1410
+ */
1411
+ function ancestorIdsOf(sessionId) {
1412
+ const detached = detachedIds()
1413
+ for (const entry of trees.values()) {
1414
+ if (!entry.byId.has(sessionId)) continue
1415
+ const parents = displayParents(entry.sessions, detached, forkLinkMap())
1416
+ const chain = []
1417
+ const seen = new Set([sessionId])
1418
+ let parentId = parents.get(sessionId) ?? null
1419
+ while (typeof parentId === 'string' && !seen.has(parentId)) {
1420
+ seen.add(parentId)
1421
+ chain.push(parentId)
1422
+ parentId = parents.get(parentId) ?? null
1423
+ }
1424
+ return chain
1425
+ }
1426
+ return []
1427
+ }
1428
+
1429
+ /**
1430
+ * Remove the ancestor-chain highlight.
1431
+ */
1432
+ function clearAncestorHighlight() {
1433
+ for (const row of highlightedRows) row.classList.remove('dsl-ancestor')
1434
+ highlightedRows = []
1435
+ hoveredSession = null
1436
+ }
1437
+
1438
+ /**
1439
+ * Highlight the ancestor chain of one hovered session row.
1440
+ *
1441
+ * @param sessionId - hovered session id.
1442
+ */
1443
+ function updateAncestorHighlight(sessionId) {
1444
+ if (sessionId === hoveredSession) return
1445
+ for (const row of highlightedRows) row.classList.remove('dsl-ancestor')
1446
+ highlightedRows = []
1447
+ hoveredSession = sessionId
1448
+ for (const id of ancestorIdsOf(sessionId)) {
1449
+ const row = rowOfSession(id)
1450
+ if (row === null) continue
1451
+ row.classList.add('dsl-ancestor')
1452
+ highlightedRows.push(row)
1453
+ }
1454
+ }
1455
+
1456
+ /**
1457
+ * Delegated pointerover handler for the ancestor-chain highlight.
1458
+ *
1459
+ * @param event - pointer event.
1460
+ */
1461
+ function onPointerOver(event) {
1462
+ const row = event.target?.closest?.('[data-row-key^="session:"]')
1463
+ if (!row) return
1464
+ updateAncestorHighlight(sessionIdOf(row))
1465
+ }
1466
+
1467
+ /**
1468
+ * Delegated pointerout handler for the ancestor-chain highlight.
1469
+ *
1470
+ * @param event - pointer event.
1471
+ */
1472
+ function onPointerOut(event) {
1473
+ const row = event.target?.closest?.('[data-row-key^="session:"]')
1474
+ if (!row) return
1475
+ const next = event.relatedTarget
1476
+ if (next && row.contains(next)) return
1477
+ clearAncestorHighlight()
1478
+ }
1479
+
1480
+ /**
1481
+ * Drop manual order/collapse/detach entries for sessions no longer returned
1482
+ * by any loaded workspace. Only runs once every mounted workspace tree is
1483
+ * loaded, so a slow workspace never loses its saved order.
1484
+ */
1485
+ function pruneState() {
1486
+ const known = new Set()
1487
+ for (const entry of trees.values()) {
1488
+ for (const item of entry.sessions) known.add(item.id)
1489
+ }
1490
+ if (known.size === 0) return
1491
+ let changed = false
1492
+ const nextOrder = {}
1493
+ for (const [key, ids] of Object.entries(state.order)) {
1494
+ if (key !== ROOT_KEY && !known.has(key)) {
1495
+ changed = true
1496
+ continue
1497
+ }
1498
+ const filtered = Array.isArray(ids) ? ids.filter((id) => known.has(id)) : []
1499
+ if (!Array.isArray(ids) || filtered.length !== ids.length) changed = true
1500
+ nextOrder[key] = filtered
1501
+ }
1502
+ const nextCollapsed = state.collapsed.filter((id) => known.has(id))
1503
+ if (nextCollapsed.length !== state.collapsed.length) changed = true
1504
+ const nextDetached = state.detached.filter((id) => known.has(id))
1505
+ if (nextDetached.length !== state.detached.length) changed = true
1506
+ if (!changed) return
1507
+ state = { ...state, order: nextOrder, collapsed: nextCollapsed, detached: nextDetached }
1508
+ scheduleSave()
1509
+ }
1510
+
1511
+ /**
1512
+ * Apply the current lineage to every mounted workspace section.
1513
+ */
1514
+ async function applyAll() {
1515
+ if (disposed || applying) {
1516
+ if (applying) queued = true
1517
+ return
1518
+ }
1519
+ applying = true
1520
+ try {
1521
+ await ensureState()
1522
+ const collapsed = new Set(state.collapsed)
1523
+ const detached = detachedIds()
1524
+ const sections = workspaceSections().map((entry) => ({
1525
+ ...entry,
1526
+ rows: sessionRowsIn(entry.section),
1527
+ }))
1528
+ await Promise.all(sections.map(async (entry) => {
1529
+ try {
1530
+ await ensureTree(
1531
+ entry.workspaceId,
1532
+ entry.workspaceId === UNGROUPED_ID
1533
+ ? entry.rows.map(sessionIdOf).filter((id) => id !== '')
1534
+ : undefined,
1535
+ )
1536
+ } catch (error) {
1537
+ warn(`workspace ${entry.workspaceId}: lineage unavailable`, error)
1538
+ }
1539
+ }))
1540
+ let allLoaded = sections.length > 0
1541
+ // A launch opens as a plain list: every session with children starts
1542
+ // folded, so the sidebar is not a wall of branches until one is opened.
1543
+ if (!launchFolded && stateLoaded) {
1544
+ let folded = 0
1545
+ let sawTree = false
1546
+ for (const entry of sections) {
1547
+ const tree = trees.get(entry.workspaceId)
1548
+ if (tree === undefined) continue
1549
+ sawTree = true
1550
+ const parents = parentIdsWithChildren(computePlan(tree.sessions, {
1551
+ nativeRank: new Map(),
1552
+ collapsed: new Set(),
1553
+ detached,
1554
+ order: state.order,
1555
+ links: forkLinkMap(),
1556
+ }))
1557
+ for (const id of parents) {
1558
+ if (collapsed.has(id)) continue
1559
+ collapsed.add(id)
1560
+ folded += 1
1561
+ }
1562
+ }
1563
+ // Only a workspace we could read counts as the launch fold; if the
1564
+ // lineage API was down the next successful apply still folds.
1565
+ if (sawTree) launchFolded = true
1566
+ if (folded > 0) {
1567
+ state = { ...state, collapsed: [...collapsed] }
1568
+ scheduleSave()
1569
+ }
1570
+ }
1571
+ // A sidebar fork is created but never opened, so the row it produces is
1572
+ // the only feedback. Expand a collapsed ancestor chain and pulse it.
1573
+ const revealed = revealNewBranches(sections, collapsed)
1574
+ for (const entry of sections) {
1575
+ const tree = trees.get(entry.workspaceId)
1576
+ if (tree === undefined) allLoaded = false
1577
+ const rows = entry.rows
1578
+ const nativeRank = new Map(rows.map((row, index) => [sessionIdOf(row), index]))
1579
+ const plan = tree === undefined
1580
+ ? new Map()
1581
+ : computePlan(tree.sessions, { nativeRank, collapsed, detached, order: state.order, links: forkLinkMap() })
1582
+ try {
1583
+ const unknown = applySection(entry, plan, collapsed)
1584
+ if (tree !== undefined && unknown.length > 0) refetchWorkspace(entry.workspaceId)
1585
+ } catch (error) {
1586
+ warn(`workspace ${entry.workspaceId}: apply failed`, error)
1587
+ }
1588
+ }
1589
+ if (allLoaded) pruneState()
1590
+ for (const id of revealed) flashBranch(id)
1591
+ } catch (error) {
1592
+ warn('apply failed', error)
1593
+ } finally {
1594
+ applying = false
1595
+ }
1596
+ if (queued) {
1597
+ queued = false
1598
+ scheduleApply()
1599
+ }
1600
+ }
1601
+
1602
+ /**
1603
+ * Coalesce DOM mutations into one apply.
1604
+ */
1605
+ function scheduleApply() {
1606
+ if (disposed) return
1607
+ clearTimeout(applyTimer)
1608
+ applyTimer = setTimeout(() => void applyAll(), APPLY_DEBOUNCE_MS)
1609
+ }
1610
+
1611
+ /**
1612
+ * Observe the session list for rows React adds or replaces.
1613
+ *
1614
+ * The observer has to survive the sidebar being collapsed and expanded:
1615
+ * DSH unmounts the whole sidebar subtree there, so an observer bound to the
1616
+ * `[role="tree"]` element of the previous mount would go silent forever.
1617
+ * `document.body` is stable; every batch is filtered down to mutations that
1618
+ * touch the current tree (inside it, or on an ancestor that contains it), so
1619
+ * unrelated churn such as chat streaming does not trigger a re-apply.
1620
+ */
1621
+ function observe() {
1622
+ if (observer !== null) return
1623
+ observer = new MutationObserver((records) => {
1624
+ if (disposed) return
1625
+ const tree = document.querySelector('[role="tree"]')
1626
+ if (tree === null) return
1627
+ let relevant = false
1628
+ let removed = null
1629
+ for (const record of records) {
1630
+ if (record.type !== 'childList') continue
1631
+ const target = record.target
1632
+ const touchesTree = tree.contains(target)
1633
+ || (target instanceof Element && target.contains(tree))
1634
+ if (!touchesTree) continue
1635
+ if (record.addedNodes.length === 0 && record.removedNodes.length === 0) continue
1636
+ relevant = true
1637
+ if (removed !== null) continue
1638
+ for (const node of record.removedNodes) {
1639
+ const sessionId = sessionIdInNode(node)
1640
+ if (sessionId === null) continue
1641
+ const section = target instanceof Element ? target.closest('[data-dsl-section]') : null
1642
+ const workspaceId = section === null ? null : workspaceIdOfSection(section)
1643
+ if (workspaceId !== null) removed = { workspaceId, sessionId }
1644
+ break
1645
+ }
1646
+ }
1647
+ if (removed !== null) {
1648
+ const cached = trees.get(removed.workspaceId)
1649
+ if (cached !== undefined && cached.byId.has(removed.sessionId)) {
1650
+ // A row the cached tree knows disappeared natively (archive, move,
1651
+ // delete): the saved lineage may no longer be valid.
1652
+ refetchWorkspace(removed.workspaceId)
1653
+ }
1654
+ }
1655
+ if (relevant) scheduleApply()
1656
+ })
1657
+ observer.observe(document.body, { childList: true, subtree: true })
1658
+ }
1659
+
1660
+ /**
1661
+ * Refresh cached trees when the page becomes visible again, so changes made
1662
+ * while the window was hidden (archive, move, delete) are picked up.
1663
+ */
1664
+ function onVisibilityRefresh() {
1665
+ if (disposed || document.visibilityState !== 'visible') return
1666
+ const now = Date.now()
1667
+ if (now - lastFocusRefresh < FOCUS_REFRESH_MS) return
1668
+ lastFocusRefresh = now
1669
+ for (const entry of workspaceSections()) refetchWorkspace(entry.workspaceId)
1670
+ }
1671
+
1672
+ /**
1673
+ * Inject this plugin's stylesheet once.
1674
+ */
1675
+ function injectStyle() {
1676
+ if (styleEl !== null) return
1677
+ styleEl = document.createElement('style')
1678
+ styleEl.id = `${MARK}-style`
1679
+ styleEl.dataset.plugin = MARK
1680
+ styleEl.textContent = CSS
1681
+ document.head.append(styleEl)
1682
+ }
1683
+
1684
+ /**
1685
+ * Remove every trace this plugin left in the page.
1686
+ */
1687
+ function cleanup() {
1688
+ disposed = true
1689
+ clearTimeout(applyTimer)
1690
+ clearTimeout(saveTimer)
1691
+ clearInterval(branchTimer)
1692
+ branchTimer = null
1693
+ clearInterval(chatTimer)
1694
+ chatTimer = 0
1695
+ if (chatObserver !== null) {
1696
+ chatObserver.disconnect()
1697
+ chatObserver = null
1698
+ }
1699
+ for (const button of document.querySelectorAll(`[${CHAT_ATTR}]`)) button.remove()
1700
+ if (observer !== null) {
1701
+ observer.disconnect()
1702
+ observer = null
1703
+ }
1704
+ if (styleEl !== null) {
1705
+ styleEl.remove()
1706
+ styleEl = null
1707
+ }
1708
+ for (const toggle of document.querySelectorAll('.dsl-toggle')) toggle.remove()
1709
+ for (const number of document.querySelectorAll('.dsl-number')) number.remove()
1710
+ for (const section of document.querySelectorAll('[data-dsl-section]')) {
1711
+ for (const child of Array.from(section.children)) {
1712
+ child.style.removeProperty('order')
1713
+ child.style.removeProperty('display')
1714
+ }
1715
+ section.removeAttribute('data-dsl-section')
1716
+ }
1717
+ for (const row of document.querySelectorAll('[data-row-key^="session:"]')) {
1718
+ row.style.removeProperty('--dsl-indent')
1719
+ row.classList.remove('dsl-ancestor')
1720
+ row.classList.remove('dsl-new-branch')
1721
+ }
1722
+ clearAncestorHighlight()
1723
+ uiWorkspace = null
1724
+ document.body.removeEventListener('pointerover', onPointerOver)
1725
+ document.body.removeEventListener('pointerout', onPointerOut)
1726
+ document.removeEventListener('visibilitychange', onVisibilityRefresh)
1727
+ if (window.__DSH_SESSION_LINEAGE_INSTANCE__ !== undefined) delete window.__DSH_SESSION_LINEAGE_INSTANCE__
1728
+ }
1729
+
1730
+ /**
1731
+ * Mount the browser half.
1732
+ *
1733
+ * @param ctx - browser Cordis context.
1734
+ */
1735
+ function apply(ctx) {
1736
+ if (window.__DSH_SESSION_LINEAGE_INSTANCE__ !== undefined) {
1737
+ try {
1738
+ window.__DSH_SESSION_LINEAGE_INSTANCE__.dispose()
1739
+ } catch {
1740
+ /* a stale instance is simply replaced */
1741
+ }
1742
+ }
1743
+ if (!document.body) return
1744
+ injectStyle()
1745
+ observe()
1746
+ document.body.addEventListener('pointerover', onPointerOver)
1747
+ document.body.addEventListener('pointerout', onPointerOut)
1748
+ document.addEventListener('visibilitychange', onVisibilityRefresh)
1749
+ window.__DSH_SESSION_LINEAGE_INSTANCE__ = { dispose: cleanup, applyAll: () => void applyAll() }
1750
+ ctx.effect(() => () => cleanup(), `${MARK}: sidebar`)
1751
+ try {
1752
+ ctx.inject(['uiWorkspace'], (scope) => {
1753
+ uiWorkspace = scope.uiWorkspace ?? scope.get?.('uiWorkspace') ?? null
1754
+ })
1755
+ ctx.inject(['workspaces'], (scope) => {
1756
+ workspaces = scope.workspaces ?? scope.get?.('workspaces') ?? null
1757
+ })
1758
+ ctx.inject(['sessions'], (scope) => {
1759
+ sessions = scope.sessions ?? scope.get?.('sessions') ?? null
1760
+ scheduleChatSync()
1761
+ })
1762
+ } catch (error) {
1763
+ warn('workspace navigation service unavailable', error)
1764
+ }
1765
+ try {
1766
+ ctx.inject(['contextMenus'], (scope) => {
1767
+ try {
1768
+ const menus = scope.contextMenus ?? scope.get?.('contextMenus')
1769
+ if (!menus || typeof menus.register !== 'function') return
1770
+ scope.effect(() => menus.register({
1771
+ id: 'lineage.sibling-order',
1772
+ target: 'session',
1773
+ order: 400,
1774
+ resolve: (target) => siblingActions(target?.sessionId),
1775
+ }), `${MARK}: session menu`)
1776
+ } catch (error) {
1777
+ warn('session menu registration failed', error)
1778
+ }
1779
+ })
1780
+ } catch (error) {
1781
+ warn('context menu service unavailable', error)
1782
+ }
1783
+ try {
1784
+ ctx.inject(['contextMenus'], (scope) => {
1785
+ try {
1786
+ const menus = scope.contextMenus ?? scope.get?.('contextMenus')
1787
+ if (!menus || typeof menus.register !== 'function') return
1788
+ scope.effect(() => menus.register({
1789
+ id: 'lineage.branch-chat',
1790
+ target: 'session',
1791
+ order: 290,
1792
+ resolve: (target) => {
1793
+ const sessionId = target?.sessionId
1794
+ if (typeof sessionId !== 'string' || sessionId === '') return []
1795
+ return [{
1796
+ id: 'lineage.branch-chat',
1797
+ label: uiText().forkBranch,
1798
+ run: () => { void branchFromHere(sessionId) },
1799
+ }]
1800
+ },
1801
+ }), `${MARK}: branch menu`)
1802
+ } catch (error) {
1803
+ warn('branch menu registration failed', error)
1804
+ }
1805
+ })
1806
+ } catch (error) {
1807
+ warn('branch menu service unavailable', error)
1808
+ }
1809
+ scheduleApply()
1810
+ branchTimer = setInterval(() => { void pollBranches() }, BRANCH_POLL_MS)
1811
+ observeChat()
1812
+ syncChatButtons()
1813
+ chatTimer = setInterval(syncChatButtons, CHAT_SYNC_MS)
1814
+ }
1815
+
1816
+ return { inject: [], apply }
1817
+ },
1818
+ })
1819
+
1820
+ /**
1821
+ * Build the sibling comparator for one parent group: the saved manual order
1822
+ * first, then creation time, then the native DOM index as the last tie-break.
1823
+ *
1824
+ * @param parentKey - parent id or {@link ROOT_KEY}.
1825
+ * @param nativeRank - session id to native DOM index.
1826
+ * @param order - saved manual sibling order (`state.order`).
1827
+ * @returns comparator over lineage nodes.
1828
+ */
1829
+ function siblingComparator(parentKey, nativeRank, order) {
1830
+ const manual = Array.isArray(order[parentKey]) ? order[parentKey] : []
1831
+ const manualRank = new Map(manual.map((id, index) => [id, index]))
1832
+ return (left, right) => {
1833
+ const leftManual = manualRank.get(left.id)
1834
+ const rightManual = manualRank.get(right.id)
1835
+ if (leftManual !== undefined || rightManual !== undefined) {
1836
+ const a = leftManual === undefined ? Number.POSITIVE_INFINITY : leftManual
1837
+ const b = rightManual === undefined ? Number.POSITIVE_INFINITY : rightManual
1838
+ if (a !== b) return a - b
1839
+ }
1840
+ const leftCreated = Number(left.createdAt)
1841
+ const rightCreated = Number(right.createdAt)
1842
+ if (leftCreated !== rightCreated) return leftCreated - rightCreated
1843
+ const a = nativeRank.get(left.id) ?? Number.POSITIVE_INFINITY
1844
+ const b = nativeRank.get(right.id) ?? Number.POSITIVE_INFINITY
1845
+ return a - b
1846
+ }
1847
+ }
1848
+
1849
+ /**
1850
+ * Display parent of every session: normally the inferred parent, but a
1851
+ * detached session skips its parent and hangs under that parent's own display
1852
+ * parent instead (one level up, next to the parent). Detaching several sessions
1853
+ * composes; ids without a usable inferred parent stay roots.
1854
+ *
1855
+ * @param sessions - lineage nodes of one workspace or section.
1856
+ * @param detached - set of detached session ids.
1857
+ * @param links - explicit child to parent edges recorded at fork time.
1858
+ * @returns session id to display parent id (null for a root).
1859
+ */
1860
+ function displayParents(sessions, detached, links = null) {
1861
+ const known = new Set(sessions.map((item) => item.id))
1862
+ const inferred = new Map()
1863
+ const exact = links instanceof Map ? links : null
1864
+ for (const node of sessions) {
1865
+ const recorded = exact === null ? undefined : exact.get(node.id)
1866
+ const parentId = typeof recorded === 'string' && recorded !== node.id && known.has(recorded)
1867
+ ? recorded
1868
+ : typeof node.parentId === 'string' && known.has(node.parentId) ? node.parentId : null
1869
+ inferred.set(node.id, parentId)
1870
+ }
1871
+ const memo = new Map()
1872
+ const resolve = (id) => {
1873
+ if (memo.has(id)) return memo.get(id)
1874
+ const parentId = inferred.get(id) ?? null
1875
+ const result = parentId === null ? null : detached.has(id) ? resolve(parentId) : parentId
1876
+ memo.set(id, result)
1877
+ return result
1878
+ }
1879
+ const parents = new Map()
1880
+ for (const node of sessions) parents.set(node.id, resolve(node.id))
1881
+ return parents
1882
+ }
1883
+
1884
+ /**
1885
+ * Preorder display plan: `sessionId -> { orderIndex, depth, hasChildren, hidden, parent }`.
1886
+ *
1887
+ * @param sessions - lineage nodes of one workspace or section.
1888
+ * @param options - `nativeRank`, `collapsed`, `detached`, the manual `order` and recorded `links`.
1889
+ * @returns display plan map.
1890
+ */
1891
+ function computePlan(sessions, { nativeRank, collapsed, detached, order, links = null }) {
1892
+ const plan = new Map()
1893
+ const parents = displayParents(sessions, detached, links)
1894
+ const childrenByParent = new Map()
1895
+ for (const node of sessions) {
1896
+ const key = parents.get(node.id) ?? ROOT_KEY
1897
+ const siblings = childrenByParent.get(key)
1898
+ if (siblings === undefined) childrenByParent.set(key, [node])
1899
+ else siblings.push(node)
1900
+ }
1901
+ let orderIndex = 0
1902
+ const visit = (node, depth, hidden) => {
1903
+ const children = childrenByParent.get(node.id) ?? []
1904
+ plan.set(node.id, {
1905
+ orderIndex,
1906
+ depth,
1907
+ hasChildren: children.length > 0,
1908
+ hidden,
1909
+ parent: parents.get(node.id) ?? null,
1910
+ })
1911
+ orderIndex += 1
1912
+ children.sort(siblingComparator(node.id, nativeRank, order))
1913
+ const childHidden = hidden || collapsed.has(node.id)
1914
+ for (const child of children) visit(child, depth + 1, childHidden)
1915
+ }
1916
+ const roots = childrenByParent.get(ROOT_KEY) ?? []
1917
+ roots.sort(siblingComparator(ROOT_KEY, nativeRank, order))
1918
+ for (const root of roots) visit(root, 0, false)
1919
+ return plan
1920
+ }
1921
+
1922
+ /**
1923
+ * Hierarchy numbers for the rows actually rendered in one section. A row the
1924
+ * sidebar filtered out (an archived row while the archive filter hides it, a
1925
+ * row not mounted yet) keeps its display order but does not consume a number;
1926
+ * a rendered row whose parent is filtered out numbers as a root.
1927
+ *
1928
+ * @param plan - display plan for the workspace.
1929
+ * @param mounted - ids of the session rows present in the DOM.
1930
+ * @returns session id to its `1.` / `2.1` number.
1931
+ */
1932
+ function visibleNumbers(plan, mounted) {
1933
+ const ordered = [...plan.entries()].sort((left, right) => left[1].orderIndex - right[1].orderIndex)
1934
+ const numbers = new Map()
1935
+ const nextOrdinal = new Map()
1936
+ for (const [id, node] of ordered) {
1937
+ if (!mounted.has(id)) continue
1938
+ const parentNumber = node.parent === null ? undefined : numbers.get(node.parent)
1939
+ if (parentNumber === undefined) {
1940
+ const ordinal = (nextOrdinal.get(null) ?? 0) + 1
1941
+ nextOrdinal.set(null, ordinal)
1942
+ numbers.set(id, `${ordinal}.`)
1943
+ continue
1944
+ }
1945
+ const ordinal = (nextOrdinal.get(node.parent) ?? 0) + 1
1946
+ nextOrdinal.set(node.parent, ordinal)
1947
+ const base = parentNumber.endsWith('.') ? parentNumber.slice(0, -1) : parentNumber
1948
+ numbers.set(id, `${base}.${ordinal}`)
1949
+ }
1950
+ return numbers
1951
+ }
1952
+
1953
+ /**
1954
+ * Parents that own at least one mounted child row. The collapse arrow belongs to
1955
+ * these rows only: a parent whose children are all filtered out (hidden behind
1956
+ * the sidebar's session watermark, archived, or in another section) has nothing
1957
+ * visible to collapse, so an arrow there is a dead end.
1958
+ *
1959
+ * @param plan - display plan for the workspace.
1960
+ * @param mounted - ids of the session rows present in the DOM.
1961
+ * @returns parent ids that have at least one mounted child.
1962
+ */
1963
+ function parentsWithMountedChildren(plan, mounted) {
1964
+ const parents = new Set()
1965
+ for (const [id, node] of plan) {
1966
+ if (node.parent === null || !mounted.has(id)) continue
1967
+ parents.add(node.parent)
1968
+ }
1969
+ return parents
1970
+ }
1971
+
1972
+ /**
1973
+ * Every session that owns at least one child in the display plan.
1974
+ *
1975
+ * A launch folds these so the sidebar opens as a flat list of conversations.
1976
+ *
1977
+ * @param plan - display plan for the workspace.
1978
+ * @returns ids of all parent sessions.
1979
+ */
1980
+ function parentIdsWithChildren(plan) {
1981
+ const parents = new Set()
1982
+ for (const [id, node] of plan) {
1983
+ if (node.hasChildren) parents.add(id)
1984
+ }
1985
+ return parents
1986
+ }
1987
+
1988
+ /**
1989
+ * Inclusive fork boundary of one conversation turn in a retained event window.
1990
+ *
1991
+ * The chat row only knows the turn number; DSH's fork takes an exact event seq.
1992
+ * The last `assistant/message` event of that turn is the boundary the native
1993
+ * per-message branch button uses, so the child starts with exactly that answer.
1994
+ *
1995
+ * @param entries - retained session event window entries.
1996
+ * @param turn - 1-based conversation turn.
1997
+ * @returns the boundary seq, or null when that turn is not loaded.
1998
+ */
1999
+ function turnSeqFromEvents(entries, turn) {
2000
+ if (!Array.isArray(entries) || !Number.isSafeInteger(turn)) return null
2001
+ let seq = null
2002
+ for (const entry of entries) {
2003
+ if (entry === null || typeof entry !== 'object' || entry.type !== 'event') continue
2004
+ const event = entry.event
2005
+ if (event === null || typeof event !== 'object' || event.type !== 'assistant/message') continue
2006
+ if (event.data?.turn !== turn) continue
2007
+ if (typeof event.seq !== 'number') continue
2008
+ if (seq === null || event.seq > seq) seq = event.seq
2009
+ }
2010
+ return seq
2011
+ }
2012
+
2013
+ /**
2014
+ * Sessions to reveal because they appeared after the sidebar was rendered.
2015
+ *
2016
+ * DSH's fork action creates the child session without opening it, so the only
2017
+ * feedback is the new sidebar row. Rows present on the first render are only
2018
+ * recorded in `seen` (`seeding`, never revealed); a session that shows up
2019
+ * later, carries a parent and was created inside the reveal window is a branch
2020
+ * born while the page was open.
2021
+ *
2022
+ * @param sessions - lineage nodes of the loaded trees.
2023
+ * @param seen - ids already rendered; mutated with every id in `sessions`.
2024
+ * @param options - `seeding`, `now` and `windowMs`.
2025
+ * @returns ids of the branches to reveal.
2026
+ */
2027
+ function revealableBranches(sessions, seen, { seeding = false, now = Date.now(), windowMs = 300000 } = {}) {
2028
+ const revealed = []
2029
+ for (const session of sessions) {
2030
+ if (session === null || typeof session !== 'object') continue
2031
+ const id = session.id
2032
+ if (typeof id !== 'string' || id === '') continue
2033
+ const isNew = !seen.has(id)
2034
+ seen.add(id)
2035
+ if (!isNew || seeding) continue
2036
+ if (typeof session.parentId !== 'string' || session.parentId === '') continue
2037
+ const created = typeof session.createdAt === 'number' ? session.createdAt : Date.parse(session.createdAt)
2038
+ if (!Number.isFinite(created) || now - created > windowMs) continue
2039
+ revealed.push(id)
2040
+ }
2041
+ return revealed
2042
+ }
2043
+
2044
+ /**
2045
+ * Expand every collapsed ancestor a session renders under, so its row becomes
2046
+ * visible. Follows the display chain, not the inferred one, so a session shown
2047
+ * next to its parent (`detached`) expands what is actually above it.
2048
+ *
2049
+ * @param sessionId - the session to reveal.
2050
+ * @param displayParent - session id to display parent id (null for a root).
2051
+ * @param collapsed - collapsed set, mutated in place.
2052
+ * @returns true when at least one ancestor was expanded.
2053
+ */
2054
+ function expandChain(sessionId, displayParent, collapsed) {
2055
+ let changed = false
2056
+ let current = displayParent.get(sessionId) ?? null
2057
+ const guard = new Set([sessionId])
2058
+ while (typeof current === 'string' && !guard.has(current)) {
2059
+ guard.add(current)
2060
+ if (collapsed.has(current)) {
2061
+ collapsed.delete(current)
2062
+ changed = true
2063
+ }
2064
+ current = displayParent.get(current) ?? null
2065
+ }
2066
+ return changed
2067
+ }
2068
+
2069
+ // Node tests import this file directly; the browser never sees this hook.
2070
+ if (typeof window === 'undefined') {
2071
+ globalThis.__DSH_SESSION_LINEAGE_TEST__ = {
2072
+ computePlan,
2073
+ displayParents,
2074
+ siblingComparator,
2075
+ visibleNumbers,
2076
+ parentsWithMountedChildren,
2077
+ parentIdsWithChildren,
2078
+ revealableBranches,
2079
+ expandChain,
2080
+ turnSeqFromEvents,
2081
+ }
2082
+ }