dsh-plugin-marginalia 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js ADDED
@@ -0,0 +1,1571 @@
1
+ window.__ModuleLoader__.load({
2
+ id: 'dsh-plugin-marginalia',
3
+ factory(require) {
4
+ const React = require('react');
5
+ const h = React.createElement;
6
+
7
+ const PLUGIN_ID = 'dsh-plugin-marginalia';
8
+ const TAB_KIND = 'marginalia';
9
+ const STORAGE_PREFIX = 'dsh.marginalia.v2.';
10
+ const MAX_STORED_MESSAGES = 40;
11
+
12
+ const en = {
13
+ 'tab.title': 'Marginalia',
14
+ 'guide.title': 'Marginalia',
15
+ 'guide.description': 'Select text or ask side-channel questions about the main chat',
16
+ 'header.tooltip': 'Ask Marginalia (Side Chat)',
17
+ 'sel.addToChat': 'Add to chat',
18
+ 'sel.askSide': 'Ask in side chat',
19
+ 'mode.side': 'Side Chat',
20
+ 'mode.main': 'To Main Chat',
21
+ 'context.on': 'With main context',
22
+ 'context.off': 'Standalone',
23
+ 'newChat': 'New side chat',
24
+ 'quote.count': '{n} selected snippet',
25
+ 'quote.countPlural': '{n} selected snippets',
26
+ 'empty.title': 'Ask anything in the side chat',
27
+ 'empty.subtitle.side': 'Select any text in the main conversation and click "Ask in side chat", or type a question below without interrupting the main thread.',
28
+ 'empty.subtitle.main': 'Send a prompt directly into the main conversation queue from the sidebar.',
29
+ 'chip.summarize': 'Summarize progress so far',
30
+ 'chip.explain': 'Explain the latest response',
31
+ 'chip.next': 'What should we do next?',
32
+ 'placeholder.side': 'Ask about this conversation…',
33
+ 'placeholder.main': 'Send a message to the main conversation…',
34
+ 'send': 'Send',
35
+ 'stop': 'Stop',
36
+ 'copy': 'Copy',
37
+ 'copied': 'Copied',
38
+ 'promote': 'Send to main',
39
+ 'sentToMain': 'Sent to main conversation',
40
+ 'addedToMain': 'Copied & sent to main chat',
41
+ 'thinking': 'Thinking…',
42
+ 'error.noSession': 'Open or start a conversation first.',
43
+ 'error.sendFailed': 'Failed to send request',
44
+ };
45
+
46
+ const zh = {
47
+ 'tab.title': '旁注提问',
48
+ 'guide.title': '旁注提问 Marginalia',
49
+ 'guide.description': '划词或直接在右侧边栏向主对话提问,不打断主流程',
50
+ 'header.tooltip': '打开旁注提问 (Marginalia)',
51
+ 'sel.addToChat': '添加到对话',
52
+ 'sel.askSide': '在侧边聊天中提问',
53
+ 'mode.side': '旁注提问',
54
+ 'mode.main': '直发主对话',
55
+ 'context.on': '携带主对话上下文',
56
+ 'context.off': '独立提问',
57
+ 'newChat': '新旁注对话',
58
+ 'quote.count': '{n} 个已选文本片段',
59
+ 'quote.countPlural': '{n} 个已选文本片段',
60
+ 'empty.title': '在侧边聊天中随时提问',
61
+ 'empty.subtitle.side': '在主对话中划选任意文字即可「在侧边聊天中提问」,也可以直接输入问题,不会打断或污染主对话。',
62
+ 'empty.subtitle.main': '「直发主对话」会将你的问题直接排队或插队发送到主会话中。',
63
+ 'chip.summarize': '总结目前为止的进展',
64
+ 'chip.explain': '解释一下刚才的回复',
65
+ 'chip.next': '接下来建议做什么?',
66
+ 'placeholder.side': '针对当前对话提问…',
67
+ 'placeholder.main': '直接发送消息到主对话…',
68
+ 'send': '发送',
69
+ 'stop': '停止',
70
+ 'copy': '复制',
71
+ 'copied': '已复制',
72
+ 'promote': '发到主对话',
73
+ 'sentToMain': '已发送到主对话',
74
+ 'addedToMain': '已添加到主对话',
75
+ 'thinking': '思考中…',
76
+ 'error.noSession': '请先打开或创建一个会话。',
77
+ 'error.sendFailed': '发送失败',
78
+ };
79
+
80
+ const CSS = `
81
+ .mg-header-btn {
82
+ display: inline-flex;
83
+ align-items: center;
84
+ justify-content: center;
85
+ width: 28px;
86
+ height: 28px;
87
+ padding: 0;
88
+ border: none;
89
+ border-radius: 8px;
90
+ background: transparent;
91
+ color: var(--dsw-alias-label-secondary);
92
+ cursor: pointer;
93
+ transition: background-color 0.15s ease, color 0.15s ease;
94
+ }
95
+ .mg-header-btn:hover {
96
+ background: var(--dsw-alias-bg-layer-2);
97
+ color: var(--dsw-alias-label-primary);
98
+ }
99
+ .mg-sel-bar {
100
+ position: fixed;
101
+ z-index: 9999;
102
+ display: inline-flex;
103
+ align-items: center;
104
+ padding: 3px;
105
+ border-radius: 12px;
106
+ background: var(--dsw-alias-bg-overlay);
107
+ border: 1px solid var(--dsw-alias-border-l1);
108
+ box-shadow: 0 6px 20px rgba(0, 0, 0, 0.14), 0 1px 3px rgba(0, 0, 0, 0.08);
109
+ transform: translate(-50%, -100%);
110
+ pointer-events: auto;
111
+ user-select: none;
112
+ }
113
+ .mg-sel-btn {
114
+ border: none;
115
+ background: transparent;
116
+ color: var(--dsw-alias-label-primary);
117
+ font-size: 13px;
118
+ font-weight: 500;
119
+ padding: 6px 12px;
120
+ border-radius: 9px;
121
+ cursor: pointer;
122
+ white-space: nowrap;
123
+ transition: background-color 0.12s ease;
124
+ }
125
+ .mg-sel-btn:hover {
126
+ background: var(--dsw-alias-bg-layer-2);
127
+ }
128
+ .mg-sel-sep {
129
+ width: 1px;
130
+ height: 16px;
131
+ background: var(--dsw-alias-border-l1);
132
+ margin: 0 1px;
133
+ }
134
+ .mg-root {
135
+ display: flex;
136
+ flex-direction: column;
137
+ height: 100%;
138
+ min-height: 0;
139
+ background: var(--dsw-alias-bg-base);
140
+ color: var(--dsw-alias-label-primary);
141
+ font-size: 14px;
142
+ line-height: 1.65;
143
+ }
144
+ .mg-toolbar {
145
+ display: flex;
146
+ align-items: center;
147
+ justify-content: space-between;
148
+ gap: 8px;
149
+ padding: 8px 14px;
150
+ border-bottom: 1px solid var(--dsw-alias-border-l1);
151
+ flex-wrap: wrap;
152
+ }
153
+ .mg-seg {
154
+ display: inline-flex;
155
+ padding: 2px;
156
+ border-radius: 10px;
157
+ background: var(--dsw-alias-bg-layer-2);
158
+ }
159
+ .mg-seg-btn {
160
+ border: none;
161
+ background: transparent;
162
+ color: var(--dsw-alias-label-secondary);
163
+ font-size: 12.5px;
164
+ font-weight: 500;
165
+ padding: 4px 10px;
166
+ border-radius: 8px;
167
+ cursor: pointer;
168
+ transition: background-color 0.15s ease, color 0.15s ease;
169
+ }
170
+ .mg-seg-btn.is-active {
171
+ background: var(--dsw-alias-bg-base);
172
+ color: var(--dsw-alias-label-primary);
173
+ box-shadow: 0 1px 2px rgba(0, 0, 0, 0.08);
174
+ }
175
+ .mg-toolbar-right {
176
+ display: inline-flex;
177
+ align-items: center;
178
+ gap: 6px;
179
+ }
180
+ .mg-pill-btn {
181
+ display: inline-flex;
182
+ align-items: center;
183
+ gap: 4px;
184
+ border: 1px solid var(--dsw-alias-border-l1);
185
+ background: transparent;
186
+ color: var(--dsw-alias-label-secondary);
187
+ font-size: 12px;
188
+ padding: 3px 9px;
189
+ border-radius: 999px;
190
+ cursor: pointer;
191
+ transition: border-color 0.15s ease, color 0.15s ease, background-color 0.15s ease;
192
+ }
193
+ .mg-pill-btn:hover {
194
+ background: var(--dsw-alias-bg-layer-2);
195
+ color: var(--dsw-alias-label-primary);
196
+ }
197
+ .mg-pill-btn.is-on {
198
+ border-color: var(--dsw-alias-brand-primary);
199
+ color: var(--dsw-alias-brand-primary);
200
+ }
201
+ .mg-scroll {
202
+ flex: 1;
203
+ min-height: 0;
204
+ overflow-y: auto;
205
+ padding: 16px 16px 12px;
206
+ display: flex;
207
+ flex-direction: column;
208
+ gap: 18px;
209
+ }
210
+ .mg-empty {
211
+ margin: auto 0;
212
+ padding: 24px 12px;
213
+ text-align: center;
214
+ display: flex;
215
+ flex-direction: column;
216
+ align-items: center;
217
+ gap: 10px;
218
+ }
219
+ .mg-empty-icon {
220
+ width: 36px;
221
+ height: 36px;
222
+ border-radius: 12px;
223
+ display: inline-flex;
224
+ align-items: center;
225
+ justify-content: center;
226
+ background: var(--dsw-alias-bg-layer-2);
227
+ color: var(--dsw-alias-brand-primary);
228
+ }
229
+ .mg-empty-title {
230
+ font-size: 15px;
231
+ font-weight: 600;
232
+ color: var(--dsw-alias-label-primary);
233
+ }
234
+ .mg-empty-sub {
235
+ font-size: 13px;
236
+ color: var(--dsw-alias-label-secondary);
237
+ max-width: 300px;
238
+ line-height: 1.55;
239
+ }
240
+ .mg-chips {
241
+ display: flex;
242
+ flex-wrap: wrap;
243
+ justify-content: center;
244
+ gap: 8px;
245
+ margin-top: 6px;
246
+ }
247
+ .mg-chip {
248
+ border: 1px solid var(--dsw-alias-border-l1);
249
+ background: var(--dsw-alias-bg-layer-1);
250
+ color: var(--dsw-alias-label-primary);
251
+ font-size: 12.5px;
252
+ padding: 6px 12px;
253
+ border-radius: 999px;
254
+ cursor: pointer;
255
+ transition: border-color 0.15s ease, background-color 0.15s ease;
256
+ }
257
+ .mg-chip:hover {
258
+ border-color: var(--dsw-alias-brand-primary);
259
+ background: var(--dsw-alias-bg-layer-2);
260
+ }
261
+ .mg-msg {
262
+ display: flex;
263
+ flex-direction: column;
264
+ gap: 6px;
265
+ }
266
+ .mg-msg.is-user {
267
+ align-items: flex-end;
268
+ }
269
+ .mg-msg.is-assistant {
270
+ align-items: flex-start;
271
+ }
272
+ .mg-user-quotes {
273
+ display: flex;
274
+ flex-wrap: wrap;
275
+ justify-content: flex-end;
276
+ gap: 4px;
277
+ max-width: 88%;
278
+ }
279
+ .mg-user-bubble {
280
+ max-width: 88%;
281
+ padding: 9px 14px;
282
+ border-radius: 18px;
283
+ background: var(--dsw-alias-bg-layer-2);
284
+ color: var(--dsw-alias-label-primary);
285
+ white-space: pre-wrap;
286
+ word-break: break-word;
287
+ font-size: 14px;
288
+ line-height: 1.55;
289
+ }
290
+ .mg-assistant-body {
291
+ width: 100%;
292
+ color: var(--dsw-alias-label-primary);
293
+ word-break: break-word;
294
+ font-size: 14px;
295
+ line-height: 1.65;
296
+ }
297
+ .mg-assistant-body.is-error {
298
+ padding: 10px 12px;
299
+ border-radius: 12px;
300
+ background: var(--dsw-alias-bg-layer-1);
301
+ border: 1px solid var(--dsw-alias-state-error-primary);
302
+ color: var(--dsw-alias-state-error-primary);
303
+ }
304
+ .mg-md p {
305
+ margin: 0 0 10px;
306
+ }
307
+ .mg-md p:last-child {
308
+ margin-bottom: 0;
309
+ }
310
+ .mg-md h1, .mg-md h2, .mg-md h3, .mg-md h4 {
311
+ margin: 14px 0 6px;
312
+ font-weight: 600;
313
+ line-height: 1.35;
314
+ }
315
+ .mg-md h1 { font-size: 17px; }
316
+ .mg-md h2 { font-size: 15.5px; }
317
+ .mg-md h3, .mg-md h4 { font-size: 14.5px; }
318
+ .mg-md ul, .mg-md ol {
319
+ margin: 6px 0 10px;
320
+ padding-left: 20px;
321
+ }
322
+ .mg-md li {
323
+ margin: 3px 0;
324
+ }
325
+ .mg-md blockquote {
326
+ margin: 8px 0;
327
+ padding: 4px 12px;
328
+ border-left: 3px solid var(--dsw-alias-border-l2);
329
+ color: var(--dsw-alias-label-secondary);
330
+ }
331
+ .mg-md a {
332
+ color: var(--dsw-alias-brand-primary);
333
+ text-decoration: none;
334
+ }
335
+ .mg-md a:hover {
336
+ text-decoration: underline;
337
+ }
338
+ .mg-md code {
339
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
340
+ font-size: 12.5px;
341
+ padding: 1px 5px;
342
+ border-radius: 5px;
343
+ background: var(--dsw-alias-bg-layer-2);
344
+ }
345
+ .mg-code-wrap {
346
+ margin: 10px 0;
347
+ border-radius: 10px;
348
+ overflow: hidden;
349
+ border: 1px solid var(--dsw-alias-border-l1);
350
+ background: var(--dsw-alias-bg-layer-1);
351
+ }
352
+ .mg-code-head {
353
+ display: flex;
354
+ align-items: center;
355
+ justify-content: space-between;
356
+ padding: 5px 10px;
357
+ font-size: 11.5px;
358
+ color: var(--dsw-alias-label-secondary);
359
+ border-bottom: 1px solid var(--dsw-alias-border-l1);
360
+ background: var(--dsw-alias-bg-layer-2);
361
+ }
362
+ .mg-code-pre {
363
+ margin: 0;
364
+ padding: 10px 12px;
365
+ overflow-x: auto;
366
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
367
+ font-size: 12.5px;
368
+ line-height: 1.5;
369
+ }
370
+ .mg-thinking {
371
+ display: inline-flex;
372
+ align-items: center;
373
+ gap: 6px;
374
+ color: var(--dsw-alias-label-secondary);
375
+ font-size: 13px;
376
+ }
377
+ .mg-dot {
378
+ width: 7px;
379
+ height: 7px;
380
+ border-radius: 50%;
381
+ background: var(--dsw-alias-brand-primary);
382
+ animation: mgPulse 1.1s ease-in-out infinite;
383
+ }
384
+ @keyframes mgPulse {
385
+ 0%, 100% { opacity: 0.35; transform: scale(0.85); }
386
+ 50% { opacity: 1; transform: scale(1.1); }
387
+ }
388
+ .mg-msg-meta {
389
+ display: flex;
390
+ align-items: center;
391
+ gap: 10px;
392
+ font-size: 12px;
393
+ color: var(--dsw-alias-label-secondary);
394
+ padding: 2px 0;
395
+ }
396
+ .mg-action-link {
397
+ display: inline-flex;
398
+ align-items: center;
399
+ gap: 4px;
400
+ border: none;
401
+ background: transparent;
402
+ color: var(--dsw-alias-label-secondary);
403
+ font-size: 12px;
404
+ padding: 2px 4px;
405
+ border-radius: 6px;
406
+ cursor: pointer;
407
+ }
408
+ .mg-action-link:hover {
409
+ background: var(--dsw-alias-bg-layer-2);
410
+ color: var(--dsw-alias-label-primary);
411
+ }
412
+ .mg-notice {
413
+ margin: 0 14px 8px;
414
+ padding: 7px 12px;
415
+ border-radius: 10px;
416
+ font-size: 12.5px;
417
+ background: var(--dsw-alias-bg-layer-2);
418
+ border: 1px solid var(--dsw-alias-border-l1);
419
+ color: var(--dsw-alias-state-success-primary);
420
+ }
421
+ .mg-notice.is-error {
422
+ color: var(--dsw-alias-state-error-primary);
423
+ border-color: var(--dsw-alias-state-error-primary);
424
+ }
425
+ .mg-composer {
426
+ padding: 8px 14px 14px;
427
+ background: var(--dsw-alias-bg-base);
428
+ }
429
+ .mg-input-box {
430
+ display: flex;
431
+ flex-direction: column;
432
+ gap: 8px;
433
+ padding: 10px 12px;
434
+ border-radius: 18px;
435
+ border: 1px solid var(--dsw-alias-border-l1);
436
+ background: var(--dsw-alias-bg-layer-1);
437
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
438
+ }
439
+ .mg-input-box:focus-within {
440
+ border-color: var(--dsw-alias-border-l2);
441
+ }
442
+ .mg-quote-strip {
443
+ display: flex;
444
+ flex-direction: column;
445
+ gap: 6px;
446
+ }
447
+ .mg-quote-chip {
448
+ display: inline-flex;
449
+ align-items: center;
450
+ gap: 6px;
451
+ align-self: flex-start;
452
+ padding: 4px 10px;
453
+ border-radius: 10px;
454
+ background: var(--dsw-alias-bg-layer-2);
455
+ border: 1px solid var(--dsw-alias-border-l1);
456
+ color: var(--dsw-alias-label-primary);
457
+ font-size: 12.5px;
458
+ font-weight: 500;
459
+ cursor: pointer;
460
+ }
461
+ .mg-quote-x {
462
+ border: none;
463
+ background: transparent;
464
+ color: var(--dsw-alias-label-secondary);
465
+ font-size: 14px;
466
+ line-height: 1;
467
+ padding: 0 2px;
468
+ cursor: pointer;
469
+ }
470
+ .mg-quote-x:hover {
471
+ color: var(--dsw-alias-label-primary);
472
+ }
473
+ .mg-quote-preview {
474
+ padding: 6px 10px;
475
+ border-radius: 8px;
476
+ background: var(--dsw-alias-bg-base);
477
+ border: 1px solid var(--dsw-alias-border-l1);
478
+ font-size: 12px;
479
+ color: var(--dsw-alias-label-secondary);
480
+ max-height: 96px;
481
+ overflow-y: auto;
482
+ white-space: pre-wrap;
483
+ }
484
+ .mg-textarea {
485
+ width: 100%;
486
+ min-height: 24px;
487
+ max-height: 160px;
488
+ resize: none;
489
+ border: none;
490
+ outline: none;
491
+ background: transparent;
492
+ color: var(--dsw-alias-label-primary);
493
+ font-family: inherit;
494
+ font-size: 14px;
495
+ line-height: 1.5;
496
+ padding: 0;
497
+ }
498
+ .mg-textarea::placeholder {
499
+ color: var(--dsw-alias-label-secondary);
500
+ }
501
+ .mg-composer-foot {
502
+ display: flex;
503
+ align-items: center;
504
+ justify-content: space-between;
505
+ gap: 8px;
506
+ }
507
+ .mg-composer-tag {
508
+ font-size: 12px;
509
+ color: var(--dsw-alias-label-secondary);
510
+ }
511
+ .mg-circle-btn {
512
+ display: inline-flex;
513
+ align-items: center;
514
+ justify-content: center;
515
+ width: 30px;
516
+ height: 30px;
517
+ border: none;
518
+ border-radius: 50%;
519
+ cursor: pointer;
520
+ background: var(--dsw-alias-brand-primary);
521
+ color: #ffffff;
522
+ transition: opacity 0.15s ease, transform 0.1s ease;
523
+ }
524
+ .mg-circle-btn:disabled {
525
+ opacity: 0.35;
526
+ cursor: not-allowed;
527
+ }
528
+ .mg-circle-btn.is-stop {
529
+ background: var(--dsw-alias-label-primary);
530
+ color: var(--dsw-alias-bg-base);
531
+ }
532
+ .mg-header-btn:focus-visible,
533
+ .mg-sel-btn:focus-visible,
534
+ .mg-seg-btn:focus-visible,
535
+ .mg-pill-btn:focus-visible,
536
+ .mg-chip:focus-visible,
537
+ .mg-action-link:focus-visible,
538
+ .mg-circle-btn:focus-visible {
539
+ outline: 2px solid var(--dsw-alias-brand-primary);
540
+ outline-offset: 1px;
541
+ }
542
+ `;
543
+
544
+ function MarginaliaGlyph(props) {
545
+ const size = props?.size || 16;
546
+ return h(
547
+ 'svg',
548
+ {
549
+ width: size,
550
+ height: size,
551
+ viewBox: '0 0 24 24',
552
+ fill: 'none',
553
+ stroke: 'currentColor',
554
+ strokeWidth: 1.8,
555
+ strokeLinecap: 'round',
556
+ strokeLinejoin: 'round',
557
+ className: props?.className,
558
+ 'aria-hidden': true,
559
+ },
560
+ h('rect', { x: 3.5, y: 4, width: 9.5, height: 16, rx: 2 }),
561
+ h('path', { d: 'M6.5 8.5h3.5M6.5 12h3.5M6.5 15.5h2' }),
562
+ h('path', {
563
+ d: 'M14 7.5a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2h-1.8L15 17.5V15.5a1.5 1.5 0 0 1-1-1.4V7.5z',
564
+ }),
565
+ );
566
+ }
567
+
568
+ function renderInline(text, keyPrefix) {
569
+ const nodes = [];
570
+ const tokenRe = /(`[^`]+`|\*\*[^*]+\*\*|\*[^*]+\*|\[[^\]]+\]\(https?:\/\/[^)]+\))/g;
571
+ let last = 0;
572
+ let match;
573
+ let idx = 0;
574
+ while ((match = tokenRe.exec(text)) !== null) {
575
+ if (match.index > last) {
576
+ nodes.push(text.slice(last, match.index));
577
+ }
578
+ const tok = match[0];
579
+ const k = keyPrefix + '-' + idx++;
580
+ if (tok.startsWith('`') && tok.endsWith('`')) {
581
+ nodes.push(h('code', { key: k }, tok.slice(1, -1)));
582
+ } else if (tok.startsWith('**') && tok.endsWith('**')) {
583
+ nodes.push(h('strong', { key: k }, tok.slice(2, -2)));
584
+ } else if (tok.startsWith('*') && tok.endsWith('*')) {
585
+ nodes.push(h('em', { key: k }, tok.slice(1, -1)));
586
+ } else if (tok.startsWith('[')) {
587
+ const split = tok.indexOf('](');
588
+ const label = tok.slice(1, split);
589
+ const href = tok.slice(split + 2, -1);
590
+ nodes.push(
591
+ h(
592
+ 'a',
593
+ { key: k, href, target: '_blank', rel: 'noopener noreferrer' },
594
+ label,
595
+ ),
596
+ );
597
+ }
598
+ last = tokenRe.lastIndex;
599
+ }
600
+ if (last < text.length) {
601
+ nodes.push(text.slice(last));
602
+ }
603
+ return nodes;
604
+ }
605
+
606
+ function MarkdownBlock({ text, copyLabel, copiedLabel }) {
607
+ const [copiedCodeIdx, setCopiedCodeIdx] = React.useState(null);
608
+ if (!text) return null;
609
+
610
+ const blocks = [];
611
+ const fenceRe = /```([a-zA-Z0-9_-]*)\n([\s\S]*?)```/g;
612
+ let last = 0;
613
+ let m;
614
+ let partIdx = 0;
615
+ while ((m = fenceRe.exec(text)) !== null) {
616
+ if (m.index > last) {
617
+ blocks.push({ kind: 'prose', content: text.slice(last, m.index), key: 'p-' + partIdx++ });
618
+ }
619
+ blocks.push({ kind: 'code', lang: m[1] || 'code', content: m[2].replace(/\n$/, ''), key: 'c-' + partIdx++ });
620
+ last = fenceRe.lastIndex;
621
+ }
622
+ if (last < text.length) {
623
+ blocks.push({ kind: 'prose', content: text.slice(last), key: 'p-' + partIdx++ });
624
+ }
625
+
626
+ const elements = [];
627
+ for (const blk of blocks) {
628
+ if (blk.kind === 'code') {
629
+ const codeKey = blk.key;
630
+ elements.push(
631
+ h(
632
+ 'div',
633
+ { key: codeKey, className: 'mg-code-wrap' },
634
+ h(
635
+ 'div',
636
+ { className: 'mg-code-head' },
637
+ h('span', null, blk.lang),
638
+ h(
639
+ 'button',
640
+ {
641
+ type: 'button',
642
+ className: 'mg-action-link',
643
+ onClick: () => {
644
+ navigator.clipboard?.writeText(blk.content).then(() => {
645
+ setCopiedCodeIdx(codeKey);
646
+ window.setTimeout(() => {
647
+ setCopiedCodeIdx((c) => (c === codeKey ? null : c));
648
+ }, 1500);
649
+ }).catch(() => {});
650
+ },
651
+ },
652
+ copiedCodeIdx === codeKey ? copiedLabel : copyLabel,
653
+ ),
654
+ ),
655
+ h('pre', { className: 'mg-code-pre' }, h('code', null, blk.content)),
656
+ ),
657
+ );
658
+ continue;
659
+ }
660
+
661
+ const lines = blk.content.split(/\r?\n/);
662
+ let listItems = [];
663
+ let listOrdered = false;
664
+ let pLines = [];
665
+ let subIdx = 0;
666
+
667
+ const flushPara = () => {
668
+ if (pLines.length === 0) return;
669
+ const joined = pLines.join('\n').trim();
670
+ pLines = [];
671
+ if (!joined) return;
672
+ elements.push(h('p', { key: blk.key + '-p-' + subIdx++ }, renderInline(joined, blk.key + '-i-' + subIdx)));
673
+ };
674
+
675
+ const flushList = () => {
676
+ if (listItems.length === 0) return;
677
+ const items = listItems;
678
+ const ordered = listOrdered;
679
+ listItems = [];
680
+ elements.push(
681
+ h(
682
+ ordered ? 'ol' : 'ul',
683
+ { key: blk.key + '-l-' + subIdx++ },
684
+ items.map((item, i) =>
685
+ h('li', { key: i }, renderInline(item, blk.key + '-li-' + subIdx + '-' + i)),
686
+ ),
687
+ ),
688
+ );
689
+ };
690
+
691
+ for (const line of lines) {
692
+ const trimmed = line.trim();
693
+ if (!trimmed) {
694
+ flushPara();
695
+ flushList();
696
+ continue;
697
+ }
698
+ const headingMatch = trimmed.match(/^(#{1,4})\s+(.+)$/);
699
+ if (headingMatch) {
700
+ flushPara();
701
+ flushList();
702
+ const lvl = headingMatch[1].length;
703
+ elements.push(
704
+ h('h' + lvl, { key: blk.key + '-h-' + subIdx++ }, renderInline(headingMatch[2], blk.key + '-hi-' + subIdx)),
705
+ );
706
+ continue;
707
+ }
708
+ const ulMatch = trimmed.match(/^[-*]\s+(.+)$/);
709
+ if (ulMatch) {
710
+ flushPara();
711
+ if (listItems.length > 0 && listOrdered) flushList();
712
+ listOrdered = false;
713
+ listItems.push(ulMatch[1]);
714
+ continue;
715
+ }
716
+ const olMatch = trimmed.match(/^\d+\.\s+(.+)$/);
717
+ if (olMatch) {
718
+ flushPara();
719
+ if (listItems.length > 0 && !listOrdered) flushList();
720
+ listOrdered = true;
721
+ listItems.push(olMatch[1]);
722
+ continue;
723
+ }
724
+ if (trimmed.startsWith('> ')) {
725
+ flushPara();
726
+ flushList();
727
+ elements.push(
728
+ h('blockquote', { key: blk.key + '-q-' + subIdx++ }, renderInline(trimmed.slice(2), blk.key + '-qi-' + subIdx)),
729
+ );
730
+ continue;
731
+ }
732
+ flushList();
733
+ pLines.push(line);
734
+ }
735
+ flushPara();
736
+ flushList();
737
+ }
738
+
739
+ return h('div', { className: 'mg-md' }, elements);
740
+ }
741
+
742
+ function loadStoredMessages(sessionId) {
743
+ if (!sessionId) return [];
744
+ try {
745
+ const raw = window.localStorage.getItem(STORAGE_PREFIX + sessionId);
746
+ if (!raw) return [];
747
+ const parsed = JSON.parse(raw);
748
+ return Array.isArray(parsed) ? parsed : [];
749
+ } catch {
750
+ return [];
751
+ }
752
+ }
753
+
754
+ function saveStoredMessages(sessionId, messages) {
755
+ if (!sessionId) return;
756
+ try {
757
+ const compact = messages.slice(-MAX_STORED_MESSAGES).map((m) => ({
758
+ id: m.id,
759
+ role: m.role,
760
+ text: m.text,
761
+ quotes: m.quotes,
762
+ model: m.model,
763
+ error: m.error,
764
+ }));
765
+ window.localStorage.setItem(STORAGE_PREFIX + sessionId, JSON.stringify(compact));
766
+ } catch {
767
+ // Ignore storage quota errors.
768
+ }
769
+ }
770
+
771
+ function makeId() {
772
+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
773
+ return crypto.randomUUID();
774
+ }
775
+ return 'mg-' + Date.now() + '-' + Math.random().toString(36).slice(2, 8);
776
+ }
777
+
778
+ return {
779
+ inject: ['slots', 'locale', 'sidebarRight', 'sidebarRightTabs', 'remote', 'uiSession'],
780
+ apply(ctx) {
781
+ ctx.effect(() => ctx.locale.register('marginalia', { en, zh }), 'marginalia: locale');
782
+ const t = ctx.locale.bind('marginalia');
783
+
784
+ // Shared quote bus so selecting text in the main chat immediately populates the side chat.
785
+ let pendingQuotes = [];
786
+ const quoteListeners = new Set();
787
+ function pushQuote(text) {
788
+ const clean = (text || '').trim();
789
+ if (!clean) return;
790
+ if (!pendingQuotes.includes(clean)) {
791
+ pendingQuotes = [...pendingQuotes, clean].slice(-5);
792
+ }
793
+ for (const fn of quoteListeners) fn(pendingQuotes);
794
+ }
795
+ function clearQuotes() {
796
+ pendingQuotes = [];
797
+ for (const fn of quoteListeners) fn(pendingQuotes);
798
+ }
799
+ function removeQuoteAt(index) {
800
+ pendingQuotes = pendingQuotes.filter((_, i) => i !== index);
801
+ for (const fn of quoteListeners) fn(pendingQuotes);
802
+ }
803
+
804
+ ctx.effect(() => {
805
+ const styleEl = document.createElement('style');
806
+ styleEl.setAttribute('data-marginalia-styles', 'true');
807
+ styleEl.textContent = CSS;
808
+ document.head.appendChild(styleEl);
809
+ return () => {
810
+ styleEl.remove();
811
+ };
812
+ }, 'marginalia: styles');
813
+
814
+ ctx.effect(
815
+ () =>
816
+ ctx.sidebarRightTabs.register({
817
+ id: PLUGIN_ID,
818
+ kind: TAB_KIND,
819
+ priority: 'extension',
820
+ keepMounted: true,
821
+ title: () => t('tab.title'),
822
+ guide: [
823
+ {
824
+ id: 'open',
825
+ order: 45,
826
+ title: () => t('guide.title'),
827
+ description: () => t('guide.description'),
828
+ icon: MarginaliaGlyph,
829
+ },
830
+ ],
831
+ }),
832
+ 'marginalia: tab-type',
833
+ );
834
+
835
+ function SelectionFloatingBar() {
836
+ const [, setTick] = React.useState(0);
837
+ const [sel, setSel] = React.useState(null);
838
+
839
+ React.useEffect(() => ctx.locale.subscribe(() => setTick((v) => v + 1)), []);
840
+
841
+ React.useEffect(() => {
842
+ const updateSelection = () => {
843
+ const s = window.getSelection();
844
+ if (!s || s.isCollapsed || s.rangeCount === 0) {
845
+ setSel(null);
846
+ return;
847
+ }
848
+ const text = s.toString().trim();
849
+ if (text.length < 2) {
850
+ setSel(null);
851
+ return;
852
+ }
853
+ const anchorEl =
854
+ s.anchorNode?.nodeType === 1 ? s.anchorNode : s.anchorNode?.parentElement;
855
+ if (!anchorEl) {
856
+ setSel(null);
857
+ return;
858
+ }
859
+ if (
860
+ anchorEl.closest('[data-marginalia-root]') ||
861
+ anchorEl.closest('input, textarea, [contenteditable="true"]')
862
+ ) {
863
+ setSel(null);
864
+ return;
865
+ }
866
+ const range = s.getRangeAt(0);
867
+ const rect = range.getBoundingClientRect();
868
+ if (!rect || (rect.width === 0 && rect.height === 0)) {
869
+ setSel(null);
870
+ return;
871
+ }
872
+ const left = Math.min(Math.max(rect.left + rect.width / 2, 130), window.innerWidth - 130);
873
+ const top = Math.max(rect.top - 8, 48);
874
+ setSel({ text, left, top });
875
+ };
876
+
877
+ const onMouseUp = () => window.setTimeout(updateSelection, 10);
878
+ const onKeyUp = () => window.setTimeout(updateSelection, 10);
879
+ const onScroll = () => setSel(null);
880
+
881
+ document.addEventListener('mouseup', onMouseUp);
882
+ document.addEventListener('keyup', onKeyUp);
883
+ window.addEventListener('scroll', onScroll, true);
884
+ return () => {
885
+ document.removeEventListener('mouseup', onMouseUp);
886
+ document.removeEventListener('keyup', onKeyUp);
887
+ window.removeEventListener('scroll', onScroll, true);
888
+ };
889
+ }, []);
890
+
891
+ if (!sel) return null;
892
+
893
+ const currentSessionId = ctx.uiSession?.adapter?.current?.getSnapshot()?.key;
894
+
895
+ return h(
896
+ 'div',
897
+ {
898
+ className: 'mg-sel-bar',
899
+ style: { left: sel.left + 'px', top: sel.top + 'px' },
900
+ onMouseDown: (e) => e.preventDefault(),
901
+ },
902
+ h(
903
+ 'button',
904
+ {
905
+ type: 'button',
906
+ className: 'mg-sel-btn',
907
+ onClick: () => {
908
+ const quoted = '> ' + sel.text.replace(/\n/g, '\n> ') + '\n\n';
909
+ navigator.clipboard?.writeText(quoted).catch(() => {});
910
+ if (currentSessionId && typeof ctx.remote?.session?.prompt === 'function') {
911
+ // Focus main composer if available; otherwise copy quote.
912
+ const composer = document.querySelector('textarea:not([data-marginalia-input])');
913
+ if (composer) {
914
+ composer.focus();
915
+ const setter = Object.getOwnPropertyDescriptor(
916
+ window.HTMLTextAreaElement.prototype,
917
+ 'value',
918
+ )?.set;
919
+ const nextVal = (composer.value ? composer.value + '\n' : '') + quoted;
920
+ setter?.call(composer, nextVal);
921
+ composer.dispatchEvent(new Event('input', { bubbles: true }));
922
+ }
923
+ }
924
+ window.getSelection()?.removeAllRanges();
925
+ setSel(null);
926
+ },
927
+ },
928
+ t('sel.addToChat'),
929
+ ),
930
+ h('div', { className: 'mg-sel-sep' }),
931
+ h(
932
+ 'button',
933
+ {
934
+ type: 'button',
935
+ className: 'mg-sel-btn',
936
+ onClick: () => {
937
+ pushQuote(sel.text);
938
+ window.getSelection()?.removeAllRanges();
939
+ setSel(null);
940
+ ctx.sidebarRight.openTab(TAB_KIND);
941
+ },
942
+ },
943
+ t('sel.askSide'),
944
+ ),
945
+ );
946
+ }
947
+
948
+ function HeaderTrigger() {
949
+ const [, setTick] = React.useState(0);
950
+ React.useEffect(() => ctx.locale.subscribe(() => setTick((v) => v + 1)), []);
951
+ const label = t('header.tooltip');
952
+ return h(
953
+ 'button',
954
+ {
955
+ type: 'button',
956
+ className: 'mg-header-btn',
957
+ title: label,
958
+ 'aria-label': label,
959
+ onClick: () => {
960
+ ctx.sidebarRight.openTab(TAB_KIND);
961
+ },
962
+ },
963
+ h(MarginaliaGlyph, { size: 16 }),
964
+ );
965
+ }
966
+
967
+ function MarginaliaBody(props) {
968
+ const sessionId = props?.sessionId;
969
+ const sessionStatus =
970
+ typeof props?.useSessionStatus === 'function' ? props.useSessionStatus() : undefined;
971
+ const isMainRunning = Boolean(sessionStatus?.running);
972
+
973
+ const [, setLocaleTick] = React.useState(0);
974
+ React.useEffect(() => ctx.locale.subscribe(() => setLocaleTick((v) => v + 1)), []);
975
+
976
+ const [mode, setMode] = React.useState('side');
977
+ const [includeContext, setIncludeContext] = React.useState(true);
978
+ const [messages, setMessages] = React.useState(() => loadStoredMessages(sessionId));
979
+ const [quotes, setQuotes] = React.useState(() => pendingQuotes);
980
+ const [showQuotePreview, setShowQuotePreview] = React.useState(false);
981
+ const [draft, setDraft] = React.useState('');
982
+ const [streaming, setStreaming] = React.useState(false);
983
+ const [copiedId, setCopiedId] = React.useState(null);
984
+ const [notice, setNotice] = React.useState(null);
985
+
986
+ const abortRef = React.useRef(null);
987
+ const scrollRef = React.useRef(null);
988
+ const textareaRef = React.useRef(null);
989
+
990
+ React.useEffect(() => {
991
+ const listener = (nextQuotes) => {
992
+ setQuotes(nextQuotes);
993
+ if (nextQuotes.length > 0) {
994
+ setMode('side');
995
+ window.setTimeout(() => textareaRef.current?.focus(), 40);
996
+ }
997
+ };
998
+ quoteListeners.add(listener);
999
+ return () => quoteListeners.delete(listener);
1000
+ }, []);
1001
+
1002
+ React.useEffect(() => {
1003
+ if (abortRef.current) {
1004
+ abortRef.current.abort();
1005
+ abortRef.current = null;
1006
+ }
1007
+ setStreaming(false);
1008
+ setMessages(loadStoredMessages(sessionId));
1009
+ }, [sessionId]);
1010
+
1011
+ React.useEffect(() => {
1012
+ if (!streaming) {
1013
+ saveStoredMessages(sessionId, messages);
1014
+ }
1015
+ }, [sessionId, messages, streaming]);
1016
+
1017
+ React.useEffect(() => {
1018
+ if (scrollRef.current) {
1019
+ scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
1020
+ }
1021
+ }, [messages, streaming]);
1022
+
1023
+ React.useEffect(() => {
1024
+ const el = textareaRef.current;
1025
+ if (!el) return;
1026
+ el.style.height = 'auto';
1027
+ el.style.height = Math.min(el.scrollHeight, 160) + 'px';
1028
+ }, [draft]);
1029
+
1030
+ React.useEffect(() => {
1031
+ return () => {
1032
+ if (abortRef.current) {
1033
+ abortRef.current.abort();
1034
+ abortRef.current = null;
1035
+ }
1036
+ };
1037
+ }, []);
1038
+
1039
+ function showNotice(text, isError) {
1040
+ const entry = { text, isError: Boolean(isError) };
1041
+ setNotice(entry);
1042
+ window.setTimeout(() => {
1043
+ setNotice((curr) => (curr === entry ? null : curr));
1044
+ }, 2400);
1045
+ }
1046
+
1047
+ async function sendToMainChat(text) {
1048
+ const trimmed = text.trim();
1049
+ if (!trimmed) return;
1050
+ if (!sessionId) {
1051
+ showNotice(t('error.noSession'), true);
1052
+ return;
1053
+ }
1054
+ const promptFn = ctx.remote?.session?.prompt;
1055
+ if (typeof promptFn !== 'function') {
1056
+ showNotice(t('error.sendFailed'), true);
1057
+ return;
1058
+ }
1059
+ try {
1060
+ await promptFn({
1061
+ requestId: makeId(),
1062
+ sessionId,
1063
+ mode: isMainRunning ? 'steer' : 'queue',
1064
+ content: [{ type: 'text', text: trimmed }],
1065
+ });
1066
+ showNotice(t('sentToMain'), false);
1067
+ } catch (err) {
1068
+ const msg = err instanceof Error ? err.message : String(err);
1069
+ showNotice(msg || t('error.sendFailed'), true);
1070
+ }
1071
+ }
1072
+
1073
+ async function handleSubmit(overrideText) {
1074
+ const text = (typeof overrideText === 'string' ? overrideText : draft).trim();
1075
+ const activeQuotes = quotes.slice();
1076
+ if ((!text && activeQuotes.length === 0) || streaming) return;
1077
+
1078
+ if (mode === 'main') {
1079
+ const combined =
1080
+ activeQuotes.length > 0
1081
+ ? activeQuotes.map((q) => '> ' + q.replace(/\n/g, '\n> ')).join('\n\n') +
1082
+ (text ? '\n\n' + text : '')
1083
+ : text;
1084
+ setDraft('');
1085
+ clearQuotes();
1086
+ await sendToMainChat(combined);
1087
+ return;
1088
+ }
1089
+
1090
+ if (!overrideText) setDraft('');
1091
+ clearQuotes();
1092
+ setShowQuotePreview(false);
1093
+
1094
+ const userMsg = {
1095
+ id: makeId(),
1096
+ role: 'user',
1097
+ text: text || activeQuotes[0],
1098
+ quotes: text ? activeQuotes : [],
1099
+ };
1100
+ const assistantId = makeId();
1101
+ const assistantMsg = { id: assistantId, role: 'assistant', text: '' };
1102
+
1103
+ const priorHistory = messages
1104
+ .filter((m) => !m.error && m.text)
1105
+ .map((m) => ({
1106
+ role: m.role,
1107
+ text:
1108
+ m.quotes && m.quotes.length > 0
1109
+ ? m.quotes.map((q) => '> ' + q).join('\n') + '\n\n' + m.text
1110
+ : m.text,
1111
+ }));
1112
+
1113
+ setMessages((prev) => [...prev, userMsg, assistantMsg]);
1114
+ setStreaming(true);
1115
+
1116
+ const controller = new AbortController();
1117
+ abortRef.current = controller;
1118
+
1119
+ try {
1120
+ const res = await fetch('/api/marginalia/ask', {
1121
+ method: 'POST',
1122
+ credentials: 'same-origin',
1123
+ headers: { 'Content-Type': 'application/json' },
1124
+ body: JSON.stringify({
1125
+ sessionId: sessionId || '',
1126
+ question: text,
1127
+ quotes: activeQuotes,
1128
+ includeContext,
1129
+ history: priorHistory,
1130
+ }),
1131
+ signal: controller.signal,
1132
+ });
1133
+
1134
+ if (!res.ok || !res.body) {
1135
+ let errMsg = t('error.sendFailed');
1136
+ try {
1137
+ const errJson = await res.json();
1138
+ if (errJson?.error) errMsg = errJson.error;
1139
+ } catch {
1140
+ // Ignore JSON parse failure.
1141
+ }
1142
+ setMessages((prev) =>
1143
+ prev.map((m) => (m.id === assistantId ? { ...m, text: errMsg, error: true } : m)),
1144
+ );
1145
+ return;
1146
+ }
1147
+
1148
+ const reader = res.body.getReader();
1149
+ const decoder = new TextDecoder();
1150
+ let buffer = '';
1151
+ let modelLabel = '';
1152
+
1153
+ while (true) {
1154
+ const { done, value } = await reader.read();
1155
+ if (done) break;
1156
+ buffer += decoder.decode(value, { stream: true });
1157
+ const frames = buffer.split('\n\n');
1158
+ buffer = frames.pop() || '';
1159
+ for (const frame of frames) {
1160
+ const line = frame.trim();
1161
+ if (!line.startsWith('data:')) continue;
1162
+ const jsonText = line.slice(5).trim();
1163
+ if (!jsonText) continue;
1164
+ let ev;
1165
+ try {
1166
+ ev = JSON.parse(jsonText);
1167
+ } catch {
1168
+ continue;
1169
+ }
1170
+ if (ev.type === 'meta' && ev.model) {
1171
+ modelLabel = ev.model;
1172
+ } else if (ev.type === 'delta' && ev.text) {
1173
+ setMessages((prev) =>
1174
+ prev.map((m) =>
1175
+ m.id === assistantId
1176
+ ? { ...m, text: m.text + ev.text, model: modelLabel || m.model }
1177
+ : m,
1178
+ ),
1179
+ );
1180
+ } else if (ev.type === 'error') {
1181
+ setMessages((prev) =>
1182
+ prev.map((m) =>
1183
+ m.id === assistantId
1184
+ ? { ...m, text: ev.message || t('error.sendFailed'), error: true }
1185
+ : m,
1186
+ ),
1187
+ );
1188
+ }
1189
+ }
1190
+ }
1191
+ } catch (err) {
1192
+ if (!controller.signal.aborted) {
1193
+ const msg = err instanceof Error ? err.message : String(err);
1194
+ setMessages((prev) =>
1195
+ prev.map((m) =>
1196
+ m.id === assistantId
1197
+ ? { ...m, text: msg || t('error.sendFailed'), error: true }
1198
+ : m,
1199
+ ),
1200
+ );
1201
+ }
1202
+ } finally {
1203
+ abortRef.current = null;
1204
+ setStreaming(false);
1205
+ setMessages((prev) => prev.filter((m) => !(m.id === assistantId && !m.text)));
1206
+ }
1207
+ }
1208
+
1209
+ function handleStop() {
1210
+ if (abortRef.current) {
1211
+ abortRef.current.abort();
1212
+ abortRef.current = null;
1213
+ }
1214
+ setStreaming(false);
1215
+ setMessages((prev) => prev.filter((m) => !(m.role === 'assistant' && !m.text)));
1216
+ }
1217
+
1218
+ function handleCopy(msg) {
1219
+ if (!msg?.text || !navigator.clipboard) return;
1220
+ navigator.clipboard
1221
+ .writeText(msg.text)
1222
+ .then(() => {
1223
+ setCopiedId(msg.id);
1224
+ window.setTimeout(() => {
1225
+ setCopiedId((curr) => (curr === msg.id ? null : curr));
1226
+ }, 1600);
1227
+ })
1228
+ .catch(() => {});
1229
+ }
1230
+
1231
+ const chips = [t('chip.summarize'), t('chip.explain'), t('chip.next')];
1232
+ const quoteLabel = (
1233
+ quotes.length === 1 ? t('quote.count') : t('quote.countPlural')
1234
+ ).replace('{n}', String(quotes.length));
1235
+
1236
+ return h(
1237
+ 'div',
1238
+ { className: 'mg-root', 'data-marginalia-root': 'true' },
1239
+ h(
1240
+ 'div',
1241
+ { className: 'mg-toolbar' },
1242
+ h(
1243
+ 'div',
1244
+ { className: 'mg-seg', role: 'tablist' },
1245
+ h(
1246
+ 'button',
1247
+ {
1248
+ type: 'button',
1249
+ role: 'tab',
1250
+ 'aria-selected': mode === 'side',
1251
+ className: 'mg-seg-btn' + (mode === 'side' ? ' is-active' : ''),
1252
+ onClick: () => setMode('side'),
1253
+ },
1254
+ t('mode.side'),
1255
+ ),
1256
+ h(
1257
+ 'button',
1258
+ {
1259
+ type: 'button',
1260
+ role: 'tab',
1261
+ 'aria-selected': mode === 'main',
1262
+ className: 'mg-seg-btn' + (mode === 'main' ? ' is-active' : ''),
1263
+ onClick: () => setMode('main'),
1264
+ },
1265
+ t('mode.main'),
1266
+ ),
1267
+ ),
1268
+ h(
1269
+ 'div',
1270
+ { className: 'mg-toolbar-right' },
1271
+ mode === 'side'
1272
+ ? h(
1273
+ 'button',
1274
+ {
1275
+ type: 'button',
1276
+ className: 'mg-pill-btn' + (includeContext ? ' is-on' : ''),
1277
+ onClick: () => setIncludeContext((v) => !v),
1278
+ },
1279
+ includeContext ? t('context.on') : t('context.off'),
1280
+ )
1281
+ : null,
1282
+ messages.length > 0 && !streaming
1283
+ ? h(
1284
+ 'button',
1285
+ {
1286
+ type: 'button',
1287
+ className: 'mg-pill-btn',
1288
+ onClick: () => {
1289
+ setMessages([]);
1290
+ saveStoredMessages(sessionId, []);
1291
+ },
1292
+ },
1293
+ t('newChat'),
1294
+ )
1295
+ : null,
1296
+ ),
1297
+ ),
1298
+ h(
1299
+ 'div',
1300
+ { className: 'mg-scroll', ref: scrollRef },
1301
+ messages.length === 0
1302
+ ? h(
1303
+ 'div',
1304
+ { className: 'mg-empty' },
1305
+ h('div', { className: 'mg-empty-icon' }, h(MarginaliaGlyph, { size: 20 })),
1306
+ h('div', { className: 'mg-empty-title' }, t('empty.title')),
1307
+ h(
1308
+ 'div',
1309
+ { className: 'mg-empty-sub' },
1310
+ mode === 'side' ? t('empty.subtitle.side') : t('empty.subtitle.main'),
1311
+ ),
1312
+ mode === 'side'
1313
+ ? h(
1314
+ 'div',
1315
+ { className: 'mg-chips' },
1316
+ chips.map((chip) =>
1317
+ h(
1318
+ 'button',
1319
+ {
1320
+ key: chip,
1321
+ type: 'button',
1322
+ className: 'mg-chip',
1323
+ onClick: () => handleSubmit(chip),
1324
+ },
1325
+ chip,
1326
+ ),
1327
+ ),
1328
+ )
1329
+ : null,
1330
+ )
1331
+ : messages.map((msg) =>
1332
+ msg.role === 'user'
1333
+ ? h(
1334
+ 'div',
1335
+ { key: msg.id, className: 'mg-msg is-user' },
1336
+ msg.quotes && msg.quotes.length > 0
1337
+ ? h(
1338
+ 'div',
1339
+ { className: 'mg-user-quotes' },
1340
+ h(
1341
+ 'span',
1342
+ { className: 'mg-quote-chip' },
1343
+ (msg.quotes.length === 1 ? t('quote.count') : t('quote.countPlural')).replace(
1344
+ '{n}',
1345
+ String(msg.quotes.length),
1346
+ ),
1347
+ ),
1348
+ )
1349
+ : null,
1350
+ h('div', { className: 'mg-user-bubble' }, msg.text),
1351
+ )
1352
+ : h(
1353
+ 'div',
1354
+ { key: msg.id, className: 'mg-msg is-assistant' },
1355
+ msg.text
1356
+ ? h(
1357
+ 'div',
1358
+ { className: 'mg-assistant-body' + (msg.error ? ' is-error' : '') },
1359
+ msg.error
1360
+ ? msg.text
1361
+ : h(MarkdownBlock, {
1362
+ text: msg.text,
1363
+ copyLabel: t('copy'),
1364
+ copiedLabel: t('copied'),
1365
+ }),
1366
+ )
1367
+ : h(
1368
+ 'div',
1369
+ { className: 'mg-thinking' },
1370
+ h('span', { className: 'mg-dot' }),
1371
+ h('span', null, t('thinking')),
1372
+ ),
1373
+ msg.text
1374
+ ? h(
1375
+ 'div',
1376
+ { className: 'mg-msg-meta' },
1377
+ msg.model ? h('span', null, msg.model) : null,
1378
+ h(
1379
+ 'button',
1380
+ {
1381
+ type: 'button',
1382
+ className: 'mg-action-link',
1383
+ onClick: () => handleCopy(msg),
1384
+ },
1385
+ copiedId === msg.id ? t('copied') : t('copy'),
1386
+ ),
1387
+ !msg.error
1388
+ ? h(
1389
+ 'button',
1390
+ {
1391
+ type: 'button',
1392
+ className: 'mg-action-link',
1393
+ onClick: () => sendToMainChat(msg.text),
1394
+ },
1395
+ t('promote'),
1396
+ )
1397
+ : null,
1398
+ )
1399
+ : null,
1400
+ ),
1401
+ ),
1402
+ ),
1403
+ notice
1404
+ ? h('div', { className: 'mg-notice' + (notice.isError ? ' is-error' : '') }, notice.text)
1405
+ : null,
1406
+ h(
1407
+ 'div',
1408
+ { className: 'mg-composer' },
1409
+ h(
1410
+ 'div',
1411
+ { className: 'mg-input-box' },
1412
+ quotes.length > 0
1413
+ ? h(
1414
+ 'div',
1415
+ { className: 'mg-quote-strip' },
1416
+ h(
1417
+ 'div',
1418
+ {
1419
+ className: 'mg-quote-chip',
1420
+ onClick: () => setShowQuotePreview((v) => !v),
1421
+ },
1422
+ h('span', null, quoteLabel),
1423
+ h(
1424
+ 'button',
1425
+ {
1426
+ type: 'button',
1427
+ className: 'mg-quote-x',
1428
+ 'aria-label': 'Clear',
1429
+ onClick: (e) => {
1430
+ e.stopPropagation();
1431
+ clearQuotes();
1432
+ setShowQuotePreview(false);
1433
+ },
1434
+ },
1435
+ '×',
1436
+ ),
1437
+ ),
1438
+ showQuotePreview
1439
+ ? quotes.map((q, idx) =>
1440
+ h(
1441
+ 'div',
1442
+ { key: idx, className: 'mg-quote-preview' },
1443
+ q,
1444
+ quotes.length > 1
1445
+ ? h(
1446
+ 'button',
1447
+ {
1448
+ type: 'button',
1449
+ className: 'mg-quote-x',
1450
+ onClick: () => removeQuoteAt(idx),
1451
+ },
1452
+ ' ×',
1453
+ )
1454
+ : null,
1455
+ ),
1456
+ )
1457
+ : null,
1458
+ )
1459
+ : null,
1460
+ h('textarea', {
1461
+ ref: textareaRef,
1462
+ 'data-marginalia-input': 'true',
1463
+ className: 'mg-textarea',
1464
+ rows: 1,
1465
+ value: draft,
1466
+ placeholder: mode === 'side' ? t('placeholder.side') : t('placeholder.main'),
1467
+ onChange: (e) => setDraft(e.target.value),
1468
+ onKeyDown: (e) => {
1469
+ if (e.nativeEvent?.isComposing || e.isComposing) return;
1470
+ if (e.key === 'Enter' && !e.shiftKey) {
1471
+ e.preventDefault();
1472
+ handleSubmit();
1473
+ }
1474
+ },
1475
+ }),
1476
+ h(
1477
+ 'div',
1478
+ { className: 'mg-composer-foot' },
1479
+ h(
1480
+ 'span',
1481
+ { className: 'mg-composer-tag' },
1482
+ mode === 'side'
1483
+ ? includeContext
1484
+ ? t('context.on')
1485
+ : t('context.off')
1486
+ : t('mode.main'),
1487
+ ),
1488
+ streaming
1489
+ ? h(
1490
+ 'button',
1491
+ {
1492
+ type: 'button',
1493
+ className: 'mg-circle-btn is-stop',
1494
+ title: t('stop'),
1495
+ 'aria-label': t('stop'),
1496
+ onClick: handleStop,
1497
+ },
1498
+ h(
1499
+ 'svg',
1500
+ { width: 12, height: 12, viewBox: '0 0 12 12', fill: 'currentColor' },
1501
+ h('rect', { x: 2, y: 2, width: 8, height: 8, rx: 1.5 }),
1502
+ ),
1503
+ )
1504
+ : h(
1505
+ 'button',
1506
+ {
1507
+ type: 'button',
1508
+ className: 'mg-circle-btn',
1509
+ title: t('send'),
1510
+ 'aria-label': t('send'),
1511
+ disabled: !draft.trim() && quotes.length === 0,
1512
+ onClick: () => handleSubmit(),
1513
+ },
1514
+ h(
1515
+ 'svg',
1516
+ {
1517
+ width: 15,
1518
+ height: 15,
1519
+ viewBox: '0 0 24 24',
1520
+ fill: 'none',
1521
+ stroke: 'currentColor',
1522
+ strokeWidth: 2.3,
1523
+ strokeLinecap: 'round',
1524
+ strokeLinejoin: 'round',
1525
+ },
1526
+ h('path', { d: 'M12 19V5M5 12l7-7 7 7' }),
1527
+ ),
1528
+ ),
1529
+ ),
1530
+ ),
1531
+ ),
1532
+ );
1533
+ }
1534
+
1535
+ ctx.slots.inject('sidebar.right.pane.tab', () =>
1536
+ ctx.slots.register(
1537
+ {
1538
+ name: 'sidebar.right.pane.tab',
1539
+ key: PLUGIN_ID,
1540
+ locale: 'marginalia',
1541
+ },
1542
+ MarginaliaBody,
1543
+ ),
1544
+ );
1545
+
1546
+ ctx.slots.inject('conversation.session.header.utilities', () =>
1547
+ ctx.slots.register(
1548
+ {
1549
+ name: 'conversation.session.header.utilities',
1550
+ id: 'marginalia-trigger',
1551
+ order: 20,
1552
+ label: () => t('header.tooltip'),
1553
+ },
1554
+ HeaderTrigger,
1555
+ ),
1556
+ );
1557
+
1558
+ ctx.slots.inject('shell.overlay', () =>
1559
+ ctx.slots.register(
1560
+ {
1561
+ name: 'shell.overlay',
1562
+ id: 'marginalia-selection-bar',
1563
+ order: 50,
1564
+ },
1565
+ SelectionFloatingBar,
1566
+ ),
1567
+ );
1568
+ },
1569
+ };
1570
+ },
1571
+ });