samagotchi 0.180.0 → 0.182.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 (123) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +71 -1
  3. data/bin/chi +11 -0
  4. data/docs/architecture.md +2 -2
  5. data/docs/bundles.md +7 -2
  6. data/docs/cli.md +46 -13
  7. data/docs/configuration.md +25 -4
  8. data/docs/internals/anthropic.md +4 -3
  9. data/docs/internals/background-tasks.md +2 -0
  10. data/docs/internals/block-renderers.md +123 -6
  11. data/docs/internals/bridge.md +10 -0
  12. data/docs/internals/engine.md +11 -0
  13. data/docs/internals/inline-widgets.md +3 -1
  14. data/docs/internals/objectives.md +9 -4
  15. data/docs/internals/prompt-caching.md +9 -1
  16. data/docs/internals/remote-sessions.md +14 -2
  17. data/docs/internals/web-frontend.md +100 -10
  18. data/docs/internals/working-set.md +24 -5
  19. data/docs/memory.md +3 -0
  20. data/docs/plugins.md +11 -4
  21. data/docs/sessions.md +8 -5
  22. data/docs/testing.md +1 -1
  23. data/lib/samagotchi/answer_display.rb +3 -2
  24. data/lib/samagotchi/block_fix/stamp.rb +49 -0
  25. data/lib/samagotchi/block_fix.rb +220 -0
  26. data/lib/samagotchi/bridge/block_fix_route.rb +30 -0
  27. data/lib/samagotchi/bridge/turn_drawings.rb +19 -0
  28. data/lib/samagotchi/bridge.rb +11 -2
  29. data/lib/samagotchi/bridge_client.rb +9 -0
  30. data/lib/samagotchi/bundle_command.rb +4 -1
  31. data/lib/samagotchi/bundles/known-names/manifest.yml +2 -2
  32. data/lib/samagotchi/bundles/known-names/plugin.rb +4 -3
  33. data/lib/samagotchi/bundles/system/config_modification_protocol.md +3 -2
  34. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  35. data/lib/samagotchi/client.rb +8 -1
  36. data/lib/samagotchi/config.rb +9 -1
  37. data/lib/samagotchi/continue_intent.rb +8 -0
  38. data/lib/samagotchi/core_notice.rb +44 -0
  39. data/lib/samagotchi/engine/block_fix.rb +332 -0
  40. data/lib/samagotchi/engine/side_requests.rb +7 -5
  41. data/lib/samagotchi/engine.rb +4 -0
  42. data/lib/samagotchi/events.rb +1 -0
  43. data/lib/samagotchi/host_address.rb +7 -0
  44. data/lib/samagotchi/host_config.rb +8 -5
  45. data/lib/samagotchi/host_registry.rb +26 -8
  46. data/lib/samagotchi/idle_client.rb +10 -6
  47. data/lib/samagotchi/inline_widgets.rb +12 -0
  48. data/lib/samagotchi/kernel_loop.rb +10 -7
  49. data/lib/samagotchi/llm/adapter_common.rb +3 -2
  50. data/lib/samagotchi/llm/adapters.rb +2 -1
  51. data/lib/samagotchi/llm/anthropic_assembly.rb +5 -0
  52. data/lib/samagotchi/llm/anthropic_messages.rb +6 -2
  53. data/lib/samagotchi/llm/chat_loop.rb +8 -5
  54. data/lib/samagotchi/llm/errors.rb +41 -3
  55. data/lib/samagotchi/llm/http.rb +85 -22
  56. data/lib/samagotchi/llm/openai_chat.rb +20 -3
  57. data/lib/samagotchi/markdown_parser.rb +28 -0
  58. data/lib/samagotchi/memory_bundle/status.rb +2 -1
  59. data/lib/samagotchi/objectives.rb +7 -2
  60. data/lib/samagotchi/owner_lock.rb +2 -0
  61. data/lib/samagotchi/plugin/api.rb +4 -1
  62. data/lib/samagotchi/plugin/context.rb +9 -0
  63. data/lib/samagotchi/plugin/peer.rb +32 -15
  64. data/lib/samagotchi/plugin/tool_spec.rb +13 -2
  65. data/lib/samagotchi/row_refs.rb +14 -3
  66. data/lib/samagotchi/session_access/contract.rb +3 -0
  67. data/lib/samagotchi/session_access/delete_plan.rb +77 -0
  68. data/lib/samagotchi/session_access/local.rb +13 -0
  69. data/lib/samagotchi/session_access/remote.rb +19 -1
  70. data/lib/samagotchi/session_access.rb +1 -0
  71. data/lib/samagotchi/session_chain/delete.rb +45 -87
  72. data/lib/samagotchi/session_chain/delete_preview.rb +55 -19
  73. data/lib/samagotchi/session_delete_command.rb +129 -3
  74. data/lib/samagotchi/session_manager/delegate_rule.rb +86 -0
  75. data/lib/samagotchi/session_manager/listing.rb +4 -4
  76. data/lib/samagotchi/session_manager/removal.rb +40 -14
  77. data/lib/samagotchi/session_manager/running_tasks.rb +50 -23
  78. data/lib/samagotchi/session_manager.rb +1 -0
  79. data/lib/samagotchi/tool_ids.rb +19 -0
  80. data/lib/samagotchi/tool_runner.rb +8 -4
  81. data/lib/samagotchi/tools/registry.rb +3 -2
  82. data/lib/samagotchi/tools/task_runtime.rb +34 -0
  83. data/lib/samagotchi/turn_stages/objectives.rb +10 -5
  84. data/lib/samagotchi/version.rb +1 -1
  85. data/lib/samagotchi/web/app.rb +13 -1
  86. data/lib/samagotchi/web/block_fix_routes.rb +39 -0
  87. data/lib/samagotchi/web/markdown_renderer.rb +24 -9
  88. data/lib/samagotchi/web/message_display.rb +6 -1
  89. data/lib/samagotchi/web/participant_view.rb +1 -1
  90. data/lib/samagotchi/web/public/app.js +15 -19
  91. data/lib/samagotchi/web/public/block_fix.js +270 -0
  92. data/lib/samagotchi/web/public/block_fix_note.js +104 -0
  93. data/lib/samagotchi/web/public/block_frame.js +6 -3
  94. data/lib/samagotchi/web/public/block_host.js +21 -21
  95. data/lib/samagotchi/web/public/block_renderers.css +17 -5
  96. data/lib/samagotchi/web/public/block_watch.js +16 -2
  97. data/lib/samagotchi/web/public/context_chips.js +3 -4
  98. data/lib/samagotchi/web/public/images.js +1 -1
  99. data/lib/samagotchi/web/public/index.html +24 -5
  100. data/lib/samagotchi/web/public/inline_widgets.js +1 -1
  101. data/lib/samagotchi/web/public/objectives_strip.js +16 -6
  102. data/lib/samagotchi/web/public/pan_zoom.js +121 -0
  103. data/lib/samagotchi/web/public/peer_chip.js +3 -3
  104. data/lib/samagotchi/web/public/peer_data.js +27 -15
  105. data/lib/samagotchi/web/public/picture_viewer.js +304 -0
  106. data/lib/samagotchi/web/public/popover_modal.js +3 -2
  107. data/lib/samagotchi/web/public/session_view.js +4 -0
  108. data/lib/samagotchi/web/public/stream_handlers.js +5 -1
  109. data/lib/samagotchi/web/public/turn_block.js +5 -2
  110. data/lib/samagotchi/web/public/working_set.js +9 -3
  111. data/lib/samagotchi/web/public/working_set_view.js +28 -11
  112. data/lib/samagotchi/web/public/ws_cards.js +36 -10
  113. data/lib/samagotchi/web/public/ws_markdown.js +129 -0
  114. data/lib/samagotchi/web/public/ws_order.js +48 -0
  115. data/lib/samagotchi/web/public/ws_peek.js +22 -5
  116. data/lib/samagotchi/web/public/ws_preview.css +41 -1
  117. data/lib/samagotchi/web/public/ws_reader.js +35 -6
  118. data/lib/samagotchi/web/public/ws_sections.js +24 -15
  119. data/lib/samagotchi/web/server.rb +6 -4
  120. data/lib/samagotchi/web/session_control.rb +53 -21
  121. data/lib/samagotchi/worker/block_fixes.rb +22 -0
  122. data/lib/samagotchi/worker.rb +10 -3
  123. metadata +17 -1
