dsh-codex-session-pin 0.0.0-stage → 1.0.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/client.js ADDED
@@ -0,0 +1,767 @@
1
+ // Browser half of dsh-session-pin.
2
+ //
3
+ // Two surfaces, one data source (the official Workspace pin set):
4
+ //
5
+ // 1. A pin toggle in the Session header (`conversation.session.header.utilities`)
6
+ // — a real slot, so it works on any sidebar implementation.
7
+ // 2. A DOM enhancement of the session list drawn by a third-party sidebar
8
+ // (currently `@michengai/dsh-codex-ui`, which renders its own rows and never
9
+ // reads the official pin set): a hover pin button, a menu row, a leading
10
+ // marker on pinned rows, and pinned rows ordered first inside their project.
11
+ // Only nodes this plugin created are added or removed, and the ordering uses
12
+ // CSS `order`, so React keeps owning the DOM structure.
13
+ //
14
+ // Pin state itself is never stored here: it is `ctx.workspaces.pinnedSessionIds`,
15
+ // persisted by the Host in `~/.dsh/storages/workspace.json`.
16
+ window.__ModuleLoader__.load({
17
+ id: 'dsh-codex-session-pin',
18
+ factory(require) {
19
+ const React = require('react')
20
+
21
+ const NS = 'codex-session-pin'
22
+ // Bumped on every edit so a diagnostics report names the code that ran.
23
+ const BUILD = 'v12'
24
+ const EMPTY_IDS = Object.freeze([])
25
+ const ROW_SELECTOR = '[data-dcu-session]'
26
+ const BODY_SELECTOR = '.dcu-wb-project-body'
27
+ const PIN_ATTR = 'data-dcsp-pin'
28
+ const MARK_ATTR = 'data-dcsp-mark'
29
+ const MENU_ATTR = 'data-dcsp-menu'
30
+ const PINNED_ATTR = 'data-dcsp-pinned'
31
+ const ORDER_ATTR = 'data-dcsp-order'
32
+
33
+ const ICON_PIN_OUTLINE =
34
+ '<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' +
35
+ '<path d="M6 2h4l-.6 3.2 2.1 2.1v1.2H4.5V7.3l2.1-2.1z"/><path d="M8 8.5V14"/></svg>'
36
+ const ICON_PIN_FILLED =
37
+ '<svg viewBox="0 0 16 16" width="14" height="14" fill="currentColor" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' +
38
+ '<path d="M6 2h4l-.6 3.2 2.1 2.1v1.2H4.5V7.3l2.1-2.1z"/><path d="M8 8.8V14" fill="none" stroke-width="1.4"/></svg>'
39
+ const ICON_PIN_MARK =
40
+ '<svg viewBox="0 0 16 16" width="12" height="12" fill="currentColor" aria-hidden="true">' +
41
+ '<path d="M6 1.5h4a.7.7 0 0 1 .68.87l-.5 2.6 1.9 1.9a.7.7 0 0 1 .2.5v1.1a.7.7 0 0 1-.7.7H4.42a.7.7 0 0 1-.7-.7V7.37c0-.19.07-.36.2-.5l1.9-1.9-.5-2.6A.7.7 0 0 1 6 1.5Z"/>' +
42
+ '<path d="M8 9.2v4.6" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>'
43
+
44
+ const CSS = `
45
+ .dcsp-mark{display:inline-flex;flex:none;align-items:center;justify-content:center;width:12px;height:12px;color:var(--dsw-alias-brand-primary);opacity:.9}
46
+ .dcsp-pin-btn{color:inherit}
47
+ .dcsp-pin-btn[data-dcsp-on="1"]{color:var(--dsw-alias-brand-primary)}
48
+ /* The extra attribute beats the sidebar's own display:block rule, and the open
49
+ guard keeps a collapsed project collapsed. */
50
+ ${BODY_SELECTOR}[data-open="true"][${ORDER_ATTR}]{display:flex;flex-direction:column}
51
+ ${BODY_SELECTOR}[${ORDER_ATTR}] > .dcu-wb-session[${PINNED_ATTR}="1"]{order:-1}
52
+ `
53
+
54
+ /** String guard shared by every id read from the DOM. */
55
+ function asId(value) {
56
+ return typeof value === 'string' && value.length > 0 ? value : undefined
57
+ }
58
+
59
+ function postDiag(payload) {
60
+ try {
61
+ fetch('/codex-session-pin/diag', {
62
+ method: 'POST',
63
+ headers: { 'content-type': 'application/json' },
64
+ body: JSON.stringify(payload),
65
+ keepalive: true,
66
+ }).catch(() => {})
67
+ } catch {
68
+ // Diagnostics never affect the user action.
69
+ }
70
+ }
71
+
72
+ /** Wait without animation frames: a hidden window produces none. */
73
+ function sleep(ms) {
74
+ return new Promise((resolve) => window.setTimeout(resolve, ms))
75
+ }
76
+
77
+ function applyInner(ctx) {
78
+ const disposers = []
79
+ postDiag({ kind: 'client-boot', build: BUILD, url: typeof window !== 'undefined' ? window.location.href : '' })
80
+ const workspaces = () => {
81
+ try {
82
+ return ctx.get('workspaces')
83
+ } catch {
84
+ return undefined
85
+ }
86
+ }
87
+ const pinnedIds = () => {
88
+ const service = workspaces()
89
+ const list = service === undefined ? undefined : service.list
90
+ if (list === undefined || typeof list.getSnapshot !== 'function') return EMPTY_IDS
91
+ const snapshot = list.getSnapshot()
92
+ return snapshot && Array.isArray(snapshot.pinnedSessionIds) ? snapshot.pinnedSessionIds : EMPTY_IDS
93
+ }
94
+ const isPinned = (sessionId) => pinnedIds().indexOf(sessionId) !== -1
95
+ const t = (key, params) => {
96
+ try {
97
+ return ctx.locale.bind(NS)(key, params)
98
+ } catch {
99
+ return key
100
+ }
101
+ }
102
+
103
+ // A duplicate namespace registration throws, and a hot reload loads this
104
+ // half again in the same page; a failed dictionary must never prevent the
105
+ // surfaces from mounting, so it is caught and reported.
106
+ disposers.push(
107
+ ctx.effect(() => {
108
+ try {
109
+ return ctx.locale.register(NS, {
110
+ zh: {
111
+ pin: '置顶会话',
112
+ unpin: '取消置顶',
113
+ pinned: '已置顶',
114
+ },
115
+ en: {
116
+ pin: 'Pin session',
117
+ unpin: 'Unpin session',
118
+ pinned: 'Pinned',
119
+ },
120
+ })
121
+ } catch (error) {
122
+ postDiag({ kind: 'locale-failed', build: BUILD, message: String((error && error.message) || error) })
123
+ return () => {}
124
+ }
125
+ }, 'dsh-codex-session-pin: dictionaries'),
126
+ )
127
+
128
+ // Assigned by the list surface below; the header surface only needs it to
129
+ // ask the list surfaces for a refresh after a mutation.
130
+ let scheduleSync = () => {}
131
+
132
+ /**
133
+ * Change one Session's pin state through the official Client service,
134
+ * falling back to this bundle's Host route only when that service is
135
+ * absent or predates the pin methods.
136
+ */
137
+ async function setPinned(sessionId, nextPinned) {
138
+ const service = workspaces()
139
+ const viaService =
140
+ service !== undefined &&
141
+ typeof service.pinSession === 'function' &&
142
+ typeof service.unpinSession === 'function'
143
+ try {
144
+ postDiag({ kind: 'action-start', sessionId, pinned: nextPinned, viaService })
145
+ const startedAt = Date.now()
146
+ if (viaService) {
147
+ if (nextPinned) await service.pinSession(sessionId)
148
+ else await service.unpinSession(sessionId)
149
+ postDiag({ kind: 'action', via: 'workspaces', sessionId, pinned: nextPinned, ms: Date.now() - startedAt })
150
+ } else {
151
+ const response = await fetch('/codex-session-pin/toggle', {
152
+ method: 'POST',
153
+ headers: { 'content-type': 'application/json' },
154
+ body: JSON.stringify({ sessionId, pinned: nextPinned }),
155
+ })
156
+ const payload = await response.json().catch(() => null)
157
+ if (!response.ok || payload === null || payload.ok !== true) {
158
+ throw new Error((payload && payload.error) || 'request failed (' + response.status + ')')
159
+ }
160
+ postDiag({ kind: 'action', via: 'host-route', sessionId, pinned: nextPinned })
161
+ }
162
+ scheduleSync()
163
+ } catch (error) {
164
+ const message = String((error && error.message) || error)
165
+ postDiag({ kind: 'action-failed', sessionId, pinned: nextPinned, message })
166
+ throw error
167
+ }
168
+ }
169
+
170
+ // ---- surface 1: Session header toggle -------------------------------
171
+ function PinHeaderButton(props) {
172
+ const sessionId = asId(props.sessionId)
173
+ const ids = React.useSyncExternalStore(
174
+ (listener) => {
175
+ const service = workspaces()
176
+ const list = service === undefined ? undefined : service.list
177
+ if (list === undefined || typeof list.subscribe !== 'function') return () => {}
178
+ return list.subscribe(listener)
179
+ },
180
+ pinnedIds,
181
+ () => EMPTY_IDS,
182
+ )
183
+ const [busy, setBusy] = React.useState(false)
184
+ if (sessionId === undefined) return null
185
+ const pinned = ids.indexOf(sessionId) !== -1
186
+ const label = pinned ? t('unpin') : t('pin')
187
+ const onClick = (event) => {
188
+ event.preventDefault()
189
+ event.stopPropagation()
190
+ if (busy) return
191
+ setBusy(true)
192
+ setPinned(sessionId, !pinned)
193
+ .catch(() => {})
194
+ .finally(() => setBusy(false))
195
+ }
196
+ return React.createElement(
197
+ 'button',
198
+ {
199
+ type: 'button',
200
+ className: 'dcsp-pin-btn',
201
+ 'data-dcsp-on': pinned ? '1' : '0',
202
+ 'data-dcsp-header': '',
203
+ 'aria-label': label,
204
+ 'aria-pressed': pinned,
205
+ title: label,
206
+ disabled: busy,
207
+ onClick,
208
+ style: {
209
+ display: 'inline-flex',
210
+ alignItems: 'center',
211
+ justifyContent: 'center',
212
+ width: 26,
213
+ height: 26,
214
+ padding: 0,
215
+ border: 'none',
216
+ borderRadius: 6,
217
+ background: 'transparent',
218
+ color: pinned ? 'var(--dsw-alias-brand-primary)' : 'var(--dsw-alias-label-secondary)',
219
+ cursor: busy ? 'default' : 'pointer',
220
+ opacity: busy ? 0.6 : 1,
221
+ },
222
+ },
223
+ React.createElement('span', {
224
+ style: { display: 'inline-flex' },
225
+ dangerouslySetInnerHTML: { __html: pinned ? ICON_PIN_FILLED : ICON_PIN_OUTLINE },
226
+ }),
227
+ )
228
+ }
229
+
230
+ disposers.push(
231
+ ctx.slots.inject('conversation.session.header.utilities', () =>
232
+ ctx.slots.register(
233
+ {
234
+ name: 'conversation.session.header.utilities',
235
+ id: 'codex-session-pin',
236
+ order: 5,
237
+ locale: NS,
238
+ },
239
+ PinHeaderButton,
240
+ ),
241
+ ),
242
+ )
243
+
244
+ // ---- surface 2: session list DOM enhancement ------------------------
245
+ let styleElement
246
+ let frame = 0
247
+ // Every node this generation injected, so cleanup touches nothing a
248
+ // newer generation of the same plugin owns.
249
+ const owned = new Set()
250
+ const stats = { syncs: 0, rows: 0, pinnedRows: 0, pinButtons: 0, menus: 0, orderedGroups: 0, lastReport: '' }
251
+
252
+ if (typeof document !== 'undefined') {
253
+ try {
254
+ styleElement = document.createElement('style')
255
+ styleElement.setAttribute('data-dcsp', '')
256
+ styleElement.textContent = CSS
257
+ document.head.appendChild(styleElement)
258
+
259
+ const makePinButton = (sessionId, pinned, template) => {
260
+ const button = document.createElement('button')
261
+ button.type = 'button'
262
+ button.className = (template && template.className ? template.className + ' ' : '') + 'dcsp-pin-btn'
263
+ button.setAttribute(PIN_ATTR, sessionId)
264
+ button.setAttribute('data-dcsp-on', pinned ? '1' : '0')
265
+ const label = pinned ? t('unpin') : t('pin')
266
+ button.setAttribute('aria-label', label)
267
+ button.setAttribute('aria-pressed', pinned ? 'true' : 'false')
268
+ button.title = label
269
+ button.innerHTML = pinned ? ICON_PIN_FILLED : ICON_PIN_OUTLINE
270
+ button.addEventListener('click', (event) => {
271
+ event.preventDefault()
272
+ event.stopPropagation()
273
+ setPinned(sessionId, !isPinned(sessionId)).catch(() => {})
274
+ })
275
+ owned.add(button)
276
+ return button
277
+ }
278
+
279
+ const syncRow = (row, pinnedSet, pinRank) => {
280
+ const sessionId = asId(row.getAttribute('data-dcu-session'))
281
+ if (sessionId === undefined) return false
282
+ const pinned = pinnedSet.has(sessionId)
283
+ const flag = pinned ? '1' : '0'
284
+ if (row.getAttribute(PINNED_ATTR) !== flag) row.setAttribute(PINNED_ATTR, flag)
285
+ // Rank pinned rows in the official pin order (most recently pinned
286
+ // first). Only this element's own inline property is written, so
287
+ // removal restores the sidebar's own layout exactly.
288
+ if (pinned) {
289
+ const rank = pinRank.get(sessionId)
290
+ const order = String(-1000 + (rank === undefined ? 0 : rank))
291
+ if (row.style.order !== order) row.style.order = order
292
+ } else if (row.style.order !== '') {
293
+ row.style.removeProperty('order')
294
+ }
295
+
296
+ const existingMark = row.querySelector(':scope > [' + MARK_ATTR + ']')
297
+ if (pinned && existingMark === null) {
298
+ const mark = document.createElement('span')
299
+ mark.className = 'dcsp-mark'
300
+ mark.setAttribute(MARK_ATTR, '')
301
+ mark.setAttribute('aria-hidden', 'true')
302
+ mark.title = t('pinned')
303
+ mark.innerHTML = ICON_PIN_MARK
304
+ owned.add(mark)
305
+ row.insertBefore(mark, row.firstChild)
306
+ } else if (!pinned && existingMark !== null && owned.has(existingMark)) {
307
+ owned.delete(existingMark)
308
+ existingMark.remove()
309
+ }
310
+
311
+ const quick = row.querySelector('.dcu-wb-quick-actions')
312
+ if (quick !== null) {
313
+ let existing = quick.querySelector(':scope > [' + PIN_ATTR + ']')
314
+ // A button injected by an earlier generation of this plugin is
315
+ // replaced rather than adopted, so the two never both own it.
316
+ if (existing !== null && !owned.has(existing)) {
317
+ existing.remove()
318
+ existing = null
319
+ }
320
+ if (existing === null) {
321
+ const proto = quick.querySelector('button')
322
+ if (proto !== null) quick.insertBefore(makePinButton(sessionId, pinned, proto), quick.firstChild)
323
+ } else if (existing.getAttribute('data-dcsp-on') !== flag) {
324
+ const label = pinned ? t('unpin') : t('pin')
325
+ existing.setAttribute('data-dcsp-on', flag)
326
+ existing.setAttribute('aria-pressed', pinned ? 'true' : 'false')
327
+ existing.setAttribute('aria-label', label)
328
+ existing.title = label
329
+ existing.innerHTML = pinned ? ICON_PIN_FILLED : ICON_PIN_OUTLINE
330
+ }
331
+ }
332
+ return pinned
333
+ }
334
+
335
+ const syncGroup = (body, pinnedSet) => {
336
+ let hasPinned = false
337
+ for (const row of body.children) {
338
+ if (!(row instanceof HTMLElement) || !row.matches(ROW_SELECTOR)) continue
339
+ const sessionId = asId(row.getAttribute('data-dcu-session'))
340
+ if (sessionId !== undefined && pinnedSet.has(sessionId)) {
341
+ hasPinned = true
342
+ break
343
+ }
344
+ }
345
+ if (hasPinned) {
346
+ if (!body.hasAttribute(ORDER_ATTR)) body.setAttribute(ORDER_ATTR, '')
347
+ } else if (body.hasAttribute(ORDER_ATTR)) {
348
+ body.removeAttribute(ORDER_ATTR)
349
+ }
350
+ return hasPinned
351
+ }
352
+
353
+ /** Add the pin row to the open Session menu. */
354
+ const syncMenu = (pinnedSet) => {
355
+ const row = document.querySelector(ROW_SELECTOR + '.dcu-wb-menu-open')
356
+ if (row === null) return
357
+ const sessionId = asId(row.getAttribute('data-dcu-session'))
358
+ if (sessionId === undefined) return
359
+ let menu
360
+ for (const candidate of document.querySelectorAll('[role="menu"]')) {
361
+ if (candidate.hasAttribute('data-dsm-sub')) continue
362
+ const rect = candidate.getBoundingClientRect()
363
+ if (rect.width > 0 && rect.height > 0) menu = candidate
364
+ }
365
+ if (menu === undefined || menu.querySelector('[' + MENU_ATTR + ']') !== null) return
366
+ const proto = menu.querySelector('[role="menuitem"]')
367
+ if (proto === null) return
368
+ const viewport = menu.querySelector('[role="presentation"]') || menu.firstElementChild
369
+ if (viewport === null) return
370
+ const pinned = pinnedSet.has(sessionId)
371
+ const wrap = proto.parentElement ? proto.parentElement.cloneNode(false) : document.createElement('div')
372
+ if (proto.parentElement && proto.parentElement.className) wrap.className = proto.parentElement.className
373
+ const item = document.createElement('button')
374
+ item.type = 'button'
375
+ item.setAttribute('role', 'menuitem')
376
+ item.className = proto.className
377
+ item.setAttribute(MENU_ATTR, '')
378
+ const icon = document.createElement('span')
379
+ icon.style.cssText =
380
+ 'display:inline-flex;flex:none;width:16px;height:16px;align-items:center;justify-content:center;color:' +
381
+ (pinned ? 'var(--dsw-alias-brand-primary)' : 'var(--dsw-alias-label-secondary)')
382
+ icon.innerHTML = pinned ? ICON_PIN_FILLED : ICON_PIN_OUTLINE
383
+ const label = document.createElement('span')
384
+ label.style.cssText = 'flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap'
385
+ label.textContent = pinned ? t('unpin') : t('pin')
386
+ item.appendChild(icon)
387
+ item.appendChild(label)
388
+ item.addEventListener('click', (event) => {
389
+ event.preventDefault()
390
+ event.stopPropagation()
391
+ document.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }))
392
+ setPinned(sessionId, !pinned).catch(() => {})
393
+ })
394
+ wrap.appendChild(item)
395
+ owned.add(wrap)
396
+ viewport.insertBefore(wrap, viewport.firstElementChild)
397
+ stats.menus += 1
398
+ postDiag({ kind: 'menu-injected', build: BUILD, sessionId, pinned })
399
+ }
400
+
401
+ /** What the page currently contains, so a report names real selectors. */
402
+ const census = () => ({
403
+ kind: 'census',
404
+ url: window.location.href,
405
+ viewport: { w: window.innerWidth, h: window.innerHeight },
406
+ rows: document.querySelectorAll(ROW_SELECTOR).length,
407
+ codexSessions: document.querySelectorAll('.dcu-wb-session').length,
408
+ projectBodies: document.querySelectorAll(BODY_SELECTOR).length,
409
+ treeitems: document.querySelectorAll('[role="treeitem"]').length,
410
+ asides: document.querySelectorAll('aside').length,
411
+ pinButtons: document.querySelectorAll('[' + PIN_ATTR + ']').length,
412
+ marks: document.querySelectorAll('[' + MARK_ATTR + ']').length,
413
+ headerButtons: document.querySelectorAll('[data-dcsp-header]').length,
414
+ pinnedIds: pinnedIds(),
415
+ hasWorkspacesService: workspaces() !== undefined && typeof workspaces().pinSession === 'function',
416
+ })
417
+
418
+ /** Visual order per project: pinned rows first, with the CSS in effect. */
419
+ const rowsReport = () => {
420
+ const groups = []
421
+ for (const body of document.querySelectorAll(BODY_SELECTOR)) {
422
+ const head = body.parentElement === null ? null : body.parentElement.querySelector('.dcu-wb-project-head')
423
+ const nodes = [...body.querySelectorAll(':scope > ' + ROW_SELECTOR)]
424
+ const ordered = nodes
425
+ .map((node) => ({
426
+ node,
427
+ order: Number.parseFloat(window.getComputedStyle(node).order) || 0,
428
+ top: Math.round(node.getBoundingClientRect().top),
429
+ }))
430
+ .sort((left, right) => left.order - right.order || left.top - right.top)
431
+ groups.push({
432
+ project: head === null ? '' : (head.textContent || '').trim().slice(0, 24),
433
+ ordered: body.hasAttribute(ORDER_ATTR),
434
+ display: window.getComputedStyle(body).display,
435
+ count: nodes.length,
436
+ first: ordered.slice(0, 3).map((entry) => ({
437
+ id: String(entry.node.getAttribute('data-dcu-session')).slice(-8),
438
+ pinned: entry.node.getAttribute(PINNED_ATTR) === '1',
439
+ mark: entry.node.querySelector('[' + MARK_ATTR + ']') !== null,
440
+ button: entry.node.querySelector('[' + PIN_ATTR + ']') !== null,
441
+ order: entry.order,
442
+ top: entry.top,
443
+ })),
444
+ })
445
+ }
446
+ return { kind: 'rows', pinnedIds: pinnedIds(), groups }
447
+ }
448
+
449
+ /** Everything about one Session row: flags, injected nodes and siblings. */
450
+ const rowInfo = (sessionId) => {
451
+ const row = document.querySelector('[data-dcu-session="' + sessionId + '"]')
452
+ if (row === null) return { kind: 'row', sessionId, found: false, pinned: isPinned(sessionId) }
453
+ const body = row.closest(BODY_SELECTOR)
454
+ const siblings = body === null ? [] : [...body.querySelectorAll(':scope > ' + ROW_SELECTOR)]
455
+ const head = body === null || body.parentElement === null ? null : body.parentElement.querySelector('.dcu-wb-project-head')
456
+ const button = row.querySelector('[' + PIN_ATTR + ']')
457
+ return {
458
+ kind: 'row',
459
+ sessionId,
460
+ found: true,
461
+ pinned: isPinned(sessionId),
462
+ rowFlag: row.getAttribute(PINNED_ATTR),
463
+ mark: row.querySelector(':scope > [' + MARK_ATTR + ']') !== null,
464
+ button: button !== null,
465
+ buttonOn: button === null ? null : button.getAttribute('data-dcsp-on'),
466
+ title: (row.querySelector('.dcu-wb-session-title-text') || {}).textContent || '',
467
+ project: head === null ? '' : (head.textContent || '').trim().slice(0, 32),
468
+ groupOrdered: body !== null && body !== undefined && body.hasAttribute(ORDER_ATTR),
469
+ groupDisplay: body === null ? null : window.getComputedStyle(body).display,
470
+ index: siblings.indexOf(row),
471
+ order: Number.parseFloat(window.getComputedStyle(row).order) || 0,
472
+ firstPinnedIndex: siblings.findIndex((node) => node.getAttribute(PINNED_ATTR) === '1'),
473
+ firstUnpinnedIndex: siblings.findIndex((node) => node.getAttribute(PINNED_ATTR) !== '1'),
474
+ }
475
+ }
476
+
477
+ /** Full session ids in visual order, so a probe can address an exact row. */
478
+ const idsReport = () => {
479
+ const rows = [...document.querySelectorAll(ROW_SELECTOR)]
480
+ .map((node) => {
481
+ const rect = node.getBoundingClientRect()
482
+ return {
483
+ id: node.getAttribute('data-dcu-session'),
484
+ order: Number.parseFloat(window.getComputedStyle(node).order) || 0,
485
+ top: Math.round(rect.top),
486
+ onScreen: rect.height > 0 && rect.top > 0 && rect.top < window.innerHeight,
487
+ }
488
+ })
489
+ .sort((left, right) => left.order - right.order || left.top - right.top)
490
+ return { kind: 'ids', count: rows.length, rows: rows.slice(0, 10) }
491
+ }
492
+
493
+ const sync = () => {
494
+ frame = 0
495
+ if (!document.head.contains(styleElement)) document.head.appendChild(styleElement)
496
+ const ids = pinnedIds()
497
+ const pinnedSet = new Set(ids)
498
+ const pinRank = new Map(ids.map((id, index) => [id, index]))
499
+ let rows = 0
500
+ let pinnedRows = 0
501
+ let buttons = 0
502
+ for (const row of document.querySelectorAll(ROW_SELECTOR)) {
503
+ if (syncRow(row, pinnedSet, pinRank)) pinnedRows += 1
504
+ if (row.querySelector('[' + PIN_ATTR + ']') !== null) buttons += 1
505
+ rows += 1
506
+ }
507
+ let orderedGroups = 0
508
+ for (const body of document.querySelectorAll(BODY_SELECTOR)) if (syncGroup(body, pinnedSet)) orderedGroups += 1
509
+ syncMenu(pinnedSet)
510
+ stats.syncs += 1
511
+ stats.rows = rows
512
+ stats.pinnedRows = pinnedRows
513
+ stats.pinButtons = buttons
514
+ stats.orderedGroups = orderedGroups
515
+ const report = rows + '/' + buttons + '/' + pinnedRows + '/' + orderedGroups
516
+ if (report !== stats.lastReport) {
517
+ stats.lastReport = report
518
+ postDiag({ kind: 'sync', rows, pinButtons: buttons, pinnedRows, orderedGroups })
519
+ }
520
+ }
521
+
522
+ const scheduleSyncFrame = () => {
523
+ if (frame !== 0) return
524
+ frame = window.setTimeout(runSync, 16)
525
+ }
526
+ scheduleSync = scheduleSyncFrame
527
+
528
+ // A thrown sync must never leave the list half-done or kill the
529
+ // observer chain: report it once and re-arm on the next mutation.
530
+ let lastFailure = ''
531
+ function runSync() {
532
+ try {
533
+ sync()
534
+ } catch (error) {
535
+ const message = String((error && error.stack) || error).slice(0, 400)
536
+ if (message !== lastFailure) {
537
+ lastFailure = message
538
+ postDiag({ kind: 'sync-failed', build: BUILD, message })
539
+ }
540
+ frame = 0
541
+ }
542
+ }
543
+
544
+ const observer = new MutationObserver(scheduleSyncFrame)
545
+ observer.observe(document.body, { childList: true, subtree: true })
546
+ disposers.push(() => observer.disconnect())
547
+
548
+ // React-driven pin changes need not mutate the sidebar DOM, so the
549
+ // official store is observed too.
550
+ const subscribeStore = () => {
551
+ const service = workspaces()
552
+ const list = service === undefined ? undefined : service.list
553
+ if (list === undefined || typeof list.subscribe !== 'function') return undefined
554
+ return list.subscribe(scheduleSyncFrame)
555
+ }
556
+ let unsubscribeStore = subscribeStore()
557
+ const retry = window.setInterval(() => {
558
+ if (unsubscribeStore !== undefined) {
559
+ window.clearInterval(retry)
560
+ return
561
+ }
562
+ unsubscribeStore = subscribeStore()
563
+ }, 1000)
564
+ disposers.push(() => {
565
+ window.clearInterval(retry)
566
+ if (unsubscribeStore !== undefined) unsubscribeStore()
567
+ })
568
+
569
+ // Generation-safe teardown: remove only the nodes this generation
570
+ // created, and strip only the attributes it set, so a newer generation
571
+ // of the same plugin (a hot reload) keeps working.
572
+ disposers.push(() => {
573
+ if (frame !== 0) window.clearTimeout(frame)
574
+ for (const node of owned) node.remove()
575
+ owned.clear()
576
+ for (const node of document.querySelectorAll('[' + PINNED_ATTR + ']')) node.removeAttribute(PINNED_ATTR)
577
+ for (const node of document.querySelectorAll('[' + ORDER_ATTR + ']')) node.removeAttribute(ORDER_ATTR)
578
+ for (const node of document.querySelectorAll(ROW_SELECTOR)) {
579
+ if (node.style && node.style.order !== '') node.style.removeProperty('order')
580
+ }
581
+ if (styleElement && styleElement.parentNode) styleElement.remove()
582
+ })
583
+
584
+ /**
585
+ * End-to-end check of this plugin's own action path: pin through the
586
+ * same call the buttons make, read the DOM back, unpin, read again.
587
+ */
588
+ const selfTest = async (sessionId) => {
589
+ const before = pinnedIds().slice()
590
+ const result = { kind: 'self-test', build: BUILD, sessionId, before }
591
+ try {
592
+ await setPinned(sessionId, true)
593
+ await sleep(400)
594
+ scheduleSyncFrame()
595
+ await sleep(400)
596
+ const row = document.querySelector('[data-dcu-session="' + sessionId + '"]')
597
+ result.pinnedAfterPin = isPinned(sessionId)
598
+ result.markAfterPin = row !== null && row.querySelector('[' + MARK_ATTR + ']') !== null
599
+ result.rowFlagAfterPin = row === null ? null : row.getAttribute(PINNED_ATTR)
600
+ result.rowOrderAfterPin = row === null ? null : row.style.order
601
+ const body = row === null ? null : row.closest(BODY_SELECTOR)
602
+ result.groupOrdered = body !== null && body !== undefined && body.hasAttribute(ORDER_ATTR)
603
+ const button = row === null ? null : row.querySelector('[' + PIN_ATTR + ']')
604
+ result.buttonPresent = button !== null
605
+ result.buttonOn = button === null ? null : button.getAttribute('data-dcsp-on')
606
+ await setPinned(sessionId, false)
607
+ await sleep(400)
608
+ scheduleSyncFrame()
609
+ await sleep(400)
610
+ const rowAfter = document.querySelector('[data-dcu-session="' + sessionId + '"]')
611
+ result.pinnedAfterUnpin = isPinned(sessionId)
612
+ result.markAfterUnpin = rowAfter !== null && rowAfter.querySelector('[' + MARK_ATTR + ']') !== null
613
+ result.rowOrderAfterUnpin = rowAfter === null ? null : rowAfter.style.order
614
+ result.restored = JSON.stringify(pinnedIds().slice()) === JSON.stringify(before)
615
+ result.ok =
616
+ result.pinnedAfterPin === true &&
617
+ result.markAfterPin === true &&
618
+ result.rowOrderAfterPin !== '' &&
619
+ result.groupOrdered === true &&
620
+ result.pinnedAfterUnpin === false &&
621
+ result.markAfterUnpin === false &&
622
+ result.rowOrderAfterUnpin === '' &&
623
+ result.restored === true
624
+ } catch (error) {
625
+ result.ok = false
626
+ result.error = String((error && error.message) || error)
627
+ }
628
+ postDiag(result)
629
+ return result
630
+ }
631
+
632
+ window.__dshCodexSessionPin = {
633
+ version: 1,
634
+ pinnedIds,
635
+ isPinned,
636
+ setPinned,
637
+ selfTest,
638
+ census,
639
+ rowsReport,
640
+ rowInfo,
641
+ idsReport,
642
+ sync: scheduleSyncFrame,
643
+ stats,
644
+ hasWorkspacesService: () => workspaces() !== undefined && typeof workspaces().pinSession === 'function',
645
+ }
646
+
647
+ scheduleSyncFrame()
648
+ // Deferred reports are cancelled on unload: a timer that outlives the
649
+ // surfaces would read a global this plugin already deleted.
650
+ let disposed = false
651
+ disposers.push(() => {
652
+ disposed = true
653
+ })
654
+ const readyTimer = window.setTimeout(() => {
655
+ if (disposed) return
656
+ postDiag({
657
+ kind: 'client-ready',
658
+ build: BUILD,
659
+ url: window.location.href,
660
+ hasWorkspacesService: workspaces() !== undefined && typeof workspaces().pinSession === 'function',
661
+ rows: stats.rows,
662
+ pinButtons: stats.pinButtons,
663
+ pinnedIds: pinnedIds(),
664
+ })
665
+ }, 600)
666
+ disposers.push(() => window.clearTimeout(readyTimer))
667
+
668
+ // Same-origin fetch of this plugin's own Host route. The Host renames a
669
+ // live command file away before reading it, so each command runs at
670
+ // most once. The Host answers `disabled` when its Config leaves `probe`
671
+ // off, and polling stops for this page at once: an installed release
672
+ // performs no recurring work. Otherwise the window closes a few minutes
673
+ // after load.
674
+ let running = false
675
+ const deadline = Date.now() + 10 * 60 * 1000
676
+ const poll = window.setInterval(async () => {
677
+ if (running) return
678
+ if (Date.now() > deadline) {
679
+ window.clearInterval(poll)
680
+ return
681
+ }
682
+ running = true
683
+ try {
684
+ const response = await fetch('/codex-session-pin/command', { cache: 'no-store' })
685
+ if (response.status === 204) {
686
+ window.clearInterval(poll)
687
+ return
688
+ }
689
+ if (response.ok) {
690
+ const raw = await response.text()
691
+ let command
692
+ try {
693
+ command = JSON.parse(raw)
694
+ } catch {
695
+ command = undefined
696
+ }
697
+ const action = command === undefined ? undefined : command.action
698
+ if (action !== undefined && action !== 'none' && action !== 'disabled') {
699
+ postDiag({ kind: 'command-received', build: BUILD, action })
700
+ // Commands are matched case-insensitively so a hand-written
701
+ // command file cannot fail on capitalisation alone.
702
+ const wanted = String(action).toLowerCase()
703
+ try {
704
+ if (wanted === 'selftest' && typeof command.sessionId === 'string') {
705
+ await selfTest(command.sessionId)
706
+ } else if (wanted === 'census') {
707
+ postDiag(census())
708
+ } else if (wanted === 'rows') {
709
+ postDiag(rowsReport())
710
+ } else if (wanted === 'row' && typeof command.sessionId === 'string') {
711
+ postDiag(rowInfo(command.sessionId))
712
+ } else if (wanted === 'ids') {
713
+ postDiag(idsReport())
714
+ } else if (wanted === 'sync') {
715
+ scheduleSyncFrame()
716
+ postDiag({ kind: 'client-sync-on-demand', rows: stats.rows, pinButtons: stats.pinButtons })
717
+ } else {
718
+ postDiag({ kind: 'command-unknown', action })
719
+ }
720
+ } catch (error) {
721
+ postDiag({ kind: 'command-error', action, message: String((error && error.message) || error) })
722
+ }
723
+ }
724
+ }
725
+ } catch {
726
+ // A refused probe is not an error state for the user's session.
727
+ } finally {
728
+ running = false
729
+ }
730
+ }, 1500)
731
+ disposers.push(() => window.clearInterval(poll))
732
+ } catch (fatal) {
733
+ postDiag({ kind: 'list-surface-failed', build: BUILD, message: String((fatal && fatal.stack) || fatal).slice(0, 600) })
734
+ }
735
+ }
736
+
737
+ ctx.effect(() => () => {
738
+ for (const dispose of disposers.reverse()) {
739
+ try {
740
+ dispose()
741
+ } catch {
742
+ // A surface already torn down by its owner needs no cleanup.
743
+ }
744
+ }
745
+ try {
746
+ delete window.__dshCodexSessionPin
747
+ } catch {
748
+ // A non-configurable global is left in place; it is inert.
749
+ }
750
+ }, 'dsh-codex-session-pin: surfaces')
751
+ }
752
+
753
+ return {
754
+ inject: ['slots', 'locale'],
755
+ apply(ctx) {
756
+ // A failure anywhere below becomes a diagnostic line: the page console is
757
+ // not visible to support, and a silently blank surface is the worst outcome.
758
+ try {
759
+ applyInner(ctx)
760
+ } catch (error) {
761
+ postDiag({ kind: 'apply-failed', build: BUILD, message: String((error && error.stack) || error).slice(0, 600) })
762
+ throw error
763
+ }
764
+ },
765
+ }
766
+ },
767
+ })