samagotchi 0.179.0 → 0.181.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 (95) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +76 -1
  3. data/bin/chi +10 -0
  4. data/docs/architecture.md +1 -1
  5. data/docs/bundles.md +39 -3
  6. data/docs/cli.md +16 -9
  7. data/docs/configuration.md +25 -5
  8. data/docs/context.md +7 -0
  9. data/docs/internals/anthropic.md +4 -3
  10. data/docs/internals/background-tasks.md +4 -1
  11. data/docs/internals/block-renderers.md +11 -7
  12. data/docs/internals/bundles.md +12 -10
  13. data/docs/internals/objectives.md +9 -4
  14. data/docs/internals/web-frontend.md +127 -6
  15. data/docs/internals/working-set.md +24 -5
  16. data/docs/memory.md +3 -0
  17. data/docs/plugins.md +17 -6
  18. data/docs/sessions.md +1 -1
  19. data/docs/testing.md +5 -1
  20. data/lib/samagotchi/block_renderers.rb +22 -3
  21. data/lib/samagotchi/bundle_command.rb +9 -2
  22. data/lib/samagotchi/bundle_needs.rb +1 -1
  23. data/lib/samagotchi/bundle_settings_check.rb +5 -2
  24. data/lib/samagotchi/bundles/known-names/manifest.yml +2 -2
  25. data/lib/samagotchi/bundles/known-names/plugin.rb +4 -3
  26. data/lib/samagotchi/bundles/system/config_modification_protocol.md +3 -2
  27. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  28. data/lib/samagotchi/client.rb +8 -1
  29. data/lib/samagotchi/config.rb +6 -1
  30. data/lib/samagotchi/context_providers.rb +6 -8
  31. data/lib/samagotchi/core_notice.rb +44 -0
  32. data/lib/samagotchi/host_address.rb +7 -0
  33. data/lib/samagotchi/host_config.rb +8 -5
  34. data/lib/samagotchi/host_registry.rb +26 -8
  35. data/lib/samagotchi/installed_bundles/dir.rb +17 -55
  36. data/lib/samagotchi/installed_bundles/standing.rb +23 -3
  37. data/lib/samagotchi/installed_bundles.rb +26 -11
  38. data/lib/samagotchi/kernel_loop.rb +3 -2
  39. data/lib/samagotchi/llm/adapter_common.rb +3 -2
  40. data/lib/samagotchi/llm/adapters.rb +2 -1
  41. data/lib/samagotchi/llm/anthropic_assembly.rb +5 -0
  42. data/lib/samagotchi/llm/anthropic_messages.rb +6 -2
  43. data/lib/samagotchi/llm/chat_loop.rb +6 -5
  44. data/lib/samagotchi/llm/errors.rb +41 -3
  45. data/lib/samagotchi/llm/http.rb +85 -22
  46. data/lib/samagotchi/llm/openai_chat.rb +20 -3
  47. data/lib/samagotchi/memory_bundle/status.rb +10 -6
  48. data/lib/samagotchi/objectives.rb +7 -2
  49. data/lib/samagotchi/owner_lock.rb +2 -0
  50. data/lib/samagotchi/plugin/api.rb +4 -1
  51. data/lib/samagotchi/plugin/context.rb +9 -0
  52. data/lib/samagotchi/plugin/peer.rb +32 -15
  53. data/lib/samagotchi/plugin/tool_spec.rb +13 -2
  54. data/lib/samagotchi/row_refs.rb +14 -3
  55. data/lib/samagotchi/session_chain/delete.rb +6 -6
  56. data/lib/samagotchi/session_config.rb +15 -9
  57. data/lib/samagotchi/session_manager/removal.rb +2 -2
  58. data/lib/samagotchi/terminal_ui/attached_loop.rb +1 -1
  59. data/lib/samagotchi/terminal_ui/formatting.rb +13 -3
  60. data/lib/samagotchi/terminal_ui/join_replay.rb +1 -1
  61. data/lib/samagotchi/tool_ids.rb +19 -0
  62. data/lib/samagotchi/tool_runner.rb +8 -4
  63. data/lib/samagotchi/tools/registry.rb +3 -2
  64. data/lib/samagotchi/tools/task_runtime.rb +46 -3
  65. data/lib/samagotchi/turn_stages/objectives.rb +10 -5
  66. data/lib/samagotchi/version.rb +1 -1
  67. data/lib/samagotchi/web/public/app.js +22 -14
  68. data/lib/samagotchi/web/public/block_host.js +20 -20
  69. data/lib/samagotchi/web/public/block_renderers.css +5 -5
  70. data/lib/samagotchi/web/public/context_chips.js +183 -49
  71. data/lib/samagotchi/web/public/history_shape.js +5 -3
  72. data/lib/samagotchi/web/public/images.js +1 -1
  73. data/lib/samagotchi/web/public/index.html +90 -5
  74. data/lib/samagotchi/web/public/objectives_strip.js +16 -6
  75. data/lib/samagotchi/web/public/pan_zoom.js +121 -0
  76. data/lib/samagotchi/web/public/peer_chip.js +171 -0
  77. data/lib/samagotchi/web/public/peer_data.js +131 -0
  78. data/lib/samagotchi/web/public/peer_exchange.js +83 -0
  79. data/lib/samagotchi/web/public/peer_links.js +161 -0
  80. data/lib/samagotchi/web/public/peer_note.js +49 -0
  81. data/lib/samagotchi/web/public/picture_viewer.js +304 -0
  82. data/lib/samagotchi/web/public/popover_modal.js +3 -2
  83. data/lib/samagotchi/web/public/session_view.js +10 -1
  84. data/lib/samagotchi/web/public/stream_handlers.js +17 -4
  85. data/lib/samagotchi/web/public/turn_html.js +11 -2
  86. data/lib/samagotchi/web/public/working_set.js +9 -3
  87. data/lib/samagotchi/web/public/working_set_view.js +28 -11
  88. data/lib/samagotchi/web/public/ws_cards.js +36 -10
  89. data/lib/samagotchi/web/public/ws_markdown.js +129 -0
  90. data/lib/samagotchi/web/public/ws_order.js +48 -0
  91. data/lib/samagotchi/web/public/ws_peek.js +22 -5
  92. data/lib/samagotchi/web/public/ws_preview.css +41 -1
  93. data/lib/samagotchi/web/public/ws_reader.js +35 -6
  94. data/lib/samagotchi/web/public/ws_sections.js +24 -15
  95. metadata +11 -1