@@ -82,13 +82,16 @@ export function frameMessage(event, frameWindow) {
82
82
 
83
83
  // A reason a render or load failed. +timedOut+: the page's timer fired, so the
84
84
  // block is suspect (block_host.js keeps its mark); +dropped+: the page let the
85
- // frame go, which says nothing of the block.
85
+ // frame go, which says nothing of the block; +renderer+: the renderer itself
86
+ // refused the source (the frame's error {id, message}), the model's input
87
+ // being wrong: the one failure a fix may help (block_fix.js).
86
88
  export class FrameError extends Error {
87
- constructor(message, { timedOut = false, dropped = false, load = false } = {}) {
89
+ constructor(message, { timedOut = false, dropped = false, load = false, renderer = false } = {}) {
88
90
  super(message);
89
91
  this.timedOut = timedOut;
90
92
  this.dropped = dropped;
91
93
  this.load = load;
94
+ this.renderer = renderer;
92
95
  }
93
96
  }
94
97
 
@@ -146,7 +149,7 @@ export function createBlockFrame({ files, fetchFile, doc = document, win = windo
146
149
  if (typeof m.svg !== "string" || m.svg.length > MAX_SVG_CHARS) settle((w) => w.reject(new FrameError("the renderer's SVG is too large or not text")));
147
150
  else settle((w) => w.resolve(m.svg));
148
151
  } else if (m.type === "error" && m.id === waiting.id) {
149
- settle((w) => w.reject(new FrameError(String(m.message ?? "render failed"))));
152
+ settle((w) => w.reject(new FrameError(String(m.message ?? "render failed"), { renderer: true })));
150
153
  }
151
154
  }
152
155
 
@@ -37,9 +37,9 @@ const NOT_AN_IMAGE = "the renderer's SVG can't be shown as an image";
37
37
  // this tall and scrolls sideways instead.
38
38
  const MIN_SHOWN_HEIGHT = 120;
39
39
 
40
- // The zoom button's words: the picture fitted to the column, or at its natural size.
41
- const ZOOM_IN = "Show at full size";
42
- const ZOOM_OUT = "Fit to the column";
40
+ // The zoom button's words: it opens the picture in the viewer (picture_viewer.js),
41
+ // as a click on the picture does.
42
+ const OPEN_IN_VIEWER = "Open in the viewer";
43
43
 
44
44
  const ZOOM_ICON = html`<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true"><circle cx="7" cy="7" r="4.25" fill="none" stroke="currentColor" stroke-width="1.4"/><path d="m10.2 10.2 3.3 3.3" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/></svg>`;
45
45
  const ICON = html`<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true"><path d="M5.5 4 2 8l3.5 4M10.5 4 14 8l-3.5 4" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg>`;
@@ -133,10 +133,12 @@ function guardedStorage(get) {
133
133
 
134
134
  // The drawer of a bundle's renderers (block_watch.js has the contract): one
135
135
  // frame per language, waiting for /api/block_renderers to say who draws what.
136
- // @param roots the turn roots, for the view held and the zoom's listeners
136
+ // @param roots the turn roots, for the view held and the viewer's click
137
+ // @param openPicture (picture, {opener}) => shows a picture full screen (app.js's
138
+ // picture viewer); null (an older app.js): a click on a picture does nothing
137
139
  // The rest are createBlockHost's.
138
140
  export function createFrameDrawer({
139
- roots, listRenderers = fetchRendererList, fetchFile = fetchRendererFile, makeFrame = createBlockFrame,
141
+ roots, openPicture = null, listRenderers = fetchRendererList, fetchFile = fetchRendererFile, makeFrame = createBlockFrame,
140
142
  decodeImage = async (url) => { const img = new win.Image(); img.src = url; await img.decode(); return { width: img.naturalWidth, height: img.naturalHeight }; },
141
143
  decodeTimeoutMs = DECODE_TIMEOUT_MS, theme = currentTheme,
142
144
  doc = document, win = window, storage = guardedStorage(() => globalThis.sessionStorage),
@@ -224,8 +226,9 @@ export function createFrameDrawer({
224
226
  }
225
227
 
226
228
  // The picture's name says where its words are: the source <pre> is hidden, so a
227
- // screen reader reaches it through the toggle. The zoom is a button too, for the
228
- // keyboard (a click on the picture does the same); it shows on keyboard focus only.
229
+ // screen reader reaches it through the toggle. Opening it in the viewer is a
230
+ // button too, for the keyboard (a click on the picture does the same); it shows
231
+ // on keyboard focus only.
229
232
  function makeFigure(picture, themeName, lang) {
230
233
  const figure = doc.createElement("figure");
231
234
  figure.className = DRAWN;
@@ -239,8 +242,9 @@ export function createFrameDrawer({
239
242
  scroll.append(img);
240
243
  const zoom = button("block-zoom", ZOOM_ICON);
241
244
  const toggle = button("block-toggle", ICON);
245
+ zoom.setAttribute("aria-label", OPEN_IN_VIEWER);
246
+ zoom.title = OPEN_IN_VIEWER;
242
247
  figure.append(scroll, zoom, toggle);
243
- setZoomed(figure, false);
244
248
  return figure;
245
249
  }
246
250
 
@@ -252,15 +256,6 @@ export function createFrameDrawer({
252
256
  return el;
253
257
  }
254
258
 
255
- function setZoomed(figure, on) {
256
- figure.classList.toggle("natural", on);
257
- const zoom = figure.querySelector(":scope > .block-zoom");
258
- if (!zoom) return;
259
- zoom.setAttribute("aria-pressed", on ? "true" : "false");
260
- zoom.setAttribute("aria-label", on ? ZOOM_OUT : ZOOM_IN);
261
- zoom.title = on ? ZOOM_OUT : ZOOM_IN;
262
- }
263
-
264
259
  function showPicture(img, { url, width, height }) {
265
260
  if (width && height) {
266
261
  img.setAttribute("width", width);
@@ -350,7 +345,7 @@ export function createFrameDrawer({
350
345
  place(pre, await pictureFor(key, lang, source, renderer, now), now.name, lang);
351
346
  } catch (e) {
352
347
  // A redraw that failed keeps the picture it has.
353
- if (!e?.dropped && !figureOf(pre)) failBlock(pre, lang, e?.message);
348
+ if (!e?.dropped && !figureOf(pre)) failBlock(pre, lang, e?.message, { fixable: !!e?.renderer });
354
349
  retry = !!e?.dropped;
355
350
  }
356
351
  // Queued behind a frame that died (another block's timeout): a new frame's
@@ -368,11 +363,15 @@ export function createFrameDrawer({
368
363
  root.addEventListener("mousedown", (e) => {
369
364
  if (e.target.closest?.(".block-zoom")) e.preventDefault();
370
365
  });
371
- // Delegated, so a Revise clone's work too.
366
+ // Delegated, so a Revise clone's work too: the picture in the viewer, at its
367
+ // size from the viewBox (showPicture's attributes), the focus back on the button.
372
368
  root.addEventListener("click", (e) => {
373
- if (!e.target.closest?.(".block-zoom, .block-img")) return;
369
+ if (!openPicture || !e.target.closest?.(".block-zoom, .block-img")) return;
374
370
  const figure = e.target.closest(`.${DRAWN}`);
375
- setZoomed(figure, !figure.classList.contains("natural"));
371
+ const img = figure?.querySelector(".block-img");
372
+ if (!img) return;
373
+ const size = (name) => Number(img.getAttribute(name)) || null;
374
+ openPicture({ url: img.src, width: size("width"), height: size("height"), alt: img.alt }, { opener: figure.querySelector(":scope > .block-zoom") });
376
375
  });
377
376
  }
378
377
 
@@ -392,6 +391,7 @@ export function createFrameDrawer({
392
391
  // @param sessionId () => the open session's id: the frames go on a change, to
393
392
  // limit what they hold (docs/internals/block-renderers.md, residual risk)
394
393
  // @param drawers core drawers, asked before the bundle renderers
394
+ // +openPicture+: shows a drawn picture full screen (createFrameDrawer's).
395
395
  // The rest are seams for the specs.
396
396
  // +renderers+: false for a viewer without the bundles' renderers (viewer.js):
397
397
  // the core +drawers+ only, and GET /api/block_renderers is never asked.
@@ -1,12 +1,11 @@
1
- /* A drawn fenced block (block_host.js): the picture scales to the column, a click shows its natural size in a scroller; the toggle shows the source, in the block's place. In a .code-wrap the copy button sits top-right, so the toggle sits left of it. The zoom button, the keyboard's way to the natural size, shows on keyboard focus only, left of the toggle. */
1
+ /* A drawn fenced block (block_host.js): the picture scales to the column, a click opens it in the picture viewer (picture_viewer.js); the toggle shows the source, in the block's place. In a .code-wrap the copy button sits top-right, so the toggle sits left of it. The zoom button, the keyboard's way to the viewer, shows on keyboard focus only, left of the toggle. */
2
2
  .block-drawn{position:relative;margin:0 0 12px;white-space:normal}
3
3
  .code-wrap>.block-drawn{margin:0}
4
4
  .code-wrap>.block-drawn.source{height:0}
5
5
  .block-drawn:last-child{margin-bottom:0}
6
6
  .block-scroll{overflow-x:auto;padding:4px 0}
7
- /* max-height and the natural max-width are block_host.js MAX_PICTURE_SIDE: a backstop, so no parsing or decoding surprise reaches the browser's 33M px. */
7
+ /* max-height is block_host.js MAX_PICTURE_SIDE: a backstop, so no parsing or decoding surprise reaches the browser's 33M px. A very wide picture keeps its min-width (block_host.js minShownWidth) and scrolls sideways. */
8
8
  .block-img{display:block;max-width:100%;max-height:50000px;object-fit:contain;height:auto;margin:0 auto;cursor:zoom-in}
9
- .block-drawn.natural .block-img{max-width:50000px;margin:0;cursor:zoom-out}
10
9
  .block-drawn.source .block-scroll{display:none}
11
10
  /* A chi-ui widget (inline_widgets.js): its host holds the shadow root, whose own sheet is widgets.css; the source hides it as the picture. */
12
11
  .block-drawn.source>.widget-host{display:none}
@@ -17,10 +16,23 @@
17
16
  .block-drawn.source>.block-zoom{display:none}
18
17
  .block-zoom:not(:focus-visible){pointer-events:none}
19
18
  .block-toggle svg,.block-zoom svg{display:block}
20
- .block-drawn:hover>.block-toggle,.code-wrap:hover>.block-drawn>.block-toggle,.block-toggle:focus-visible,.block-zoom:focus-visible,.block-drawn.source>.block-toggle{opacity:1}
21
- .block-toggle:hover:not(:disabled),.block-zoom:hover:not(:disabled){filter:none}@media(hover:hover){.block-toggle:hover:not(:disabled),.block-zoom:hover:not(:disabled){color:var(--text-bright)}}
19
+ .block-toggle:focus-visible,.block-zoom:focus-visible,.block-drawn.source>.block-toggle{opacity:1}
20
+ @media(hover:hover){.block-drawn:hover>.block-toggle,.code-wrap:hover>.block-drawn>.block-toggle{opacity:1}.block-toggle:hover:not(:disabled),.block-zoom:hover:not(:disabled){filter:none;color:var(--text-bright)}}
21
+ @media(hover:none){.block-drawn>.block-toggle{opacity:.5}.block-drawn>.block-toggle:active,.block-drawn>.block-toggle:focus-visible{opacity:1}}
22
22
  .block-drawn.source:not(:last-child){margin:0}
23
23
  /* Its words are the attribute's, so a bubble's text stays the answer's (block_host.js fail). */
24
24
  .block-note{margin:4px 0 12px;font-size:12px;color:var(--text-3);white-space:normal}
25
25
  .block-note{cursor:copy}
26
26
  .block-note::before{content:attr(data-text)}
27
+ /* A failed block asked for again (block_fix_note.js): the line keeps one line's height while its words change, wraps only at a phone's width; "asking for a fix…" has a pulsing dot; Ask in chat is a pill whose label is CSS (data-label), so nothing of the page's own is in the bubble's text. */
28
+ .block-note[data-fix]{display:flex;flex-wrap:wrap;align-items:center;gap:2px 10px;min-height:28px}
29
+ .block-note[data-fix="asking"]::after{content:"";display:inline-block;flex:none;width:6px;height:6px;margin-left:-4px;border-radius:50%;background:var(--accent);animation:block-fix-pulse 1s steps(13) infinite}
30
+ @keyframes block-fix-pulse{50%{opacity:.25}}
31
+ @media (prefers-reduced-motion:reduce){.block-note[data-fix="asking"]::after{animation:none}}
32
+ .block-fix-ask{flex:none;font:inherit;font-size:12px;font-weight:500;line-height:1.5;color:var(--accent);background:none;border:1px solid var(--border-strong);border-radius:999px;padding:3px 10px;cursor:pointer}
33
+ .block-fix-ask::before{content:attr(data-label)}
34
+ .block-fix-ask:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
35
+ @media(hover:hover){.block-fix-ask:hover{border-color:var(--accent)}}
36
+ @media (pointer:coarse),(max-width:700px){.block-fix-ask{min-height:44px;padding:0 14px}}
37
+ /* "Drawn after a fix" under a fixed block that drew: muted, not a copy target. */
38
+ .block-note.fixed{margin-top:4px;cursor:default}
@@ -78,13 +78,23 @@ export function holdingView(pre, roots, mutate, bottomOf, win = window) {
78
78
  return result;
79
79
  }
80
80
 
81
+ // How much of a drawer's error a block keeps for a fix's request
82
+ // (BlockFix::MAX_REASON_CHARS): a Mermaid error's useful part is after its
83
+ // first line, which alone the line shows.
84
+ const MAX_REASON = 300;
85
+
81
86
  // The <pre> stays as it is, under one muted line: never markup (the words are
82
87
  // a drawer's, driven by the model's input), and shown by CSS, so a bubble's
83
88
  // textContent, its dedupe and an annotation's text stay what they were (copy.js's
84
89
  // rule for its buttons). A click on the line copies it (the watcher's listener).
85
- export function failBlock(pre, lang, message) {
90
+ // +fixable+: the failure is the model's (a refused chi-ui block, a renderer's
91
+ // own error), so a fix may be asked for (block_fix.js). Either way a bubbling
92
+ // "block-failed" event goes out from the <pre>.
93
+ export function failBlock(pre, lang, message, { fixable = false } = {}) {
86
94
  if (!pre.isConnected) return;
87
95
  pre.dataset.blockFailed = "1";
96
+ if (fixable) pre.dataset.blockFixable = "1";
97
+ pre.dataset.blockReason = String(message ?? "").trim().slice(0, MAX_REASON);
88
98
  const note = pre.ownerDocument.createElement("div");
89
99
  note.className = "block-note";
90
100
  const first = String(message ?? "").split("\n")[0].trim();
@@ -94,6 +104,7 @@ export function failBlock(pre, lang, message) {
94
104
  note.setAttribute("aria-label", words);
95
105
  note.title = "Click to copy";
96
106
  pre.after(note);
107
+ pre.dispatchEvent(new (pre.ownerDocument.defaultView?.CustomEvent || CustomEvent)("block-failed", { bubbles: true }));
97
108
  }
98
109
 
99
110
  // A copy.js wrap took the <pre> away from a figure placed first: back with it.
@@ -247,7 +258,10 @@ export function createBlockWatch({ roots, sessionId, drawers, watch = null, copy
247
258
  setSourceShown(figure, figure.nextElementSibling, !figure.classList.contains("source"));
248
259
  return;
249
260
  }
250
- const note = e.target.closest?.(".block-note");
261
+ // A button in the line (block_fix_note.js) is its own, not a copy, and
262
+ // "Drawn after a fix" (.block-note.fixed) has no error to copy.
263
+ if (e.target.closest?.(".block-note button")) return;
264
+ const note = e.target.closest?.(".block-note:not(.fixed)");
251
265
  if (note) copy(note.dataset.text);
252
266
  });
253
267
  }
@@ -166,11 +166,10 @@ export function createContextChips({ el, api, toast = () => {}, peers = () => nu
166
166
  draw();
167
167
  // An open popover follows its row, but not while it shows the text.
168
168
  follow();
169
- // The peers' exchanges for the chips: at a session's open (the
170
- // conversation's own read may have found no peer yet), and when a peer
171
- // comes (a pairing while the session is open).
169
+ // The peers' exchanges for the chips: at a session's open (reuse the
170
+ // conversation's read if loaded or in flight), and when a peer comes.
172
171
  const names = groups().map((group) => group.name).join(" ");
173
- if (names && (loading || names !== peerNames)) peers()?.refresh?.();
172
+ if (names && (loading || names !== peerNames)) peers()?.refresh?.({ reuse: loading });
174
173
  peerNames = names;
175
174
  }
176
175
 
@@ -1,6 +1,6 @@
1
1
  // Images in the web UI: pasted or dropped into the composer as chips, sent
2
2
  // with a turn as refs (uploaded first), shown as thumbnails in the bubbles
3
- // and tool rows, opened full size in a lightbox. No DOM here beyond what the
3
+ // and tool rows, opened in the picture viewer (picture_viewer.js). No DOM here beyond what the
4
4
  // callers pass (the templates are lit-html's), so it runs under `node --test`.
5
5
  import { html, nothing } from "./vendor/lit-html.js";
6
6
 
@@ -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). */
@@ -795,10 +795,28 @@ body.has-session #history{padding-bottom:calc(var(--dock-h,160px) + 16px + var(-
795
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)}
796
796
  .activity-row .thumbs{flex-basis:100%;margin-left:var(--row-gutter)}
797
797
  @media(max-width:600px){.activity-row .thumbs{margin-left:0}}
798
- /* The image keeps clear of the notch and the home indicator (its padding: the safe areas; 0 on a desktop). */
799
- #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}
800
801
  #lightbox[hidden]{display:none}
801
- #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)}
802
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. */
803
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}
804
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. */
@@ -1180,8 +1198,9 @@ button.ws-step:hover:not(:disabled){filter:none}@media(hover:hover){button.ws-st
1180
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}
1181
1199
  .ws-sec-head:hover:not(:disabled){filter:none}@media(hover:hover){.ws-sec-head:hover{background:var(--bg-hover)}}
1182
1200
  .ws-sec-head .k{flex:none;width:12px;text-align:center;color:var(--ws-faint)}
1183
- .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)}
1184
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)}
1185
1204
  .ws-sec-head .tk{flex:none;margin-left:auto;font-size:11px;color:var(--ws-faint);font-variant-numeric:tabular-nums}
1186
1205
  .ws-sec .ws-sub{margin-top:2px;padding-left:6px}
1187
1206
  .ws-row.part .t{margin-right:auto;font-family:ui-sans-serif,system-ui,sans-serif}
@@ -112,7 +112,7 @@ export function createWidgetDrawer({ roots, composerText, fillComposer, doc = do
112
112
  function needsDraw(pre, figure) {
113
113
  if (figure) return !hostOf(figure)?.shadowRoot;
114
114
  if (pre.hasAttribute("data-widget-error")) {
115
- failBlock(pre, LANG, pre.getAttribute("data-widget-error"));
115
+ failBlock(pre, LANG, pre.getAttribute("data-widget-error"), { fixable: true });
116
116
  return false;
117
117
  }
118
118
  return pre.hasAttribute("data-widget");
@@ -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
+ }
@@ -67,7 +67,7 @@ const since = (iso, now) => {
67
67
  };
68
68
 
69
69
  // The chip of +group+: the first state that applies.
70
- // - answers-only: no inbox leg (a pairing through a remote: chi there can't send);
70
+ // - answers-only: no inbox leg (chi can't send);
71
71
  // - cant-send: the newest send failed (the transport refused it);
72
72
  // - waiting: the newest validate or question send has no answer (its age the send's);
73
73
  // - answered: the outbox has a text the agent hasn't read (its age the text's), with the dot;
@@ -86,7 +86,7 @@ export function peerChipModel(group, exchanges = [], now = Date.now()) {
86
86
  if (!inbox) {
87
87
  state = "answers-only";
88
88
  words = "answers only";
89
- why = "paired through a remote: it answers, chi here can't send to it";
89
+ why = "no inbox attached here: it answers, chi can't send to it";
90
90
  } else if (cantSend(group, exchanges)) {
91
91
  state = "cant-send";
92
92
  words = "can't send";
@@ -135,7 +135,7 @@ export function peerPopoverTemplate(group, exchanges = [], { text = null, status
135
135
  const all = sends(exchanges);
136
136
  const lastSent = all.find((ex) => ex.state !== "failed");
137
137
  const sendsLine = !inbox
138
- ? "can't: paired through a remote"
138
+ ? "can't: no inbox attached here"
139
139
  : cantSend(group, exchanges)
140
140
  ? `the last send didn't go through: pair again from ${group.label}`
141
141
  : [`to its inbox (${group.inbox.name})`, lastSent ? `last sent ${wallClock(lastSent.at, now)}` : ""].filter(Boolean).join(" · ");
@@ -37,6 +37,7 @@ export function createPeers({ sessionId, hasPeer = () => false, onChange = () =>
37
37
  win = globalThis, tickMs = WAITING_TICK_MS } = {}) {
38
38
  // The last read: {id: the session it is for, peers}.
39
39
  let data = null;
40
+ let inFlight = null;
40
41
  let tick = null;
41
42
  // Only the newest read for the open session is kept (latest.js).
42
43
  const latest = createLatest(() => sessionId());
@@ -55,25 +56,35 @@ export function createPeers({ sessionId, hasPeer = () => false, onChange = () =>
55
56
  else if (tick === null && win.setInterval) tick = win.setInterval(() => refresh(), tickMs);
56
57
  }
57
58
 
58
- async function refresh() {
59
+ function refresh({ reuse = false } = {}) {
59
60
  const id = sessionId();
60
- if (!id || !hasPeer()) return false;
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);
61
64
  const fresh = latest.begin();
62
- try {
63
- const answer = await list(id);
64
- if (!fresh()) return false;
65
- data = { id, peers: Array.isArray(answer?.peers) ? answer.peers : [] };
66
- } catch {
67
- // Unreachable for now: what was read stays.
68
- if (!fresh()) return false;
69
- }
70
- syncTick();
71
- onChange();
72
- return true;
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;
73
83
  }
74
84
 
75
- // The newest exchange of send +id+ (a resend has one id), with its
76
- // peer's name; null when none is read.
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.
77
88
  function exchange(id) {
78
89
  if (!id) return null;
79
90
  let found = null;
@@ -103,6 +114,7 @@ export function createPeers({ sessionId, hasPeer = () => false, onChange = () =>
103
114
  function clear() {
104
115
  latest.drop();
105
116
  data = null;
117
+ inFlight = null;
106
118
  stopTick();
107
119
  }
108
120