@aparte/core 0.32.1 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/README.md +30 -19
  2. package/dist/client/agent-runner.d.ts.map +1 -1
  3. package/dist/components/bubble/aparte-chat-bubble.d.ts +33 -0
  4. package/dist/components/bubble/aparte-chat-bubble.d.ts.map +1 -1
  5. package/dist/components/bubble/bubble-sync.d.ts.map +1 -1
  6. package/dist/components/context/aparte-context.d.ts +4 -11
  7. package/dist/components/context/aparte-context.d.ts.map +1 -1
  8. package/dist/components/launcher/aparte-launcher.d.ts.map +1 -1
  9. package/dist/components/scroll-rail/aparte-scroll-rail.d.ts +77 -5
  10. package/dist/components/scroll-rail/aparte-scroll-rail.d.ts.map +1 -1
  11. package/dist/components/sidebar/aparte-sidebar.d.ts.map +1 -1
  12. package/dist/components/split/aparte-split.d.ts.map +1 -1
  13. package/dist/components/suggestions/aparte-suggestions.d.ts +15 -1
  14. package/dist/components/suggestions/aparte-suggestions.d.ts.map +1 -1
  15. package/dist/components/suggestions/suggestion-blocks.d.ts +21 -1
  16. package/dist/components/suggestions/suggestion-blocks.d.ts.map +1 -1
  17. package/dist/components/viewport/aparte-chat-viewport.d.ts +2 -5
  18. package/dist/components/viewport/aparte-chat-viewport.d.ts.map +1 -1
  19. package/dist/config/aparte-config.d.ts +56 -4
  20. package/dist/config/aparte-config.d.ts.map +1 -1
  21. package/dist/config/config-context.d.ts.map +1 -1
  22. package/dist/config/image-policy.d.ts +104 -0
  23. package/dist/config/image-policy.d.ts.map +1 -0
  24. package/dist/config/index.d.ts +1 -0
  25. package/dist/config/index.d.ts.map +1 -1
  26. package/dist/config/locale.d.ts +8 -10
  27. package/dist/config/locale.d.ts.map +1 -1
  28. package/dist/config/sanitize.d.ts +36 -0
  29. package/dist/config/sanitize.d.ts.map +1 -1
  30. package/dist/custom-elements.json +1226 -82
  31. package/dist/{defer-hydration-DQKULLmH.js → defer-hydration-_SZv5PeY.js} +827 -65
  32. package/dist/defer-hydration-_SZv5PeY.js.map +1 -0
  33. package/dist/generated/element-attributes.d.ts +1 -3
  34. package/dist/generated/element-attributes.d.ts.map +1 -1
  35. package/dist/index.css +1 -1
  36. package/dist/index.d.ts +2 -2
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +497 -124
  39. package/dist/index.js.map +1 -1
  40. package/dist/index.node.d.ts +2 -2
  41. package/dist/index.node.d.ts.map +1 -1
  42. package/dist/index.node.js +1 -1
  43. package/dist/index.node.js.map +1 -1
  44. package/dist/interop/dialog-triggers.d.ts.map +1 -1
  45. package/dist/interop/image-holds.d.ts +20 -0
  46. package/dist/interop/image-holds.d.ts.map +1 -0
  47. package/dist/renderers/segments/text.d.ts.map +1 -1
  48. package/dist/renderers/segments/thinking.d.ts.map +1 -1
  49. package/dist/transport/agent-handler.d.ts +10 -0
  50. package/dist/transport/agent-handler.d.ts.map +1 -1
  51. package/dist/transport/agent-ticket.d.ts.map +1 -1
  52. package/dist/transport/backend-handler.d.ts +8 -0
  53. package/dist/transport/backend-handler.d.ts.map +1 -1
  54. package/dist/transport/backend-transport.d.ts.map +1 -1
  55. package/dist/transport/json-headers.d.ts +10 -0
  56. package/dist/transport/json-headers.d.ts.map +1 -0
  57. package/dist/transport/request-guard.d.ts +14 -0
  58. package/dist/transport/request-guard.d.ts.map +1 -0
  59. package/dist/types/events.d.ts +6 -13
  60. package/dist/types/events.d.ts.map +1 -1
  61. package/dist/types/index.d.ts +1 -1
  62. package/dist/types/index.d.ts.map +1 -1
  63. package/dist/types/models.d.ts +0 -34
  64. package/dist/types/models.d.ts.map +1 -1
  65. package/dist/types/segments.d.ts +0 -11
  66. package/dist/types/segments.d.ts.map +1 -1
  67. package/dist/utils/rendered-content.d.ts +3 -0
  68. package/dist/utils/rendered-content.d.ts.map +1 -0
  69. package/llms.txt +13 -0
  70. package/package.json +11 -4
  71. package/dist/defer-hydration-DQKULLmH.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { K as deferHydrationOf, ad as resolveConfig, ao as eventOrigin, ap as activeElementIn, aj as subscribeConfigChange, af as runWithConfig, o as AparteElicitationAbortError, w as buildApprovalPanel, x as buildElicitationPanel, aq as gateGlide, O as escapeAttr, ar as chatBoundaryOf, as as relabelCodeLanguages, at as relabelCitations, au as toolCallRenderer, av as toolRendererThatDrew, t as aparteGlobalConfig, aw as isMountedRenderer, ax as renderingVersionOf, H as cssEscape, ay as onRenderersChange, az as renderSourceList, aA as mergeSegmentUpdate, P as escapeHtml, a0 as isSegmentSettled, aB as writeStreamedMarkdown, aC as replaceHighlighted, $ as isSafeUrl, C as copyText, V as getSegmentRenderer, X as installDefaultRenderersOnce, r as AparteMessageRepository, aD as CheckpointStateWatcher, aE as chatIdOf, aF as stampSegmentActivity, aG as stampSegmentOnInsert, aH as stampSegmentOnUpdate, aI as renumberSegments, aJ as openSegmentIds, aK as isTerminalStatus, aL as adoptMessageSegments, Z as isAwaitingReply, a5 as populateBubbleFromMessage, an as uuid, ae as revokeAttachmentUrls, a4 as parseMarkdownToSegments, aM as APARTE_DERIVED_SEGMENTS, aN as rememberConversationStatus, aO as tellConversationStatus, aP as conversationStatusOf, e as APARTE_DEFAULT_LOCALE, aQ as usageTokens, q as AparteErrorCode, a1 as measureContext, aR as rootOf, g as APARTE_HOST_ATTR, Y as installDialogTriggersOnce } from "./defer-hydration-DQKULLmH.js";
2
- import { A, a, b, c, d, f, h, i, j, k, l, m, n, p, s, S, u, v, y, z, B, D, E, F, G, I, J, L, M, N, Q, R, T, U, W, _, a2, a3, a6, a7, a8, a9, aa, ab, ac, ag, ah, ai, ak, al, am } from "./defer-hydration-DQKULLmH.js";
1
+ import { K as deferHydrationOf, ad as resolveConfig, ao as eventOrigin, ap as activeElementIn, aj as subscribeConfigChange, af as runWithConfig, o as AparteElicitationAbortError, w as buildApprovalPanel, x as buildElicitationPanel, aq as gateGlide, O as escapeAttr, ar as chatBoundaryOf, as as relabelCodeLanguages, at as relabelCitations, au as toolCallRenderer, av as toolRendererThatDrew, t as aparteGlobalConfig, aw as isMountedRenderer, ax as renderingVersionOf, H as cssEscape, ay as onRenderersChange, az as renderSourceList, aA as mergeSegmentUpdate, P as escapeHtml, a0 as isSegmentSettled, aB as writeStreamedMarkdown, aC as replaceHighlighted, $ as isSafeUrl, C as copyText, V as getSegmentRenderer, X as installDefaultRenderersOnce, r as AparteMessageRepository, aD as CheckpointStateWatcher, aE as chatIdOf, aF as stampSegmentActivity, aG as stampSegmentOnInsert, aH as stampSegmentOnUpdate, aI as renumberSegments, aJ as openSegmentIds, aK as isTerminalStatus, aL as adoptMessageSegments, Z as isAwaitingReply, a5 as populateBubbleFromMessage, an as uuid, ae as revokeAttachmentUrls, a4 as parseMarkdownToSegments, aM as APARTE_DERIVED_SEGMENTS, aN as rememberConversationStatus, aO as tellConversationStatus, aP as conversationStatusOf, e as APARTE_DEFAULT_LOCALE, aQ as visibleReply, aR as usageTokens, q as AparteErrorCode, a1 as measureContext, aS as rootOf, aT as inRenderedContent, g as APARTE_HOST_ATTR, Y as installDialogTriggersOnce } from "./defer-hydration-_SZv5PeY.js";
2
+ import { A, a, b, c, d, f, h, i, j, k, l, m, n, p, s, S, u, v, y, z, B, D, E, F, G, I, J, L, M, N, Q, R, T, U, W, _, a2, a3, a6, a7, a8, a9, aa, ab, ac, ag, ah, ai, ak, al, am } from "./defer-hydration-_SZv5PeY.js";
3
3
  function presenceOn(value) {
4
4
  return value === "" ? true : Boolean(value);
5
5
  }
