@tanzz/dsh-explore 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/README.md +131 -96
  2. package/README.zh-CN.md +185 -0
  3. package/client.js +1984 -196
  4. package/package.json +2 -2
package/client.js CHANGED
@@ -23,15 +23,21 @@ window.__ModuleLoader__.load({
23
23
  ink: 'var(--dsw-alias-label-primary)',
24
24
  ink2: 'var(--dsw-alias-label-secondary)',
25
25
  ink3: 'var(--dsw-alias-label-secondary)',
26
+ // Reasoning reads as a footnote to the answer, so it sits one step
27
+ // quieter than the body text.
28
+ ink4: 'var(--dsw-alias-label-tertiary)',
26
29
  line: 'var(--dsw-alias-border-l2)',
27
30
  card: 'var(--dsw-alias-bg-layer-1)',
31
+ // Floating surfaces (menus) take the overlay level: on a dark theme a
32
+ // menu painted with the card colour would disappear into the card under
33
+ // it, and this is the level the host reserves for exactly that case.
34
+ overlay: 'var(--dsw-alias-bg-overlay)',
28
35
  cardEdge: 'var(--dsw-alias-border-l1)',
29
36
  canvas: 'var(--dsw-alias-bg-base)',
30
37
  code: 'var(--dsw-alias-markdown-code-block)',
31
38
  // A `label-primary` tint keeps the chip visible on a white card (the
32
39
  // markdown inline-code token is nearly white in the light theme).
33
40
  codeInline: 'color-mix(in srgb, var(--dsw-alias-label-primary) 7%, transparent)',
34
- scrim: 'var(--dsw-alias-bg-mask-1)',
35
41
  warn: 'var(--dsw-alias-state-error-primary)',
36
42
  ok: 'var(--dsw-alias-state-success-primary)',
37
43
  };
@@ -39,6 +45,24 @@ window.__ModuleLoader__.load({
39
45
  const NODE_H = 212;
40
46
  const GAP_X = 44;
41
47
  const GAP_Y = 76;
48
+ const LAYOUT_DIRECTION_KEY = 'dsh-explore:layout-direction';
49
+
50
+ function readLayoutDirection() {
51
+ try {
52
+ return window.localStorage.getItem(LAYOUT_DIRECTION_KEY) === 'horizontal' ? 'horizontal' : 'vertical';
53
+ } catch (error) {
54
+ return 'vertical';
55
+ }
56
+ }
57
+
58
+ function saveLayoutDirection(direction) {
59
+ try {
60
+ window.localStorage.setItem(LAYOUT_DIRECTION_KEY, direction);
61
+ } catch (error) {
62
+ /* Layout remains available for this view when storage is blocked. */
63
+ }
64
+ }
65
+
42
66
  // Font families follow Settings → Appearance. DSH composes the user's list
43
67
  // with its own default stack on body (`--dsw-font-family` /
44
68
  // `--ds-font-family-code`), so reading the composed tokens keeps glyph
@@ -72,6 +96,10 @@ window.__ModuleLoader__.load({
72
96
  'view.zoomOut': '缩小画布',
73
97
  'view.zoomIn': '放大画布',
74
98
  'view.zoomLevel': '当前缩放比例',
99
+ 'view.layoutGroup': '布局方向',
100
+ 'view.layoutVertical': '上下布局',
101
+ 'view.layoutHorizontal': '左右布局',
102
+ 'view.layoutTitle': '切换左右布局和上下布局',
75
103
  'view.fit': '适应画布',
76
104
  'view.fitTitle': '缩放到能看见整棵树',
77
105
  'view.latest': '定位最新',
@@ -116,6 +144,12 @@ window.__ModuleLoader__.load({
116
144
  'card.cost.context': '上下文 {value}',
117
145
  'card.cost.cached': '缓存 {value}',
118
146
 
147
+ 'card.think': '思考过程',
148
+ 'card.thinkExpandTitle': '展开思考过程',
149
+ 'card.thinkCollapseTitle': '收起思考过程',
150
+ 'card.thinkMeta': '思考 {count} 字',
151
+ 'card.thinkTruncated': '(只保留了最新的 {count} 字思考)',
152
+
119
153
  'live.calling': '正在调用 {tool}',
120
154
  'live.outputting': '正在输出…',
121
155
  'live.thinking': '正在思考…',
@@ -169,6 +203,10 @@ window.__ModuleLoader__.load({
169
203
  'view.zoomOut': 'Zoom out',
170
204
  'view.zoomIn': 'Zoom in',
171
205
  'view.zoomLevel': 'Current zoom level',
206
+ 'view.layoutGroup': 'Layout direction',
207
+ 'view.layoutVertical': 'Top to bottom',
208
+ 'view.layoutHorizontal': 'Left to right',
209
+ 'view.layoutTitle': 'Switch between left-to-right and top-to-bottom layouts',
172
210
  'view.fit': 'Fit canvas',
173
211
  'view.fitTitle': 'Zoom out to show the whole tree',
174
212
  'view.latest': 'Jump to latest',
@@ -213,6 +251,12 @@ window.__ModuleLoader__.load({
213
251
  'card.cost.context': 'context {value}',
214
252
  'card.cost.cached': 'cached {value}',
215
253
 
254
+ 'card.think': 'Reasoning',
255
+ 'card.thinkExpandTitle': 'Expand the reasoning',
256
+ 'card.thinkCollapseTitle': 'Collapse the reasoning',
257
+ 'card.thinkMeta': '{count} chars of reasoning',
258
+ 'card.thinkTruncated': '(only the newest {count} chars of reasoning are kept)',
259
+
216
260
  'live.calling': 'Calling {tool}',
217
261
  'live.outputting': 'Writing…',
218
262
  'live.thinking': 'Thinking…',
@@ -248,17 +292,614 @@ window.__ModuleLoader__.load({
248
292
  'error.submitFailed': 'Submit failed: {reason}',
249
293
  'error.loadOlderFailed': 'Could not load earlier history: {reason}',
250
294
  },
295
+ de: {
296
+ 'view.tab': 'Endlose Erkundung',
297
+ 'view.heading': 'Endlose Erkundung',
298
+ 'view.nodes': '{count} Knoten',
299
+ 'view.running': '{count} Zweige laufen',
300
+ 'view.runningTitle': 'Zum nächsten laufenden Knoten springen',
301
+ 'view.awaiting': '{count} warten auf dich',
302
+ 'view.awaitingTitle': 'Zum Knoten springen, der auf dich wartet',
303
+ 'view.loadOlder': 'Frühere laden',
304
+ 'view.restoreHidden': '{count} ausgeblendet · Wiederherstellen',
305
+ 'view.restoreHiddenTitle': 'Gelöschte Knoten und Zweige wiederherstellen',
306
+ 'view.searchPlaceholder': 'Knoten suchen',
307
+ 'view.searchLabel': 'Knoten suchen',
308
+ 'view.zoomGroup': 'Leinwand-Zoom',
309
+ 'view.zoomOut': 'Verkleinern',
310
+ 'view.zoomIn': 'Vergrößern',
311
+ 'view.zoomLevel': 'Aktuelle Zoomstufe',
312
+ 'view.layoutHorizontal': 'Links nach rechts',
313
+ 'view.layoutTitle': 'Zwischen Links-nach-rechts und Oben-nach-unten wechseln',
314
+ 'view.fit': 'Leinwand einpassen',
315
+ 'view.fitTitle': 'Herauszoomen, bis der ganze Baum sichtbar ist',
316
+ 'view.latest': 'Zum Neuesten',
317
+ 'view.latestTitle': 'Pfad ausklappen und zum neuesten Knoten springen',
318
+ 'view.latestTitleEmpty': 'Noch keine Knoten',
319
+ 'view.empty.title': 'Dieser Baum ist noch leer',
320
+ 'view.empty.hint': 'Stelle im Chat eine Frage, dann wächst hier der erste Knoten.',
321
+ 'view.empty.report': 'Wenn du schon gefragt hast und es hier noch leer ist, sag mir: {events} Ereignisse · Sitzung {state}.',
322
+ 'card.noQuestion': '(keine Frage)',
323
+ 'card.questionReply': '(Antwort auf die vorherige Frage)',
324
+ 'card.latestBadge': 'Neuestes',
325
+ 'card.latestTitle': 'Der neueste Knoten in diesem Baum',
326
+ 'card.status.thinking': 'Denkt nach',
327
+ 'card.status.streaming': 'Antwortet',
328
+ 'card.status.error': 'Fehler',
329
+ 'card.status.stopped': 'Angehalten',
330
+ 'card.status.done': 'Fertig',
331
+ 'card.status.awaiting': 'Braucht Antwort',
332
+ 'card.status.awaitingApproval': 'Braucht Freigabe',
333
+ 'card.stop': 'Stoppen',
334
+ 'card.stopTitle': 'Diesen Zweig stoppen',
335
+ 'card.ask': 'Auf diesem Zweig nachfragen',
336
+ 'card.more': 'Weitere Aktionen',
337
+ 'card.delete': 'Diesen Knoten löschen',
338
+ 'card.deleteTitle': 'Diesen Knoten und alle Zweige darunter ausblenden',
339
+ 'card.deleteConfirm': 'Diesen Knoten und alle Zweige darunter löschen? (umkehrbar)',
340
+ 'card.readTitle': 'Klicken, um im Vollbild zu lesen',
341
+ 'card.expandTitle': 'Diese Antwort ausklappen',
342
+ 'card.collapseTitle': 'Diese Antwort einklappen',
343
+ 'card.expand': 'Antwort ausklappen',
344
+ 'card.collapse': 'Antwort einklappen',
345
+ 'card.fullscreen': 'Vollbild lesen',
346
+ 'card.fullscreenTitle': 'Die vollständige Antwort im Vollbild lesen',
347
+ 'card.unfoldBranch': 'Diesen Zweig ausklappen',
348
+ 'card.foldBranch': 'Diesen Zweig einklappen',
349
+ 'card.unfoldDescendants': '{count} Nachfolger ausklappen',
350
+ 'card.foldDescendants': '{count} Nachfolger einklappen',
351
+ 'card.descendants': '{count} Nachfolger',
352
+ 'card.truncated': '\n\n… (im Vollbild die vollständige Antwort lesen)',
353
+ 'card.cost.elapsed': 'Dauer {value}',
354
+ 'card.cost.context': 'Kontext {value}',
355
+ 'card.cost.cached': 'Cache {value}',
356
+ 'card.think': 'Gedankengang',
357
+ 'card.thinkExpandTitle': 'Den Gedankengang ausklappen',
358
+ 'card.thinkCollapseTitle': 'Den Gedankengang einklappen',
359
+ 'card.thinkMeta': '{count} Zeichen Gedankengang',
360
+ 'card.thinkTruncated': '(nur die neuesten {count} Zeichen Gedankengang bleiben erhalten)',
361
+ 'live.calling': 'Ruft {tool} auf',
362
+ 'live.outputting': 'Schreibt…',
363
+ 'live.thinking': 'Denkt nach…',
364
+ 'live.starting': 'Startet…',
365
+ 'live.awaiting': 'Wartet auf deine Antwort…',
366
+ 'live.awaitingApproval': 'Wartet auf deine Freigabe…',
367
+ 'live.step': 'Schritt {step}',
368
+ 'composer.placeholder': 'Auf diesem Zweig nachfragen… (Enter senden, Shift+Enter neue Zeile)',
369
+ 'composer.label': 'Nachfrage',
370
+ 'composer.from': 'Ausgehend von „{question}…“',
371
+ 'composer.cancel': 'Abbrechen',
372
+ 'composer.send': 'Senden',
373
+ 'reader.close': 'Schließen (Esc)',
374
+ 'reader.closeLabel': 'Leser schließen',
375
+ 'reader.noAnswer': '(noch keine Antwort)',
376
+ 'reader.hint': 'Esc oder Klick auf den Hintergrund zum Schließen',
377
+ 'reader.branch': 'Zweig',
378
+ 'reader.mainline': 'Hauptlinie',
379
+ 'error.title': 'Die Baumansicht ist abgestürzt',
380
+ 'error.reload': 'Ansicht neu laden',
381
+ 'error.hint': 'Die Leinwand-Daten sind sicher; nur diese Darstellung ist fehlgeschlagen.',
382
+ 'error.sessionNotOpen': 'Die Sitzung ist noch nicht geöffnet und kann daher nicht projiziert werden.',
383
+ 'error.noBinding': 'Die Sitzung hat keine Bindung zurückgegeben.',
384
+ 'error.openFailed': 'Sitzung konnte nicht geöffnet werden: {reason}',
385
+ 'error.forkFailed': 'Fork fehlgeschlagen: {reason}',
386
+ 'error.branchUnopenable': 'Die Zweig-Sitzung konnte nicht geöffnet werden: {reason}',
387
+ 'error.branchNoBinding': 'Die Zweig-Sitzung konnte nicht geöffnet werden: {reason}',
388
+ 'error.branchNoUsableBinding': 'Die Zweig-Sitzung hat keine brauchbare Bindung zurückgegeben.',
389
+ 'error.submitFailed': 'Übermittlung fehlgeschlagen: {reason}',
390
+ 'error.loadOlderFailed': 'Frühere Verlaufsdaten konnten nicht geladen werden: {reason}',
391
+ 'view.layoutGroup': 'Layout-Richtung',
392
+ 'view.layoutVertical': 'Oben nach unten',
393
+ },
394
+ es: {
395
+ 'view.tab': 'Exploración infinita',
396
+ 'view.heading': 'Exploración infinita',
397
+ 'view.nodes': '{count} nodos',
398
+ 'view.running': '{count} ramas en curso',
399
+ 'view.runningTitle': 'Ir al siguiente nodo en curso',
400
+ 'view.awaiting': '{count} esperando tu respuesta',
401
+ 'view.awaitingTitle': 'Ir al nodo que espera tu respuesta',
402
+ 'view.loadOlder': 'Cargar anteriores',
403
+ 'view.restoreHidden': '{count} ocultos · Restaurar',
404
+ 'view.restoreHiddenTitle': 'Restaurar los nodos y ramas eliminados',
405
+ 'view.searchPlaceholder': 'Buscar nodos',
406
+ 'view.searchLabel': 'Buscar nodos',
407
+ 'view.zoomGroup': 'Zoom del lienzo',
408
+ 'view.zoomOut': 'Alejar',
409
+ 'view.zoomIn': 'Acercar',
410
+ 'view.zoomLevel': 'Nivel de zoom actual',
411
+ 'view.layoutHorizontal': 'De izquierda a derecha',
412
+ 'view.layoutTitle': 'Alternar entre diseño de izquierda a derecha y de arriba abajo',
413
+ 'view.fit': 'Ajustar lienzo',
414
+ 'view.fitTitle': 'Alejar hasta ver el árbol completo',
415
+ 'view.latest': 'Ir a lo más reciente',
416
+ 'view.latestTitle': 'Expandir la ruta e ir al nodo más reciente',
417
+ 'view.latestTitleEmpty': 'Aún no hay nodos',
418
+ 'view.empty.title': 'Este árbol aún está vacío',
419
+ 'view.empty.hint': 'Pregunta algo en Chat y el primer nodo crecerá aquí.',
420
+ 'view.empty.report': 'Si ya preguntaste y esto sigue vacío, dime: {events} eventos · sesión {state}.',
421
+ 'card.noQuestion': '(sin pregunta)',
422
+ 'card.questionReply': '(respondiendo a la pregunta anterior)',
423
+ 'card.latestBadge': 'Último',
424
+ 'card.latestTitle': 'El nodo más reciente de este árbol',
425
+ 'card.status.thinking': 'Pensando',
426
+ 'card.status.streaming': 'Respondiendo',
427
+ 'card.status.error': 'Error',
428
+ 'card.status.stopped': 'Detenido',
429
+ 'card.status.done': 'Listo',
430
+ 'card.status.awaiting': 'Necesita respuesta',
431
+ 'card.status.awaitingApproval': 'Necesita aprobación',
432
+ 'card.stop': 'Detener',
433
+ 'card.stopTitle': 'Detener esta rama',
434
+ 'card.ask': 'Seguir preguntando en esta rama',
435
+ 'card.more': 'Más acciones',
436
+ 'card.delete': 'Eliminar este nodo',
437
+ 'card.deleteTitle': 'Ocultar este nodo y todas las ramas que cuelgan de él',
438
+ 'card.deleteConfirm': '¿Eliminar este nodo y todas sus ramas? (reversible)',
439
+ 'card.readTitle': 'Haz clic para leer a pantalla completa',
440
+ 'card.expandTitle': 'Expandir esta respuesta',
441
+ 'card.collapseTitle': 'Contraer esta respuesta',
442
+ 'card.expand': 'Expandir respuesta',
443
+ 'card.collapse': 'Contraer respuesta',
444
+ 'card.fullscreen': 'Pantalla completa',
445
+ 'card.fullscreenTitle': 'Leer la respuesta completa a pantalla completa',
446
+ 'card.unfoldBranch': 'Expandir esta rama',
447
+ 'card.foldBranch': 'Contraer esta rama',
448
+ 'card.unfoldDescendants': 'Expandir {count} descendientes',
449
+ 'card.foldDescendants': 'Contraer {count} descendientes',
450
+ 'card.descendants': '{count} descendientes',
451
+ 'card.truncated': '\n\n… (abre a pantalla completa para ver la respuesta completa)',
452
+ 'card.cost.elapsed': 'duró {value}',
453
+ 'card.cost.context': 'contexto {value}',
454
+ 'card.cost.cached': 'caché {value}',
455
+ 'card.think': 'Razonamiento',
456
+ 'card.thinkExpandTitle': 'Expandir el razonamiento',
457
+ 'card.thinkCollapseTitle': 'Contraer el razonamiento',
458
+ 'card.thinkMeta': '{count} caracteres de razonamiento',
459
+ 'card.thinkTruncated': '(solo se conservan los {count} caracteres más recientes del razonamiento)',
460
+ 'live.calling': 'Llamando a {tool}',
461
+ 'live.outputting': 'Escribiendo…',
462
+ 'live.thinking': 'Pensando…',
463
+ 'live.starting': 'Iniciando…',
464
+ 'live.awaiting': 'Esperando tu respuesta…',
465
+ 'live.awaitingApproval': 'Esperando tu aprobación…',
466
+ 'live.step': 'paso {step}',
467
+ 'composer.placeholder': 'Pregunta de nuevo en esta rama… (Enter para enviar, Shift+Enter para nueva línea)',
468
+ 'composer.label': 'Texto de seguimiento',
469
+ 'composer.from': 'A partir de «{question}…»',
470
+ 'composer.cancel': 'Cancelar',
471
+ 'composer.send': 'Enviar',
472
+ 'reader.close': 'Cerrar (Esc)',
473
+ 'reader.closeLabel': 'Cerrar el lector',
474
+ 'reader.noAnswer': '(aún sin respuesta)',
475
+ 'reader.hint': 'Esc o clic en el fondo para cerrar',
476
+ 'reader.branch': 'Rama',
477
+ 'reader.mainline': 'Línea principal',
478
+ 'error.title': 'La vista de árbol falló',
479
+ 'error.reload': 'Recargar la vista',
480
+ 'error.hint': 'Los datos del lienzo están a salvo; solo falló este render.',
481
+ 'error.sessionNotOpen': 'La sesión aún no está abierta, así que no se puede proyectar.',
482
+ 'error.noBinding': 'La sesión no devolvió ninguna vinculación.',
483
+ 'error.openFailed': 'No se pudo abrir la sesión: {reason}',
484
+ 'error.forkFailed': 'Falló la bifurcación: {reason}',
485
+ 'error.branchUnopenable': 'No se pudo abrir la sesión de la rama: {reason}',
486
+ 'error.branchNoBinding': 'No se pudo abrir la sesión de la rama: {reason}',
487
+ 'error.branchNoUsableBinding': 'La sesión de la rama no devolvió una vinculación utilizable.',
488
+ 'error.submitFailed': 'No se pudo enviar: {reason}',
489
+ 'error.loadOlderFailed': 'No se pudo cargar el historial anterior: {reason}',
490
+ 'view.layoutGroup': 'Dirección del diseño',
491
+ 'view.layoutVertical': 'De arriba abajo',
492
+ },
493
+ fr: {
494
+ 'view.tab': 'Exploration infinie',
495
+ 'view.heading': 'Exploration infinie',
496
+ 'view.nodes': '{count} nœuds',
497
+ 'view.running': '{count} branches en cours',
498
+ 'view.runningTitle': 'Aller au prochain nœud en cours',
499
+ 'view.awaiting': '{count} en attente de vous',
500
+ 'view.awaitingTitle': 'Aller au nœud qui attend votre réponse',
501
+ 'view.loadOlder': 'Charger les précédents',
502
+ 'view.restoreHidden': '{count} masqués · Restaurer',
503
+ 'view.restoreHiddenTitle': 'Restaurer les nœuds et branches supprimés',
504
+ 'view.searchPlaceholder': 'Rechercher des nœuds',
505
+ 'view.searchLabel': 'Rechercher des nœuds',
506
+ 'view.zoomGroup': 'Zoom du canevas',
507
+ 'view.zoomOut': 'Dézoomer',
508
+ 'view.zoomIn': 'Zoomer',
509
+ 'view.zoomLevel': 'Niveau de zoom actuel',
510
+ 'view.layoutHorizontal': 'De gauche à droite',
511
+ 'view.layoutTitle': 'Basculer entre disposition de gauche à droite et de haut en bas',
512
+ 'view.fit': 'Ajuster le canevas',
513
+ 'view.fitTitle': 'Dézoomer pour afficher tout l’arbre',
514
+ 'view.latest': 'Aller au plus récent',
515
+ 'view.latestTitle': 'Déplier le chemin et aller au nœud le plus récent',
516
+ 'view.latestTitleEmpty': 'Aucun nœud pour l’instant',
517
+ 'view.empty.title': 'Cet arbre est encore vide',
518
+ 'view.empty.hint': 'Posez une question dans Chat et le premier nœud poussera ici.',
519
+ 'view.empty.report': 'Si vous avez déjà posé une question et que c’est toujours vide, dites-moi : {events} événements · session {state}.',
520
+ 'card.noQuestion': '(aucune question)',
521
+ 'card.questionReply': '(réponse à la question précédente)',
522
+ 'card.latestBadge': 'Dernier',
523
+ 'card.latestTitle': 'Le nœud le plus récent de cet arbre',
524
+ 'card.status.thinking': 'Réflexion',
525
+ 'card.status.streaming': 'Réponse en cours',
526
+ 'card.status.error': 'Erreur',
527
+ 'card.status.stopped': 'Arrêté',
528
+ 'card.status.done': 'Terminé',
529
+ 'card.status.awaiting': 'Réponse attendue',
530
+ 'card.status.awaitingApproval': 'Approbation attendue',
531
+ 'card.stop': 'Arrêter',
532
+ 'card.stopTitle': 'Arrêter cette branche',
533
+ 'card.ask': 'Relancer sur cette branche',
534
+ 'card.more': 'Plus d’actions',
535
+ 'card.delete': 'Supprimer ce nœud',
536
+ 'card.deleteTitle': 'Masquer ce nœud et toutes les branches en dessous',
537
+ 'card.deleteConfirm': 'Supprimer ce nœud et toutes les branches en dessous ? (réversible)',
538
+ 'card.readTitle': 'Cliquez pour lire en plein écran',
539
+ 'card.expandTitle': 'Déplier cette réponse',
540
+ 'card.collapseTitle': 'Replier cette réponse',
541
+ 'card.expand': 'Déplier la réponse',
542
+ 'card.collapse': 'Replier la réponse',
543
+ 'card.fullscreen': 'Plein écran',
544
+ 'card.fullscreenTitle': 'Lire la réponse complète en plein écran',
545
+ 'card.unfoldBranch': 'Déplier cette branche',
546
+ 'card.foldBranch': 'Replier cette branche',
547
+ 'card.unfoldDescendants': 'Déplier {count} descendants',
548
+ 'card.foldDescendants': 'Replier {count} descendants',
549
+ 'card.descendants': '{count} descendants',
550
+ 'card.truncated': '\n\n… (ouvrez le plein écran pour la réponse complète)',
551
+ 'card.cost.elapsed': 'durée {value}',
552
+ 'card.cost.context': 'contexte {value}',
553
+ 'card.cost.cached': 'cache {value}',
554
+ 'card.think': 'Raisonnement',
555
+ 'card.thinkExpandTitle': 'Déplier le raisonnement',
556
+ 'card.thinkCollapseTitle': 'Replier le raisonnement',
557
+ 'card.thinkMeta': '{count} caractères de raisonnement',
558
+ 'card.thinkTruncated': '(seuls les {count} derniers caractères du raisonnement sont conservés)',
559
+ 'live.calling': 'Appel de {tool}',
560
+ 'live.outputting': 'Écriture…',
561
+ 'live.thinking': 'En réflexion…',
562
+ 'live.starting': 'Démarrage…',
563
+ 'live.awaiting': 'En attente de votre réponse…',
564
+ 'live.awaitingApproval': 'En attente de votre approbation…',
565
+ 'live.step': 'étape {step}',
566
+ 'composer.placeholder': 'Relancer sur cette branche… (Entrée pour envoyer, Maj+Entrée pour une nouvelle ligne)',
567
+ 'composer.label': 'Texte de suivi',
568
+ 'composer.from': 'À partir de « {question}… »',
569
+ 'composer.cancel': 'Annuler',
570
+ 'composer.send': 'Envoyer',
571
+ 'reader.close': 'Fermer (Échap)',
572
+ 'reader.closeLabel': 'Fermer le lecteur',
573
+ 'reader.noAnswer': '(pas encore de réponse)',
574
+ 'reader.hint': 'Échap ou clic sur l’arrière-plan pour fermer',
575
+ 'reader.branch': 'Branche',
576
+ 'reader.mainline': 'Ligne principale',
577
+ 'error.title': 'La vue arborescente a planté',
578
+ 'error.reload': 'Recharger la vue',
579
+ 'error.hint': 'Les données du canevas sont intactes ; seul ce rendu a échoué.',
580
+ 'error.sessionNotOpen': 'La session n’est pas encore ouverte ; elle ne peut donc pas être projetée.',
581
+ 'error.noBinding': 'La session n’a renvoyé aucune liaison.',
582
+ 'error.openFailed': 'Impossible d’ouvrir la session : {reason}',
583
+ 'error.forkFailed': 'Échec de l’embranchement : {reason}',
584
+ 'error.branchUnopenable': 'Impossible d’ouvrir la session de la branche : {reason}',
585
+ 'error.branchNoBinding': 'Impossible d’ouvrir la session de la branche : {reason}',
586
+ 'error.branchNoUsableBinding': 'La session de la branche n’a renvoyé aucune liaison utilisable.',
587
+ 'error.submitFailed': 'Échec de l’envoi : {reason}',
588
+ 'error.loadOlderFailed': 'Impossible de charger l’historique précédent : {reason}',
589
+ 'view.layoutGroup': 'Sens de la disposition',
590
+ 'view.layoutVertical': 'De haut en bas',
591
+ },
592
+ ja: {
593
+ 'view.tab': '無限探索',
594
+ 'view.heading': '無限探索',
595
+ 'view.nodes': '{count} 個のノード',
596
+ 'view.running': '{count} ブランチ実行中',
597
+ 'view.runningTitle': '次に実行中のノードへ移動',
598
+ 'view.awaiting': '{count} 件が対応待ち',
599
+ 'view.awaitingTitle': 'あなたの対応を待つノードへ移動',
600
+ 'view.loadOlder': '以前を読み込む',
601
+ 'view.restoreHidden': '{count} 件非表示 · 復元',
602
+ 'view.restoreHiddenTitle': '削除したノードとブランチを復元',
603
+ 'view.searchPlaceholder': 'ノードを検索',
604
+ 'view.searchLabel': 'ノードを検索',
605
+ 'view.zoomGroup': 'キャンバスのズーム',
606
+ 'view.zoomOut': '縮小',
607
+ 'view.zoomIn': '拡大',
608
+ 'view.zoomLevel': '現在のズーム率',
609
+ 'view.layoutHorizontal': '左右配置',
610
+ 'view.layoutTitle': '左右配置と上下配置を切り替える',
611
+ 'view.fit': 'キャンバスに合わせる',
612
+ 'view.fitTitle': 'ツリー全体が見えるまで縮小',
613
+ 'view.latest': '最新へ移動',
614
+ 'view.latestTitle': '経路を展開して最新のノードへ移動',
615
+ 'view.latestTitleEmpty': 'ノードはまだありません',
616
+ 'view.empty.title': 'このツリーはまだ空です',
617
+ 'view.empty.hint': 'Chat で質問すると、ここに最初のノードが生まれます。',
618
+ 'view.empty.report': 'すでに質問したのに空のままなら、次を伝えてください:イベント {events} · セッション {state}。',
619
+ 'card.noQuestion': '(質問なし)',
620
+ 'card.questionReply': '(前の質問への回答)',
621
+ 'card.latestBadge': '最新',
622
+ 'card.latestTitle': 'このツリーで最新のノード',
623
+ 'card.status.thinking': '思考中',
624
+ 'card.status.streaming': '回答中',
625
+ 'card.status.error': 'エラー',
626
+ 'card.status.stopped': '停止しました',
627
+ 'card.status.done': '完了',
628
+ 'card.status.awaiting': '回答待ち',
629
+ 'card.status.awaitingApproval': '承認待ち',
630
+ 'card.stop': '停止',
631
+ 'card.stopTitle': 'このブランチを停止',
632
+ 'card.ask': 'このブランチで追加質問',
633
+ 'card.more': 'その他の操作',
634
+ 'card.delete': 'このノードを削除',
635
+ 'card.deleteTitle': 'このノードとその下のすべてのブランチを非表示',
636
+ 'card.deleteConfirm': 'このノードとその下のすべてのブランチを削除しますか?(復元できます)',
637
+ 'card.readTitle': 'クリックして全画面で読む',
638
+ 'card.expandTitle': 'この回答を展開',
639
+ 'card.collapseTitle': 'この回答を折りたたむ',
640
+ 'card.expand': '回答を展開',
641
+ 'card.collapse': '回答を折りたたむ',
642
+ 'card.fullscreen': '全画面で読む',
643
+ 'card.fullscreenTitle': '完全な回答を全画面で読む',
644
+ 'card.unfoldBranch': 'このブランチを展開',
645
+ 'card.foldBranch': 'このブランチを折りたたむ',
646
+ 'card.unfoldDescendants': '子孫 {count} 件を展開',
647
+ 'card.foldDescendants': '子孫 {count} 件を折りたたむ',
648
+ 'card.descendants': '子孫 {count} 件',
649
+ 'card.truncated': '\n\n…(全画面で完全な回答を表示)',
650
+ 'card.cost.elapsed': '所要 {value}',
651
+ 'card.cost.context': 'コンテキスト {value}',
652
+ 'card.cost.cached': 'キャッシュ {value}',
653
+ 'card.think': '思考',
654
+ 'card.thinkExpandTitle': '思考を展開',
655
+ 'card.thinkCollapseTitle': '思考を折りたたむ',
656
+ 'card.thinkMeta': '思考 {count} 文字',
657
+ 'card.thinkTruncated': '(最新の思考 {count} 文字のみ保持)',
658
+ 'live.calling': '{tool} を呼び出し中',
659
+ 'live.outputting': '出力中…',
660
+ 'live.thinking': '考えています…',
661
+ 'live.starting': '開始中…',
662
+ 'live.awaiting': '回答をお待ちしています…',
663
+ 'live.awaitingApproval': '承認をお待ちしています…',
664
+ 'live.step': 'ステップ {step}',
665
+ 'composer.placeholder': 'このブランチで追加質問…(Enter で送信、Shift+Enter で改行)',
666
+ 'composer.label': '追加質問の内容',
667
+ 'composer.from': '「{question}…」から開始',
668
+ 'composer.cancel': 'キャンセル',
669
+ 'composer.send': '送信',
670
+ 'reader.close': '閉じる(Esc)',
671
+ 'reader.closeLabel': 'リーダーを閉じる',
672
+ 'reader.noAnswer': '(まだ回答はありません)',
673
+ 'reader.hint': 'Esc または背景をクリックで閉じる',
674
+ 'reader.branch': 'ブランチ',
675
+ 'reader.mainline': '本線',
676
+ 'error.title': 'ツリービューでエラーが発生しました',
677
+ 'error.reload': 'ビューを再読み込み',
678
+ 'error.hint': 'キャンバスのデータは失われていません。描画だけが失敗しました。',
679
+ 'error.sessionNotOpen': 'セッションがまだ開いていないため、投影できません。',
680
+ 'error.noBinding': 'セッションからバインディングが返されませんでした。',
681
+ 'error.openFailed': 'セッションを開けませんでした:{reason}',
682
+ 'error.forkFailed': 'フォークに失敗しました:{reason}',
683
+ 'error.branchUnopenable': 'ブランチセッションを開けませんでした:{reason}',
684
+ 'error.branchNoBinding': 'ブランチセッションを開けませんでした:{reason}',
685
+ 'error.branchNoUsableBinding': 'ブランチセッションから使用可能なバインディングが返されませんでした。',
686
+ 'error.submitFailed': '送信に失敗しました:{reason}',
687
+ 'error.loadOlderFailed': '以前の履歴を読み込めませんでした:{reason}',
688
+ 'view.layoutGroup': 'レイアウト方向',
689
+ 'view.layoutVertical': '上から下',
690
+ },
691
+ pt: {
692
+ 'view.tab': 'Exploração infinita',
693
+ 'view.heading': 'Exploração infinita',
694
+ 'view.nodes': '{count} nós',
695
+ 'view.running': '{count} ramos em execução',
696
+ 'view.runningTitle': 'Ir para o próximo nó em execução',
697
+ 'view.awaiting': '{count} aguardando você',
698
+ 'view.awaitingTitle': 'Ir para o nó que aguarda você',
699
+ 'view.loadOlder': 'Carregar anteriores',
700
+ 'view.restoreHidden': '{count} ocultos · Restaurar',
701
+ 'view.restoreHiddenTitle': 'Restaurar nós e ramos excluídos',
702
+ 'view.searchPlaceholder': 'Buscar nós',
703
+ 'view.searchLabel': 'Buscar nós',
704
+ 'view.zoomGroup': 'Zoom do canvas',
705
+ 'view.zoomOut': 'Afastar',
706
+ 'view.zoomIn': 'Aproximar',
707
+ 'view.zoomLevel': 'Nível de zoom atual',
708
+ 'view.layoutHorizontal': 'Da esquerda para a direita',
709
+ 'view.layoutTitle': 'Alternar entre layout da esquerda para a direita e de cima para baixo',
710
+ 'view.fit': 'Ajustar canvas',
711
+ 'view.fitTitle': 'Afastar até mostrar a árvore inteira',
712
+ 'view.latest': 'Ir para o mais recente',
713
+ 'view.latestTitle': 'Expandir o caminho e ir para o nó mais recente',
714
+ 'view.latestTitleEmpty': 'Ainda não há nós',
715
+ 'view.empty.title': 'Esta árvore ainda está vazia',
716
+ 'view.empty.hint': 'Pergunte algo no Chat e o primeiro nó vai crescer aqui.',
717
+ 'view.empty.report': 'Se você já perguntou e isto continua vazio, me diga: {events} eventos · sessão {state}.',
718
+ 'card.noQuestion': '(sem pergunta)',
719
+ 'card.questionReply': '(respondendo à pergunta anterior)',
720
+ 'card.latestBadge': 'Recente',
721
+ 'card.latestTitle': 'O nó mais recente desta árvore',
722
+ 'card.status.thinking': 'Pensando',
723
+ 'card.status.streaming': 'Respondendo',
724
+ 'card.status.error': 'Erro',
725
+ 'card.status.stopped': 'Interrompido',
726
+ 'card.status.done': 'Concluído',
727
+ 'card.status.awaiting': 'Aguardando resposta',
728
+ 'card.status.awaitingApproval': 'Aguardando aprovação',
729
+ 'card.stop': 'Parar',
730
+ 'card.stopTitle': 'Parar este ramo',
731
+ 'card.ask': 'Perguntar novamente neste ramo',
732
+ 'card.more': 'Mais ações',
733
+ 'card.delete': 'Excluir este nó',
734
+ 'card.deleteTitle': 'Ocultar este nó e todos os ramos abaixo dele',
735
+ 'card.deleteConfirm': 'Excluir este nó e todos os ramos abaixo dele? (reversível)',
736
+ 'card.readTitle': 'Clique para ler em tela cheia',
737
+ 'card.expandTitle': 'Expandir esta resposta',
738
+ 'card.collapseTitle': 'Recolher esta resposta',
739
+ 'card.expand': 'Expandir resposta',
740
+ 'card.collapse': 'Recolher resposta',
741
+ 'card.fullscreen': 'Tela cheia',
742
+ 'card.fullscreenTitle': 'Ler a resposta completa em tela cheia',
743
+ 'card.unfoldBranch': 'Expandir este ramo',
744
+ 'card.foldBranch': 'Recolher este ramo',
745
+ 'card.unfoldDescendants': 'Expandir {count} descendentes',
746
+ 'card.foldDescendants': 'Recolher {count} descendentes',
747
+ 'card.descendants': '{count} descendentes',
748
+ 'card.truncated': '\n\n… (abra em tela cheia para ver a resposta completa)',
749
+ 'card.cost.elapsed': 'levou {value}',
750
+ 'card.cost.context': 'contexto {value}',
751
+ 'card.cost.cached': 'cache {value}',
752
+ 'card.think': 'Raciocínio',
753
+ 'card.thinkExpandTitle': 'Expandir o raciocínio',
754
+ 'card.thinkCollapseTitle': 'Recolher o raciocínio',
755
+ 'card.thinkMeta': '{count} caracteres de raciocínio',
756
+ 'card.thinkTruncated': '(apenas os {count} caracteres mais recentes do raciocínio são mantidos)',
757
+ 'live.calling': 'Chamando {tool}',
758
+ 'live.outputting': 'Escrevendo…',
759
+ 'live.thinking': 'Pensando…',
760
+ 'live.starting': 'Iniciando…',
761
+ 'live.awaiting': 'Aguardando sua resposta…',
762
+ 'live.awaitingApproval': 'Aguardando sua aprovação…',
763
+ 'live.step': 'etapa {step}',
764
+ 'composer.placeholder': 'Pergunte novamente neste ramo… (Enter para enviar, Shift+Enter para nova linha)',
765
+ 'composer.label': 'Texto da pergunta',
766
+ 'composer.from': 'A partir de “{question}…”',
767
+ 'composer.cancel': 'Cancelar',
768
+ 'composer.send': 'Enviar',
769
+ 'reader.close': 'Fechar (Esc)',
770
+ 'reader.closeLabel': 'Fechar o leitor',
771
+ 'reader.noAnswer': '(ainda sem resposta)',
772
+ 'reader.hint': 'Esc ou clique no fundo para fechar',
773
+ 'reader.branch': 'Ramo',
774
+ 'reader.mainline': 'Linha principal',
775
+ 'error.title': 'A visualização em árvore falhou',
776
+ 'error.reload': 'Recarregar a visualização',
777
+ 'error.hint': 'Os dados do canvas estão seguros; apenas esta renderização falhou.',
778
+ 'error.sessionNotOpen': 'A sessão ainda não está aberta, então não pode ser projetada.',
779
+ 'error.noBinding': 'A sessão não retornou nenhuma vinculação.',
780
+ 'error.openFailed': 'Não foi possível abrir a sessão: {reason}',
781
+ 'error.forkFailed': 'Falha na bifurcação: {reason}',
782
+ 'error.branchUnopenable': 'Não foi possível abrir a sessão do ramo: {reason}',
783
+ 'error.branchNoBinding': 'Não foi possível abrir a sessão do ramo: {reason}',
784
+ 'error.branchNoUsableBinding': 'A sessão do ramo não retornou uma vinculação utilizável.',
785
+ 'error.submitFailed': 'Falha no envio: {reason}',
786
+ 'error.loadOlderFailed': 'Não foi possível carregar o histórico anterior: {reason}',
787
+ 'view.layoutGroup': 'Direção do layout',
788
+ 'view.layoutVertical': 'De cima para baixo',
789
+ },
790
+ ru: {
791
+ 'view.tab': 'Бесконечное исследование',
792
+ 'view.heading': 'Бесконечное исследование',
793
+ 'view.nodes': 'Узлов: {count}',
794
+ 'view.running': 'Ветки в работе: {count}',
795
+ 'view.runningTitle': 'Перейти к следующему работающему узлу',
796
+ 'view.awaiting': 'Ждут вас: {count}',
797
+ 'view.awaitingTitle': 'Перейти к узлу, который ждёт вас',
798
+ 'view.loadOlder': 'Загрузить ранее',
799
+ 'view.restoreHidden': 'Скрыто {count} · Восстановить',
800
+ 'view.restoreHiddenTitle': 'Восстановить удалённые узлы и ветки',
801
+ 'view.searchPlaceholder': 'Поиск узлов',
802
+ 'view.searchLabel': 'Поиск узлов',
803
+ 'view.zoomGroup': 'Масштаб холста',
804
+ 'view.zoomOut': 'Уменьшить',
805
+ 'view.zoomIn': 'Увеличить',
806
+ 'view.zoomLevel': 'Текущий масштаб',
807
+ 'view.layoutHorizontal': 'Слева направо',
808
+ 'view.layoutTitle': 'Переключить раскладку слева направо и сверху вниз',
809
+ 'view.fit': 'Вписать холст',
810
+ 'view.fitTitle': 'Уменьшить, чтобы показать всё дерево',
811
+ 'view.latest': 'К последнему',
812
+ 'view.latestTitle': 'Развернуть путь и перейти к новейшему узлу',
813
+ 'view.latestTitleEmpty': 'Узлов пока нет',
814
+ 'view.empty.title': 'Это дерево пока пустое',
815
+ 'view.empty.hint': 'Спросите что-нибудь в Chat, и здесь появится первый узел.',
816
+ 'view.empty.report': 'Если вы уже спрашивали, а здесь по-прежнему пусто, сообщите: события {events} · сеанс {state}.',
817
+ 'card.noQuestion': '(без вопроса)',
818
+ 'card.questionReply': '(ответ на предыдущий вопрос)',
819
+ 'card.latestBadge': 'Последний',
820
+ 'card.latestTitle': 'Самый новый узел в этом дереве',
821
+ 'card.status.thinking': 'Думает',
822
+ 'card.status.streaming': 'Отвечает',
823
+ 'card.status.error': 'Ошибка',
824
+ 'card.status.stopped': 'Остановлено',
825
+ 'card.status.done': 'Готово',
826
+ 'card.status.awaiting': 'Нужен ответ',
827
+ 'card.status.awaitingApproval': 'Нужно подтверждение',
828
+ 'card.stop': 'Остановить',
829
+ 'card.stopTitle': 'Остановить эту ветку',
830
+ 'card.ask': 'Задать вопрос на этой ветке',
831
+ 'card.more': 'Ещё действия',
832
+ 'card.delete': 'Удалить этот узел',
833
+ 'card.deleteTitle': 'Скрыть этот узел и все ветки под ним',
834
+ 'card.deleteConfirm': 'Удалить этот узел и все ветки под ним? (обратимо)',
835
+ 'card.readTitle': 'Нажмите, чтобы читать на весь экран',
836
+ 'card.expandTitle': 'Развернуть этот ответ',
837
+ 'card.collapseTitle': 'Свернуть этот ответ',
838
+ 'card.expand': 'Развернуть ответ',
839
+ 'card.collapse': 'Свернуть ответ',
840
+ 'card.fullscreen': 'Во весь экран',
841
+ 'card.fullscreenTitle': 'Прочитать полный ответ во весь экран',
842
+ 'card.unfoldBranch': 'Развернуть эту ветку',
843
+ 'card.foldBranch': 'Свернуть эту ветку',
844
+ 'card.unfoldDescendants': 'Развернуть {count} потомков',
845
+ 'card.foldDescendants': 'Свернуть {count} потомков',
846
+ 'card.descendants': 'Потомков: {count}',
847
+ 'card.truncated': '\n\n… (откройте на весь экран, чтобы прочитать полный ответ)',
848
+ 'card.cost.elapsed': 'заняло {value}',
849
+ 'card.cost.context': 'контекст {value}',
850
+ 'card.cost.cached': 'кэш {value}',
851
+ 'card.think': 'Рассуждения',
852
+ 'card.thinkExpandTitle': 'Развернуть рассуждения',
853
+ 'card.thinkCollapseTitle': 'Свернуть рассуждения',
854
+ 'card.thinkMeta': 'Рассуждения: {count} симв.',
855
+ 'card.thinkTruncated': '(сохранены только последние {count} симв. рассуждений)',
856
+ 'live.calling': 'Вызов {tool}',
857
+ 'live.outputting': 'Пишет…',
858
+ 'live.thinking': 'Думает…',
859
+ 'live.starting': 'Запуск…',
860
+ 'live.awaiting': 'Ждёт вашего ответа…',
861
+ 'live.awaitingApproval': 'Ждёт вашего подтверждения…',
862
+ 'live.step': 'шаг {step}',
863
+ 'composer.placeholder': 'Задайте уточнение на этой ветке… (Enter — отправить, Shift+Enter — новая строка)',
864
+ 'composer.label': 'Текст уточнения',
865
+ 'composer.from': 'Начиная с «{question}…»',
866
+ 'composer.cancel': 'Отмена',
867
+ 'composer.send': 'Отправить',
868
+ 'reader.close': 'Закрыть (Esc)',
869
+ 'reader.closeLabel': 'Закрыть режим чтения',
870
+ 'reader.noAnswer': '(ответа пока нет)',
871
+ 'reader.hint': 'Esc или клик по фону, чтобы закрыть',
872
+ 'reader.branch': 'Ветка',
873
+ 'reader.mainline': 'Основная линия',
874
+ 'error.title': 'Древовидное представление упало',
875
+ 'error.reload': 'Перезагрузить представление',
876
+ 'error.hint': 'Данные холста не потеряны; не удалась только эта отрисовка.',
877
+ 'error.sessionNotOpen': 'Сеанс ещё не открыт, поэтому его нельзя спроецировать.',
878
+ 'error.noBinding': 'Сеанс не вернул привязку.',
879
+ 'error.openFailed': 'Не удалось открыть сеанс: {reason}',
880
+ 'error.forkFailed': 'Не удалось создать ответвление: {reason}',
881
+ 'error.branchUnopenable': 'Не удалось открыть сеанс ветки: {reason}',
882
+ 'error.branchNoBinding': 'Не удалось открыть сеанс ветки: {reason}',
883
+ 'error.branchNoUsableBinding': 'Сеанс ветки не вернул пригодную привязку.',
884
+ 'error.submitFailed': 'Не удалось отправить: {reason}',
885
+ 'error.loadOlderFailed': 'Не удалось загрузить более раннюю историю: {reason}',
886
+ 'view.layoutGroup': 'Направление макета',
887
+ 'view.layoutVertical': 'Сверху вниз',
888
+ },
251
889
  };
252
890
 
253
891
  const localeListeners = new Set();
254
892
 
255
893
  /** Look a key up in the built-in table when the locale service is absent. */
256
894
  function fallbackTranslate(key, params) {
257
- const lang = typeof document !== 'undefined' && document.documentElement.lang
258
- ? String(document.documentElement.lang).slice(0, 2).toLowerCase()
895
+ const raw = typeof document !== 'undefined' && document.documentElement.lang
896
+ ? String(document.documentElement.lang)
259
897
  : 'zh';
260
- const table = DICT[lang] || DICT.zh;
261
- const template = table[key] ?? DICT.zh[key] ?? key;
898
+ // `pt-BR` and `zh-CN` are the same table as `pt` and `zh`; the region
899
+ // subtag only matters to the locale service, not to our flat keys.
900
+ const lang = raw.toLowerCase().split(/[-_]/)[0];
901
+ const table = DICT[lang] || DICT.en;
902
+ const template = table[key] ?? DICT.en[key] ?? DICT.zh[key] ?? key;
262
903
  if (!params) return template;
263
904
  return template.replace(/\{(\w+)\}/g, (match, name) => (name in params ? String(params[name]) : match));
264
905
  }
@@ -300,6 +941,291 @@ window.__ModuleLoader__.load({
300
941
  return event && typeof event.seq === 'number' ? event.seq : 0;
301
942
  }
302
943
 
944
+ // ---------------------------------------------------------------- reasoning
945
+ // The model writes its thinking as `reasoning` content blocks: live as a
946
+ // `reasoning-delta` chunk, and settled as a `{ type: 'reasoning', text }`
947
+ // block inside the durable `assistant/message`. Both reach a client plugin
948
+ // through the same event window, so one accumulator serves the running tail
949
+ // and the finished transcript.
950
+ //
951
+ // A provider that does not think emits no reasoning at all — the card then
952
+ // simply has nothing to show, which is why the section is hidden rather
953
+ // than rendered empty.
954
+
955
+ /** The reasoning blocks inside one assistant message, in order. */
956
+ function reasoningBlocksOfMessage(message) {
957
+ const content = message && message.content;
958
+ if (!Array.isArray(content)) return [];
959
+ const blocks = [];
960
+ for (const block of content) {
961
+ if (block && block.type === 'reasoning' && typeof block.text === 'string' && block.text.trim()) {
962
+ blocks.push(block.text);
963
+ }
964
+ }
965
+ return blocks;
966
+ }
967
+
968
+ /**
969
+ * The key of one reasoning block inside one step.
970
+ *
971
+ * The host frames both the live chunks and the settled message with the
972
+ * same `turn` and `step`, and a step can hold several reasoning blocks
973
+ * (one per content-block index). The index is part of the key so two
974
+ * blocks in the same step do not overwrite each other.
975
+ */
976
+ function reasoningKey(turn, step, index) {
977
+ const base = reasoningStepPrefix(turn, step);
978
+ return typeof index === 'number' ? base + index : base;
979
+ }
980
+
981
+ /**
982
+ * The prefix every reasoning block of one step shares.
983
+ *
984
+ * The trailing separator is what makes the prefix safe: without it, step
985
+ * `1` of turn `1` would also match step `11` of turn `1`.
986
+ */
987
+ function reasoningStepPrefix(turn, step) {
988
+ const base = typeof turn === 'number' && typeof step === 'number'
989
+ ? turn + ':' + step + '#'
990
+ : 'unknown#';
991
+ return base;
992
+ }
993
+
994
+ /**
995
+ * The cap on how much reasoning a card keeps.
996
+ *
997
+ * A long agent turn can think for hundreds of kilobytes. The card shows
998
+ * the newest thinking, so the cap keeps the *tail*: the oldest paragraphs
999
+ * are dropped, and the fact that something was dropped is recorded so the
1000
+ * reader knows the text is not the whole story.
1001
+ *
1002
+ * The cap is enforced inside the accumulator rather than at render time,
1003
+ * so a streaming turn never builds a string larger than this.
1004
+ */
1005
+ const REASONING_LIMIT = 12000;
1006
+
1007
+ /**
1008
+ * A fresh reasoning accumulator: one segment per reasoning block.
1009
+ *
1010
+ * `received` records how many characters each block ever delivered. The
1011
+ * amount dropped is *derived* from it (`received - kept`) rather than
1012
+ * accumulated as a counter: a block is trimmed more than once in normal
1013
+ * use — once while it streams, again when its settled block replaces the
1014
+ * streamed draft — so a running counter would report the same characters
1015
+ * as dropped twice, and would keep claiming a loss after a settled block
1016
+ * replaced a long draft with a short one.
1017
+ */
1018
+ function reasoningState() {
1019
+ return { segments: new Map(), received: new Map() };
1020
+ }
1021
+
1022
+ /**
1023
+ * Count the bytes of a streamed fragment as arrived.
1024
+ *
1025
+ * This must be an addition, not a maximum of the kept length: the trim
1026
+ * cuts the fragment back off immediately, so `kept` plateaus at the cap
1027
+ * and a "max kept" would report one chunk's worth of loss for a turn that
1028
+ * actually dropped tens of kilobytes.
1029
+ */
1030
+ function addReceived(state, key, length) {
1031
+ state.received.set(key, (state.received.get(key) || 0) + length);
1032
+ }
1033
+
1034
+ /**
1035
+ * The two reasoning fields a card needs: the kept text, and how much the
1036
+ * cap dropped. Keeping them separate lets a collapsed row admit that the
1037
+ * text is partial without gluing a notice onto the reasoning itself.
1038
+ */
1039
+ function reasoningFieldsOf(state) {
1040
+ return {
1041
+ reasoning: reasoningTextOf(state),
1042
+ reasoningDropped: droppedReasoningOf(state),
1043
+ };
1044
+ }
1045
+
1046
+ /** Whether a chunk belongs to the model's reasoning. */
1047
+ function isReasoningChunk(chunk) {
1048
+ if (!chunk) return false;
1049
+ if (chunk.type === 'reasoning-delta') return true;
1050
+ if (chunk.type === 'block-end') return Boolean(chunk.block && chunk.block.type === 'reasoning');
1051
+ if (chunk.type === 'block-start') return chunk.blockType === 'reasoning';
1052
+ return false;
1053
+ }
1054
+
1055
+ /**
1056
+ * Fold one live chunk into a reasoning accumulator.
1057
+ *
1058
+ * `reasoning-delta` appends to the block's segment; `block-end` replaces it
1059
+ * with the block the host settled.
1060
+ */
1061
+ function applyReasoningChunk(state, chunk, turn, step) {
1062
+ if (!chunk) return state;
1063
+ const index = typeof chunk.index === 'number' ? chunk.index : undefined;
1064
+ const key = reasoningKey(turn, step, index);
1065
+ if (chunk.type === 'reasoning-delta' && typeof chunk.text === 'string') {
1066
+ const previous = state.segments.get(key);
1067
+ state.segments.set(key, (previous || '') + chunk.text);
1068
+ // Bytes arrived, however much the trim keeps of them.
1069
+ addReceived(state, key, chunk.text.length);
1070
+ trimReasoning(state);
1071
+ return state;
1072
+ }
1073
+ if (chunk.type === 'block-end' && chunk.block && chunk.block.type === 'reasoning'
1074
+ && typeof chunk.block.text === 'string' && chunk.block.text.trim()) {
1075
+ // The settled block is the authoritative full text of this block, so
1076
+ // it replaces both the streamed draft and its arrived-bytes tally.
1077
+ // An empty block says nothing and must not wipe what arrived.
1078
+ state.segments.set(key, chunk.block.text);
1079
+ state.received.set(key, chunk.block.text.length);
1080
+ trimReasoning(state);
1081
+ return state;
1082
+ }
1083
+ if (chunk.type === 'block-start' && chunk.blockType === 'reasoning') {
1084
+ if (!state.segments.has(key)) state.segments.set(key, '');
1085
+ }
1086
+ return state;
1087
+ }
1088
+
1089
+ /**
1090
+ * Merge one settled step's reasoning into the accumulator.
1091
+ *
1092
+ * The settled blocks are that step's complete thinking, so they replace
1093
+ * what was streamed for the step instead of being appended to it.
1094
+ * Transient chunks are retired when the step settles, so the durable
1095
+ * message is the only reliable source once it has landed.
1096
+ */
1097
+ function mergeSettledReasoning(state, blocks, turn, step) {
1098
+ if (!Array.isArray(blocks) || !blocks.length) return state;
1099
+ // Replace the whole step: the settled blocks are the step's final
1100
+ // thinking, and the streamed draft for them is gone by now. The
1101
+ // `received` marks go with them, so a short settled block does not
1102
+ // inherit the draft's dropped-chars claim.
1103
+ const prefix = reasoningStepPrefix(turn, step);
1104
+ for (const key of [...state.segments.keys()]) {
1105
+ if (key.startsWith(prefix)) state.segments.delete(key);
1106
+ }
1107
+ for (const key of [...state.received.keys()]) {
1108
+ if (key.startsWith(prefix)) state.received.delete(key);
1109
+ }
1110
+ blocks.forEach((text, index) => {
1111
+ if (typeof text !== 'string' || !text.trim()) return;
1112
+ const key = reasoningKey(turn, step, index);
1113
+ state.segments.set(key, text);
1114
+ // The settled block is the truth for this block, so it replaces the
1115
+ // streamed tally rather than adding to it.
1116
+ state.received.set(key, text.length);
1117
+ });
1118
+ trimReasoning(state);
1119
+ return state;
1120
+ }
1121
+
1122
+ /**
1123
+ * Drop the reasoning of a retried step.
1124
+ *
1125
+ * A retry reuses the same turn and step, so the failed attempt's thinking
1126
+ * would otherwise be concatenated with the successful one. The attempt
1127
+ * that is about to run starts from a clean slate, which is what the
1128
+ * official Trajectory view does too.
1129
+ */
1130
+ function resetStepReasoning(state, turn, step) {
1131
+ if (!state) return state;
1132
+ const prefix = reasoningStepPrefix(turn, step);
1133
+ for (const key of [...state.segments.keys()]) {
1134
+ if (key.startsWith(prefix)) state.segments.delete(key);
1135
+ }
1136
+ for (const key of [...state.received.keys()]) {
1137
+ if (key.startsWith(prefix)) state.received.delete(key);
1138
+ }
1139
+ return state;
1140
+ }
1141
+
1142
+ /**
1143
+ * Drop the oldest reasoning until the accumulator fits the cap.
1144
+ *
1145
+ * The oldest block goes first: the reader cares about what the agent is
1146
+ * doing now, and the newest blocks are the ones still in play. Trimming
1147
+ * only shortens the kept text — how much was dropped is derived later
1148
+ * from `received`, so trimming twice never double-counts.
1149
+ */
1150
+ function trimReasoning(state) {
1151
+ let total = 0;
1152
+ for (const text of state.segments.values()) total += text.length;
1153
+ if (total <= REASONING_LIMIT) return;
1154
+ for (const [key, text] of state.segments) {
1155
+ if (total <= REASONING_LIMIT) break;
1156
+ const excess = total - REASONING_LIMIT;
1157
+ const cut = Math.min(text.length, excess);
1158
+ if (cut <= 0) continue;
1159
+ state.segments.set(key, text.slice(cut));
1160
+ total -= cut;
1161
+ }
1162
+ }
1163
+
1164
+ /** How many characters the cap has dropped, derived from what arrived. */
1165
+ function droppedReasoningOf(state) {
1166
+ if (!state || !state.segments || !state.received) return 0;
1167
+ let dropped = 0;
1168
+ for (const [key, text] of state.segments) {
1169
+ const received = state.received.get(key) || text.length;
1170
+ if (received > text.length) dropped += received - text.length;
1171
+ }
1172
+ return dropped;
1173
+ }
1174
+
1175
+ /**
1176
+ * The accumulated reasoning, one block's thinking per paragraph group.
1177
+ *
1178
+ * The dropped-chars count is *not* baked into this string: the card needs
1179
+ * it as metadata so a collapsed row can still say the text is partial,
1180
+ * and the reader wants the reasoning itself, not a notice glued to it.
1181
+ */
1182
+ function reasoningTextOf(state) {
1183
+ if (!state || !state.segments) return '';
1184
+ const parts = [];
1185
+ for (const text of state.segments.values()) {
1186
+ if (text && text.trim()) parts.push(text);
1187
+ }
1188
+ return parts.join('\n\n');
1189
+ }
1190
+
1191
+ /**
1192
+ * The one-line summary of a reasoning text: the first line of its last
1193
+ * paragraph.
1194
+ *
1195
+ * A collapsed section shows this so the reader learns what the agent was
1196
+ * up to without opening anything. It is deliberately *not* a copy of the
1197
+ * official Chat row, which picks the last completed paragraph's first line
1198
+ * only while streaming and the first line of the whole text once settled.
1199
+ */
1200
+ function reasoningPreview(text) {
1201
+ if (!text) return '';
1202
+ const source = String(text);
1203
+ // The last paragraph is the freshest thought; take its first line.
1204
+ const paragraphs = source.split(/\r?\n[\t ]*\r?\n/);
1205
+ const last = paragraphs[paragraphs.length - 1] || '';
1206
+ const firstLine = last.split(/\r?\n/).find((line) => line.trim());
1207
+ const chosen = firstLine ? firstLine.trim() : '';
1208
+ return chosen.replace(/\*\*/g, '').slice(0, 200);
1209
+ }
1210
+
1211
+ /**
1212
+ * The newest thing the model wrote, in one line.
1213
+ *
1214
+ * While a branch runs this is the only honest answer to "what is it
1215
+ * doing right now": the most recent line of its thinking, not a summary
1216
+ * of a paragraph it started a while ago.
1217
+ */
1218
+ function reasoningTail(text) {
1219
+ if (!text) return '';
1220
+ const lines = String(text).split(/\r?\n/);
1221
+ for (let index = lines.length - 1; index >= 0; index -= 1) {
1222
+ const trimmed = lines[index].trim();
1223
+ if (!trimmed) continue;
1224
+ return trimmed.replace(/\*\*/g, '').slice(0, 200);
1225
+ }
1226
+ return '';
1227
+ }
1228
+
303
1229
  function maxDurableSeq(entries) {
304
1230
  let max = 0;
305
1231
  for (const entry of entries) {
@@ -415,6 +1341,9 @@ window.__ModuleLoader__.load({
415
1341
  function projectTurns(entries, sessionRunning) {
416
1342
  const turns = [];
417
1343
  let current = null;
1344
+ // Reasoning is accumulated across the whole turn: a turn is one user
1345
+ // question and the model may think in several steps before answering.
1346
+ let reasoning = reasoningState();
418
1347
  for (let index = 0; index < entries.length; index += 1) {
419
1348
  const entry = entries[index];
420
1349
  if (!entry || !entry.event) continue;
@@ -428,6 +1357,13 @@ window.__ModuleLoader__.load({
428
1357
  if (chunk && chunk.type === 'text-delta' && typeof chunk.text === 'string') {
429
1358
  current.streamText = (current.streamText || '') + chunk.text;
430
1359
  current.answer = current.streamText;
1360
+ } else if (chunk && isReasoningChunk(chunk)) {
1361
+ // Only reasoning chunks touch the reasoning text: a text or
1362
+ // tool-call token must not rebuild a multi-kilobyte string.
1363
+ // The host frames a chunk with the same turn/step as the
1364
+ // message that will settle it.
1365
+ applyReasoningChunk(reasoning, chunk, data.turn, data.step);
1366
+ Object.assign(current, reasoningFieldsOf(reasoning));
431
1367
  }
432
1368
  }
433
1369
  continue;
@@ -439,10 +1375,17 @@ window.__ModuleLoader__.load({
439
1375
  real: false, kind: '', costFrom: index, streamText: '',
440
1376
  step: 0, tool: '', startedAt: typeof event.time === 'number' ? event.time : 0,
441
1377
  awaiting: '', pendingQuestions: new Set(), pendingApprovals: new Set(),
1378
+ reasoning: '',
442
1379
  };
1380
+ reasoning = reasoningState();
443
1381
  turns.push(current);
444
1382
  } else if (event.type === 'step/start') {
445
1383
  if (current) current.step = typeof data.step === 'number' ? data.step : current.step + 1;
1384
+ } else if (event.type === 'llm/retry' || event.type === 'llm/retry-started') {
1385
+ // A retry reuses the same turn and step, so the failed attempt's
1386
+ // thinking has to go before the new attempt's arrives.
1387
+ resetStepReasoning(reasoning, data.turn, data.step);
1388
+ if (current) Object.assign(current, reasoningFieldsOf(reasoning));
446
1389
  } else if (event.type === 'tool/call') {
447
1390
  if (current) {
448
1391
  if (data.name) current.tool = String(data.name);
@@ -488,6 +1431,12 @@ window.__ModuleLoader__.load({
488
1431
  target.answer = text;
489
1432
  target.streamText = text;
490
1433
  }
1434
+ // The settled message carries the step's reasoning blocks.
1435
+ const settled = reasoningBlocksOfMessage(data.message);
1436
+ if (settled.length) {
1437
+ mergeSettledReasoning(reasoning, settled, data.turn, data.step);
1438
+ Object.assign(target, reasoningFieldsOf(reasoning));
1439
+ }
491
1440
  target.answerSeq = typeof event.seq === 'number' ? event.seq : target.answerSeq;
492
1441
  }
493
1442
  } else if (event.type === 'turn/end') {
@@ -539,14 +1488,18 @@ window.__ModuleLoader__.load({
539
1488
  let startedAt = 0;
540
1489
  const pendingQuestions = new Set();
541
1490
  const pendingApprovals = new Set();
1491
+ // A branch reasons over its own steps, exactly like the mainline.
1492
+ const reasoning = reasoningState();
542
1493
  const cost = turnCost(entries, baseline);
543
1494
  for (const entry of entries) {
544
1495
  const event = entry && entry.event;
545
1496
  if (!event) continue;
546
1497
  if (entry.type === 'transient') {
547
1498
  if (event.type === 'assistant/live-chunk' && seqOf(entry) > baseline) {
548
- const chunk = event.data && event.data.chunk;
1499
+ const data = event.data || {};
1500
+ const chunk = data.chunk;
549
1501
  if (chunk && chunk.type === 'text-delta' && typeof chunk.text === 'string') text += chunk.text;
1502
+ else if (isReasoningChunk(chunk)) applyReasoningChunk(reasoning, chunk, data.turn, data.step);
550
1503
  }
551
1504
  continue;
552
1505
  }
@@ -562,6 +1515,11 @@ window.__ModuleLoader__.load({
562
1515
  } else if (event.type === 'step/start') {
563
1516
  const data = event.data || {};
564
1517
  step = typeof data.step === 'number' ? data.step : step + 1;
1518
+ } else if (event.type === 'llm/retry' || event.type === 'llm/retry-started') {
1519
+ // A retry reuses the same turn and step, so the failed attempt's
1520
+ // thinking has to go before the new attempt's arrives.
1521
+ const data = event.data || {};
1522
+ resetStepReasoning(reasoning, data.turn, data.step);
565
1523
  } else if (event.type === 'tool/call') {
566
1524
  const data = event.data || {};
567
1525
  if (data.name) tool = String(data.name);
@@ -586,6 +1544,8 @@ window.__ModuleLoader__.load({
586
1544
  answer = finalText;
587
1545
  text = finalText;
588
1546
  }
1547
+ const settled = reasoningBlocksOfMessage(data.message);
1548
+ if (settled.length) mergeSettledReasoning(reasoning, settled, data.turn, data.step);
589
1549
  }
590
1550
  answerSeq = seq;
591
1551
  } else if (event.type === 'turn/end') {
@@ -596,7 +1556,10 @@ window.__ModuleLoader__.load({
596
1556
  }
597
1557
  }
598
1558
  const awaiting = ended ? '' : (pendingQuestions.size ? 'question' : pendingApprovals.size ? 'approval' : '');
599
- return { text, answer, answerSeq, ended, cost, step, tool, startedAt, awaiting };
1559
+ return {
1560
+ text, answer, answerSeq, ended, cost, step, tool, startedAt, awaiting,
1561
+ ...reasoningFieldsOf(reasoning),
1562
+ };
600
1563
  }
601
1564
 
602
1565
  // ----------------------------------------------------------------- layout
@@ -769,13 +1732,70 @@ window.__ModuleLoader__.load({
769
1732
  return result;
770
1733
  }
771
1734
 
772
- function layoutTree(nodes, collapsed, heights) {
1735
+ function layoutTree(nodes, collapsed, heights, direction) {
773
1736
  const childrenOf = childrenMapOf(nodes);
774
1737
  const kids = (node) => (collapsed[node.id] ? [] : childrenOf.get(node.id) || []);
775
1738
  const roots = childrenOf.get('@root') || [];
776
- const widths = new Map();
777
1739
  const depthOf = depthMapOf(nodes);
778
1740
 
1741
+ if (direction === 'horizontal') {
1742
+ const spans = new Map();
1743
+ const positions = new Map();
1744
+ const edges = [];
1745
+ const heightOf = (node) => heights[node.id] || NODE_H;
1746
+ function measure(node) {
1747
+ const list = kids(node);
1748
+ const childSpan = list.reduce((total, child, index) => total + measure(child) + (index ? GAP_X : 0), 0);
1749
+ const span = Math.max(heightOf(node), childSpan);
1750
+ spans.set(node.id, span);
1751
+ return span;
1752
+ }
1753
+ function place(node, top) {
1754
+ const list = kids(node);
1755
+ const ownHeight = heightOf(node);
1756
+ const span = spans.get(node.id);
1757
+ const childSpan = list.reduce((total, child, index) => total + spans.get(child.id) + (index ? GAP_X : 0), 0);
1758
+ let cursor = top + (span - childSpan) / 2;
1759
+ for (const child of list) {
1760
+ place(child, cursor);
1761
+ cursor += spans.get(child.id) + GAP_X;
1762
+ }
1763
+ let center = top + span / 2;
1764
+ if (list.length) {
1765
+ const first = list[0];
1766
+ const last = list[list.length - 1];
1767
+ center = (positions.get(first.id).y + heightOf(first) / 2 + positions.get(last.id).y + heightOf(last) / 2) / 2;
1768
+ }
1769
+ const y = Math.max(top, Math.min(top + span - ownHeight, center - ownHeight / 2));
1770
+ positions.set(node.id, { x: (depthOf.get(node.id) || 0) * (NODE_W + GAP_Y), y });
1771
+ }
1772
+ let top = 0;
1773
+ for (const root of roots) {
1774
+ measure(root);
1775
+ place(root, top);
1776
+ top += spans.get(root.id) + GAP_X * 2;
1777
+ }
1778
+ let maxX = 0;
1779
+ let maxY = 0;
1780
+ for (const node of nodes) {
1781
+ const pos = positions.get(node.id);
1782
+ if (!pos) continue;
1783
+ const height = heightOf(node);
1784
+ maxX = Math.max(maxX, pos.x + NODE_W);
1785
+ maxY = Math.max(maxY, pos.y + height);
1786
+ for (const child of kids(node)) {
1787
+ const childPos = positions.get(child.id);
1788
+ if (childPos) edges.push({
1789
+ id: node.id + '>' + child.id,
1790
+ x1: pos.x + NODE_W, y1: pos.y + height / 2,
1791
+ x2: childPos.x, y2: childPos.y + heightOf(child) / 2,
1792
+ });
1793
+ }
1794
+ }
1795
+ return { positions, edges, width: maxX, height: maxY, roots };
1796
+ }
1797
+
1798
+ const widths = new Map();
779
1799
  const rowHeight = [];
780
1800
  for (const node of nodes) {
781
1801
  const depth = depthOf.get(node.id);
@@ -944,6 +1964,15 @@ window.__ModuleLoader__.load({
944
1964
  function writeNow() {
945
1965
  try {
946
1966
  const payload = {
1967
+ // Reasoning is deliberately NOT persisted here.
1968
+ //
1969
+ // Two reasons. It is re-derived from the session log on every
1970
+ // projection, so a copy here only duplicates bytes. And it is the
1971
+ // one field that can reach tens of kilobytes per node, which is
1972
+ // exactly what would push this snapshot into the localStorage
1973
+ // quota — and this snapshot also holds the parent links, which
1974
+ // are the only thing here that *cannot* be rebuilt. Losing those
1975
+ // flattens the tree, so the large derivable field gives way.
947
1976
  nodes: state.nodes.map((node) => ({
948
1977
  id: node.id,
949
1978
  parentId: node.parentId,
@@ -1034,6 +2063,8 @@ window.__ModuleLoader__.load({
1034
2063
  sessionId: rootId,
1035
2064
  question: turn.question,
1036
2065
  answer: turn.answer,
2066
+ reasoning: turn.reasoning || '',
2067
+ reasoningDropped: turn.reasoningDropped || 0,
1037
2068
  status: turn.status,
1038
2069
  answerSeq: turn.answerSeq,
1039
2070
  kind: 'root',
@@ -1051,6 +2082,8 @@ window.__ModuleLoader__.load({
1051
2082
  existing.parentId !== next.parentId ||
1052
2083
  existing.question !== next.question ||
1053
2084
  existing.answer !== next.answer ||
2085
+ (existing.reasoning || '') !== next.reasoning ||
2086
+ (existing.reasoningDropped || 0) !== next.reasoningDropped ||
1054
2087
  existing.answerSeq !== next.answerSeq ||
1055
2088
  existing.status !== next.status ||
1056
2089
  (existing.awaiting || '') !== next.awaiting ||
@@ -1440,6 +2473,10 @@ window.__ModuleLoader__.load({
1440
2473
  if (read2.answerSeq) changes.answerSeq = read2.answerSeq;
1441
2474
  if (read2.step !== (current.step || 0)) changes.step = read2.step;
1442
2475
  if (read2.tool !== (current.tool || '')) changes.tool = read2.tool;
2476
+ if ((read2.reasoning || '') !== (current.reasoning || '')) changes.reasoning = read2.reasoning || '';
2477
+ if ((read2.reasoningDropped || 0) !== (current.reasoningDropped || 0)) {
2478
+ changes.reasoningDropped = read2.reasoningDropped || 0;
2479
+ }
1443
2480
  const awaiting = read2.awaiting || '';
1444
2481
  if (awaiting !== (current.awaiting || '')) changes.awaiting = awaiting;
1445
2482
  if (read2.startedAt && read2.startedAt !== current.startedAt) changes.startedAt = read2.startedAt;
@@ -1570,6 +2607,15 @@ window.__ModuleLoader__.load({
1570
2607
  const awaiting = read.awaiting || '';
1571
2608
  const node = store.getNode(nodeId);
1572
2609
  if (node && awaiting !== (node.awaiting || '')) store.patch(nodeId, { awaiting });
2610
+ // The branch's reasoning arrives with the same events as its answer,
2611
+ // so it is patched in the same breath.
2612
+ if (node && ((read.reasoning || '') !== (node.reasoning || '')
2613
+ || (read.reasoningDropped || 0) !== (node.reasoningDropped || 0))) {
2614
+ store.patch(nodeId, {
2615
+ reasoning: read.reasoning || '',
2616
+ reasoningDropped: read.reasoningDropped || 0,
2617
+ });
2618
+ }
1573
2619
  if (read.ended) {
1574
2620
  unsubscribe();
1575
2621
  try {
@@ -1609,67 +2655,302 @@ window.__ModuleLoader__.load({
1609
2655
  // -------------------------------------------------------------- markdown
1610
2656
  const MD = {
1611
2657
  body: { fontSize: 12, lineHeight: 1.72, color: C.ink2, wordBreak: 'break-word' },
1612
- h1: { fontSize: '1.14em', fontWeight: 700, color: C.ink, margin: '0.62em 0 0.28em', lineHeight: 1.4 },
1613
- h2: { fontSize: '1.08em', fontWeight: 700, color: C.ink, margin: '0.58em 0 0.24em', lineHeight: 1.4 },
1614
- h3: { fontSize: '1.02em', fontWeight: 600, color: C.ink, margin: '0.52em 0 0.22em', lineHeight: 1.4 },
2658
+ h1: { fontSize: '1.3em', fontWeight: 700, color: C.ink, margin: '0.7em 0 0.3em', lineHeight: 1.35 },
2659
+ h2: { fontSize: '1.16em', fontWeight: 700, color: C.ink, margin: '0.65em 0 0.28em', lineHeight: 1.38 },
2660
+ h3: { fontSize: '1.06em', fontWeight: 600, color: C.ink, margin: '0.58em 0 0.24em', lineHeight: 1.4 },
2661
+ h4: { fontSize: '1.01em', fontWeight: 600, color: C.ink, margin: '0.52em 0 0.22em', lineHeight: 1.42 },
2662
+ h5: { fontSize: '0.98em', fontWeight: 600, color: C.ink3, margin: '0.48em 0 0.2em', lineHeight: 1.42 },
2663
+ h6: { fontSize: '0.96em', fontWeight: 600, color: C.ink3, margin: '0.44em 0 0.18em', lineHeight: 1.42 },
1615
2664
  p: { margin: '0 0 0.5em' },
1616
- ul: { margin: '0 0 0.5em', paddingLeft: '1.5em' },
2665
+ ul: { margin: '0 0 0.5em', paddingLeft: '1.4em' },
1617
2666
  ol: { margin: '0 0 0.5em', paddingLeft: '1.5em' },
1618
2667
  li: { margin: '0 0 0.16em' },
2668
+ checkbox: { marginRight: '0.4em', verticalAlign: 'middle' },
1619
2669
  quote: {
1620
2670
  margin: '0 0 0.5em', paddingLeft: '0.75em', borderLeft: '2px solid ' + C.line,
1621
2671
  color: C.ink3,
1622
2672
  },
1623
2673
  hr: { border: 'none', borderTop: '1px solid ' + C.line, margin: '0.75em 0' },
1624
2674
  codeBlock: {
1625
- margin: '0 0 0.6em', padding: '0.55em 0.75em', borderRadius: 6, background: C.code,
2675
+ margin: 0, padding: '0.55em 0.75em', borderRadius: 6, background: C.code,
1626
2676
  border: '1px solid ' + C.line, fontFamily: MONO,
1627
2677
  fontSize: '0.9em', lineHeight: 1.6, whiteSpace: 'pre-wrap', overflowX: 'auto', color: C.ink,
1628
2678
  },
2679
+ codeLang: {
2680
+ margin: '0 0 0.3em', fontSize: '0.78em', letterSpacing: '0.04em',
2681
+ color: C.ink4, fontFamily: MONO, textTransform: 'uppercase',
2682
+ },
1629
2683
  inlineCode: {
1630
2684
  fontFamily: MONO, fontSize: '0.92em',
1631
2685
  background: C.codeInline, borderRadius: 3, padding: '0 0.28em', color: C.ink,
1632
2686
  },
1633
2687
  link: { color: C.accent, textDecoration: 'none' },
2688
+ image: {
2689
+ display: 'block', maxWidth: '100%', height: 'auto',
2690
+ margin: '0.4em 0', borderRadius: 6,
2691
+ },
1634
2692
  strong: { fontWeight: 700, color: C.ink },
1635
2693
  };
1636
2694
 
2695
+ /*
2696
+ * Why this is a renderer and not a Markdown library.
2697
+ *
2698
+ * The view has no dependencies and ships as one file the host loads, so it
2699
+ * cannot pull in a parser. What it can do is cover the subset an answer
2700
+ * actually uses and be explicit about the rest: reference links, footnotes
2701
+ * and raw HTML blocks are passed through as text rather than half-rendered.
2702
+ *
2703
+ * Raw HTML is never injected — every string here becomes a React text node,
2704
+ * so a model that writes a script tag gets the characters, not an element.
2705
+ * That is also why this is safe to run on model output.
2706
+ */
2707
+
2708
+ /** Only these schemes may become a live link. */
2709
+ function safeHref(raw) {
2710
+ const url = String(raw || '').trim();
2711
+ if (!url) return null;
2712
+ if (/^(https?:|mailto:)/i.test(url)) return url;
2713
+ // Relative links and fragment anchors are fine. Anything else — notably
2714
+ // javascript: and data: — would turn model output into script execution.
2715
+ if (/^(\/|\.{1,2}\/|#)/.test(url)) return url;
2716
+ return null;
2717
+ }
2718
+
2719
+ /** Strip the angle brackets or quotes a URL may be wrapped in. */
2720
+ function cleanUrl(raw) {
2721
+ return String(raw || '').trim().replace(/^<|>$/g, '').replace(/^["']|["']$/g, '');
2722
+ }
2723
+
2724
+ /** Index of the closing `marker` at or after `from`, or -1 when unclosed. */
2725
+ function closeOf(text, from, marker) {
2726
+ let found = text.indexOf(marker, from);
2727
+ while (found >= 0) {
2728
+ if (text[found - 1] !== '\\') return found;
2729
+ found = text.indexOf(marker, found + marker.length);
2730
+ }
2731
+ return -1;
2732
+ }
2733
+
2734
+ /**
2735
+ * Inline Markdown: escapes, code spans, emphasis, strikethrough, images,
2736
+ * links, autolinks and hard breaks.
2737
+ */
1637
2738
  function inlineNodes(text, keyBase) {
1638
2739
  const out = [];
1639
- const pattern = /(\*\*[^*\n]+\*\*|__[^_\n]+__|`[^`\n]+`|\[[^\]\n]+\]\([^)\s]+\)|\*[^*\n]+\*)/g;
1640
- let last = 0;
1641
- let match;
2740
+ const source = String(text === undefined || text === null ? '' : text);
2741
+ let buffer = '';
1642
2742
  let index = 0;
1643
- while ((match = pattern.exec(text)) !== null) {
1644
- if (match.index > last) out.push(text.slice(last, match.index));
1645
- const token = match[0];
1646
- const key = keyBase + '-' + index;
1647
- index += 1;
1648
- if (token.startsWith('**') || token.startsWith('__')) {
1649
- out.push(h('strong', { key, style: MD.strong }, token.slice(2, -2)));
1650
- } else if (token.startsWith('`')) {
1651
- out.push(h('code', { key, style: MD.inlineCode }, token.slice(1, -1)));
1652
- } else if (token.startsWith('[')) {
1653
- const link = /^\[([^\]]+)\]\(([^)]+)\)$/.exec(token);
1654
- out.push(h('a', {
1655
- key,
1656
- href: link ? link[2] : '#',
1657
- target: '_blank',
1658
- rel: 'noreferrer noopener',
1659
- style: MD.link,
1660
- }, link ? link[1] : token));
1661
- } else {
1662
- out.push(h('em', { key }, token.slice(1, -1)));
2743
+ const nextKey = () => keyBase + '-' + (index++);
2744
+ const flush = () => { if (buffer) { out.push(buffer); buffer = ''; } };
2745
+ let i = 0;
2746
+ while (i < source.length) {
2747
+ const ch = source[i];
2748
+ // Backslash escape: the next character is literal.
2749
+ if (ch === '\\' && i + 1 < source.length && /[\\`*_{}[\]()#+\-.!>~|]/.test(source[i + 1])) {
2750
+ buffer += source[i + 1];
2751
+ i += 2;
2752
+ continue;
2753
+ }
2754
+ // A backslash at the end of a line is a hard break.
2755
+ if (ch === '\\' && source[i + 1] === '\n') {
2756
+ flush();
2757
+ out.push(h('br', { key: nextKey() }));
2758
+ i += 2;
2759
+ continue;
2760
+ }
2761
+ if (ch === '\n') {
2762
+ // Two trailing spaces are a hard break; any other newline is a space,
2763
+ // since a card is a narrow column where a stray newline reads as a
2764
+ // broken word.
2765
+ if (/ $/.test(buffer)) {
2766
+ buffer = buffer.replace(/ +$/, '');
2767
+ flush();
2768
+ out.push(h('br', { key: nextKey() }));
2769
+ } else {
2770
+ buffer += ' ';
2771
+ }
2772
+ i += 1;
2773
+ continue;
1663
2774
  }
1664
- last = match.index + token.length;
2775
+ // Code span: a run of N backticks closed by the same run.
2776
+ if (ch === '`') {
2777
+ const run = /^`+/.exec(source.slice(i))[0];
2778
+ const close = source.indexOf(run, i + run.length);
2779
+ if (close > i) {
2780
+ flush();
2781
+ const inner = source.slice(i + run.length, close).replace(/^ | $/g, '');
2782
+ out.push(h('code', { key: nextKey(), style: MD.inlineCode }, inner));
2783
+ i = close + run.length;
2784
+ continue;
2785
+ }
2786
+ }
2787
+ // Image: ![alt](src "title")
2788
+ if (ch === '!' && source[i + 1] === '[') {
2789
+ const match = /^!\[([^\]]*)\]\(\s*((?:[^()\s]|\([^()]*\))+)(?:\s+"([^"]*)")?\s*\)/.exec(source.slice(i));
2790
+ if (match) {
2791
+ flush();
2792
+ const href = safeHref(cleanUrl(match[2]));
2793
+ if (href) {
2794
+ out.push(h('img', {
2795
+ key: nextKey(), src: href, alt: match[1] || '',
2796
+ title: match[3] || undefined, loading: 'lazy', style: MD.image,
2797
+ }));
2798
+ } else {
2799
+ out.push(match[1] || match[2]);
2800
+ }
2801
+ i += match[0].length;
2802
+ continue;
2803
+ }
2804
+ }
2805
+ // Link: [text](href "title")
2806
+ if (ch === '[') {
2807
+ const match = /^\[([^\]]*)\]\(\s*((?:[^()\s]|\([^()]*\))+)(?:\s+"([^"]*)")?\s*\)/.exec(source.slice(i));
2808
+ if (match) {
2809
+ flush();
2810
+ const href = safeHref(cleanUrl(match[2]));
2811
+ const label = match[1] || match[2];
2812
+ if (href) {
2813
+ out.push(h('a', {
2814
+ key: nextKey(), href, target: '_blank', rel: 'noreferrer noopener',
2815
+ title: match[3] || undefined, style: MD.link,
2816
+ }, inlineNodes(label, nextKey())));
2817
+ } else {
2818
+ out.push(label);
2819
+ }
2820
+ i += match[0].length;
2821
+ continue;
2822
+ }
2823
+ }
2824
+ // Autolink: <https://example.com>
2825
+ if (ch === '<') {
2826
+ const match = /^<((?:https?:|mailto:)[^>\s]+)>/.exec(source.slice(i));
2827
+ if (match) {
2828
+ flush();
2829
+ out.push(h('a', {
2830
+ key: nextKey(), href: match[1], target: '_blank',
2831
+ rel: 'noreferrer noopener', style: MD.link,
2832
+ }, match[1].replace(/^mailto:/, '')));
2833
+ i += match[0].length;
2834
+ continue;
2835
+ }
2836
+ }
2837
+ // A bare URL outside a link is still a link.
2838
+ if ((ch === 'h' || ch === 'H') && /^https?:\/\//i.test(source.slice(i, i + 8))) {
2839
+ const match = /^https?:\/\/[^\s<>()]+/i.exec(source.slice(i));
2840
+ if (match) {
2841
+ const url = match[0].replace(/[.,;:!?'"]+$/, '');
2842
+ flush();
2843
+ out.push(h('a', {
2844
+ key: nextKey(), href: url, target: '_blank',
2845
+ rel: 'noreferrer noopener', style: MD.link,
2846
+ }, url));
2847
+ i += url.length;
2848
+ continue;
2849
+ }
2850
+ }
2851
+ // Strikethrough, strong and emphasis. The inner text is parsed again so
2852
+ // that strong-wrapping-code and nested emphasis come out right.
2853
+ if (ch === '~' && source[i + 1] === '~') {
2854
+ const close = closeOf(source, i + 2, '~~');
2855
+ if (close > i) {
2856
+ flush();
2857
+ out.push(h('del', { key: nextKey() }, inlineNodes(source.slice(i + 2, close), nextKey())));
2858
+ i = close + 2;
2859
+ continue;
2860
+ }
2861
+ }
2862
+ if ((ch === '*' && source[i + 1] === '*') || (ch === '_' && source[i + 1] === '_')) {
2863
+ const marker = ch + ch;
2864
+ const close = closeOf(source, i + 2, marker);
2865
+ if (close > i) {
2866
+ flush();
2867
+ out.push(h('strong', { key: nextKey(), style: MD.strong },
2868
+ inlineNodes(source.slice(i + 2, close), nextKey())));
2869
+ i = close + 2;
2870
+ continue;
2871
+ }
2872
+ }
2873
+ if (ch === '*' || ch === '_') {
2874
+ const close = closeOf(source, i + 1, ch);
2875
+ if (close > i) {
2876
+ flush();
2877
+ out.push(h('em', { key: nextKey() }, inlineNodes(source.slice(i + 1, close), nextKey())));
2878
+ i = close + 1;
2879
+ continue;
2880
+ }
2881
+ }
2882
+ buffer += ch;
2883
+ i += 1;
1665
2884
  }
1666
- if (last < text.length) out.push(text.slice(last));
2885
+ flush();
1667
2886
  return out;
1668
2887
  }
1669
2888
 
1670
- /** Small block-level Markdown renderer: headings, lists, quotes, fences, rules, paragraphs. */
2889
+ /** Leading indentation of a line, with tabs counted as four spaces. */
2890
+ function indentOf(line) {
2891
+ const lead = /^[ \t]*/.exec(line)[0];
2892
+ return lead.replace(/\t/g, ' ').length;
2893
+ }
2894
+
2895
+ /**
2896
+ * Read one list block, including nesting.
2897
+ *
2898
+ * The walk is indentation-based: an item at the list's own indent starts a
2899
+ * new entry, and anything deeper belongs to the entry above and is rendered
2900
+ * as nested blocks — which is what makes a sub-bullet read as a child
2901
+ * instead of a second flat item, the single most common shape in an answer.
2902
+ */
2903
+ function parseListBlock(lines, start) {
2904
+ const ordered = /^\s*\d+[.)]\s+/.test(lines[start]);
2905
+ const baseIndent = indentOf(lines[start]);
2906
+ const itemRe = ordered ? /^(\s*)(\d+)[.)]\s+(.*)$/ : /^(\s*)[-*+]\s+(.*)$/;
2907
+ const items = [];
2908
+ let startNumber = 1;
2909
+ let i = start;
2910
+ while (i < lines.length) {
2911
+ const line = lines[i];
2912
+ if (/^\s*$/.test(line)) {
2913
+ // A blank line only ends the list when the next non-blank line is not
2914
+ // another item of this list.
2915
+ let j = i + 1;
2916
+ while (j < lines.length && /^\s*$/.test(lines[j])) j += 1;
2917
+ if (j < lines.length && indentOf(lines[j]) === baseIndent && itemRe.test(lines[j])) {
2918
+ i = j;
2919
+ continue;
2920
+ }
2921
+ break;
2922
+ }
2923
+ const match = itemRe.exec(line);
2924
+ const indent = indentOf(line);
2925
+ if (match && indent === baseIndent) {
2926
+ if (ordered && items.length === 0) startNumber = parseInt(match[2], 10) || 1;
2927
+ items.push({ text: ordered ? match[3] : match[2], rest: [] });
2928
+ i += 1;
2929
+ continue;
2930
+ }
2931
+ if (!items.length) break;
2932
+ if (indent > baseIndent) {
2933
+ items[items.length - 1].rest.push(line.slice(Math.min(indent, baseIndent + 2)));
2934
+ i += 1;
2935
+ continue;
2936
+ }
2937
+ break;
2938
+ }
2939
+ return { items, ordered, startNumber, next: i };
2940
+ }
2941
+
2942
+ /** A fenced code block, with its info string kept as a visible label. */
2943
+ function renderCodeBlock(language, body, key) {
2944
+ const lang = String(language || '').trim().split(/\s+/)[0];
2945
+ const label = lang ? h('div', { style: MD.codeLang }, lang) : null;
2946
+ return h('div', { key, style: { margin: '0 0 0.6em' } },
2947
+ label,
2948
+ h('pre', { style: MD.codeBlock }, body.join('\n')));
2949
+ }
2950
+
2951
+ /** Small block-level Markdown renderer. */
1671
2952
  function renderMarkdown(text) {
1672
- const source = String(text || '').replace(/\r\n/g, '\n');
2953
+ const source = String(text || '').replace(/\r\n?/g, '\n');
1673
2954
  if (!source.trim()) return null;
1674
2955
  const lines = source.split('\n');
1675
2956
  const blocks = [];
@@ -1678,82 +2959,201 @@ window.__ModuleLoader__.load({
1678
2959
 
1679
2960
  while (i < lines.length) {
1680
2961
  const line = lines[i];
1681
- const fence = /^\s*```(.*)$/.exec(line);
2962
+ if (/^\s*$/.test(line)) { i += 1; continue; }
2963
+
2964
+ // Fenced code: three or more backticks or tildes, closed by at least as
2965
+ // many of the same character.
2966
+ const fence = /^\s*(`{3,}|~{3,})(.*)$/.exec(line);
1682
2967
  if (fence) {
2968
+ const marker = fence[1];
2969
+ const closer = new RegExp('^\\s*' + (marker[0] === '`' ? '`' : '~') + '{' + marker.length + ',}\\s*$');
1683
2970
  const body = [];
1684
2971
  i += 1;
1685
- while (i < lines.length && !/^\s*```/.test(lines[i])) {
2972
+ while (i < lines.length && !closer.test(lines[i])) {
1686
2973
  body.push(lines[i]);
1687
2974
  i += 1;
1688
2975
  }
1689
2976
  i += 1;
1690
- blocks.push(h('pre', { key: 'b' + blockKey, style: MD.codeBlock }, body.join('\n')));
2977
+ blocks.push(renderCodeBlock(fence[2], body, 'b' + blockKey));
1691
2978
  blockKey += 1;
1692
2979
  continue;
1693
2980
  }
1694
- if (/^\s*$/.test(line)) { i += 1; continue; }
1695
- if (/^#{1,6}\s+/.test(line)) {
1696
- const level = line.match(/^#+/)[0].length;
1697
- const content = line.replace(/^#+\s+/, '');
1698
- const style = level === 1 ? MD.h1 : level === 2 ? MD.h2 : MD.h3;
1699
- blocks.push(h('div', { key: 'b' + blockKey, style }, inlineNodes(content, 'h' + blockKey)));
2981
+
2982
+ // Indented code block: four spaces. A list continuation never reaches
2983
+ // here, because the list branch above consumes it.
2984
+ if (/^ {4}\S/.test(line)) {
2985
+ const body = [];
2986
+ while (i < lines.length && (/^ {4}/.test(lines[i]) || /^\s*$/.test(lines[i]))) {
2987
+ body.push(lines[i].replace(/^ {4}/, ''));
2988
+ i += 1;
2989
+ }
2990
+ while (body.length && /^\s*$/.test(body[body.length - 1])) body.pop();
2991
+ blocks.push(renderCodeBlock('', body, 'b' + blockKey));
2992
+ blockKey += 1;
2993
+ continue;
2994
+ }
2995
+
2996
+ // ATX heading -> a real heading element, so the reader has a document
2997
+ // structure and a screen reader announces it as one.
2998
+ const atx = /^(#{1,6})\s+(.*?)\s*#*\s*$/.exec(line);
2999
+ if (atx) {
3000
+ const level = atx[1].length;
3001
+ blocks.push(h('h' + level, { key: 'b' + blockKey, style: MD['h' + level] },
3002
+ inlineNodes(atx[2], 'h' + blockKey)));
1700
3003
  blockKey += 1;
1701
3004
  i += 1;
1702
3005
  continue;
1703
3006
  }
1704
- if (/^\s*([-*_])\s*\1\s*\1[\s\-*_]*$/.test(line) || /^\s*---+\s*$/.test(line)) {
3007
+
3008
+ // Setext heading: a text line underlined by === or ---.
3009
+ if (i + 1 < lines.length && /^\s*(=+|-{2,})\s*$/.test(lines[i + 1])
3010
+ && !/^\s*([-*+]|\d+[.)])\s+/.test(line) && !/^\s*\|/.test(line)) {
3011
+ const level = /^\s*=/.test(lines[i + 1]) ? 1 : 2;
3012
+ blocks.push(h('h' + level, { key: 'b' + blockKey, style: MD['h' + level] },
3013
+ inlineNodes(line.trim(), 'h' + blockKey)));
3014
+ blockKey += 1;
3015
+ i += 2;
3016
+ continue;
3017
+ }
3018
+
3019
+ if (/^\s*([-*_])\s*\1\s*\1[\s\-*_]*$/.test(line)) {
1705
3020
  blocks.push(h('hr', { key: 'b' + blockKey, style: MD.hr }));
1706
3021
  blockKey += 1;
1707
3022
  i += 1;
1708
3023
  continue;
1709
3024
  }
1710
- if (/^\s*[-*+]\s+/.test(line)) {
1711
- const items = [];
1712
- while (i < lines.length && /^\s*[-*+]\s+/.test(lines[i])) {
1713
- items.push(lines[i].replace(/^\s*[-*+]\s+/, ''));
1714
- i += 1;
1715
- }
1716
- blocks.push(h('ul', { key: 'b' + blockKey, style: MD.ul },
1717
- items.map((item, n) => h('li', { key: 'l' + n, style: MD.li }, inlineNodes(item, 'b' + blockKey + '-' + n)))));
3025
+
3026
+ if (/^\s*[-*+]\s+/.test(line) || /^\s*\d+[.)]\s+/.test(line)) {
3027
+ const parsed = parseListBlock(lines, i);
3028
+ i = parsed.next;
3029
+ const tag = parsed.ordered ? 'ol' : 'ul';
3030
+ blocks.push(h(tag, {
3031
+ key: 'b' + blockKey,
3032
+ style: parsed.ordered ? MD.ol : MD.ul,
3033
+ start: parsed.ordered && parsed.startNumber !== 1 ? parsed.startNumber : undefined,
3034
+ }, parsed.items.map((item, n) => {
3035
+ const task = /^\[([ xX])\]\s+/.exec(item.text);
3036
+ const content = task ? item.text.slice(task[0].length) : item.text;
3037
+ const children = [];
3038
+ if (task) {
3039
+ children.push(h('input', {
3040
+ key: 't' + n, type: 'checkbox', checked: task[1] !== ' ',
3041
+ disabled: true, readOnly: true, style: MD.checkbox,
3042
+ }));
3043
+ }
3044
+ children.push(...inlineNodes(content, 'b' + blockKey + '-' + n));
3045
+ if (item.rest.length) children.push(...(renderMarkdown(item.rest.join('\n')) || []));
3046
+ return h('li', { key: 'l' + n, style: MD.li }, children);
3047
+ })));
1718
3048
  blockKey += 1;
1719
3049
  continue;
1720
3050
  }
1721
- if (/^\s*\d+[.)]\s+/.test(line)) {
1722
- const items = [];
1723
- while (i < lines.length && /^\s*\d+[.)]\s+/.test(lines[i])) {
1724
- items.push(lines[i].replace(/^\s*\d+[.)]\s+/, ''));
3051
+
3052
+ // Block quote: recurse, so a list or a fence inside a quote renders.
3053
+ if (/^\s*>/.test(line)) {
3054
+ const quoted = [];
3055
+ while (i < lines.length && (/^\s*>/.test(lines[i]) || /^\s*$/.test(lines[i]))) {
3056
+ if (/^\s*$/.test(lines[i])) {
3057
+ const next = lines[i + 1];
3058
+ if (next === undefined || !/^\s*>/.test(next)) break;
3059
+ quoted.push('');
3060
+ i += 1;
3061
+ continue;
3062
+ }
3063
+ quoted.push(lines[i].replace(/^\s*>\s?/, ''));
1725
3064
  i += 1;
1726
3065
  }
1727
- blocks.push(h('ol', { key: 'b' + blockKey, style: MD.ol },
1728
- items.map((item, n) => h('li', { key: 'l' + n, style: MD.li }, inlineNodes(item, 'b' + blockKey + '-' + n)))));
3066
+ blocks.push(h('blockquote', { key: 'b' + blockKey, style: MD.quote },
3067
+ renderMarkdown(quoted.join('\n')) || null));
1729
3068
  blockKey += 1;
1730
3069
  continue;
1731
3070
  }
1732
- if (/^\s*>\s?/.test(line)) {
1733
- const quoted = [];
1734
- while (i < lines.length && /^\s*>\s?/.test(lines[i])) {
1735
- quoted.push(lines[i].replace(/^\s*>\s?/, ''));
3071
+
3072
+ // A GFM table: a pipe row whose next line is the delimiter row. The
3073
+ // delimiter is what separates a table from prose containing pipes.
3074
+ if (/\|/.test(line) && i + 1 < lines.length && isTableDelimiter(lines[i + 1])) {
3075
+ const aligns = splitTableRow(lines[i + 1]).map((cell) => {
3076
+ const left = cell.startsWith(':');
3077
+ const right = cell.endsWith(':');
3078
+ return left && right ? 'center' : right ? 'right' : 'left';
3079
+ });
3080
+ const header = splitTableRow(line);
3081
+ i += 2;
3082
+ const rows = [];
3083
+ while (i < lines.length && /\|/.test(lines[i]) && !/^\s*$/.test(lines[i])) {
3084
+ rows.push(splitTableRow(lines[i]));
1736
3085
  i += 1;
1737
3086
  }
1738
- blocks.push(h('div', { key: 'b' + blockKey, style: MD.quote },
1739
- inlineNodes(quoted.join(' '), 'q' + blockKey)));
3087
+ const cellStyle = (index) => ({ textAlign: aligns[index] || 'left' });
3088
+ blocks.push(h('div', { key: 'b' + blockKey, className: 'dsh-tree-table-wrap' },
3089
+ h('table', { className: 'dsh-tree-table' },
3090
+ h('thead', null,
3091
+ h('tr', null, header.map((cell, index) => h('th', {
3092
+ key: 'h' + index,
3093
+ style: cellStyle(index),
3094
+ }, inlineNodes(cell, 'th' + blockKey + '-' + index))))),
3095
+ h('tbody', null, rows.map((row, rowIndex) => h('tr', { key: 'r' + rowIndex },
3096
+ row.map((cell, index) => h('td', {
3097
+ key: 'c' + index,
3098
+ style: cellStyle(index),
3099
+ }, inlineNodes(cell, 'td' + blockKey + '-' + rowIndex + '-' + index)))))))));
1740
3100
  blockKey += 1;
1741
3101
  continue;
1742
3102
  }
3103
+
3104
+ // Paragraph: runs to the next block start.
1743
3105
  const paragraph = [];
1744
3106
  while (i < lines.length && !/^\s*$/.test(lines[i])
1745
- && !/^\s*```/.test(lines[i]) && !/^#{1,6}\s+/.test(lines[i])
1746
- && !/^\s*([-*+]|\d+[.)])\s+/.test(lines[i]) && !/^\s*>\s?/.test(lines[i])) {
3107
+ && !/^\s*(`{3,}|~{3,})/.test(lines[i]) && !/^#{1,6}\s+/.test(lines[i])
3108
+ && !/^\s*[-*+]\s+/.test(lines[i]) && !/^\s*\d+[.)]\s+/.test(lines[i])
3109
+ && !/^\s*>/.test(lines[i]) && !/^ {4}\S/.test(lines[i])
3110
+ && !(/^\s*\|/.test(lines[i]) && i + 1 < lines.length && isTableDelimiter(lines[i + 1]))
3111
+ && !(i + 1 < lines.length && /^\s*(=+|-{2,})\s*$/.test(lines[i + 1]))) {
1747
3112
  paragraph.push(lines[i]);
1748
3113
  i += 1;
1749
3114
  }
1750
- blocks.push(h('div', { key: 'b' + blockKey, style: MD.p },
3115
+ if (!paragraph.length) { i += 1; continue; }
3116
+ blocks.push(h('p', { key: 'b' + blockKey, style: MD.p },
1751
3117
  inlineNodes(paragraph.join('\n'), 'p' + blockKey)));
1752
3118
  blockKey += 1;
1753
3119
  }
1754
3120
  return blocks;
1755
3121
  }
1756
3122
 
3123
+ /** Whether a line is a GFM table delimiter row (`| --- | :---: |`). */
3124
+ function isTableDelimiter(line) {
3125
+ if (!line || line.indexOf('-') < 0) return false;
3126
+ const cells = splitTableRow(line);
3127
+ return cells.length > 0 && cells.every((cell) => /^:?-{1,}:?$/.test(cell));
3128
+ }
3129
+
3130
+ /**
3131
+ * Split one table row into cells.
3132
+ *
3133
+ * The outer pipes are optional in GFM, and `\|` is a literal pipe inside a
3134
+ * cell, so it is swapped for a placeholder before splitting and restored
3135
+ * afterwards.
3136
+ */
3137
+ function splitTableRow(line) {
3138
+ const source = String(line).trim().replace(/^\|/, '').replace(/\|$/, '');
3139
+ const cells = [];
3140
+ let cell = '';
3141
+ for (let index = 0; index < source.length; index += 1) {
3142
+ const ch = source[index];
3143
+ if (ch === '\\' && source[index + 1] === '|') {
3144
+ cell += '\u0000';
3145
+ index += 1;
3146
+ } else if (ch === '|') {
3147
+ cells.push(cell.trim().replace(/\u0000/g, '|'));
3148
+ cell = '';
3149
+ } else {
3150
+ cell += ch;
3151
+ }
3152
+ }
3153
+ cells.push(cell.trim().replace(/\u0000/g, '|'));
3154
+ return cells;
3155
+ }
3156
+
1757
3157
  function Chevron({ dir, size, color }) {
1758
3158
  const box = size || 10;
1759
3159
  const rotate = dir === 'down' ? 0 : dir === 'up' ? 180 : dir === 'right' ? -90 : 90;
@@ -1873,21 +3273,41 @@ window.__ModuleLoader__.load({
1873
3273
  });
1874
3274
  }
1875
3275
 
3276
+ /**
3277
+ * How long the turn has been open, in milliseconds of wall clock.
3278
+ *
3279
+ * This is deliberately not `cost.ms`: `turnCost` can only measure between
3280
+ * durable events, so during one long thinking step it stops moving and then
3281
+ * jumps by minutes when the step settles. An open turn has to be measured
3282
+ * against the clock, clamped at zero so a skewed clock cannot print "-3s".
3283
+ */
3284
+ function liveElapsedMs(node, now) {
3285
+ if (!node || !node.startedAt || !now) return 0;
3286
+ return Math.max(0, now - node.startedAt);
3287
+ }
3288
+
3289
+ /** Re-render the caller once a second while `active`. */
3290
+ function useTicker(active) {
3291
+ const [, setTick] = useState(0);
3292
+ useEffect(() => {
3293
+ if (!active) return undefined;
3294
+ const timer = setInterval(() => setTick((n) => n + 1), 1000);
3295
+ return () => clearInterval(timer);
3296
+ }, [active]);
3297
+ return Date.now();
3298
+ }
3299
+
1876
3300
  /** What the model is doing right now: thinking, calling a tool, or writing. */
1877
- function LiveProgress({ node }) {
3301
+ function LiveProgress({ node, now }) {
1878
3302
  useLocale();
1879
3303
  const awaiting = node.awaiting === 'question' || node.awaiting === 'approval';
1880
3304
  const running = awaiting || node.status === 'thinking' || node.status === 'streaming' || node.status === 'running';
1881
- const [, tick] = useState(0);
1882
- useEffect(() => {
1883
- if (!running) return undefined;
1884
- const timer = setInterval(() => tick((n) => n + 1), 1000);
1885
- return () => clearInterval(timer);
1886
- }, [running]);
1887
3305
  if (!running) return null;
1888
3306
  const tool = node.tool || '';
1889
3307
  const step = node.step || 0;
1890
- const elapsed = node.startedAt ? Math.max(0, Math.round((Date.now() - node.startedAt) / 1000)) : 0;
3308
+ // The clock lives in the card (one timer for the whole card); this row
3309
+ // only reads it, so the live row and the header can never disagree.
3310
+ const elapsed = Math.round(liveElapsedMs(node, now) / 1000);
1891
3311
  // A pending question/approval is not "calling the tool": name the wait so
1892
3312
  // the card says the ball is in the user's court.
1893
3313
  const label = awaiting
@@ -1926,6 +3346,142 @@ window.__ModuleLoader__.load({
1926
3346
  elapsed > 0 ? h('span', { style: { fontVariantNumeric: 'tabular-nums', opacity: 0.6 } }, elapsed + 's') : null);
1927
3347
  }
1928
3348
 
3349
+ /**
3350
+ * The agent's current thought, in one line.
3351
+ *
3352
+ * An elapsed time says the agent is busy; it does not say what it is
3353
+ * doing. This row carries the newest reasoning the model has written, so
3354
+ * the reader can tell a search from a refactor without opening anything.
3355
+ * Clicking it opens the reader, where the whole chain is readable while the
3356
+ * answer is still streaming.
3357
+ */
3358
+ function ReasoningTail({ node, onOpen }) {
3359
+ useLocale();
3360
+ const awaiting = node.awaiting === 'question' || node.awaiting === 'approval';
3361
+ const running = awaiting || node.status === 'thinking' || node.status === 'streaming' || node.status === 'running';
3362
+ const text = node.reasoning || '';
3363
+ if (!running || !text.trim()) return null;
3364
+ const preview = reasoningTail(text);
3365
+ if (!preview) return null;
3366
+ return h('button', {
3367
+ onClick: (event) => {
3368
+ event.stopPropagation();
3369
+ onOpen();
3370
+ },
3371
+ title: T('card.thinkExpandTitle'),
3372
+ className: 'dsh-tree-reasoning-tail dsh-tree-clamp-2',
3373
+ style: {
3374
+ display: 'block', width: '100%', textAlign: 'left', cursor: 'pointer',
3375
+ fontFamily: 'inherit',
3376
+ marginTop: 5, padding: '4px 7px', borderRadius: 6,
3377
+ border: 'none', borderLeft: '2px solid ' + C.accentEdge,
3378
+ background: 'color-mix(in srgb, var(--dsw-alias-label-primary) 4%, transparent)',
3379
+ fontSize: 10.5, color: C.ink4, lineHeight: 1.45,
3380
+ },
3381
+ }, preview);
3382
+ }
3383
+
3384
+ /**
3385
+ * The card's reasoning row.
3386
+ *
3387
+ * It is a pointer, not a panel. Expanding the thinking inside a 320px card
3388
+ * stretched the card into a very long strip, which is exactly what made it
3389
+ * awkward to use; the reader is where a long answer — and the thinking
3390
+ * behind it — is actually read. So the row says how much there is and opens
3391
+ * the reader, where the chain sits at the top and folds away.
3392
+ */
3393
+ function ReasoningRow({ node, onOpen }) {
3394
+ useLocale();
3395
+ const text = node.reasoning || '';
3396
+ if (!text.trim()) return null;
3397
+ const preview = reasoningPreview(text);
3398
+ const dropped = node.reasoningDropped || 0;
3399
+ return h('div', {
3400
+ className: 'dsh-tree-reasoning',
3401
+ style: { marginTop: 6 },
3402
+ },
3403
+ h('button', {
3404
+ onClick: (event) => {
3405
+ event.stopPropagation();
3406
+ onOpen();
3407
+ },
3408
+ title: T('card.thinkExpandTitle'),
3409
+ className: LINK,
3410
+ style: { color: C.accent, gap: 5, maxWidth: '100%' },
3411
+ },
3412
+ h(Chevron, { dir: 'right', size: 9 }),
3413
+ h('span', { style: { flex: '0 0 auto' } }, T('card.think')),
3414
+ h('span', { style: { color: C.ink4, fontVariantNumeric: 'tabular-nums', flex: '0 0 auto' } },
3415
+ T('card.thinkMeta', { count: text.length }))),
3416
+ // The truncation notice is metadata, not part of the reasoning, so the
3417
+ // collapsed row can still say the text is partial.
3418
+ dropped > 0
3419
+ ? h('div', {
3420
+ style: {
3421
+ marginTop: 3, paddingLeft: 13, fontSize: 10.2,
3422
+ color: C.ink4, fontVariantNumeric: 'tabular-nums',
3423
+ },
3424
+ }, T('card.thinkTruncated', { count: dropped }))
3425
+ : null,
3426
+ preview
3427
+ ? h('div', {
3428
+ className: 'dsh-tree-reasoning-preview dsh-tree-clamp-2',
3429
+ style: {
3430
+ marginTop: 4, paddingLeft: 13, fontSize: 10.8, lineHeight: 1.5,
3431
+ color: C.ink4,
3432
+ },
3433
+ }, preview)
3434
+ : null);
3435
+ }
3436
+
3437
+ /**
3438
+ * The reader's reasoning block: first thing in the answer, folded away.
3439
+ *
3440
+ * It lives in the reader's own scroll container rather than a nested one:
3441
+ * a second scroll area inside the reader is what made the wheel ambiguous,
3442
+ * and a long chain is easier to read in the flow than in a 260px box.
3443
+ */
3444
+ function ReasoningDisclosure({ node }) {
3445
+ useLocale();
3446
+ const [open, setOpen] = useState(false);
3447
+ const text = node.reasoning || '';
3448
+ if (!text.trim()) return null;
3449
+ const dropped = node.reasoningDropped || 0;
3450
+ return h('div', {
3451
+ className: 'dsh-tree-reasoning',
3452
+ style: { marginBottom: 18 },
3453
+ },
3454
+ h('button', {
3455
+ onClick: () => setOpen((value) => !value),
3456
+ 'aria-expanded': open,
3457
+ title: open ? T('card.thinkCollapseTitle') : T('card.thinkExpandTitle'),
3458
+ className: LINK,
3459
+ style: { color: C.accent, gap: 5 },
3460
+ },
3461
+ h(Chevron, { dir: open ? 'down' : 'right', size: 9 }),
3462
+ h('span', null, T('card.think')),
3463
+ h('span', { style: { color: C.ink4, fontVariantNumeric: 'tabular-nums' } },
3464
+ T('card.thinkMeta', { count: text.length }))),
3465
+ dropped > 0
3466
+ ? h('div', {
3467
+ style: {
3468
+ marginTop: 4, paddingLeft: 13, fontSize: 10.8,
3469
+ color: C.ink4, fontVariantNumeric: 'tabular-nums',
3470
+ },
3471
+ }, T('card.thinkTruncated', { count: dropped }))
3472
+ : null,
3473
+ open
3474
+ ? h('div', {
3475
+ style: {
3476
+ marginTop: 8, padding: '10px 13px', borderRadius: 9,
3477
+ border: '1px solid ' + C.cardEdge,
3478
+ background: 'color-mix(in srgb, var(--dsw-alias-label-primary) 3%, transparent)',
3479
+ fontSize: 12.4, lineHeight: 1.78, color: C.ink4,
3480
+ },
3481
+ }, renderMarkdown(text))
3482
+ : null);
3483
+ }
3484
+
1929
3485
  function NodeCard({ node, selected, dimmed, index, store, api, rootId, match, collapsed, childCount, descendants, isLatest, entering }) {
1930
3486
  useLocale();
1931
3487
  const snapshot = store.getSnapshot();
@@ -1937,6 +3493,10 @@ window.__ModuleLoader__.load({
1937
3493
  const animateEntry = useRef(entering);
1938
3494
  const isRunning = isInProgressNode(node);
1939
3495
  const awaiting = node.awaiting === 'question' || node.awaiting === 'approval';
3496
+ // A running card has a clock. Without it the elapsed time only moved when
3497
+ // a durable event landed, so a long thinking step left the number frozen
3498
+ // for minutes and then jumped — the label looked broken rather than busy.
3499
+ const now = useTicker(isRunning && Boolean(node.startedAt));
1940
3500
  const answer = node.answer || '';
1941
3501
  const answerText = answer.length > 1400 ? answer.slice(0, 1400) + T('card.truncated') : answer;
1942
3502
 
@@ -1988,10 +3548,10 @@ window.__ModuleLoader__.load({
1988
3548
  borderLeft: '3px solid ' + (selected || isRunning ? C.accent : dimmed ? C.cardEdge : C.line),
1989
3549
  borderRadius: 10,
1990
3550
  boxShadow: awaiting || selected
1991
- ? '0 0 0 4px ' + C.accentSoft + ', 0 6px 18px rgba(0,0,0,0.08)'
3551
+ ? '0 0 0 4px ' + C.accentSoft + ', var(--dsh-tree-shadow-2)'
1992
3552
  : match
1993
- ? '0 0 0 3px ' + C.accentSoft + ', 0 2px 8px rgba(0,0,0,0.05)'
1994
- : '0 2px 8px rgba(0,0,0,0.05)',
3553
+ ? '0 0 0 3px ' + C.accentSoft + ', var(--dsh-tree-shadow-1)'
3554
+ : 'var(--dsh-tree-shadow-1)',
1995
3555
  padding: '10px 12px 9px',
1996
3556
  opacity: dimmed ? 0.72 : 1,
1997
3557
  boxSizing: 'border-box',
@@ -2011,19 +3571,31 @@ window.__ModuleLoader__.load({
2011
3571
  }, T('card.latestBadge'))
2012
3572
  : null,
2013
3573
  h(Badge, { label: statusLabel }),
2014
- node.cost && (node.cost.ms || node.cost.tokens)
2015
- ? h('span', {
2016
- title: [
2017
- node.cost.ms ? T('card.cost.elapsed', { value: formatCost({ ms: node.cost.ms, tokens: 0 }) }) : '',
2018
- node.cost.tokens ? T('card.cost.context', { value: formatCost({ ms: 0, tokens: node.cost.tokens }) }) : '',
2019
- node.cost.cached ? T('card.cost.cached', { value: formatCost({ ms: 0, tokens: node.cost.cached }) }) : '',
2020
- ].filter(Boolean).join(' · '),
2021
- style: {
2022
- fontSize: 10.5, color: C.ink3, fontVariantNumeric: 'tabular-nums',
2023
- whiteSpace: 'nowrap', letterSpacing: '0.02em',
2024
- },
2025
- }, formatCost(node.cost))
2026
- : null,
3574
+ // While the turn is open the header clock is wall clock, not the span
3575
+ // between the first and last durable event: the latter is what
3576
+ // `turnCost` can know from the log, and it stops moving the moment the
3577
+ // model thinks for a while without emitting anything durable.
3578
+ (function () {
3579
+ const live = isRunning && node.startedAt && now
3580
+ ? {
3581
+ ms: liveElapsedMs(node, now),
3582
+ tokens: node.cost ? node.cost.tokens : 0,
3583
+ cached: node.cost ? node.cost.cached : 0,
3584
+ }
3585
+ : node.cost;
3586
+ if (!live || !(live.ms || live.tokens)) return null;
3587
+ return h('span', {
3588
+ title: [
3589
+ live.ms ? T('card.cost.elapsed', { value: formatCost({ ms: live.ms, tokens: 0 }) }) : '',
3590
+ live.tokens ? T('card.cost.context', { value: formatCost({ ms: 0, tokens: live.tokens }) }) : '',
3591
+ live.cached ? T('card.cost.cached', { value: formatCost({ ms: 0, tokens: live.cached }) }) : '',
3592
+ ].filter(Boolean).join(' · '),
3593
+ style: {
3594
+ fontSize: 10.5, color: C.ink3, fontVariantNumeric: 'tabular-nums',
3595
+ whiteSpace: 'nowrap', letterSpacing: '0.02em',
3596
+ },
3597
+ }, formatCost(live));
3598
+ })(),
2027
3599
  h('span', { style: { flex: 1 } }),
2028
3600
  isRunning
2029
3601
  ? h('button', {
@@ -2074,9 +3646,9 @@ window.__ModuleLoader__.load({
2074
3646
  onMouseDown: (event) => event.stopPropagation(),
2075
3647
  onClick: (event) => event.stopPropagation(),
2076
3648
  style: {
2077
- position: 'absolute', top: 28, right: 0, zIndex: 5, background: C.card,
3649
+ position: 'absolute', top: 28, right: 0, zIndex: 5, background: C.overlay,
2078
3650
  border: '1px solid ' + C.cardEdge, borderRadius: 9, padding: 4,
2079
- boxShadow: '0 8px 22px rgba(0,0,0,0.12)', minWidth: 132,
3651
+ boxShadow: 'var(--dsh-tree-shadow-2)', minWidth: 132,
2080
3652
  },
2081
3653
  }, h('button', {
2082
3654
  onClick: () => {
@@ -2089,9 +3661,9 @@ window.__ModuleLoader__.load({
2089
3661
  }, T('card.delete'))))
2090
3662
  : null),
2091
3663
  h('div', {
3664
+ className: 'dsh-tree-clamp-3',
2092
3665
  style: {
2093
3666
  fontSize: 12.5, fontWeight: 600, lineHeight: 1.45, color: C.ink,
2094
- display: '-webkit-box', WebkitLineClamp: 3, WebkitBoxOrient: 'vertical', overflow: 'hidden',
2095
3667
  },
2096
3668
  }, node.question || T('card.noQuestion')),
2097
3669
  h('div', {
@@ -2111,7 +3683,9 @@ window.__ModuleLoader__.load({
2111
3683
  WebkitMaskImage: (!expanded && answer.length > 320) ? 'linear-gradient(#000 82%, transparent 100%)' : 'none',
2112
3684
  },
2113
3685
  }, answer ? renderMarkdown(answerText) : null),
2114
- h(LiveProgress, { node }),
3686
+ h(LiveProgress, { node, now }),
3687
+ h(ReasoningTail, { node, onOpen: () => store.openReader(node.id) }),
3688
+ h(ReasoningRow, { node, onOpen: () => store.openReader(node.id) }),
2115
3689
  h(Presence, { show: composing, className: 'dsh-tree-composer' },
2116
3690
  h(Composer, { store, api, rootId, node, active: composing })),
2117
3691
  answer.length > 260 || childCount > 0
@@ -2209,7 +3783,7 @@ window.__ModuleLoader__.load({
2209
3783
  },
2210
3784
  }),
2211
3785
  h('div', { style: { display: 'flex', gap: 6, marginTop: 8, alignItems: 'center' } },
2212
- h('span', { style: { fontSize: 10.5, color: C.ink3, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } },
3786
+ h('span', { className: 'dsh-tree-one-line', style: { fontSize: 10.5, color: C.ink3 } },
2213
3787
  T('composer.from', { question: (node.question || '').slice(0, 12) })),
2214
3788
  h('span', { style: { flex: 1 } }),
2215
3789
  h('button', {
@@ -2222,7 +3796,7 @@ window.__ModuleLoader__.load({
2222
3796
  }, T('composer.send'))));
2223
3797
  }
2224
3798
 
2225
- function Canvas({ store, api, rootId, size }) {
3799
+ function Canvas({ store, api, rootId, size, ready }) {
2226
3800
  useLocale();
2227
3801
  const snapshot = store.getSnapshot();
2228
3802
  const nodes = snapshot.nodes;
@@ -2233,6 +3807,7 @@ window.__ModuleLoader__.load({
2233
3807
  for (const node of nodes) seenNodes.current.add(node.id);
2234
3808
  }, [nodes]);
2235
3809
  const [query, setQuery] = useState('');
3810
+ const [direction, setDirection] = useState(readLayoutDirection);
2236
3811
  const drag = useRef(null);
2237
3812
  const wrapRef = useRef(null);
2238
3813
  const searchRef = useRef(null);
@@ -2264,8 +3839,8 @@ window.__ModuleLoader__.load({
2264
3839
  return { direct, descendants: descendantCountsOf(liveNodes, childrenOf) };
2265
3840
  }, [liveNodes]);
2266
3841
  const layout = useMemo(
2267
- () => layoutTree(liveNodes, collapsedMap, snapshot.heights),
2268
- [liveNodes, collapsedMap, snapshot.heights]);
3842
+ () => layoutTree(liveNodes, collapsedMap, snapshot.heights, direction),
3843
+ [liveNodes, collapsedMap, snapshot.heights, direction]);
2269
3844
  const path = useMemo(
2270
3845
  () => (snapshot.selectedId ? pathOf(liveNodes, snapshot.selectedId) : new Set()),
2271
3846
  [liveNodes, snapshot.selectedId]);
@@ -2315,13 +3890,14 @@ window.__ModuleLoader__.load({
2315
3890
  const pos = layout.positions.get(pendingFocus);
2316
3891
  if (!pos) { setPendingFocus(null); return; }
2317
3892
  const rect = wrapRef.current ? wrapRef.current.getBoundingClientRect() : { width: 900, height: 600 };
2318
- const top = (toolbarRef.current ? toolbarRef.current.offsetHeight : 44) + 28;
3893
+ const top = size.top + (toolbarRef.current ? toolbarRef.current.offsetHeight : 44) + 28;
3894
+ const availableHeight = Math.max(1, rect.height - top - size.bottom);
2319
3895
  const height = snapshot.heights[pendingFocus] || NODE_H;
2320
- const z = Math.max(0.2, Math.min(1, (rect.width - 48) / NODE_W, (rect.height - top - 32) / height));
3896
+ const z = Math.max(0.2, Math.min(1, (rect.width - 48) / NODE_W, (availableHeight - 32) / height));
2321
3897
  setView({ z, x: rect.width / 2 - (pos.x + NODE_W / 2) * z,
2322
- y: top + (rect.height - top) / 2 - (pos.y + height / 2) * z }, true);
3898
+ y: top + availableHeight / 2 - (pos.y + height / 2) * z }, true);
2323
3899
  setPendingFocus(null);
2324
- }, [pendingFocus, layout, snapshot.heights]);
3900
+ }, [pendingFocus, layout, snapshot.heights, size.top, size.bottom]);
2325
3901
  const latest = latestNodeOf(liveNodes);
2326
3902
 
2327
3903
  /** Jump to the next card matching `predicate`, wrapping around. */
@@ -2395,8 +3971,45 @@ window.__ModuleLoader__.load({
2395
3971
  focusNode(hitIds[nextIndex]);
2396
3972
  }, [matches, liveNodes, snapshot.selectedId, focusNode]);
2397
3973
 
3974
+ /**
3975
+ * Whether a wheel event belongs to something that scrolls on its own.
3976
+ *
3977
+ * The canvas claims every wheel event to zoom, so without this guard a
3978
+ * reader scrolling the expanded reasoning text (or the composer) zoomed
3979
+ * the whole canvas instead of scrolling the box under the pointer.
3980
+ *
3981
+ * `overflow-y` comes from the computed style rather than from our own
3982
+ * class names, so a native scrollable — the composer's textarea — is
3983
+ * covered by the same rule. The result distinguishes the two cases that
3984
+ * need different handling:
3985
+ *
3986
+ * 'scroll' — the box can move further in this direction, so the browser
3987
+ * must handle the event natively and the canvas must stay out
3988
+ * of it entirely;
3989
+ * 'edge' — the box is already at that end. The wheel must do nothing
3990
+ * at all: falling through to the zoom is what made the canvas
3991
+ * jump under a reader who had simply reached the bottom.
3992
+ */
3993
+ function wheelOwner(target, stopAt, deltaY) {
3994
+ if (!target || !stopAt || typeof window === 'undefined') return false;
3995
+ for (let el = target; el && el !== stopAt; el = el.parentElement) {
3996
+ const style = window.getComputedStyle(el);
3997
+ const overflowY = style && style.overflowY;
3998
+ if (overflowY !== 'auto' && overflowY !== 'scroll') continue;
3999
+ const range = el.scrollHeight - el.clientHeight;
4000
+ if (range <= 1) continue;
4001
+ const atTop = el.scrollTop <= 0;
4002
+ const atBottom = el.scrollTop >= range - 1;
4003
+ return deltaY < 0 ? (atTop ? 'edge' : 'scroll') : (atBottom ? 'edge' : 'scroll');
4004
+ }
4005
+ return false;
4006
+ }
4007
+
2398
4008
  const onWheel = (event) => {
4009
+ const owned = wheelOwner(event.target, wrapRef.current, event.deltaY);
4010
+ if (owned === 'scroll') return;
2399
4011
  event.preventDefault();
4012
+ if (owned === 'edge') return;
2400
4013
  const rect = wrapRef.current ? wrapRef.current.getBoundingClientRect() : { left: 0, top: 0 };
2401
4014
  const px = event.clientX - rect.left;
2402
4015
  const py = event.clientY - rect.top;
@@ -2429,14 +4042,14 @@ window.__ModuleLoader__.load({
2429
4042
  };
2430
4043
 
2431
4044
  /** Height the floating toolbar occupies, so the tree starts below it. */
2432
- const chromeHeight = () => (toolbarRef.current ? toolbarRef.current.offsetHeight : 48) + 22;
4045
+ const chromeHeight = () => size.top + (toolbarRef.current ? toolbarRef.current.offsetHeight : 48) + 22;
2433
4046
 
2434
4047
  const fit = () => {
2435
4048
  const rect = wrapRef.current ? wrapRef.current.getBoundingClientRect() : { width: 900, height: 600 };
2436
4049
  if (!layout.width || !layout.height) return;
2437
4050
  const chrome = chromeHeight();
2438
4051
  const availableW = Math.max(200, rect.width - 80);
2439
- const availableH = Math.max(200, rect.height - chrome - 48);
4052
+ const availableH = Math.max(200, rect.height - chrome - size.bottom - 48);
2440
4053
  const z = Math.min(1, Math.min(availableW / layout.width, availableH / layout.height));
2441
4054
  const scale = Math.max(0.2, z);
2442
4055
  setView({
@@ -2458,14 +4071,22 @@ window.__ModuleLoader__.load({
2458
4071
  }, true);
2459
4072
  };
2460
4073
 
4074
+ const previousDirection = useRef(direction);
4075
+ useEffect(() => {
4076
+ if (previousDirection.current === direction) return;
4077
+ previousDirection.current = direction;
4078
+ if (snapshot.selectedId && layout.positions.has(snapshot.selectedId)) setPendingFocus(snapshot.selectedId);
4079
+ else fit();
4080
+ }, [direction]);
4081
+
2461
4082
  const fittedRef = useRef(false);
2462
4083
  useEffect(() => {
2463
- if (fittedRef.current || !liveNodes.length || !size.w) return;
4084
+ if (fittedRef.current || !ready || !liveNodes.length || !size.w) return;
2464
4085
  fittedRef.current = true;
2465
4086
  const rect = wrapRef.current ? wrapRef.current.getBoundingClientRect() : { width: 900, height: 600 };
2466
4087
  const chrome = chromeHeight();
2467
4088
  const availableW = Math.max(200, rect.width - 96);
2468
- const availableH = Math.max(200, rect.height - chrome - 56);
4089
+ const availableH = Math.max(200, rect.height - chrome - size.bottom - 56);
2469
4090
  const raw = Math.min(1, availableW / Math.max(1, layout.width), availableH / Math.max(1, layout.height));
2470
4091
  const scale = Math.max(0.62, raw);
2471
4092
  setView({
@@ -2473,7 +4094,7 @@ window.__ModuleLoader__.load({
2473
4094
  x: Math.max(28, (rect.width - layout.width * scale) / 2),
2474
4095
  y: chrome,
2475
4096
  });
2476
- }, [liveNodes.length, size.w]);
4097
+ }, [liveNodes.length, size.w, ready]);
2477
4098
 
2478
4099
  // Ctrl/Cmd+F is the tree's own search while this view is mounted.
2479
4100
  useEffect(() => {
@@ -2525,7 +4146,9 @@ window.__ModuleLoader__.load({
2525
4146
  const active = path.has(edge.id.split('>')[0]) && path.has(edge.id.split('>')[1]);
2526
4147
  return h('path', {
2527
4148
  key: edge.id,
2528
- d: 'M' + edge.x1 + ' ' + edge.y1 + ' C' + edge.x1 + ' ' + (edge.y1 + 40) + ', ' + edge.x2 + ' ' + (edge.y2 - 40) + ', ' + edge.x2 + ' ' + edge.y2,
4149
+ d: direction === 'horizontal'
4150
+ ? 'M' + edge.x1 + ' ' + edge.y1 + ' C' + (edge.x1 + 40) + ' ' + edge.y1 + ', ' + (edge.x2 - 40) + ' ' + edge.y2 + ', ' + edge.x2 + ' ' + edge.y2
4151
+ : 'M' + edge.x1 + ' ' + edge.y1 + ' C' + edge.x1 + ' ' + (edge.y1 + 40) + ', ' + edge.x2 + ' ' + (edge.y2 - 40) + ', ' + edge.x2 + ' ' + edge.y2,
2529
4152
  fill: 'none',
2530
4153
  stroke: active ? C.accent : C.line,
2531
4154
  strokeWidth: active ? 2 : 1.4,
@@ -2558,9 +4181,9 @@ window.__ModuleLoader__.load({
2558
4181
  onMouseDown: (event) => event.stopPropagation(),
2559
4182
  onWheel: (event) => event.stopPropagation(),
2560
4183
  style: {
2561
- position: 'absolute', top: 10, left: 12, right: 12, display: 'flex', gap: 8,
4184
+ position: 'absolute', top: size.top + 10, left: 12, right: 12, display: 'flex', gap: 8,
2562
4185
  flexWrap: 'wrap', padding: 8, borderRadius: 12, background: C.card,
2563
- border: '1px solid ' + C.cardEdge, boxShadow: '0 2px 8px rgba(0,0,0,0.04)',
4186
+ border: '1px solid ' + C.cardEdge, boxShadow: 'var(--dsh-tree-shadow-1)',
2564
4187
  alignItems: 'center', fontSize: 12, color: C.ink3,
2565
4188
  },
2566
4189
  },
@@ -2638,6 +4261,41 @@ window.__ModuleLoader__.load({
2638
4261
  onClick: () => zoomBy(1.15),
2639
4262
  className: BTN_ICON,
2640
4263
  }, h(Icon, { name: 'plus' }))),
4264
+ // Both directions are visible at once, so the current one is a pressed
4265
+ // state rather than something the reader has to infer from the shape of
4266
+ // the canvas. A single toggle whose label never changes cannot say
4267
+ // which way the tree is running.
4268
+ h('div', {
4269
+ role: 'group',
4270
+ 'aria-label': T('view.layoutGroup'),
4271
+ title: T('view.layoutTitle'),
4272
+ style: {
4273
+ display: 'flex', alignItems: 'center', gap: 2, padding: 2,
4274
+ border: '1px solid ' + C.cardEdge, borderRadius: 9, background: C.canvas,
4275
+ },
4276
+ },
4277
+ h('button', {
4278
+ className: BTN_SEGMENT,
4279
+ title: T('view.layoutVertical'),
4280
+ 'aria-label': T('view.layoutVertical'),
4281
+ 'aria-pressed': direction === 'vertical',
4282
+ onClick: () => {
4283
+ if (direction === 'vertical') return;
4284
+ saveLayoutDirection('vertical');
4285
+ setDirection('vertical');
4286
+ },
4287
+ }, h(Icon, { name: 'layoutVertical' })),
4288
+ h('button', {
4289
+ className: BTN_SEGMENT,
4290
+ title: T('view.layoutHorizontal'),
4291
+ 'aria-label': T('view.layoutHorizontal'),
4292
+ 'aria-pressed': direction === 'horizontal',
4293
+ onClick: () => {
4294
+ if (direction === 'horizontal') return;
4295
+ saveLayoutDirection('horizontal');
4296
+ setDirection('horizontal');
4297
+ },
4298
+ }, h(Icon, { name: 'layoutHorizontal' }))),
2641
4299
  h('button', { onClick: fit, className: BTN, title: T('view.fitTitle') }, h(Icon, { name: 'fit' }), T('view.fit')),
2642
4300
  h('button', {
2643
4301
  disabled: !latest,
@@ -2651,9 +4309,9 @@ window.__ModuleLoader__.load({
2651
4309
  ? h('div', {
2652
4310
  onMouseDown: (event) => event.stopPropagation(),
2653
4311
  style: {
2654
- position: 'absolute', right: 12, bottom: 12, width: 168, height: 112,
4312
+ position: 'absolute', right: 12, bottom: 12 + Math.min(size.bottom, Math.max(0, size.h - size.top - 160)), width: 168, height: 112,
2655
4313
  border: '1px solid ' + C.cardEdge, borderRadius: 8, background: C.card,
2656
- boxShadow: '0 2px 10px rgba(0,0,0,0.06)', overflow: 'hidden', cursor: 'pointer',
4314
+ boxShadow: 'var(--dsh-tree-shadow-1)', overflow: 'hidden', cursor: 'pointer',
2657
4315
  },
2658
4316
  onClick: (event) => {
2659
4317
  const rect = event.currentTarget.getBoundingClientRect();
@@ -2704,15 +4362,14 @@ window.__ModuleLoader__.load({
2704
4362
  stroke: active ? C.accent : 'transparent',
2705
4363
  strokeWidth: 1 / minimap.scale,
2706
4364
  });
2707
- })),
2708
- // What the canvas is looking at right now.
2709
- h('rect', {
2710
- x: -view.x / view.z, y: -view.y / view.z,
2711
- width: size.w / view.z, height: size.h / view.z,
2712
- fill: C.accentSoft, fillOpacity: 0.45,
2713
- stroke: C.accent, strokeWidth: 1.5 / minimap.scale,
2714
- rx: 6,
2715
- })))
4365
+ }),
4366
+ h('rect', {
4367
+ x: -view.x / view.z, y: -view.y / view.z,
4368
+ width: size.w / view.z, height: size.h / view.z,
4369
+ fill: C.accentSoft, fillOpacity: 0.45,
4370
+ stroke: C.accent, strokeWidth: 1.5 / minimap.scale,
4371
+ rx: 6,
4372
+ }))))
2716
4373
  : null,
2717
4374
 
2718
4375
  nodes.length === 0
@@ -2741,6 +4398,10 @@ window.__ModuleLoader__.load({
2741
4398
  latest: 'M8 1v3M8 12v3M1 8h3M12 8h3M12 8a4 4 0 1 1-8 0 4 4 0 0 1 8 0',
2742
4399
  more: 'M3 8h.01M8 8h.01M13 8h.01',
2743
4400
  close: 'M4 4l8 8M12 4l-8 8',
4401
+ // The two layout directions: one parent, two children, drawn the way
4402
+ // the tree reads in that direction.
4403
+ layoutVertical: 'M8 2v3M4 5h8M4 5v4M12 5v4M4 11h.01M12 11h.01',
4404
+ layoutHorizontal: 'M2 8h3M5 4v8M5 4h4M5 12h4M11 4h.01M11 12h.01',
2744
4405
  };
2745
4406
  return h('svg', { width: 16, height: 16, viewBox: '0 0 16 16', 'aria-hidden': true,
2746
4407
  style: { display: 'block', flexShrink: 0 } }, h('path', {
@@ -2753,6 +4414,9 @@ window.__ModuleLoader__.load({
2753
4414
  // Inline styles only carry layout that varies per call site.
2754
4415
  const BTN = 'dsh-tree-btn';
2755
4416
  const BTN_ICON = 'dsh-tree-btn dsh-tree-btn--icon';
4417
+ // A segment inside the layout group: same hit area as an icon button, but
4418
+ // it borrows the group's border instead of drawing its own.
4419
+ const BTN_SEGMENT = 'dsh-tree-btn dsh-tree-btn--icon dsh-tree-btn--segment';
2756
4420
  const BTN_PRIMARY = 'dsh-tree-btn dsh-tree-btn--primary';
2757
4421
  const CHIP = 'dsh-tree-chip';
2758
4422
  const LINK = 'dsh-tree-link';
@@ -2807,63 +4471,62 @@ window.__ModuleLoader__.load({
2807
4471
  }
2808
4472
  }
2809
4473
 
4474
+ /**
4475
+ * The full-screen reader.
4476
+ *
4477
+ * A native <dialog> opened with `showModal()`, not a hand-built overlay.
4478
+ * The browser then owns everything that is easy to get wrong here: focus is
4479
+ * contained, the page behind is inert, Esc and the back gesture close it,
4480
+ * and it renders in the top layer — which matters here because a card lives
4481
+ * inside the transformed canvas, so a positioned child of it would be
4482
+ * clipped and scaled along with the canvas.
4483
+ *
4484
+ * The plugin therefore writes no focus trap, no Tab handler, no Esc handler
4485
+ * and no focus restoration; it only mirrors the element's `close` event back
4486
+ * into React state.
4487
+ */
2810
4488
  function Reader({ node, open, onClose }) {
2811
4489
  useLocale();
2812
- const panelRef = useRef(null);
2813
- const closeRef = useRef(null);
4490
+ const dialogRef = useRef(null);
2814
4491
  const close = useRef(onClose);
2815
4492
  close.current = onClose;
4493
+
4494
+ // `show()` would leave the page interactive; the reader is blocking.
2816
4495
  useEffect(() => {
2817
- if (!open) return undefined;
2818
- const previousFocus = document.activeElement;
2819
- if (closeRef.current) closeRef.current.focus();
2820
- const onKey = (event) => {
2821
- if (event.key === 'Escape') {
2822
- event.stopPropagation();
2823
- close.current();
2824
- } else if (event.key === 'Tab' && panelRef.current) {
2825
- const controls = panelRef.current.querySelectorAll('button, a[href], input, textarea, [tabindex="0"]');
2826
- const first = controls[0];
2827
- const last = controls[controls.length - 1];
2828
- if (event.shiftKey && document.activeElement === first) {
2829
- event.preventDefault();
2830
- if (last) last.focus();
2831
- } else if (!event.shiftKey && document.activeElement === last) {
2832
- event.preventDefault();
2833
- if (first) first.focus();
2834
- }
4496
+ const dialog = dialogRef.current;
4497
+ if (!dialog) return undefined;
4498
+ if (open) {
4499
+ if (!dialog.open) {
4500
+ if (typeof dialog.showModal === 'function') dialog.showModal();
4501
+ else dialog.setAttribute('open', '');
2835
4502
  }
2836
- };
2837
- window.addEventListener('keydown', onKey, true);
2838
- return () => {
2839
- window.removeEventListener('keydown', onKey, true);
2840
- if (previousFocus && previousFocus.isConnected) previousFocus.focus();
2841
- };
2842
- }, [open]);
4503
+ } else if (dialog.open) {
4504
+ dialog.close();
4505
+ }
4506
+ return undefined;
4507
+ }, [open, node && node.id]);
4508
+
4509
+ // Esc, the back gesture and light dismiss all end in a `close` event.
4510
+ useEffect(() => {
4511
+ const dialog = dialogRef.current;
4512
+ if (!dialog) return undefined;
4513
+ const onDismiss = () => close.current();
4514
+ dialog.addEventListener('close', onDismiss);
4515
+ return () => dialog.removeEventListener('close', onDismiss);
4516
+ }, []);
2843
4517
 
2844
4518
  if (!node) return null;
2845
- return h(Presence, {
2846
- show: open,
4519
+ const titleId = 'dsh-tree-reader-title-' + (node.id || 'node');
4520
+ return h('dialog', {
4521
+ ref: dialogRef,
2847
4522
  className: 'dsh-tree-reader',
2848
- onClick: onClose,
2849
- style: {
2850
- position: 'absolute', inset: 0, zIndex: 40, background: C.scrim,
2851
- display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '28px 34px',
2852
- },
4523
+ // The modal already carries role="dialog" and aria-modal: adding them
4524
+ // here would announce the overlay twice.
4525
+ 'aria-labelledby': titleId,
4526
+ // Click-outside dismissal. Where `closedby` is unsupported the dialog
4527
+ // still closes on Esc and the back gesture, so this only degrades.
4528
+ closedby: 'any',
2853
4529
  },
2854
- h('div', {
2855
- ref: panelRef,
2856
- className: 'dsh-tree-reader-panel',
2857
- role: 'dialog',
2858
- 'aria-modal': true,
2859
- 'aria-label': node.question || T('card.noQuestion'),
2860
- onClick: (event) => event.stopPropagation(),
2861
- style: {
2862
- width: '100%', maxWidth: 820, maxHeight: '100%', background: C.card,
2863
- borderRadius: 14, boxShadow: '0 20px 60px rgba(0,0,0,0.28)',
2864
- display: 'flex', flexDirection: 'column', overflow: 'hidden',
2865
- },
2866
- },
2867
4530
  h('div', {
2868
4531
  style: {
2869
4532
  padding: '14px 20px 11px', borderBottom: '1px solid ' + C.line,
@@ -2875,10 +4538,10 @@ window.__ModuleLoader__.load({
2875
4538
  style: { fontSize: 10.5, color: C.ink3, letterSpacing: '0.05em', marginBottom: 4 },
2876
4539
  }, (node.kind === 'branch' ? T('reader.branch') : T('reader.mainline')) + ' · ' + (node.id || '')),
2877
4540
  h('div', {
4541
+ id: titleId,
2878
4542
  style: { fontSize: 15, fontWeight: 600, lineHeight: 1.5, color: C.ink },
2879
4543
  }, node.question || T('card.noQuestion'))),
2880
4544
  h('button', {
2881
- ref: closeRef,
2882
4545
  onClick: onClose,
2883
4546
  title: T('reader.close'),
2884
4547
  'aria-label': T('reader.closeLabel'),
@@ -2886,11 +4549,18 @@ window.__ModuleLoader__.load({
2886
4549
  style: { width: 30, height: 30, minWidth: 30, minHeight: 30 },
2887
4550
  }, h(Icon, { name: 'close' }))),
2888
4551
  h('div', {
4552
+ className: 'dsh-tree-scroll',
2889
4553
  style: {
2890
4554
  padding: '18px 22px 22px', overflow: 'auto', flex: 1,
2891
4555
  ...MD.body, fontSize: 13.4, lineHeight: 1.85,
2892
4556
  },
2893
- }, node.answer ? renderMarkdown(node.answer) : T('reader.noAnswer')),
4557
+ },
4558
+ // The thinking comes first: it is what the reader opened the
4559
+ // card for, and folding it keeps the answer itself at the top
4560
+ // of the eye.
4561
+ h(ReasoningDisclosure, { node }),
4562
+ node.answer ? renderMarkdown(node.answer) : T('reader.noAnswer')),
4563
+
2894
4564
  h('div', {
2895
4565
  style: {
2896
4566
  padding: '8px 20px', borderTop: '1px solid ' + C.cardEdge, fontSize: 10.5,
@@ -2901,7 +4571,7 @@ window.__ModuleLoader__.load({
2901
4571
  h('span', { style: { flex: 1 } }),
2902
4572
  node.cost && (node.cost.ms || node.cost.tokens)
2903
4573
  ? h('span', null, formatCost(node.cost))
2904
- : null)));
4574
+ : null));
2905
4575
  }
2906
4576
 
2907
4577
  function TreeView(props) {
@@ -2910,17 +4580,41 @@ window.__ModuleLoader__.load({
2910
4580
  const rootId = useMemo(() => api.rootOf(sessionId), [sessionId, api]);
2911
4581
  const store = useMemo(() => api.storeFor(rootId), [rootId, api]);
2912
4582
  const [, force] = useState(0);
4583
+ const anchorRef = useRef(null);
2913
4584
  const hostRef = useRef(null);
2914
- const [size, setSize] = useState({ w: 0, h: 0 });
4585
+ const [surface, setSurface] = useState(null);
4586
+ const [size, setSize] = useState({ w: 0, h: 0, top: 0, bottom: 0 });
2915
4587
 
2916
4588
  useEffect(() => store.subscribe(() => force((n) => n + 1)), [store]);
2917
4589
  useEffect(() => {
2918
4590
  api.ensureOpen(rootId, store);
2919
4591
  }, [rootId, store, api]);
4592
+ useEffect(() => {
4593
+ const anchor = anchorRef.current;
4594
+ const body = anchor && anchor.closest('[data-conversation-content]');
4595
+ const container = body && body.parentElement;
4596
+ const header = container && (container.querySelector(':scope > header') ||
4597
+ container.querySelector(':scope > [data-slot="conversation.header"] > header'));
4598
+ const composer = body && body.querySelector('[data-composer-seat]');
4599
+ if (!container || !header || !composer) return;
4600
+ try {
4601
+ const { createPortal } = require('react-dom');
4602
+ if (typeof createPortal !== 'function') return;
4603
+ setSize({ w: 0, h: 0, top: 0, bottom: 0 });
4604
+ setSurface({ container, header, composer, createPortal });
4605
+ } catch (error) {
4606
+ /* Hosts without a portal keep the canvas inside the view. */
4607
+ }
4608
+ }, []);
2920
4609
  useEffect(() => {
2921
4610
  const element = hostRef.current;
2922
4611
  if (!element) return undefined;
2923
- const measure = () => setSize({ w: element.clientWidth, h: element.clientHeight });
4612
+ const measure = () => {
4613
+ const rect = element.getBoundingClientRect();
4614
+ const top = surface ? Math.max(0, surface.header.getBoundingClientRect().bottom - rect.top) : 0;
4615
+ const bottom = surface ? Math.max(0, rect.bottom - surface.composer.getBoundingClientRect().top) : 0;
4616
+ setSize({ w: element.clientWidth, h: element.clientHeight, top, bottom, container: surface ? surface.container : null });
4617
+ };
2924
4618
  measure();
2925
4619
  if (typeof ResizeObserver === 'undefined') {
2926
4620
  window.addEventListener('resize', measure);
@@ -2928,24 +4622,31 @@ window.__ModuleLoader__.load({
2928
4622
  }
2929
4623
  const observer = new ResizeObserver(measure);
2930
4624
  observer.observe(element);
4625
+ if (surface) {
4626
+ observer.observe(surface.header);
4627
+ observer.observe(surface.composer);
4628
+ }
2931
4629
  return () => observer.disconnect();
2932
- }, []);
4630
+ }, [surface]);
2933
4631
 
2934
4632
  const snapshot = store.getSnapshot();
2935
4633
  const reading = snapshot.readingId ? store.getNode(snapshot.readingId) : undefined;
2936
4634
  const readerNode = useRef(null);
2937
4635
  if (reading) readerNode.current = reading;
2938
4636
 
2939
- return h('div', {
4637
+ const canvas = h('div', {
2940
4638
  ref: hostRef,
2941
- className: 'dsh-tree-root',
4639
+ className: surface ? 'dsh-tree-root dsh-tree-root--overlay' : 'dsh-tree-root',
2942
4640
  style: {
2943
- position: 'relative', width: '100%', height: '100%', minHeight: 420,
4641
+ position: surface ? 'absolute' : 'relative', inset: surface ? 0 : undefined,
4642
+ width: '100%', height: '100%', minHeight: 0, zIndex: surface ? (reading ? 20 : 1) : undefined,
2944
4643
  overflow: 'hidden', fontFamily: FONT, color: C.ink, background: C.canvas,
2945
4644
  },
2946
4645
  },
2947
- h(Boundary, null, h(Canvas, { key: rootId, store, api, rootId, size })),
4646
+ h(Boundary, null, h(Canvas, { key: rootId, store, api, rootId, size, ready: !surface || size.container === surface.container })),
2948
4647
  h(Reader, { key: rootId, node: reading || readerNode.current, open: Boolean(reading), onClose: () => store.closeReader() }));
4648
+ return h('div', { ref: anchorRef, style: { width: '100%', height: '100%', minHeight: 0, flex: '1 1 0' } },
4649
+ surface ? surface.createPortal(canvas, surface.container) : canvas);
2949
4650
  }
2950
4651
 
2951
4652
  // ------------------------------------------------------------------ mount
@@ -2964,10 +4665,55 @@ window.__ModuleLoader__.load({
2964
4665
  '@keyframes dshTreeSpin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }',
2965
4666
  '@keyframes dshTreePulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.35; } }',
2966
4667
  '.dsh-tree-root { --tree-fast: 120ms; --tree-enter: 240ms; --tree-exit: ' + MOTION_EXIT_MS + 'ms; --tree-ease: cubic-bezier(.2,.8,.2,1); --tree-spring: cubic-bezier(.16,1.3,.3,1); }',
4668
+ // Elevation in two themes. A black-alpha shadow is what gives a card depth
4669
+ // on a white canvas, and on a dark canvas it is invisible — the surface
4670
+ // has to separate by a heavier shadow instead. The three levels are
4671
+ // declared once and read by both themes.
4672
+ '.dsh-tree-root { --dsh-tree-shadow-1: 0 2px 8px rgba(0,0,0,0.05); --dsh-tree-shadow-2: 0 8px 22px rgba(0,0,0,0.12); --dsh-tree-shadow-3: 0 20px 60px rgba(0,0,0,0.28); }',
4673
+ 'body[data-ds-dark-theme] .dsh-tree-root { --dsh-tree-shadow-1: 0 2px 10px rgba(0,0,0,0.45); --dsh-tree-shadow-2: 0 10px 28px rgba(0,0,0,0.55); --dsh-tree-shadow-3: 0 22px 64px rgba(0,0,0,0.65); }',
4674
+ // Native affordances follow the host theme too: form controls and
4675
+ // scrollbars take their colour from `color-scheme`, and the plugin's own
4676
+ // scroll areas use the host's scrollbar tokens.
4677
+ '.dsh-tree-root { color-scheme: light; }',
4678
+ 'body[data-ds-dark-theme] .dsh-tree-root { color-scheme: dark; }',
4679
+ '.dsh-tree-clamp-2, .dsh-tree-clamp-3 {',
4680
+ ' display: -webkit-box; -webkit-box-orient: vertical;',
4681
+ ' -webkit-line-clamp: 2; line-clamp: 2;',
4682
+ ' overflow: hidden; overflow-wrap: break-word;',
4683
+ '}',
4684
+ '.dsh-tree-clamp-3 { -webkit-line-clamp: 3; line-clamp: 3; }',
4685
+ '.dsh-tree-one-line {',
4686
+ ' min-inline-size: 0; overflow: hidden; text-overflow: ellipsis;',
4687
+ ' white-space: nowrap;',
4688
+ '}',
4689
+ '.dsh-tree-scroll { scrollbar-width: thin; scrollbar-color: var(--dsw-alias-scrollbar-bg-l1) transparent; }',
4690
+ '.dsh-tree-scroll:hover { scrollbar-color: var(--dsw-alias-scrollbar-hover-l1) transparent; }',
4691
+ // Tables: a wide one scrolls sideways inside its own wrapper instead of
4692
+ // widening the card or the reader. The wrapper is the scroll container,
4693
+ // so the table keeps its natural width and cells stay on one line.
4694
+ '.dsh-tree-table-wrap {',
4695
+ ' max-width: 100%; margin: 0.7em 0; overflow-x: auto;',
4696
+ ' scrollbar-width: thin; scrollbar-color: var(--dsw-alias-scrollbar-bg-l1) transparent;',
4697
+ '}',
4698
+ '.dsh-tree-table {',
4699
+ ' border-collapse: collapse; font-size: 0.93em; line-height: 1.5;',
4700
+ ' width: max-content; min-width: 100%;',
4701
+ '}',
4702
+ '.dsh-tree-table th, .dsh-tree-table td {',
4703
+ ' border: 1px solid var(--dsw-alias-border-l1); padding: 6px 10px;',
4704
+ ' vertical-align: top; overflow-wrap: break-word;',
4705
+ '}',
4706
+ '.dsh-tree-table th {',
4707
+ ' font-weight: 600; white-space: nowrap;',
4708
+ ' background: color-mix(in srgb, var(--dsw-alias-label-primary) 5%, transparent);',
4709
+ '}',
4710
+ '.dsh-tree-table tbody tr:nth-child(even) td {',
4711
+ ' background: color-mix(in srgb, var(--dsw-alias-label-primary) 2%, transparent);',
4712
+ '}',
4713
+ ':has(> .dsh-tree-root--overlay) > header, :has(> .dsh-tree-root--overlay) > [data-slot="conversation.header"] > header { position: relative; z-index: 2; }',
4714
+ ':has(> .dsh-tree-root--overlay) > [data-conversation-content] [data-composer-seat]:not(:has([data-conversation-composer-overlay])) { width: min(100%, calc(var(--dsh-composer-card-max-width, 920px) + 2 * var(--dsh-composer-side-clearance, 16px))); align-self: center; background: transparent !important; }',
2967
4715
  '@keyframes dshTreeReveal { from { opacity: 0; transform: translateY(6px) scale(.985); } to { opacity: 1; transform: none; } }',
2968
4716
  '@keyframes dshTreeDismiss { from { opacity: 1; transform: none; } to { opacity: 0; transform: translateY(3px) scale(.99); } }',
2969
- '@keyframes dshTreeFadeIn { from { opacity: 0; } to { opacity: 1; } }',
2970
- '@keyframes dshTreeFadeOut { from { opacity: 1; } to { opacity: 0; } }',
2971
4717
  '.dsh-tree-card { transition: opacity var(--tree-enter) var(--tree-ease), box-shadow var(--tree-enter) var(--tree-ease), border-color var(--tree-fast) ease; }',
2972
4718
  '.dsh-tree-card--enter { animation: dshTreeReveal var(--tree-enter) var(--tree-ease); }',
2973
4719
  '.dsh-tree-presence[data-open="true"] { animation: dshTreeReveal var(--tree-enter) var(--tree-ease); }',
@@ -2975,10 +4721,43 @@ window.__ModuleLoader__.load({
2975
4721
  '.dsh-tree-menu { transform-origin: top right; }',
2976
4722
  '.dsh-tree-menu[data-open="true"] { animation-timing-function: var(--tree-spring); }',
2977
4723
  '.dsh-tree-composer { transform-origin: top center; }',
2978
- '.dsh-tree-reader[data-open="true"] { animation: dshTreeFadeIn 180ms ease-out; }',
2979
- '.dsh-tree-reader[data-open="false"] { animation: dshTreeFadeOut var(--tree-exit) ease-in forwards; }',
2980
- '.dsh-tree-reader[data-open="true"] .dsh-tree-reader-panel { animation: dshTreeReveal var(--tree-enter) var(--tree-ease); }',
2981
- '.dsh-tree-reader[data-open="false"] .dsh-tree-reader-panel { animation: dshTreeDismiss var(--tree-exit) ease-in forwards; }',
4724
+ // The reader is a native modal dialog; only its surface and its enter/exit
4725
+ // transition belong to the plugin.
4726
+ '.dsh-tree-reader {',
4727
+ ' margin: auto; padding: 0; border: none; margin-block: auto;',
4728
+ ' width: min(820px, calc(100vw - 68px)); max-width: calc(100vw - 68px);',
4729
+ ' max-height: calc(100vh - 56px);',
4730
+ ' background: var(--dsw-alias-bg-layer-1); color: var(--dsw-alias-label-primary);',
4731
+ ' border-radius: 14px; box-shadow: var(--dsh-tree-shadow-3); overflow: hidden;',
4732
+ // MANDATORY: without this, a scroll inside the dialog chains to the page
4733
+ // behind it as soon as the dialog reaches its own scroll boundary.
4734
+ ' overscroll-behavior: contain;',
4735
+ ' opacity: 0;',
4736
+ // MANDATORY for the top layer: display and overlay are discrete, and the
4737
+ // element has to stay in the top layer while it animates out.
4738
+ ' transition-property: opacity, transform, display, overlay;',
4739
+ ' transition-duration: var(--tree-exit);',
4740
+ ' transition-timing-function: ease-out;',
4741
+ ' transition-behavior: allow-discrete;',
4742
+ '}',
4743
+ // display is set only while open: an unconditional display would override
4744
+ // the closed state and leave the dialog permanently on screen.
4745
+ '.dsh-tree-reader[open] {',
4746
+ ' display: flex; flex-direction: column; opacity: 1;',
4747
+ ' transition-duration: var(--tree-enter);',
4748
+ '}',
4749
+ '@media (prefers-reduced-motion: no-preference) {',
4750
+ ' .dsh-tree-reader { transform: translateY(6px) scale(.985); }',
4751
+ ' .dsh-tree-reader[open] { transform: none; }',
4752
+ '}',
4753
+ '@starting-style { .dsh-tree-reader[open] { opacity: 0; } }',
4754
+ // MANDATORY: ::backdrop is not a scroll container by default, so
4755
+ // overscroll-behavior alone would not stop a gesture over the backdrop
4756
+ // from scrolling the page underneath.
4757
+ '.dsh-tree-reader::backdrop {',
4758
+ ' background: var(--dsw-alias-bg-mask-1);',
4759
+ ' overflow: hidden; overscroll-behavior: contain;',
4760
+ '}',
2982
4761
  // Every control shares one geometry so the toolbar reads as one row.
2983
4762
  '.dsh-tree-btn {',
2984
4763
  ' border: 1px solid var(--dsw-alias-border-l1); background: var(--dsw-alias-bg-layer-1);',
@@ -3001,7 +4780,19 @@ window.__ModuleLoader__.load({
3001
4780
  ' outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 1px;',
3002
4781
  '}',
3003
4782
  '.dsh-tree-btn[disabled] { opacity: 0.45; cursor: default; }',
4783
+ '.dsh-tree-btn[aria-pressed="true"] { color: var(--dsw-alias-brand-primary); border-color: var(--dsw-alias-brand-primary); background: color-mix(in srgb, var(--dsw-alias-brand-primary) 8%, transparent); }',
3004
4784
  '.dsh-tree-btn--icon { padding: 0; min-width: 30px; min-height: 30px; }',
4785
+ '.dsh-tree-btn--segment {',
4786
+ ' border-color: transparent; background: transparent;',
4787
+ ' min-width: 28px; min-height: 26px; border-radius: 7px; color: var(--dsw-alias-label-tertiary);',
4788
+ '}',
4789
+ '.dsh-tree-btn--segment:hover:not([disabled]) {',
4790
+ ' border-color: transparent; background: color-mix(in srgb, var(--dsw-alias-label-primary) 7%, transparent);',
4791
+ '}',
4792
+ '.dsh-tree-btn--segment[aria-pressed="true"], .dsh-tree-btn--segment[aria-pressed="true"]:hover {',
4793
+ ' border-color: transparent; color: var(--dsw-alias-brand-primary);',
4794
+ ' background: color-mix(in srgb, var(--dsw-alias-brand-primary) 10%, transparent);',
4795
+ '}',
3005
4796
  '.dsh-tree-btn--primary {',
3006
4797
  ' background: var(--dsw-alias-button-primary-fill); border-color: var(--dsw-alias-button-primary-fill);',
3007
4798
  ' color: var(--dsw-alias-label-primary-foreground);',
@@ -3067,10 +4858,7 @@ window.__ModuleLoader__.load({
3067
4858
  // the shared "common" namespace, and the service's fallback chain
3068
4859
  // serves English to any language we did not translate.
3069
4860
  try {
3070
- ctx.effect(() => ctx.locale.register(NS, {
3071
- zh: DICT.zh,
3072
- en: DICT.en,
3073
- }), 'dsh-explore: locale dictionaries');
4861
+ ctx.effect(() => ctx.locale.register(NS, DICT), 'dsh-explore: locale dictionaries');
3074
4862
  } catch (error) {
3075
4863
  // A profile without the locale plugin still gets the built-in table.
3076
4864
  }