@@ -29,7 +29,7 @@
29
29
  /* Icon masks shared by the phone info bar and the all view's cards (the stroke only shapes the mask; the icon takes currentColor); the image icon is composer.css's. */
30
30
  :root{--icon-archive:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='none' stroke='black' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='2' y='2.75' width='12' height='3.5' rx='1'/%3E%3Cpath d='M3.25 6.25v6a1 1 0 0 0 1 1h7.5a1 1 0 0 0 1-1v-6M6.5 9h3'/%3E%3C/svg%3E");--icon-unarchive:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='none' stroke='black' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='2' y='2.75' width='12' height='3.5' rx='1'/%3E%3Cpath d='M3.25 6.25v6a1 1 0 0 0 1 1h7.5a1 1 0 0 0 1-1v-6M8 11.5V8.25M6.5 9.75 8 8.25l1.5 1.5'/%3E%3C/svg%3E")}
31
31
  /* The phone's safe areas (the notch, the status bar, the home indicator; 0 elsewhere): main's padding, the bottom
32
- sheets, the update sheet, the toast and the lightbox keep clear of them. One name per side, so the e2e can set them. */
32
+ sheets, the update sheet, the toast and the picture viewer keep clear of them. One name per side, so the e2e can set them. */
33
33
  :root{--safe-t:env(safe-area-inset-top,0px);--safe-r:env(safe-area-inset-right,0px);--safe-b:env(safe-area-inset-bottom,0px);--safe-l:env(safe-area-inset-left,0px)}
34
34
  *{box-sizing:border-box;margin:0;padding:0}
35
35
  /* No iOS text autosizing: it grows text in a box sized for the text as written (it clipped the session cards). */
@@ -508,6 +508,44 @@ button.system-one-wrong,.system-one-wrong.marked{flex:none;padding:1px 6px;borde
508
508
  .bubble.note{border-left:3px dotted var(--text-faint);background:transparent;font-size:12px;color:var(--text-muted);opacity:.85}
509
509
  .note-line{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--text-faint);margin-bottom:2px}
510
510
  .note-text{white-space:pre-wrap;max-height:8em;overflow:auto}
511
+ /* A peer's answer (peer_note.js): a bubble from the peer, not a dotted system note; its verdict pill, the ↑ to its
512
+ send, "Read the full answer" (the newest answer only) and chi's instruction folded under "what chi told the agent".
513
+ A send's state (peer_exchange.js pillTemplate) is a pill in the chip's shape after the row's params. */
514
+ .bubble.note.peer-answer{border:1px solid var(--border-strong);border-radius:10px;background:var(--bg-panel);opacity:1;font-size:13px;color:var(--text);white-space:normal;display:flex;flex-direction:column;gap:8px}
515
+ .bubble.note.peer-answer .note-text{max-height:none;overflow:visible;line-height:1.5}
516
+ .peer-head{display:flex;flex-wrap:wrap;align-items:baseline;gap:4px 8px}
517
+ .peer-who{font-weight:700;color:var(--text-bright)}
518
+ .peer-mark{margin-left:auto;display:inline-flex;align-items:baseline;gap:8px}
519
+ .peer-closed{font-size:12px;color:var(--ok-text)}
520
+ :is(.peer-state,.peer-verdict){display:inline-block;padding:2px 9px;border-radius:999px;font:600 11px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;white-space:nowrap;border:1px solid var(--border-strong);color:var(--text-3);background:transparent}
521
+ :is(.peer-state,.peer-verdict).changes{color:var(--warn-text);background:var(--warn-bg);border-color:var(--warn-border)}
522
+ :is(.peer-state,.peer-verdict).ok{color:var(--ok-text);background:var(--ok-bg);border-color:color-mix(in srgb,var(--ok) 45%,transparent)}
523
+ .peer-state.waiting{color:var(--accent);background:var(--accent-bg);border-color:var(--accent-border)}
524
+ .peer-state.failed{color:var(--danger-text);background:var(--danger-bg-dim);border-color:color-mix(in srgb,var(--danger) 45%,transparent)}
525
+ .peer-slot{margin-left:auto;display:inline-flex}
526
+ .peer-slot:empty{display:none}
527
+ button.peer-state{cursor:pointer}
528
+ @media(hover:hover){button.peer-state:hover{filter:brightness(1.15)}}
529
+ .peer-short{display:none}
530
+ :is(button.peer-up,button.peer-full){padding:0;border:0;background:none;color:var(--accent);font:inherit;font-size:12px;text-align:left;cursor:pointer}
531
+ @media(hover:hover){:is(button.peer-up,button.peer-full):hover{color:var(--text-hover);text-decoration:underline}}
532
+ .peer-foot{display:flex;flex-wrap:wrap;align-items:baseline;gap:6px 14px;font-size:12px}
533
+ .peer-told>summary{cursor:pointer;color:var(--text-3);list-style:none;width:max-content}
534
+ .peer-told>summary::-webkit-details-marker{display:none}
535
+ .peer-told>summary::before{content:"\25B8 "}
536
+ .peer-told[open]{flex-basis:100%}
537
+ .peer-told[open]>summary::before{content:"\25BE "}
538
+ .peer-told-text{margin-top:6px;white-space:pre-wrap;color:var(--text-muted);max-height:16em;overflow:auto}
539
+ @media(max-width:600px){
540
+ .peer-short{display:inline}
541
+ :is(.peer-state,.peer-verdict) .peer-long:has(+.peer-short),.peer-verdict .peer-long{display:none}
542
+ .activity-row .peer-slot{order:1;flex:1 1 100%;margin:2px 0 0 var(--row-gutter)}
543
+ .activity-row:has(>.peer-slot:not(:empty))>.activity-duration{display:none}
544
+ .activity-row button.peer-state{min-height:44px;padding:10px 12px;font-size:12px;box-sizing:border-box}
545
+ .peer-head .peer-up-slot{flex:1 1 100%;order:3}
546
+ button.peer-up{padding:6px 0;min-height:32px}
547
+ button.peer-full{padding:12px 0}
548
+ }
511
549
  .bubble.command.busy{border-left-color:var(--warn)}
512
550
  .bubble.command.failed{border-left-color:var(--danger)}
513
551
  .bubble.command.queued{border-left-style:dashed}
@@ -757,10 +795,28 @@ body.has-session #history{padding-bottom:calc(var(--dock-h,160px) + 16px + var(-
757
795
  .thumb{max-height:120px;max-width:200px;border-radius:6px;border:1px solid var(--border-strong);cursor:zoom-in;object-fit:contain;background:var(--bg)}
