dsh-session-lineage 0.0.0-stage → 1.0.2

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,920 @@
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. Native drag reordering is intentionally not adopted (v1): the
8
+ * sidebar keeps its durable order while this plugin owns the displayed order.
9
+ *
10
+ * Integration surface is the official row-key DOM contract only:
11
+ * [role="tree"] the session list root
12
+ * [data-row-key="workspace:<id>"] a workspace header (inside its HoverCard wrapper)
13
+ * [data-row-key="session:<id>"] a session row (inside a HoverCard wrapper)
14
+ * [data-row-key="overflow:<key>"] the "show more" row
15
+ * Hashed CSS-module class names are never used.
16
+ */
17
+
18
+ window.__ModuleLoader__.load({
19
+ id: 'dsh-session-lineage',
20
+ factory() {
21
+ const MARK = 'dsh-session-lineage'
22
+ const TREE_PATH = '/api/session-lineage'
23
+ const STATE_PATH = '/api/session-lineage.state'
24
+ const INDENT_STEP = 14
25
+ const ROOT_KEY = 'root'
26
+ const OVERFLOW_ORDER = 100000
27
+ const APPLY_DEBOUNCE_MS = 150
28
+ const SAVE_DEBOUNCE_MS = 300
29
+ const REFETCH_DELAY_MS = 600
30
+ const FOCUS_REFRESH_MS = 60000
31
+
32
+ /** Localized labels for the controls this plugin adds. */
33
+ const UI_TEXT = {
34
+ zh: { moveUp: '同级上移', moveDown: '同级下移', expand: '展开分支', collapse: '收起分支' },
35
+ en: { moveUp: 'Move up', moveDown: 'Move down', expand: 'Expand branch', collapse: 'Collapse branch' },
36
+ }
37
+
38
+ /**
39
+ * Labels for the current interface language.
40
+ *
41
+ * @returns `{ moveUp, moveDown, expand, collapse }`.
42
+ */
43
+ function uiText() {
44
+ const language = document.documentElement.lang || navigator.language || 'zh'
45
+ return language.toLowerCase().startsWith('zh') ? UI_TEXT.zh : UI_TEXT.en
46
+ }
47
+
48
+ /**
49
+ * Write one inline style only when it actually changes.
50
+ *
51
+ * @param element - target element.
52
+ * @param property - CSS property name.
53
+ * @param value - desired value.
54
+ */
55
+ function setStyle(element, property, value) {
56
+ if (element.style.getPropertyValue(property) !== value) element.style.setProperty(property, value)
57
+ }
58
+
59
+ /**
60
+ * Remove one inline style only when it is present.
61
+ *
62
+ * @param element - target element.
63
+ * @param property - CSS property name.
64
+ */
65
+ function removeStyle(element, property) {
66
+ if (element.style.getPropertyValue(property) !== '') element.style.removeProperty(property)
67
+ }
68
+
69
+ const CSS = `
70
+ [data-dsl-section] { display: flex !important; flex-direction: column; }
71
+ [data-row-key^="session:"] {
72
+ padding-inline-start: calc(
73
+ var(--dsh-sidebar-row-padding, 12px) - var(--dsh-sidebar-paint-inset, 3px) +
74
+ var(--dsh-workspace-indent, 0px) + var(--dsl-indent, 0px)
75
+ ) !important;
76
+ }
77
+ .dsl-toggle {
78
+ flex: none;
79
+ display: inline-flex;
80
+ align-items: center;
81
+ justify-content: center;
82
+ width: 16px;
83
+ height: 16px;
84
+ margin-inline-end: 2px;
85
+ padding: 0;
86
+ border: 0;
87
+ border-radius: 4px;
88
+ background: transparent;
89
+ color: var(--dsw-alias-label-secondary, #5f6368);
90
+ font: 12px/1 var(--dsw-font-family, system-ui, sans-serif);
91
+ cursor: pointer;
92
+ }
93
+ .dsl-toggle:hover {
94
+ color: var(--dsw-alias-state-business-primary, #2563eb);
95
+ background: var(--dsw-alias-interactive-bg-hover, rgba(0,0,0,0.06));
96
+ }
97
+ .dsl-toggle-ghost { visibility: hidden; pointer-events: none; }
98
+ /* C: a guide rail for every ancestor level the row is indented through. */
99
+ [data-row-key^="session:"] {
100
+ --dsl-rail: color-mix(in srgb, var(--dsw-alias-label-tertiary, #8a8f98) 35%, transparent);
101
+ background-image: repeating-linear-gradient(
102
+ to right,
103
+ transparent 0 13px,
104
+ var(--dsl-rail) 13px 14px
105
+ );
106
+ background-repeat: no-repeat;
107
+ background-origin: border-box;
108
+ background-position-x: calc(var(--dsh-sidebar-row-padding, 12px) + var(--dsh-workspace-indent, 0px));
109
+ background-size: calc(max(0px, (var(--dsl-depth, 0) - 1) * 14px)) 100%;
110
+ }
111
+ /* D: hovering a descendant lights up its whole ancestor chain. */
112
+ .dsl-ancestor {
113
+ background-color: color-mix(in srgb, var(--dsw-alias-state-business-primary, #2563eb) 12%, transparent);
114
+ }
115
+ `
116
+
117
+ let disposed = false
118
+ let applying = false
119
+ let queued = false
120
+ let observer = null
121
+ let styleEl = null
122
+ let applyTimer = 0
123
+ let saveTimer = 0
124
+ let stateLoaded = false
125
+ let state = { version: 1, order: {}, collapsed: [] }
126
+ let hoveredSession = null
127
+ let highlightedRows = []
128
+ let lastFocusRefresh = 0
129
+ const trees = new Map()
130
+ const refetching = new Set()
131
+
132
+ /**
133
+ * Log one degradation without throwing at the caller.
134
+ *
135
+ * @param message - diagnostic text.
136
+ * @param error - optional failure.
137
+ */
138
+ function warn(message, error) {
139
+ console.warn(`[${MARK}] ${message}`, error === undefined ? '' : error)
140
+ }
141
+
142
+ /**
143
+ * Discover workspace sections from their header rows.
144
+ *
145
+ * @returns `{ section, header, workspaceId }` per workspace header.
146
+ */
147
+ function workspaceSections() {
148
+ const sections = []
149
+ for (const header of document.querySelectorAll('[data-row-key^="workspace:"]')) {
150
+ const wrapper = header.parentElement
151
+ const section = wrapper?.parentElement
152
+ const workspaceId = header.getAttribute('data-row-key')?.slice('workspace:'.length) ?? ''
153
+ if (!wrapper || !section || workspaceId === '') continue
154
+ sections.push({ section, header, workspaceId })
155
+ }
156
+ return sections
157
+ }
158
+
159
+ /**
160
+ * The section an element belongs to: the node whose parent is the tree or a
161
+ * nested workspace group.
162
+ *
163
+ * @param element - any sidebar element.
164
+ * @returns section element or null.
165
+ */
166
+ function sectionOfElement(element) {
167
+ let node = element.parentElement
168
+ for (let depth = 0; node && depth < 6; depth += 1) {
169
+ const parent = node.parentElement
170
+ if (!parent) return node
171
+ const role = parent.getAttribute('role')
172
+ if (role === 'tree' || role === 'group') return node
173
+ node = parent
174
+ }
175
+ return null
176
+ }
177
+
178
+ /**
179
+ * Session rows that belong to exactly this section (nested workspaces excluded).
180
+ *
181
+ * @param section - workspace section element.
182
+ * @returns session row elements in DOM order.
183
+ */
184
+ function sessionRowsIn(section) {
185
+ return Array.from(section.querySelectorAll('[data-row-key^="session:"]')).filter(
186
+ (row) => sectionOfElement(row) === section,
187
+ )
188
+ }
189
+
190
+ /**
191
+ * The flex item carrying `order` for one session row.
192
+ *
193
+ * @param row - session row element.
194
+ * @param section - owning section.
195
+ * @returns wrapper element (the row itself when it is a direct child).
196
+ */
197
+ function wrapperOf(row, section) {
198
+ const parent = row.parentElement
199
+ if (!parent || parent === section) return row
200
+ return parent
201
+ }
202
+
203
+ /**
204
+ * Session id encoded in a row's data attribute.
205
+ *
206
+ * @param row - session row element.
207
+ * @returns session id or ''.
208
+ */
209
+ function sessionIdOf(row) {
210
+ const key = row.getAttribute('data-row-key') ?? ''
211
+ return key.startsWith('session:') ? key.slice('session:'.length) : ''
212
+ }
213
+
214
+ /**
215
+ * Workspace id of one workspace section element.
216
+ *
217
+ * @param section - element carrying `data-dsl-section`.
218
+ * @returns workspace id or null.
219
+ */
220
+ function workspaceIdOfSection(section) {
221
+ const header = section.querySelector('[data-row-key^="workspace:"]')
222
+ const key = header?.getAttribute('data-row-key') ?? ''
223
+ return key.startsWith('workspace:') ? key.slice('workspace:'.length) : null
224
+ }
225
+
226
+ /**
227
+ * Session id carried by one removed DOM node, if any.
228
+ *
229
+ * @param node - removed node.
230
+ * @returns session id or null.
231
+ */
232
+ function sessionIdInNode(node) {
233
+ if (!(node instanceof Element)) return null
234
+ const row = node.matches('[data-row-key^="session:"]')
235
+ ? node
236
+ : node.querySelector('[data-row-key^="session:"]')
237
+ return row === null ? null : sessionIdOf(row) || null
238
+ }
239
+
240
+ /**
241
+ * Load one workspace's lineage once and cache it.
242
+ *
243
+ * @param workspaceId - DSH workspace id.
244
+ * @returns `{ sessions, byId }`.
245
+ */
246
+ async function ensureTree(workspaceId) {
247
+ const cached = trees.get(workspaceId)
248
+ if (cached !== undefined) return cached
249
+ const response = await fetch(`${TREE_PATH}?workspaceId=${encodeURIComponent(workspaceId)}`, {
250
+ credentials: 'same-origin',
251
+ })
252
+ if (!response.ok) throw new Error(`lineage HTTP ${response.status}`)
253
+ const body = await response.json()
254
+ const sessions = Array.isArray(body?.sessions) ? body.sessions : []
255
+ const entry = { sessions, byId: new Map(sessions.map((item) => [item.id, item])) }
256
+ trees.set(workspaceId, entry)
257
+ return entry
258
+ }
259
+
260
+ /**
261
+ * Drop one cached tree and apply again after the debounce delay, so a fresh
262
+ * fork (a row the cached tree does not know yet) ends up under its parent.
263
+ *
264
+ * @param workspaceId - workspace whose cache is stale.
265
+ */
266
+ function refetchWorkspace(workspaceId) {
267
+ if (refetching.has(workspaceId)) return
268
+ refetching.add(workspaceId)
269
+ setTimeout(() => {
270
+ trees.delete(workspaceId)
271
+ refetching.delete(workspaceId)
272
+ scheduleApply()
273
+ }, REFETCH_DELAY_MS)
274
+ }
275
+
276
+ /**
277
+ * Load the persisted display state once.
278
+ */
279
+ async function ensureState() {
280
+ if (stateLoaded) return
281
+ stateLoaded = true
282
+ try {
283
+ const response = await fetch(STATE_PATH, { credentials: 'same-origin' })
284
+ if (!response.ok) throw new Error(`state HTTP ${response.status}`)
285
+ const body = await response.json()
286
+ if (body && typeof body === 'object') {
287
+ state = {
288
+ version: 1,
289
+ order: body.order && typeof body.order === 'object' ? body.order : {},
290
+ collapsed: Array.isArray(body.collapsed) ? body.collapsed : [],
291
+ }
292
+ }
293
+ } catch (error) {
294
+ warn('could not load display state', error)
295
+ }
296
+ }
297
+
298
+ /**
299
+ * Persist the display state.
300
+ */
301
+ async function saveState() {
302
+ try {
303
+ const response = await fetch(STATE_PATH, {
304
+ method: 'POST',
305
+ credentials: 'same-origin',
306
+ headers: { 'content-type': 'application/json' },
307
+ body: JSON.stringify({ state }),
308
+ })
309
+ if (!response.ok) throw new Error(`state HTTP ${response.status}`)
310
+ } catch (error) {
311
+ warn('could not save display state', error)
312
+ }
313
+ }
314
+
315
+ /**
316
+ * Schedule one debounced state save.
317
+ */
318
+ function scheduleSave() {
319
+ if (disposed) return
320
+ clearTimeout(saveTimer)
321
+ saveTimer = setTimeout(() => void saveState(), SAVE_DEBOUNCE_MS)
322
+ }
323
+
324
+ /**
325
+ * Build the sibling comparator for one parent group.
326
+ *
327
+ * @param parentKey - parent id or {@link ROOT_KEY}.
328
+ * @param nativeRank - session id to native DOM index.
329
+ * @returns comparator over lineage nodes.
330
+ */
331
+ function siblingComparator(parentKey, nativeRank) {
332
+ const manual = Array.isArray(state.order[parentKey]) ? state.order[parentKey] : []
333
+ const manualRank = new Map(manual.map((id, index) => [id, index]))
334
+ return (left, right) => {
335
+ const leftManual = manualRank.get(left.id)
336
+ const rightManual = manualRank.get(right.id)
337
+ if (leftManual !== undefined || rightManual !== undefined) {
338
+ const a = leftManual === undefined ? Number.POSITIVE_INFINITY : leftManual
339
+ const b = rightManual === undefined ? Number.POSITIVE_INFINITY : rightManual
340
+ if (a !== b) return a - b
341
+ }
342
+ const leftCreated = Number(left.createdAt)
343
+ const rightCreated = Number(right.createdAt)
344
+ if (leftCreated !== rightCreated) return leftCreated - rightCreated
345
+ const a = nativeRank.get(left.id) ?? Number.POSITIVE_INFINITY
346
+ const b = nativeRank.get(right.id) ?? Number.POSITIVE_INFINITY
347
+ return a - b
348
+ }
349
+ }
350
+
351
+ /**
352
+ * Sibling group a lineage node belongs to.
353
+ *
354
+ * @param node - lineage node.
355
+ * @param known - ids present in the same tree.
356
+ * @returns parent id or {@link ROOT_KEY}.
357
+ */
358
+ function parentKeyOf(node, known) {
359
+ if (node.parentId === null || !known.has(node.parentId)) return ROOT_KEY
360
+ return node.parentId
361
+ }
362
+
363
+ /**
364
+ * Preorder display plan: `sessionId -> { orderIndex, depth, hasChildren, hidden }`.
365
+ *
366
+ * @param entry - cached tree entry.
367
+ * @param nativeRank - session id to native DOM index.
368
+ * @param collapsed - set of collapsed session ids.
369
+ * @returns display plan map.
370
+ */
371
+ function computePlan(entry, nativeRank, collapsed) {
372
+ const plan = new Map()
373
+ const sessions = entry.sessions
374
+ const known = new Set(sessions.map((item) => item.id))
375
+ const childrenByParent = new Map()
376
+ for (const node of sessions) {
377
+ const key = parentKeyOf(node, known)
378
+ const siblings = childrenByParent.get(key)
379
+ if (siblings === undefined) childrenByParent.set(key, [node])
380
+ else siblings.push(node)
381
+ }
382
+ let orderIndex = 0
383
+ const visit = (node, depth, hidden) => {
384
+ const children = childrenByParent.get(node.id) ?? []
385
+ plan.set(node.id, {
386
+ orderIndex,
387
+ depth,
388
+ hasChildren: children.length > 0,
389
+ hidden,
390
+ })
391
+ orderIndex += 1
392
+ children.sort(siblingComparator(node.id, nativeRank))
393
+ const childHidden = hidden || collapsed.has(node.id)
394
+ for (const child of children) visit(child, depth + 1, childHidden)
395
+ }
396
+ const roots = childrenByParent.get(ROOT_KEY) ?? []
397
+ roots.sort(siblingComparator(ROOT_KEY, nativeRank))
398
+ for (const root of roots) visit(root, 0, false)
399
+ return plan
400
+ }
401
+
402
+ /**
403
+ * Ensure the collapse control slot of one row. Every row gets one slot so
404
+ * sibling text starts in the same column; rows without children get an
405
+ * invisible, non-interactive placeholder instead of a toggle.
406
+ *
407
+ * @param row - session row element.
408
+ * @param sessionId - session id.
409
+ * @param hasChildren - whether the lineage gives this session children.
410
+ * @param isCollapsed - whether this session's subtree is collapsed.
411
+ */
412
+ function ensureToggle(row, sessionId, hasChildren, isCollapsed) {
413
+ const labels = uiText()
414
+ let element = row.querySelector(':scope > .dsl-toggle')
415
+ const isButton = element !== null && element !== undefined && element.tagName === 'BUTTON'
416
+ if (element !== null && element !== undefined && hasChildren === isButton) {
417
+ if (hasChildren) {
418
+ element.textContent = isCollapsed ? '▸' : '▾'
419
+ element.setAttribute('aria-expanded', isCollapsed ? 'false' : 'true')
420
+ element.setAttribute('aria-label', isCollapsed ? labels.expand : labels.collapse)
421
+ }
422
+ return
423
+ }
424
+ element?.remove()
425
+ element = document.createElement(hasChildren ? 'button' : 'span')
426
+ element.className = hasChildren ? 'dsl-toggle' : 'dsl-toggle dsl-toggle-ghost'
427
+ if (hasChildren) {
428
+ element.type = 'button'
429
+ element.textContent = isCollapsed ? '▸' : '▾'
430
+ element.setAttribute('aria-expanded', isCollapsed ? 'false' : 'true')
431
+ element.setAttribute('aria-label', isCollapsed ? labels.expand : labels.collapse)
432
+ const stop = (event) => {
433
+ event.preventDefault()
434
+ event.stopPropagation()
435
+ }
436
+ element.addEventListener('mousedown', stop)
437
+ element.addEventListener('dblclick', stop)
438
+ element.addEventListener('click', (event) => {
439
+ stop(event)
440
+ toggleCollapsed(sessionId)
441
+ })
442
+ } else {
443
+ element.setAttribute('aria-hidden', 'true')
444
+ }
445
+ const first = row.firstElementChild
446
+ if (first === null) row.append(element)
447
+ else first.after(element)
448
+ }
449
+
450
+ /**
451
+ * Toggle one session's subtree visibility.
452
+ *
453
+ * @param sessionId - session id.
454
+ */
455
+ function toggleCollapsed(sessionId) {
456
+ const collapsed = new Set(state.collapsed)
457
+ if (collapsed.has(sessionId)) collapsed.delete(sessionId)
458
+ else collapsed.add(sessionId)
459
+ state = { ...state, collapsed: [...collapsed] }
460
+ scheduleSave()
461
+ void applyAll()
462
+ }
463
+
464
+ /**
465
+ * Order every direct child of one section, indent rows, apply collapse and
466
+ * ensure toggles.
467
+ *
468
+ * @param sectionEntry - `{ section, header, workspaceId }`.
469
+ * @param plan - display plan for the workspace.
470
+ * @param collapsed - set of collapsed session ids.
471
+ * @returns session ids found in the DOM but missing from the plan.
472
+ */
473
+ function applySection(sectionEntry, plan, collapsed) {
474
+ const { section, header } = sectionEntry
475
+ const headerWrapper = header.parentElement ?? header
476
+ let fallbackOrder = plan.size + 10
477
+ const unknown = []
478
+ for (const child of Array.from(section.children)) {
479
+ if (child === headerWrapper) {
480
+ setStyle(child, 'order', '0')
481
+ continue
482
+ }
483
+ if (child.getAttribute('role') === 'group') {
484
+ setStyle(child, 'order', '1')
485
+ continue
486
+ }
487
+ const row = child.getAttribute('data-row-key')?.startsWith('session:')
488
+ ? child
489
+ : child.querySelector('[data-row-key^="session:"]')
490
+ if (row) {
491
+ const id = sessionIdOf(row)
492
+ const planned = plan.get(id)
493
+ const wrapper = wrapperOf(row, section)
494
+ if (planned === undefined) {
495
+ setStyle(wrapper, 'order', String(fallbackOrder))
496
+ fallbackOrder += 1
497
+ removeStyle(wrapper, 'display')
498
+ removeStyle(row, '--dsl-indent')
499
+ removeStyle(row, '--dsl-depth')
500
+ ensureToggle(row, id, false, false)
501
+ unknown.push(id)
502
+ continue
503
+ }
504
+ setStyle(wrapper, 'order', String(10 + planned.orderIndex))
505
+ setStyle(row, '--dsl-indent', `${planned.depth * INDENT_STEP}px`)
506
+ setStyle(row, '--dsl-depth', String(planned.depth))
507
+ if (planned.hidden) setStyle(wrapper, 'display', 'none')
508
+ else removeStyle(wrapper, 'display')
509
+ ensureToggle(row, id, planned.hasChildren, collapsed.has(id))
510
+ continue
511
+ }
512
+ if (child.querySelector('[data-row-key^="overflow:"]')) {
513
+ setStyle(child, 'order', String(OVERFLOW_ORDER))
514
+ continue
515
+ }
516
+ setStyle(child, 'order', '5')
517
+ }
518
+ section.setAttribute('data-dsl-section', '')
519
+ return unknown
520
+ }
521
+
522
+ /**
523
+ * Find the lineage node for one session across cached trees.
524
+ *
525
+ * @param sessionId - session id.
526
+ * @returns `{ entry, node, parentKey, siblings, index }` or null.
527
+ */
528
+ function locateSiblings(sessionId) {
529
+ for (const entry of trees.values()) {
530
+ const node = entry.byId.get(sessionId)
531
+ if (node === undefined) continue
532
+ const known = new Set(entry.sessions.map((item) => item.id))
533
+ const parentKey = parentKeyOf(node, known)
534
+ const siblings = entry.sessions.filter((item) => parentKeyOf(item, known) === parentKey)
535
+ siblings.sort(siblingComparator(parentKey, new Map()))
536
+ const index = siblings.findIndex((item) => item.id === sessionId)
537
+ return { entry, node, parentKey, siblings, index }
538
+ }
539
+ return null
540
+ }
541
+
542
+ /**
543
+ * Move one session one place inside its sibling group.
544
+ *
545
+ * @param sessionId - session id to move.
546
+ * @param delta - -1 for up, +1 for down.
547
+ */
548
+ function moveSibling(sessionId, delta) {
549
+ const located = locateSiblings(sessionId)
550
+ if (located === null) return
551
+ const { parentKey, siblings, index } = located
552
+ const target = index + delta
553
+ if (index < 0 || target < 0 || target >= siblings.length) return
554
+ const ids = siblings.map((item) => item.id)
555
+ const moved = ids[index]
556
+ ids[index] = ids[target]
557
+ ids[target] = moved
558
+ state = { ...state, order: { ...state.order, [parentKey]: ids } }
559
+ scheduleSave()
560
+ void applyAll()
561
+ }
562
+
563
+ /**
564
+ * Actions for the Session 「…」/right-click menu.
565
+ *
566
+ * @param sessionId - clicked session id.
567
+ * @returns menu actions (empty when the session has no siblings).
568
+ */
569
+ function siblingActions(sessionId) {
570
+ const located = locateSiblings(sessionId)
571
+ if (located === null || located.siblings.length < 2) return []
572
+ const labels = uiText()
573
+ return [
574
+ {
575
+ id: 'lineage.move-up',
576
+ label: labels.moveUp,
577
+ disabled: located.index <= 0,
578
+ run: () => moveSibling(sessionId, -1),
579
+ },
580
+ {
581
+ id: 'lineage.move-down',
582
+ label: labels.moveDown,
583
+ disabled: located.index >= located.siblings.length - 1,
584
+ run: () => moveSibling(sessionId, 1),
585
+ },
586
+ ]
587
+ }
588
+
589
+ /**
590
+ * Escape one session id for a CSS attribute selector.
591
+ *
592
+ * @param value - raw id.
593
+ * @returns escaped id.
594
+ */
595
+ function cssEscape(value) {
596
+ if (typeof CSS !== 'undefined' && typeof CSS.escape === 'function') return CSS.escape(value)
597
+ return String(value).replace(/["\\]/g, '\\$&')
598
+ }
599
+
600
+ /**
601
+ * Row element of one session id.
602
+ *
603
+ * @param sessionId - session id.
604
+ * @returns row element or null.
605
+ */
606
+ function rowOfSession(sessionId) {
607
+ return document.querySelector(`[data-row-key="session:${cssEscape(sessionId)}"]`)
608
+ }
609
+
610
+ /**
611
+ * Ancestor session ids of one session inside its cached tree.
612
+ *
613
+ * @param sessionId - session id.
614
+ * @returns ancestor ids from parent upward.
615
+ */
616
+ function ancestorIdsOf(sessionId) {
617
+ for (const entry of trees.values()) {
618
+ const node = entry.byId.get(sessionId)
619
+ if (node === undefined) continue
620
+ const chain = []
621
+ const seen = new Set([sessionId])
622
+ let parentId = node.parentId
623
+ while (typeof parentId === 'string' && entry.byId.has(parentId) && !seen.has(parentId)) {
624
+ seen.add(parentId)
625
+ chain.push(parentId)
626
+ parentId = entry.byId.get(parentId).parentId
627
+ }
628
+ return chain
629
+ }
630
+ return []
631
+ }
632
+
633
+ /**
634
+ * Remove the ancestor-chain highlight.
635
+ */
636
+ function clearAncestorHighlight() {
637
+ for (const row of highlightedRows) row.classList.remove('dsl-ancestor')
638
+ highlightedRows = []
639
+ hoveredSession = null
640
+ }
641
+
642
+ /**
643
+ * Highlight the ancestor chain of one hovered session row.
644
+ *
645
+ * @param sessionId - hovered session id.
646
+ */
647
+ function updateAncestorHighlight(sessionId) {
648
+ if (sessionId === hoveredSession) return
649
+ for (const row of highlightedRows) row.classList.remove('dsl-ancestor')
650
+ highlightedRows = []
651
+ hoveredSession = sessionId
652
+ for (const id of ancestorIdsOf(sessionId)) {
653
+ const row = rowOfSession(id)
654
+ if (row === null) continue
655
+ row.classList.add('dsl-ancestor')
656
+ highlightedRows.push(row)
657
+ }
658
+ }
659
+
660
+ /**
661
+ * Delegated pointerover handler for the ancestor-chain highlight.
662
+ *
663
+ * @param event - pointer event.
664
+ */
665
+ function onPointerOver(event) {
666
+ const row = event.target?.closest?.('[data-row-key^="session:"]')
667
+ if (!row) return
668
+ updateAncestorHighlight(sessionIdOf(row))
669
+ }
670
+
671
+ /**
672
+ * Delegated pointerout handler for the ancestor-chain highlight.
673
+ *
674
+ * @param event - pointer event.
675
+ */
676
+ function onPointerOut(event) {
677
+ const row = event.target?.closest?.('[data-row-key^="session:"]')
678
+ if (!row) return
679
+ const next = event.relatedTarget
680
+ if (next && row.contains(next)) return
681
+ clearAncestorHighlight()
682
+ }
683
+
684
+ /**
685
+ * Drop manual order/collapse entries for sessions no longer returned by any
686
+ * loaded workspace. Only runs once every mounted workspace tree is loaded,
687
+ * so a slow workspace never loses its saved order.
688
+ */
689
+ function pruneState() {
690
+ const known = new Set()
691
+ for (const entry of trees.values()) {
692
+ for (const item of entry.sessions) known.add(item.id)
693
+ }
694
+ if (known.size === 0) return
695
+ let changed = false
696
+ const nextOrder = {}
697
+ for (const [key, ids] of Object.entries(state.order)) {
698
+ if (key !== ROOT_KEY && !known.has(key)) {
699
+ changed = true
700
+ continue
701
+ }
702
+ const filtered = Array.isArray(ids) ? ids.filter((id) => known.has(id)) : []
703
+ if (!Array.isArray(ids) || filtered.length !== ids.length) changed = true
704
+ nextOrder[key] = filtered
705
+ }
706
+ const nextCollapsed = state.collapsed.filter((id) => known.has(id))
707
+ if (nextCollapsed.length !== state.collapsed.length) changed = true
708
+ if (!changed) return
709
+ state = { ...state, order: nextOrder, collapsed: nextCollapsed }
710
+ scheduleSave()
711
+ }
712
+
713
+ /**
714
+ * Apply the current lineage to every mounted workspace section.
715
+ */
716
+ async function applyAll() {
717
+ if (disposed || applying) {
718
+ if (applying) queued = true
719
+ return
720
+ }
721
+ applying = true
722
+ try {
723
+ await ensureState()
724
+ const collapsed = new Set(state.collapsed)
725
+ const sections = workspaceSections()
726
+ await Promise.all(sections.map(async (entry) => {
727
+ try {
728
+ await ensureTree(entry.workspaceId)
729
+ } catch (error) {
730
+ warn(`workspace ${entry.workspaceId}: lineage unavailable`, error)
731
+ }
732
+ }))
733
+ let allLoaded = sections.length > 0
734
+ for (const entry of sections) {
735
+ const tree = trees.get(entry.workspaceId)
736
+ if (tree === undefined) allLoaded = false
737
+ const rows = sessionRowsIn(entry.section)
738
+ const nativeRank = new Map(rows.map((row, index) => [sessionIdOf(row), index]))
739
+ const plan = tree === undefined ? new Map() : computePlan(tree, nativeRank, collapsed)
740
+ try {
741
+ const unknown = applySection(entry, plan, collapsed)
742
+ if (tree !== undefined && unknown.length > 0) refetchWorkspace(entry.workspaceId)
743
+ } catch (error) {
744
+ warn(`workspace ${entry.workspaceId}: apply failed`, error)
745
+ }
746
+ }
747
+ if (allLoaded) pruneState()
748
+ } catch (error) {
749
+ warn('apply failed', error)
750
+ } finally {
751
+ applying = false
752
+ }
753
+ if (queued) {
754
+ queued = false
755
+ scheduleApply()
756
+ }
757
+ }
758
+
759
+ /**
760
+ * Coalesce DOM mutations into one apply.
761
+ */
762
+ function scheduleApply() {
763
+ if (disposed) return
764
+ clearTimeout(applyTimer)
765
+ applyTimer = setTimeout(() => void applyAll(), APPLY_DEBOUNCE_MS)
766
+ }
767
+
768
+ /**
769
+ * Observe the session list for rows React adds or replaces.
770
+ *
771
+ * The observer has to survive the sidebar being collapsed and expanded:
772
+ * DSH unmounts the whole sidebar subtree there, so an observer bound to the
773
+ * `[role="tree"]` element of the previous mount would go silent forever.
774
+ * `document.body` is stable; every batch is filtered down to mutations that
775
+ * touch the current tree (inside it, or on an ancestor that contains it), so
776
+ * unrelated churn such as chat streaming does not trigger a re-apply.
777
+ */
778
+ function observe() {
779
+ if (observer !== null) return
780
+ observer = new MutationObserver((records) => {
781
+ if (disposed) return
782
+ const tree = document.querySelector('[role="tree"]')
783
+ if (tree === null) return
784
+ let relevant = false
785
+ let removed = null
786
+ for (const record of records) {
787
+ if (record.type !== 'childList') continue
788
+ const target = record.target
789
+ const touchesTree = tree.contains(target)
790
+ || (target instanceof Element && target.contains(tree))
791
+ if (!touchesTree) continue
792
+ if (record.addedNodes.length === 0 && record.removedNodes.length === 0) continue
793
+ relevant = true
794
+ if (removed !== null) continue
795
+ for (const node of record.removedNodes) {
796
+ const sessionId = sessionIdInNode(node)
797
+ if (sessionId === null) continue
798
+ const section = target instanceof Element ? target.closest('[data-dsl-section]') : null
799
+ const workspaceId = section === null ? null : workspaceIdOfSection(section)
800
+ if (workspaceId !== null) removed = { workspaceId, sessionId }
801
+ break
802
+ }
803
+ }
804
+ if (removed !== null) {
805
+ const cached = trees.get(removed.workspaceId)
806
+ if (cached !== undefined && cached.byId.has(removed.sessionId)) {
807
+ // A row the cached tree knows disappeared natively (archive, move,
808
+ // delete): the saved lineage may no longer be valid.
809
+ refetchWorkspace(removed.workspaceId)
810
+ }
811
+ }
812
+ if (relevant) scheduleApply()
813
+ })
814
+ observer.observe(document.body, { childList: true, subtree: true })
815
+ }
816
+
817
+ /**
818
+ * Refresh cached trees when the page becomes visible again, so changes made
819
+ * while the window was hidden (archive, move, delete) are picked up.
820
+ */
821
+ function onVisibilityRefresh() {
822
+ if (disposed || document.visibilityState !== 'visible') return
823
+ const now = Date.now()
824
+ if (now - lastFocusRefresh < FOCUS_REFRESH_MS) return
825
+ lastFocusRefresh = now
826
+ for (const entry of workspaceSections()) refetchWorkspace(entry.workspaceId)
827
+ }
828
+
829
+ /**
830
+ * Inject this plugin's stylesheet once.
831
+ */
832
+ function injectStyle() {
833
+ if (styleEl !== null) return
834
+ styleEl = document.createElement('style')
835
+ styleEl.id = `${MARK}-style`
836
+ styleEl.dataset.plugin = MARK
837
+ styleEl.textContent = CSS
838
+ document.head.append(styleEl)
839
+ }
840
+
841
+ /**
842
+ * Remove every trace this plugin left in the page.
843
+ */
844
+ function cleanup() {
845
+ disposed = true
846
+ clearTimeout(applyTimer)
847
+ clearTimeout(saveTimer)
848
+ if (observer !== null) {
849
+ observer.disconnect()
850
+ observer = null
851
+ }
852
+ if (styleEl !== null) {
853
+ styleEl.remove()
854
+ styleEl = null
855
+ }
856
+ for (const toggle of document.querySelectorAll('.dsl-toggle')) toggle.remove()
857
+ for (const section of document.querySelectorAll('[data-dsl-section]')) {
858
+ for (const child of Array.from(section.children)) {
859
+ child.style.removeProperty('order')
860
+ child.style.removeProperty('display')
861
+ }
862
+ section.removeAttribute('data-dsl-section')
863
+ }
864
+ for (const row of document.querySelectorAll('[data-row-key^="session:"]')) {
865
+ row.style.removeProperty('--dsl-indent')
866
+ row.style.removeProperty('--dsl-depth')
867
+ row.classList.remove('dsl-ancestor')
868
+ }
869
+ clearAncestorHighlight()
870
+ document.body.removeEventListener('pointerover', onPointerOver)
871
+ document.body.removeEventListener('pointerout', onPointerOut)
872
+ document.removeEventListener('visibilitychange', onVisibilityRefresh)
873
+ if (window.__DSH_SESSION_LINEAGE_INSTANCE__ !== undefined) delete window.__DSH_SESSION_LINEAGE_INSTANCE__
874
+ }
875
+
876
+ /**
877
+ * Mount the browser half.
878
+ *
879
+ * @param ctx - browser Cordis context.
880
+ */
881
+ function apply(ctx) {
882
+ if (window.__DSH_SESSION_LINEAGE_INSTANCE__ !== undefined) {
883
+ try {
884
+ window.__DSH_SESSION_LINEAGE_INSTANCE__.dispose()
885
+ } catch {
886
+ /* a stale instance is simply replaced */
887
+ }
888
+ }
889
+ if (!document.body) return
890
+ injectStyle()
891
+ observe()
892
+ document.body.addEventListener('pointerover', onPointerOver)
893
+ document.body.addEventListener('pointerout', onPointerOut)
894
+ document.addEventListener('visibilitychange', onVisibilityRefresh)
895
+ window.__DSH_SESSION_LINEAGE_INSTANCE__ = { dispose: cleanup, applyAll: () => void applyAll() }
896
+ ctx.effect(() => () => cleanup(), `${MARK}: sidebar`)
897
+ try {
898
+ ctx.inject(['contextMenus'], (scope) => {
899
+ try {
900
+ const menus = scope.contextMenus ?? scope.get?.('contextMenus')
901
+ if (!menus || typeof menus.register !== 'function') return
902
+ scope.effect(() => menus.register({
903
+ id: 'lineage.sibling-order',
904
+ target: 'session',
905
+ order: 400,
906
+ resolve: (target) => siblingActions(target?.sessionId),
907
+ }), `${MARK}: session menu`)
908
+ } catch (error) {
909
+ warn('session menu registration failed', error)
910
+ }
911
+ })
912
+ } catch (error) {
913
+ warn('context menu service unavailable', error)
914
+ }
915
+ scheduleApply()
916
+ }
917
+
918
+ return { inject: [], apply }
919
+ },
920
+ })