dsh-plugin-marginalia 0.2.1 → 0.3.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.
Files changed (3) hide show
  1. package/client.js +191 -1181
  2. package/index.js +2 -270
  3. package/package.json +2 -1
package/client.js CHANGED
@@ -6,75 +6,34 @@ window.__ModuleLoader__.load({
6
6
 
7
7
  const PLUGIN_ID = 'dsh-plugin-marginalia';
8
8
  const TAB_KIND = 'marginalia';
9
- const STORAGE_PREFIX = 'dsh.marginalia.v2.';
10
- const MAX_STORED_MESSAGES = 40;
9
+ const SIDE_SESSION_PREFIX = 'dsh.marginalia.side.v1.';
11
10
 
12
11
  const en = {
13
- 'tab.title': 'Marginalia',
12
+ 'tab.title': 'Side Chat',
14
13
  'guide.title': 'Marginalia',
15
- 'guide.description': 'Select text or ask side-channel questions about the main chat',
16
- 'header.tooltip': 'Ask Marginalia (Side Chat)',
14
+ 'guide.description': 'Open a full native side conversation in the right sidebar',
15
+ 'header.tooltip': 'Open Side Chat (Marginalia)',
17
16
  'sel.addToChat': 'Add to chat',
18
17
  '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',
18
+ 'bar.label': 'Side Chat · Inherits main context',
23
19
  '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',
20
+ 'loading': 'Starting side chat…',
21
+ 'error.prefix': 'Unable to start side chat: ',
22
+ 'retry': 'Retry',
44
23
  };
45
24
 
46
25
  const zh = {
47
- 'tab.title': '旁注提问',
48
- 'guide.title': '旁注提问 Marginalia',
49
- 'guide.description': '划词或直接在右侧边栏向主对话提问,不打断主流程',
50
- 'header.tooltip': '打开旁注提问 (Marginalia)',
26
+ 'tab.title': '旁注对话',
27
+ 'guide.title': '旁注对话 Marginalia',
28
+ 'guide.description': '在右侧边栏开启原生级完整子对话(支持文件、技能、模型与权限)',
29
+ 'header.tooltip': '打开旁注对话 (Marginalia)',
51
30
  'sel.addToChat': '添加到对话',
52
31
  'sel.askSide': '在侧边聊天中提问',
53
- 'mode.side': '旁注提问',
54
- 'mode.main': '直发主对话',
55
- 'context.on': '携带主对话上下文',
56
- 'context.off': '独立提问',
32
+ 'bar.label': '旁注对话 · 已继承主对话上下文',
57
33
  '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': '发送失败',
34
+ 'loading': '正在开启旁注对话…',
35
+ 'error.prefix': '无法开启旁注对话:',
36
+ 'retry': '重试',
78
37
  };
79
38
 
80
39
  const CSS = `
@@ -131,411 +90,68 @@ window.__ModuleLoader__.load({
131
90
  background: var(--dsw-alias-border-l1);
132
91
  margin: 0 1px;
133
92
  }
134
- .mg-root {
93
+ .mg-native-wrap {
135
94
  display: flex;
136
95
  flex-direction: column;
137
96
  height: 100%;
138
97
  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;
98
+ width: 100%;
143
99
  }
144
- .mg-toolbar {
100
+ .mg-native-bar {
145
101
  display: flex;
146
102
  align-items: center;
147
103
  justify-content: space-between;
148
104
  gap: 8px;
149
- padding: 8px 14px;
105
+ padding: 6px 12px;
150
106
  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;
107
+ font-size: 12px;
162
108
  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;
109
+ flex-shrink: 0;
169
110
  }
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;
111
+ .mg-native-label {
112
+ overflow: hidden;
113
+ text-overflow: ellipsis;
114
+ white-space: nowrap;
179
115
  }
180
- .mg-pill-btn {
181
- display: inline-flex;
182
- align-items: center;
183
- gap: 4px;
116
+ .mg-native-btn {
184
117
  border: 1px solid var(--dsw-alias-border-l1);
185
118
  background: transparent;
186
- color: var(--dsw-alias-label-secondary);
187
- font-size: 12px;
119
+ color: var(--dsw-alias-label-primary);
120
+ font-size: 11.5px;
121
+ font-weight: 500;
188
122
  padding: 3px 9px;
189
123
  border-radius: 999px;
190
124
  cursor: pointer;
191
- transition: border-color 0.15s ease, color 0.15s ease, background-color 0.15s ease;
125
+ white-space: nowrap;
126
+ transition: background-color 0.15s ease, border-color 0.15s ease;
192
127
  }
193
- .mg-pill-btn:hover {
128
+ .mg-native-btn:hover {
194
129
  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);
130
+ border-color: var(--dsw-alias-border-l2);
200
131
  }
201
- .mg-scroll {
132
+ .mg-native-conv {
202
133
  flex: 1;
203
134
  min-height: 0;
204
- overflow-y: auto;
205
- padding: 16px 16px 12px;
206
135
  display: flex;
207
136
  flex-direction: column;
208
- gap: 18px;
209
137
  }
210
- .mg-empty {
211
- margin: auto 0;
212
- padding: 24px 12px;
138
+ .mg-state {
139
+ margin: auto;
140
+ padding: 24px 16px;
213
141
  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
142
  color: var(--dsw-alias-label-secondary);
375
143
  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
144
  display: flex;
145
+ flex-direction: column;
390
146
  align-items: center;
391
147
  gap: 10px;
392
- font-size: 12px;
393
- color: var(--dsw-alias-label-secondary);
394
- padding: 2px 0;
395
148
  }
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 {
149
+ .mg-state-error {
422
150
  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
151
  }
532
152
  .mg-header-btn:focus-visible,
533
153
  .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 {
154
+ .mg-native-btn:focus-visible {
539
155
  outline: 2px solid var(--dsw-alias-brand-primary);
540
156
  outline-offset: 1px;
541
157
  }
@@ -565,240 +181,62 @@ window.__ModuleLoader__.load({
565
181
  );
566
182
  }
567
183
 
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);
184
+ function insertTextIntoComposer(editorEl, text) {
185
+ if (!editorEl || !text) return false;
186
+ editorEl.focus();
187
+ try {
188
+ const dt = new DataTransfer();
189
+ dt.setData('text/plain', text);
190
+ const pasteEv = new ClipboardEvent('paste', {
191
+ clipboardData: dt,
192
+ bubbles: true,
193
+ cancelable: true,
194
+ });
195
+ editorEl.dispatchEvent(pasteEv);
196
+ return true;
197
+ } catch {
198
+ try {
199
+ document.execCommand('insertText', false, text);
200
+ return true;
201
+ } catch {
202
+ return false;
734
203
  }
735
- flushPara();
736
- flushList();
737
204
  }
738
-
739
- return h('div', { className: 'mg-md' }, elements);
740
205
  }
741
206
 
742
- function loadStoredMessages(sessionId) {
743
- if (!sessionId) return [];
207
+ function getStoredSideSession(mainSessionId) {
208
+ if (!mainSessionId) return null;
744
209
  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 : [];
210
+ return window.localStorage.getItem(SIDE_SESSION_PREFIX + mainSessionId);
749
211
  } catch {
750
- return [];
212
+ return null;
751
213
  }
752
214
  }
753
215
 
754
- function saveStoredMessages(sessionId, messages) {
755
- if (!sessionId) return;
216
+ function setStoredSideSession(mainSessionId, sideSessionId) {
217
+ if (!mainSessionId) return;
756
218
  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));
219
+ if (sideSessionId) {
220
+ window.localStorage.setItem(SIDE_SESSION_PREFIX + mainSessionId, sideSessionId);
221
+ } else {
222
+ window.localStorage.removeItem(SIDE_SESSION_PREFIX + mainSessionId);
223
+ }
766
224
  } catch {
767
- // Ignore storage quota errors.
225
+ // Ignore storage errors.
768
226
  }
769
227
  }
770
228
 
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
229
  return {
779
- inject: ['slots', 'locale', 'sidebarRight', 'sidebarRightTabs', 'remote', 'uiSession'],
230
+ inject: ['slots', 'locale', 'sidebarRight', 'sidebarRightTabs', 'remote', 'sessions', 'uiSession'],
780
231
  apply(ctx) {
781
232
  ctx.effect(() => ctx.locale.register('marginalia', { en, zh }), 'marginalia: locale');
782
233
  const t = ctx.locale.bind('marginalia');
783
234
 
784
- // Shared quote bus so selecting text in the main chat immediately populates the side chat.
785
- let pendingQuotes = [];
235
+ let pendingQuote = '';
786
236
  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);
237
+ function queueQuote(text) {
238
+ pendingQuote = text;
239
+ for (const fn of quoteListeners) fn(text);
802
240
  }
803
241
 
804
242
  ctx.effect(() => {
@@ -890,8 +328,6 @@ window.__ModuleLoader__.load({
890
328
 
891
329
  if (!sel) return null;
892
330
 
893
- const currentSessionId = ctx.uiSession?.adapter?.current?.getSnapshot()?.key;
894
-
895
331
  return h(
896
332
  'div',
897
333
  {
@@ -906,20 +342,10 @@ window.__ModuleLoader__.load({
906
342
  className: 'mg-sel-btn',
907
343
  onClick: () => {
908
344
  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
- }
345
+ const editors = Array.from(document.querySelectorAll('[contenteditable="true"]'));
346
+ const mainEditor = editors.find((el) => !el.closest('[data-marginalia-root]'));
347
+ if (!insertTextIntoComposer(mainEditor, quoted)) {
348
+ navigator.clipboard?.writeText(quoted).catch(() => {});
923
349
  }
924
350
  window.getSelection()?.removeAllRanges();
925
351
  setSel(null);
@@ -934,7 +360,7 @@ window.__ModuleLoader__.load({
934
360
  type: 'button',
935
361
  className: 'mg-sel-btn',
936
362
  onClick: () => {
937
- pushQuote(sel.text);
363
+ queueQuote(sel.text);
938
364
  window.getSelection()?.removeAllRanges();
939
365
  setSel(null);
940
366
  ctx.sidebarRight.openTab(TAB_KIND);
@@ -965,570 +391,153 @@ window.__ModuleLoader__.load({
965
391
  }
966
392
 
967
393
  function MarginaliaBody(props) {
968
- const sessionId = props?.sessionId;
969
- const isMainRunning =
970
- typeof props?.useSessionStatus === 'function'
971
- ? Boolean(props.useSessionStatus((s) => Boolean(s?.running)))
972
- : false;
394
+ const mainSessionId = props?.sessionId;
395
+ const SessionProvider = props?.SessionProvider;
396
+ const renderSlot = props?.renderSlot;
973
397
 
974
398
  const [, setLocaleTick] = React.useState(0);
975
399
  React.useEffect(() => ctx.locale.subscribe(() => setLocaleTick((v) => v + 1)), []);
976
400
 
977
- const [mode, setMode] = React.useState('side');
978
- const [includeContext, setIncludeContext] = React.useState(true);
979
- const [messages, setMessages] = React.useState(() => loadStoredMessages(sessionId));
980
- const [quotes, setQuotes] = React.useState(() => pendingQuotes);
981
- const [showQuotePreview, setShowQuotePreview] = React.useState(false);
982
- const [draft, setDraft] = React.useState('');
983
- const [streaming, setStreaming] = React.useState(false);
984
- const [copiedId, setCopiedId] = React.useState(null);
985
- const [notice, setNotice] = React.useState(null);
986
-
987
- const abortRef = React.useRef(null);
988
- const scrollRef = React.useRef(null);
989
- const textareaRef = React.useRef(null);
990
-
991
- React.useEffect(() => {
992
- const listener = (nextQuotes) => {
993
- setQuotes(nextQuotes);
994
- if (nextQuotes.length > 0) {
995
- setMode('side');
996
- window.setTimeout(() => textareaRef.current?.focus(), 40);
401
+ const [sideRef, setSideRef] = React.useState(null);
402
+ const [errorMsg, setErrorMsg] = React.useState('');
403
+ const [retryNonce, setRetryNonce] = React.useState(0);
404
+ const rootRef = React.useRef(null);
405
+
406
+ const flushPendingQuote = React.useCallback(() => {
407
+ if (!pendingQuote || !rootRef.current) return;
408
+ const text = pendingQuote;
409
+ let attempts = 0;
410
+ const tryInsert = () => {
411
+ const editor = rootRef.current?.querySelector('[contenteditable="true"]');
412
+ if (editor) {
413
+ pendingQuote = '';
414
+ const quoted = '> ' + text.replace(/\n/g, '\n> ') + '\n\n';
415
+ insertTextIntoComposer(editor, quoted);
416
+ return;
417
+ }
418
+ if (++attempts < 20) {
419
+ window.setTimeout(tryInsert, 80);
997
420
  }
998
421
  };
999
- quoteListeners.add(listener);
1000
- return () => quoteListeners.delete(listener);
422
+ window.setTimeout(tryInsert, 60);
1001
423
  }, []);
1002
424
 
1003
425
  React.useEffect(() => {
1004
- if (abortRef.current) {
1005
- abortRef.current.abort();
1006
- abortRef.current = null;
1007
- }
1008
- setStreaming(false);
1009
- setMessages(loadStoredMessages(sessionId));
1010
- }, [sessionId]);
1011
-
1012
- React.useEffect(() => {
1013
- if (!streaming) {
1014
- saveStoredMessages(sessionId, messages);
1015
- }
1016
- }, [sessionId, messages, streaming]);
426
+ const onQuote = () => {
427
+ if (sideRef) flushPendingQuote();
428
+ };
429
+ quoteListeners.add(onQuote);
430
+ return () => quoteListeners.delete(onQuote);
431
+ }, [sideRef, flushPendingQuote]);
1017
432
 
1018
433
  React.useEffect(() => {
1019
- if (scrollRef.current) {
1020
- scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
1021
- }
1022
- }, [messages, streaming]);
434
+ if (sideRef) flushPendingQuote();
435
+ }, [sideRef, flushPendingQuote]);
1023
436
 
1024
437
  React.useEffect(() => {
1025
- const el = textareaRef.current;
1026
- if (!el) return;
1027
- el.style.height = 'auto';
1028
- el.style.height = Math.min(el.scrollHeight, 160) + 'px';
1029
- }, [draft]);
438
+ if (!mainSessionId) return;
439
+ const ac = new AbortController();
440
+ let activeRef = null;
441
+
442
+ const ensureSideSession = async () => {
443
+ setErrorMsg('');
444
+ setSideRef(null);
445
+ try {
446
+ const listSnap = ctx.sessions.list.getSnapshot();
447
+ let sideId = getStoredSideSession(mainSessionId);
448
+ if (sideId && !listSnap.byId[sideId]) {
449
+ sideId = null;
450
+ }
451
+ if (!sideId) {
452
+ const mainSummary = listSnap.byId[mainSessionId];
453
+ if (mainSummary && !mainSummary.blank && typeof ctx.remote?.session?.fork === 'function') {
454
+ const forked = await ctx.remote.session.fork({ sessionId: mainSessionId });
455
+ sideId = forked?.sessionId;
456
+ } else if (typeof ctx.remote?.session?.create === 'function') {
457
+ const created = await ctx.remote.session.create({
458
+ cwd: mainSummary?.cwd,
459
+ });
460
+ sideId = created?.sessionId;
461
+ }
462
+ if (sideId) {
463
+ setStoredSideSession(mainSessionId, sideId);
464
+ }
465
+ }
466
+ if (!sideId || ac.signal.aborted) return;
1030
467
 
1031
- React.useEffect(() => {
1032
- return () => {
1033
- if (abortRef.current) {
1034
- abortRef.current.abort();
1035
- abortRef.current = null;
468
+ activeRef = ctx.sessions.retain(
469
+ { kind: 'session', sessionId: sideId },
470
+ { source: 'sidebarChat', signal: ac.signal },
471
+ );
472
+ setSideRef(activeRef);
473
+ } catch (err) {
474
+ if (!ac.signal.aborted) {
475
+ setErrorMsg(err instanceof Error ? err.message : String(err));
476
+ }
1036
477
  }
1037
478
  };
1038
- }, []);
1039
-
1040
- function showNotice(text, isError) {
1041
- const entry = { text, isError: Boolean(isError) };
1042
- setNotice(entry);
1043
- window.setTimeout(() => {
1044
- setNotice((curr) => (curr === entry ? null : curr));
1045
- }, 2400);
1046
- }
1047
-
1048
- async function sendToMainChat(text) {
1049
- const trimmed = text.trim();
1050
- if (!trimmed) return;
1051
- if (!sessionId) {
1052
- showNotice(t('error.noSession'), true);
1053
- return;
1054
- }
1055
- const promptFn = ctx.remote?.session?.prompt;
1056
- if (typeof promptFn !== 'function') {
1057
- showNotice(t('error.sendFailed'), true);
1058
- return;
1059
- }
1060
- try {
1061
- await promptFn({
1062
- requestId: makeId(),
1063
- sessionId,
1064
- mode: isMainRunning ? 'steer' : 'queue',
1065
- content: [{ type: 'text', text: trimmed }],
1066
- });
1067
- showNotice(t('sentToMain'), false);
1068
- } catch (err) {
1069
- const msg = err instanceof Error ? err.message : String(err);
1070
- showNotice(msg || t('error.sendFailed'), true);
1071
- }
1072
- }
1073
-
1074
- async function handleSubmit(overrideText) {
1075
- const text = (typeof overrideText === 'string' ? overrideText : draft).trim();
1076
- const activeQuotes = quotes.slice();
1077
- if ((!text && activeQuotes.length === 0) || streaming) return;
1078
-
1079
- if (mode === 'main') {
1080
- const combined =
1081
- activeQuotes.length > 0
1082
- ? activeQuotes.map((q) => '> ' + q.replace(/\n/g, '\n> ')).join('\n\n') +
1083
- (text ? '\n\n' + text : '')
1084
- : text;
1085
- setDraft('');
1086
- clearQuotes();
1087
- await sendToMainChat(combined);
1088
- return;
1089
- }
1090
-
1091
- if (!overrideText) setDraft('');
1092
- clearQuotes();
1093
- setShowQuotePreview(false);
1094
-
1095
- const userMsg = {
1096
- id: makeId(),
1097
- role: 'user',
1098
- text: text || activeQuotes[0],
1099
- quotes: text ? activeQuotes : [],
1100
- };
1101
- const assistantId = makeId();
1102
- const assistantMsg = { id: assistantId, role: 'assistant', text: '' };
1103
-
1104
- const priorHistory = messages
1105
- .filter((m) => !m.error && m.text)
1106
- .map((m) => ({
1107
- role: m.role,
1108
- text:
1109
- m.quotes && m.quotes.length > 0
1110
- ? m.quotes.map((q) => '> ' + q).join('\n') + '\n\n' + m.text
1111
- : m.text,
1112
- }));
1113
479
 
1114
- setMessages((prev) => [...prev, userMsg, assistantMsg]);
1115
- setStreaming(true);
1116
-
1117
- const controller = new AbortController();
1118
- abortRef.current = controller;
1119
-
1120
- try {
1121
- const res = await fetch('/api/marginalia/ask', {
1122
- method: 'POST',
1123
- credentials: 'same-origin',
1124
- headers: { 'Content-Type': 'application/json' },
1125
- body: JSON.stringify({
1126
- sessionId: sessionId || '',
1127
- question: text,
1128
- quotes: activeQuotes,
1129
- includeContext,
1130
- history: priorHistory,
1131
- }),
1132
- signal: controller.signal,
1133
- });
1134
-
1135
- if (!res.ok || !res.body) {
1136
- let errMsg = t('error.sendFailed');
480
+ ensureSideSession();
481
+ return () => {
482
+ ac.abort();
483
+ if (activeRef) {
1137
484
  try {
1138
- const errJson = await res.json();
1139
- if (errJson?.error) errMsg = errJson.error;
485
+ activeRef.release();
1140
486
  } catch {
1141
- // Ignore JSON parse failure.
1142
- }
1143
- setMessages((prev) =>
1144
- prev.map((m) => (m.id === assistantId ? { ...m, text: errMsg, error: true } : m)),
1145
- );
1146
- return;
1147
- }
1148
-
1149
- const reader = res.body.getReader();
1150
- const decoder = new TextDecoder();
1151
- let buffer = '';
1152
- let modelLabel = '';
1153
-
1154
- while (true) {
1155
- const { done, value } = await reader.read();
1156
- if (done) break;
1157
- buffer += decoder.decode(value, { stream: true });
1158
- const frames = buffer.split('\n\n');
1159
- buffer = frames.pop() || '';
1160
- for (const frame of frames) {
1161
- const line = frame.trim();
1162
- if (!line.startsWith('data:')) continue;
1163
- const jsonText = line.slice(5).trim();
1164
- if (!jsonText) continue;
1165
- let ev;
1166
- try {
1167
- ev = JSON.parse(jsonText);
1168
- } catch {
1169
- continue;
1170
- }
1171
- if (ev.type === 'meta' && ev.model) {
1172
- modelLabel = ev.model;
1173
- } else if (ev.type === 'delta' && ev.text) {
1174
- setMessages((prev) =>
1175
- prev.map((m) =>
1176
- m.id === assistantId
1177
- ? { ...m, text: m.text + ev.text, model: modelLabel || m.model }
1178
- : m,
1179
- ),
1180
- );
1181
- } else if (ev.type === 'error') {
1182
- setMessages((prev) =>
1183
- prev.map((m) =>
1184
- m.id === assistantId
1185
- ? { ...m, text: ev.message || t('error.sendFailed'), error: true }
1186
- : m,
1187
- ),
1188
- );
1189
- }
487
+ // Ignore release error.
1190
488
  }
1191
489
  }
1192
- } catch (err) {
1193
- if (!controller.signal.aborted) {
1194
- const msg = err instanceof Error ? err.message : String(err);
1195
- setMessages((prev) =>
1196
- prev.map((m) =>
1197
- m.id === assistantId
1198
- ? { ...m, text: msg || t('error.sendFailed'), error: true }
1199
- : m,
1200
- ),
1201
- );
1202
- }
1203
- } finally {
1204
- abortRef.current = null;
1205
- setStreaming(false);
1206
- setMessages((prev) => prev.filter((m) => !(m.id === assistantId && !m.text)));
1207
- }
1208
- }
1209
-
1210
- function handleStop() {
1211
- if (abortRef.current) {
1212
- abortRef.current.abort();
1213
- abortRef.current = null;
1214
- }
1215
- setStreaming(false);
1216
- setMessages((prev) => prev.filter((m) => !(m.role === 'assistant' && !m.text)));
1217
- }
1218
-
1219
- function handleCopy(msg) {
1220
- if (!msg?.text || !navigator.clipboard) return;
1221
- navigator.clipboard
1222
- .writeText(msg.text)
1223
- .then(() => {
1224
- setCopiedId(msg.id);
1225
- window.setTimeout(() => {
1226
- setCopiedId((curr) => (curr === msg.id ? null : curr));
1227
- }, 1600);
1228
- })
1229
- .catch(() => {});
1230
- }
490
+ };
491
+ }, [mainSessionId, retryNonce]);
1231
492
 
1232
- const chips = [t('chip.summarize'), t('chip.explain'), t('chip.next')];
1233
- const quoteLabel = (
1234
- quotes.length === 1 ? t('quote.count') : t('quote.countPlural')
1235
- ).replace('{n}', String(quotes.length));
493
+ const handleNewSideChat = () => {
494
+ if (!mainSessionId) return;
495
+ setStoredSideSession(mainSessionId, null);
496
+ setRetryNonce((n) => n + 1);
497
+ };
1236
498
 
1237
499
  return h(
1238
500
  'div',
1239
- { className: 'mg-root', 'data-marginalia-root': 'true' },
501
+ { className: 'mg-native-wrap', 'data-marginalia-root': 'true', ref: rootRef },
1240
502
  h(
1241
503
  'div',
1242
- { className: 'mg-toolbar' },
1243
- h(
1244
- 'div',
1245
- { className: 'mg-seg', role: 'tablist' },
1246
- h(
1247
- 'button',
1248
- {
1249
- type: 'button',
1250
- role: 'tab',
1251
- 'aria-selected': mode === 'side',
1252
- className: 'mg-seg-btn' + (mode === 'side' ? ' is-active' : ''),
1253
- onClick: () => setMode('side'),
1254
- },
1255
- t('mode.side'),
1256
- ),
1257
- h(
1258
- 'button',
1259
- {
1260
- type: 'button',
1261
- role: 'tab',
1262
- 'aria-selected': mode === 'main',
1263
- className: 'mg-seg-btn' + (mode === 'main' ? ' is-active' : ''),
1264
- onClick: () => setMode('main'),
1265
- },
1266
- t('mode.main'),
1267
- ),
1268
- ),
504
+ { className: 'mg-native-bar' },
505
+ h('span', { className: 'mg-native-label' }, t('bar.label')),
1269
506
  h(
1270
- 'div',
1271
- { className: 'mg-toolbar-right' },
1272
- mode === 'side'
1273
- ? h(
1274
- 'button',
1275
- {
1276
- type: 'button',
1277
- className: 'mg-pill-btn' + (includeContext ? ' is-on' : ''),
1278
- onClick: () => setIncludeContext((v) => !v),
1279
- },
1280
- includeContext ? t('context.on') : t('context.off'),
1281
- )
1282
- : null,
1283
- messages.length > 0 && !streaming
1284
- ? h(
1285
- 'button',
1286
- {
1287
- type: 'button',
1288
- className: 'mg-pill-btn',
1289
- onClick: () => {
1290
- setMessages([]);
1291
- saveStoredMessages(sessionId, []);
1292
- },
1293
- },
1294
- t('newChat'),
1295
- )
1296
- : null,
507
+ 'button',
508
+ {
509
+ type: 'button',
510
+ className: 'mg-native-btn',
511
+ onClick: handleNewSideChat,
512
+ },
513
+ t('newChat'),
1297
514
  ),
1298
515
  ),
1299
516
  h(
1300
517
  'div',
1301
- { className: 'mg-scroll', ref: scrollRef },
1302
- messages.length === 0
518
+ { className: 'mg-native-conv' },
519
+ errorMsg
1303
520
  ? h(
1304
521
  'div',
1305
- { className: 'mg-empty' },
1306
- h('div', { className: 'mg-empty-icon' }, h(MarginaliaGlyph, { size: 20 })),
1307
- h('div', { className: 'mg-empty-title' }, t('empty.title')),
522
+ { className: 'mg-state mg-state-error' },
523
+ h('div', null, t('error.prefix') + errorMsg),
1308
524
  h(
1309
- 'div',
1310
- { className: 'mg-empty-sub' },
1311
- mode === 'side' ? t('empty.subtitle.side') : t('empty.subtitle.main'),
525
+ 'button',
526
+ {
527
+ type: 'button',
528
+ className: 'mg-native-btn',
529
+ onClick: () => setRetryNonce((n) => n + 1),
530
+ },
531
+ t('retry'),
1312
532
  ),
1313
- mode === 'side'
1314
- ? h(
1315
- 'div',
1316
- { className: 'mg-chips' },
1317
- chips.map((chip) =>
1318
- h(
1319
- 'button',
1320
- {
1321
- key: chip,
1322
- type: 'button',
1323
- className: 'mg-chip',
1324
- onClick: () => handleSubmit(chip),
1325
- },
1326
- chip,
1327
- ),
1328
- ),
1329
- )
1330
- : null,
1331
533
  )
1332
- : messages.map((msg) =>
1333
- msg.role === 'user'
1334
- ? h(
1335
- 'div',
1336
- { key: msg.id, className: 'mg-msg is-user' },
1337
- msg.quotes && msg.quotes.length > 0
1338
- ? h(
1339
- 'div',
1340
- { className: 'mg-user-quotes' },
1341
- h(
1342
- 'span',
1343
- { className: 'mg-quote-chip' },
1344
- (msg.quotes.length === 1 ? t('quote.count') : t('quote.countPlural')).replace(
1345
- '{n}',
1346
- String(msg.quotes.length),
1347
- ),
1348
- ),
1349
- )
1350
- : null,
1351
- h('div', { className: 'mg-user-bubble' }, msg.text),
1352
- )
1353
- : h(
1354
- 'div',
1355
- { key: msg.id, className: 'mg-msg is-assistant' },
1356
- msg.text
1357
- ? h(
1358
- 'div',
1359
- { className: 'mg-assistant-body' + (msg.error ? ' is-error' : '') },
1360
- msg.error
1361
- ? msg.text
1362
- : h(MarkdownBlock, {
1363
- text: msg.text,
1364
- copyLabel: t('copy'),
1365
- copiedLabel: t('copied'),
1366
- }),
1367
- )
1368
- : h(
1369
- 'div',
1370
- { className: 'mg-thinking' },
1371
- h('span', { className: 'mg-dot' }),
1372
- h('span', null, t('thinking')),
1373
- ),
1374
- msg.text
1375
- ? h(
1376
- 'div',
1377
- { className: 'mg-msg-meta' },
1378
- msg.model ? h('span', null, msg.model) : null,
1379
- h(
1380
- 'button',
1381
- {
1382
- type: 'button',
1383
- className: 'mg-action-link',
1384
- onClick: () => handleCopy(msg),
1385
- },
1386
- copiedId === msg.id ? t('copied') : t('copy'),
1387
- ),
1388
- !msg.error
1389
- ? h(
1390
- 'button',
1391
- {
1392
- type: 'button',
1393
- className: 'mg-action-link',
1394
- onClick: () => sendToMainChat(msg.text),
1395
- },
1396
- t('promote'),
1397
- )
1398
- : null,
1399
- )
1400
- : null,
1401
- ),
1402
- ),
1403
- ),
1404
- notice
1405
- ? h('div', { className: 'mg-notice' + (notice.isError ? ' is-error' : '') }, notice.text)
1406
- : null,
1407
- h(
1408
- 'div',
1409
- { className: 'mg-composer' },
1410
- h(
1411
- 'div',
1412
- { className: 'mg-input-box' },
1413
- quotes.length > 0
534
+ : sideRef && SessionProvider && typeof renderSlot === 'function'
1414
535
  ? h(
1415
- 'div',
1416
- { className: 'mg-quote-strip' },
1417
- h(
1418
- 'div',
1419
- {
1420
- className: 'mg-quote-chip',
1421
- onClick: () => setShowQuotePreview((v) => !v),
1422
- },
1423
- h('span', null, quoteLabel),
1424
- h(
1425
- 'button',
1426
- {
1427
- type: 'button',
1428
- className: 'mg-quote-x',
1429
- 'aria-label': 'Clear',
1430
- onClick: (e) => {
1431
- e.stopPropagation();
1432
- clearQuotes();
1433
- setShowQuotePreview(false);
1434
- },
1435
- },
1436
- '×',
1437
- ),
1438
- ),
1439
- showQuotePreview
1440
- ? quotes.map((q, idx) =>
1441
- h(
1442
- 'div',
1443
- { key: idx, className: 'mg-quote-preview' },
1444
- q,
1445
- quotes.length > 1
1446
- ? h(
1447
- 'button',
1448
- {
1449
- type: 'button',
1450
- className: 'mg-quote-x',
1451
- onClick: () => removeQuoteAt(idx),
1452
- },
1453
- ' ×',
1454
- )
1455
- : null,
1456
- ),
1457
- )
1458
- : null,
536
+ SessionProvider,
537
+ { session: sideRef },
538
+ renderSlot('sidebar.chat.conversation', {}),
1459
539
  )
1460
- : null,
1461
- h('textarea', {
1462
- ref: textareaRef,
1463
- 'data-marginalia-input': 'true',
1464
- className: 'mg-textarea',
1465
- rows: 1,
1466
- value: draft,
1467
- placeholder: mode === 'side' ? t('placeholder.side') : t('placeholder.main'),
1468
- onChange: (e) => setDraft(e.target.value),
1469
- onKeyDown: (e) => {
1470
- if (e.nativeEvent?.isComposing || e.isComposing) return;
1471
- if (e.key === 'Enter' && !e.shiftKey) {
1472
- e.preventDefault();
1473
- handleSubmit();
1474
- }
1475
- },
1476
- }),
1477
- h(
1478
- 'div',
1479
- { className: 'mg-composer-foot' },
1480
- h(
1481
- 'span',
1482
- { className: 'mg-composer-tag' },
1483
- mode === 'side'
1484
- ? includeContext
1485
- ? t('context.on')
1486
- : t('context.off')
1487
- : t('mode.main'),
1488
- ),
1489
- streaming
1490
- ? h(
1491
- 'button',
1492
- {
1493
- type: 'button',
1494
- className: 'mg-circle-btn is-stop',
1495
- title: t('stop'),
1496
- 'aria-label': t('stop'),
1497
- onClick: handleStop,
1498
- },
1499
- h(
1500
- 'svg',
1501
- { width: 12, height: 12, viewBox: '0 0 12 12', fill: 'currentColor' },
1502
- h('rect', { x: 2, y: 2, width: 8, height: 8, rx: 1.5 }),
1503
- ),
1504
- )
1505
- : h(
1506
- 'button',
1507
- {
1508
- type: 'button',
1509
- className: 'mg-circle-btn',
1510
- title: t('send'),
1511
- 'aria-label': t('send'),
1512
- disabled: !draft.trim() && quotes.length === 0,
1513
- onClick: () => handleSubmit(),
1514
- },
1515
- h(
1516
- 'svg',
1517
- {
1518
- width: 15,
1519
- height: 15,
1520
- viewBox: '0 0 24 24',
1521
- fill: 'none',
1522
- stroke: 'currentColor',
1523
- strokeWidth: 2.3,
1524
- strokeLinecap: 'round',
1525
- strokeLinejoin: 'round',
1526
- },
1527
- h('path', { d: 'M12 19V5M5 12l7-7 7 7' }),
1528
- ),
1529
- ),
1530
- ),
1531
- ),
540
+ : h('div', { className: 'mg-state' }, t('loading')),
1532
541
  ),
1533
542
  );
1534
543
  }
@@ -1539,6 +548,7 @@ window.__ModuleLoader__.load({
1539
548
  name: 'sidebar.right.pane.tab',
1540
549
  key: PLUGIN_ID,
1541
550
  locale: 'marginalia',
551
+ children: { 'sidebar.chat.conversation': { kind: 'single', scope: 'session' } },
1542
552
  },
1543
553
  MarginaliaBody,
1544
554
  ),