@agy-daddy/plugin-chat-nav 1.1.0 → 1.1.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.
@@ -0,0 +1,664 @@
1
+ 'use strict';
2
+
3
+ const CODE_COPY_ICON = '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>';
4
+ const CODE_FOLD_ICON = '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m18 15-6-6-6 6"/></svg>';
5
+ const CODE_EXPAND_ICON = '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg>';
6
+
7
+ const EXCLUDED_ANCESTOR_SELECTOR = [
8
+ '#agy-chat-nav-float',
9
+ '#agy-chat-outline-rail',
10
+ '#agy-chat-outline-popover',
11
+ '#agy-inline-file-editor-panel',
12
+ '[data-testid="settings-dialog"]',
13
+ '[role="dialog"]',
14
+ '[role="alertdialog"]',
15
+ 'dialog',
16
+ '.monaco-editor',
17
+ '.cm-editor',
18
+ '.CodeMirror'
19
+ ].join(', ');
20
+
21
+ const CODE_CONTAINER_SELECTORS = [
22
+ '[data-testid="autoscroll-viewport"] pre',
23
+ '[data-testid="user-message"] pre',
24
+ '[data-testid="agent-response"] pre',
25
+ '[data-testid*="artifact"] pre',
26
+ '[aria-label*="Artifact"] pre',
27
+ '[aria-label*="artifact"] pre',
28
+ '[aria-label*="产物"] pre',
29
+ '[aria-label*="File Viewer"] pre',
30
+ '[aria-label*="文件查看器"] pre',
31
+ '.artifact-content pre',
32
+ '.markdown-body pre',
33
+ '.prose pre'
34
+ ].join(', ');
35
+
36
+ function getPrevElementSibling(el) {
37
+ if (!el) return null;
38
+ if (el.previousElementSibling !== undefined) return el.previousElementSibling;
39
+ const children = el.parentElement?.children;
40
+ if (!Array.isArray(children)) return null;
41
+ const idx = children.indexOf(el);
42
+ return idx > 0 ? children[idx - 1] : null;
43
+ }
44
+
45
+ function getNextElementSibling(el) {
46
+ if (!el) return null;
47
+ if (el.nextElementSibling !== undefined) return el.nextElementSibling;
48
+ const children = el.parentElement?.children;
49
+ if (!Array.isArray(children)) return null;
50
+ const idx = children.indexOf(el);
51
+ return idx >= 0 && idx + 1 < children.length ? children[idx + 1] : null;
52
+ }
53
+
54
+ function getRectSafe(el) {
55
+ if (!el || typeof el.getBoundingClientRect !== 'function') return null;
56
+ try {
57
+ return el.getBoundingClientRect() || null;
58
+ } catch {
59
+ return null;
60
+ }
61
+ }
62
+
63
+ function countCodeLines(rawText) {
64
+ const str = String(rawText ?? '').replace(/\r\n/g, '\n');
65
+ if (!str) return 0;
66
+ const normalized = str.endsWith('\n') ? str.slice(0, -1) : str;
67
+ if (!normalized) return 0;
68
+ return normalized.split('\n').length;
69
+ }
70
+
71
+ function extractCodeText(preEl) {
72
+ if (!preEl) return '';
73
+ const codeEl = preEl.querySelector?.('code') || preEl;
74
+ return String(codeEl?.textContent ?? preEl.textContent ?? '');
75
+ }
76
+
77
+ function extractCodeLanguage(preEl, nativeHeaderEl = null) {
78
+ const codeEl = preEl?.querySelector?.('code');
79
+ const candidates = [
80
+ codeEl?.getAttribute?.('data-language'),
81
+ codeEl?.getAttribute?.('data-lang'),
82
+ preEl?.getAttribute?.('data-language'),
83
+ preEl?.getAttribute?.('data-lang'),
84
+ codeEl?.className,
85
+ preEl?.className
86
+ ];
87
+ for (const cand of candidates) {
88
+ if (!cand) continue;
89
+ const str = String(cand);
90
+ const match = /(?:^|\s)(?:language-|lang-)([a-zA-Z0-9_+#.-]+)/i.exec(str);
91
+ if (match) return match[1].toLowerCase();
92
+ if (!/\s/.test(str) && /^[a-zA-Z0-9_+#.-]{1,24}$/.test(str) && !/^(hljs|shiki|prose|not-prose)$/i.test(str)) {
93
+ return str.toLowerCase();
94
+ }
95
+ }
96
+ if (nativeHeaderEl) {
97
+ const hdrText = String(nativeHeaderEl.textContent || '')
98
+ .replace(/复制代码|复制|copy code|copy|折叠|展开|collapse|expand/gi, ' ')
99
+ .trim();
100
+ const firstToken = hdrText.split(/\s+/).find((t) => /^[a-zA-Z0-9_+#.-]{1,20}$/.test(t));
101
+ if (firstToken) return firstToken.toLowerCase();
102
+ }
103
+ return 'code';
104
+ }
105
+
106
+ function isCodeBlockCompleted(preEl, opts = {}) {
107
+ if (!preEl) return false;
108
+ if (preEl.getAttribute?.('data-streaming') === 'true' || preEl.closest?.('[data-streaming="true"]')) {
109
+ return false;
110
+ }
111
+ if (!opts.isAssistantBusy) return true;
112
+ const doc = opts.doc || preEl.ownerDocument;
113
+ const vp = opts.viewport || doc?.querySelector?.('[data-testid="autoscroll-viewport"]');
114
+ const responses = vp?.querySelectorAll
115
+ ? Array.from(vp.querySelectorAll('[data-testid="agent-response"]') || [])
116
+ : (doc?.querySelectorAll ? Array.from(doc.querySelectorAll('[data-testid="agent-response"]') || []) : []);
117
+ if (responses.length === 0) return true;
118
+ const lastResp = responses[responses.length - 1];
119
+ if (!lastResp || (lastResp !== preEl && !lastResp.contains?.(preEl))) {
120
+ return true;
121
+ }
122
+ const presInLast = Array.from(lastResp.querySelectorAll?.('pre') || []);
123
+ if (presInLast.length === 0) return true;
124
+ return presInLast[presInLast.length - 1] !== preEl;
125
+ }
126
+
127
+ function computeCollapseScrollCompensation({
128
+ blockTop = 0,
129
+ blockHeightBefore = 0,
130
+ blockHeightAfter = 0,
131
+ viewportTop = 0,
132
+ scrollTop = 0
133
+ } = {}) {
134
+ const curTop = Math.max(0, Number(scrollTop) || 0);
135
+ const deltaHeight = Math.max(0, (Number(blockHeightBefore) || 0) - (Number(blockHeightAfter) || 0));
136
+ if (deltaHeight <= 0) return curTop;
137
+ const overlapAbove = Math.max(0, (Number(viewportTop) || 0) - (Number(blockTop) || 0));
138
+ if (overlapAbove <= 0) return curTop;
139
+ const compensate = Math.min(overlapAbove, deltaHeight);
140
+ return Math.max(0, Math.round(curTop - compensate));
141
+ }
142
+
143
+ function isMessageRootElement(el) {
144
+ if (!el) return false;
145
+ const tid = el.getAttribute?.('data-testid');
146
+ if (tid === 'user-message' || tid === 'agent-response' || tid === 'autoscroll-viewport' || tid === 'turn-cards-container') {
147
+ return true;
148
+ }
149
+ const tag = String(el.tagName || '').toLowerCase();
150
+ return tag === 'body' || tag === 'html' || tag === 'main' || tag === 'article';
151
+ }
152
+
153
+ function findNativeCodeHeader(preEl) {
154
+ const parent = preEl?.parentElement;
155
+ if (!parent || isMessageRootElement(parent)) return null;
156
+ const prev = getPrevElementSibling(preEl);
157
+ if (!prev || prev.getAttribute?.('data-agy-code-injected') === '1') return null;
158
+ const prevTag = String(prev.tagName || '').toLowerCase();
159
+ if (prevTag === 'pre' || prevTag === 'p' || prevTag === 'ul' || prevTag === 'ol' || /^h[1-6]$/.test(prevTag)) {
160
+ return null;
161
+ }
162
+ const hasCopyBtn = Boolean(
163
+ prev.querySelector?.('button[aria-label*="copy" i], button[title*="copy" i], button[aria-label*="复制"], button[title*="复制"], [data-testid*="copy"]')
164
+ );
165
+ const nonInjectedSiblings = Array.from(parent.children || []).filter(
166
+ (ch) => ch && ch.getAttribute?.('data-agy-code-injected') !== '1' && ch.getAttribute?.('data-agy-code-collapsed-bar') !== '1'
167
+ );
168
+ const compactHeader = nonInjectedSiblings.length <= 3 && String(prev.textContent || '').trim().length <= 64;
169
+ if (hasCopyBtn || compactHeader) {
170
+ return prev;
171
+ }
172
+ return null;
173
+ }
174
+
175
+ function createCodeBlockEnhancer(deps = {}) {
176
+ const {
177
+ doc,
178
+ win,
179
+ anchors,
180
+ hostDom,
181
+ copyText,
182
+ showToast,
183
+ getSettings,
184
+ onDomMutated
185
+ } = deps;
186
+
187
+ const trackedBlocks = new Map(); // preEl -> record
188
+ let domObserver = null;
189
+ let refreshTimer = null;
190
+ let rafId = null;
191
+ let onViewportScroll = null;
192
+ let observedScrollEl = null;
193
+ let disposed = false;
194
+
195
+ function readSettings() {
196
+ const raw = typeof getSettings === 'function' ? (getSettings() || {}) : {};
197
+ const minLines = Number(raw.codeFoldMinLines);
198
+ return {
199
+ enableCodeBlockSticky: raw.enableCodeBlockSticky !== false,
200
+ enableCodeBlockFold: raw.enableCodeBlockFold !== false,
201
+ codeFoldMinLines: Number.isFinite(minLines) && minLines >= 12 ? Math.min(500, Math.round(minLines)) : 48
202
+ };
203
+ }
204
+
205
+ function findNearestScrollViewport(el) {
206
+ const chatVp = anchors?.query?.('chat.scrollViewport') || null;
207
+ if (chatVp && chatVp.contains?.(el)) return chatVp;
208
+ let cur = el?.parentElement;
209
+ while (cur && cur !== doc?.body && cur !== doc?.documentElement) {
210
+ if (typeof win?.getComputedStyle === 'function') {
211
+ try {
212
+ const ov = String(win.getComputedStyle(cur)?.overflowY || '');
213
+ if (ov === 'auto' || ov === 'scroll') return cur;
214
+ } catch {}
215
+ }
216
+ if (Number(cur.scrollHeight || 0) > Number(cur.clientHeight || 0) + 8) {
217
+ return cur;
218
+ }
219
+ cur = cur.parentElement;
220
+ }
221
+ return chatVp;
222
+ }
223
+
224
+ function updateRecordUi(rec, cfg) {
225
+ const { preEl, wrapEl, headerEl, isNativeHeader, foldBtn, collapsedBar, linesEl, lineCount, completed } = rec;
226
+ const canFold = cfg.enableCodeBlockFold && completed && lineCount >= cfg.codeFoldMinLines;
227
+ const isCollapsed = canFold && rec.collapsed;
228
+
229
+ if (wrapEl) {
230
+ if (cfg.enableCodeBlockSticky) wrapEl.setAttribute?.('data-agy-code-wrap', '1');
231
+ else wrapEl.removeAttribute?.('data-agy-code-wrap');
232
+ if (isCollapsed) wrapEl.setAttribute?.('data-agy-code-collapsed', 'true');
233
+ else wrapEl.removeAttribute?.('data-agy-code-collapsed');
234
+ }
235
+
236
+ if (headerEl) {
237
+ if (cfg.enableCodeBlockSticky) {
238
+ headerEl.setAttribute?.('data-agy-code-header', isNativeHeader ? 'native' : 'injected');
239
+ } else if (isNativeHeader) {
240
+ headerEl.removeAttribute?.('data-agy-code-header');
241
+ } else {
242
+ headerEl.setAttribute?.('data-agy-code-header', 'static');
243
+ }
244
+ headerEl.hidden = !isNativeHeader && !cfg.enableCodeBlockSticky && !canFold;
245
+ if (headerEl.hidden) headerEl.setAttribute?.('hidden', 'true');
246
+ else headerEl.removeAttribute?.('hidden');
247
+ }
248
+
249
+ if (linesEl) {
250
+ linesEl.textContent = `${lineCount} 行`;
251
+ }
252
+
253
+ if (foldBtn) {
254
+ foldBtn.hidden = !canFold;
255
+ if (!canFold) {
256
+ foldBtn.setAttribute?.('hidden', 'true');
257
+ } else {
258
+ foldBtn.removeAttribute?.('hidden');
259
+ foldBtn.setAttribute?.('aria-expanded', isCollapsed ? 'false' : 'true');
260
+ foldBtn.setAttribute?.('data-collapsed', isCollapsed ? 'true' : 'false');
261
+ const label = isCollapsed ? `展开 (${lineCount} 行)` : '折叠';
262
+ foldBtn.setAttribute?.('title', isCollapsed ? `展开代码块 (${lineCount} 行)` : `折叠长代码块 (${lineCount} 行)`);
263
+ foldBtn.setAttribute?.('aria-label', label);
264
+ foldBtn.innerHTML = `${isCollapsed ? CODE_EXPAND_ICON : CODE_FOLD_ICON}<span>${label}</span>`;
265
+ }
266
+ }
267
+
268
+ if (isCollapsed) {
269
+ preEl.setAttribute?.('data-agy-code-collapsed', 'true');
270
+ } else {
271
+ preEl.removeAttribute?.('data-agy-code-collapsed');
272
+ }
273
+
274
+ if (collapsedBar) {
275
+ collapsedBar.hidden = !isCollapsed;
276
+ if (!isCollapsed) collapsedBar.setAttribute?.('hidden', 'true');
277
+ else {
278
+ collapsedBar.removeAttribute?.('hidden');
279
+ collapsedBar.textContent = `已折叠 ${lineCount} 行代码 · 点击展开`;
280
+ }
281
+ }
282
+ }
283
+
284
+ function setRecordCollapsed(rec, nextCollapsed) {
285
+ if (!rec || rec.collapsed === Boolean(nextCollapsed)) return false;
286
+ const cfg = readSettings();
287
+ const canFold = cfg.enableCodeBlockFold && rec.completed && rec.lineCount >= cfg.codeFoldMinLines;
288
+ if (nextCollapsed && !canFold) return false;
289
+
290
+ const vp = findNearestScrollViewport(rec.preEl);
291
+ const vpRect = getRectSafe(vp);
292
+ const targetBlock = rec.wrapEl || rec.preEl;
293
+ const beforeRect = getRectSafe(targetBlock);
294
+ const beforeScrollTop = vp ? Number(vp.scrollTop || 0) : 0;
295
+
296
+ rec.collapsed = Boolean(nextCollapsed);
297
+ updateRecordUi(rec, cfg);
298
+
299
+ if (rec.collapsed && vp && vpRect && beforeRect && beforeRect.height > 0) {
300
+ const afterRect = getRectSafe(targetBlock);
301
+ const afterHeight = afterRect ? Number(afterRect.height || 0) : 36;
302
+ const nextTop = computeCollapseScrollCompensation({
303
+ blockTop: beforeRect.top,
304
+ blockHeightBefore: beforeRect.height,
305
+ blockHeightAfter: afterHeight,
306
+ viewportTop: vpRect.top,
307
+ scrollTop: beforeScrollTop
308
+ });
309
+ if (nextTop !== beforeScrollTop) {
310
+ vp.scrollTop = nextTop;
311
+ }
312
+ }
313
+ if (rec.headerEl) {
314
+ rec.headerEl.removeAttribute?.('data-agy-sticky-ended');
315
+ }
316
+ return true;
317
+ }
318
+
319
+ function syncBareStickyHeaders() {
320
+ const vp = anchors?.query?.('chat.scrollViewport');
321
+ const vpRect = getRectSafe(vp);
322
+ if (!vpRect) return;
323
+ for (const rec of trackedBlocks.values()) {
324
+ if (!rec.headerEl || rec.hasDedicatedWrapper || rec.isNativeHeader) continue;
325
+ const preRect = getRectSafe(rec.preEl);
326
+ const hdrRect = getRectSafe(rec.headerEl);
327
+ if (!preRect || !hdrRect) continue;
328
+ const ended = preRect.bottom < vpRect.top + hdrRect.height + 4;
329
+ if (ended) rec.headerEl.setAttribute?.('data-agy-sticky-ended', 'true');
330
+ else rec.headerEl.removeAttribute?.('data-agy-sticky-ended');
331
+ }
332
+ }
333
+
334
+ function cleanupRecord(preEl) {
335
+ const rec = trackedBlocks.get(preEl);
336
+ if (!rec) return;
337
+ trackedBlocks.delete(preEl);
338
+ if (rec.foldBtn?.remove) rec.foldBtn.remove();
339
+ if (rec.collapsedBar?.remove) rec.collapsedBar.remove();
340
+ if (!rec.isNativeHeader && rec.headerEl?.remove) rec.headerEl.remove();
341
+ if (rec.isNativeHeader && rec.headerEl) {
342
+ rec.headerEl.removeAttribute?.('data-agy-code-header');
343
+ rec.headerEl.removeAttribute?.('data-agy-sticky-ended');
344
+ }
345
+ if (rec.wrapEl) {
346
+ rec.wrapEl.removeAttribute?.('data-agy-code-wrap');
347
+ rec.wrapEl.removeAttribute?.('data-agy-code-collapsed');
348
+ }
349
+ preEl?.removeAttribute?.('data-agy-code-collapsed');
350
+ preEl?.removeAttribute?.('data-agy-code-enhanced');
351
+ }
352
+
353
+ function enhancePre(preEl, cfg, isBusy) {
354
+ if (!preEl || !doc?.createElement) return;
355
+ if (preEl.closest?.(EXCLUDED_ANCESTOR_SELECTOR)) return;
356
+
357
+ const rawText = extractCodeText(preEl);
358
+ const lineCount = countCodeLines(rawText);
359
+ const completed = isCodeBlockCompleted(preEl, {
360
+ isAssistantBusy: isBusy,
361
+ doc,
362
+ viewport: anchors?.query?.('chat.scrollViewport')
363
+ });
364
+
365
+ const existing = trackedBlocks.get(preEl);
366
+ if (existing) {
367
+ existing.lineCount = lineCount;
368
+ existing.completed = completed;
369
+ if (!completed && existing.collapsed) existing.collapsed = false;
370
+ updateRecordUi(existing, cfg);
371
+ return;
372
+ }
373
+
374
+ const nativeHeader = findNativeCodeHeader(preEl);
375
+ const parent = preEl.parentElement;
376
+ if (!parent) return;
377
+
378
+ const nonInjectedSiblings = Array.from(parent.children || []).filter(
379
+ (ch) => ch && ch.getAttribute?.('data-agy-code-injected') !== '1' && ch.getAttribute?.('data-agy-code-collapsed-bar') !== '1'
380
+ );
381
+ const hasDedicatedWrapper = !isMessageRootElement(parent) && nonInjectedSiblings.length <= (nativeHeader ? 3 : 2);
382
+ const wrapEl = hasDedicatedWrapper ? parent : null;
383
+ const lang = extractCodeLanguage(preEl, nativeHeader);
384
+
385
+ let headerEl = nativeHeader;
386
+ let linesEl = null;
387
+ let foldBtn = null;
388
+
389
+ if (!headerEl) {
390
+ headerEl = doc.createElement('div');
391
+ headerEl.className = 'agy-code-header';
392
+ headerEl.setAttribute?.('data-agy-code-injected', '1');
393
+ headerEl.setAttribute?.('data-agy-code-header', 'injected');
394
+
395
+ const leftGroup = doc.createElement('div');
396
+ leftGroup.className = 'agy-code-header-left';
397
+ const langEl = doc.createElement('span');
398
+ langEl.className = 'agy-code-lang';
399
+ langEl.textContent = lang;
400
+ leftGroup.appendChild(langEl);
401
+
402
+ linesEl = doc.createElement('span');
403
+ linesEl.className = 'agy-code-lines';
404
+ linesEl.textContent = `${lineCount} 行`;
405
+ leftGroup.appendChild(linesEl);
406
+
407
+ const rightGroup = doc.createElement('div');
408
+ rightGroup.className = 'agy-code-header-actions';
409
+
410
+ foldBtn = doc.createElement('button');
411
+ foldBtn.type = 'button';
412
+ foldBtn.className = 'agy-code-fold-btn';
413
+ foldBtn.setAttribute?.('data-agy-code-fold', '1');
414
+ rightGroup.appendChild(foldBtn);
415
+
416
+ const copyBtn = doc.createElement('button');
417
+ copyBtn.type = 'button';
418
+ copyBtn.className = 'agy-code-copy-btn';
419
+ copyBtn.setAttribute?.('aria-label', '复制代码');
420
+ copyBtn.setAttribute?.('title', '复制代码');
421
+ copyBtn.innerHTML = `${CODE_COPY_ICON}<span>复制</span>`;
422
+ copyBtn.addEventListener('click', (e) => {
423
+ e?.stopPropagation?.();
424
+ const txt = extractCodeText(preEl);
425
+ if (typeof copyText === 'function') {
426
+ Promise.resolve(copyText(txt)).then((ok) => {
427
+ if (ok !== false) showToast?.('已复制代码');
428
+ }).catch(() => {});
429
+ }
430
+ });
431
+ rightGroup.appendChild(copyBtn);
432
+
433
+ headerEl.appendChild(leftGroup);
434
+ headerEl.appendChild(rightGroup);
435
+ parent.insertBefore(headerEl, preEl);
436
+ } else {
437
+ foldBtn = doc.createElement('button');
438
+ foldBtn.type = 'button';
439
+ foldBtn.className = 'agy-code-fold-btn';
440
+ foldBtn.setAttribute?.('data-agy-code-fold', '1');
441
+ const existingCopy = nativeHeader.querySelector?.('button[aria-label*="copy" i], button[title*="copy" i], button[aria-label*="复制"], button[title*="复制"], button');
442
+ const actionHost = existingCopy?.parentElement && existingCopy.parentElement !== nativeHeader
443
+ ? existingCopy.parentElement
444
+ : nativeHeader;
445
+ if (existingCopy && existingCopy.parentElement === actionHost) {
446
+ actionHost.insertBefore(foldBtn, existingCopy);
447
+ } else {
448
+ actionHost.appendChild(foldBtn);
449
+ }
450
+ }
451
+
452
+ const collapsedBar = doc.createElement('button');
453
+ collapsedBar.type = 'button';
454
+ collapsedBar.className = 'agy-code-collapsed-bar';
455
+ collapsedBar.setAttribute?.('data-agy-code-collapsed-bar', '1');
456
+ collapsedBar.hidden = true;
457
+ collapsedBar.setAttribute?.('hidden', 'true');
458
+ const nextSib = getNextElementSibling(preEl);
459
+ if (nextSib) parent.insertBefore(collapsedBar, nextSib);
460
+ else parent.appendChild(collapsedBar);
461
+
462
+ const rec = {
463
+ preEl,
464
+ wrapEl,
465
+ headerEl,
466
+ isNativeHeader: Boolean(nativeHeader),
467
+ hasDedicatedWrapper,
468
+ linesEl,
469
+ foldBtn,
470
+ collapsedBar,
471
+ lineCount,
472
+ completed,
473
+ collapsed: false
474
+ };
475
+
476
+ foldBtn.addEventListener('click', (e) => {
477
+ e?.stopPropagation?.();
478
+ setRecordCollapsed(rec, !rec.collapsed);
479
+ });
480
+ collapsedBar.addEventListener('click', (e) => {
481
+ e?.stopPropagation?.();
482
+ setRecordCollapsed(rec, false);
483
+ });
484
+
485
+ preEl.setAttribute?.('data-agy-code-enhanced', '1');
486
+ trackedBlocks.set(preEl, rec);
487
+ updateRecordUi(rec, cfg);
488
+ }
489
+
490
+ function queryTargetPres() {
491
+ const seen = new Set();
492
+ const out = [];
493
+ const add = (el) => {
494
+ if (!el || seen.has(el)) return;
495
+ seen.add(el);
496
+ out.push(el);
497
+ };
498
+ const vp = anchors?.query?.('chat.scrollViewport');
499
+ if (vp?.querySelectorAll) {
500
+ for (const el of vp.querySelectorAll('pre') || []) add(el);
501
+ }
502
+ if (doc?.querySelectorAll) {
503
+ try {
504
+ for (const el of doc.querySelectorAll(CODE_CONTAINER_SELECTORS) || []) add(el);
505
+ } catch {
506
+ for (const el of doc.querySelectorAll('pre') || []) add(el);
507
+ }
508
+ }
509
+ return out;
510
+ }
511
+
512
+ function attachViewportScrollListener() {
513
+ const vp = anchors?.query?.('chat.scrollViewport') || null;
514
+ if (vp === observedScrollEl) return;
515
+ if (observedScrollEl && onViewportScroll) {
516
+ try { observedScrollEl.removeEventListener?.('scroll', onViewportScroll); } catch {}
517
+ }
518
+ observedScrollEl = vp;
519
+ if (vp && vp.addEventListener) {
520
+ onViewportScroll = () => syncBareStickyHeaders();
521
+ vp.addEventListener('scroll', onViewportScroll, { passive: true });
522
+ } else {
523
+ onViewportScroll = null;
524
+ }
525
+ }
526
+
527
+ function refresh() {
528
+ if (disposed) return 0;
529
+ attachViewportScrollListener();
530
+ const cfg = readSettings();
531
+ const isBusy = Boolean(hostDom?.isAssistantBusy?.());
532
+
533
+ if (!cfg.enableCodeBlockSticky && !cfg.enableCodeBlockFold) {
534
+ for (const preEl of Array.from(trackedBlocks.keys())) {
535
+ cleanupRecord(preEl);
536
+ }
537
+ return 0;
538
+ }
539
+
540
+ const activePres = new Set(queryTargetPres());
541
+ for (const preEl of Array.from(trackedBlocks.keys())) {
542
+ if (!activePres.has(preEl) || !preEl.parentElement) {
543
+ cleanupRecord(preEl);
544
+ }
545
+ }
546
+ for (const preEl of activePres) {
547
+ enhancePre(preEl, cfg, isBusy);
548
+ }
549
+ syncBareStickyHeaders();
550
+ return trackedBlocks.size;
551
+ }
552
+
553
+ function scheduleRefresh() {
554
+ if (disposed || refreshTimer !== null) return;
555
+ refreshTimer = setTimeout(() => {
556
+ refreshTimer = null;
557
+ refresh();
558
+ if (typeof onDomMutated === 'function') {
559
+ try { onDomMutated(); } catch {}
560
+ }
561
+ }, 60);
562
+ }
563
+
564
+ function isPluginOwnedNode(node) {
565
+ if (!node || typeof node.getAttribute !== 'function') return false;
566
+ return Boolean(
567
+ node.getAttribute('data-agy-code-injected') === '1'
568
+ || node.getAttribute('data-agy-code-fold') === '1'
569
+ || node.getAttribute('data-agy-code-collapsed-bar') === '1'
570
+ || node.id === 'agy-chat-nav-float'
571
+ || node.id === 'agy-chat-outline-rail'
572
+ || node.id === 'agy-chat-outline-popover'
573
+ );
574
+ }
575
+
576
+ function toggleAllLongBlocks(forceState) {
577
+ const cfg = readSettings();
578
+ if (!cfg.enableCodeBlockFold) return 0;
579
+ const eligible = Array.from(trackedBlocks.values()).filter(
580
+ (r) => r.completed && r.lineCount >= cfg.codeFoldMinLines
581
+ );
582
+ if (eligible.length === 0) return 0;
583
+ const targetCollapsed = typeof forceState === 'boolean'
584
+ ? forceState
585
+ : eligible.some((r) => !r.collapsed);
586
+ let changed = 0;
587
+ for (const rec of eligible) {
588
+ if (setRecordCollapsed(rec, targetCollapsed)) changed++;
589
+ }
590
+ return changed;
591
+ }
592
+
593
+ function startObserver() {
594
+ const MO = win?.MutationObserver || globalThis.MutationObserver;
595
+ const root = doc?.body || doc?.documentElement;
596
+ if (typeof MO !== 'function' || !root) return;
597
+ domObserver = new MO((records) => {
598
+ let relevant = false;
599
+ for (const rec of records || []) {
600
+ if (isPluginOwnedNode(rec.target)) continue;
601
+ const nodes = [...Array.from(rec.addedNodes || []), ...Array.from(rec.removedNodes || [])];
602
+ if (nodes.length === 0 || nodes.some((n) => !isPluginOwnedNode(n))) {
603
+ relevant = true;
604
+ break;
605
+ }
606
+ }
607
+ if (relevant) scheduleRefresh();
608
+ });
609
+ try {
610
+ domObserver.observe(root, { childList: true, subtree: true });
611
+ } catch {
612
+ domObserver = null;
613
+ }
614
+ }
615
+
616
+ function dispose() {
617
+ disposed = true;
618
+ if (refreshTimer !== null) {
619
+ clearTimeout(refreshTimer);
620
+ refreshTimer = null;
621
+ }
622
+ if (rafId !== null && typeof win?.cancelAnimationFrame === 'function') {
623
+ try { win.cancelAnimationFrame(rafId); } catch {}
624
+ rafId = null;
625
+ }
626
+ if (domObserver) {
627
+ try { domObserver.disconnect(); } catch {}
628
+ domObserver = null;
629
+ }
630
+ if (observedScrollEl && onViewportScroll) {
631
+ try { observedScrollEl.removeEventListener?.('scroll', onViewportScroll); } catch {}
632
+ }
633
+ observedScrollEl = null;
634
+ onViewportScroll = null;
635
+ for (const preEl of Array.from(trackedBlocks.keys())) {
636
+ cleanupRecord(preEl);
637
+ }
638
+ trackedBlocks.clear();
639
+ }
640
+
641
+ startObserver();
642
+ refresh();
643
+
644
+ return {
645
+ refresh,
646
+ scheduleRefresh,
647
+ toggleAllLongBlocks,
648
+ getTrackedBlocks: () => Array.from(trackedBlocks.values()),
649
+ setBlockCollapsed: (preEl, collapsed) => {
650
+ const rec = trackedBlocks.get(preEl);
651
+ return rec ? setRecordCollapsed(rec, collapsed) : false;
652
+ },
653
+ dispose
654
+ };
655
+ }
656
+
657
+ module.exports = {
658
+ countCodeLines,
659
+ extractCodeLanguage,
660
+ isCodeBlockCompleted,
661
+ computeCollapseScrollCompensation,
662
+ findNativeCodeHeader,
663
+ createCodeBlockEnhancer
664
+ };