@agy-daddy/plugin-chat-nav 0.0.0-stage → 1.1.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.
@@ -0,0 +1,1817 @@
1
+ 'use strict';
2
+
3
+ const { CHAT_NAV_STYLES } = require('./styles');
4
+
5
+ const DEFAULT_SETTINGS = Object.freeze({
6
+ showFloatDock: true,
7
+ keepThinkingExpanded: false,
8
+ enableInlineFileEditor: true,
9
+ enableCmdClickLinks: true,
10
+ searchRegexMode: false,
11
+ searchCaseSensitive: false,
12
+ exportSaveBehavior: 'dialog',
13
+ exportSaveDir: '',
14
+ exportFormats: ['md']
15
+ });
16
+
17
+ const EXPORT_FORMAT_META = Object.freeze({
18
+ md: { id: 'md', label: 'Markdown', ext: '.md' },
19
+ html: { id: 'html', label: '网页 HTML', ext: '.html' },
20
+ pdf: { id: 'pdf', label: 'PDF 文档', ext: '.pdf' }
21
+ });
22
+
23
+ function normalizeExportFormats(raw) {
24
+ const arr = Array.isArray(raw) ? raw : (typeof raw === 'string' ? [raw] : []);
25
+ const out = [];
26
+ const seen = new Set();
27
+ for (const item of arr) {
28
+ let val = '';
29
+ if (typeof item === 'string') val = item.trim();
30
+ else if (item && typeof item === 'object') val = String(item.id || item.value || '').trim();
31
+ const norm = val.toLowerCase() === 'markdown' ? 'md' : val.toLowerCase();
32
+ if (!EXPORT_FORMAT_META[norm] || seen.has(norm)) continue;
33
+ seen.add(norm);
34
+ out.push(norm);
35
+ }
36
+ return out.length > 0 ? out : ['md'];
37
+ }
38
+
39
+ function normalizeRendererSettings(raw = {}) {
40
+ const merged = {
41
+ ...DEFAULT_SETTINGS,
42
+ ...(raw && typeof raw === 'object' ? raw : {})
43
+ };
44
+ merged.exportSaveBehavior = merged.exportSaveBehavior === 'direct' ? 'direct' : 'dialog';
45
+ merged.exportSaveDir = typeof merged.exportSaveDir === 'string' ? merged.exportSaveDir.trim() : '';
46
+ merged.exportFormats = normalizeExportFormats(merged.exportFormats);
47
+ return merged;
48
+ }
49
+
50
+ function createSearchMatcher(query, regexMode, caseSensitive) {
51
+ const q = String(query || '').trim();
52
+ if (!q) return null;
53
+ if (regexMode) {
54
+ try {
55
+ const re = new RegExp(q, caseSensitive ? '' : 'i');
56
+ return (txt) => re.test(txt);
57
+ } catch {
58
+ return () => false;
59
+ }
60
+ }
61
+ const needle = caseSensitive ? q : q.toLowerCase();
62
+ return (txt) => (caseSensitive ? txt.includes(needle) : txt.toLowerCase().includes(needle));
63
+ }
64
+
65
+ function escapeRegExp(str) {
66
+ return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
67
+ }
68
+
69
+ function findRangesInText(text, query, regexMode, caseSensitive, maxHits = 2000) {
70
+ const q = String(query || '').trim();
71
+ if (!q || !text) return [];
72
+ let re;
73
+ try {
74
+ const source = regexMode ? q : escapeRegExp(q);
75
+ re = new RegExp(source, caseSensitive ? 'g' : 'gi');
76
+ } catch {
77
+ return [];
78
+ }
79
+ const out = [];
80
+ let m;
81
+ while ((m = re.exec(text)) !== null) {
82
+ if (m[0].length === 0) {
83
+ re.lastIndex += 1;
84
+ continue;
85
+ }
86
+ out.push({ start: m.index, end: m.index + m[0].length });
87
+ if (out.length >= maxHits) break;
88
+ }
89
+ return out;
90
+ }
91
+
92
+ const NAV_ICONS = Object.freeze({
93
+ top: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 5h14"/><path d="M12 19V9"/><path d="m7 14 5-5 5 5"/></svg>',
94
+ prev: '<svg width="14" height="14" 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>',
95
+ next: '<svg width="14" height="14" 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>',
96
+ bottom: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 19h14"/><path d="M12 5v10"/><path d="m7 10 5 5 5-5"/></svg>',
97
+ think: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5"/><path d="M9 18h6"/><path d="M10 22h4"/></svg>',
98
+ search: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>',
99
+ copyId: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" 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>',
100
+ exportMd: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>'
101
+ });
102
+
103
+ let disposers = [];
104
+
105
+ function isSafeExternalUrl(rawUrl) {
106
+ if (!rawUrl || typeof rawUrl !== 'string') return false;
107
+ const trimmed = rawUrl.trim();
108
+ if (!trimmed) return false;
109
+ if (typeof URL === 'function') {
110
+ try {
111
+ const u = new URL(trimmed);
112
+ return u.protocol === 'http:' || u.protocol === 'https:' || u.protocol === 'mailto:';
113
+ } catch {
114
+ return false;
115
+ }
116
+ }
117
+ return /^(?:https?:\/\/[^\s/$.?#][^\s]*|mailto:[^\s@]+@[^\s@]+)$/i.test(trimmed);
118
+ }
119
+
120
+ async function mount(ctx, options = {}) {
121
+ let settings = normalizeRendererSettings(ctx.settings?.get?.() || {});
122
+
123
+ const stopStyles = ctx.styles?.inject?.(CHAT_NAV_STYLES, {
124
+ scope: 'document',
125
+ id: 'chat-nav-styles'
126
+ });
127
+
128
+ const doc = options.document
129
+ || ctx.anchors.query('chat.scrollViewport')?.ownerDocument
130
+ || ctx.anchors.query('composer.root')?.ownerDocument
131
+ || ctx.anchors.query('sidebar.conversationRows')?.ownerDocument
132
+ || globalThis.document;
133
+ const win = options.window || (typeof globalThis.window !== 'undefined' ? globalThis.window : null);
134
+
135
+ const customButtons = new Map();
136
+ const customButtonNodes = [];
137
+ const mountedBadges = [];
138
+ let dockEl = null;
139
+ let extraButtonsSlot = null;
140
+ let searchSlot = null;
141
+ let searchBoxEl = null;
142
+ let searchInputEl = null;
143
+ let searchCountEl = null;
144
+ let searchPrevBtn = null;
145
+ let searchNextBtn = null;
146
+ let searchToggleBtn = null;
147
+ let thinkBtn = null;
148
+ let copyIdBtn = null;
149
+ let exportBtnEl = null;
150
+ let exportMenuEl = null;
151
+ let exportMenuOpen = false;
152
+ let toastEl = null;
153
+ let toastTimer = null;
154
+ let copyFeedbackTimer = null;
155
+ let exportLoading = false;
156
+ let latestContextCascadeId = null;
157
+ let searchOpen = false;
158
+ let searchMatches = [];
159
+ let searchMode = 'block';
160
+ let searchActiveIdx = -1;
161
+ let lastSearchQuery = '';
162
+ let thinkingToggleFallback = false;
163
+ let pendingThinkTimer = null;
164
+ let lastTurnNav = null;
165
+ let dockResizeObserver = null;
166
+ let observedAreaEl = null;
167
+ let dockRafId = null;
168
+ let dockRafUsingTimeout = false;
169
+ let onSearchSlotKeyDown = null;
170
+ let revokeNavButtonsSurface = null;
171
+ let editorControlEl = null;
172
+ let editorPanelEl = null;
173
+ let editorTextareaEl = null;
174
+ let activeEditorPath = '';
175
+ let activeConvIndex = 0;
176
+
177
+ function clearNodes(list) {
178
+ while (list.length > 0) {
179
+ const node = list.pop();
180
+ if (node?.remove) node.remove();
181
+ }
182
+ }
183
+
184
+ function cancelScheduledSync() {
185
+ if (dockRafId !== null) {
186
+ if (dockRafUsingTimeout) {
187
+ clearTimeout(dockRafId);
188
+ } else if (win && typeof win.cancelAnimationFrame === 'function') {
189
+ try { win.cancelAnimationFrame(dockRafId); } catch {}
190
+ } else if (typeof globalThis.cancelAnimationFrame === 'function') {
191
+ try { globalThis.cancelAnimationFrame(dockRafId); } catch {}
192
+ }
193
+ dockRafId = null;
194
+ dockRafUsingTimeout = false;
195
+ }
196
+ }
197
+
198
+ function clearPendingThinkTimer() {
199
+ if (pendingThinkTimer !== null) {
200
+ clearTimeout(pendingThinkTimer);
201
+ pendingThinkTimer = null;
202
+ }
203
+ }
204
+
205
+ function clearToastTimer() {
206
+ if (toastTimer !== null) {
207
+ clearTimeout(toastTimer);
208
+ toastTimer = null;
209
+ }
210
+ }
211
+
212
+ function clearCopyFeedbackTimer() {
213
+ if (copyFeedbackTimer !== null) {
214
+ clearTimeout(copyFeedbackTimer);
215
+ copyFeedbackTimer = null;
216
+ }
217
+ }
218
+
219
+ function showDockToast(message, opts = {}) {
220
+ clearToastTimer();
221
+ const msg = String(message || '').trim();
222
+ if (!toastEl) return;
223
+ if (!msg) {
224
+ toastEl.textContent = '';
225
+ toastEl.hidden = true;
226
+ toastEl.setAttribute?.('hidden', 'true');
227
+ toastEl.removeAttribute?.('data-tone');
228
+ return;
229
+ }
230
+ toastEl.textContent = msg;
231
+ toastEl.hidden = false;
232
+ toastEl.removeAttribute?.('hidden');
233
+ if (toastEl.style) toastEl.style.display = '';
234
+ if (opts.tone) toastEl.setAttribute?.('data-tone', opts.tone);
235
+ else toastEl.removeAttribute?.('data-tone');
236
+ if (!opts.persistent) {
237
+ toastTimer = setTimeout(() => {
238
+ toastTimer = null;
239
+ showDockToast('');
240
+ }, Number(opts.durationMs) > 0 ? Number(opts.durationMs) : 2600);
241
+ }
242
+ }
243
+
244
+ async function copyTextToClipboard(text) {
245
+ const str = String(text ?? '');
246
+ if (!str) return false;
247
+ if (typeof options.copyText === 'function') {
248
+ const res = await options.copyText(str);
249
+ return res !== false;
250
+ }
251
+ const nav = win?.navigator || doc?.defaultView?.navigator || globalThis.navigator;
252
+ if (typeof nav?.clipboard?.writeText === 'function') {
253
+ try {
254
+ await nav.clipboard.writeText(str);
255
+ return true;
256
+ } catch {}
257
+ }
258
+ if (typeof doc?.createElement === 'function' && typeof doc?.execCommand === 'function' && doc?.body) {
259
+ try {
260
+ const ta = doc.createElement('textarea');
261
+ ta.value = str;
262
+ if (ta.style) {
263
+ ta.style.position = 'fixed';
264
+ ta.style.opacity = '0';
265
+ ta.style.pointerEvents = 'none';
266
+ }
267
+ doc.body.appendChild(ta);
268
+ ta.focus?.();
269
+ ta.select?.();
270
+ const ok = Boolean(doc.execCommand('copy'));
271
+ ta.remove?.();
272
+ if (ok) return true;
273
+ } catch {}
274
+ }
275
+ return false;
276
+ }
277
+
278
+ function collectDomMessages() {
279
+ const scope = ctx.anchors.query('chat.scrollViewport') || doc;
280
+ if (typeof scope?.querySelectorAll !== 'function') return [];
281
+ const nodes = Array.from(scope.querySelectorAll('[data-testid="user-message"], [data-testid="agent-response"]') || []);
282
+ const out = [];
283
+ for (const node of nodes) {
284
+ const text = String(node?.innerText || node?.textContent || '').trim();
285
+ if (!text) continue;
286
+ const tid = node.getAttribute?.('data-testid');
287
+ out.push({
288
+ role: tid === 'user-message' ? 'user' : 'assistant',
289
+ text
290
+ });
291
+ }
292
+ return out;
293
+ }
294
+
295
+ async function resolveSessionId() {
296
+ const fromOpt = typeof options.getSessionId === 'function' ? String(options.getSessionId() || '').trim() : '';
297
+ if (fromOpt) return fromOpt;
298
+ const fromHostDom = String(ctx.hostDom?.getSessionId?.() || '').trim();
299
+ if (fromHostDom) return fromHostDom;
300
+ if (latestContextCascadeId) return String(latestContextCascadeId).trim();
301
+ if (typeof ctx.bridge?.post === 'function') {
302
+ try {
303
+ const res = await ctx.bridge.post('/session-id', {});
304
+ if (res?.ok && res.cascadeId) return String(res.cascadeId).trim();
305
+ } catch {}
306
+ }
307
+ return '';
308
+ }
309
+
310
+ async function copyConversationId() {
311
+ const cascadeId = await resolveSessionId();
312
+ if (!cascadeId) {
313
+ showDockToast('未检测到当前会话 ID', { tone: 'error', durationMs: 2800 });
314
+ return { ok: false, error: 'NO_SESSION_ID' };
315
+ }
316
+ const copied = await copyTextToClipboard(cascadeId);
317
+ if (copyIdBtn) {
318
+ clearCopyFeedbackTimer();
319
+ copyIdBtn.setAttribute?.('data-active', 'true');
320
+ copyFeedbackTimer = setTimeout(() => {
321
+ copyFeedbackTimer = null;
322
+ copyIdBtn?.setAttribute?.('data-active', 'false');
323
+ }, 1500);
324
+ }
325
+ const shortId = cascadeId.length > 12 ? `${cascadeId.slice(0, 8)}…` : cascadeId;
326
+ showDockToast(copied ? `已复制会话 ID: ${shortId}` : `会话 ID: ${shortId}`);
327
+ ctx.events?.emit?.('chat:session-id-copied@1', { cascadeId, copied });
328
+ return { ok: true, cascadeId, copied };
329
+ }
330
+
331
+ function getConfiguredExportFormats() {
332
+ return normalizeExportFormats(settings.exportFormats);
333
+ }
334
+
335
+ function updateExportButtonMeta() {
336
+ if (!exportBtnEl) return;
337
+ const formats = getConfiguredExportFormats();
338
+ const title = formats.length > 1
339
+ ? `导出对话 (${formats.map((f) => f.toUpperCase()).join(' / ')})`
340
+ : `导出当前对话为 ${EXPORT_FORMAT_META[formats[0]]?.label || formats[0].toUpperCase()}`;
341
+ exportBtnEl.setAttribute?.('title', title);
342
+ exportBtnEl.setAttribute?.('aria-label', title);
343
+ exportBtnEl.setAttribute?.('aria-haspopup', formats.length > 1 ? 'menu' : 'false');
344
+ exportBtnEl.setAttribute?.('aria-expanded', exportMenuOpen ? 'true' : 'false');
345
+ exportBtnEl.setAttribute?.('data-active', exportMenuOpen ? 'true' : 'false');
346
+ }
347
+
348
+ function renderExportFormatMenu() {
349
+ if (!exportMenuEl || !doc?.createElement) return;
350
+ while (exportMenuEl.children?.length > 0) {
351
+ const ch = exportMenuEl.children[exportMenuEl.children.length - 1];
352
+ if (ch?.remove) ch.remove();
353
+ else break;
354
+ }
355
+ if (Array.isArray(exportMenuEl.children)) exportMenuEl.children.length = 0;
356
+
357
+ const head = doc.createElement('div');
358
+ head.className = 'agy-export-format-title';
359
+ head.textContent = '选择导出格式';
360
+ exportMenuEl.appendChild(head);
361
+
362
+ const formats = getConfiguredExportFormats();
363
+ for (const fmt of formats) {
364
+ const meta = EXPORT_FORMAT_META[fmt] || { id: fmt, label: fmt.toUpperCase(), ext: `.${fmt}` };
365
+ const itemBtn = doc.createElement('button');
366
+ itemBtn.type = 'button';
367
+ itemBtn.id = `agy-export-fmt-${fmt}`;
368
+ itemBtn.setAttribute?.('data-export-format', fmt);
369
+ itemBtn.setAttribute?.('role', 'menuitem');
370
+
371
+ const lblSpan = doc.createElement('span');
372
+ lblSpan.textContent = meta.label;
373
+ const extSpan = doc.createElement('span');
374
+ extSpan.className = 'agy-export-format-ext';
375
+ extSpan.textContent = meta.ext;
376
+ itemBtn.appendChild(lblSpan);
377
+ itemBtn.appendChild(extSpan);
378
+
379
+ itemBtn.addEventListener('click', (e) => {
380
+ e?.stopPropagation?.();
381
+ setExportMenuOpen(false);
382
+ void exportConversation({ format: fmt });
383
+ });
384
+ exportMenuEl.appendChild(itemBtn);
385
+ }
386
+
387
+ if (formats.length > 1) {
388
+ const divider = doc.createElement('div');
389
+ divider.className = 'agy-export-format-divider';
390
+ divider.setAttribute?.('aria-hidden', 'true');
391
+ exportMenuEl.appendChild(divider);
392
+
393
+ const allBtn = doc.createElement('button');
394
+ allBtn.type = 'button';
395
+ allBtn.id = 'agy-export-fmt-all';
396
+ allBtn.className = 'agy-export-format-all';
397
+ allBtn.setAttribute?.('data-export-format', 'all');
398
+ allBtn.setAttribute?.('role', 'menuitem');
399
+
400
+ const allLbl = doc.createElement('span');
401
+ allLbl.textContent = '全部保存';
402
+ const allCount = doc.createElement('span');
403
+ allCount.className = 'agy-export-format-ext';
404
+ allCount.textContent = `${formats.length} 种格式`;
405
+ allBtn.appendChild(allLbl);
406
+ allBtn.appendChild(allCount);
407
+
408
+ allBtn.addEventListener('click', (e) => {
409
+ e?.stopPropagation?.();
410
+ setExportMenuOpen(false);
411
+ void exportAllConversations();
412
+ });
413
+ exportMenuEl.appendChild(allBtn);
414
+ }
415
+ }
416
+
417
+ function setExportMenuOpen(open) {
418
+ const formats = getConfiguredExportFormats();
419
+ const nextOpen = Boolean(open) && formats.length > 1;
420
+ exportMenuOpen = nextOpen;
421
+ if (nextOpen) {
422
+ if (searchOpen) setSearchOpen(false, { silent: true, reason: 'export-menu' });
423
+ renderExportFormatMenu();
424
+ }
425
+ if (exportMenuEl) {
426
+ exportMenuEl.hidden = !nextOpen;
427
+ if (nextOpen) exportMenuEl.removeAttribute?.('hidden');
428
+ else exportMenuEl.setAttribute?.('hidden', 'true');
429
+ }
430
+ updateExportButtonMeta();
431
+ return exportMenuOpen;
432
+ }
433
+
434
+ function handleExportButtonClick(e) {
435
+ e?.stopPropagation?.();
436
+ if (exportLoading) return;
437
+ const formats = getConfiguredExportFormats();
438
+ if (formats.length > 1) {
439
+ setExportMenuOpen(!exportMenuOpen);
440
+ return;
441
+ }
442
+ setExportMenuOpen(false);
443
+ void exportConversation({ format: formats[0] });
444
+ }
445
+
446
+ function setExportButtonLoading(loading) {
447
+ exportLoading = Boolean(loading);
448
+ if (!exportBtnEl) return;
449
+ exportBtnEl.disabled = exportLoading;
450
+ if (exportLoading) {
451
+ exportBtnEl.setAttribute?.('data-loading', 'true');
452
+ } else {
453
+ exportBtnEl.removeAttribute?.('data-loading');
454
+ }
455
+ }
456
+
457
+ async function collectExportRequestMeta(exportOpts = {}) {
458
+ const saveBehavior = (exportOpts.saveBehavior === 'dialog' || exportOpts.saveBehavior === 'direct' || exportOpts.saveBehavior === 'none')
459
+ ? exportOpts.saveBehavior
460
+ : (settings.exportSaveBehavior === 'direct' ? 'direct' : 'dialog');
461
+ const cascadeId = (typeof exportOpts.cascadeId === 'string' && exportOpts.cascadeId.trim())
462
+ ? exportOpts.cascadeId.trim()
463
+ : await resolveSessionId();
464
+ const domMessages = Array.isArray(exportOpts.domMessages) ? exportOpts.domMessages : collectDomMessages();
465
+ const title = typeof exportOpts.title === 'string' && exportOpts.title.trim()
466
+ ? exportOpts.title.trim()
467
+ : String(doc?.title || '').trim();
468
+ const outputDir = exportOpts.outputDir || options.exportDir || settings.exportSaveDir || undefined;
469
+ return { saveBehavior, cascadeId, domMessages, title, outputDir };
470
+ }
471
+
472
+ async function exportConversation(exportOpts = {}) {
473
+ if (exportLoading) return { ok: false, error: 'EXPORT_IN_PROGRESS' };
474
+ setExportMenuOpen(false);
475
+ const formats = getConfiguredExportFormats();
476
+ const format = String(exportOpts.format || formats[0] || 'md').trim().toLowerCase();
477
+ const saveBehaviorHint = (exportOpts.saveBehavior === 'dialog' || exportOpts.saveBehavior === 'direct' || exportOpts.saveBehavior === 'none')
478
+ ? exportOpts.saveBehavior
479
+ : (settings.exportSaveBehavior === 'direct' ? 'direct' : 'dialog');
480
+
481
+ setExportButtonLoading(true);
482
+ showDockToast(saveBehaviorHint === 'dialog' ? '正在打开保存对话框…' : '正在导出对话…', { persistent: true });
483
+ try {
484
+ const { saveBehavior, cascadeId, domMessages, title, outputDir } = await collectExportRequestMeta(exportOpts);
485
+
486
+ if (typeof ctx.bridge?.post !== 'function') {
487
+ showDockToast('导出服务不可用', { tone: 'error', durationMs: 3200 });
488
+ return { ok: false, error: 'NO_BRIDGE' };
489
+ }
490
+ const res = await ctx.bridge.post('/export-md', {
491
+ format,
492
+ saveBehavior,
493
+ cascadeId: cascadeId || undefined,
494
+ title: title || undefined,
495
+ domMessages,
496
+ outputDir
497
+ });
498
+ if (res?.cancelled) {
499
+ showDockToast('已取消导出', { durationMs: 2000 });
500
+ return { ok: true, cancelled: true, format };
501
+ }
502
+ if (!res?.ok) {
503
+ const errMsg = String(res?.error || res?.saveError || '导出对话失败');
504
+ showDockToast(errMsg, { tone: 'error', durationMs: 3200 });
505
+ return { ok: false, error: errMsg };
506
+ }
507
+
508
+ const copied = format === 'md' && res.markdown ? await copyTextToClipboard(res.markdown) : false;
509
+ const fileName = res.filePath ? String(res.filePath).split(/[\\/]/).pop() : '';
510
+ let toastMsg = '';
511
+ if (res.saveError) {
512
+ toastMsg = copied ? `已复制 Markdown,写盘失败:${res.saveError}` : `保存失败:${res.saveError}`;
513
+ showDockToast(toastMsg, { tone: 'error', durationMs: 3600 });
514
+ } else {
515
+ if (fileName && copied) toastMsg = `已保存并复制:${fileName}`;
516
+ else if (fileName) toastMsg = `已保存:${fileName}`;
517
+ else if (copied) toastMsg = '已复制 Markdown 到剪贴板';
518
+ else toastMsg = `已导出 ${format.toUpperCase()}`;
519
+ showDockToast(toastMsg, { durationMs: 3000 });
520
+ }
521
+
522
+ ctx.events?.emit?.('chat:conversation-exported@1', {
523
+ format,
524
+ saveBehavior,
525
+ cascadeId: res.cascadeId || cascadeId || null,
526
+ filePath: res.filePath || null,
527
+ copied
528
+ });
529
+ return { ...res, copied };
530
+ } catch (err) {
531
+ const errMsg = String(err?.message || '导出对话失败');
532
+ showDockToast(errMsg, { tone: 'error', durationMs: 3200 });
533
+ return { ok: false, error: errMsg };
534
+ } finally {
535
+ setExportButtonLoading(false);
536
+ }
537
+ }
538
+
539
+ async function exportAllConversations(exportOpts = {}) {
540
+ if (exportLoading) return { ok: false, error: 'EXPORT_IN_PROGRESS' };
541
+ setExportMenuOpen(false);
542
+ const formats = Array.isArray(exportOpts.formats) && exportOpts.formats.length > 0
543
+ ? normalizeExportFormats(exportOpts.formats)
544
+ : getConfiguredExportFormats();
545
+ const saveBehaviorHint = (exportOpts.saveBehavior === 'dialog' || exportOpts.saveBehavior === 'direct' || exportOpts.saveBehavior === 'none')
546
+ ? exportOpts.saveBehavior
547
+ : (settings.exportSaveBehavior === 'direct' ? 'direct' : 'dialog');
548
+
549
+ setExportButtonLoading(true);
550
+ showDockToast(saveBehaviorHint === 'dialog' ? '正在选择保存文件夹…' : '正在批量导出对话…', { persistent: true });
551
+ try {
552
+ const { saveBehavior, cascadeId, domMessages, title, outputDir } = await collectExportRequestMeta(exportOpts);
553
+
554
+ if (typeof ctx.bridge?.post !== 'function') {
555
+ showDockToast('导出服务不可用', { tone: 'error', durationMs: 3200 });
556
+ return { ok: false, error: 'NO_BRIDGE' };
557
+ }
558
+ const res = await ctx.bridge.post('/export-all', {
559
+ formats,
560
+ saveBehavior,
561
+ cascadeId: cascadeId || undefined,
562
+ title: title || undefined,
563
+ domMessages,
564
+ outputDir
565
+ });
566
+ if (res?.cancelled) {
567
+ showDockToast('已取消导出', { durationMs: 2000 });
568
+ return { ok: true, cancelled: true, formats };
569
+ }
570
+ if (!res?.ok) {
571
+ const errMsg = String(res?.error || '批量导出失败');
572
+ showDockToast(`批量导出失败:${errMsg}`, { tone: 'error', durationMs: 3600 });
573
+ return { ...res, ok: false, error: errMsg };
574
+ }
575
+
576
+ const copied = formats.includes('md') && res.markdown ? await copyTextToClipboard(res.markdown) : false;
577
+ const succeeded = Array.isArray(res.succeeded) ? res.succeeded : [];
578
+ const failed = Array.isArray(res.failed) ? res.failed : [];
579
+ if (res.partial && failed.length > 0) {
580
+ const failedNames = failed.map((f) => String(f.format || '').toUpperCase()).join(' / ');
581
+ showDockToast(`部分保存成功 (${succeeded.length}/${formats.length}),失败:${failedNames}`, { tone: 'error', durationMs: 4200 });
582
+ } else {
583
+ const fmtText = formats.map((f) => f.toUpperCase()).join(' / ');
584
+ showDockToast(`已全部保存 ${succeeded.length || formats.length} 个文件(${fmtText})`, { durationMs: 3200 });
585
+ }
586
+
587
+ ctx.events?.emit?.('chat:conversation-exported@1', {
588
+ batch: true,
589
+ formats,
590
+ saveBehavior,
591
+ cascadeId: res.cascadeId || cascadeId || null,
592
+ targetDir: res.targetDir || null,
593
+ results: res.results || [],
594
+ copied
595
+ });
596
+ return { ...res, copied };
597
+ } catch (err) {
598
+ const errMsg = String(err?.message || '批量导出失败');
599
+ showDockToast(`批量导出失败:${errMsg}`, { tone: 'error', durationMs: 3600 });
600
+ return { ok: false, error: errMsg };
601
+ } finally {
602
+ setExportButtonLoading(false);
603
+ }
604
+ }
605
+
606
+ function getRect(el) {
607
+ if (!el || typeof el.getBoundingClientRect !== 'function') return null;
608
+ try {
609
+ const r = el.getBoundingClientRect();
610
+ return r || null;
611
+ } catch {
612
+ return null;
613
+ }
614
+ }
615
+
616
+ function findChatAreaElement() {
617
+ const vp = ctx.anchors.query('chat.scrollViewport');
618
+ const vpRect = getRect(vp);
619
+ if (vp && vpRect && vpRect.width > 40 && vpRect.height > 40) {
620
+ return vp;
621
+ }
622
+ const conv = doc?.querySelector?.('[data-testid="conversation-view"], .agy-home');
623
+ const convRect = getRect(conv);
624
+ if (conv && convRect && convRect.width > 40 && convRect.height > 40) {
625
+ return conv;
626
+ }
627
+ const comp = ctx.anchors.query('composer.root');
628
+ if (!comp) return null;
629
+ let cur = comp;
630
+ let best = null;
631
+ for (let i = 0; i < 12 && cur && cur !== doc?.body && cur !== doc?.documentElement; i++) {
632
+ const curRect = getRect(cur);
633
+ if (curRect && curRect.width > 40 && curRect.height > 40) {
634
+ best = cur;
635
+ }
636
+ const parent = cur.parentElement;
637
+ if (!parent || parent === doc?.body || parent === doc?.documentElement) break;
638
+ const parentRect = getRect(parent);
639
+ const baseRect = (curRect && curRect.width > 40) ? curRect : getRect(best);
640
+ if (baseRect && parentRect && parentRect.width > 40) {
641
+ const siblings = Array.from(parent.children || []).filter((c) => c && c !== cur);
642
+ const hasRightPaneSibling = siblings.some((sib) => {
643
+ const sr = getRect(sib);
644
+ return sr && sr.width >= 80 && sr.height > 40 && sr.left >= baseRect.right - 8;
645
+ });
646
+ let parentIsRow = false;
647
+ if (typeof win?.getComputedStyle === 'function') {
648
+ try {
649
+ const cs = win.getComputedStyle(parent);
650
+ parentIsRow = String(cs?.display || '').includes('flex') && cs?.flexDirection !== 'column';
651
+ } catch {}
652
+ }
653
+ if (hasRightPaneSibling || (parentRect.right - baseRect.right > 24 && (parentIsRow || siblings.length > 0))) {
654
+ break;
655
+ }
656
+ }
657
+ cur = parent;
658
+ }
659
+ return best;
660
+ }
661
+
662
+ function hasOpenDialog() {
663
+ if (!doc?.querySelectorAll) return false;
664
+ let dialogs = [];
665
+ try {
666
+ dialogs = Array.from(doc.querySelectorAll('[role="dialog"], [role="alertdialog"], dialog[open]') || []);
667
+ } catch {
668
+ return false;
669
+ }
670
+ for (const d of dialogs) {
671
+ if (!d) continue;
672
+ if (dockEl && (d === dockEl || dockEl.contains?.(d))) continue;
673
+ if (d.hidden || d.getAttribute?.('aria-hidden') === 'true') continue;
674
+ if (d.closest?.('[hidden], [aria-hidden="true"]')) continue;
675
+ if (typeof win?.getComputedStyle === 'function') {
676
+ try {
677
+ const cs = win.getComputedStyle(d);
678
+ if (cs?.display === 'none' || cs?.visibility === 'hidden' || cs?.opacity === '0') continue;
679
+ } catch {}
680
+ }
681
+ return true;
682
+ }
683
+ return false;
684
+ }
685
+
686
+ function syncDockDialogLayering() {
687
+ if (!dockEl) return false;
688
+ const open = hasOpenDialog();
689
+ dockEl.setAttribute?.('data-under-dialog', open ? 'true' : 'false');
690
+ if (open && exportMenuOpen) {
691
+ setExportMenuOpen(false);
692
+ }
693
+ return open;
694
+ }
695
+
696
+ function syncDockPosition() {
697
+ if (!dockEl) return false;
698
+ syncDockDialogLayering();
699
+ const areaEl = findChatAreaElement();
700
+ if (dockResizeObserver && areaEl && observedAreaEl !== areaEl) {
701
+ if (observedAreaEl) {
702
+ try { dockResizeObserver.unobserve(observedAreaEl); } catch {}
703
+ }
704
+ try {
705
+ dockResizeObserver.observe(areaEl);
706
+ observedAreaEl = areaEl;
707
+ } catch {}
708
+ }
709
+ const rect = getRect(areaEl);
710
+ const winW = Number(win?.innerWidth || doc?.documentElement?.clientWidth || 0);
711
+ const winH = Number(win?.innerHeight || doc?.documentElement?.clientHeight || 0);
712
+ if (!rect || rect.width <= 40 || rect.height <= 40 || !winW || !winH) {
713
+ return false;
714
+ }
715
+ const rightPx = Math.max(6, Math.round(winW - rect.right) + 6);
716
+ const topPx = Math.max(120, Math.min(Math.max(120, winH - 120), Math.round(rect.top + rect.height / 2)));
717
+ if (dockEl.style) {
718
+ dockEl.style.right = `${rightPx}px`;
719
+ dockEl.style.top = `${topPx}px`;
720
+ dockEl.style.setProperty?.('--agy-chat-area-width', `${Math.round(rect.width)}px`);
721
+ }
722
+ return true;
723
+ }
724
+
725
+ function scheduleSyncDockPosition() {
726
+ if (!dockEl || dockRafId !== null) return;
727
+ const raf = (win && typeof win.requestAnimationFrame === 'function')
728
+ ? win.requestAnimationFrame.bind(win)
729
+ : (typeof globalThis.requestAnimationFrame === 'function' ? globalThis.requestAnimationFrame : null);
730
+ if (raf) {
731
+ dockRafUsingTimeout = false;
732
+ dockRafId = raf(() => {
733
+ dockRafId = null;
734
+ dockRafUsingTimeout = false;
735
+ syncDockPosition();
736
+ });
737
+ } else {
738
+ dockRafUsingTimeout = true;
739
+ dockRafId = setTimeout(() => {
740
+ dockRafId = null;
741
+ dockRafUsingTimeout = false;
742
+ syncDockPosition();
743
+ }, 16);
744
+ }
745
+ }
746
+
747
+ function getHighlightsApi() {
748
+ const view = doc?.defaultView || win || globalThis;
749
+ const HighlightCtor = view?.Highlight || globalThis.Highlight;
750
+ const cssHighlights = view?.CSS?.highlights || globalThis.CSS?.highlights;
751
+ if (typeof HighlightCtor === 'function' && cssHighlights) {
752
+ return { HighlightCtor, cssHighlights };
753
+ }
754
+ return null;
755
+ }
756
+
757
+ function updateSearchNavButtonsState() {
758
+ const disabled = searchMatches.length === 0;
759
+ if (searchPrevBtn) searchPrevBtn.disabled = disabled;
760
+ if (searchNextBtn) searchNextBtn.disabled = disabled;
761
+ }
762
+
763
+ function clearHighlights() {
764
+ for (const m of searchMatches) {
765
+ const el = m?.blockEl || m?.el || m;
766
+ if (el?.removeAttribute) el.removeAttribute('data-agy-search-hit');
767
+ else el?.setAttribute?.('data-agy-search-hit', '');
768
+ }
769
+ const hl = getHighlightsApi();
770
+ if (hl) {
771
+ try { hl.cssHighlights.delete('agy-search-hit'); } catch {}
772
+ try { hl.cssHighlights.delete('agy-search-active'); } catch {}
773
+ }
774
+ searchMatches = [];
775
+ searchMode = 'block';
776
+ searchActiveIdx = -1;
777
+ if (searchCountEl) {
778
+ searchCountEl.textContent = '0/0';
779
+ searchCountEl.removeAttribute?.('data-empty');
780
+ }
781
+ updateSearchNavButtonsState();
782
+ }
783
+
784
+ function focusMatch(idx) {
785
+ if (!searchMatches.length) return -1;
786
+ searchActiveIdx = (idx + searchMatches.length) % searchMatches.length;
787
+ if (searchMode === 'range') {
788
+ for (const m of searchMatches) {
789
+ m.blockEl?.removeAttribute?.('data-agy-search-hit');
790
+ }
791
+ searchMatches[searchActiveIdx].blockEl?.setAttribute?.('data-agy-search-hit', 'active');
792
+ const hl = getHighlightsApi();
793
+ if (hl && searchMatches[searchActiveIdx].range) {
794
+ try {
795
+ hl.cssHighlights.set('agy-search-active', new hl.HighlightCtor(searchMatches[searchActiveIdx].range));
796
+ } catch {}
797
+ }
798
+ } else {
799
+ for (let i = 0; i < searchMatches.length; i++) {
800
+ const el = searchMatches[i].el || searchMatches[i];
801
+ el?.setAttribute?.('data-agy-search-hit', i === searchActiveIdx ? 'active' : 'hit');
802
+ }
803
+ }
804
+
805
+ const cur = searchMatches[searchActiveIdx];
806
+ const targetEl = cur.blockEl || cur.el || cur;
807
+ const vp = ctx.anchors.query('chat.scrollViewport');
808
+ const vpRect = getRect(vp);
809
+ if (vp && vpRect && vpRect.height > 0) {
810
+ const rangeRect = typeof cur.range?.getBoundingClientRect === 'function' ? cur.range.getBoundingClientRect() : null;
811
+ const elRect = getRect(targetEl);
812
+ const targetRect = (rangeRect && (rangeRect.height > 0 || rangeRect.width > 0)) ? rangeRect : elRect;
813
+ if (targetRect && (targetRect.height > 0 || targetRect.width > 0)) {
814
+ const targetTop = Math.max(
815
+ 0,
816
+ Number(vp.scrollTop || 0) + (targetRect.top - vpRect.top) - vpRect.height / 2 + targetRect.height / 2
817
+ );
818
+ scrollViewportTo(vp, targetTop);
819
+ } else if (typeof targetEl?.scrollIntoView === 'function') {
820
+ try { targetEl.scrollIntoView({ block: 'center', behavior: 'smooth' }); } catch {}
821
+ }
822
+ } else if (typeof targetEl?.scrollIntoView === 'function') {
823
+ try { targetEl.scrollIntoView({ block: 'center', behavior: 'smooth' }); } catch {}
824
+ } else if (vp) {
825
+ vp.scrollTop = searchActiveIdx * 180;
826
+ }
827
+
828
+ if (searchCountEl) {
829
+ searchCountEl.textContent = `${searchActiveIdx + 1}/${searchMatches.length}`;
830
+ searchCountEl.removeAttribute?.('data-empty');
831
+ }
832
+ updateSearchNavButtonsState();
833
+ return searchActiveIdx;
834
+ }
835
+
836
+ function runSearch(query) {
837
+ lastSearchQuery = String(query || '');
838
+ clearHighlights();
839
+ const trimmed = lastSearchQuery.trim();
840
+ if (!trimmed) {
841
+ ctx.state?.set?.('state:chat-nav.search@1', { query: '', total: 0 });
842
+ return 0;
843
+ }
844
+
845
+ const vp = ctx.anchors.query('chat.scrollViewport');
846
+ const msgNodes = vp?.querySelectorAll
847
+ ? Array.from(vp.querySelectorAll('[data-testid="user-message"], [data-testid="agent-response"]') || [])
848
+ : [];
849
+ const canWalk = msgNodes.length > 0 && typeof doc?.createTreeWalker === 'function' && typeof doc?.createRange === 'function';
850
+
851
+ if (canWalk) {
852
+ searchMode = 'range';
853
+ const showText = globalThis.NodeFilter?.SHOW_TEXT ?? 4;
854
+ const maxHits = 2000;
855
+ for (const msg of msgNodes) {
856
+ if (searchMatches.length >= maxHits) break;
857
+ const walker = doc.createTreeWalker(msg, showText);
858
+ let textNode;
859
+ while ((textNode = walker.nextNode())) {
860
+ const parentEl = textNode.parentElement;
861
+ if (!parentEl) continue;
862
+ if (parentEl.closest?.('style, script, noscript, [data-find-ignore="true"], .sr-only, [hidden], #agy-chat-search-box, #agy-chat-nav-float')) {
863
+ continue;
864
+ }
865
+ const val = textNode.nodeValue || '';
866
+ const hitRanges = findRangesInText(val, trimmed, settings.searchRegexMode, settings.searchCaseSensitive, maxHits - searchMatches.length);
867
+ for (const hr of hitRanges) {
868
+ const range = doc.createRange();
869
+ range.setStart(textNode, hr.start);
870
+ range.setEnd(textNode, hr.end);
871
+ if (typeof range.getClientRects === 'function' && range.getClientRects().length === 0) {
872
+ continue;
873
+ }
874
+ const blockEl = parentEl.closest?.('[data-testid="user-message-content"], p, li, tr, pre, blockquote, h1, h2, h3, h4, h5, h6') || parentEl;
875
+ searchMatches.push({ range, blockEl });
876
+ if (searchMatches.length >= maxHits) break;
877
+ }
878
+ if (searchMatches.length >= maxHits) break;
879
+ }
880
+ }
881
+ if (searchMatches.length > 0) {
882
+ const hl = getHighlightsApi();
883
+ if (hl) {
884
+ try {
885
+ hl.cssHighlights.set('agy-search-hit', new hl.HighlightCtor(...searchMatches.map((m) => m.range)));
886
+ } catch {}
887
+ }
888
+ }
889
+ } else {
890
+ searchMode = 'block';
891
+ const fn = createSearchMatcher(trimmed, settings.searchRegexMode, settings.searchCaseSensitive);
892
+ if (fn) {
893
+ const ml = ctx.anchors.query('chat.messageList');
894
+ const listEl = (ml && ml.children && ml.children.length > 0) ? ml : vp;
895
+ const candidates = msgNodes.length > 0 ? msgNodes : (listEl?.children || []);
896
+ for (const node of candidates) {
897
+ if (!node || node === searchBoxEl || node.id === 'agy-chat-search-box' || node.id === 'agy-chat-nav-float') continue;
898
+ const txt = String(node.textContent || '');
899
+ if (fn(txt)) {
900
+ node.setAttribute?.('data-agy-search-hit', 'hit');
901
+ searchMatches.push({ el: node, blockEl: node });
902
+ }
903
+ }
904
+ }
905
+ }
906
+
907
+ ctx.state?.set?.('state:chat-nav.search@1', { query: lastSearchQuery, total: searchMatches.length });
908
+ if (searchMatches.length > 0) {
909
+ focusMatch(0);
910
+ } else {
911
+ if (searchCountEl) {
912
+ searchCountEl.textContent = '0/0';
913
+ searchCountEl.setAttribute?.('data-empty', 'true');
914
+ }
915
+ updateSearchNavButtonsState();
916
+ }
917
+ return searchMatches.length;
918
+ }
919
+
920
+ function clearAndClose(reason = 'close-button') {
921
+ if (searchInputEl) searchInputEl.value = '';
922
+ lastSearchQuery = '';
923
+ clearHighlights();
924
+ ctx.state?.set?.('state:chat-nav.search@1', { query: '', total: 0 });
925
+ setSearchOpen(false, { reason });
926
+ }
927
+
928
+ function setSearchOpen(open, opts = {}) {
929
+ const nextOpen = Boolean(open);
930
+ const silent = Boolean(opts.silent);
931
+ const reason = opts.reason || 'toggle';
932
+ searchOpen = nextOpen;
933
+ if (searchSlot) {
934
+ searchSlot.className = nextOpen ? 'agy-search-open' : 'agy-search-collapsed';
935
+ }
936
+ if (searchToggleBtn) {
937
+ searchToggleBtn.setAttribute?.('data-active', nextOpen ? 'true' : 'false');
938
+ searchToggleBtn.setAttribute?.('aria-expanded', nextOpen ? 'true' : 'false');
939
+ }
940
+ if (nextOpen) {
941
+ searchInputEl?.focus?.();
942
+ searchInputEl?.select?.();
943
+ if (searchInputEl?.value) {
944
+ runSearch(searchInputEl.value);
945
+ }
946
+ if (!silent) {
947
+ ctx.events?.emit?.('chat:search-opened@1', { reason });
948
+ }
949
+ } else {
950
+ clearHighlights();
951
+ if (!silent) {
952
+ ctx.events?.emit?.('chat:search-closed@1', { reason });
953
+ }
954
+ }
955
+ return searchOpen;
956
+ }
957
+
958
+ function buildBuiltinSearchBox() {
959
+ const box = doc.createElement('div');
960
+ box.id = 'agy-chat-search-box';
961
+
962
+ const inp = doc.createElement('input');
963
+ inp.id = 'agy-chat-search-input';
964
+ inp.type = 'text';
965
+ inp.placeholder = '搜索对话...';
966
+ inp.className = 'settings-input';
967
+ inp.addEventListener('change', () => runSearch(inp.value));
968
+ inp.addEventListener('input', () => runSearch(inp.value));
969
+ inp.addEventListener('keydown', (e) => {
970
+ if (!e) return;
971
+ if (e.key === 'Enter') {
972
+ e.preventDefault?.();
973
+ if (searchMatches.length > 0) {
974
+ focusMatch(e.shiftKey ? searchActiveIdx - 1 : searchActiveIdx + 1);
975
+ } else if (inp.value) {
976
+ runSearch(inp.value);
977
+ }
978
+ return;
979
+ }
980
+ if (e.key === 'Escape') {
981
+ e.preventDefault?.();
982
+ e.stopPropagation?.();
983
+ clearAndClose('escape');
984
+ }
985
+ });
986
+ box.appendChild(inp);
987
+
988
+ const prevBtn = doc.createElement('button');
989
+ prevBtn.type = 'button';
990
+ prevBtn.id = 'agy-chat-search-prev';
991
+ prevBtn.disabled = true;
992
+ prevBtn.setAttribute('aria-label', '上一条匹配');
993
+ prevBtn.setAttribute('title', '上一条匹配 (Shift+Enter)');
994
+ prevBtn.innerHTML = '<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>';
995
+ prevBtn.addEventListener('click', () => focusMatch(searchActiveIdx - 1));
996
+ box.appendChild(prevBtn);
997
+
998
+ const nextBtn = doc.createElement('button');
999
+ nextBtn.type = 'button';
1000
+ nextBtn.id = 'agy-chat-search-next';
1001
+ nextBtn.disabled = true;
1002
+ nextBtn.setAttribute('aria-label', '下一条匹配');
1003
+ nextBtn.setAttribute('title', '下一条匹配 (Enter)');
1004
+ nextBtn.innerHTML = '<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>';
1005
+ nextBtn.addEventListener('click', () => focusMatch(searchActiveIdx + 1));
1006
+ box.appendChild(nextBtn);
1007
+
1008
+ const countEl = doc.createElement('span');
1009
+ countEl.id = 'agy-chat-search-count';
1010
+ countEl.textContent = '0/0';
1011
+ box.appendChild(countEl);
1012
+
1013
+ const clearBtn = doc.createElement('button');
1014
+ clearBtn.type = 'button';
1015
+ clearBtn.id = 'agy-chat-search-clear';
1016
+ clearBtn.setAttribute('aria-label', '关闭搜索');
1017
+ clearBtn.setAttribute('title', '清除并关闭搜索 (Esc)');
1018
+ clearBtn.innerHTML = '<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 6 6 18"/><path d="m6 6 12 12"/></svg>';
1019
+ clearBtn.addEventListener('click', () => {
1020
+ clearAndClose('close-button');
1021
+ });
1022
+ box.appendChild(clearBtn);
1023
+
1024
+ return { box, inp, countEl, prevBtn, nextBtn };
1025
+ }
1026
+
1027
+ function teardownDock() {
1028
+ cancelScheduledSync();
1029
+ clearPendingThinkTimer();
1030
+ clearToastTimer();
1031
+ clearCopyFeedbackTimer();
1032
+ clearHighlights();
1033
+ if (dockResizeObserver) {
1034
+ try { dockResizeObserver.disconnect(); } catch {}
1035
+ dockResizeObserver = null;
1036
+ }
1037
+ observedAreaEl = null;
1038
+ if (searchSlot && onSearchSlotKeyDown) {
1039
+ try { searchSlot.removeEventListener?.('keydown', onSearchSlotKeyDown); } catch {}
1040
+ }
1041
+ onSearchSlotKeyDown = null;
1042
+ clearNodes(customButtonNodes);
1043
+ if (typeof revokeNavButtonsSurface === 'function') {
1044
+ try { revokeNavButtonsSurface(); } catch {}
1045
+ revokeNavButtonsSurface = null;
1046
+ }
1047
+ if (searchBoxEl?.remove) searchBoxEl.remove();
1048
+ if (exportMenuEl?.remove) exportMenuEl.remove();
1049
+ if (toastEl?.remove) toastEl.remove();
1050
+ if (dockEl?.remove) dockEl.remove();
1051
+ dockEl = null;
1052
+ extraButtonsSlot = null;
1053
+ searchSlot = null;
1054
+ searchBoxEl = null;
1055
+ searchInputEl = null;
1056
+ searchCountEl = null;
1057
+ searchPrevBtn = null;
1058
+ searchNextBtn = null;
1059
+ searchToggleBtn = null;
1060
+ thinkBtn = null;
1061
+ copyIdBtn = null;
1062
+ exportBtnEl = null;
1063
+ exportMenuEl = null;
1064
+ exportMenuOpen = false;
1065
+ toastEl = null;
1066
+ exportLoading = false;
1067
+ searchOpen = false;
1068
+ }
1069
+
1070
+ function ensureDock() {
1071
+ if (!doc?.createElement) return null;
1072
+ if (!settings.showFloatDock) {
1073
+ teardownDock();
1074
+ return null;
1075
+ }
1076
+ if (dockEl) return dockEl;
1077
+
1078
+ dockEl = doc.createElement('div');
1079
+ dockEl.id = 'agy-chat-nav-float';
1080
+ dockEl.className = 'agy-chat-nav-float';
1081
+
1082
+ const actions = [
1083
+ { id: 'top', icon: NAV_ICONS.top, title: '滚动到对话顶部', fn: () => scrollTop() },
1084
+ { id: 'prev', icon: NAV_ICONS.prev, title: '上一轮对话', fn: () => stepTurn(-1) },
1085
+ { id: 'next', icon: NAV_ICONS.next, title: '下一轮对话', fn: () => stepTurn(1) },
1086
+ { id: 'bottom', icon: NAV_ICONS.bottom, title: '滚动到对话底部', fn: () => scrollBottom() },
1087
+ { id: 'think', icon: NAV_ICONS.think, title: '展开/收起思考过程', fn: () => toggleThinking() },
1088
+ { id: 'copy-id', icon: NAV_ICONS.copyId, title: '复制当前会话 ID', fn: () => { void copyConversationId(); } },
1089
+ { id: 'export-md', icon: NAV_ICONS.exportMd, title: '导出对话', fn: handleExportButtonClick }
1090
+ ];
1091
+ for (const act of actions) {
1092
+ const btn = doc.createElement('button');
1093
+ btn.type = 'button';
1094
+ btn.id = `agy-nav-${act.id}`;
1095
+ btn.innerHTML = act.icon;
1096
+ btn.setAttribute?.('title', act.title);
1097
+ btn.setAttribute?.('aria-label', act.title);
1098
+ if (act.id === 'think') {
1099
+ btn.setAttribute?.('data-active', 'false');
1100
+ thinkBtn = btn;
1101
+ } else if (act.id === 'copy-id') {
1102
+ btn.setAttribute?.('data-active', 'false');
1103
+ copyIdBtn = btn;
1104
+ } else if (act.id === 'export-md') {
1105
+ exportBtnEl = btn;
1106
+ updateExportButtonMeta();
1107
+ }
1108
+ btn.addEventListener('click', act.fn);
1109
+ dockEl.appendChild(btn);
1110
+ }
1111
+
1112
+ extraButtonsSlot = doc.createElement('div');
1113
+ extraButtonsSlot.id = 'agy-chat-nav-extra';
1114
+ dockEl.appendChild(extraButtonsSlot);
1115
+
1116
+ searchOpen = false;
1117
+ searchToggleBtn = doc.createElement('button');
1118
+ searchToggleBtn.type = 'button';
1119
+ searchToggleBtn.id = 'agy-nav-search-toggle';
1120
+ searchToggleBtn.innerHTML = NAV_ICONS.search;
1121
+ searchToggleBtn.setAttribute?.('title', '搜索对话记录');
1122
+ searchToggleBtn.setAttribute?.('aria-label', '搜索对话记录');
1123
+ searchToggleBtn.setAttribute?.('aria-expanded', 'false');
1124
+ searchToggleBtn.setAttribute?.('data-active', 'false');
1125
+
1126
+ searchSlot = doc.createElement('div');
1127
+ searchSlot.id = 'agy-chat-search-slot';
1128
+ searchSlot.className = 'agy-search-collapsed';
1129
+
1130
+ onSearchSlotKeyDown = (e) => {
1131
+ if (e?.key === 'Escape') {
1132
+ e.preventDefault?.();
1133
+ e.stopPropagation?.();
1134
+ clearAndClose('escape');
1135
+ }
1136
+ };
1137
+ searchSlot.addEventListener('keydown', onSearchSlotKeyDown);
1138
+
1139
+ const builtinSearch = buildBuiltinSearchBox();
1140
+ searchBoxEl = builtinSearch.box;
1141
+ searchInputEl = builtinSearch.inp;
1142
+ searchCountEl = builtinSearch.countEl;
1143
+ searchPrevBtn = builtinSearch.prevBtn;
1144
+ searchNextBtn = builtinSearch.nextBtn;
1145
+ searchSlot.appendChild(searchBoxEl);
1146
+ if (lastSearchQuery) {
1147
+ searchInputEl.value = lastSearchQuery;
1148
+ }
1149
+
1150
+ searchToggleBtn.addEventListener('click', () => {
1151
+ setSearchOpen(!searchOpen, { reason: 'toggle' });
1152
+ });
1153
+ dockEl.appendChild(searchToggleBtn);
1154
+ dockEl.appendChild(searchSlot);
1155
+
1156
+ exportMenuEl = doc.createElement('div');
1157
+ exportMenuEl.id = 'agy-export-format-menu';
1158
+ exportMenuEl.setAttribute?.('role', 'menu');
1159
+ exportMenuEl.hidden = true;
1160
+ exportMenuEl.setAttribute?.('hidden', 'true');
1161
+ renderExportFormatMenu();
1162
+ dockEl.appendChild(exportMenuEl);
1163
+
1164
+ toastEl = doc.createElement('div');
1165
+ toastEl.id = 'agy-chat-nav-toast';
1166
+ toastEl.hidden = true;
1167
+ toastEl.setAttribute?.('hidden', 'true');
1168
+ dockEl.appendChild(toastEl);
1169
+
1170
+ const mountRoot = doc.body || doc.documentElement;
1171
+ mountRoot?.appendChild?.(dockEl);
1172
+
1173
+ // 必须先将宿主插槽挂载入文档树,再向底座注册 ctx.surfaces(供跨世界查询与订阅)
1174
+ if (ctx.surfaces && typeof ctx.surfaces.provide === 'function') {
1175
+ revokeNavButtonsSurface = ctx.surfaces.provide('chat.navButtons', extraButtonsSlot);
1176
+ }
1177
+
1178
+ renderCustomButtons();
1179
+
1180
+ const RO = win?.ResizeObserver || globalThis.ResizeObserver;
1181
+ if (typeof RO === 'function') {
1182
+ try {
1183
+ dockResizeObserver = new RO(() => scheduleSyncDockPosition());
1184
+ if (doc.body) dockResizeObserver.observe(doc.body);
1185
+ } catch {
1186
+ dockResizeObserver = null;
1187
+ }
1188
+ }
1189
+ syncDockPosition();
1190
+ return dockEl;
1191
+ }
1192
+
1193
+ function renderCustomButtons() {
1194
+ if (!extraButtonsSlot || !doc?.createElement) return;
1195
+ clearNodes(customButtonNodes);
1196
+ for (const [id, def] of customButtons.entries()) {
1197
+ const btn = doc.createElement('button');
1198
+ btn.type = 'button';
1199
+ btn.id = `agy-nav-ext-${id}`;
1200
+ btn.textContent = def.label || id;
1201
+ if (typeof def.onClick === 'function') btn.addEventListener('click', def.onClick);
1202
+ extraButtonsSlot.appendChild(btn);
1203
+ customButtonNodes.push(btn);
1204
+ }
1205
+ }
1206
+
1207
+ function scrollViewportTo(vp, top) {
1208
+ if (!vp) return;
1209
+ const target = Math.max(0, Number(top) || 0);
1210
+ if (typeof vp.scrollTo === 'function') {
1211
+ try {
1212
+ vp.scrollTo({ top: target, behavior: 'smooth' });
1213
+ return;
1214
+ } catch {}
1215
+ }
1216
+ vp.scrollTop = target;
1217
+ }
1218
+
1219
+ function scrollTop() {
1220
+ const vp = ctx.anchors.query('chat.scrollViewport');
1221
+ if (vp) {
1222
+ lastTurnNav = null;
1223
+ scrollViewportTo(vp, 0);
1224
+ }
1225
+ return Boolean(vp);
1226
+ }
1227
+
1228
+ function scrollBottom() {
1229
+ const vp = ctx.anchors.query('chat.scrollViewport');
1230
+ if (vp) {
1231
+ lastTurnNav = null;
1232
+ const maxTop = Math.max(0, Number(vp.scrollHeight || 999999) - Number(vp.clientHeight || 0));
1233
+ scrollViewportTo(vp, vp.scrollHeight ? maxTop : 999999);
1234
+ }
1235
+ return Boolean(vp);
1236
+ }
1237
+
1238
+ function getTurnElements(vp) {
1239
+ if (vp && typeof vp.querySelectorAll === 'function') {
1240
+ const userMsgs = Array.from(vp.querySelectorAll('[data-testid="user-message"]') || []);
1241
+ const agentResps = Array.from(vp.querySelectorAll('[data-testid="agent-response"]') || []);
1242
+ if (userMsgs.length > 0) {
1243
+ const firstUser = userMsgs[0];
1244
+ const leadingResps = agentResps.filter((r) => {
1245
+ if (typeof r.compareDocumentPosition === 'function') {
1246
+ return (r.compareDocumentPosition(firstUser) & 4) !== 0;
1247
+ }
1248
+ return false;
1249
+ });
1250
+ const combined = [...leadingResps, ...userMsgs];
1251
+ if (combined.length > 1 && typeof combined[0].compareDocumentPosition === 'function') {
1252
+ combined.sort((a, b) => {
1253
+ if (a === b) return 0;
1254
+ return (a.compareDocumentPosition(b) & 4) !== 0 ? -1 : 1;
1255
+ });
1256
+ }
1257
+ return combined;
1258
+ }
1259
+ if (agentResps.length > 0) return agentResps;
1260
+ }
1261
+ const list = ctx.anchors.query('chat.messageList');
1262
+ const children = Array.from(list?.children || []).filter((c) => {
1263
+ if (!c) return false;
1264
+ return (c.textContent || '').length > 0 || (c.children?.length || 0) > 0;
1265
+ });
1266
+ return children;
1267
+ }
1268
+
1269
+ function stepTurn(delta) {
1270
+ const vp = ctx.anchors.query('chat.scrollViewport') || ctx.anchors.query('chat.messageList');
1271
+ if (!vp) return false;
1272
+ const vpRect = getRect(vp);
1273
+ if (vpRect && vpRect.height > 0) {
1274
+ const turns = getTurnElements(vp);
1275
+ const curScrollTop = Number(vp.scrollTop || 0);
1276
+ const turnsWithTop = [];
1277
+ for (const el of turns) {
1278
+ const r = getRect(el);
1279
+ if (!r) continue;
1280
+ const top = Math.round(r.top - vpRect.top + curScrollTop);
1281
+ turnsWithTop.push({ el, top });
1282
+ }
1283
+ if (turnsWithTop.length > 0) {
1284
+ turnsWithTop.sort((a, b) => a.top - b.top);
1285
+ const now = Date.now();
1286
+ const baseTop = (lastTurnNav && (now - lastTurnNav.ts) < 500) ? lastTurnNav.top : curScrollTop;
1287
+ const maxScroll = Math.max(0, Number(vp.scrollHeight || 0) - Number(vp.clientHeight || vpRect.height || 0));
1288
+ let target = baseTop;
1289
+ if (delta < 0) {
1290
+ let found = null;
1291
+ for (let i = turnsWithTop.length - 1; i >= 0; i--) {
1292
+ if (turnsWithTop[i].top < baseTop - 16) {
1293
+ found = turnsWithTop[i];
1294
+ break;
1295
+ }
1296
+ }
1297
+ target = found ? Math.max(0, found.top - 12) : 0;
1298
+ } else {
1299
+ const found = turnsWithTop.find((t) => t.top > baseTop + 16);
1300
+ target = found ? Math.min(maxScroll, Math.max(0, found.top - 12)) : maxScroll;
1301
+ }
1302
+ lastTurnNav = { top: target, ts: now };
1303
+ scrollViewportTo(vp, target);
1304
+ return true;
1305
+ }
1306
+ }
1307
+ const cur = Number(vp.scrollTop || 0);
1308
+ vp.scrollTop = Math.max(0, cur + delta * 360);
1309
+ return true;
1310
+ }
1311
+
1312
+ function getThinkingTriggers() {
1313
+ const seen = new Set();
1314
+ const out = [];
1315
+ const add = (el) => {
1316
+ if (!el || seen.has(el)) return;
1317
+ seen.add(el);
1318
+ out.push(el);
1319
+ };
1320
+ for (const el of ctx.anchors.queryAll('chat.thinkingTrigger') || []) add(el);
1321
+ const vp = ctx.anchors.query('chat.scrollViewport');
1322
+ const worked = vp?.querySelectorAll?.('[data-testid="worked-for-collapsible"]')
1323
+ || doc?.querySelectorAll?.('[data-testid="worked-for-collapsible"]')
1324
+ || [];
1325
+ for (const el of worked) add(el);
1326
+ if (out.length > 1 && typeof out[0]?.compareDocumentPosition === 'function') {
1327
+ out.sort((a, b) => {
1328
+ if (a === b) return 0;
1329
+ return (a.compareDocumentPosition(b) & 4) !== 0 ? -1 : 1;
1330
+ });
1331
+ }
1332
+ return out;
1333
+ }
1334
+
1335
+ function getTriggerExpandedState(t) {
1336
+ if (!t) return null;
1337
+ const aria = t.getAttribute?.('aria-expanded');
1338
+ if (aria === 'true') return true;
1339
+ if (aria === 'false') return false;
1340
+
1341
+ const ds = t.getAttribute?.('data-state') || t.closest?.('[data-state]')?.getAttribute?.('data-state');
1342
+ if (ds === 'open') return true;
1343
+ if (ds === 'closed') return false;
1344
+
1345
+ const ctrlId = t.getAttribute?.('aria-controls');
1346
+ if (ctrlId && doc?.getElementById) {
1347
+ const ctrlEl = doc.getElementById(ctrlId);
1348
+ if (ctrlEl) {
1349
+ if (ctrlEl.hidden || ctrlEl.getAttribute?.('hidden') !== null) return false;
1350
+ const cr = getRect(ctrlEl);
1351
+ if (cr) return cr.height > 0;
1352
+ }
1353
+ }
1354
+
1355
+ const nextSib = t.nextElementSibling;
1356
+ if (nextSib) {
1357
+ const nr = getRect(nextSib);
1358
+ if (nr && nr.height > 0) return true;
1359
+ }
1360
+ if (t.parentElement?.children?.length === 1 && getRect(t)) {
1361
+ return false;
1362
+ }
1363
+ return null;
1364
+ }
1365
+
1366
+ function updateThinkButtonVisual(active) {
1367
+ if (!thinkBtn) return;
1368
+ thinkBtn.setAttribute?.('data-active', active ? 'true' : 'false');
1369
+ const title = active ? '收起思考过程' : '展开思考过程';
1370
+ thinkBtn.setAttribute?.('title', title);
1371
+ thinkBtn.setAttribute?.('aria-label', title);
1372
+ }
1373
+
1374
+ function expandThinking() {
1375
+ const triggers = getThinkingTriggers();
1376
+ let expandedCount = 0;
1377
+ let clickedWorked = false;
1378
+ for (const t of triggers) {
1379
+ if (getTriggerExpandedState(t) !== true) {
1380
+ t.setAttribute?.('data-agy-keep-expanded', '1');
1381
+ if (t.getAttribute?.('data-testid') === 'worked-for-collapsible') {
1382
+ clickedWorked = true;
1383
+ }
1384
+ if (typeof t.click === 'function') t.click();
1385
+ expandedCount++;
1386
+ }
1387
+ }
1388
+ if (clickedWorked) {
1389
+ clearPendingThinkTimer();
1390
+ pendingThinkTimer = setTimeout(() => {
1391
+ pendingThinkTimer = null;
1392
+ const nested = ctx.anchors.queryAll('chat.thinkingTrigger') || [];
1393
+ for (const nt of nested) {
1394
+ if (getTriggerExpandedState(nt) !== true) {
1395
+ nt.setAttribute?.('data-agy-keep-expanded', '1');
1396
+ if (typeof nt.click === 'function') nt.click();
1397
+ }
1398
+ }
1399
+ }, 120);
1400
+ }
1401
+ updateThinkButtonVisual(true);
1402
+ ctx.events.emit('chat:thinking-expanded@1', { expandedCount, total: triggers.length });
1403
+ return expandedCount;
1404
+ }
1405
+
1406
+ function collapseThinking() {
1407
+ clearPendingThinkTimer();
1408
+ const triggers = getThinkingTriggers();
1409
+ let collapsedCount = 0;
1410
+ for (const t of triggers) {
1411
+ if (getTriggerExpandedState(t) === true) {
1412
+ t.removeAttribute?.('data-agy-keep-expanded');
1413
+ if (typeof t.click === 'function') t.click();
1414
+ collapsedCount++;
1415
+ }
1416
+ }
1417
+ updateThinkButtonVisual(false);
1418
+ ctx.events.emit('chat:thinking-collapsed@1', { collapsedCount, total: triggers.length });
1419
+ return collapsedCount;
1420
+ }
1421
+
1422
+ function toggleThinking() {
1423
+ const triggers = getThinkingTriggers();
1424
+ const states = triggers.map((t) => getTriggerExpandedState(t));
1425
+ if (states.some((s) => s === false)) {
1426
+ return expandThinking();
1427
+ }
1428
+ if (states.some((s) => s === true)) {
1429
+ return collapseThinking();
1430
+ }
1431
+ thinkingToggleFallback = !thinkingToggleFallback;
1432
+ for (const t of triggers) {
1433
+ if (thinkingToggleFallback) t.setAttribute?.('data-agy-keep-expanded', '1');
1434
+ else t.removeAttribute?.('data-agy-keep-expanded');
1435
+ if (typeof t.click === 'function') t.click();
1436
+ }
1437
+ updateThinkButtonVisual(thinkingToggleFallback);
1438
+ ctx.events.emit(
1439
+ thinkingToggleFallback ? 'chat:thinking-expanded@1' : 'chat:thinking-collapsed@1',
1440
+ thinkingToggleFallback
1441
+ ? { expandedCount: triggers.length, total: triggers.length }
1442
+ : { collapsedCount: triggers.length, total: triggers.length }
1443
+ );
1444
+ return triggers.length;
1445
+ }
1446
+
1447
+ function getConversationRows() {
1448
+ return ctx.anchors.queryAll('sidebar.conversationRows') || [];
1449
+ }
1450
+
1451
+ function switchConversation(index) {
1452
+ const rows = getConversationRows();
1453
+ if (!rows.length || index < 0 || index >= rows.length) return false;
1454
+ for (let i = 0; i < rows.length; i++) {
1455
+ rows[i].setAttribute?.('aria-selected', i === index ? 'true' : 'false');
1456
+ }
1457
+ const target = rows[index];
1458
+ activeConvIndex = index;
1459
+ if (typeof target.click === 'function') target.click();
1460
+ if (typeof options.onConversationSwitch === 'function') {
1461
+ options.onConversationSwitch(index, target);
1462
+ }
1463
+ return true;
1464
+ }
1465
+
1466
+ function cycleConversation(delta) {
1467
+ const rows = getConversationRows();
1468
+ if (!rows.length) return false;
1469
+ let cur = rows.findIndex((r) => r.getAttribute?.('aria-selected') === 'true' || r.getAttribute?.('aria-current') === 'true');
1470
+ if (cur < 0) cur = activeConvIndex;
1471
+ const next = (cur + delta + rows.length) % rows.length;
1472
+ return switchConversation(next);
1473
+ }
1474
+
1475
+ function showConvBadges() {
1476
+ hideConvBadges();
1477
+ if (!doc?.createElement) return 0;
1478
+ const rows = getConversationRows();
1479
+ const limit = Math.min(rows.length, 9);
1480
+ for (let i = 0; i < limit; i++) {
1481
+ const badge = doc.createElement('span');
1482
+ badge.className = 'agy-conv-shortcut-badge';
1483
+ badge.setAttribute('data-agy-conv-badge', String(i + 1));
1484
+ badge.textContent = String(i + 1);
1485
+ if (badge.style?.setProperty) {
1486
+ badge.style.setProperty('background', 'var(--ag-bg-control, rgba(113, 113, 122, 0.14))');
1487
+ badge.style.setProperty('color', 'var(--ag-text-primary, currentColor)');
1488
+ badge.style.setProperty('border-color', 'var(--ag-border-card, rgba(113, 113, 122, 0.24))');
1489
+ }
1490
+ rows[i].appendChild?.(badge);
1491
+ mountedBadges.push(badge);
1492
+ }
1493
+ return limit;
1494
+ }
1495
+
1496
+ function hideConvBadges() {
1497
+ while (mountedBadges.length > 0) {
1498
+ const b = mountedBadges.pop();
1499
+ if (b?.remove) b.remove();
1500
+ }
1501
+ }
1502
+
1503
+ function closeInlineEditor(refreshPreview = false) {
1504
+ if (editorPanelEl?.remove) editorPanelEl.remove();
1505
+ editorPanelEl = null;
1506
+ editorTextareaEl = null;
1507
+ if (refreshPreview && typeof options.onEditorExit === 'function') {
1508
+ options.onEditorExit(activeEditorPath);
1509
+ }
1510
+ }
1511
+
1512
+ async function saveInlineFile() {
1513
+ if (!editorTextareaEl || !activeEditorPath) return { ok: false, error: 'NO_ACTIVE_FILE' };
1514
+ const res = await ctx.bridge.post('/file/write', {
1515
+ path: activeEditorPath,
1516
+ content: editorTextareaEl.value || ''
1517
+ });
1518
+ if (res?.ok && typeof options.onFileSaved === 'function') {
1519
+ options.onFileSaved(activeEditorPath, res);
1520
+ }
1521
+ return res;
1522
+ }
1523
+
1524
+ async function openInlineEditor(headerOrPath) {
1525
+ if (!doc?.createElement) return false;
1526
+ const headerEl = (headerOrPath && typeof headerOrPath === 'object')
1527
+ ? headerOrPath
1528
+ : ctx.anchors.query('fileViewer.header');
1529
+ activeEditorPath = (typeof headerOrPath === 'string' && headerOrPath)
1530
+ || headerEl?.getAttribute?.('data-file-path')
1531
+ || headerEl?.getAttribute?.('data-uri')
1532
+ || options.activeFilePath
1533
+ || '';
1534
+ if (editorPanelEl) {
1535
+ closeInlineEditor(false);
1536
+ return false;
1537
+ }
1538
+ let initialContent = '';
1539
+ if (activeEditorPath) {
1540
+ try {
1541
+ const readRes = await ctx.bridge.post('/file/read', { path: activeEditorPath });
1542
+ if (readRes?.ok) initialContent = readRes.content || '';
1543
+ } catch {}
1544
+ }
1545
+
1546
+ editorPanelEl = doc.createElement('div');
1547
+ editorPanelEl.id = 'agy-inline-file-editor-panel';
1548
+ editorTextareaEl = doc.createElement('textarea');
1549
+ editorTextareaEl.id = 'agy-inline-file-textarea';
1550
+ editorTextareaEl.value = initialContent;
1551
+ editorPanelEl.appendChild(editorTextareaEl);
1552
+
1553
+ const saveBtn = doc.createElement('button');
1554
+ saveBtn.type = 'button';
1555
+ saveBtn.id = 'agy-inline-file-save';
1556
+ saveBtn.textContent = '保存 (⌘S)';
1557
+ saveBtn.addEventListener('click', () => { void saveInlineFile(); });
1558
+ editorPanelEl.appendChild(saveBtn);
1559
+
1560
+ const doneBtn = doc.createElement('button');
1561
+ doneBtn.type = 'button';
1562
+ doneBtn.id = 'agy-inline-file-done';
1563
+ doneBtn.textContent = '完成';
1564
+ doneBtn.addEventListener('click', () => closeInlineEditor(true));
1565
+ editorPanelEl.appendChild(doneBtn);
1566
+
1567
+ const mountTarget = headerEl?.parentElement || headerEl || doc.body;
1568
+ mountTarget?.appendChild?.(editorPanelEl);
1569
+ return true;
1570
+ }
1571
+
1572
+ function attachFileEditorControl(headerEl) {
1573
+ if (!settings.enableInlineFileEditor || !headerEl || !doc?.createElement) return;
1574
+ if (headerEl.querySelector?.('#agy-file-editor-controls')) return;
1575
+ editorControlEl = doc.createElement('button');
1576
+ editorControlEl.type = 'button';
1577
+ editorControlEl.id = 'agy-file-editor-controls';
1578
+ editorControlEl.textContent = '编辑';
1579
+ editorControlEl.addEventListener('click', () => { void openInlineEditor(headerEl); });
1580
+ headerEl.appendChild(editorControlEl);
1581
+ }
1582
+
1583
+ const stopThinkingGuard = ctx.anchors.observe('chat.thinkingTrigger', () => {
1584
+ if (settings.keepThinkingExpanded) {
1585
+ expandThinking();
1586
+ }
1587
+ });
1588
+
1589
+ const stopViewportObserver = ctx.anchors.observe('chat.scrollViewport', () => {
1590
+ scheduleSyncDockPosition();
1591
+ });
1592
+
1593
+ const stopComposerObserver = ctx.anchors.observe('composer.root', () => {
1594
+ scheduleSyncDockPosition();
1595
+ });
1596
+
1597
+ const stopFileHeaderObserver = ctx.anchors.observe('fileViewer.header', (headerEl) => {
1598
+ attachFileEditorControl(headerEl);
1599
+ });
1600
+
1601
+ const stopDialogObserver = ctx.anchors.observe('settings.dialog', () => {
1602
+ syncDockDialogLayering();
1603
+ });
1604
+
1605
+ const stopSearchCloseSub = ctx.events?.on?.('chat:search-close@1', () => {
1606
+ setSearchOpen(false, { silent: true, reason: 'external-close' });
1607
+ });
1608
+
1609
+ const stopContextSub = ctx.state?.subscribe?.('state:context.snapshot@1', (snap) => {
1610
+ latestContextCascadeId = snap?.cascadeId ? String(snap.cascadeId) : null;
1611
+ });
1612
+
1613
+ const onWinResize = () => scheduleSyncDockPosition();
1614
+
1615
+ const onKeyDown = (e) => {
1616
+ if (!e) return;
1617
+ if (e.key === 'Escape' && exportMenuOpen) {
1618
+ setExportMenuOpen(false);
1619
+ e.preventDefault?.();
1620
+ e.stopPropagation?.();
1621
+ return;
1622
+ }
1623
+ // 按住 ⌘(无其他修饰键)浮现左侧 1~9 序号角标
1624
+ if ((e.key === 'Meta' || (e.metaKey && !e.key)) && !e.shiftKey && !e.ctrlKey && !e.altKey) {
1625
+ showConvBadges();
1626
+ return;
1627
+ }
1628
+
1629
+ // ⌘1~⌘9 快速切换对话(显式避开 ⌘⇧3/4/5 系统截图)
1630
+ if (e.metaKey && !e.shiftKey && !e.ctrlKey && !e.altKey) {
1631
+ const mCode = typeof e.code === 'string' && /^Digit([1-9])$/.exec(e.code);
1632
+ const digit = mCode ? Number(mCode[1]) : (/^[1-9]$/.test(String(e.key || '')) ? Number(e.key) : 0);
1633
+ if (digit >= 1 && digit <= 9) {
1634
+ if (switchConversation(digit - 1)) {
1635
+ e.preventDefault?.();
1636
+ e.stopPropagation?.();
1637
+ e.stopImmediatePropagation?.();
1638
+ hideConvBadges();
1639
+ }
1640
+ return;
1641
+ }
1642
+ if (String(e.key || '').toLowerCase() === 's' && editorPanelEl) {
1643
+ e.preventDefault?.();
1644
+ e.stopPropagation?.();
1645
+ void saveInlineFile();
1646
+ return;
1647
+ }
1648
+ }
1649
+
1650
+ // ⌘⇧[ / ⌘⇧] 与 ⌃Tab / ⌃⇧Tab 循环切换对话
1651
+ if (e.metaKey && e.shiftKey && !e.ctrlKey && !e.altKey) {
1652
+ if (e.key === '[' || e.key === '{' || e.code === 'BracketLeft') {
1653
+ if (cycleConversation(-1)) {
1654
+ e.preventDefault?.();
1655
+ e.stopPropagation?.();
1656
+ hideConvBadges();
1657
+ }
1658
+ return;
1659
+ }
1660
+ if (e.key === ']' || e.key === '}' || e.code === 'BracketRight') {
1661
+ if (cycleConversation(1)) {
1662
+ e.preventDefault?.();
1663
+ e.stopPropagation?.();
1664
+ hideConvBadges();
1665
+ }
1666
+ return;
1667
+ }
1668
+ }
1669
+
1670
+ if (e.ctrlKey && !e.metaKey && !e.altKey && e.key === 'Tab') {
1671
+ if (cycleConversation(e.shiftKey ? -1 : 1)) {
1672
+ e.preventDefault?.();
1673
+ e.stopPropagation?.();
1674
+ }
1675
+ }
1676
+ };
1677
+
1678
+ const onKeyUp = (e) => {
1679
+ if (!e || e.key === 'Meta' || !e.metaKey) {
1680
+ hideConvBadges();
1681
+ }
1682
+ };
1683
+
1684
+ const onBlur = () => hideConvBadges();
1685
+
1686
+ const onDocClick = (ev) => {
1687
+ if (exportMenuOpen) {
1688
+ const target = ev?.target;
1689
+ const inMenu = target && (target === exportMenuEl || target === exportBtnEl || exportMenuEl?.contains?.(target) || exportBtnEl?.contains?.(target));
1690
+ if (!inMenu) {
1691
+ setExportMenuOpen(false);
1692
+ }
1693
+ }
1694
+ if (!settings.enableCmdClickLinks) return;
1695
+ const isMod = Boolean(ev?.metaKey || ev?.ctrlKey);
1696
+ if (!isMod) return;
1697
+ const href = ev?.target?.getAttribute?.('href') || ev?.href || '';
1698
+ if (!href) return;
1699
+ if (!isSafeExternalUrl(href)) return;
1700
+ if (typeof ev.preventDefault === 'function') ev.preventDefault();
1701
+ if (typeof options.onOpenExternal === 'function') {
1702
+ options.onOpenExternal(href);
1703
+ } else if (typeof globalThis.open === 'function') {
1704
+ globalThis.open(href, '_blank', 'noopener,noreferrer');
1705
+ }
1706
+ };
1707
+
1708
+ doc?.addEventListener?.('click', onDocClick);
1709
+ doc?.addEventListener?.('keydown', onKeyDown, true);
1710
+ doc?.addEventListener?.('keyup', onKeyUp, true);
1711
+ win?.addEventListener?.('blur', onBlur);
1712
+ win?.addEventListener?.('resize', onWinResize);
1713
+
1714
+ ensureDock();
1715
+
1716
+ const stopSvc = ctx.services.provide('chat-nav', {
1717
+ scrollTop,
1718
+ scrollBottom,
1719
+ stepTurn,
1720
+ expandThinking,
1721
+ collapseThinking,
1722
+ toggleThinking,
1723
+ setSearchOpen,
1724
+ runSearch,
1725
+ focusMatch,
1726
+ clearHighlights,
1727
+ syncDockPosition,
1728
+ syncDockDialogLayering,
1729
+ switchConversation,
1730
+ cycleConversation,
1731
+ showConvBadges,
1732
+ hideConvBadges,
1733
+ openInlineEditor,
1734
+ saveInlineFile,
1735
+ closeInlineEditor,
1736
+ isSafeExternalUrl,
1737
+ copyConversationId,
1738
+ exportConversation,
1739
+ exportAllConversations,
1740
+ setExportMenuOpen,
1741
+ getConfiguredExportFormats,
1742
+ getSettings: () => ({ ...settings }),
1743
+ registerNavButton(def) {
1744
+ if (!def?.id) throw new Error('registerNavButton requires id');
1745
+ customButtons.set(def.id, def);
1746
+ renderCustomButtons();
1747
+ return () => {
1748
+ customButtons.delete(def.id);
1749
+ renderCustomButtons();
1750
+ };
1751
+ }
1752
+ });
1753
+
1754
+ const stopSettingsChange = ctx.settings?.onChange?.((nextValues) => {
1755
+ settings = normalizeRendererSettings(nextValues || {});
1756
+ ensureDock();
1757
+ updateExportButtonMeta();
1758
+ if (exportMenuOpen) {
1759
+ if (getConfiguredExportFormats().length <= 1) {
1760
+ setExportMenuOpen(false);
1761
+ } else {
1762
+ renderExportFormatMenu();
1763
+ }
1764
+ }
1765
+ if (searchInputEl?.value && (searchOpen || searchMatches.length > 0)) {
1766
+ runSearch(searchInputEl.value);
1767
+ }
1768
+ if (!settings.enableInlineFileEditor) {
1769
+ closeInlineEditor(false);
1770
+ if (editorControlEl?.remove) editorControlEl.remove();
1771
+ editorControlEl = null;
1772
+ } else {
1773
+ attachFileEditorControl(ctx.anchors.query('fileViewer.header'));
1774
+ }
1775
+ if (settings.keepThinkingExpanded) {
1776
+ expandThinking();
1777
+ }
1778
+ });
1779
+
1780
+ disposers.push(
1781
+ stopSvc,
1782
+ stopSettingsChange,
1783
+ stopStyles,
1784
+ stopThinkingGuard,
1785
+ stopViewportObserver,
1786
+ stopComposerObserver,
1787
+ stopFileHeaderObserver,
1788
+ stopDialogObserver,
1789
+ stopSearchCloseSub,
1790
+ stopContextSub,
1791
+ () => doc?.removeEventListener?.('click', onDocClick),
1792
+ () => doc?.removeEventListener?.('keydown', onKeyDown, true),
1793
+ () => doc?.removeEventListener?.('keyup', onKeyUp, true),
1794
+ () => win?.removeEventListener?.('blur', onBlur),
1795
+ () => win?.removeEventListener?.('resize', onWinResize),
1796
+ hideConvBadges,
1797
+ () => closeInlineEditor(false),
1798
+ clearHighlights,
1799
+ teardownDock,
1800
+ () => { if (editorControlEl?.remove) editorControlEl.remove(); editorControlEl = null; },
1801
+ () => { customButtons.clear(); }
1802
+ );
1803
+ }
1804
+
1805
+ function dispose() {
1806
+ for (const fn of disposers) {
1807
+ try { if (typeof fn === 'function') fn(); } catch {}
1808
+ }
1809
+ disposers = [];
1810
+ }
1811
+
1812
+ module.exports = {
1813
+ isSafeExternalUrl,
1814
+ createSearchMatcher,
1815
+ mount,
1816
+ dispose
1817
+ };