polygram 0.32.0 → 0.33.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.
@@ -0,0 +1,53 @@
1
+ /**
2
+ * The trailing line a still-growing preview bubble carries: "⏳ пишу дальше…".
3
+ *
4
+ * Mid-stream the reader cannot tell "more is coming" from "the bot stalled",
5
+ * and the bubble itself is the only place that can answer. Polygram appends
6
+ * the line deterministically rather than asking the agent to write one: a
7
+ * stall is precisely the moment a model stops cooperating, so an instruction
8
+ * to announce one cannot be relied on to run.
9
+ *
10
+ * Presentation, not content. It is appended AFTER a payload has been planned
11
+ * and measured, never enters the streamer's notion of the answer, and never
12
+ * reaches the transcript — see streamer.js for where it is applied and where
13
+ * it is deliberately not.
14
+ */
15
+
16
+ 'use strict';
17
+
18
+ const COMPOSING_MARKER_TEXT = '⏳ пишу дальше…';
19
+
20
+ // The plain path's form. A blank line so it reads as its own line, and
21
+ // markdown emphasis because tg()'s formatter renders `em` as <i> — the same
22
+ // italic the rich block carries.
23
+ const COMPOSING_MARKER_SUFFIX = `\n\n_${COMPOSING_MARKER_TEXT}_`;
24
+
25
+ /**
26
+ * @param {object} [opts]
27
+ * @param {boolean} [opts.styled=true] — emit the rich block's text as a typed
28
+ * italic node. The caller decides, and must decide from the CONTENT it is
29
+ * decorating, not from whether styling is available: blocksAreStyled reads
30
+ * the shape, so a styled marker on flat content makes the whole payload
31
+ * count as styled. rich-edit.js then records a styling verdict about it —
32
+ * an acceptance resets the latch's strike run, a refusal costs the
33
+ * styled→flatten retry — and every one of those verdicts would be about
34
+ * markup polygram injected rather than anything the agent wrote.
35
+ * @returns {{ block: object, plainSuffix: string }}
36
+ */
37
+ function composingMarker({ styled = true } = {}) {
38
+ return {
39
+ block: {
40
+ type: 'paragraph',
41
+ text: styled
42
+ ? [{ type: 'italic', text: COMPOSING_MARKER_TEXT }]
43
+ : COMPOSING_MARKER_TEXT,
44
+ },
45
+ plainSuffix: COMPOSING_MARKER_SUFFIX,
46
+ };
47
+ }
48
+
49
+ module.exports = {
50
+ composingMarker,
51
+ COMPOSING_MARKER_TEXT,
52
+ COMPOSING_MARKER_SUFFIX,
53
+ };
@@ -1169,6 +1169,41 @@ function toTelegramRichBlocks(markdown, opts = {}) {
1169
1169
  return { blocks, usedRich: true };
1170
1170
  }
1171
1171
 
1172
+ /**
1173
+ * partialVisibleExtent(markdown) -> number of leading SOURCE characters that a
1174
+ * partial render actually puts on screen.
1175
+ *
1176
+ * Partial mode holds the last top-level block back (it may be half-written),
1177
+ * so the reader sees the source behind blocks 0..n-2 and nothing of the rest.
1178
+ * Anything that needs to reason about "what has the reader already seen"
1179
+ * has to ask the renderer, because only the renderer knows where its own
1180
+ * blocks begin and end — a blank-line heuristic disagrees with it in both
1181
+ * directions (a fence or a loose list carries internal blank lines; adjacent
1182
+ * headings carry none).
1183
+ *
1184
+ * Returns the extent of the largest token prefix that renders no MORE than
1185
+ * the displayed blocks, so the answer is exact wherever a token maps to one
1186
+ * block and errs toward reporting less rather than claiming the reader saw
1187
+ * something they did not.
1188
+ */
1189
+ function partialVisibleExtent(markdown) {
1190
+ if (typeof markdown !== 'string' || markdown.length === 0) return 0;
1191
+ const tokens = _lexer.lexer(markdown);
1192
+ const displayed = blocksFromTokens(tokens, FLAT).length - 1;
1193
+ // One block (or none) is emitted whole rather than held back, so all of it
1194
+ // reached the screen — same rule toTelegramRichBlocks applies.
1195
+ if (displayed < 1) return markdown.length;
1196
+
1197
+ let extent = 0;
1198
+ let consumed = 0;
1199
+ for (let n = 1; n <= tokens.length; n += 1) {
1200
+ consumed += (tokens[n - 1].raw || '').length;
1201
+ if (blocksFromTokens(tokens.slice(0, n), FLAT).length > displayed) break;
1202
+ extent = consumed;
1203
+ }
1204
+ return extent;
1205
+ }
1206
+
1172
1207
  // ─── Error classification ────────────────────────────────────────────