@@ -1538,6 +1538,8 @@ class AparteChatBubble extends HTMLElement {
1538
1538
  _drawnWithVersion = 0;
1539
1539
  /** Every segment on screen, by id: see {@link DrawnSegment}. */
1540
1540
  _drawn = /* @__PURE__ */ new Map();
1541
+ /** Segments written to with no `isStreaming: false` yet: settled when the message stops streaming. */
1542
+ _written = /* @__PURE__ */ new Set();
1541
1543
  /** The segments were released because the bubble was still out of the page at the next microtask. */
1542
1544
  _releasedWhileDetached = false;
1543
1545
  /** A {@link _scheduleReleaseCheck} is queued. */
@@ -1559,15 +1561,45 @@ class AparteChatBubble extends HTMLElement {
1559
1561
  * Recorded BEFORE `setup`: a setup that throws (a framework mount) leaves an element that
1560
1562
  * will still be cleaned up. The same id drawn twice releases the first element.
1561
1563
  */
1562
- _install(segment, el2, renderer) {
1564
+ _install(segment, el2, renderer, drawnAs = segment) {
1563
1565
  const previous = this._drawn.get(segment.id);
1564
1566
  if (previous && previous.el !== el2) this._release(segment.id);
1565
1567
  const drawn = { el: el2, renderer, tool: null, segment };
1566
1568
  this._drawn.set(segment.id, drawn);
1567
1569
  if (!this.isConnected) this._scheduleReleaseCheck();
1568
- if (renderer?.setup) runWithConfig(this._cfg, () => renderer.setup(el2, segment));
1570
+ if (renderer?.setup) runWithConfig(this._cfg, () => renderer.setup(el2, drawnAs));
1569
1571
  if (segment.type === "tool_call") drawn.tool = toolRendererThatDrew(el2);
1570
1572
  }
1573
+ /**
1574
+ * The segment as its renderer's `setup` sees it: one ADDED while the message streams is
1575
+ * arriving, flag or no flag.
1576
+ *
1577
+ * A text or reasoning segment flagged `isStreaming: true` is written by its renderer's
1578
+ * `setup` through the streaming renderer, from its first chunk. The stream parser's text
1579
+ * carries no flag at all, though: `update` reads a missing flag as "still arriving",
1580
+ * `setup` cannot, because a restored message's segments carry none either and are
1581
+ * finished. So its first chunk — drawn by `render` and `setup`, while `update` only runs
1582
+ * from the second — went through the one-shot provider, which reads `Done: **Book ` as
1583
+ * finished text: with marked, the `**` showed raw until the next chunk reached the
1584
+ * streaming renderer, which completes it. `addSegment` on a streaming message is a segment
1585
+ * arriving, and the bubble is what knows the message streams, so it tells `setup`
1586
+ * (`render` keeps the segment as stored: the reasoning label reads the flag, and would lose
1587
+ * its shimmer again at the next chunk). `setSegments` infers nothing — a hand-set text is
1588
+ * finished, and the streaming renderer would keep back what may still open a token (the
1589
+ * full stop after `**bold**`) until the turn ends; a framework host flags the segment
1590
+ * itself (`populateBubbleFromMessage`). Either way the segment joins `_written`, to be
1591
+ * settled — flushed, then drawn whole — when the message stops.
1592
+ */
1593
+ _drawnAs(segment, added = false) {
1594
+ if (segment.type !== "text" && segment.type !== "thinking") return segment;
1595
+ if (segment.isStreaming === true) {
1596
+ this._written.add(segment.id);
1597
+ return segment;
1598
+ }
1599
+ if (!added || segment.isStreaming === false || !this._streaming) return segment;
1600
+ this._written.add(segment.id);
1601
+ return { ...segment, isStreaming: true };
1602
+ }
1571
1603
  /**
1572
1604
  * The segment's element leaves for good: its renderer's `cleanup`, once. A cleanup that
1573
1605
  * throws is reported and costs nothing else — the element still goes, and the others
@@ -1610,13 +1642,14 @@ class AparteChatBubble extends HTMLElement {
1610
1642
  const renderer = resolveSegmentRenderer(segment.type, cfg);
1611
1643
  const old = drawn.el;
1612
1644
  this._release(segment.id);
1645
+ const drawnAs = renderer ? this._drawnAs(segment) : segment;
1613
1646
  const el2 = renderer ? segmentRenderResultToElement(runWithConfig(cfg, () => renderer.render(segment)), segment) : unrenderedSegment(segment);
1614
1647
  if (!el2) {
1615
1648
  old.remove();
1616
1649
  return true;
1617
1650
  }
1618
1651
  old.replaceWith(el2);
1619
- this._install(segment, el2, renderer);
1652
+ this._install(segment, el2, renderer, drawnAs);
1620
1653
  return true;
1621
1654
  }
1622
1655
  /** The renderer that drew this segment is still the one in effect (for a tool call, the tool renderer too). */
@@ -1928,6 +1961,8 @@ class AparteChatBubble extends HTMLElement {
1928
1961
  if (index !== -1) {
1929
1962
  const updated = mergeSegmentUpdate(this._segments[index], updates);
1930
1963
  this._segments[index] = updated;
1964
+ if (updated.isStreaming === false) this._written.delete(segmentId);
1965
+ else if ("content" in updates) this._written.add(segmentId);
1931
1966
  this._applySegmentUpdate(segmentId, updated, updates);
1932
1967
  if ("sources" in updates) this._syncSources();
1933
1968
  this._syncCopyAction();
@@ -1939,10 +1974,31 @@ class AparteChatBubble extends HTMLElement {
1939
1974
  const segment = this._segments.find((s2) => s2.id === segmentId);
1940
1975
  if (segment && "content" in segment) {
1941
1976
  segment.content += content;
1977
+ if (segment.isStreaming !== false) this._written.add(segmentId);
1942
1978
  this._applySegmentUpdate(segmentId, segment, { content: segment.content });
1943
1979
  this._syncCopyAction();
1944
1980
  }
1945
1981
  }
1982
+ /**
1983
+ * The message stopped streaming, so a segment it was still writing is finished too.
1984
+ *
1985
+ * A segment written to with no `isStreaming` flag — `appendToSegment` from a stream driven
1986
+ * by hand, as the docs' own streaming demo does — goes through the incremental Markdown
1987
+ * parser, which holds back what may still open a token (the full stop after `**bold**`)
1988
+ * until it is told the text is complete. Nothing told it: the message ended with its tail
1989
+ * missing. Marked finished here, it is flushed and settled like any finished segment.
1990
+ */
1991
+ _settleWrittenSegments() {
1992
+ for (const id of this._written) {
1993
+ const index = this._segments.findIndex((s2) => s2.id === id);
1994
+ const segment = this._segments[index];
1995
+ if (!segment || segment.isStreaming === false) continue;
1996
+ const settled = { ...segment, isStreaming: false };
1997
+ this._segments[index] = settled;
1998
+ this._applySegmentUpdate(id, settled, { isStreaming: false });
1999
+ }
2000
+ this._written.clear();
2001
+ }
1946
2002
  /** Get all segments */
1947
2003
  getSegments() {
1948
2004
  return [...this._segments];
@@ -2186,6 +2242,7 @@ class AparteChatBubble extends HTMLElement {
2186
2242
  const button = event.target?.closest?.("[data-checkpoint-action]");
2187
2243
  const separator = button?.closest(".aparte-checkpoint");
2188
2244
  if (!button || !separator || separator.parentElement !== this) return;
2245
+ if (button.closest(".aparte-checkpoint__summary")) return;
2189
2246
  switch (button.getAttribute("data-checkpoint-action")) {
2190
2247
  case "toggle":
2191
2248
  this._checkpointOpen = !this._checkpointOpen;
@@ -2238,10 +2295,11 @@ class AparteChatBubble extends HTMLElement {
2238
2295
  if (this._segments.length === 1) this._drawnWithVersion = renderingVersionOf(this._cfg);
2239
2296
  const renderer = resolveSegmentRenderer(segment.type, this._cfg);
2240
2297
  if (renderer) {
2298
+ const drawnAs = this._drawnAs(segment, true);
2241
2299
  const el2 = segmentRenderResultToElement(runWithConfig(this._cfg, () => renderer.render(segment)), segment);
2242
2300
  if (el2) {
2243
2301
  this._segmentsEl.appendChild(el2);
2244
- this._install(segment, el2, renderer);
2302
+ this._install(segment, el2, renderer, drawnAs);
2245
2303
  }
2246
2304
  } else {
2247
2305
  const el2 = unrenderedSegment(segment);
@@ -2572,10 +2630,11 @@ class AparteChatBubble extends HTMLElement {
2572
2630
  for (const segment of this._segments) {
2573
2631
  const renderer = resolveSegmentRenderer(segment.type, this._cfg);
2574
2632
  if (renderer) {
2633
+ const drawnAs = this._drawnAs(segment);
2575
2634
  const el2 = segmentRenderResultToElement(runWithConfig(this._cfg, () => renderer.render(segment)), segment);
2576
2635
  if (el2) {
2577
2636
  this._segmentsEl.appendChild(el2);
2578
- this._install(segment, el2, renderer);
2637
+ this._install(segment, el2, renderer, drawnAs);
2579
2638
  }
2580
2639
  } else {
2581
2640
  const el2 = unrenderedSegment(segment);
@@ -3207,6 +3266,7 @@ class AparteChatBubble extends HTMLElement {
3207
3266
  this._updateWaiting();
3208
3267
  this._updateFinishNote();
3209
3268
  if (wasStreaming && !streaming) this._updateContent();
3269
+ if (wasStreaming && !streaming) this._settleWrittenSegments();
3210
3270
  if (wasStreaming && !streaming && this._segments.length > 0) this._redrawIfStale();
3211
3271
  }
3212
3272
  }
@@ -3515,6 +3575,8 @@ class AparteChatViewport extends HTMLElement {
3515
3575
  * (e.g. Angular) owns the bubble elements.
3516
3576
  */
3517
3577
  _frameworkManagedDOM = false;
3578
+ /** Inside `setMessages`: each append leaves the layout work to the end of the loop. */
3579
+ _bulkAppend = false;
3518
3580
  static get observedAttributes() {
3519
3581
  return ["scroll-threshold", "max-rendered-bubbles", "loading"];
3520
3582
  }
@@ -3993,6 +4055,7 @@ class AparteChatViewport extends HTMLElement {
3993
4055
  populateBubbleFromMessage(bubble, stored);
3994
4056
  }
3995
4057
  }
4058
+ if (this._bulkAppend) return;
3996
4059
  this._pruneRenderedBubbles();
3997
4060
  this._syncBusy();
3998
4061
  if (message.role === "user") {
@@ -4195,13 +4258,6 @@ class AparteChatViewport extends HTMLElement {
4195
4258
  this._checkpointState?.clear();
4196
4259
  this.dispatchEvent(new CustomEvent("aparte-reset-done", { bubbles: true, composed: true }));
4197
4260
  }
4198
- /**
4199
- * Clear all messages
4200
- * @deprecated Use clearAll() to also remove DOM bubbles
4201
- */
4202
- clearMessages() {
4203
- this._repo.clear();
4204
- }
4205
4261
  /**
4206
4262
  * Replace the entire message list in one shot. Used when switching
4207
4263
  * conversations: clears existing repo + DOM, then appends each message.
@@ -4212,9 +4268,19 @@ class AparteChatViewport extends HTMLElement {
4212
4268
  */
4213
4269
  setMessages(messages) {
4214
4270
  this.clearAll({ revokeAttachments: false });
4215
- for (const m2 of messages) {
4216
- this.appendMessage(m2, { historical: true });
4271
+ this._bulkAppend = true;
4272
+ try {
4273
+ for (const m2 of messages) {
4274
+ this.appendMessage(m2, { historical: true });
4275
+ }
4276
+ } finally {
4277
+ this._bulkAppend = false;
4217
4278
  }
4279
+ this._pruneRenderedBubbles();
4280
+ this._syncBusy();
4281
+ if (messages.some((m2) => m2.role === "user")) this._isAutoScrollEnabled = true;
4282
+ this._recalculateSpacer();
4283
+ this._autoScroll();
4218
4284
  }
4219
4285
  /**
4220
4286
  * Scroll to bottom of viewport
@@ -7182,6 +7248,7 @@ class AparteSuggestions extends HTMLElement {
7182
7248
  this._transcriptObserver?.disconnect();
7183
7249
  this._transcriptObserver = null;
7184
7250
  this._transcript = null;
7251
+ this._stopHolding();
7185
7252
  window.removeEventListener("aparte-config-change", this._onConfigChange);
7186
7253
  }
7187
7254
  attributeChangedCallback(name) {
@@ -7289,7 +7356,8 @@ class AparteSuggestions extends HTMLElement {
7289
7356
  const last = bubbles && bubbles.length ? bubbles[bubbles.length - 1] : null;
7290
7357
  const marks = last && last.getAttribute("data-role") !== "user" ? last.querySelectorAll("[data-aparte-suggestions]") : null;
7291
7358
  const mark = marks && marks.length ? marks[marks.length - 1] : null;
7292
- this._showAnswers(mark ? parseSuggestions(mark.getAttribute("data-aparte-suggestions") ?? "[]") : []);
7359
+ const offered = mark ? parseSuggestions(mark.getAttribute("data-aparte-suggestions") ?? "[]") : [];
7360
+ this._showAnswers(offered.map(visibleReply).filter((r) => r !== null));
7293
7361
  }
7294
7362
  /** Show these replies; the same ones already shown redraw nothing (a transcript mutation is frequent). */
7295
7363
  _showAnswers(list) {
@@ -7331,6 +7399,40 @@ class AparteSuggestions extends HTMLElement {
7331
7399
  }
7332
7400
  this.appendChild(row);
7333
7401
  }
7402
+ _sending = false;
7403
+ _sendingTimer;
7404
+ _stopHolding = () => {
7405
+ this._sending = false;
7406
+ clearTimeout(this._sendingTimer);
7407
+ window.removeEventListener("aparte-message-start", this._onTurnStart);
7408
+ };
7409
+ /**
7410
+ * The latch ends when ITS chat's turn starts. Another chat's `aparte-message-start` crosses the
7411
+ * window too, and must not release it: the second chip would then send a second message while the
7412
+ * first is still being built. The composer's own rule: an event naming no chat is for every chat.
7413
+ */
7414
+ _onTurnStart = (e) => {
7415
+ const from = e.detail?.targetId;
7416
+ const own = this._ownChatId();
7417
+ if (!from || !own || from === own) this._stopHolding();
7418
+ };
7419
+ /** The chat the sending composer belongs to: its `target`, else the id of the chat host above it. */
7420
+ _ownChatId() {
7421
+ const composer = this._composer;
7422
+ const attr = composer?.getAttribute("target");
7423
+ if (attr) return attr;
7424
+ for (let el2 = composer?.parentElement ?? null; el2; el2 = el2.parentElement) {
7425
+ if ((el2.tagName.toLowerCase() === "aparte-chat" || el2.hasAttribute("data-aparte-chat")) && el2.id) return el2.id;
7426
+ }
7427
+ return void 0;
7428
+ }
7429
+ /** A chip sent: no other chip sends until the turn has started, or a second has passed without one. */
7430
+ _holdUntilStreaming() {
7431
+ this._stopHolding();
7432
+ this._sending = true;
7433
+ window.addEventListener("aparte-message-start", this._onTurnStart);
7434
+ this._sendingTimer = setTimeout(this._stopHolding, 1e3);
7435
+ }
7334
7436
  _activate(suggestion) {
7335
7437
  const detail = { label: labelOf(suggestion), prompt: promptOf(suggestion) };
7336
7438
  const proceed = this.dispatchEvent(new CustomEvent("aparte-suggestion", {
@@ -7346,11 +7448,27 @@ class AparteSuggestions extends HTMLElement {
7346
7448
  return;
7347
7449
  }
7348
7450
  if (composer !== this._composer) this._watchComposer();
7451
+ const held = composer;
7452
+ if (held.panelActive) return;
7453
+ const fill = this.getAttribute("mode") === "fill";
7454
+ if (!fill && (held.streaming || this._sending)) return;
7349
7455
  const chipHadFocus = this.contains(document.activeElement);
7456
+ const draft = typeof composer.value === "string" ? composer.value : "";
7457
+ const files = fill ? [] : (composer.attachments ?? []).slice();
7458
+ if (files.length) composer.clearAttachments();
7350
7459
  composer.setValue(detail.prompt);
7351
- if (this.getAttribute("mode") === "fill") composer.focus();
7460
+ if (fill) composer.focus();
7352
7461
  else {
7462
+ let sent = false;
7463
+ const sawSend = () => {
7464
+ sent = true;
7465
+ };
7466
+ composer.addEventListener("aparte-send", sawSend, { once: true });
7353
7467
  composer.submit();
7468
+ composer.removeEventListener("aparte-send", sawSend);
7469
+ if (sent) this._holdUntilStreaming();
7470
+ if (files.length) composer.addAttachments(files);
7471
+ if ((typeof composer.value === "string" ? composer.value : "") !== draft) composer.setValue(draft);
7354
7472
  if (chipHadFocus) composer.focus();
7355
7473
  }
7356
7474
  }
@@ -7409,7 +7527,6 @@ class AparteContext extends HTMLElement {
7409
7527
  */
7410
7528
  _used = null;
7411
7529
  _level = null;
7412
- _compactRequested = false;
7413
7530
  /** The last turn's usage and the reply it belongs to, so the measure has it before the list has written it back. */
7414
7531
  _lastDone = null;
7415
7532
  /** What the model reads changed with nothing on the path to say so (a Restore): the reading is an estimate until the next turn reports. */
@@ -7440,7 +7557,7 @@ class AparteContext extends HTMLElement {
7440
7557
  this._viewChanged = false;
7441
7558
  this._blank = false;
7442
7559
  this._overflow = false;
7443
- this._render(true);
7560
+ this._render();
7444
7561
  };
7445
7562
  /**
7446
7563
  * A conversation is replaced — a new chat, or one loaded in place of the last — and the
@@ -7503,7 +7620,6 @@ class AparteContext extends HTMLElement {
7503
7620
  _onCompacted = (e) => {
7504
7621
  const detail = e.detail;
7505
7622
  if (!this._isMine(detail?.targetId)) return;
7506
- this._compactRequested = false;
7507
7623
  this._compact = null;
7508
7624
  if (detail?.skipped) {
7509
7625
  this._render();
@@ -7514,11 +7630,9 @@ class AparteContext extends HTMLElement {
7514
7630
  if (!this._messages()) this._used = null;
7515
7631
  this._render();
7516
7632
  };
7517
- /** A failed compaction spends the request too; the next `danger` asks again. */
7518
7633
  _onCompactError = (e) => {
7519
7634
  const detail = e.detail;
7520
7635
  if (!this._isMine(detail?.targetId)) return;
7521
- this._compactRequested = false;
7522
7636
  this._compact = detail?.aborted ? null : "failed";
7523
7637
  this._failure = detail?.aborted ? "" : typeof detail?.error === "string" ? detail.error : "";
7524
7638
  this._render();
@@ -7680,7 +7794,7 @@ class AparteContext extends HTMLElement {
7680
7794
  if (this._used === null) return null;
7681
7795
  return { window: capacity, used: this._used, estimated: false, parts: { ...NO_PARTS }, other: this._used };
7682
7796
  }
7683
- _render(askToCompact = false) {
7797
+ _render() {
7684
7798
  const capacity = this._window();
7685
7799
  const measure = capacity === null ? null : this._measure(capacity);
7686
7800
  if (this._compact) this.setAttribute("data-compact", this._compact);
@@ -7767,13 +7881,6 @@ class AparteContext extends HTMLElement {
7767
7881
  const targetId = this._ownTargetId();
7768
7882
  const detail = { level, used, window: capacity, ratio, targetId };
7769
7883
  this.dispatchEvent(new CustomEvent("aparte-context-threshold", { detail, bubbles: true, composed: true }));
7770
- if (level !== "danger") this._compactRequested = false;
7771
- }
7772
- if (askToCompact && level === "danger" && this.hasAttribute("auto-compact") && !this._compactRequested) {
7773
- this._compactRequested = true;
7774
- window.dispatchEvent(new CustomEvent("aparte-compact", {
7775
- detail: { targetId: this._ownTargetId(), auto: true, window: capacity }
7776
- }));
7777
7884
  }
7778
7885
  }
7779
7886
  // ─────────────────────────────────────────────────────────────────────────
@@ -7982,6 +8089,7 @@ const MIN_PITCH = 6;
7982
8089
  const SETTLE_MS = 150;
7983
8090
  const MAX_ALIGN_PASSES = 4;
7984
8091
  const ALIGN_TOLERANCE = 1;
8092
+ const BAND_PERCENT = 30;
7985
8093
  class AparteScrollRail extends HTMLElement {
7986
8094
  static get observedAttributes() {
7987
8095
  return ["target", "every"];
@@ -7989,18 +8097,39 @@ class AparteScrollRail extends HTMLElement {
7989
8097
  _host = null;
7990
8098
  _mutations = null;
7991
8099
  _resizes = null;
8100
+ /** The boxes the resize observer watches: the host, the transcript and its scroll surface. */
8101
+ _sized = [];
7992
8102
  _intersections = null;
7993
8103
  /** The bubbles the intersection observer watches — compared by identity, so a re-rendered bubble is re-observed. */
7994
8104
  _observedBubbles = [];
8105
+ /**
8106
+ * Every message the reading band watches: the ticked ones and, with `every="user"`, the
8107
+ * replies too, each read under the question above it.
8108
+ */
8109
+ _bandTargets = [];
7995
8110
  /** The scroll surface the observer is rooted on, and whose bottom edge is read. */
7996
8111
  _observedSurface = null;
7997
- _rebuildQueued = false;
8112
+ /** One frame does the queued work: a full rebuild when bubbles came or went, else the re-labels. */
8113
+ _frameQueued = false;
8114
+ _rebuildWanted = false;
8115
+ /** Ticked bubbles whose text changed since the last frame: only their names can have moved. */
8116
+ _relabel = /* @__PURE__ */ new Set();
8117
+ /**
8118
+ * Each message's excerpt, read once and forgotten when a mutation touches its text: a
8119
+ * rebuild re-read the head of all 500 questions of a long conversation, twice a turn, for
8120
+ * names that had not changed.
8121
+ */
8122
+ _excerpts = /* @__PURE__ */ new WeakMap();
7998
8123
  _pickQueued = false;
7999
8124
  _currentId = null;
8000
- /** Visible ratio per message id in the reading band, from the intersection observer. */
8001
- _visible = /* @__PURE__ */ new Map();
8002
- /** The bubbles on screen at all, from the second observer; only the last one is read. */
8003
- _onScreen = /* @__PURE__ */ new Set();
8125
+ /**
8126
+ * Visible ratio per message in the reading band, from the intersection observer. Keyed by
8127
+ * the element, not its id: an id changed in place keeps what the observer saw, and a
8128
+ * bubble that left is let go with it.
8129
+ */
8130
+ _visible = /* @__PURE__ */ new WeakMap();
8131
+ /** Whether the last question is on screen at all, from the second observer. */
8132
+ _onScreen = /* @__PURE__ */ new WeakSet();
8004
8133
  _onScreenObserver = null;
8005
8134
  /** The mark a jump asked for, held until the transcript has stopped moving. */
8006
8135
  _held = null;
@@ -8021,6 +8150,8 @@ class AparteScrollRail extends HTMLElement {
8021
8150
  if (!this.getAttribute("role")) this.setAttribute("role", "navigation");
8022
8151
  this.addEventListener("click", this._onClick);
8023
8152
  this.addEventListener("keydown", this._onKeydown);
8153
+ this.addEventListener("focusin", this._onFocusIn);
8154
+ this.addEventListener("focusout", this._onFocusOut);
8024
8155
  window.addEventListener("aparte-config-change", this._onConfigChange);
8025
8156
  this._attach();
8026
8157
  }
@@ -8028,6 +8159,8 @@ class AparteScrollRail extends HTMLElement {
8028
8159
  this._detach();
8029
8160
  this.removeEventListener("click", this._onClick);
8030
8161
  this.removeEventListener("keydown", this._onKeydown);
8162
+ this.removeEventListener("focusin", this._onFocusIn);
8163
+ this.removeEventListener("focusout", this._onFocusOut);
8031
8164
  window.removeEventListener("aparte-config-change", this._onConfigChange);
8032
8165
  }
8033
8166
  attributeChangedCallback(name) {
@@ -8056,16 +8189,37 @@ class AparteScrollRail extends HTMLElement {
8056
8189
  }
8057
8190
  if (typeof MutationObserver !== "undefined") {
8058
8191
  this._mutations = new MutationObserver((records) => {
8059
- if (records.some((record) => !this.contains(record.target))) this._queueRebuild();
8192
+ for (const record of records) {
8193
+ if (this.contains(record.target)) continue;
8194
+ if (record.type === "attributes") {
8195
+ if (isBubble(record.target)) {
8196
+ this._queueRebuild();
8197
+ return;
8198
+ }
8199
+ continue;
8200
+ }
8201
+ const at = record.target instanceof Element ? record.target : record.target.parentElement;
8202
+ const owner = at?.closest("aparte-chat-bubble");
8203
+ if (owner) {
8204
+ this._excerpts.delete(owner);
8205
+ if (this._ticked(owner)) this._queueRelabel(owner);
8206
+ continue;
8207
+ }
8208
+ if (record.type === "childList" && (holdsBubbles(record.addedNodes) || holdsBubbles(record.removedNodes))) {
8209
+ this._queueRebuild();
8210
+ return;
8211
+ }
8212
+ }
8213
+ });
8214
+ this._mutations.observe(this._host, {
8215
+ childList: true,
8216
+ subtree: true,
8217
+ characterData: true,
8218
+ attributes: true,
8219
+ attributeFilter: ["message-id", "data-role"]
8060
8220
  });
8061
- this._mutations.observe(this._host, { childList: true, subtree: true, characterData: true });
8062
- }
8063
- if (typeof ResizeObserver !== "undefined") {
8064
- this._resizes = new ResizeObserver(() => this._layout());
8065
- this._resizes.observe(this._host);
8066
- const viewport = this._viewport();
8067
- if (viewport) this._resizes.observe(viewport);
8068
8221
  }
8222
+ if (typeof ResizeObserver !== "undefined") this._resizes = new ResizeObserver(() => this._layout());
8069
8223
  this._rebuild();
8070
8224
  }
8071
8225
  _detach() {
@@ -8073,19 +8227,56 @@ class AparteScrollRail extends HTMLElement {
8073
8227
  this._mutations = null;
8074
8228
  this._resizes?.disconnect();
8075
8229
  this._resizes = null;
8230
+ this._sized = [];
8231
+ this._relabel.clear();
8232
+ this._rebuildWanted = false;
8076
8233
  this._unobserve();
8077
8234
  this._release();
8078
8235
  this._host = null;
8079
8236
  }
8080
- /** Coalesce a burst of mutations (a streaming reply is one per token) into one rebuild. */
8237
+ /** Coalesce a burst of mutations into one frame of work: a rebuild, which re-names every tick too. */
8081
8238
  _queueRebuild() {
8082
- if (this._rebuildQueued) return;
8083
- this._rebuildQueued = true;
8239
+ this._rebuildWanted = true;
8240
+ this._queueFrame();
8241
+ }
8242
+ _queueRelabel(bubble) {
8243
+ this._relabel.add(bubble);
8244
+ this._queueFrame();
8245
+ }
8246
+ _queueFrame() {
8247
+ if (this._frameQueued) return;
8248
+ this._frameQueued = true;
8084
8249
  requestAnimationFrame(() => {
8085
- this._rebuildQueued = false;
8086
- this._rebuild();
8250
+ this._frameQueued = false;
8251
+ const relabel = [...this._relabel];
8252
+ this._relabel.clear();
8253
+ if (this._rebuildWanted) {
8254
+ this._rebuildWanted = false;
8255
+ this._rebuild();
8256
+ return;
8257
+ }
8258
+ const locale = resolveConfig(this).getLocale();
8259
+ for (const bubble of relabel) this._label(bubble, locale);
8087
8260
  });
8088
8261
  }
8262
+ /** Whether a bubble has a tick: every message with `every="message"`, else the user's. */
8263
+ _ticked(bubble) {
8264
+ if (!bubble.hasAttribute("message-id")) return false;
8265
+ return this.getAttribute("every") === "message" || bubble.getAttribute("data-role") === "user";
8266
+ }
8267
+ /** Re-name one bubble's tick, written only when the name changed. */
8268
+ _label(bubble, locale) {
8269
+ if (!this._host?.contains(bubble)) return;
8270
+ const id = bubble.getAttribute("message-id");
8271
+ if (!id) return;
8272
+ const tick = this.querySelector(`.aparte-scroll-rail__tick[data-message-id="${cssEscape(id)}"]`);
8273
+ if (!tick) return;
8274
+ const label = this._tickLabel(bubble, locale);
8275
+ if (tick.getAttribute("aria-label") !== label) {
8276
+ tick.setAttribute("aria-label", label);
8277
+ tick.title = label;
8278
+ }
8279
+ }
8089
8280
  _viewport() {
8090
8281
  return this._host?.querySelector("aparte-chat-viewport") ?? null;
8091
8282
  }
@@ -8095,22 +8286,31 @@ class AparteScrollRail extends HTMLElement {
8095
8286
  if (!viewport) return null;
8096
8287
  return viewport.querySelector(".aparte-viewport-container") ?? viewport;
8097
8288
  }
8098
- _bubbles() {
8289
+ /** Every message bubble of the transcript, in document order. */
8290
+ _messages() {
8099
8291
  const viewport = this._viewport();
8100
- if (!viewport) return [];
8292
+ return viewport ? Array.from(viewport.querySelectorAll("aparte-chat-bubble[message-id]")) : [];
8293
+ }
8294
+ /** The bubbles that get a tick, from all of them. */
8295
+ _bubbles(all = this._messages()) {
8101
8296
  const every = this.getAttribute("every") === "message" ? "message" : "user";
8102
- const all = Array.from(viewport.querySelectorAll("aparte-chat-bubble[message-id]"));
8103
8297
  return every === "message" ? all : all.filter((b2) => b2.getAttribute("data-role") === "user");
8104
8298
  }
8105
8299
  // ─── Rendering ────────────────────────────────────────────────────────
8106
8300
  /** The first words of a message, for the tick's name. An excerpt, never a summary. */
8107
8301
  _excerpt(bubble) {
8302
+ const known = this._excerpts.get(bubble);
8303
+ if (known !== void 0) return known;
8108
8304
  const body = bubble.querySelector(".aparte-message-content") ?? bubble;
8109
- const text = (body.textContent ?? "").replace(/\s+/g, " ").trim();
8110
- return text.length > EXCERPT_LENGTH ? `${text.slice(0, EXCERPT_LENGTH - 1).trimEnd()}…` : text;
8111
- }
8112
- _tickLabel(bubble) {
8113
- const locale = resolveConfig(this).getLocale();
8305
+ let head = "";
8306
+ const walker = document.createTreeWalker(body, NodeFilter.SHOW_TEXT);
8307
+ for (let node = walker.nextNode(); node && head.length < EXCERPT_LENGTH * 16; node = walker.nextNode()) head += node.nodeValue ?? "";
8308
+ const text = head.slice(0, EXCERPT_LENGTH * 16).replace(/\s+/g, " ").trim();
8309
+ const excerpt = text.length > EXCERPT_LENGTH ? `${text.slice(0, EXCERPT_LENGTH - 1).trimEnd()}…` : text;
8310
+ this._excerpts.set(bubble, excerpt);
8311
+ return excerpt;
8312
+ }
8313
+ _tickLabel(bubble, locale) {
8114
8314
  const role = bubble.getAttribute("data-role") === "user" ? locale.roleNameUser ?? "You" : locale.roleNameAssistant ?? "Assistant";
8115
8315
  const excerpt = this._excerpt(bubble);
8116
8316
  return excerpt ? `${role}: ${excerpt}` : role;
@@ -8125,7 +8325,9 @@ class AparteScrollRail extends HTMLElement {
8125
8325
  * and dropped when its bubble left.
8126
8326
  */
8127
8327
  _rebuild() {
8128
- const bubbles = this._bubbles();
8328
+ this._watchSizes();
8329
+ const all = this._messages();
8330
+ const bubbles = this._bubbles(all);
8129
8331
  const locale = resolveConfig(this).getLocale();
8130
8332
  const railLabel = locale.scrollRailLabel ?? "Conversation outline";
8131
8333
  if (this.getAttribute("aria-label") !== railLabel) this.setAttribute("aria-label", railLabel);
@@ -8135,6 +8337,7 @@ class AparteScrollRail extends HTMLElement {
8135
8337
  this._unobserve();
8136
8338
  this._currentId = null;
8137
8339
  this._write("--aparte-scroll-rail-hit-size", "");
8340
+ this._write("--aparte-scroll-rail-gap", "");
8138
8341
  return;
8139
8342
  }
8140
8343
  this.removeAttribute("data-empty");
@@ -8149,24 +8352,27 @@ class AparteScrollRail extends HTMLElement {
8149
8352
  const id = item.firstElementChild instanceof HTMLElement ? item.firstElementChild.dataset["messageId"] : void 0;
8150
8353
  if (id) existing.set(id, item);
8151
8354
  }
8152
- const known = /* @__PURE__ */ new Set();
8153
- let index = 0;
8355
+ const known = new Set(bubbles.map((b2) => b2.getAttribute("message-id")));
8356
+ for (const [id, item] of existing) {
8357
+ if (known.has(id)) continue;
8358
+ item.remove();
8359
+ existing.delete(id);
8360
+ }
8361
+ let at = list.firstElementChild;
8154
8362
  for (const bubble of bubbles) {
8155
8363
  const id = bubble.getAttribute("message-id");
8156
- known.add(id);
8157
8364
  let item = existing.get(id);
8158
- if (item) {
8159
- existing.delete(id);
8160
- } else {
8365
+ if (!item) {
8161
8366
  item = document.createElement("li");
8162
8367
  const tick2 = document.createElement("button");
8163
8368
  tick2.type = "button";
8164
8369
  tick2.className = "aparte-scroll-rail__tick";
8165
8370
  tick2.dataset["messageId"] = id;
8371
+ tick2.tabIndex = -1;
8166
8372
  item.appendChild(tick2);
8167
8373
  }
8168
8374
  const tick = item.firstElementChild;
8169
- const label = this._tickLabel(bubble);
8375
+ const label = this._tickLabel(bubble, locale);
8170
8376
  if (tick.getAttribute("aria-label") !== label) {
8171
8377
  tick.setAttribute("aria-label", label);
8172
8378
  tick.title = label;
@@ -8176,14 +8382,15 @@ class AparteScrollRail extends HTMLElement {
8176
8382
  } else {
8177
8383
  tick.removeAttribute("aria-current");
8178
8384
  }
8179
- const at = list.children[index] ?? null;
8180
- if (at !== item) list.insertBefore(item, at);
8181
- index++;
8385
+ if (item === at) at = at.nextElementSibling;
8386
+ else list.insertBefore(item, at);
8182
8387
  }
8183
- for (const stale of existing.values()) stale.remove();
8184
- if (this._currentId && !known.has(this._currentId)) this._currentId = null;
8185
- if (!sameElements(this._observedBubbles, bubbles)) this._observe(bubbles);
8388
+ const dropped = this._currentId !== null && !known.has(this._currentId);
8389
+ if (dropped) this._currentId = null;
8390
+ this._syncTabStop();
8391
+ if (!sameElements(this._observedBubbles, bubbles) || !sameElements(this._bandTargets, all)) this._observe(bubbles, all);
8186
8392
  this._layout();
8393
+ if (dropped) this._pickCurrent();
8187
8394
  }
8188
8395
  /**
8189
8396
  * Which tick is current is read, not computed: the scroll surface is the root and an
@@ -8195,35 +8402,50 @@ class AparteScrollRail extends HTMLElement {
8195
8402
  * position read is the bottom, because there the reader is under the latest question
8196
8403
  * whatever the band holds, and the observer has nothing to report on the last few
8197
8404
  * pixels.
8198
- */
8199
- _observe(bubbles) {
8200
- this._unobserve();
8201
- this._observedBubbles = bubbles;
8202
- if (typeof IntersectionObserver === "undefined") return;
8203
- const root = this._scrollSurface();
8204
- if (!root) return;
8205
- this._intersections = new IntersectionObserver((entries) => {
8206
- for (const entry of entries) {
8207
- const id = entry.target.getAttribute("message-id");
8208
- if (id) this._visible.set(id, entry.isIntersecting ? entry.intersectionRatio : 0);
8209
- }
8210
- this._pickCurrent();
8211
- }, { root, rootMargin: "0px 0px -70% 0px", threshold: [0, 0.1, 0.25, 0.5, 0.75, 1] });
8212
- this._onScreenObserver = new IntersectionObserver((entries) => {
8213
- for (const entry of entries) {
8214
- const id = entry.target.getAttribute("message-id");
8215
- if (!id) continue;
8216
- if (entry.isIntersecting) this._onScreen.add(id);
8217
- else this._onScreen.delete(id);
8218
- }
8219
- this._pickCurrent();
8220
- }, { root, threshold: [0] });
8221
- for (const bubble of bubbles) {
8222
- this._intersections.observe(bubble);
8223
- this._onScreenObserver.observe(bubble);
8405
+ *
8406
+ * The replies are watched too, and a reply in the band is read under its question. With
8407
+ * the questions alone the band was empty whenever the reader was inside a long reply, and
8408
+ * nothing moved the mark when the layout did: a bubble never rendered has an estimated
8409
+ * height (`content-visibility`) and takes its real one once the scroll has stopped, so a
8410
+ * still reader's question changed with no scroll and no question crossing the band. The
8411
+ * observer reports a reply entering the band whatever moved it.
8412
+ */
8413
+ _observe(bubbles, all) {
8414
+ const root = typeof IntersectionObserver === "undefined" ? null : this._scrollSurface();
8415
+ if (!root) {
8416
+ this._unobserve();
8417
+ this._observedBubbles = bubbles;
8418
+ this._bandTargets = all;
8419
+ return;
8420
+ }
8421
+ if (!this._intersections || !this._onScreenObserver || this._observedSurface !== root) {
8422
+ this._unobserve();
8423
+ this._intersections = new IntersectionObserver((entries) => {
8424
+ for (const entry of entries) this._visible.set(entry.target, entry.isIntersecting ? entry.intersectionRatio : 0);
8425
+ this._pickCurrent();
8426
+ }, { root, rootMargin: `0px 0px -${100 - BAND_PERCENT}% 0px`, threshold: [0, 0.1, 0.25, 0.5, 0.75, 1] });
8427
+ this._onScreenObserver = new IntersectionObserver((entries) => {
8428
+ for (const entry of entries) {
8429
+ if (entry.isIntersecting) this._onScreen.add(entry.target);
8430
+ else this._onScreen.delete(entry.target);
8431
+ }
8432
+ this._pickCurrent();
8433
+ }, { root, threshold: [0] });
8434
+ this._observedSurface = root;
8435
+ root.addEventListener("scroll", this._onRootScroll, { passive: true });
8436
+ }
8437
+ const next = new Set(all);
8438
+ for (const bubble of this._bandTargets) if (!next.has(bubble)) this._intersections.unobserve(bubble);
8439
+ const before = new Set(this._bandTargets);
8440
+ for (const bubble of all) if (!before.has(bubble)) this._intersections.observe(bubble);
8441
+ const last = bubbles[bubbles.length - 1];
8442
+ const previous = this._observedBubbles[this._observedBubbles.length - 1];
8443
+ if (previous !== last) {
8444
+ if (previous) this._onScreenObserver.unobserve(previous);
8445
+ this._onScreenObserver.observe(last);
8224
8446
  }
8225
- this._observedSurface = root;
8226
- root.addEventListener("scroll", this._onRootScroll, { passive: true });
8447
+ this._observedBubbles = bubbles;
8448
+ this._bandTargets = all;
8227
8449
  }
8228
8450
  _unobserve() {
8229
8451
  this._intersections?.disconnect();
@@ -8233,8 +8455,9 @@ class AparteScrollRail extends HTMLElement {
8233
8455
  this._observedSurface?.removeEventListener("scroll", this._onRootScroll);
8234
8456
  this._observedSurface = null;
8235
8457
  this._observedBubbles = [];
8236
- this._visible.clear();
8237
- this._onScreen.clear();
8458
+ this._bandTargets = [];
8459
+ this._visible = /* @__PURE__ */ new WeakMap();
8460
+ this._onScreen = /* @__PURE__ */ new WeakSet();
8238
8461
  }
8239
8462
  /** A scroll only matters at the bottom edge, where the observer is silent: one pick per frame. */
8240
8463
  _onRootScroll = () => {
@@ -8256,18 +8479,65 @@ class AparteScrollRail extends HTMLElement {
8256
8479
  if (this._held) return;
8257
8480
  const bubbles = this._observedBubbles;
8258
8481
  if (bubbles.length === 0) return;
8259
- const lastId = bubbles[bubbles.length - 1].getAttribute("message-id");
8260
- if (this._atBottom() || this._onScreen.has(lastId)) {
8482
+ const lastBubble = bubbles[bubbles.length - 1];
8483
+ const lastId = lastBubble.getAttribute("message-id");
8484
+ if (this._atBottom() || this._onScreen.has(lastBubble)) {
8261
8485
  this._setCurrent(lastId);
8262
8486
  return;
8263
8487
  }
8264
8488
  let last = null;
8265
- for (const bubble of bubbles) {
8266
- const id = bubble.getAttribute("message-id");
8267
- if ((this._visible.get(id) ?? 0) > 0) last = id;
8489
+ let above = null;
8490
+ let seen = false;
8491
+ for (const bubble of this._bandTargets) {
8492
+ if (this._ticked(bubble)) above = bubble.getAttribute("message-id");
8493
+ if ((this._visible.get(bubble) ?? 0) > 0) {
8494
+ seen = true;
8495
+ if (above !== null) last = above;
8496
+ }
8268
8497
  }
8498
+ if (last === null && seen) return;
8499
+ last ??= this._lastAbove();
8269
8500
  if (last !== null) this._setCurrent(last);
8270
8501
  }
8502
+ /**
8503
+ * The last question whose top is above the reading band's lower edge: by halves, since
8504
+ * the questions are in document order and their tops only grow. A question never
8505
+ * rendered has its estimated height (`content-visibility`), which keeps that order.
8506
+ * `null` when no question is above the edge or nothing is laid out, and the mark stays
8507
+ * as it was.
8508
+ */
8509
+ _lastAbove() {
8510
+ const surface = this._observedSurface;
8511
+ const bubbles = this._observedBubbles;
8512
+ if (!surface || bubbles.length === 0) return null;
8513
+ const box = surface.getBoundingClientRect();
8514
+ if (box.height <= 0) return null;
8515
+ const edge = box.top + box.height * BAND_PERCENT / 100;
8516
+ let low = 0;
8517
+ let high = bubbles.length - 1;
8518
+ let found = -1;
8519
+ while (low <= high) {
8520
+ const mid = low + high >> 1;
8521
+ if (bubbles[mid].getBoundingClientRect().top < edge) {
8522
+ found = mid;
8523
+ low = mid + 1;
8524
+ } else {
8525
+ high = mid - 1;
8526
+ }
8527
+ }
8528
+ return found < 0 ? null : bubbles[found].getAttribute("message-id");
8529
+ }
8530
+ /** The tick a message is read under: its own, else the question above it, as the band reads a reply. */
8531
+ _markFor(bubble) {
8532
+ const id = bubble.getAttribute("message-id");
8533
+ if (this._ticked(bubble)) return id;
8534
+ let above = null;
8535
+ for (const candidate of this._messages()) {
8536
+ if (candidate === bubble) break;
8537
+ if (this._ticked(candidate)) above = candidate.getAttribute("message-id");
8538
+ }
8539
+ return above ?? id;
8540
+ }
8271
8541
  _setCurrent(id) {
8272
8542
  if (this._currentId === id) return;
8273
8543
  this._currentId = id;
@@ -8279,6 +8549,40 @@ class AparteScrollRail extends HTMLElement {
8279
8549
  tick.removeAttribute("aria-current");
8280
8550
  }
8281
8551
  }
8552
+ this._syncTabStop();
8553
+ }
8554
+ /**
8555
+ * One Tab stop for the whole rail, as in a toolbar: the tick that has the focus, else
8556
+ * the current one, else the last. Every tick was a button in the tab order, so a
8557
+ * keyboard reader crossed 500 of them between the transcript and the composer of a
8558
+ * long conversation; the arrows, Home and End walk the rail instead.
8559
+ */
8560
+ _syncTabStop(ignoreFocus = false) {
8561
+ const ticks = Array.from(this.querySelectorAll(".aparte-scroll-rail__tick"));
8562
+ if (ticks.length === 0) return;
8563
+ const focused = ignoreFocus ? null : activeElementIn(this);
8564
+ const stop = (focused instanceof HTMLElement && ticks.includes(focused) ? focused : void 0) ?? ticks.find((t) => t.dataset["messageId"] === this._currentId) ?? ticks[ticks.length - 1];
8565
+ this._setTabStop(stop, ticks);
8566
+ }
8567
+ /**
8568
+ * The stop follows the focus onto a tick, however it got there: the arrows, a click (a
8569
+ * click on the current tick moved the focus but not the stop, which made two), a host's
8570
+ * `focus()`.
8571
+ */
8572
+ _onFocusIn = (e) => {
8573
+ const tick = e.target instanceof HTMLElement && e.target.classList.contains("aparte-scroll-rail__tick") ? e.target : null;
8574
+ if (tick && this.contains(tick)) this._setTabStop(tick, Array.from(this.querySelectorAll(".aparte-scroll-rail__tick")));
8575
+ };
8576
+ /** Leaving the rail, the stop goes back to the current tick: Tab back in lands where the reader is. */
8577
+ _onFocusOut = (e) => {
8578
+ if (e.relatedTarget instanceof Node && this.contains(e.relatedTarget)) return;
8579
+ this._syncTabStop(true);
8580
+ };
8581
+ _setTabStop(stop, ticks) {
8582
+ for (const tick of ticks) {
8583
+ const wanted = tick === stop ? 0 : -1;
8584
+ if (tick.tabIndex !== wanted) tick.tabIndex = wanted;
8585
+ }
8282
8586
  }
8283
8587
  /** Past the floor the rail scrolls itself: the current tick is kept inside its window. */
8284
8588
  _reveal(tick) {
@@ -8290,6 +8594,22 @@ class AparteScrollRail extends HTMLElement {
8290
8594
  else if (bottom > this.scrollTop + room) this.scrollTop = bottom - room;
8291
8595
  }
8292
8596
  // ─── Geometry ─────────────────────────────────────────────────────────
8597
+ /**
8598
+ * Point the resize observer at the boxes the geometry is read from. Re-pointed on each
8599
+ * rebuild: a viewport a wrapper mounts after the rail, or replaces, was never watched, and
8600
+ * the panel or composer that resized it later left the rail measuring the old box. The
8601
+ * scroll surface is watched for itself: a classic scrollbar appearing narrows it without
8602
+ * resizing the viewport, and the rail has to move clear of the bar.
8603
+ */
8604
+ _watchSizes() {
8605
+ if (!this._resizes) return;
8606
+ const wanted = [];
8607
+ for (const box of [this._host, this._viewport(), this._scrollSurface()]) if (box && !wanted.includes(box)) wanted.push(box);
8608
+ if (sameElements(this._sized, wanted)) return;
8609
+ for (const box of this._sized) if (!wanted.includes(box)) this._resizes.unobserve(box);
8610
+ for (const box of wanted) if (!this._sized.includes(box)) this._resizes.observe(box);
8611
+ this._sized = wanted;
8612
+ }
8293
8613
  /** Write a custom property on this element only when its value changed; '' removes it. */
8294
8614
  _write(name, value) {
8295
8615
  if (this._written.get(name) === value) return;
@@ -8324,18 +8644,18 @@ class AparteScrollRail extends HTMLElement {
8324
8644
  this._write("--aparte-scroll-rail-block-end", `${Math.max(0, Math.round(h2.bottom - v2.bottom))}px`);
8325
8645
  }
8326
8646
  }
8327
- const count = this._list()?.children.length ?? 0;
8328
- const height = this.clientHeight;
8329
- if (!count || !height) {
8330
- this._write("--aparte-scroll-rail-hit-size", "");
8331
- this._write("--aparte-scroll-rail-gap", "");
8332
- return;
8333
- }
8334
8647
  const above = host ?? document.documentElement;
8335
8648
  const aboveStyle = getComputedStyle(above);
8336
8649
  const hit = parseFloat(aboveStyle.getPropertyValue("--aparte-scroll-rail-hit-size")) || 24;
8337
8650
  const thickness = parseFloat(aboveStyle.getPropertyValue("--aparte-scroll-rail-tick-thickness")) || 2;
8338
- if (count * hit <= height) {
8651
+ const tightened = (this._written.get("--aparte-scroll-rail-hit-size") ?? "") !== "";
8652
+ if (tightened && this.scrollHeight <= this.clientHeight + 1) {
8653
+ this._write("--aparte-scroll-rail-hit-size", "");
8654
+ this._write("--aparte-scroll-rail-gap", "");
8655
+ }
8656
+ const height = this.clientHeight;
8657
+ const count = this._list()?.children.length ?? 0;
8658
+ if (!count || !height || count * hit <= height) {
8339
8659
  this._write("--aparte-scroll-rail-hit-size", "");
8340
8660
  this._write("--aparte-scroll-rail-gap", "");
8341
8661
  return;
@@ -8360,7 +8680,10 @@ class AparteScrollRail extends HTMLElement {
8360
8680
  if (index === -1) return;
8361
8681
  e.preventDefault();
8362
8682
  const next = e.key === "Home" ? 0 : e.key === "End" ? ticks.length - 1 : e.key === "ArrowDown" ? Math.min(ticks.length - 1, index + 1) : Math.max(0, index - 1);
8363
- ticks[next]?.focus();
8683
+ const target = ticks[next];
8684
+ if (!target) return;
8685
+ this._setTabStop(target, ticks);
8686
+ target.focus();
8364
8687
  };
8365
8688
  /**
8366
8689
  * Scroll the transcript to a message. Announced first, cancelable; then a
@@ -8387,7 +8710,7 @@ class AparteScrollRail extends HTMLElement {
8387
8710
  if (!bubble) return;
8388
8711
  this._viewport()?.setAutoScroll?.(false);
8389
8712
  this._scrollTo(bubble);
8390
- this._setCurrent(messageId);
8713
+ this._setCurrent(this._markFor(bubble));
8391
8714
  this._hold(messageId);
8392
8715
  }
8393
8716
  _bubbleOf(messageId) {
@@ -8426,7 +8749,7 @@ class AparteScrollRail extends HTMLElement {
8426
8749
  }
8427
8750
  }
8428
8751
  this._release();
8429
- if (id) this._setCurrent(id);
8752
+ if (id) this._setCurrent(bubble ? this._markFor(bubble) : id);
8430
8753
  }
8431
8754
  _release() {
8432
8755
  if (this._settleTimer !== null) clearTimeout(this._settleTimer);
@@ -8436,6 +8759,12 @@ class AparteScrollRail extends HTMLElement {
8436
8759
  this._held = null;
8437
8760
  }
8438
8761
  }
8762
+ function isBubble(node) {
8763
+ return node instanceof Element && node.localName === "aparte-chat-bubble";
8764
+ }
8765
+ function holdsBubbles(nodes) {
8766
+ return Array.from(nodes).some((n2) => n2 instanceof Element && (isBubble(n2) || n2.localName === "aparte-chat-viewport" || n2.querySelector("aparte-chat-bubble") !== null));
8767
+ }
8439
8768
  function sameElements(a4, b2) {
8440
8769
  if (a4.length !== b2.length) return false;
8441
8770
  for (let i2 = 0; i2 < a4.length; i2++) if (a4[i2] !== b2[i2]) return false;
@@ -8631,7 +8960,7 @@ class AparteSidebar extends HTMLElement {
8631
8960
  const root = rootOf(this);
8632
8961
  const controls = root === document ? Array.from(document.querySelectorAll(selector)) : [...root.querySelectorAll(selector), ...document.querySelectorAll(selector)];
8633
8962
  for (const control of controls) {
8634
- if (!this._drives(control)) continue;
8963
+ if (inRenderedContent(control) || !this._drives(control)) continue;
8635
8964
  control.setAttribute("aria-expanded", String(!this.collapsed));
8636
8965
  control.setAttribute("aria-controls", this.id);
8637
8966
  }
@@ -8719,7 +9048,7 @@ class AparteSidebar extends HTMLElement {
8719
9048
  /** A `[data-aparte-sidebar-toggle]` anywhere toggles this sidebar — no script in the host. */
8720
9049
  _onDocumentClick = (e) => {
8721
9050
  const control = eventOrigin(e)?.closest?.("[data-aparte-sidebar-toggle]");
8722
- if (!control) return;
9051
+ if (!control || inRenderedContent(control)) return;
8723
9052
  if (!this._drives(control)) return;
8724
9053
  this.toggle(control);
8725
9054
  };
@@ -9520,7 +9849,7 @@ class AparteSplit extends HTMLElement {
9520
9849
  */
9521
9850
  _onDocumentClick = (e) => {
9522
9851
  const control = eventOrigin(e)?.closest?.("[data-aparte-split-pane]");
9523
- if (!control) return;
9852
+ if (!control || inRenderedContent(control)) return;
9524
9853
  const value = (control.getAttribute("data-aparte-split-pane") ?? "").trim();
9525
9854
  const which = value === "start" || value === "end" ? value : null;
9526
9855
  const named = which ? "" : value;
@@ -9547,6 +9876,7 @@ class AparteSplit extends HTMLElement {
9547
9876
  const which = (control.getAttribute("data-aparte-split-pane") ?? "").trim();
9548
9877
  if (which !== "start" && which !== "end") continue;
9549
9878
  if (control.localName !== "button" && control.getAttribute("role") !== "button") continue;
9879
+ if (inRenderedContent(control)) continue;
9550
9880
  const target = control.closest("aparte-split") ?? rootOf(control).querySelector("aparte-split") ?? document.querySelector("aparte-split");
9551
9881
  if (target !== this) continue;
9552
9882
  if (this.stacked) control.setAttribute("aria-pressed", String(which === this.pane));
@@ -9713,7 +10043,8 @@ class AparteLauncher extends HTMLElement {
9713
10043
  * in another language. Resolved live, never kept: the boundary may arrive after connect.
9714
10044
  */
9715
10045
  _config() {
9716
- return resolveConfig(this.querySelector(`[${APARTE_HOST_ATTR}]`) ?? this);
10046
+ const boundary = Array.from(this.querySelectorAll(`[${APARTE_HOST_ATTR}]`)).find((el2) => !inRenderedContent(el2));
10047
+ return resolveConfig(boundary ?? this);
9717
10048
  }
9718
10049
  /**
9719
10050
  * The button is a child of the element, whatever was done to the children since: put
@@ -9795,14 +10126,14 @@ class AparteLauncher extends HTMLElement {
9795
10126
  * person just pressed.
9796
10127
  */
9797
10128
  _focusChat() {
9798
- const composer = Array.from(this.querySelectorAll('[role="textbox"]:not([aria-disabled="true"])')).find((el2) => !el2.closest("[hidden]") && el2.checkVisibility?.() !== false);
10129
+ const composer = Array.from(this.querySelectorAll('[role="textbox"]:not([aria-disabled="true"])')).find((el2) => !inRenderedContent(el2) && !el2.closest("[hidden]") && el2.checkVisibility?.() !== false);
9799
10130
  const target = composer ?? this._focusables().find((el2) => el2 !== this._button);
9800
10131
  target?.focus();
9801
10132
  }
9802
10133
  /** A `[data-aparte-launcher-close]` inside closes the chat — no script in your card. */
9803
10134
  _onClick = (e) => {
9804
10135
  const control = eventOrigin(e)?.closest?.("[data-aparte-launcher-close]");
9805
- if (control && this.contains(control)) this.close();
10136
+ if (control && this.contains(control) && !inRenderedContent(control)) this.close();
9806
10137
  };
9807
10138
  /**
9808
10139
  * A modal dialog open inside the card, with the key pressed inside it. The browser
@@ -9847,6 +10178,45 @@ deferHydrationOf(AparteLauncher);
9847
10178
  if (!customElements.get("aparte-launcher")) {
9848
10179
  customElements.define("aparte-launcher", AparteLauncher);
9849
10180
  }
10181
+ const INSTALLED = Symbol.for("aparte.imageHolds");
10182
+ const HELD = ".aparte-image-held[data-aparte-image]";
10183
+ function showHeldImage(link) {
10184
+ const address = link.getAttribute("data-aparte-image") ?? "";
10185
+ resolveConfig(link).showImage(address);
10186
+ const img = document.createElement("img");
10187
+ img.setAttribute("referrerpolicy", "no-referrer");
10188
+ img.setAttribute("alt", link.getAttribute("data-aparte-image-alt") ?? "");
10189
+ img.setAttribute("src", address);
10190
+ const focused = link === document.activeElement;
10191
+ link.replaceWith(img);
10192
+ if (focused) {
10193
+ img.tabIndex = -1;
10194
+ img.focus({ preventScroll: true });
10195
+ }
10196
+ }
10197
+ function onClick(event) {
10198
+ if (event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return;
10199
+ const link = event.target?.closest?.(HELD);
10200
+ if (!link) return;
10201
+ event.preventDefault();
10202
+ event.stopPropagation();
10203
+ showHeldImage(link);
10204
+ }
10205
+ function onKeyDown(event) {
10206
+ if (event.key !== "Enter" && event.key !== " ") return;
10207
+ const button = event.target;
10208
+ if (!button?.matches?.(`span${HELD}`)) return;
10209
+ event.preventDefault();
10210
+ event.stopPropagation();
10211
+ showHeldImage(button);
10212
+ }
10213
+ function installImageHoldsOnce() {
10214
+ const doc = document;
10215
+ if (doc[INSTALLED]) return;
10216
+ doc[INSTALLED] = true;
10217
+ doc.addEventListener("click", onClick, true);
10218
+ doc.addEventListener("keydown", onKeyDown, true);
10219
+ }
9850
10220
  const APARTE_ELEMENTS = [
9851
10221
  // Chat shell + transcript
9852
10222
  ["aparte-chat", AparteChat],
@@ -9886,7 +10256,10 @@ function registerAllComponents() {
9886
10256
  );
9887
10257
  }
9888
10258
  }
9889
- if (typeof document !== "undefined") installDialogTriggersOnce();
10259
+ if (typeof document !== "undefined") {
10260
+ installDialogTriggersOnce();
10261
+ installImageHoldsOnce();
10262
+ }
9890
10263
  export {
9891
10264
  A as APARTE_CONFIG_CHANGE,
9892
10265
  a as APARTE_CONVERSATION_SCHEMA_VERSION,