758
796
  .activity-row .thumbs{flex-basis:100%;margin-left:var(--row-gutter)}
759
797
  @media(max-width:600px){.activity-row .thumbs{margin-left:0}}
760
- /* The image keeps clear of the notch and the home indicator (its padding: the safe areas; 0 on a desktop). */
761
- #lightbox{position:fixed;inset:0;z-index:50;background:var(--backdrop);display:flex;align-items:center;justify-content:center;cursor:zoom-out;padding:var(--safe-t) var(--safe-r) var(--safe-b) var(--safe-l)}
798
+ /* The picture viewer (picture_viewer.js): an opaque surface in the page's background (a diagram's ink is the theme's text colour, which a dark backdrop hides on the light theme). Its padding is the safe areas, read as the fit's insets; the picture is placed at 0,0 by its box's size and translate, not by flex. touch-action:none: the page under it never scrolls or zooms. */
799
+ #lightbox{position:fixed;inset:0;z-index:50;background:var(--bg);overflow:hidden;touch-action:none;cursor:grab;user-select:none;-webkit-user-select:none;-webkit-touch-callout:none;outline:none;box-sizing:border-box;padding:var(--safe-t) var(--safe-r) var(--safe-b) var(--safe-l)}
800
+ #lightbox.dragging{cursor:grabbing}
762
801
  #lightbox[hidden]{display:none}