1173
1208
  //
1174
1209
  // Capability errors (endpoint missing) latch
@@ -1254,6 +1289,7 @@ const RICH_MAX_LEN = 32768;
1254
1289
  module.exports = {
1255
1290
  needsRichRendering,
1256
1291
  toTelegramRichBlocks,
1292
+ partialVisibleExtent,
1257
1293
  RICH_MAX_LEN,
1258
1294
  resolveRichTextEnabled,
1259
1295
  isRichCapabilityError,
@@ -45,6 +45,73 @@ const DEFAULT_THROTTLE_MS = 1000;
45
45
  // (`streamThrottleMs: 50`) without rejecting the config outright.
46
46
  const THROTTLE_FLOOR_MS = 250;
47
47
 
48
+ /**
49
+ * The part of a snapshot the reader has already seen as COMPLETE: everything
50
+ * up to and including the last blank line. What follows it is the block still
51
+ * being written, which the model may revise freely.
52
+ *
53
+ * A blank line stands in for a real block boundary on purpose. It mirrors what
54
+ * the rich renderer already does — partial mode holds back the last top-level
55
+ * block, so the completed-blocks prefix IS what reached the screen — without
56
+ * a lexer call on the hot path, and it works identically on the plain path
57
+ * where rich rendering is not involved at all. It also fails OPEN: text with
58
+ * no blank line anywhere yields an empty prefix and pins nothing, matching
59
+ * rich's own rule that a single in-progress block renders as-is.
60
+ */
61
+ // Everything the reader has seen settle, in a PLAIN bubble: the complete
62
+ // lines of what was rendered. The plain path shows the whole text, so there
63
+ // is no held-back block to exempt — but the line being typed is not settled,
64
+ // and a model rewriting the sentence it is mid-way through is ordinary
65
+ // partial-mode behaviour rather than losing anything.
66
+ function completeLines(shown) {
67
+ const i = shown.lastIndexOf('\n');
68
+ return i === -1 ? '' : shown.slice(0, i + 1);
69
+ }
70
+
71
+ // Lazy so the streamer keeps loading for callers (and tests) that never touch
72
+ // the rich path, and so requiring rich.js stays out of the module's own load.
73
+ let _partialVisibleExtent = null;
74
+ function defaultRichVisibleExtent(markdown) {
75
+ if (!_partialVisibleExtent) {
76
+ ({ partialVisibleExtent: _partialVisibleExtent } = require('./rich'));
77
+ }
78
+ return _partialVisibleExtent(markdown);
79
+ }
80
+
81
+ // A task-list marker at the head of a list item, and only there. `[x]` inside
82
+ // a sentence is prose — rewriting it IS losing text, and must still be caught.
83
+ const TASK_MARKER_RE = /^([ \t]*(?:[-*+]|\d+[.)])[ \t]+)\[[ xX]\]/gm;
84
+
85
+ /**
86
+ * Flatten checkbox STATE so ticking an item reads as the same text.
87
+ *
88
+ * Polygram's own display hint tells the agent to "send an updated list with
89
+ * items checked off as you complete them" — a deliberate mutation of a line
90
+ * the reader has already seen. Comparing snapshots verbatim would refuse it
91
+ * and freeze the preview for the rest of the turn on the exact feature the
92
+ * prompt asks for. A tick loses nothing: the item is still there, in place,
93
+ * saying the same thing about a different state.
94
+ *
95
+ * Length-preserving on purpose ('[x]' and '[ ]' are both three characters),
96
+ * so a prefix stays a prefix and the comparison needs no index arithmetic.
97
+ */
98
+ function normalizeTaskMarkers(text) {
99
+ return text.replace(TASK_MARKER_RE, '$1[ ]');
100
+ }
101
+
102
+ /**
103
+ * The form both sides of the guard comparison are read in.
104
+ *
105
+ * CRLF is folded first, and not for tidiness: a boundary located by newline
106
+ * never matches `\r\n`, so a CRLF document would find none at all and
107
+ * silently switch the guard off — the one failure mode a guard must not have.
108
+ * Trailing whitespace goes too: a snapshot that loses a blank line off its end
109
+ * has lost nothing anyone was reading.
110
+ */
111
+ function canonicalizeForGuard(text) {
112
+ return normalizeTaskMarkers(text.replace(/\r\n/g, '\n')).replace(/\s+$/, '');
113
+ }
114
+
48
115
  function createStreamer({
49
116
  // async (payload) -> { message_id, _hadReplyAnchor?, wentRich? }
50
117
  //
@@ -120,6 +187,33 @@ function createStreamer({
120
187
  // OPENS rich never had a plain shape to change, so it does not fire —
121
188
  // the metric stays a count of visible flips.
122
189
  onRichUpgrade = () => {},
190
+ // Fires once per refused snapshot — one that lost text the reader had
191
+ // already seen. Receives { prevLen, newLen }; the caller owns the chat and
192
+ // turn identifiers, which this module has no business knowing, and a turn
193
+ // that keeps offending is a count over the rows it writes.
194
+ onNonCumulativeSnapshot = () => {},
195
+ // Optional "still writing" tail for partial renders.
196
+ //
197
+ // toComposingMarker() -> { block, plainSuffix } | null
198
+ //
199
+ // Called per partial render, so a caller whose rendering capabilities shift
200
+ // mid-turn (typed nodes refused, say) answers with the shape that fits NOW —
201
+ // the same reason toRichPayload is a callback rather than a value. null
202
+ // keeps every bubble exactly as it was before this existed.
203
+ //
204
+ // Deliberately NOT applied to: the initial send (sendMessage and
205
+ // sendRichMessage are the only streamer verbs that write a transcript row —
206
+ // skipping them is what keeps the marker out of storage without threading a
207
+ // do-not-persist signal through the send path), finalize, or a seal. Those
208
+ // render a bubble that is DONE, and a finished bubble must not claim
209
+ // otherwise.
210
+ toComposingMarker = null,
211
+ // (markdown) -> number of leading source characters a PARTIAL rich render
212
+ // displays. Injected for the same reason toRichPayload is: the streamer
213
+ // does not own the renderer. Defaults to lib/telegram/rich's answer, which
214
+ // is the renderer every polygram caller actually uses; a caller with no
215
+ // rich path never reaches it.
216
+ richVisibleExtent = defaultRichVisibleExtent,
123
217
  } = {}) {
124
218
  // throttleMs may be a number OR a function evaluated per edit. Telegram's
125
219
  // rate limits are per CHAT, but a streamer is per turn — several forum topics
@@ -139,6 +233,18 @@ function createStreamer({
139
233
  let hadReplyAnchor = false;
140
234
  let currentText = ''; // what's on screen right now (truncated to maxLen) — plain-path only
141
235
  let currentRichJson = null; // JSON.stringify of the last-sent rich blocks, or null when not in rich mode
236
+ // Whether the bubble is currently showing the composing marker. Tracked
237
+ // beside the content state rather than inside it: currentText and
238
+ // currentRichJson answer "is the content on screen current?", and folding a
239
+ // presentation suffix into them would re-edit unchanged bubbles. It is a
240
+ // second reason to edit, never a change of what the answer says.
241
+ let currentMarkerShown = false;
242
+ // The source behind what the reader can currently see, recorded by whichever
243
+ // render put it there. The append-only guard pins exactly this: a rich frame
244
+ // contributes the source of the blocks it displayed (the held-back tail was
245
+ // never shown), a plain frame the complete lines it displayed. Empty means
246
+ // nothing has been rendered yet, and nothing may be pinned.
247
+ let pinnedSource = '';
142
248
  let latestText = ''; // latest we've been told about
143
249
  let lastEditTs = 0;
144
250
  let pendingEdit = null; // timer id
@@ -173,11 +279,11 @@ function createStreamer({
173
279
  // is coming. Finalize doesn't truncate: overflow is handled by
174
280
  // signalling the caller to discard-and-redeliver via chunkMarkdownText,
175
281
  // which preserves all content without any byte-cut.
176
- function truncateForLive(s) {
177
- if (s.length <= maxLen) return s;
282
+ function truncateForLive(s, limit = maxLen) {
283
+ if (s.length <= limit) return s;
178
284
  // Back off one unit if the cut would split a surrogate pair (emoji /
179
285
  // astral chars) — a lone high surrogate renders as � in the live bubble.
180
- let cut = maxLen - 3;
286
+ let cut = limit - 3;
181
287
  const cc = s.charCodeAt(cut - 1);
182
288
  if (cc >= 0xD800 && cc <= 0xDBFF) cut -= 1;
183
289
  return s.slice(0, cut) + '...';
@@ -200,6 +306,33 @@ function createStreamer({
200
306
  async function onChunk(text) {
201
307
  if (state === 'finalized') return;
202
308
  text = applyTransform(text);
309
+
310
+ // Snapshots must only ever grow. Backends that build the text by
311
+ // appending satisfy this by construction; a model driving the snapshot
312
+ // itself can send a longer one that dropped earlier sections, and
313
+ // rendering it wipes text the reader is part-way through. Refuse it:
314
+ // leave the bubble on the last good snapshot and let the turn's reply
315
+ // deliver the truth, which is what it does anyway.
316
+ //
317
+ // The pin is what the RENDERER put on screen, recorded when it did — not
318
+ // a boundary re-derived from the accepted text afterwards. Only the
319
+ // renderer knows where its own blocks begin, and a snapshot can be
320
+ // accepted while its edit is still throttled, so "last accepted" and
321
+ // "on screen" are not the same text. Empty until something has actually
322
+ // been rendered, which is what keeps a turn that has not opened a bubble
323
+ // from pinning a greeting nobody saw.
324
+ const pinned = canonicalizeForGuard(pinnedSource);
325
+ if (pinned && !canonicalizeForGuard(text).startsWith(pinned)) {
326
+ try {
327
+ onNonCumulativeSnapshot({
328
+ prevLen: latestText.length,
329
+ newLen: text.length,
330
+ });
331
+ } catch (err) {
332
+ logger.error?.(`[stream] onNonCumulativeSnapshot threw: ${err.message}`);
333
+ }
334
+ return;
335
+ }
203
336
  latestText = text;
204
337
 
205
338
  // idle: not yet sent the initial message. Only fire the initial send
@@ -257,10 +390,22 @@ function createStreamer({
257
390
  if (res?.wentRich === false) {
258
391
  currentText = plainText;
259
392
  currentRichJson = null;
393
+ notePinned(shownPlainSource(plainText, text), false);
260
394
  } else {
261
395
  currentRichJson = JSON.stringify(openRich.blocks);
396
+ notePinned(text, true);
262
397
  }
398
+ } else {
399
+ notePinned(shownPlainSource(plainText, text), false);
263
400
  }
401
+ // The open carries no marker, and flush only ever runs off a LATER
402
+ // snapshot — so a turn that emits one snapshot and then goes quiet,
403
+ // the sharpest form of "is it still writing or did it die?", would
404
+ // never show one. Schedule the frame that adds it. Content is
405
+ // unchanged, so for a caller with no marker this flush finds nothing
406
+ // to do and issues no edit; gated anyway, since scheduling a timer at
407
+ // all is a change those callers did not ask for.
408
+ if (msgId != null && toComposingMarker) scheduleEdit();
264
409
  } catch (err) {
265
410
  if (generation !== bubbleGeneration) return;
266
411
  logger.error(`[stream] initial send failed: ${err.message}`);
@@ -311,6 +456,62 @@ function createStreamer({
311
456
  return payload && payload.usedRich ? payload : null;
312
457
  }
313
458
 
459
+ // The marker for THIS partial render, or null when there is none to show or
460
+ // no room for it. `contentLen` is measured on the content alone and the
461
+ // marker has to fit beside it: a bubble gives up the marker before it gives
462
+ // up a character of the answer.
463
+ // Record what a frame just put on screen, so the guard pins that and only
464
+ // that. `shownSource` is the source the frame rendered; `wasRich` picks
465
+ // which part of it the reader actually saw.
466
+ // The source prefix a plain frame actually displayed. An untruncated frame
467
+ // showed all of it; a truncated one showed everything before the "..." the
468
+ // truncation appended, and pinning past that would pin characters the
469
+ // reader could not see.
470
+ function shownPlainSource(rendered, source) {
471
+ return rendered === source ? source : rendered.slice(0, -3);
472
+ }
473
+
474
+ function notePinned(shownSource, wasRich) {
475
+ // partialVisibleExtent answers from the renderer's own token/block stream,
476
+ // so the pin cannot disagree with what was drawn. Absent (a caller with no
477
+ // rich path at all), a rich frame is impossible anyway.
478
+ const visible = wasRich
479
+ ? shownSource.slice(0, richVisibleExtent ? richVisibleExtent(shownSource) : 0)
480
+ : shownSource;
481
+ // Settled, not merely visible. A rich frame with nothing held back — one
482
+ // block, which the renderer draws rather than showing an empty bubble —
483
+ // puts the block being WRITTEN on screen, and the reader is watching it
484
+ // resize. Its finished lines have settled; the line in progress has not,
485
+ // exactly as on the plain path.
486
+ pinnedSource = completeLines(visible);
487
+ }
488
+
489
+ // The marker this render would carry, before any question of whether it
490
+ // fits. `blocks` is the planned content (null on the plain path): the
491
+ // builder needs it because a marker that is styled while the content is not
492
+ // would make polygram's own decoration the thing rich-edit.js's styling
493
+ // verdicts are recorded about.
494
+ function buildComposingMarker(blocks) {
495
+ if (!toComposingMarker) return null;
496
+ let marker;
497
+ try {
498
+ marker = toComposingMarker({ blocks });
499
+ } catch (err) {
500
+ logger.error?.(`[stream] toComposingMarker threw, rendering without it: ${err.message}`);
501
+ return null;
502
+ }
503
+ if (!marker || !marker.block || typeof marker.plainSuffix !== 'string') return null;
504
+ return marker;
505
+ }
506
+
507
+ // Whether `marker` fits beside content of `contentLen` under `cap`. One
508
+ // budget for both shapes: the rich block's rendered weight is the same line
509
+ // of text the plain suffix carries, and a single measurement keeps the two
510
+ // paths from disagreeing about whether there is room.
511
+ function markerFits(marker, contentLen, cap) {
512
+ return marker != null && contentLen + marker.plainSuffix.length <= cap;
513
+ }
514
+
314
515
  async function flush() {
315
516
  pendingEdit = null;
316
517
  if (state !== 'live' || msgId == null) return;
@@ -347,26 +548,48 @@ function createStreamer({
347
548
  const richPayload = resolveRichPayload(sourceText, { partial: true });
348
549
  if (richPayload) {
349
550
  const json = JSON.stringify(richPayload.blocks);
350
- if (json === currentRichJson) return; // no structural change since last edit
551
+ const built = buildComposingMarker(richPayload.blocks);
552
+ const marker = markerFits(built, sourceText.length, richMaxLen) ? built : null;
553
+ // Appearing or disappearing is itself a change worth an edit — the
554
+ // content-only comparison would otherwise leave the bubble mismatched.
555
+ if (json === currentRichJson && !!marker === currentMarkerShown) return;
351
556
  const wasRich = currentRichJson !== null;
352
557
  lastEditTs = clock();
558
+ // Committed BEFORE the await, unlike the content state beside it. This
559
+ // flag's job is to tell a later seal that a marker may be on screen, and
560
+ // a detach landing during this await would otherwise snapshot "no
561
+ // marker" for a bubble about to display one — with nothing left that
562
+ // will ever edit it again. Wrong-in-the-true-direction costs one
563
+ // redundant strip edit; wrong the other way is permanent — which is
564
+ // also why this only ever SETS: a removal is believed once Telegram
565
+ // confirms it, never before.
566
+ if (marker) currentMarkerShown = true;
353
567
  try {
354
568
  // Keep the source beside its blocks so a content-error fallback
355
- // can render the same Markdown through the plain-text path.
569
+ // can render the same Markdown through the plain-text path. The
570
+ // marker is not in it: a fallback delivers the answer, not the
571
+ // decoration.
356
572
  const editResult = await edit(editMsgId, {
357
- rich: true, blocks: richPayload.blocks, sourceText,
573
+ rich: true,
574
+ blocks: marker ? [...richPayload.blocks, marker.block] : richPayload.blocks,
575
+ sourceText,
358
576
  phase: 'preview', hadReplyAnchor,
359
577
  });
360
578
  if (generation !== bubbleGeneration || msgId !== editMsgId) return;
361
579
  // A rich editor can resolve successfully after sending the same
362
580
  // source as plain fallback. Track what actually landed.
363
581
  const wentRich = editResult == null || editResult.wentRich !== false;
582
+ currentMarkerShown = !!marker; // confirmed: this frame is on screen
364
583
  if (wentRich) {
365
584
  currentRichJson = json;
585
+ notePinned(sourceText, true);
366
586
  if (!wasRich) onRichUpgrade();
367
587
  } else {
588
+ // The fallback rendered sourceText, which never carries the marker.
368
589
  currentText = sourceText;
369
590
  currentRichJson = null;
591
+ currentMarkerShown = false;
592
+ notePinned(sourceText, false);
370
593
  }
371
594
  } catch (err) {
372
595
  logger.error(`[stream] rich edit failed: ${err.message}`);
@@ -374,14 +597,30 @@ function createStreamer({
374
597
  return;
375
598
  }
376
599
 
377
- const next = truncateForLive(sourceText);
378
- if (currentRichJson === null && next === currentText) return;
600
+ const built = buildComposingMarker(null);
601
+ let next = truncateForLive(sourceText);
602
+ let marker = markerFits(built, next.length, maxLen) ? built : null;
603
+ if (built && !marker && sourceText.length > maxLen) {
604
+ // The bubble is already eliding — the text on screen is a view of the
605
+ // answer, not the answer, and finalize delivers the whole thing. Moving
606
+ // the cut back far enough to keep the marker costs nothing anyone would
607
+ // otherwise have read, and a reply long enough to be truncated is the
608
+ // one that streams longest and most needs to say it is still going.
609
+ // Content that fits WITHOUT truncation is never cut to make room: there
610
+ // the marker gives way instead.
611
+ next = truncateForLive(sourceText, maxLen - built.plainSuffix.length);
612
+ marker = built;
613
+ }
614
+ if (currentRichJson === null && next === currentText && !!marker === currentMarkerShown) return;
379
615
  lastEditTs = clock();
616
+ if (marker) currentMarkerShown = true; // before the await — see the rich branch
380
617
  try {
381
- await edit(editMsgId, next);
618
+ await edit(editMsgId, marker ? next + marker.plainSuffix : next);
382
619
  if (generation !== bubbleGeneration || msgId !== editMsgId) return;
383
620
  currentText = next;
384
621
  currentRichJson = null;
622
+ currentMarkerShown = !!marker;
623
+ notePinned(shownPlainSource(next, sourceText), false);
385
624
  } catch (err) {
386
625
  // Non-fatal — maybe 429 or transient. Log and keep going; next
387
626
  // chunk will retry. The HTML→plain fallback in lib/telegram.js
@@ -445,23 +684,75 @@ function createStreamer({
445
684
  if (snapshot.flushPromise) {
446
685
  await awaitDetached(snapshot.flushPromise, 'detached bubble flush');
447
686
  }
448
- if (targetMsgId == null || snapshot.sourceText.length > richMaxLen || !toRichPayload) return;
687
+ if (targetMsgId == null) return;
688
+
689
+ // This bubble is finished — the stream has moved to a new one and nothing
690
+ // will edit this again. A composing marker on it is now a lie, so it is a
691
+ // reason to seal in its own right, alongside media that never resolved.
692
+ const stripMarker = snapshot.markerShown === true;
693
+
694
+ const payload = (toRichPayload && snapshot.sourceText.length <= richMaxLen)
695
+ ? toRichPayload(snapshot.sourceText, { partial: false })
696
+ : null;
697
+
698
+ if (payload?.usedRich) {
699
+ const hasRescue = Array.isArray(payload.rescueEntries) && payload.rescueEntries.length > 0;
700
+ if (!hasRescue && !stripMarker) return;
701
+ const json = JSON.stringify(payload.blocks);
702
+ // Identical blocks still need the edit when a marker block is riding on
703
+ // top of them — that extra block is exactly what has to go.
704
+ if (json === snapshot.currentRichJson && !stripMarker) return;
449
705
 
450
- const payload = toRichPayload(snapshot.sourceText, { partial: false });
451
- if (!payload?.usedRich || !Array.isArray(payload.rescueEntries)
452
- || payload.rescueEntries.length === 0) {
706
+ await editWithRetry(targetMsgId, {
707
+ rich: true,
708
+ blocks: payload.blocks,
709
+ sourceText: snapshot.sourceText,
710
+ phase: 'seal',
711
+ hadReplyAnchor: targetHadReplyAnchor,
712
+ });
453
713
  return;
454
714
  }
455
- const json = JSON.stringify(payload.blocks);
456
- if (json === snapshot.currentRichJson) return;
457
-
458
- await edit(targetMsgId, {
459
- rich: true,
460
- blocks: payload.blocks,
461
- sourceText: snapshot.sourceText,
462
- phase: 'seal',
463
- hadReplyAnchor: targetHadReplyAnchor,
464
- });
715
+
716
+ if (!stripMarker) return;
717
+
718
+ // A RICH bubble whose final render declined rich still has to lose its
719
+ // marker, and it must not lose its document doing so: toRichPayload can
720
+ // render rich while partial and decline at partial:false (rich.js demotes
721
+ // a media-only document whose media never resolved, gated on !partial so
722
+ // it cannot fire during the live ticks). The blocks already on screen are
723
+ // recorded — re-send exactly those, which differ from what is displayed
724
+ // only by the marker that was appended after them.
725
+ if (snapshot.currentRichJson !== null) {
726
+ await editWithRetry(targetMsgId, {
727
+ rich: true,
728
+ blocks: JSON.parse(snapshot.currentRichJson),
729
+ sourceText: snapshot.sourceText,
730
+ phase: 'seal',
731
+ hadReplyAnchor: targetHadReplyAnchor,
732
+ });
733
+ return;
734
+ }
735
+
736
+ // A plain bubble: the content alone is the same text it already shows,
737
+ // minus the marker. truncateForLive keeps the plain path's existing cap
738
+ // contract rather than inventing a second one here.
739
+ await editWithRetry(targetMsgId, truncateForLive(snapshot.sourceText));
740
+ }
741
+
742
+ // A seal is the LAST edit a detached bubble will ever get — appendSealJob
743
+ // logs a failure and moves on, and no turn-end pass revisits it. A transient
744
+ // failure would therefore strand whatever the seal was removing, forever, so
745
+ // it is worth exactly one more attempt.
746
+ // Silent on the first failure by design: appendSealJob reports the one that
747
+ // sticks, and it reports the error CLASS rather than the message because a
748
+ // seal error can name a media path. A retry line carrying err.message would
749
+ // put that path in the log this module works to keep it out of.
750
+ async function editWithRetry(targetMsgId, payload) {
751
+ try {
752
+ await edit(targetMsgId, payload);
753
+ } catch {
754
+ await edit(targetMsgId, payload);
755
+ }
465
756
  }
466
757
 
467
758
  // 0.7.0: explicitly drain any pending edit. Useful when the caller
@@ -499,6 +790,7 @@ function createStreamer({
499
790
  msgId,
500
791
  hadReplyAnchor,
501
792
  currentRichJson,
793
+ markerShown: currentMarkerShown,
502
794
  initialSendPromise,
503
795
  flushPromise,
504
796
  };
@@ -514,6 +806,8 @@ function createStreamer({
514
806
  hadReplyAnchor = false;
515
807
  currentText = '';
516
808
  currentRichJson = null; // new bubble starts plain — see toRichPayload doc
809
+ currentMarkerShown = false;
810
+ pinnedSource = ''; // a new bubble has shown the reader nothing yet
517
811
  latestText = '';
518
812
  state = 'idle';
519
813
  lastEditTs = 0;
@@ -629,7 +923,10 @@ function createStreamer({
629
923
  };
630
924
  }
631
925
  const json = JSON.stringify(richPayload.blocks);
632
- if (json === currentRichJson) {
926
+ // A bubble showing the composing marker is NOT already correct, however
927
+ // right its content is — skipping the edit here would leave the finished
928
+ // answer claiming to still be written, permanently.
929
+ if (json === currentRichJson && !currentMarkerShown) {
633
930
  return { streamed: true, msgId, finalText: body, finalEditOk: true, overflow: false };
634
931
  }
635
932
  const wasRich = currentRichJson !== null;
@@ -640,6 +937,7 @@ function createStreamer({
640
937
  });
641
938
  // A fallback still delivered the final content, but as plain text.
642
939
  const wentRich = editResult == null || editResult.wentRich !== false;
940
+ currentMarkerShown = false; // whichever shape landed, it was the final render
643
941
  if (wentRich) {
644
942
  currentRichJson = json;
645
943
  if (!wasRich) onRichUpgrade();
@@ -677,14 +975,16 @@ function createStreamer({
677
975
  // without redelivering. If it fails (e.g. parse error after our
678
976
  // wrapper exhausts its retry, or a 5xx), caller should discard
679
977
  // and redeliver — the bubble's content is unreliable.
680
- if (currentRichJson === null && body === currentText) {
681
- // Already correct — no edit needed.
978
+ // Already correct — no edit needed. A marker on screen means it is not:
979
+ // the content matches, the bubble still says it is being written.
980
+ if (currentRichJson === null && body === currentText && !currentMarkerShown) {
682
981
  return { streamed: true, msgId, finalText: body, finalEditOk: true, overflow: false };
683
982
  }
684
983
  try {
685
984
  await edit(msgId, body);
686
985
  currentText = body;
687
986
  currentRichJson = null;
987
+ currentMarkerShown = false;
688
988
  return { streamed: true, msgId, finalText: body, finalEditOk: true, overflow: false };
689
989
  } catch (err) {
690
990
  logger.error(`[stream] final edit failed: ${err.message}`);
@@ -722,6 +1022,7 @@ function createStreamer({
722
1022
 
723
1023
  module.exports = {
724
1024
  createStreamer,
1025
+ completeLines,
725
1026
  DEFAULT_MIN_CHARS,
726
1027
  DEFAULT_THROTTLE_MS,
727
1028
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "polygram",
3
- "version": "0.32.0",
3
+ "version": "0.33.1",
4
4
  "description": "Telegram daemon for Claude Code that preserves the OpenClaw per-chat session model. Migration path for OpenClaw users moving to Claude Code.",
5
5
  "main": "lib/ipc/client.js",
6
6
  "bin": {
@@ -63,7 +63,7 @@
63
63
  "dependencies": {
64
64
  "@anthropic-ai/claude-agent-sdk": "0.2.123",
65
65
  "@modelcontextprotocol/sdk": "^1.29.0",
66
- "@shumkov/orchestra": "0.10.6",
66
+ "@shumkov/orchestra": "0.10.8",
67
67
  "better-sqlite3": "^12.9.0",
68
68
  "grammy": "^1.42.0",
69
69
  "markdown-it": "^14.1.1",