polygram 0.23.3 → 0.24.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.
@@ -108,7 +108,19 @@ function createStreamer({
108
108
  // to instrumentation for the visible bubble-shape change.
109
109
  onRichUpgrade = () => {},
110
110
  } = {}) {
111
- throttleMs = Math.max(THROTTLE_FLOOR_MS, throttleMs);
111
+ // throttleMs may be a number OR a function evaluated per edit. Telegram's
112
+ // rate limits are per CHAT, but a streamer is per turn — several forum topics
113
+ // in one chat each edit at their own cadence and share one budget. A caller
114
+ // that knows how many previews are live in the chat right now passes a
115
+ // function so the cadence scales as topics come and go mid-turn.
116
+ const fixedThrottleMs = typeof throttleMs === 'function'
117
+ ? null
118
+ : Math.max(THROTTLE_FLOOR_MS, throttleMs);
119
+ function currentThrottleMs() {
120
+ if (fixedThrottleMs != null) return fixedThrottleMs;
121
+ const n = Number(throttleMs());
122
+ return Math.max(THROTTLE_FLOOR_MS, Number.isFinite(n) && n > 0 ? n : DEFAULT_THROTTLE_MS);
123
+ }
112
124
  let state = 'idle'; // 'idle' | 'live' | 'finalized'
113
125
  let msgId = null;
114
126
  let hadReplyAnchor = false;
@@ -225,7 +237,7 @@ function createStreamer({
225
237
  const now = clock();
226
238
  const elapsed = now - lastEditTs;
227
239
  if (pendingEdit) return; // already queued
228
- const delay = Math.max(0, throttleMs - elapsed);
240
+ const delay = Math.max(0, currentThrottleMs() - elapsed);
229
241
  pendingEdit = schedule(flush, delay);
230
242
  }
231
243
 
@@ -343,6 +355,23 @@ function createStreamer({
343
355
  return sealChain;
344
356
  }
345
357
 
358
+ // The initial send is what turns the bubble from an intention into a
359
+ // message_id. onChunk flips to 'live' synchronously but assigns msgId only
360
+ // once that send resolves, so anything acting on the bubble in between —
361
+ // a final edit, a drain, a delete — would target msgId=null and the message
362
+ // that lands a moment later becomes an unreachable orphan in the chat.
363
+ // Everything that touches the bubble waits here first.
364
+ async function awaitInitialSend() {
365
+ while (initialSendPromise) {
366
+ const pending = initialSendPromise;
367
+ try { await pending; } catch { /* onChunk owns the failure path */ }
368
+ // onChunk's own continuation clears the field (it was registered on the
369
+ // promise first, so it has already committed msgId by now). If it somehow
370
+ // hasn't, stop rather than spin.
371
+ if (initialSendPromise === pending) return;
372
+ }
373
+ }
374
+
346
375
  async function drainSeals() {
347
376
  while (true) {
348
377
  const pending = sealChain;
@@ -395,6 +424,7 @@ function createStreamer({
395
424
  // visual state to be accurate (no stale half-rendered text under a
396
425
  // pending timer).
397
426
  async function flushDraft() {
427
+ await awaitInitialSend();
398
428
  if (pendingEdit) { cancel(pendingEdit); pendingEdit = null; await flush(); }
399
429
  if (flushPromise) { try { await flushPromise; } catch {} }
400
430
  await drainSeals();
@@ -479,6 +509,7 @@ function createStreamer({
479
509
  // state without touching Telegram — the bubble stays at its last
480
510
  // edited content, becoming a vestigial "head" of the conversation.
481
511
  async function discard() {
512
+ await awaitInitialSend();
482
513
  if (pendingEdit) { cancel(pendingEdit); pendingEdit = null; }
483
514
  if (flushPromise) { try { await flushPromise; } catch {} }
484
515
  await drainSeals();
@@ -513,6 +544,11 @@ function createStreamer({
513
544
  // discard + deliverReplies (false). `overflow` is the one specific
514
545
  // reason: body wouldn't fit in a single Telegram message.
515
546
  async function finalize(finalText, { errorSuffix = null } = {}) {
547
+ if (state === 'finalized') return { streamed: false, msgId, finalEditOk: false, overflow: false };
548
+ // An in-flight send can still resolve the bubble into existence (or fail
549
+ // and drop us back to 'idle'), and another caller can finalize while we
550
+ // wait — hence the re-check on the far side.
551
+ await awaitInitialSend();
516
552
  if (state === 'finalized') return { streamed: false, msgId, finalEditOk: false, overflow: false };
517
553
  if (pendingEdit) { cancel(pendingEdit); pendingEdit = null; }
518
554
  if (flushPromise) { try { await flushPromise; } catch {} }
@@ -628,6 +664,11 @@ function createStreamer({
628
664
  // Introspection for tests:
629
665
  get state() { return state; },
630
666
  get msgId() { return msgId; },
667
+ // The most recent text the streamer was told about, which is NOT always
668
+ // what's on screen (a throttled edit may still be pending) and NOT always
669
+ // what a reply delivered. A caller reconciling a live preview at turn end
670
+ // needs it to decide whether the draft still holds undelivered content.
671
+ get latestText() { return latestText; },
631
672
  get currentText() { return currentText; },
632
673
  get isRichMode() { return currentRichJson !== null; },
633
674
  get currentRichBlocks() { return currentRichJson ? JSON.parse(currentRichJson) : null; },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "polygram",
3
- "version": "0.23.3",
3
+ "version": "0.24.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.7.4",
66
+ "@shumkov/orchestra": "0.8.0",
67
67
  "better-sqlite3": "^12.9.0",
68
68
  "grammy": "^1.42.0",
69
69
  "markdown-it": "^14.1.1",
package/polygram.js CHANGED
@@ -111,11 +111,15 @@ const { sweepInbox } = require('./lib/db/inbox');
111
111
  const { parseBotArg, parseDbArg, filterConfigToBot, activeBotConfig } = require('./lib/config-scope');
112
112
  const { createStore: createPairingsStore, parseTtl: parsePairingTtl } = require('./lib/db/pairings');
113
113
  const { transcribe: transcribeVoice, isVoiceAttachment } = require('./lib/telegram/voice');
114
- const { createStreamer } = require('./lib/telegram/streamer');
114
+ const { createStreamer, DEFAULT_THROTTLE_MS } = require('./lib/telegram/streamer');
115
+ const {
116
+ createStreamerRegistry, createDeliverTextFactory, createTurnSettler,
117
+ resolveStreamPreviewEnabled,
118
+ } = require('./lib/telegram/live-preview');
115
119
  const { chunkMarkdownText } = require('./lib/telegram/chunk');
116
120
  const {
117
121
  toTelegramRichBlocks, resolveRichTextEnabled, isRichCapabilityError, isRichContentError,
118
- stripMediaMarkdown,
122
+ isRichCapabilityErrorExplicit, isRichMessageFieldRejection, stripMediaMarkdown,
119
123
  } = require('./lib/telegram/rich');
120
124
  const {
121
125
  createRichMediaResolver,
@@ -126,6 +130,15 @@ const {
126
130
  OTHER_MEDIA_UPLOAD_CEILING,
127
131
  } = require('./lib/telegram/rich-media');
128
132
  const { createRichEditor } = require('./lib/telegram/rich-edit');
133
+ const { createRichCapabilityLatch } = require('./lib/telegram/rich-capability-latch');
134
+
135
+ // What a reply consisting only of media the delivering path cannot render
136
+ // degrades to. Silence would leave the user with nothing and the agent
137
+ // believing it answered.
138
+ const MEDIA_ONLY_FALLBACK_TEXT = '(media unavailable)';
139
+ const { createRichSender } = require('./lib/telegram/rich-send');
140
+ const { createRichDeliveryFactory } = require('./lib/telegram/rich-dispatch');
141
+ const { composeDeliverTextFactories } = require('./lib/telegram/deliver-strategy');
129
142
  const { buildPolygramDisplayHint } = require('./lib/telegram/display-hint');
130
143
  const { redactBotToken, stripUrlCredentials } = require('./lib/error/net');
131
144
  // F#23: shared agent-reply helper. parseResponse + sanitizer + chunked
@@ -214,6 +227,15 @@ let mediaBuffer = null; // media-group coalescing buffer, created in createBot;
214
227
  // specific turn (not the session). The old per-session Maps were a bug
215
228
  // for concurrent pendings — the second send() would overwrite the first's
216
229
  // streamer reference before the first turn finished.
230
+ //
231
+ // The registry below is the OTHER direction: the CLI reply path runs in the
232
+ // channels dispatcher, a different call stack that has only a sessionKey, and
233
+ // it must find the turn's live preview to consume it instead of sending a
234
+ // second bubble underneath. It also answers "how many previews are live in this
235
+ // chat right now" for the per-chat edit throttle. Entries live for the span of
236
+ // one dispatched turn (registered just before dispatch, released in the
237
+ // handler's finally).
238
+ const streamerRegistry = createStreamerRegistry();
217
239
 
218
240
  // Allowlist of env var names passed through to spawned Claude processes.
219
241
  // Anything not listed here is dropped to prevent leaked secrets/ssh agents
@@ -333,12 +355,47 @@ function logEvent(kind, detail) {
333
355
  dbWrite(() => db.logEvent(kind, detail), `log ${kind}`);
334
356
  }
335
357
 
358
+ // The chunked deliverer, wrapped so the live-preview coverage set learns
359
+ // whether a reply actually landed.
360
+ //
361
+ // A reply the preview strategy passed through counts as delivered only once it
362
+ // lands. Recording it at hand-off would let a FAILED reply make a later draft
363
+ // look redundant, and the draft — the only copy the user would ever get — would
364
+ // be deleted at turn end.
365
+ async function deliverRepliesTracked(opts) {
366
+ const sessionKey = opts?.meta?.sessionKey;
367
+ try {
368
+ const res = await deliverReplies(opts);
369
+ streamerRegistry.settlePending(sessionKey, (res?.failed?.length || 0) === 0);
370
+ return res;
371
+ } catch (err) {
372
+ streamerRegistry.settlePending(sessionKey, false);
373
+ throw err;
374
+ }
375
+ }
376
+
377
+ // A streamed bubble's `messages` row is written by the INITIAL send — the first
378
+ // ~30 characters — and no later edit revisits it, so the transcript would keep
379
+ // a torso of every streamed answer. Call this whenever a bubble is finalized.
380
+ function persistBubbleText(chatId, msgId, text) {
381
+ if (msgId == null || typeof text !== 'string' || text.length === 0) return;
382
+ dbWrite(
383
+ () => db.updateOutboundText({ chat_id: chatId, msg_id: msgId, text }),
384
+ 'update streamed bubble text',
385
+ );
386
+ }
387
+
336
388
  // One bot runs per process, so rich-message capability can be represented
337
389
  // by one process-wide boolean rather than a per-connection map. Set once by
338
390
  // isRichCapabilityError (endpoint missing/404) and never cleared for the
339
391
  // process lifetime — retrying a permanently-missing endpoint on every
340
392
  // future send is wasteful. Transient errors must not set the latch.
341
393
  let richKnownUnsupported = false;
394
+ // Separate verdict for the newer sendRichMessage verb. A server can implement
395
+ // editMessageText{rich_message} and not this one, answering it with a bare
396
+ // 404 — a single shared flag would let the reply tool's probe permanently
397
+ // disable the streamer's working rich edits.
398
+ let richSendKnownUnsupported = false;
342
399
 
343
400
  // Extracted to lib/telegram/rich-edit.js so the capability/content/
344
401
  // transient error-classification + fallback wiring is directly unit-
@@ -349,6 +406,10 @@ let richKnownUnsupported = false;
349
406
  // safe to reference early because it's a stable function that does its
350
407
  // own live lookups internally when called.
351
408
  let richEditMessageText;
409
+ // Send-side counterpart, used by the reply tool. Same latch and the same
410
+ // classification, but it never throws: its caller holds the only copy of the
411
+ // reply and owns the plain fallback.
412
+ let richSendMessage;
352
413
  let richMediaFileIdCache;
353
414
 
354
415
  // 0.15 secret redaction (agent-flagged path): the agent marks a secret it saw
@@ -1192,6 +1253,10 @@ async function handleMessage(sessionKey, chatId, msg, bot) {
1192
1253
  });
1193
1254
 
1194
1255
  const botCfg = config.bot || {};
1256
+ // Whether this chat has live previews at all. Resolved once per turn: it
1257
+ // gates every behavior this feature ADDS, so a chat that never opted in
1258
+ // behaves exactly as it did before the feature existed.
1259
+ const streamPreviewEnabled = resolveStreamPreviewEnabled(config, chatId, threadId);
1195
1260
  // 0.7.0: per-chat / per-bot link-preview opt-out (port from OpenClaw).
1196
1261
  // chat-level wins over bot-level. Default (both undefined) preserves
1197
1262
  // Telegram's native auto-preview behavior.
@@ -1390,7 +1455,22 @@ async function handleMessage(sessionKey, chatId, msg, bot) {
1390
1455
  }
1391
1456
  },
1392
1457
  minChars: botCfg.streamMinChars,
1393
- throttleMs: botCfg.streamThrottleMs,
1458
+ // Telegram's edit limits are per CHAT, but forum topics share one chat_id
1459
+ // and each live topic's preview edits on its own clock. With live previews
1460
+ // on, scale the interval by however many are live in this chat right now,
1461
+ // so N busy topics cost the chat the same edit budget as one — a 429 sleep
1462
+ // here would stall the turn against the tool-ack timeout. Evaluated per
1463
+ // edit because topics start and finish mid-turn.
1464
+ //
1465
+ // Without the feature the value is passed through untouched: scaling is a
1466
+ // behavior change, and a chat that never opted in must edit exactly as it
1467
+ // did before this branch.
1468
+ throttleMs: streamPreviewEnabled
1469
+ ? () => {
1470
+ const base = botCfg.streamThrottleMs != null ? botCfg.streamThrottleMs : DEFAULT_THROTTLE_MS;
1471
+ return base * Math.max(1, streamerRegistry.liveCount(chatId));
1472
+ }
1473
+ : botCfg.streamThrottleMs,
1394
1474
  // rc.44: preserve intermediate bubbles by default. These are
1395
1475
  // regular text segments the model emits across an agentic
1396
1476
  // multi-step turn ("Let me check..." → tool runs → "Found it.
@@ -1409,6 +1489,55 @@ async function handleMessage(sessionKey, chatId, msg, bot) {
1409
1489
  });
1410
1490
  // streamer is registered with this turn via pm.send's context (below)
1411
1491
 
1492
+ // Reply bodies this turn has already put on screen. The turn-end
1493
+ // reconciliation reads it to tell an orphaned draft (deliver it) from one
1494
+ // whose content a reply already carried (delete it, don't say it twice).
1495
+ const deliveredTexts = [];
1496
+ // Assigned when the turn is actually dispatched (see below) — the early
1497
+ // returns above it never register, so this stays a no-op for them.
1498
+ let releaseStreamerRegistration = () => {};
1499
+
1500
+ // The single answer to "the turn is over; what happens to the half-written
1501
+ // bubble?", shared by every turn-completion exit so no exit can invent its
1502
+ // own. `reason: 'no-reply'` marks the one case where the agent explicitly
1503
+ // chose silence and a draft must NOT be delivered.
1504
+ //
1505
+ // Gated on the feature: for a chat without live previews there is no `stream`
1506
+ // tool, so nothing can be holding a draft that the pre-branch code wouldn't
1507
+ // have handled — and running the new rule there would change settled
1508
+ // behavior for chats that never asked for the feature.
1509
+ const finishStreamer = createTurnSettler({
1510
+ streamer,
1511
+ deliveredTexts,
1512
+ enabled: streamPreviewEnabled,
1513
+ persistBubbleText,
1514
+ logEvent,
1515
+ chatId,
1516
+ detail: {
1517
+ chat_id: chatId, thread_id: threadId, msg_id: msg.message_id, bot: BOT_NAME,
1518
+ },
1519
+ // An orphaned draft too long for one bubble takes the same escape the
1520
+ // consume rule does: deliver the whole thing as chunks rather than leave
1521
+ // the user with a truncation.
1522
+ redeliver: async (text) => {
1523
+ const chunks = chunkMarkdownText(
1524
+ resolveRichTextEnabled(config, chatId, threadId) ? stripMediaMarkdown(text) : text,
1525
+ TG_CHUNK_BUDGET,
1526
+ );
1527
+ const r = await deliverReplies({
1528
+ bot,
1529
+ send: (b, method, params, m) => tg(b, method, params, m),
1530
+ chatId,
1531
+ threadId,
1532
+ chunks,
1533
+ replyToMessageId: msg.message_id,
1534
+ meta: outMetaBase,
1535
+ logger: { error: (m) => console.error(`[${label}] ${m}`) },
1536
+ });
1537
+ return r.failed.length === 0;
1538
+ },
1539
+ });
1540
+
1412
1541
  // 0.7.2: clean up bubbles superseded by forceNewMessage() — the
1413
1542
  // intermediate text segments that fired across a tool-heavy turn.
1414
1543
  // Pre-0.7.2 (since 0.7.0 multi-bubble landed) those bubbles were
@@ -1744,27 +1873,55 @@ async function handleMessage(sessionKey, chatId, msg, bot) {
1744
1873
  // (that would block every autosteer).
1745
1874
  // Pass streamer + reactor as per-turn context; pm's callbacks
1746
1875
  // pick them off entry.pendingQueue[0].context.
1747
- await new Promise((dispatched) => {
1748
- sendPromise = sendToProcess(sessionKey, prompt, {
1749
- // 0.13 D1 (S8): the typing controller rides the per-turn context so
1750
- // the question lifecycle (callbacks.js onQuestionAsked/-Resumed) can
1751
- // pause it while the bot waits on the USER and resume on the answer.
1752
- streamer, reactor, typing: stopTyping, sourceMsgId: msg.message_id,
1753
- codexDispatchReservationId: codexDispatch?.reservationId,
1754
- codexDispatchGenerationId: codexDispatch?.generationId,
1755
- // 0.7.4 (item B): fire THINKING when Claude actually starts
1756
- // emitting — not the moment we wrote stdin.
1757
- onFirstStream: () => reactor.setState('THINKING'),
1758
- }, { onDispatched: dispatched })
1759
- .catch((e) => ({ __sendError: e }))
1760
- .finally(dispatched);
1761
- });
1876
+ //
1877
+ // Registered HERE and not at creation: the early returns above (autosteer
1878
+ // fold, codex duplicate/ambiguous) abandon their streamer without ever
1879
+ // dispatching, and registering those would let a later turn's reply find
1880
+ // a preview that was never going to exist. Only for chats that have live
1881
+ // previews — an entry for a chat without them would still be counted by
1882
+ // the per-chat throttle scaling.
1883
+ //
1884
+ // dispatchedTurnId is filled by the engine's onTurnId callback below,
1885
+ // before any tool call for this turn can reach us; it lets a reply be
1886
+ // checked against the turn it actually names.
1887
+ let dispatchedTurnId = null;
1888
+ if (streamPreviewEnabled) {
1889
+ releaseStreamerRegistration = streamerRegistry.register(sessionKey, {
1890
+ streamer, chatId, deliveredTexts,
1891
+ getTurnId: () => dispatchedTurnId,
1892
+ });
1893
+ }
1894
+ try {
1895
+ await new Promise((dispatched) => {
1896
+ sendPromise = sendToProcess(sessionKey, prompt, {
1897
+ // 0.13 D1 (S8): the typing controller rides the per-turn context so
1898
+ // the question lifecycle (callbacks.js onQuestionAsked/-Resumed) can
1899
+ // pause it while the bot waits on the USER and resume on the answer.
1900
+ streamer, reactor, typing: stopTyping, sourceMsgId: msg.message_id,
1901
+ codexDispatchReservationId: codexDispatch?.reservationId,
1902
+ codexDispatchGenerationId: codexDispatch?.generationId,
1903
+ // 0.7.4 (item B): fire THINKING when Claude actually starts
1904
+ // emitting — not the moment we wrote stdin.
1905
+ onFirstStream: () => reactor.setState('THINKING'),
1906
+ onTurnId: (id) => { dispatchedTurnId = id; },
1907
+ }, { onDispatched: dispatched })
1908
+ .catch((e) => ({ __sendError: e }))
1909
+ .finally(dispatched);
1910
+ });
1911
+ } catch (err) {
1912
+ // A throw between registering and the turn's own try/finally would
1913
+ // strand a 'live' entry, inflating liveCount for every other topic in
1914
+ // the chat for the life of the process.
1915
+ releaseStreamerRegistration();
1916
+ throw err;
1917
+ }
1762
1918
  }
1763
1919
  } finally {
1764
1920
  releaseIntent();
1765
1921
  }
1766
1922
  if (codexDispatchDecision === 'duplicate') {
1767
1923
  stopTyping();
1924
+ await finishStreamer();
1768
1925
  reactor.stop();
1769
1926
  const terminalDuplicateStatus = (
1770
1927
  codexDispatch?.state === 'settled'
@@ -1786,6 +1943,7 @@ async function handleMessage(sessionKey, chatId, msg, bot) {
1786
1943
  }
1787
1944
  if (['ambiguous', 'unavailable'].includes(codexDispatchDecision)) {
1788
1945
  stopTyping();
1946
+ await finishStreamer();
1789
1947
  await reactor.clear().catch(() => {});
1790
1948
  reactor.stop();
1791
1949
  const sendCodexDispatchNotice = (notice) => tg(bot, 'sendMessage', {
@@ -1805,6 +1963,10 @@ async function handleMessage(sessionKey, chatId, msg, bot) {
1805
1963
  }
1806
1964
  if (steered.autosteered) {
1807
1965
  stopTyping();
1966
+ // This turn's streamer was built before the steer decision and never
1967
+ // dispatched, so there is normally nothing to settle — but the exit runs
1968
+ // the same rule as every other, so it can't be the one that strands a bubble.
1969
+ await finishStreamer();
1808
1970
  // setState('AUTOSTEERED') is terminal — bypasses throttle,
1809
1971
  // serializes after any in-flight QUEUED apply via applyChain.
1810
1972
  await reactor.setState('AUTOSTEERED');
@@ -2011,10 +2173,24 @@ async function handleMessage(sessionKey, chatId, msg, bot) {
2011
2173
  // NO_REPLY is an explicit "stay silent" signal from the agent —
2012
2174
  // those still markReplied silently.
2013
2175
  if (result.text === 'NO_REPLY') {
2176
+ // Explicit silence. A half-written draft is not consent to speak, so the
2177
+ // preview is deleted rather than delivered — the one case where an
2178
+ // undelivered draft is thrown away on purpose.
2179
+ await finishStreamer('no-reply');
2014
2180
  await finalizeResultDelivery();
2015
2181
  return;
2016
2182
  }
2017
2183
  if (!result.text) {
2184
+ // Covers BOTH exits below (tool-only completion and the empty-response
2185
+ // fallback): the turn produced no text to deliver, so whatever the
2186
+ // preview holds is the only thing written this turn.
2187
+ const settled = await finishStreamer();
2188
+ // If the preview HELD an answer and we just delivered it, the turn was
2189
+ // not empty — apologizing for silence underneath the answer the user is
2190
+ // reading is worse than saying nothing.
2191
+ const previewAnswered = settled.action === 'finalized'
2192
+ || settled.action === 'redelivered'
2193
+ || settled.action === 'finalize-failed';
2018
2194
  // 0.8.0-rc.7: tool-only completion is NOT an error. Under SDK
2019
2195
  // pm, a turn that ends after running tools (no closing text
2020
2196
  // block) leaves result.text empty even though the bot DID
@@ -2025,6 +2201,19 @@ async function handleMessage(sessionKey, chatId, msg, bot) {
2025
2201
  // the emoji visually) and silently mark replied.
2026
2202
  const toolOnlyTurn = (result.metrics?.numToolUses ?? 0) > 0
2027
2203
  && (result.metrics?.numAssistantMessages ?? 0) > 0;
2204
+ if (previewAnswered) {
2205
+ // The preview held an answer and reconciliation just delivered it. The
2206
+ // turn produced no `result.text` only because the agent wrote into the
2207
+ // preview instead of replying — the user has their answer.
2208
+ logEvent('stream-orphan-answered-turn', {
2209
+ chat_id: chatId, msg_id: msg.message_id, bot: BOT_NAME,
2210
+ action: settled.action,
2211
+ });
2212
+ await reactor.clear().catch(() => {});
2213
+ clearAutosteeredReactions(sessionKey).catch(() => {});
2214
+ await finalizeResultDelivery();
2215
+ return;
2216
+ }
2028
2217
  if (toolOnlyTurn) {
2029
2218
  await reactor.clear().catch(() => {});
2030
2219
  clearAutosteeredReactions(sessionKey).catch(() => {});
@@ -2081,6 +2270,10 @@ async function handleMessage(sessionKey, chatId, msg, bot) {
2081
2270
  // parseResponse/finalize/deliver block; still clear reactor + mark
2082
2271
  // replied so the reactive UI elements close cleanly.
2083
2272
  if (result.alreadyDelivered) {
2273
+ // The CLI path delivered its replies incrementally during the turn. If a
2274
+ // preview is still live here the turn ended on a stream call (or after
2275
+ // its last reply), so settle it against what the replies actually said.
2276
+ await finishStreamer();
2084
2277
  logEvent('channels-turn-resolved', {
2085
2278
  chat_id: chatId,
2086
2279
  msg_id: msg.message_id,
@@ -2217,6 +2410,7 @@ async function handleMessage(sessionKey, chatId, msg, bot) {
2217
2410
  if (fin.finalEditOk) {
2218
2411
  // Preview was successfully edited to the final text.
2219
2412
  // No follow-up messages needed.
2413
+ persistBubbleText(chatId, fin.msgId, fin.finalText ?? parsed.text);
2220
2414
  await mediaContext.flushPartialDeliveryWarning(outMetaBase);
2221
2415
  await sendInlineStickers();
2222
2416
  await sendInlineReactions();
@@ -2348,6 +2542,10 @@ async function handleMessage(sessionKey, chatId, msg, bot) {
2348
2542
  mediaContext.recordTextFailures(deliveryResult.failed.length);
2349
2543
  }
2350
2544
 
2545
+ // A turn whose final output was a solo sticker/reaction skips the
2546
+ // finalize block above entirely, so a preview streamed earlier in the turn
2547
+ // would still be live here.
2548
+ await finishStreamer();
2351
2549
  await mediaContext.flushPartialDeliveryWarning(outMetaBase);
2352
2550
  await sendInlineStickers();
2353
2551
  await sendInlineReactions();
@@ -2403,8 +2601,38 @@ async function handleMessage(sessionKey, chatId, msg, bot) {
2403
2601
  // fresh bubble with the full answer below.
2404
2602
  const abortedByUser = isSessionRecentlyAborted(sessionKey);
2405
2603
  const quietFinalize = abortedByUser || isShuttingDown;
2604
+ // A turn that already delivered replies and THEN failed must not restate
2605
+ // them: finalize(null) publishes whatever the draft holds, which on a CLI
2606
+ // turn is usually the answer a reply already sent. That is precisely the
2607
+ // duplicate the shared rule exists to prevent, so when this turn delivered
2608
+ // anything, the error paths settle through it instead (spec §3.3's "every
2609
+ // exit" beats §3.2.3's literal wording). With nothing delivered, the old
2610
+ // direct finalize is still exactly right — it is what carries the error
2611
+ // suffix onto the partial bubble.
2612
+ const settleErrorExit = async (errorSuffix) => {
2613
+ if (deliveredTexts.length > 0) {
2614
+ await finishStreamer().catch(() => {});
2615
+ if (errorSuffix) {
2616
+ await tg(bot, 'sendMessage', {
2617
+ chat_id: chatId,
2618
+ text: `⚠️ ${errorSuffix}`,
2619
+ ...(threadId && { message_thread_id: threadId }),
2620
+ }, { ...outMetaBase, source: 'turn-error-suffix' }).catch(() => {});
2621
+ }
2622
+ return;
2623
+ }
2624
+ // null, not '': finalize falls back to the drafted body. Passing ''
2625
+ // REPLACED whatever had streamed with an empty bubble — the user watched
2626
+ // a partial answer appear and then get wiped by the very failure that
2627
+ // was supposed to leave it standing.
2628
+ const fin = await streamer.finalize(null, errorSuffix ? { errorSuffix } : {})
2629
+ .catch(() => null);
2630
+ // The bubble now shows the drafted body; bring its transcript row along,
2631
+ // or the row keeps the ~30-character stub the initial send wrote.
2632
+ if (fin?.finalEditOk) persistBubbleText(chatId, fin.msgId, fin.finalText);
2633
+ };
2406
2634
  if (quietFinalize) {
2407
- await streamer.finalize('').catch(() => {});
2635
+ await settleErrorExit(null);
2408
2636
  if (abortedByUser) {
2409
2637
  // 0.8.0-rc.13: clear the in-flight emoji on abort so the user
2410
2638
  // sees a clean message after their /stop ack — pre-rc.13 the
@@ -2426,7 +2654,9 @@ async function handleMessage(sessionKey, chatId, msg, bot) {
2426
2654
  // code, not text). TURN_TIMEOUT (went quiet) / TURN_MAX_EXCEEDED (hit hard
2427
2655
  // cap) → TIMEOUT reactor; anything else → ERROR.
2428
2656
  const { errorSuffix, reactorState } = classifyTurnEndError(err);
2429
- await streamer.finalize('', errorSuffix ? { errorSuffix } : {}).catch(() => {});
2657
+ // null keeps the drafted body so the suffix APPENDS to what the user was
2658
+ // reading instead of replacing it with a bare "⚠️ …".
2659
+ await settleErrorExit(errorSuffix);
2430
2660
  reactor.setState(reactorState);
2431
2661
  }
2432
2662
  if (deliverySettlementError) throw deliverySettlementError;
@@ -2434,6 +2664,11 @@ async function handleMessage(sessionKey, chatId, msg, bot) {
2434
2664
  } finally {
2435
2665
  stopTyping();
2436
2666
  reactor.stop();
2667
+ // The preview is settled by now on every path (a turn-completion exit or
2668
+ // the catch's finalize); drop the registry entry so a later turn on this
2669
+ // session can't find this turn's dead streamer. Removes only OUR entry —
2670
+ // a newer turn that already took the slot keeps it.
2671
+ releaseStreamerRegistration();
2437
2672
  // rc.38: defensive clear-on-exit for ✍ reactions. Pre-rc.38 only
2438
2673
  // the success path (line ~2622), the abort path (line ~2858), and
2439
2674
  // the tool-only-completion path (line ~2681) cleared
@@ -2985,6 +3220,18 @@ async function main() {
2985
3220
  }
2986
3221
  tg = createSender(db, console, config);
2987
3222
  richMediaFileIdCache = createMediaFileIdCache();
3223
+ // ONE latch decision for both rich paths. They set the same flag, so a
3224
+ // counter owned by either would let that path latch on its first bare
3225
+ // 404 while the other still believed two were required.
3226
+ // One strike counter, one verdict per verb.
3227
+ const richCapabilityLatch = createRichCapabilityLatch({
3228
+ isExplicit: isRichCapabilityErrorExplicit,
3229
+ isFieldRejection: isRichMessageFieldRejection,
3230
+ setUnsupported: (verb) => {
3231
+ if (verb === 'send') richSendKnownUnsupported = true;
3232
+ else richKnownUnsupported = true;
3233
+ },
3234
+ });
2988
3235
  richEditMessageText = createRichEditor({
2989
3236
  tg,
2990
3237
  botName: BOT_NAME,
@@ -2997,6 +3244,25 @@ async function main() {
2997
3244
  getApiRoot: () => config.bot?.apiRoot || null,
2998
3245
  stripUrlCreds: stripUrlCredentials,
2999
3246
  sanitizeFallbackText: stripMediaMarkdown,
3247
+ capabilityLatch: richCapabilityLatch,
3248
+ });
3249
+ richSendMessage = createRichSender({
3250
+ tg,
3251
+ botName: BOT_NAME,
3252
+ logEvent,
3253
+ redactBotToken,
3254
+ isRichCapabilityError,
3255
+ isRichCapabilityErrorExplicit,
3256
+ isRichContentError,
3257
+ getRichKnownUnsupported: () => richSendKnownUnsupported,
3258
+ setRichKnownUnsupported: () => { richSendKnownUnsupported = true; },
3259
+ getApiRoot: () => config.bot?.apiRoot || null,
3260
+ stripUrlCreds: stripUrlCredentials,
3261
+ // api.js leaves sendRichMessage untracked so a failed attempt can't
3262
+ // leave a row the plain fallback then duplicates; the sender persists
3263
+ // its own row, on success only.
3264
+ insertSentRow: (row) => db.insertMessage(row),
3265
+ capabilityLatch: richCapabilityLatch,
3000
3266
  });
3001
3267
  pairings = createPairingsStore(db.raw);
3002
3268
  approvals = createApprovalsStore(db.raw);
@@ -3320,6 +3586,38 @@ async function main() {
3320
3586
  console.warn(`[polygram] WARNING: ${binCheck.reason}`);
3321
3587
  }
3322
3588
  }
3589
+ // The reply-tool text-delivery chain. Two independent decisions about the
3590
+ // same reply, in the order that makes them independent:
3591
+ //
3592
+ // 1. The live preview. Only it knows whether a bubble is already on screen
3593
+ // holding this answer, so it gets first refusal — when it consumes, the
3594
+ // reply IS that bubble (the streamer's own toRichPayload renders rich
3595
+ // there, so consuming loses nothing).
3596
+ // 2. Rich delivery. Everything the preview did not consume — an interim
3597
+ // status, a late reply, a body too long for one bubble, a chat with no
3598
+ // preview at all — flows here, and then to the chunked path.
3599
+ //
3600
+ // Neither feature may switch the other off, which a single strategy slot
3601
+ // could not express.
3602
+ const makeDeliverText = composeDeliverTextFactories([
3603
+ createDeliverTextFactory({
3604
+ registry: streamerRegistry,
3605
+ logEvent,
3606
+ persistBubbleText,
3607
+ logger: console,
3608
+ botName: BOT_NAME,
3609
+ }),
3610
+ // Injected rather than imported by the dispatcher: rich-media.js requires
3611
+ // the dispatcher module, so the reverse direction would be a require cycle.
3612
+ createRichDeliveryFactory({
3613
+ bot,
3614
+ sendRich: (args) => richSendMessage(args),
3615
+ isRichTextEnabled: (chatId, threadId) => resolveRichTextEnabled(config, chatId, threadId),
3616
+ getRichKnownUnsupported: () => richSendKnownUnsupported,
3617
+ redactError: redactBotToken,
3618
+ }),
3619
+ ]);
3620
+
3323
3621
  // 0.11.0: channels backend wiring. Used when a chat opts in via
3324
3622
  // `pm: 'channels'` config. Falls back to SDK gracefully if the pinned
3325
3623
  // claude binary isn't present (see factory.js — channelsClaudeBin
@@ -3328,7 +3626,8 @@ async function main() {
3328
3626
  bot,
3329
3627
  send: tg,
3330
3628
  chunkText: chunkMarkdownText,
3331
- deliverReplies,
3629
+ deliverReplies: deliverRepliesTracked,
3630
+ makeDeliverText,
3332
3631
  // Review F#1: required so [sticker:NAME] / [react:EMOJI] / canned-string
3333
3632
  // (`No response requested.`) protections fire on channels replies too.
3334
3633
  parseResponse,
@@ -3337,6 +3636,19 @@ async function main() {
3337
3636
  // inbound on the CLI-channels reply path (handleMessage short-circuits at
3338
3637
  // `alreadyDelivered` before its own redact block, so it must fire here).
3339
3638
  redactInbound,
3639
+ redactError: redactBotToken,
3640
+ // Chat-level text hygiene for the chunked path. Deliberately independent
3641
+ // of the rich strategy below: a rich-enabled chat must never render a
3642
+ // local path, including when that strategy cannot be built or fails.
3643
+ // A reply that is nothing BUT unrenderable media degrades to a line
3644
+ // saying so rather than to silence.
3645
+ projectFallbackText: (text, { chatId, threadId }) => {
3646
+ if (!resolveRichTextEnabled(config, chatId, threadId)) return text;
3647
+ const stripped = stripMediaMarkdown(text);
3648
+ if (stripped.trim()) return stripped;
3649
+ logEvent('deliver-media-only-degraded', { chat_id: chatId, thread_id: threadId, bot: BOT_NAME });
3650
+ return MEDIA_ONLY_FALLBACK_TEXT;
3651
+ },
3340
3652
  logEvent,
3341
3653
  logger: console,
3342
3654
  });
@@ -3352,6 +3664,12 @@ async function main() {
3352
3664
  botName: BOT_NAME,
3353
3665
  // channels backend
3354
3666
  toolDispatcher: channelsToolDispatcher,
3667
+ // Which optional bridge tools this dispatcher can honor. Resolved per spawn
3668
+ // so `stream` (the live-preview tool + its prompt section) rolls out per
3669
+ // chat/topic; off by default.
3670
+ toolDispatcherCapabilities: (chatId, threadId) => ({
3671
+ stream: resolveStreamPreviewEnabled(config, chatId, threadId),
3672
+ }),
3355
3673
  channelsClaudeBin,
3356
3674
  // orchestra identity — polygram's names so behavior is byte-identical to the
3357
3675
  // copied engine. bridge/tmux/hook/attachment prefixes, product/surface prose,
@@ -3367,6 +3685,9 @@ async function main() {
3367
3685
  // CliProcess. Without it, cli chats lose the Telegram table/markdown display rules.
3368
3686
  // A resolver (not a static string) so each cli-backed chat gets its own richText
3369
3687
  // state — orchestra's factory calls this per spawn with the spawning chat/topic.
3688
+ // No inline-media guidance: replies here are delivered by the reply tool, which
3689
+ // renders rich text on media-stripped input, so an image would reach the user as
3690
+ // its caption and nothing else.
3370
3691
  displayHint: (chatId, threadId) => buildPolygramDisplayHint(resolveRichTextEnabled(config, chatId, threadId)),
3371
3692
  // Backend-default outbound cap fallback (per-spawn buildSpawnContext override
3372
3693
  // normally supersedes this; kept so any context-less spawn still gets the backend