763
- #lightbox img{max-width:min(96vw,100%);max-height:min(94vh,100%);border-radius:6px}
802
+ #lightbox .pv-pic{position:absolute;left:0;top:0}
803
+ #lightbox .pv-pic.waiting{visibility:hidden}
804
+ /* No native image drag (it would cancel the pointer) and no iOS long-press sheet during a slow pan. */
805
+ #lightbox img{display:block;width:100%;height:100%;-webkit-user-drag:none;user-select:none;-webkit-user-select:none;-webkit-touch-callout:none;pointer-events:none}
806
+ /* ✕ top right, the bar bottom centre, glass cards a little more solid than the page's (they sit over any picture, a white screenshot too), both clear of the notch, the side insets and the home indicator; the standalone phone app's ✕ also clears iOS's blurred band under the clock. */
807
+ #lightbox .pv-close{position:absolute;top:calc(var(--safe-t) + 10px);right:calc(var(--safe-r) + 10px)}
808
+ @media (display-mode:standalone) and (max-width:600px){#lightbox .pv-close{top:calc(var(--safe-t) + 22px)}}
809
+ #lightbox .pv-bar{position:absolute;left:calc((100% + var(--safe-l) - var(--safe-r)) / 2);bottom:calc(var(--safe-b) + 14px);transform:translateX(-50%);display:flex;align-items:center;gap:2px;padding:3px;cursor:default}
810
+ #lightbox .pv-close,#lightbox .pv-bar{z-index:1;border-radius:12px;background:color-mix(in srgb,var(--bg-panel) 88%,transparent);-webkit-backdrop-filter:blur(18px) saturate(1.35);backdrop-filter:blur(18px) saturate(1.35);border:1px solid var(--glass-border);box-shadow:inset 0 1px 0 var(--glass-highlight),var(--glass-shadow)}
811
+ @media (prefers-reduced-transparency:reduce){#lightbox .pv-close,#lightbox .pv-bar{background:var(--bg-panel);-webkit-backdrop-filter:none;backdrop-filter:none}}
812
+ body.no-glass #lightbox :is(.pv-close,.pv-bar){background:var(--bg-panel);-webkit-backdrop-filter:none;backdrop-filter:none}
813
+ #lightbox .pv-btn{display:inline-flex;align-items:center;justify-content:center;min-width:36px;height:36px;padding:0 8px;border-radius:9px;background:transparent;color:var(--text);font-size:13px}
814
+ #lightbox .pv-fit{color:var(--text-2)}
815
+ #lightbox .pv-btn svg{display:block}
816
+ @media (pointer:coarse){#lightbox .pv-btn{min-width:44px;height:44px}}
817
+ @media(hover:hover){#lightbox .pv-btn:hover{background:var(--bg-raised);filter:none}}
818
+ #lightbox .pv-pct{min-width:52px;text-align:center;font-size:13px;font-variant-numeric:tabular-nums;color:var(--text-2)}
819
+ #lightbox .pv-sep{width:1px;height:18px;margin:0 3px;background:var(--border-strong)}
764
820
  /* The model picker (the start page, and a fresh chain link: start_page.js syncModelPick): reads as a label, "host:model ▾", left of Start; a button under a drawn caret that opens a searchable list (model_picker.js). Its name ellipsizes within max-width. */
765
821
  #composer .actions-col .model-pick{order:0;position:relative;display:inline-block;max-width:min(50%,380px);height:28px;min-height:28px;padding:0 22px 0 8px;border-radius:8px;overflow:hidden;background:transparent;color:var(--text-muted);font-size:12px;line-height:28px;text-align:left;text-overflow:ellipsis;transition:background .12s ease,color .12s ease}
766
822
  /* The start page's row stays one row (Start never wraps): the model name gives way first, down to its min-width, then the override chips ellipsize (100000x their shrink weight: at 1000x their share of the shrink was still a fraction of a pixel, enough for an ellipsis). Scoped off the session composer and a fresh link's button. */
@@ -1142,8 +1198,9 @@ button.ws-step:hover:not(:disabled){filter:none}@media(hover:hover){button.ws-st
1142
1198
  .ws-sec-head{display:flex;align-items:center;gap:8px;width:100%;min-height:30px;box-sizing:border-box;margin-top:6px;padding:0 6px;border:0;border-top:1px solid var(--border);border-radius:0;background:transparent;font-family:ui-sans-serif,system-ui,sans-serif;font-size:12px;color:var(--ws-muted);text-align:left;cursor:pointer}
1143
1199
  .ws-sec-head:hover:not(:disabled){filter:none}@media(hover:hover){.ws-sec-head:hover{background:var(--bg-hover)}}
1144
1200
  .ws-sec-head .k{flex:none;width:12px;text-align:center;color:var(--ws-faint)}
1145
- .ws-sec-head .t{font-weight:600;color:var(--text-2)}
1201
+ .ws-sec-head .t{flex:none;white-space:nowrap;font-weight:600;color:var(--text-2)}
1146
1202
  .ws-sec-head .n{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--ws-faint)}
1203
+ .ws-sec-head .w{flex:none;white-space:nowrap;color:var(--warn-text)}
1147
1204
  .ws-sec-head .tk{flex:none;margin-left:auto;font-size:11px;color:var(--ws-faint);font-variant-numeric:tabular-nums}
1148
1205
  .ws-sec .ws-sub{margin-top:2px;padding-left:6px}
1149
1206
  .ws-row.part .t{margin-right:auto;font-family:ui-sans-serif,system-ui,sans-serif}
@@ -1371,6 +1428,34 @@ body.has-session.composer-folded #infoBar{border-top-color:transparent}
1371
1428
  #infoBar .ctx-chip.empty{color:var(--text-faint);border-style:dashed}
1372
1429
  #infoBar .ctx-chip.error{color:var(--danger-text);border-color:color-mix(in srgb,var(--danger) 55%,transparent);background:var(--danger-bg-dim)}
1373
1430
  .ctx-dot{width:7px;height:7px;border-radius:50%;background:var(--accent);box-shadow:0 0 0 2px var(--accent-ring)}
1431
+ /* A paired peer's one chip (peer_chip.js): waiting in the accent, can't send in warn, answers only dashed. */
1432
+ #infoBar .ctx-chip.peer.waiting{color:var(--text);background:var(--accent-bg);border-color:var(--accent-border)}
1433
+ #infoBar .ctx-chip.peer.cant-send{color:var(--warn-text);background:var(--warn-bg);border-color:var(--warn-border)}
1434
+ #infoBar .ctx-chip.peer.answers-only{border-style:dashed}
1435
+ /* Its popover (scene 2): the two ways, the last exchanges, its actions; a bottom sheet on a phone. */
1436
+ .ctx-popover.peer-pop{gap:12px}
1437
+ .ctx-popover.peer-pop .ctx-pop-head strong{font-family:inherit;font-size:15px}
1438
+ .ctx-popover.peer-pop .ctx-pop-head .ctx-pop-kind{margin-left:auto;font-size:12px}
1439
+ .ctx-popover.peer-pop .ctx-pop-head .ctx-pop-close{margin-left:0}
1440
+ .ctx-popover.sheet{border-radius:14px}
1441
+ .peer-pop-legs{display:flex;flex-direction:column;gap:6px}
1442
+ .peer-pop-legs>div{display:flex;gap:8px}
1443
+ .peer-pop-legs>div>span:first-child{flex:0 0 78px;color:var(--text-muted)}
1444
+ .peer-pop-legs .warn{color:var(--warn-text)}
1445
+ .peer-pop-list{display:flex;flex-direction:column}
1446
+ .peer-pop-list-head{font-size:12px;font-weight:700;color:var(--text-muted);padding-bottom:4px}
1447
+ .peer-pop-x{display:flex;gap:10px;align-items:baseline;width:100%;box-sizing:border-box;padding:7px 0;margin:0;border:0;border-top:1px solid var(--border-strong);border-radius:0;background:transparent;color:inherit;font:inherit;text-align:left}
1448
+ button.peer-pop-x{cursor:pointer}@media(hover:hover){button.peer-pop-x:hover .pp-x-what{color:var(--text-hover);text-decoration:underline}}
1449
+ .pp-x-at{flex:none;font:11px ui-monospace,monospace;color:var(--text-muted)}
1450
+ .pp-x-what{flex:1;min-width:0;color:var(--text);overflow-wrap:anywhere}
1451
+ .pp-x-state{flex:none;color:var(--text-muted)}
1452
+ .pp-x-state.waiting{color:var(--accent)}
1453
+ .pp-x-state.changes{color:var(--warn-text)}
1454
+ .pp-x-state:is(.ok,.answered){color:var(--ok-text)}
1455
+ .pp-x-state.failed{color:var(--danger-text)}
1456
+ .ctx-popover.peer-pop .ctx-pop-actions{justify-content:flex-start;flex-wrap:wrap}
1457
+ .ctx-popover.peer-pop .ctx-pop-actions button{min-height:44px;padding:10px 12px;border-radius:8px}
1458
+ .ctx-popover.peer-pop .ctx-pop-actions .ctx-pop-detach{color:var(--danger-text)}
1374
1459
  .ctx-popover{position:fixed;z-index:60;max-height:min(60vh,520px);overflow:auto;padding:12px 14px;border-radius:12px;background:var(--bg-panel);color:var(--text-2);border:1px solid var(--border-strong);box-shadow:var(--toast-shadow);font-size:13px;line-height:1.45;display:flex;flex-direction:column;gap:6px}
1375
1460
  .ctx-popover[hidden]{display:none}
1376
1461
  /* The participants chip (info bar) and its panel (participants_panel.js). */
@@ -1,7 +1,9 @@
1
1
  // The session's objectives above the conversation: the fold's current state
2
2
  // (Objectives.view), from the session read (seed) and live from the stream's
3
- // objectives_updated (update). No list: the element stays hidden, nothing on
4
- // the page. A tap opens the edit list (chip_popover.js: a bottom sheet on a
3
+ // objectives_updated (update). No list, or one with only dropped objectives:
4
+ // the element stays hidden, nothing on the page (while its edit list is open
5
+ // the strip stays as the list's anchor, so an Undo just shown doesn't go
6
+ // under the finger; it goes when the list closes). A tap opens the edit list (chip_popover.js: a bottom sheet on a
5
7
  // phone): add, done, drop, undo and a new text, each a /objectives line on the
6
8
  // command route, the one way to an edit, so its refusals are the command's. No
7
9
  // message and no turn; the worker's next event redraws (every tab's), and a
@@ -41,9 +43,14 @@ export function createObjectivesStrip({ el, session = () => null, running = () =
41
43
  return html`<button type="button" class=${`obj-chip obj-open ${item.status}${first ? " first" : ""}`} data-id=${item.id} title=${item.text} aria-expanded="false"><span class="obj-id">${item.id}</span><span class="obj-text">${item.status === DONE ? "✓ " : ""}${item.text}</span></button>`;
42
44
  }
43
45
 
46
+ // Something still meant: an active or a done objective.
47
+ const meant = () => !!list && stripItems(list).length > 0;
48
+ // The strip is drawn: something meant, or its edit list open.
49
+ const shown = () => meant() || (!!list && shell.isOpen());
50
+
44
51
  function draw() {
45
- el.hidden = !list;
46
- if (!list) {
52
+ el.hidden = !shown();
53
+ if (el.hidden) {
47
54
  render(nothing, el);
48
55
  return;
49
56
  }
@@ -135,7 +142,7 @@ export function createObjectivesStrip({ el, session = () => null, running = () =
135
142
  };
136
143
 
137
144
  const shell = createChipPopover({
138
- id: "objectivesPanel", className: "ctx-popover obj-panel", width: 560, el, anchor: ".obj-open", summary: () => list,
145
+ id: "objectivesPanel", className: "ctx-popover obj-panel", width: 560, el, anchor: ".obj-open", summary: () => (shown() ? list : null),
139
146
  session, label: "Objectives", sheet: true, sheetShare: SHEET_TALL, doc, win,
140
147
  show: () => render(panelTemplate(), shell.pop),
141
148
  onOpen: () => {
@@ -146,6 +153,8 @@ export function createObjectivesStrip({ el, session = () => null, running = () =
146
153
  onClose: () => {
147
154
  editing = null;
148
155
  told.clear();
156
+ // An only-dropped list's strip goes with its edit list.
157
+ draw();
149
158
  },
150
159
  onSubmit: (form) => {
151
160
  const text = form.elements.text.value;
@@ -253,7 +262,8 @@ export function createObjectivesStrip({ el, session = () => null, running = () =
253
262
  take(null);
254
263
  },
255
264
  notYet,
256
- hasList: () => !!list,
265
+ // Something still meant (an only-dropped list is none).
266
+ hasList: meant,
257
267
  hasActive: () => hasActive(list),
258
268
  // An objective's last move as the view has it (its state, its backing), null with none.
259
269
  moveOf: (id) => list?.items?.find((i) => i.id === id)?.move ?? null,
@@ -0,0 +1,121 @@
1
+ // The picture viewer's maths (picture_viewer.js), pure: no DOM, `node --test`.
2
+ //
3
+ // A view is {scale, x, y}: the picture drawn at scale × its natural size, its
4
+ // top-left corner at (x, y) in the stage's px. A stage is {width, height,
5
+ // insets: {t, r, b, l}, bar}: the viewer's box, the safe areas and the bar's
6
+ // room at the bottom; the picture is fitted and centred in what they leave.
7
+ // A picture is {width, height}, its natural size.
8
+ //
9
+ // A module of its own: its exports are new (docs/internals/web-frontend.md).
10
+
11
+ // Never closer than 8 × natural.
12
+ export const MAX_ZOOM = 8;
13
+ // A fitted picture is never blown up past this: a tiny diagram stays small.
14
+ export const MAX_FIT = 3;
15
+ // A side of the shown picture past this isn't asked of the browser.
16
+ export const MAX_SHOWN_SIDE = 16000;
17
+ // Nor a shown area past this: 4096², iOS Safari's own canvas cap, as the budget
18
+ // for an image drawn at its layout size on an iPhone (block_host.js's
19
+ // MAX_PICTURE_PIXELS, 100M, is what the page holds at all, far over what a phone draws).
20
+ export const MAX_SHOWN_PIXELS = 4096 * 4096;
21
+ // The room kept around a fitted picture.
22
+ export const FIT_PAD = 24;
23
+ // The bar's room at the bottom (its height and its offset).
24
+ export const BAR_ROOM = 56;
25
+ // A larger picture keeps at least this much of itself on screen.
26
+ export const KEEP = 60;
27
+ // A trackpad sends many small deltas: the zoom follows them, not fixed steps.
28
+ const WHEEL_ZOOM = 0.01;
29
+ // A mouse's one notch with Ctrl held is about 100 px: no more than this per event.
30
+ const WHEEL_ZOOM_MAX_DELTA = 60;
31
+ const LINE_PX = 16;
32
+ const PAGE_PX = 400;
33
+
34
+ const insetsOf = (stage) => ({ t: 0, r: 0, b: 0, l: 0, ...(stage.insets || {}) });
35
+
36
+ // The part of the stage the picture is fitted and centred in.
37
+ export function freeBox(stage) {
38
+ const i = insetsOf(stage);
39
+ const bar = stage.bar ?? 0;
40
+ return { left: i.l, top: i.t, width: Math.max(0, stage.width - i.l - i.r), height: Math.max(0, stage.height - i.t - i.b - bar) };
41
+ }
42
+
43
+ // The scale at which the whole picture shows in the stage, minus its padding,
44
+ // the safe areas and the bar; never above +max+.
45
+ export function fitScale(picture, stage, { pad = FIT_PAD, max = MAX_FIT } = {}) {
46
+ if (!(picture?.width > 0 && picture?.height > 0)) return 1;
47
+ const box = freeBox(stage);
48
+ const w = Math.max(1, box.width - pad * 2);
49
+ const h = Math.max(1, box.height - pad * 2);
50
+ return Math.min(w / picture.width, h / picture.height, max);
51
+ }
52
+
53
+ // The closest a picture goes: 8 × natural, less when a side would pass
54
+ // MAX_SHOWN_SIDE or the area MAX_SHOWN_PIXELS; never under +fit+.
55
+ export function maxScale(picture, fit = 0) {
56
+ const side = Math.max(picture.width, picture.height);
57
+ const byArea = Math.sqrt(MAX_SHOWN_PIXELS / (picture.width * picture.height));
58
+ return Math.max(Math.min(MAX_ZOOM, MAX_SHOWN_SIDE / side, byArea), fit);
59
+ }
60
+
61
+ // +scale+ within the limits: half of min(fit, 1) at the farthest, maxScale at
62
+ // the closest. +limits+: {fit, picture}.
63
+ export function clampScale(scale, { fit, picture }) {
64
+ const min = Math.min(fit, 1) / 2;
65
+ return Math.min(Math.max(scale, min), maxScale(picture, fit));
66
+ }
67
+
68
+ // The view at scale +next+ that keeps the picture's point under +point+ still.
69
+ export function zoomAt(view, next, point) {
70
+ const k = next / view.scale;
71
+ return { scale: next, x: point.x - (point.x - view.x) * k, y: point.y - (point.y - view.y) * k };
72
+ }
73
+
74
+ function clampAxis(at, size, start, room, keep) {
75
+ if (size <= room) return start + (room - size) / 2;
76
+ return Math.min(start + room - keep, Math.max(start + keep - size, at));
77
+ }
78
+
79
+ // A picture smaller than the free box on an axis is centred on it; a larger one
80
+ // keeps at least +keep+ px of itself on screen.
81
+ export function clampView(view, picture, stage, keep = KEEP) {
82
+ const box = freeBox(stage);
83
+ const w = picture.width * view.scale;
84
+ const h = picture.height * view.scale;
85
+ const x = w <= box.width ? box.left + (box.width - w) / 2 : clampAxis(view.x, w, 0, stage.width, keep);
86
+ const y = h <= box.height ? box.top + (box.height - h) / 2 : clampAxis(view.y, h, 0, stage.height, keep);
87
+ return { scale: view.scale, x, y };
88
+ }
89
+
90
+ // The fitted view: the whole picture, centred.
91
+ export function fitView(picture, stage) {
92
+ return clampView({ scale: fitScale(picture, stage), x: 0, y: 0 }, picture, stage);
93
+ }
94
+
95
+ const distance = (a, b) => Math.hypot(a.x - b.x, a.y - b.y);
96
+ const midpoint = (a, b) => ({ x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 });
97
+
98
+ // Two pointers against the pinch's +start+ ({a, b, view}): the view whose scale
99
+ // follows their spread (through +limit+, a scale => scale) and whose picture
100
+ // point under the start's midpoint stays under the new midpoint.
101
+ export function pinch(start, a, b, limit = (s) => s) {
102
+ const from = distance(start.a, start.b);
103
+ const ratio = from > 0 ? distance(a, b) / from : 1;
104
+ const scale = limit(start.view.scale * ratio);
105
+ const was = midpoint(start.a, start.b);
106
+ const now = midpoint(a, b);
107
+ const k = scale / start.view.scale;
108
+ return { scale, x: now.x - (was.x - start.view.x) * k, y: now.y - (was.y - start.view.y) * k };
109
+ }
110
+
111
+ // A wheel event's move in px and its zoom factor: lines (deltaMode 1) are 16 px,
112
+ // pages (2) 400; the factor is exp(-deltaY × 0.01), each event's capped.
113
+ export function wheelStep(event) {
114
+ const unit = event.deltaMode === 1 ? LINE_PX : event.deltaMode === 2 ? PAGE_PX : 1;
115
+ let dx = (event.deltaX || 0) * unit;
116
+ let dy = (event.deltaY || 0) * unit;
117
+ // Shift + a mouse wheel moves sideways.
118
+ if (event.shiftKey && !dx) [dx, dy] = [dy, 0];
119
+ const capped = Math.max(-WHEEL_ZOOM_MAX_DELTA, Math.min(WHEEL_ZOOM_MAX_DELTA, (event.deltaY || 0) * unit));
120
+ return { dx, dy, zoom: Math.exp(-capped * WHEEL_ZOOM) };
121
+ }
@@ -0,0 +1,171 @@
1
+ // A paired peer in the session bar: its two context sources (<name>-inbox,
2
+ // <name>-outbox) drawn as one chip that says how the pairing stands
3
+ // (paired, waiting, answered, can't send, answers only), and that chip's
4
+ // popover (how chi and the peer reach each other, the last exchanges, View
5
+ // latest answer, Status card, Unpair). Pure templates and models: the
6
+ // chips' controller (context_chips.js) draws them, the exchanges are the
7
+ // peers model's (peer_data.js, GET …/peers). docs/internals/web-frontend.md,
8
+ // The peer exchange. Its own module: new exports go in new modules.
9
+
10
+ import { html, nothing } from "./vendor/lit-html.js";
11
+ import { spanText, verdictWord } from "./peer_exchange.js";
12
+ import { wallClock } from "./format.js";
13
+
14
+ // A peer chip's key among the chips ("peer:claude"); an ordinary chip's is
15
+ // its source's name, which never holds a ":" (ContextSources' names).
16
+ export const peerKey = (name) => `peer:${name}`;
17
+
18
+ // How many exchanges the popover lists (the newest).
19
+ export const POPOVER_EXCHANGES = 8;
20
+
21
+ // GET …/context's rows split: the peer sources (a row with `peer` and its
22
+ // `leg`) grouped per peer, {key, name, label, inbox, outbox} (a leg's row
23
+ // or null; a muted leg stays in its group), in the order their first leg
24
+ // comes; and the rest, the ordinary rows, as they were.
25
+ export function peerGroups(rows) {
26
+ const peers = new Map();
27
+ const rest = [];
28
+ for (const row of rows || []) {
29
+ if (!row) continue;
30
+ if (!row.peer || !["inbox", "outbox"].includes(row.leg)) {
31
+ rest.push(row);
32
+ continue;
33
+ }
34
+ let group = peers.get(row.peer);
35
+ if (!group) {
36
+ group = { key: peerKey(row.peer), name: row.peer, label: row.label || row.peer, inbox: null, outbox: null };
37
+ peers.set(row.peer, group);
38
+ }
39
+ group[row.leg] = row;
40
+ }
41
+ return { peers: [...peers.values()], rest };
42
+ }
43
+
44
+ // A leg that counts: there and not muted.
45
+ const live = (leg) => (leg && !leg.muted ? leg : null);
46
+ // The group's legs as the chip reads them, and whether it shows at all
47
+ // (a group whose legs are all muted is gone from the bar, as a muted row is).
48
+ export const peerShown = (group) => !!(live(group.inbox) || live(group.outbox));
49
+
50
+ // The sends among +exchanges+ (newest first): an unclaimed answer has no id.
51
+ const sends = (exchanges) => (exchanges || []).filter((ex) => ex?.id);
52
+ const ASKS = ["validate", "question"];
53
+
54
+ // The newest send failed and the peer hasn't paired again since: pairing
55
+ // again (the pair script) pushes the inbox, which moves its row's
56
+ // fetched_at past the failed send's time.
57
+ export function cantSend(group, exchanges) {
58
+ const newest = sends(exchanges)[0];
59
+ if (newest?.state !== "failed") return false;
60
+ const paired = Date.parse(live(group.inbox)?.fetched_at || "");
61
+ const failed = Date.parse(newest.at || "");
62
+ return !(paired > failed);
63
+ }
64
+ const since = (iso, now) => {
65
+ const at = Date.parse(iso || "");
66
+ return Number.isNaN(at) ? null : now - at;
67
+ };
68
+
69
+ // The chip of +group+: the first state that applies.
70
+ // - answers-only: no inbox leg (chi can't send);
71
+ // - cant-send: the newest send failed (the transport refused it);
72
+ // - waiting: the newest validate or question send has no answer (its age the send's);
73
+ // - answered: the outbox has a text the agent hasn't read (its age the text's), with the dot;
74
+ // - paired otherwise.
75
+ // +exchanges+: the peer's from GET …/peers, newest first ([] when not read,
76
+ // an older chi web, a peer the read doesn't name: nothing then says failed).
77
+ // @return {key, name, state, label, title, dot}
78
+ export function peerChipModel(group, exchanges = [], now = Date.now()) {
79
+ const inbox = live(group.inbox);
80
+ const outbox = live(group.outbox);
81
+ const all = sends(exchanges);
82
+ const ask = all.find((ex) => ASKS.includes(ex.kind));
83
+ let state = "paired";
84
+ let words = "paired";
85
+ let why = "paired: chi can send to it and it answers into its outbox";
86
+ if (!inbox) {
87
+ state = "answers-only";
88
+ words = "answers only";
89
+ why = "no inbox attached here: it answers, chi can't send to it";
90
+ } else if (cantSend(group, exchanges)) {
91
+ state = "cant-send";
92
+ words = "can't send";
93
+ why = `the last send didn't go through: pair again from ${group.label}`;
94
+ } else if (ask?.state === "waiting") {
95
+ const age = since(ask.at, now);
96
+ state = "waiting";
97
+ words = age === null ? "waiting" : `waiting ${spanText(age)}`;
98
+ why = [ask.kind, ask.title].filter(Boolean).join(" · ") || "a send";
99
+ why = `waiting for its answer to ${why}`;
100
+ } else if (outbox?.unread && outbox.has_text) {
101
+ const age = since(outbox.fetched_at, now);
102
+ state = "answered";
103
+ words = age === null ? "answered" : `answered ${spanText(age)}`;
104
+ why = "an answer the agent hasn't read yet";
105
+ }
106
+ return { key: group.key, name: group.key, state, label: `${group.label} · ${words}`, title: why,
107
+ dot: state === "answered", peer: true };
108
+ }
109
+
110
+ // An exchange's state as the popover's list says it: "waiting 2m",
111
+ // "changes · 11m", "ok · 4m", "answered · 4m", "no answer expected",
112
+ // "not sent"; +kind+ its tint.
113
+ // @return {text, kind}
114
+ export function exchangeState(ex, now = Date.now()) {
115
+ if (ex.state === "failed") return { text: "not sent", kind: "failed" };
116
+ if (ex.state === "none_expected") return { text: "no answer expected", kind: "none" };
117
+ if (ex.state === "waiting") {
118
+ const age = since(ex.at, now);
119
+ return { text: age === null ? "waiting" : `waiting ${spanText(age)}`, kind: "waiting" };
120
+ }
121
+ const took = ex.answer?.at ? since(ex.at, Date.parse(ex.answer.at)) : null;
122
+ const verdict = verdictWord(ex.answer?.verdict);
123
+ const word = verdict || "answered";
124
+ return { text: took === null ? word : `${word} · ${spanText(took)}`, kind: verdict || "answered" };
125
+ }
126
+
127
+ // The popover's inside for +group+ (scene 2). +exchanges+ newest first;
128
+ // +text+ the outbox's text once View latest answer read it (null before);
129
+ // +status+ the status card's command ("/claude") when the session has it,
130
+ // else null; +drawn+(id) whether that send's row is in the conversation
131
+ // (its list row then jumps to it).
132
+ export function peerPopoverTemplate(group, exchanges = [], { text = null, status = null, drawn = () => false, now = Date.now() } = {}) {
133
+ const inbox = live(group.inbox);
134
+ const outbox = live(group.outbox);
135
+ const all = sends(exchanges);
136
+ const lastSent = all.find((ex) => ex.state !== "failed");
137
+ const sendsLine = !inbox
138
+ ? "can't: no inbox attached here"
139
+ : cantSend(group, exchanges)
140
+ ? `the last send didn't go through: pair again from ${group.label}`
141
+ : [`to its inbox (${group.inbox.name})`, lastSent ? `last sent ${wallClock(lastSent.at, now)}` : ""].filter(Boolean).join(" · ");
142
+ const answersLine = outbox
143
+ ? [`into ${outbox.name}`, outbox.fetched_at ? `last ${wallClock(outbox.fetched_at, now)}` : "nothing yet"].join(" · ")
144
+ : "no outbox attached";
145
+ const list = all.slice(0, POPOVER_EXCHANGES);
146
+ const rowInside = (ex) => {
147
+ const state = exchangeState(ex, now);
148
+ return html`<span class="pp-x-at">${wallClock(ex.at, now)}</span><span class="pp-x-what">${
149
+ [ex.kind, ex.title].filter(Boolean).join(" · ") || "a send"}</span><span class=${`pp-x-state ${state.kind}`}>${state.text}</span>`;
150
+ };
151
+ const legs = [group.inbox, group.outbox].filter(Boolean);
152
+ return html`<div class="ctx-pop-head"><strong>${group.label}</strong
153
+ ><span class="ctx-pop-kind">paired peer</span
154
+ ><button type="button" class="ctx-pop-close" data-act="close" aria-label="Close">×</button></div
155
+ ><div class="peer-pop-legs"><div><span>chi sends</span><span class=${inbox && cantSend(group, exchanges) ? "warn" : ""}>${sendsLine}</span></div
156
+ ><div><span>it answers</span><span>${answersLine}</span></div></div
157
+ >${list.length ? html`<div class="peer-pop-list"><div class="peer-pop-list-head">Exchanges</div>${list.map((ex) => (drawn(ex.id)
158
+ ? html`<button type="button" class="peer-pop-x" data-act="jump" data-peer-id=${ex.id}>${rowInside(ex)}</button>`
159
+ : html`<div class="peer-pop-x">${rowInside(ex)}</div>`))}</div>` : nothing
160
+ }<pre class="ctx-pop-text" ?hidden=${text === null}>${text ?? ""}</pre
161
+ ><div class="ctx-pop-actions">${outbox?.has_text && text === null ? html`<button type="button" data-act="view">View latest answer</button>` : nothing
162
+ }${status ? html`<button type="button" data-act="status">Status card (${status})</button>` : nothing
163
+ }${legs.length ? html`<button type="button" class="ctx-pop-detach" data-act="unpair" title=${`Detach ${legs.map((l) => l.name).join(" and ")}`}>Unpair</button>` : nothing}</div>`;
164
+ }
165
+
166
+ // The peer's status card command ("/claude") when the session's commands
167
+ // (the session GET's `commands`) have it, else null.
168
+ export function peerStatusCommand(commands, name) {
169
+ const line = `/${name}`;
170
+ return (Array.isArray(commands) ? commands : []).some((c) => c?.name === line) ? line : null;
171
+ }
@@ -0,0 +1,131 @@
1
+ // The open session's peers as the page knows them: GET …/peers (owner only,
2
+ // read from the session's files: its peer sources and the exchange log), and
3
+ // one small model of it that the conversation (peer_links.js) and, later,
4
+ // the peer chips share. docs/internals/web-frontend.md, The peer exchange.
5
+ // Its own module: new exports go in new modules (web-frontend.md).
6
+
7
+ import { api } from "./data.js";
8
+ import { createLatest } from "./latest.js";
9
+
10
+ // GET /api/sessions/:id/peers → {peers: [{name, label, inbox, outbox,
11
+ // exchanges: [newest first]}]}. An older chi web has no route: its 404 is
12
+ // an empty list here, on its own (any other failure throws).
13
+ export async function listPeers(id, opts = {}) {
14
+ try {
15
+ return await api(`/api/sessions/${encodeURIComponent(id)}/peers`, opts);
16
+ } catch (error) {
17
+ if (error?.status === 404) return { peers: [] };
18
+ throw error;
19
+ }
20
+ }
21
+
22
+ // How often a waiting exchange is read again (its age moves on).
23
+ export const WAITING_TICK_MS = 60_000;
24
+
25
+ // How many exchanges GET …/peers gives a peer at most (PeerExchanges.joined
26
+ // last: 20): a full list may leave older sends out.
27
+ export const EXCHANGES_CAP = 20;
28
+
29
+ // The model. +sessionId+() the open session; +hasPeer+() whether it has a
30
+ // peer at all (a context row with `peer`, a drawn send or answer): without
31
+ // one, refresh asks nothing. +onChange+() after each read for the open
32
+ // session (also a failed one: what is drawn may follow it). +list+: the
33
+ // fetch (listPeers). +win+: focus and the waiting tick.
34
+ //
35
+ // @return {refresh(), exchange(id), answer(name, serial, re), peer(name), touch(), loaded(), clear(), peers()}
36
+ export function createPeers({ sessionId, hasPeer = () => false, onChange = () => {}, list = listPeers,
37
+ win = globalThis, tickMs = WAITING_TICK_MS } = {}) {
38
+ // The last read: {id: the session it is for, peers}.
39
+ let data = null;
40
+ let inFlight = null;
41
+ let tick = null;
42
+ // Only the newest read for the open session is kept (latest.js).
43
+ const latest = createLatest(() => sessionId());
44
+
45
+ const current = () => (data && data.id === sessionId() ? data.peers : []);
46
+
47
+ function stopTick() {
48
+ if (tick !== null) win.clearInterval?.(tick);
49
+ tick = null;
50
+ }
51
+
52
+ // One interval while an exchange waits, none otherwise.
53
+ function syncTick() {
54
+ const waiting = current().some((peer) => (peer.exchanges || []).some((ex) => ex?.state === "waiting"));
55
+ if (!waiting) stopTick();
56
+ else if (tick === null && win.setInterval) tick = win.setInterval(() => refresh(), tickMs);
57
+ }
58
+
59
+ function refresh({ reuse = false } = {}) {
60
+ const id = sessionId();
61
+ if (!id || !hasPeer()) return Promise.resolve(false);
62
+ if (reuse && inFlight?.id === id) return inFlight.promise;
63
+ if (reuse && data?.id === id) return Promise.resolve(true);
64
+ const fresh = latest.begin();
65
+ const request = (async () => {
66
+ try {
67
+ const answer = await list(id);
68
+ if (!fresh()) return false;
69
+ data = { id, peers: Array.isArray(answer?.peers) ? answer.peers : [] };
70
+ } catch {
71
+ // Unreachable for now: what was read stays.
72
+ if (!fresh()) return false;
73
+ }
74
+ syncTick();
75
+ onChange();
76
+ return true;
77
+ })();
78
+ const flight = { id, promise: request };
79
+ inFlight = flight;
80
+ const clearFlight = () => { if (inFlight === flight) inFlight = null; };
81
+ request.then(clearFlight, clearFlight);
82
+ return request;
83
+ }
84
+
85
+ // The newest exchange of send +id+, with its peer's name; null when
86
+ // none is read. Each send has its own id now; an older chi's resend
87
+ // shared one, and the newest of them wins.
88
+ function exchange(id) {
89
+ if (!id) return null;
90
+ let found = null;
91
+ for (const peer of current()) {
92
+ for (const ex of peer.exchanges || []) {
93
+ if (ex?.id === id && (!found || Date.parse(ex.at || "") > Date.parse(found.at || ""))) found = { ...ex, peer: peer.name };
94
+ }
95
+ }
96
+ return found;
97
+ }
98
+
99
+ // The send answer +serial+ of peer +name+ answers: the exchange its
100
+ // serial (its outbox revision's, the note's) is in, when that one is a
101
+ // send's; else the send +re+ names (a second answer to one send is an
102
+ // unclaimed row of its own on the server); null for an answer no send
103
+ // claims.
104
+ function answer(name, serial, re = null) {
105
+ const peer = current().find((p) => p.name === name);
106
+ if (!peer) return null;
107
+ const exchanges = peer.exchanges || [];
108
+ const bySerial = serial !== null && serial !== undefined && serial !== ""
109
+ ? exchanges.find((ex) => ex?.answer && String(ex.answer.serial) === String(serial)) : null;
110
+ const ex = bySerial?.id ? bySerial : (re ? exchanges.find((e) => e?.id === re) : null);
111
+ return ex ? { ...ex, peer: peer.name } : null;
112
+ }
113
+
114
+ function clear() {
115
+ latest.drop();
116
+ data = null;
117
+ inFlight = null;
118
+ stopTick();
119
+ }
120
+
121
+ win.addEventListener?.("focus", () => refresh());
122
+
123
+ return {
124
+ refresh, exchange, answer, clear, peers: current,
125
+ loaded: () => !!data && data.id === sessionId(),
126
+ // Peer +name+ as the last read gives it, or null (not paired, detached).
127
+ peer: (name) => current().find((p) => p.name === name) || null,
128
+ // What is drawn follows the read again without a fetch (a turn ended).
129
+ touch: () => { if (data && data.id === sessionId()) onChange(); },
130
+ };
131
+ }