dsh-plugin-marginalia 0.2.2 → 0.3.1

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 +189 -1441
  2. package/index.js +2 -282
  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,505 +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: 10px 16px;
282
- border-radius: 18px;
283
- background: var(--dsw-specific-user-bubble, 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: var(--dsh-content-font-size, 14px);
288
- line-height: 1.6;
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: 4px 14px 12px;
427
- background: var(--dsw-alias-bg-base);
428
- }
429
- .mg-input-box {
430
- position: relative;
431
- display: flex;
432
- flex-direction: column;
433
- gap: 10px;
434
- padding: 12px 14px 10px;
435
- border-radius: var(--dsw-radius-panel, 20px);
436
- border: 1px solid var(--dsw-alias-border-l2);
437
- background: var(--dsw-specific-input-major, var(--dsw-alias-bg-layer-1));
438
- box-shadow: var(--dsw-elevation-soft, 0 2px 10px rgba(0, 0, 0, 0.06));
439
- font-size: var(--dsh-content-font-size, 14px);
440
- }
441
- .mg-input-box:focus-within {
442
- border-color: var(--dsw-alias-border-l2);
443
- }
444
- .mg-model-wrap {
445
- position: relative;
446
- display: inline-flex;
447
- align-items: center;
448
- }
449
- .mg-model-btn {
450
- display: inline-flex;
451
- align-items: center;
452
- gap: 5px;
453
- border: none;
454
- background: transparent;
455
- color: var(--dsw-alias-label-secondary);
456
- font-size: 12.5px;
457
- font-weight: 500;
458
- padding: 4px 8px;
459
- border-radius: 8px;
460
- cursor: pointer;
461
- max-width: 190px;
462
- transition: background-color 0.15s ease, color 0.15s ease;
463
- }
464
- .mg-model-btn:hover {
465
- background: var(--dsw-alias-bg-layer-2);
466
- color: var(--dsw-alias-label-primary);
467
- }
468
- .mg-model-name {
469
- overflow: hidden;
470
- text-overflow: ellipsis;
471
- white-space: nowrap;
472
- }
473
- .mg-model-menu {
474
- position: absolute;
475
- right: 0;
476
- bottom: calc(100% + 8px);
477
- width: 260px;
478
- max-height: 320px;
479
- overflow-y: auto;
480
- padding: 6px;
481
- border-radius: 14px;
482
- background: var(--dsw-alias-bg-overlay, var(--dsw-alias-bg-layer-1));
483
- border: 1px solid var(--dsw-alias-border-l1);
484
- box-shadow: 0 10px 30px rgba(0, 0, 0, 0.16);
485
- z-index: 100;
486
- }
487
- .mg-model-group {
488
- padding: 4px 8px 2px;
489
- font-size: 11px;
490
- font-weight: 600;
491
- color: var(--dsw-alias-label-secondary);
492
- text-transform: uppercase;
493
- letter-spacing: 0.03em;
494
- }
495
- .mg-model-item {
496
- width: 100%;
497
- display: flex;
498
- align-items: center;
499
- justify-content: space-between;
500
- gap: 8px;
501
- border: none;
502
- background: transparent;
503
- color: var(--dsw-alias-label-primary);
504
- font-size: 12.5px;
505
- padding: 6px 8px;
506
- border-radius: 8px;
507
- cursor: pointer;
508
- text-align: left;
509
- }
510
- .mg-model-item:hover {
511
- background: var(--dsw-alias-bg-layer-2);
512
- }
513
- .mg-model-item.is-selected {
514
- color: var(--dsw-alias-brand-primary);
515
- font-weight: 600;
516
- }
517
- .mg-effort-row {
518
- display: flex;
519
- flex-wrap: wrap;
520
- gap: 4px;
521
- padding: 4px 8px 6px;
522
- }
523
- .mg-effort-pill {
524
- border: 1px solid var(--dsw-alias-border-l1);
525
- background: transparent;
526
- color: var(--dsw-alias-label-secondary);
527
- font-size: 11px;
528
- padding: 2px 7px;
529
- border-radius: 999px;
530
- cursor: pointer;
531
- }
532
- .mg-effort-pill.is-selected {
533
- border-color: var(--dsw-alias-brand-primary);
534
- color: var(--dsw-alias-brand-primary);
535
- }
536
- .mg-quote-strip {
537
- display: flex;
538
- flex-direction: column;
539
- gap: 6px;
540
- }
541
- .mg-quote-chip {
542
- display: inline-flex;
543
- align-items: center;
544
- gap: 6px;
545
- align-self: flex-start;
546
- padding: 4px 10px;
547
- border-radius: 10px;
548
- background: var(--dsw-alias-bg-layer-2);
549
- border: 1px solid var(--dsw-alias-border-l1);
550
- color: var(--dsw-alias-label-primary);
551
- font-size: 12.5px;
552
- font-weight: 500;
553
- cursor: pointer;
554
- }
555
- .mg-quote-x {
556
- border: none;
557
- background: transparent;
558
- color: var(--dsw-alias-label-secondary);
559
- font-size: 14px;
560
- line-height: 1;
561
- padding: 0 2px;
562
- cursor: pointer;
563
- }
564
- .mg-quote-x:hover {
565
- color: var(--dsw-alias-label-primary);
566
- }
567
- .mg-quote-preview {
568
- padding: 6px 10px;
569
- border-radius: 8px;
570
- background: var(--dsw-alias-bg-base);
571
- border: 1px solid var(--dsw-alias-border-l1);
572
- font-size: 12px;
573
- color: var(--dsw-alias-label-secondary);
574
- max-height: 96px;
575
- overflow-y: auto;
576
- white-space: pre-wrap;
577
- }
578
- .mg-textarea {
579
- width: 100%;
580
- min-height: 24px;
581
- max-height: 160px;
582
- resize: none;
583
- border: none;
584
- outline: none;
585
- background: transparent;
586
- color: var(--dsw-alias-label-primary);
587
- font-family: inherit;
588
- font-size: 14px;
589
- line-height: 1.5;
590
- padding: 0;
591
- }
592
- .mg-textarea::placeholder {
593
- color: var(--dsw-alias-label-secondary);
594
- }
595
- .mg-composer-foot {
596
- display: flex;
597
- align-items: center;
598
- justify-content: space-between;
599
- gap: 8px;
600
- }
601
- .mg-composer-tag {
602
- font-size: 12px;
603
- color: var(--dsw-alias-label-secondary);
604
- }
605
- .mg-circle-btn {
606
- display: inline-flex;
607
- align-items: center;
608
- justify-content: center;
609
- width: 30px;
610
- height: 30px;
611
- border: none;
612
- border-radius: 50%;
613
- cursor: pointer;
614
- background: var(--dsw-alias-brand-primary);
615
- color: #ffffff;
616
- transition: opacity 0.15s ease, transform 0.1s ease;
617
- }
618
- .mg-circle-btn:disabled {
619
- opacity: 0.35;
620
- cursor: not-allowed;
621
- }
622
- .mg-circle-btn.is-stop {
623
- background: var(--dsw-alias-label-primary);
624
- color: var(--dsw-alias-bg-base);
625
151
  }
626
152
  .mg-header-btn:focus-visible,
627
153
  .mg-sel-btn:focus-visible,
628
- .mg-seg-btn:focus-visible,
629
- .mg-pill-btn:focus-visible,
630
- .mg-chip:focus-visible,
631
- .mg-action-link:focus-visible,
632
- .mg-circle-btn:focus-visible {
154
+ .mg-native-btn:focus-visible {
633
155
  outline: 2px solid var(--dsw-alias-brand-primary);
634
156
  outline-offset: 1px;
635
157
  }
@@ -659,240 +181,62 @@ window.__ModuleLoader__.load({
659
181
  );
660
182
  }
661
183
 
662
- function renderInline(text, keyPrefix) {
663
- const nodes = [];
664
- const tokenRe = /(`[^`]+`|\*\*[^*]+\*\*|\*[^*]+\*|\[[^\]]+\]\(https?:\/\/[^)]+\))/g;
665
- let last = 0;
666
- let match;
667
- let idx = 0;
668
- while ((match = tokenRe.exec(text)) !== null) {
669
- if (match.index > last) {
670
- nodes.push(text.slice(last, match.index));
671
- }
672
- const tok = match[0];
673
- const k = keyPrefix + '-' + idx++;
674
- if (tok.startsWith('`') && tok.endsWith('`')) {
675
- nodes.push(h('code', { key: k }, tok.slice(1, -1)));
676
- } else if (tok.startsWith('**') && tok.endsWith('**')) {
677
- nodes.push(h('strong', { key: k }, tok.slice(2, -2)));
678
- } else if (tok.startsWith('*') && tok.endsWith('*')) {
679
- nodes.push(h('em', { key: k }, tok.slice(1, -1)));
680
- } else if (tok.startsWith('[')) {
681
- const split = tok.indexOf('](');
682
- const label = tok.slice(1, split);
683
- const href = tok.slice(split + 2, -1);
684
- nodes.push(
685
- h(
686
- 'a',
687
- { key: k, href, target: '_blank', rel: 'noopener noreferrer' },
688
- label,
689
- ),
690
- );
691
- }
692
- last = tokenRe.lastIndex;
693
- }
694
- if (last < text.length) {
695
- nodes.push(text.slice(last));
696
- }
697
- return nodes;
698
- }
699
-
700
- function MarkdownBlock({ text, copyLabel, copiedLabel }) {
701
- const [copiedCodeIdx, setCopiedCodeIdx] = React.useState(null);
702
- if (!text) return null;
703
-
704
- const blocks = [];
705
- const fenceRe = /```([a-zA-Z0-9_-]*)\n([\s\S]*?)```/g;
706
- let last = 0;
707
- let m;
708
- let partIdx = 0;
709
- while ((m = fenceRe.exec(text)) !== null) {
710
- if (m.index > last) {
711
- blocks.push({ kind: 'prose', content: text.slice(last, m.index), key: 'p-' + partIdx++ });
712
- }
713
- blocks.push({ kind: 'code', lang: m[1] || 'code', content: m[2].replace(/\n$/, ''), key: 'c-' + partIdx++ });
714
- last = fenceRe.lastIndex;
715
- }
716
- if (last < text.length) {
717
- blocks.push({ kind: 'prose', content: text.slice(last), key: 'p-' + partIdx++ });
718
- }
719
-
720
- const elements = [];
721
- for (const blk of blocks) {
722
- if (blk.kind === 'code') {
723
- const codeKey = blk.key;
724
- elements.push(
725
- h(
726
- 'div',
727
- { key: codeKey, className: 'mg-code-wrap' },
728
- h(
729
- 'div',
730
- { className: 'mg-code-head' },
731
- h('span', null, blk.lang),
732
- h(
733
- 'button',
734
- {
735
- type: 'button',
736
- className: 'mg-action-link',
737
- onClick: () => {
738
- navigator.clipboard?.writeText(blk.content).then(() => {
739
- setCopiedCodeIdx(codeKey);
740
- window.setTimeout(() => {
741
- setCopiedCodeIdx((c) => (c === codeKey ? null : c));
742
- }, 1500);
743
- }).catch(() => {});
744
- },
745
- },
746
- copiedCodeIdx === codeKey ? copiedLabel : copyLabel,
747
- ),
748
- ),
749
- h('pre', { className: 'mg-code-pre' }, h('code', null, blk.content)),
750
- ),
751
- );
752
- continue;
753
- }
754
-
755
- const lines = blk.content.split(/\r?\n/);
756
- let listItems = [];
757
- let listOrdered = false;
758
- let pLines = [];
759
- let subIdx = 0;
760
-
761
- const flushPara = () => {
762
- if (pLines.length === 0) return;
763
- const joined = pLines.join('\n').trim();
764
- pLines = [];
765
- if (!joined) return;
766
- elements.push(h('p', { key: blk.key + '-p-' + subIdx++ }, renderInline(joined, blk.key + '-i-' + subIdx)));
767
- };
768
-
769
- const flushList = () => {
770
- if (listItems.length === 0) return;
771
- const items = listItems;
772
- const ordered = listOrdered;
773
- listItems = [];
774
- elements.push(
775
- h(
776
- ordered ? 'ol' : 'ul',
777
- { key: blk.key + '-l-' + subIdx++ },
778
- items.map((item, i) =>
779
- h('li', { key: i }, renderInline(item, blk.key + '-li-' + subIdx + '-' + i)),
780
- ),
781
- ),
782
- );
783
- };
784
-
785
- for (const line of lines) {
786
- const trimmed = line.trim();
787
- if (!trimmed) {
788
- flushPara();
789
- flushList();
790
- continue;
791
- }
792
- const headingMatch = trimmed.match(/^(#{1,4})\s+(.+)$/);
793
- if (headingMatch) {
794
- flushPara();
795
- flushList();
796
- const lvl = headingMatch[1].length;
797
- elements.push(
798
- h('h' + lvl, { key: blk.key + '-h-' + subIdx++ }, renderInline(headingMatch[2], blk.key + '-hi-' + subIdx)),
799
- );
800
- continue;
801
- }
802
- const ulMatch = trimmed.match(/^[-*]\s+(.+)$/);
803
- if (ulMatch) {
804
- flushPara();
805
- if (listItems.length > 0 && listOrdered) flushList();
806
- listOrdered = false;
807
- listItems.push(ulMatch[1]);
808
- continue;
809
- }
810
- const olMatch = trimmed.match(/^\d+\.\s+(.+)$/);
811
- if (olMatch) {
812
- flushPara();
813
- if (listItems.length > 0 && !listOrdered) flushList();
814
- listOrdered = true;
815
- listItems.push(olMatch[1]);
816
- continue;
817
- }
818
- if (trimmed.startsWith('> ')) {
819
- flushPara();
820
- flushList();
821
- elements.push(
822
- h('blockquote', { key: blk.key + '-q-' + subIdx++ }, renderInline(trimmed.slice(2), blk.key + '-qi-' + subIdx)),
823
- );
824
- continue;
825
- }
826
- flushList();
827
- 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;
828
203
  }
829
- flushPara();
830
- flushList();
831
204
  }
832
-
833
- return h('div', { className: 'mg-md' }, elements);
834
205
  }
835
206
 
836
- function loadStoredMessages(sessionId) {
837
- if (!sessionId) return [];
207
+ function getStoredSideSession(mainSessionId) {
208
+ if (!mainSessionId) return null;
838
209
  try {
839
- const raw = window.localStorage.getItem(STORAGE_PREFIX + sessionId);
840
- if (!raw) return [];
841
- const parsed = JSON.parse(raw);
842
- return Array.isArray(parsed) ? parsed : [];
210
+ return window.localStorage.getItem(SIDE_SESSION_PREFIX + mainSessionId);
843
211
  } catch {
844
- return [];
212
+ return null;
845
213
  }
846
214
  }
847
215
 
848
- function saveStoredMessages(sessionId, messages) {
849
- if (!sessionId) return;
216
+ function setStoredSideSession(mainSessionId, sideSessionId) {
217
+ if (!mainSessionId) return;
850
218
  try {
851
- const compact = messages.slice(-MAX_STORED_MESSAGES).map((m) => ({
852
- id: m.id,
853
- role: m.role,
854
- text: m.text,
855
- quotes: m.quotes,
856
- model: m.model,
857
- error: m.error,
858
- }));
859
- 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
+ }
860
224
  } catch {
861
- // Ignore storage quota errors.
862
- }
863
- }
864
-
865
- function makeId() {
866
- if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
867
- return crypto.randomUUID();
225
+ // Ignore storage errors.
868
226
  }
869
- return 'mg-' + Date.now() + '-' + Math.random().toString(36).slice(2, 8);
870
227
  }
871
228
 
872
229
  return {
873
- inject: ['slots', 'locale', 'sidebarRight', 'sidebarRightTabs', 'remote', 'uiSession'],
230
+ inject: ['slots', 'locale', 'sidebarRight', 'sidebarRightTabs', 'remote', 'sessions'],
874
231
  apply(ctx) {
875
232
  ctx.effect(() => ctx.locale.register('marginalia', { en, zh }), 'marginalia: locale');
876
233
  const t = ctx.locale.bind('marginalia');
877
234
 
878
- // Shared quote bus so selecting text in the main chat immediately populates the side chat.
879
- let pendingQuotes = [];
235
+ let pendingQuote = '';
880
236
  const quoteListeners = new Set();
881
- function pushQuote(text) {
882
- const clean = (text || '').trim();
883
- if (!clean) return;
884
- if (!pendingQuotes.includes(clean)) {
885
- pendingQuotes = [...pendingQuotes, clean].slice(-5);
886
- }
887
- for (const fn of quoteListeners) fn(pendingQuotes);
888
- }
889
- function clearQuotes() {
890
- pendingQuotes = [];
891
- for (const fn of quoteListeners) fn(pendingQuotes);
892
- }
893
- function removeQuoteAt(index) {
894
- pendingQuotes = pendingQuotes.filter((_, i) => i !== index);
895
- for (const fn of quoteListeners) fn(pendingQuotes);
237
+ function queueQuote(text) {
238
+ pendingQuote = text;
239
+ for (const fn of quoteListeners) fn(text);
896
240
  }
897
241
 
898
242
  ctx.effect(() => {
@@ -984,8 +328,6 @@ window.__ModuleLoader__.load({
984
328
 
985
329
  if (!sel) return null;
986
330
 
987
- const currentSessionId = ctx.uiSession?.adapter?.current?.getSnapshot()?.key;
988
-
989
331
  return h(
990
332
  'div',
991
333
  {
@@ -1000,20 +342,10 @@ window.__ModuleLoader__.load({
1000
342
  className: 'mg-sel-btn',
1001
343
  onClick: () => {
1002
344
  const quoted = '> ' + sel.text.replace(/\n/g, '\n> ') + '\n\n';
1003
- navigator.clipboard?.writeText(quoted).catch(() => {});
1004
- if (currentSessionId && typeof ctx.remote?.session?.prompt === 'function') {
1005
- // Focus main composer if available; otherwise copy quote.
1006
- const composer = document.querySelector('textarea:not([data-marginalia-input])');
1007
- if (composer) {
1008
- composer.focus();
1009
- const setter = Object.getOwnPropertyDescriptor(
1010
- window.HTMLTextAreaElement.prototype,
1011
- 'value',
1012
- )?.set;
1013
- const nextVal = (composer.value ? composer.value + '\n' : '') + quoted;
1014
- setter?.call(composer, nextVal);
1015
- composer.dispatchEvent(new Event('input', { bubbles: true }));
1016
- }
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(() => {});
1017
349
  }
1018
350
  window.getSelection()?.removeAllRanges();
1019
351
  setSel(null);
@@ -1028,7 +360,7 @@ window.__ModuleLoader__.load({
1028
360
  type: 'button',
1029
361
  className: 'mg-sel-btn',
1030
362
  onClick: () => {
1031
- pushQuote(sel.text);
363
+ queueQuote(sel.text);
1032
364
  window.getSelection()?.removeAllRanges();
1033
365
  setSel(null);
1034
366
  ctx.sidebarRight.openTab(TAB_KIND);
@@ -1059,738 +391,153 @@ window.__ModuleLoader__.load({
1059
391
  }
1060
392
 
1061
393
  function MarginaliaBody(props) {
1062
- const sessionId = props?.sessionId;
1063
- const isMainRunning =
1064
- typeof props?.useSessionStatus === 'function'
1065
- ? Boolean(props.useSessionStatus((s) => Boolean(s?.running)))
1066
- : false;
394
+ const mainSessionId = props?.sessionId;
395
+ const SessionProvider = props?.SessionProvider;
396
+ const renderSlot = props?.renderSlot;
1067
397
 
1068
398
  const [, setLocaleTick] = React.useState(0);
1069
399
  React.useEffect(() => ctx.locale.subscribe(() => setLocaleTick((v) => v + 1)), []);
1070
400
 
1071
- const [mode, setMode] = React.useState('side');
1072
- const [includeContext, setIncludeContext] = React.useState(true);
1073
- const [messages, setMessages] = React.useState(() => loadStoredMessages(sessionId));
1074
- const [quotes, setQuotes] = React.useState(() => pendingQuotes);
1075
- const [showQuotePreview, setShowQuotePreview] = React.useState(false);
1076
- const [draft, setDraft] = React.useState('');
1077
- const [streaming, setStreaming] = React.useState(false);
1078
- const [copiedId, setCopiedId] = React.useState(null);
1079
- const [notice, setNotice] = React.useState(null);
1080
- const [catalog, setCatalog] = React.useState(null);
1081
- const [selectedModel, setSelectedModel] = React.useState(() => {
1082
- try {
1083
- const raw = window.localStorage.getItem('dsh.marginalia.model.v1');
1084
- return raw ? JSON.parse(raw) : null;
1085
- } catch {
1086
- return null;
1087
- }
1088
- });
1089
- const [modelMenuOpen, setModelMenuOpen] = React.useState(false);
1090
-
1091
- const abortRef = React.useRef(null);
1092
- const scrollRef = React.useRef(null);
1093
- const textareaRef = React.useRef(null);
1094
- const modelMenuRef = React.useRef(null);
1095
-
1096
- React.useEffect(() => {
1097
- let cancelled = false;
1098
- const loadCatalog = async () => {
1099
- const fn = ctx.remote?.session?.modelCatalog;
1100
- if (typeof fn !== 'function') return;
1101
- try {
1102
- const res = await fn();
1103
- if (!cancelled && res) {
1104
- setCatalog(res);
1105
- setSelectedModel((curr) => curr || res.default || null);
1106
- }
1107
- } catch {
1108
- // Ignore catalog load failure; server falls back to session/default model.
1109
- }
1110
- };
1111
- loadCatalog();
1112
- return () => {
1113
- cancelled = true;
1114
- };
1115
- }, []);
1116
-
1117
- React.useEffect(() => {
1118
- if (!modelMenuOpen) return;
1119
- const onDocDown = (e) => {
1120
- if (modelMenuRef.current && !modelMenuRef.current.contains(e.target)) {
1121
- setModelMenuOpen(false);
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;
1122
417
  }
1123
- };
1124
- document.addEventListener('mousedown', onDocDown);
1125
- return () => document.removeEventListener('mousedown', onDocDown);
1126
- }, [modelMenuOpen]);
1127
-
1128
- function chooseModel(next) {
1129
- setSelectedModel(next);
1130
- try {
1131
- window.localStorage.setItem('dsh.marginalia.model.v1', JSON.stringify(next));
1132
- } catch {
1133
- // Ignore storage error.
1134
- }
1135
- }
1136
-
1137
- React.useEffect(() => {
1138
- const listener = (nextQuotes) => {
1139
- setQuotes(nextQuotes);
1140
- if (nextQuotes.length > 0) {
1141
- setMode('side');
1142
- window.setTimeout(() => textareaRef.current?.focus(), 40);
418
+ if (++attempts < 20) {
419
+ window.setTimeout(tryInsert, 80);
1143
420
  }
1144
421
  };
1145
- quoteListeners.add(listener);
1146
- return () => quoteListeners.delete(listener);
422
+ window.setTimeout(tryInsert, 60);
1147
423
  }, []);
1148
424
 
1149
425
  React.useEffect(() => {
1150
- if (abortRef.current) {
1151
- abortRef.current.abort();
1152
- abortRef.current = null;
1153
- }
1154
- setStreaming(false);
1155
- setMessages(loadStoredMessages(sessionId));
1156
- }, [sessionId]);
426
+ const onQuote = () => {
427
+ if (sideRef) flushPendingQuote();
428
+ };
429
+ quoteListeners.add(onQuote);
430
+ return () => quoteListeners.delete(onQuote);
431
+ }, [sideRef, flushPendingQuote]);
1157
432
 
1158
433
  React.useEffect(() => {
1159
- if (!streaming) {
1160
- saveStoredMessages(sessionId, messages);
1161
- }
1162
- }, [sessionId, messages, streaming]);
434
+ if (sideRef) flushPendingQuote();
435
+ }, [sideRef, flushPendingQuote]);
1163
436
 
1164
437
  React.useEffect(() => {
1165
- if (scrollRef.current) {
1166
- scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
1167
- }
1168
- }, [messages, streaming]);
438
+ if (!mainSessionId) return;
439
+ const ac = new AbortController();
440
+ let activeRef = null;
1169
441
 
1170
- React.useEffect(() => {
1171
- const el = textareaRef.current;
1172
- if (!el) return;
1173
- el.style.height = 'auto';
1174
- el.style.height = Math.min(el.scrollHeight, 160) + 'px';
1175
- }, [draft]);
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;
1176
467
 
1177
- React.useEffect(() => {
1178
- return () => {
1179
- if (abortRef.current) {
1180
- abortRef.current.abort();
1181
- 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
+ }
1182
477
  }
1183
478
  };
1184
- }, []);
1185
-
1186
- function showNotice(text, isError) {
1187
- const entry = { text, isError: Boolean(isError) };
1188
- setNotice(entry);
1189
- window.setTimeout(() => {
1190
- setNotice((curr) => (curr === entry ? null : curr));
1191
- }, 2400);
1192
- }
1193
-
1194
- async function sendToMainChat(text) {
1195
- const trimmed = text.trim();
1196
- if (!trimmed) return;
1197
- if (!sessionId) {
1198
- showNotice(t('error.noSession'), true);
1199
- return;
1200
- }
1201
- const promptFn = ctx.remote?.session?.prompt;
1202
- if (typeof promptFn !== 'function') {
1203
- showNotice(t('error.sendFailed'), true);
1204
- return;
1205
- }
1206
- try {
1207
- await promptFn({
1208
- requestId: makeId(),
1209
- sessionId,
1210
- mode: isMainRunning ? 'steer' : 'queue',
1211
- content: [{ type: 'text', text: trimmed }],
1212
- });
1213
- showNotice(t('sentToMain'), false);
1214
- } catch (err) {
1215
- const msg = err instanceof Error ? err.message : String(err);
1216
- showNotice(msg || t('error.sendFailed'), true);
1217
- }
1218
- }
1219
-
1220
- async function handleSubmit(overrideText) {
1221
- const text = (typeof overrideText === 'string' ? overrideText : draft).trim();
1222
- const activeQuotes = quotes.slice();
1223
- if ((!text && activeQuotes.length === 0) || streaming) return;
1224
-
1225
- if (mode === 'main') {
1226
- const combined =
1227
- activeQuotes.length > 0
1228
- ? activeQuotes.map((q) => '> ' + q.replace(/\n/g, '\n> ')).join('\n\n') +
1229
- (text ? '\n\n' + text : '')
1230
- : text;
1231
- setDraft('');
1232
- clearQuotes();
1233
- await sendToMainChat(combined);
1234
- return;
1235
- }
1236
-
1237
- if (!overrideText) setDraft('');
1238
- clearQuotes();
1239
- setShowQuotePreview(false);
1240
-
1241
- const userMsg = {
1242
- id: makeId(),
1243
- role: 'user',
1244
- text: text || activeQuotes[0],
1245
- quotes: text ? activeQuotes : [],
1246
- };
1247
- const assistantId = makeId();
1248
- const assistantMsg = { id: assistantId, role: 'assistant', text: '' };
1249
-
1250
- const priorHistory = messages
1251
- .filter((m) => !m.error && m.text)
1252
- .map((m) => ({
1253
- role: m.role,
1254
- text:
1255
- m.quotes && m.quotes.length > 0
1256
- ? m.quotes.map((q) => '> ' + q).join('\n') + '\n\n' + m.text
1257
- : m.text,
1258
- }));
1259
-
1260
- setMessages((prev) => [...prev, userMsg, assistantMsg]);
1261
- setStreaming(true);
1262
-
1263
- const controller = new AbortController();
1264
- abortRef.current = controller;
1265
479
 
1266
- try {
1267
- const res = await fetch('/api/marginalia/ask', {
1268
- method: 'POST',
1269
- credentials: 'same-origin',
1270
- headers: { 'Content-Type': 'application/json' },
1271
- body: JSON.stringify({
1272
- sessionId: sessionId || '',
1273
- question: text,
1274
- quotes: activeQuotes,
1275
- includeContext,
1276
- history: priorHistory,
1277
- model: selectedModel || undefined,
1278
- }),
1279
- signal: controller.signal,
1280
- });
1281
-
1282
- if (!res.ok || !res.body) {
1283
- let errMsg = t('error.sendFailed');
480
+ ensureSideSession();
481
+ return () => {
482
+ ac.abort();
483
+ if (activeRef) {
1284
484
  try {
1285
- const errJson = await res.json();
1286
- if (errJson?.error) errMsg = errJson.error;
485
+ activeRef.release();
1287
486
  } catch {
1288
- // Ignore JSON parse failure.
487
+ // Ignore release error.
1289
488
  }
1290
- setMessages((prev) =>
1291
- prev.map((m) => (m.id === assistantId ? { ...m, text: errMsg, error: true } : m)),
1292
- );
1293
- return;
1294
489
  }
490
+ };
491
+ }, [mainSessionId, retryNonce]);
1295
492
 
1296
- const reader = res.body.getReader();
1297
- const decoder = new TextDecoder();
1298
- let buffer = '';
1299
- let modelLabel = '';
1300
-
1301
- while (true) {
1302
- const { done, value } = await reader.read();
1303
- if (done) break;
1304
- buffer += decoder.decode(value, { stream: true });
1305
- const frames = buffer.split('\n\n');
1306
- buffer = frames.pop() || '';
1307
- for (const frame of frames) {
1308
- const line = frame.trim();
1309
- if (!line.startsWith('data:')) continue;
1310
- const jsonText = line.slice(5).trim();
1311
- if (!jsonText) continue;
1312
- let ev;
1313
- try {
1314
- ev = JSON.parse(jsonText);
1315
- } catch {
1316
- continue;
1317
- }
1318
- if (ev.type === 'meta' && ev.model) {
1319
- modelLabel = ev.model;
1320
- } else if (ev.type === 'delta' && ev.text) {
1321
- setMessages((prev) =>
1322
- prev.map((m) =>
1323
- m.id === assistantId
1324
- ? { ...m, text: m.text + ev.text, model: modelLabel || m.model }
1325
- : m,
1326
- ),
1327
- );
1328
- } else if (ev.type === 'error') {
1329
- setMessages((prev) =>
1330
- prev.map((m) =>
1331
- m.id === assistantId
1332
- ? { ...m, text: ev.message || t('error.sendFailed'), error: true }
1333
- : m,
1334
- ),
1335
- );
1336
- }
1337
- }
1338
- }
1339
- } catch (err) {
1340
- if (!controller.signal.aborted) {
1341
- const msg = err instanceof Error ? err.message : String(err);
1342
- setMessages((prev) =>
1343
- prev.map((m) =>
1344
- m.id === assistantId
1345
- ? { ...m, text: msg || t('error.sendFailed'), error: true }
1346
- : m,
1347
- ),
1348
- );
1349
- }
1350
- } finally {
1351
- abortRef.current = null;
1352
- setStreaming(false);
1353
- setMessages((prev) => prev.filter((m) => !(m.id === assistantId && !m.text)));
1354
- }
1355
- }
1356
-
1357
- function handleStop() {
1358
- if (abortRef.current) {
1359
- abortRef.current.abort();
1360
- abortRef.current = null;
1361
- }
1362
- setStreaming(false);
1363
- setMessages((prev) => prev.filter((m) => !(m.role === 'assistant' && !m.text)));
1364
- }
1365
-
1366
- function handleCopy(msg) {
1367
- if (!msg?.text || !navigator.clipboard) return;
1368
- navigator.clipboard
1369
- .writeText(msg.text)
1370
- .then(() => {
1371
- setCopiedId(msg.id);
1372
- window.setTimeout(() => {
1373
- setCopiedId((curr) => (curr === msg.id ? null : curr));
1374
- }, 1600);
1375
- })
1376
- .catch(() => {});
1377
- }
1378
-
1379
- const chips = [t('chip.summarize'), t('chip.explain'), t('chip.next')];
1380
- const quoteLabel = (
1381
- quotes.length === 1 ? t('quote.count') : t('quote.countPlural')
1382
- ).replace('{n}', String(quotes.length));
493
+ const handleNewSideChat = () => {
494
+ if (!mainSessionId) return;
495
+ setStoredSideSession(mainSessionId, null);
496
+ setRetryNonce((n) => n + 1);
497
+ };
1383
498
 
1384
499
  return h(
1385
500
  'div',
1386
- { className: 'mg-root', 'data-marginalia-root': 'true' },
501
+ { className: 'mg-native-wrap', 'data-marginalia-root': 'true', ref: rootRef },
1387
502
  h(
1388
503
  'div',
1389
- { className: 'mg-toolbar' },
504
+ { className: 'mg-native-bar' },
505
+ h('span', { className: 'mg-native-label' }, t('bar.label')),
1390
506
  h(
1391
- 'div',
1392
- { className: 'mg-seg', role: 'tablist' },
1393
- h(
1394
- 'button',
1395
- {
1396
- type: 'button',
1397
- role: 'tab',
1398
- 'aria-selected': mode === 'side',
1399
- className: 'mg-seg-btn' + (mode === 'side' ? ' is-active' : ''),
1400
- onClick: () => setMode('side'),
1401
- },
1402
- t('mode.side'),
1403
- ),
1404
- h(
1405
- 'button',
1406
- {
1407
- type: 'button',
1408
- role: 'tab',
1409
- 'aria-selected': mode === 'main',
1410
- className: 'mg-seg-btn' + (mode === 'main' ? ' is-active' : ''),
1411
- onClick: () => setMode('main'),
1412
- },
1413
- t('mode.main'),
1414
- ),
1415
- ),
1416
- h(
1417
- 'div',
1418
- { className: 'mg-toolbar-right' },
1419
- mode === 'side'
1420
- ? h(
1421
- 'button',
1422
- {
1423
- type: 'button',
1424
- className: 'mg-pill-btn' + (includeContext ? ' is-on' : ''),
1425
- onClick: () => setIncludeContext((v) => !v),
1426
- },
1427
- includeContext ? t('context.on') : t('context.off'),
1428
- )
1429
- : null,
1430
- messages.length > 0 && !streaming
1431
- ? h(
1432
- 'button',
1433
- {
1434
- type: 'button',
1435
- className: 'mg-pill-btn',
1436
- onClick: () => {
1437
- setMessages([]);
1438
- saveStoredMessages(sessionId, []);
1439
- },
1440
- },
1441
- t('newChat'),
1442
- )
1443
- : null,
507
+ 'button',
508
+ {
509
+ type: 'button',
510
+ className: 'mg-native-btn',
511
+ onClick: handleNewSideChat,
512
+ },
513
+ t('newChat'),
1444
514
  ),
1445
515
  ),
1446
516
  h(
1447
517
  'div',
1448
- { className: 'mg-scroll', ref: scrollRef },
1449
- messages.length === 0
518
+ { className: 'mg-native-conv' },
519
+ errorMsg
1450
520
  ? h(
1451
521
  'div',
1452
- { className: 'mg-empty' },
1453
- h('div', { className: 'mg-empty-icon' }, h(MarginaliaGlyph, { size: 20 })),
1454
- h('div', { className: 'mg-empty-title' }, t('empty.title')),
522
+ { className: 'mg-state mg-state-error' },
523
+ h('div', null, t('error.prefix') + errorMsg),
1455
524
  h(
1456
- 'div',
1457
- { className: 'mg-empty-sub' },
1458
- 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'),
1459
532
  ),
1460
- mode === 'side'
1461
- ? h(
1462
- 'div',
1463
- { className: 'mg-chips' },
1464
- chips.map((chip) =>
1465
- h(
1466
- 'button',
1467
- {
1468
- key: chip,
1469
- type: 'button',
1470
- className: 'mg-chip',
1471
- onClick: () => handleSubmit(chip),
1472
- },
1473
- chip,
1474
- ),
1475
- ),
1476
- )
1477
- : null,
1478
533
  )
1479
- : messages.map((msg) =>
1480
- msg.role === 'user'
1481
- ? h(
1482
- 'div',
1483
- { key: msg.id, className: 'mg-msg is-user' },
1484
- msg.quotes && msg.quotes.length > 0
1485
- ? h(
1486
- 'div',
1487
- { className: 'mg-user-quotes' },
1488
- h(
1489
- 'span',
1490
- { className: 'mg-quote-chip' },
1491
- (msg.quotes.length === 1 ? t('quote.count') : t('quote.countPlural')).replace(
1492
- '{n}',
1493
- String(msg.quotes.length),
1494
- ),
1495
- ),
1496
- )
1497
- : null,
1498
- h('div', { className: 'mg-user-bubble' }, msg.text),
1499
- )
1500
- : h(
1501
- 'div',
1502
- { key: msg.id, className: 'mg-msg is-assistant' },
1503
- msg.text
1504
- ? h(
1505
- 'div',
1506
- { className: 'mg-assistant-body' + (msg.error ? ' is-error' : '') },
1507
- msg.error
1508
- ? msg.text
1509
- : h(MarkdownBlock, {
1510
- text: msg.text,
1511
- copyLabel: t('copy'),
1512
- copiedLabel: t('copied'),
1513
- }),
1514
- )
1515
- : h(
1516
- 'div',
1517
- { className: 'mg-thinking' },
1518
- h('span', { className: 'mg-dot' }),
1519
- h('span', null, t('thinking')),
1520
- ),
1521
- msg.text
1522
- ? h(
1523
- 'div',
1524
- { className: 'mg-msg-meta' },
1525
- msg.model ? h('span', null, msg.model) : null,
1526
- h(
1527
- 'button',
1528
- {
1529
- type: 'button',
1530
- className: 'mg-action-link',
1531
- onClick: () => handleCopy(msg),
1532
- },
1533
- copiedId === msg.id ? t('copied') : t('copy'),
1534
- ),
1535
- !msg.error
1536
- ? h(
1537
- 'button',
1538
- {
1539
- type: 'button',
1540
- className: 'mg-action-link',
1541
- onClick: () => sendToMainChat(msg.text),
1542
- },
1543
- t('promote'),
1544
- )
1545
- : null,
1546
- )
1547
- : null,
1548
- ),
1549
- ),
1550
- ),
1551
- notice
1552
- ? h('div', { className: 'mg-notice' + (notice.isError ? ' is-error' : '') }, notice.text)
1553
- : null,
1554
- h(
1555
- 'div',
1556
- { className: 'mg-composer' },
1557
- h(
1558
- 'div',
1559
- { className: 'mg-input-box' },
1560
- quotes.length > 0
534
+ : sideRef && SessionProvider && typeof renderSlot === 'function'
1561
535
  ? h(
1562
- 'div',
1563
- { className: 'mg-quote-strip' },
1564
- h(
1565
- 'div',
1566
- {
1567
- className: 'mg-quote-chip',
1568
- onClick: () => setShowQuotePreview((v) => !v),
1569
- },
1570
- h('span', null, quoteLabel),
1571
- h(
1572
- 'button',
1573
- {
1574
- type: 'button',
1575
- className: 'mg-quote-x',
1576
- 'aria-label': 'Clear',
1577
- onClick: (e) => {
1578
- e.stopPropagation();
1579
- clearQuotes();
1580
- setShowQuotePreview(false);
1581
- },
1582
- },
1583
- '×',
1584
- ),
1585
- ),
1586
- showQuotePreview
1587
- ? quotes.map((q, idx) =>
1588
- h(
1589
- 'div',
1590
- { key: idx, className: 'mg-quote-preview' },
1591
- q,
1592
- quotes.length > 1
1593
- ? h(
1594
- 'button',
1595
- {
1596
- type: 'button',
1597
- className: 'mg-quote-x',
1598
- onClick: () => removeQuoteAt(idx),
1599
- },
1600
- ' ×',
1601
- )
1602
- : null,
1603
- ),
1604
- )
1605
- : null,
536
+ SessionProvider,
537
+ { session: sideRef },
538
+ renderSlot('sidebar.chat.conversation', {}),
1606
539
  )
1607
- : null,
1608
- h('textarea', {
1609
- ref: textareaRef,
1610
- 'data-marginalia-input': 'true',
1611
- className: 'mg-textarea',
1612
- rows: 1,
1613
- value: draft,
1614
- placeholder: mode === 'side' ? t('placeholder.side') : t('placeholder.main'),
1615
- onChange: (e) => setDraft(e.target.value),
1616
- onKeyDown: (e) => {
1617
- if (e.nativeEvent?.isComposing || e.isComposing) return;
1618
- if (e.key === 'Enter' && !e.shiftKey) {
1619
- e.preventDefault();
1620
- handleSubmit();
1621
- }
1622
- },
1623
- }),
1624
- h(
1625
- 'div',
1626
- { className: 'mg-composer-foot' },
1627
- h(
1628
- 'span',
1629
- { className: 'mg-composer-tag' },
1630
- mode === 'side'
1631
- ? includeContext
1632
- ? t('context.on')
1633
- : t('context.off')
1634
- : t('mode.main'),
1635
- ),
1636
- h(
1637
- 'div',
1638
- { style: { display: 'inline-flex', alignItems: 'center', gap: '6px' } },
1639
- mode === 'side' && catalog && Array.isArray(catalog.groups) && catalog.groups.length > 0
1640
- ? h(
1641
- 'div',
1642
- { className: 'mg-model-wrap', ref: modelMenuRef },
1643
- h(
1644
- 'button',
1645
- {
1646
- type: 'button',
1647
- className: 'mg-model-btn',
1648
- onClick: () => setModelMenuOpen((v) => !v),
1649
- },
1650
- h(
1651
- 'span',
1652
- { className: 'mg-model-name' },
1653
- (() => {
1654
- const grp = catalog.groups.find((g) => g.id === selectedModel?.provider);
1655
- const mod = grp?.models?.find((m) => m.id === selectedModel?.model);
1656
- const name = mod?.name || selectedModel?.model || 'Model';
1657
- return selectedModel?.reasoningEffort
1658
- ? name + ' · ' + selectedModel.reasoningEffort
1659
- : name;
1660
- })(),
1661
- ),
1662
- h(
1663
- 'svg',
1664
- {
1665
- width: 12,
1666
- height: 12,
1667
- viewBox: '0 0 24 24',
1668
- fill: 'none',
1669
- stroke: 'currentColor',
1670
- strokeWidth: 2,
1671
- strokeLinecap: 'round',
1672
- strokeLinejoin: 'round',
1673
- },
1674
- h('path', { d: 'M6 9l6 6 6-6' }),
1675
- ),
1676
- ),
1677
- modelMenuOpen
1678
- ? h(
1679
- 'div',
1680
- { className: 'mg-model-menu' },
1681
- catalog.groups.map((grp) =>
1682
- h(
1683
- 'div',
1684
- { key: grp.id },
1685
- h('div', { className: 'mg-model-group' }, grp.name || grp.id),
1686
- (grp.models || []).map((mod) => {
1687
- const isSel =
1688
- selectedModel?.provider === grp.id &&
1689
- selectedModel?.model === mod.id;
1690
- const efforts = mod.reasoning?.efforts || [];
1691
- return h(
1692
- 'div',
1693
- { key: mod.id },
1694
- h(
1695
- 'button',
1696
- {
1697
- type: 'button',
1698
- className: 'mg-model-item' + (isSel ? ' is-selected' : ''),
1699
- onClick: () => {
1700
- chooseModel({
1701
- provider: grp.id,
1702
- model: mod.id,
1703
- ...(mod.reasoning?.defaultEffort
1704
- ? { reasoningEffort: mod.reasoning.defaultEffort }
1705
- : {}),
1706
- });
1707
- if (efforts.length === 0) setModelMenuOpen(false);
1708
- },
1709
- },
1710
- h('span', null, mod.name || mod.id),
1711
- isSel ? h('span', null, '✓') : null,
1712
- ),
1713
- isSel && efforts.length > 0
1714
- ? h(
1715
- 'div',
1716
- { className: 'mg-effort-row' },
1717
- efforts.map((eff) =>
1718
- h(
1719
- 'button',
1720
- {
1721
- key: eff.id,
1722
- type: 'button',
1723
- className:
1724
- 'mg-effort-pill' +
1725
- (selectedModel?.reasoningEffort === eff.id
1726
- ? ' is-selected'
1727
- : ''),
1728
- onClick: () => {
1729
- chooseModel({
1730
- provider: grp.id,
1731
- model: mod.id,
1732
- reasoningEffort: eff.id,
1733
- });
1734
- setModelMenuOpen(false);
1735
- },
1736
- },
1737
- eff.name || eff.id,
1738
- ),
1739
- ),
1740
- )
1741
- : null,
1742
- );
1743
- }),
1744
- ),
1745
- ),
1746
- )
1747
- : null,
1748
- )
1749
- : null,
1750
- streaming
1751
- ? h(
1752
- 'button',
1753
- {
1754
- type: 'button',
1755
- className: 'mg-circle-btn is-stop',
1756
- title: t('stop'),
1757
- 'aria-label': t('stop'),
1758
- onClick: handleStop,
1759
- },
1760
- h(
1761
- 'svg',
1762
- { width: 12, height: 12, viewBox: '0 0 12 12', fill: 'currentColor' },
1763
- h('rect', { x: 2, y: 2, width: 8, height: 8, rx: 1.5 }),
1764
- ),
1765
- )
1766
- : h(
1767
- 'button',
1768
- {
1769
- type: 'button',
1770
- className: 'mg-circle-btn',
1771
- title: t('send'),
1772
- 'aria-label': t('send'),
1773
- disabled: !draft.trim() && quotes.length === 0,
1774
- onClick: () => handleSubmit(),
1775
- },
1776
- h(
1777
- 'svg',
1778
- {
1779
- width: 15,
1780
- height: 15,
1781
- viewBox: '0 0 24 24',
1782
- fill: 'none',
1783
- stroke: 'currentColor',
1784
- strokeWidth: 2.3,
1785
- strokeLinecap: 'round',
1786
- strokeLinejoin: 'round',
1787
- },
1788
- h('path', { d: 'M12 19V5M5 12l7-7 7 7' }),
1789
- ),
1790
- ),
1791
- ),
1792
- ),
1793
- ),
540
+ : h('div', { className: 'mg-state' }, t('loading')),
1794
541
  ),
1795
542
  );
1796
543
  }
@@ -1801,6 +548,7 @@ window.__ModuleLoader__.load({
1801
548
  name: 'sidebar.right.pane.tab',
1802
549
  key: PLUGIN_ID,
1803
550
  locale: 'marginalia',
551
+ children: { 'sidebar.chat.conversation': { kind: 'single', scope: 'session' } },
1804
552
  },
1805
553
  MarginaliaBody,
1806
554
  ),