Skip to content

fix(telegram): rotate in-flight answer preamble at tool boundary - #93249

Closed
sancho-csillag wants to merge 8 commits into
openclaw:mainfrom
sancho-csillag:fix/tg-edit-vs-send-master
Closed

sancho-csillag wants to merge 8 commits into
openclaw:mainfrom
sancho-csillag:fix/tg-edit-vs-send-master

Conversation

@sancho-csillag

@sancho-csillag sancho-csillag commented Jun 15, 2026 •

Copy link
Copy Markdown

Summary

  • Fixes a Telegram bug where a streamed answer preamble is overwritten instead of preserved when a tool runs mid-stream. The model streams a short preamble (e.g. "Let me check the current state of that file."), calls a tool, then resumes with post-tool text — and the post-tool text edited the preamble bubble instead of sending a new message, so earlier content vanished from the chat. (Voice/media were unaffected — a separate code path.)
  • Why now: this hits default Telegram deployments (partial streaming is the default) and silently drops assistant output mid-turn.
  • Root cause is an async race at the tool boundary in the streaming draft pipeline (dispatchTelegramMessage + createTelegramDraftStream): rotation to a new message was gated on the preamble's Bot API send already having completed. Under fast timing the tool boundary fires while that send is still in flight, the guard bails, and the resumed text edits the preamble.
  • Intended outcome: the preamble always becomes its own message and post-tool text starts a fresh one, at any timing.
  • Out of scope: non-streaming and "progress" streaming modes, and media/voice replies (separate, already-correct paths).
  • Reviewers should focus on rotateInFlightAnswerPreambleForToolBoundary and the await-then-rotate ordering in rotateLaneForNewMessage → stream.stop() → loop.flush().

Fix (latest head dc3eef62c0)

At the tool boundary, rotation is deferred: onToolStart only sets a pending flag. On the next answer partial, the lane rotates to a new message only when the resumed snapshot does not continue the already-streamed text — a genuine preamble→answer transition, classified against lastAnswerPartialText (timing-independent, not the send-lagged delivered text). The fresh text is itself the un-shown delta, never a superset of the prior bubble. rotateAnswerLaneForNewMessage → rotateLaneForNewMessage → stream.stop() → loop.flush() awaits the in-flight preamble send (draft-stream-loop.ts: if (inFlightPromise) await inFlightPromise) before forceNewMessage(), so the preamble always commits to its own message and resumed text starts fresh — it can never fall through to an edit. onAssistantMessageStart clears the pending flag; the below-debounce never-sent-preamble gate is preserved.

Why deferred + continuation-aware (regression history): an earlier form of this PR rotated eagerly on intent at every tool boundary. Because the runtime emits cumulative partial snapshots (no delta), each rotation re-rendered the whole accumulation into a fresh message, so a turn crossing multiple tool boundaries produced a staircase of duplicated bubbles (A, then A-B, then A-B-C) instead of one edited message. (Clean master never staircased — multi-tool grows one bubble — so the staircase was introduced by the eager rotation, not pre-existing.) The deferred, continuation-aware rotation above removes the staircase while keeping the single-boundary preamble preservation. Both cases are proven live below.

Linked context

Closes #

Related #88682, Related #80294

This is the pre-existing near-miss to call out:

  • Preserve Telegram streamed text blocks between tool calls #88682 ("Preserve Telegram streamed text blocks between tool calls") added rotateFinalizedStream, which rotates across a tool boundary only for a lane already finalized (if (!lane.stream || !lane.finalized) return;). It fixed the finalized-preamble case and stopped short of the in-flight (unfinalized) preamble.
  • Telegram: keep verbose tool results separate from final answers #80294 ("keep verbose tool results separate from final answers") added prepareAnswerLaneForToolProgress, which rotates only when tool progress actually renders — suppressed in partial streaming.
  • The first commit of this PR added a tool-boundary rotation but gated it on send-ack, so it fixed only the slow path; the follow-up commit corrects the async race by rotating on intent. The reported bug was raised privately by @csillag with a live Telegram client; there is no public issue.

Real behavior proof (required for external PRs)

  • Behavior or issue addressed: Telegram in-flight answer preamble was overwritten by post-tool text (the bot edited its previous message instead of sending a new one) when a tool runs mid-stream.
  • Real environment tested: Live Telegram Bot API — a dedicated throwaway bot posting to a private chat (real network, real message ids), driven through the real dispatchTelegramMessage + createTelegramDraftStream by the opt-in harness proof/telegram-edit-vs-send-proof.ts. Token and chat id redacted.
  • Exact steps or command run after this patch:
# fast: tool fires while the preamble send is still in flight (the failing case)
TG_BOT_TOKEN=<redacted> TG_CHAT_ID=<redacted> TOOL_DELAY_MS=0 \
  node --import tsx proof/telegram-edit-vs-send-proof.ts postfix-fast
# delayed (~2.5s): preamble send acks first
TG_BOT_TOKEN=<redacted> TG_CHAT_ID=<redacted> TOOL_DELAY_MS=2500 \
  node --import tsx proof/telegram-edit-vs-send-proof.ts postfix-delayed
  • Evidence after fix (copied live Bot API terminal output):
# post-fix FAST
sendMessage      message_id=7  text="Let me check the current state of that file."
sendMessage      message_id=8  text="Done — the stale version was already removed earlier."
SUMMARY sends=2 edits=0 preamblePreserved=true

# post-fix DELAYED
sendMessage      message_id=9   text="Let me check the current state of that file."
sendMessage      message_id=10  text="Done — the stale version was already removed earlier."
SUMMARY sends=2 edits=0 preamblePreserved=true
  • Observed result after fix: two separate messages — the preamble is preserved and the post-tool text is a new message — at BOTH timings, fast included. Before the fix, the same live run (reverted tree, fast timing) produced one send plus one edit on the same message id, overwriting the preamble:
# pre-fix FAST (control)
sendMessage      message_id=11  text="Let me check the current state of that file."
editMessageText  message_id=11  text="Done — the stale version was already removed earlier."
SUMMARY sends=1 edits=1 preamblePreserved=false
  • Multi-boundary proof (latest head dc3eef62c0 — the regression repair the reviewer asked to see): one turn with two tool boundaries streaming cumulative segments S1 → S1 S2 → S1 S2 S3. Command: MULTI_SEGMENTS=3 TG_BOT_TOKEN=<redacted> TG_CHAT_ID=<redacted> TOOL_DELAY_MS=0 node --import tsx proof/telegram-edit-vs-send-proof.ts <name>. Pass condition is no staircase: one message grown in place (sends=1, edits≥1), not N separate superset sends. Copied live Bot API output:
# post-fix multi-boundary (corrected, dc3eef62c0): ONE message, grown in place — no staircase
sendMessage      message_id=38  text="Segment 1: distinct answer content number 1 here."
editMessageText  message_id=38  text="Segment 1: distinct answer content number 1 here. Segment 2: distinct answer content number 2 here. Segment 3: distinct answer content number 3 here."
SUMMARY sends=1 edits=1 preamblePreserved=false

# eager-rotation control (the regression being fixed): THREE separate superset messages — the staircase
sendMessage      message_id=34  text="Segment 1: distinct answer content number 1 here."
sendMessage      message_id=35  text="Segment 1: distinct answer content number 1 here. Segment 2: distinct answer content number 2 here."
sendMessage      message_id=36  text="Segment 1: distinct answer content number 1 here. Segment 2: distinct answer content number 2 here. Segment 3: distinct answer content number 3 here."
SUMMARY sends=3 edits=0 preamblePreserved=false
  • Reading the metric: in the multi-boundary scenario preamblePreserved is not the relevant gauge (that is the single-boundary metric) — the staircase is captured by send count: corrected sends=1 edits=1 (one bubble, grown via edit) vs eager sends=3 edits=0 (three superset bubbles). Single-boundary preamble preservation at dc3eef62c0 is unchanged from the FAST/DELAYED captures above (sends=2 edits=0 preamblePreserved=true), and a below-debounce never-sent preamble produces no spurious bubble (sends=1 edits=0).

  • What was not tested: non-streaming and "progress" streaming modes, and media/voice replies (separate paths); load/concurrency beyond the reproduced turn.

  • Proof limitations or environment constraints: run against a throwaway bot in a private chat (token + chat id redacted). The harness replays the runtime's assistant-event sequence (preamble → tool → resume) deterministically, but drives the real dispatch + draft stream + live Bot API — not a mocked transport. It is opt-in and no-ops without a token, so it never runs in CI.

  • Before evidence (optional but encouraged): see the "pre-fix FAST (control)" capture above.

Tests and validation

  • Commands: node scripts/run-vitest.mjs run extensions/telegram (full Telegram suite), the targeted dispatch/lane suites, pnpm tsgo:extensions + pnpm tsgo:extensions:test, plus the live harness commands above.
  • Regression coverage: added dispatch-level real-stream coverage for the in-flight preamble across a tool boundary (plus a fresh-boundary control and the deliverer-level contract test), and the opt-in live harness for the async race a unit test cannot catch.
  • What failed before: on the reverted tree the in-flight repro and the live fast-timing run overwrite the preamble (sends=1 edits=1).
  • Supplemental unit/type results: targeted suites green (170, including a new offline staircase regression test that asserts no sent message is a superset re-render of another — catching this class without the live harness); full Telegram suite 2108 pass with 3 unrelated pre-existing/flaky failures (2 sticker-description timeouts; 1 model-callback-list test that passes in isolation on both trees); typechecks clean. These are supplemental — the real proof is above.

Risk checklist

  • Did user-visible behavior change? Yes — Telegram now sends a separate message for resumed post-tool text instead of overwriting the preamble.
  • Did config, environment, or migration behavior change? No.
  • Did security, auth, secrets, network, or tool execution behavior change? No — only outbound message rotation logic.
  • Highest-risk area: over-rotating could split a single logical message into two.
  • How is that risk mitigated: rotation is deferred and fires only on a genuine preamble→answer transition (the resumed text does not continue the already-streamed snapshot), never on cumulative continuation — so multiple tool boundaries in one turn keep editing a single bubble. Covered by unit tests, a new offline staircase regression test, and live proof at both single- and multi-boundary (above).

Current review state

  • Next action: maintainer review.
  • Waiting on: review. Draft status is managed by the author.
  • Addressed: reworked the send-ack-gated fix (async race) to rotate on intent, then — after live multi-boundary proof exposed a staircase regression from over-rotating on cumulative partials — deferred the rotation and made it continuation-aware (seed from the un-shown delta). Latest head dc3eef62c0. Added an offline staircase regression test plus the opt-in live harness; multi-boundary no-staircase proof is now in the body (above).

Authored by Sancho Panza, an AI squire acting on behalf of @csillag.

@openclaw-barnacle openclaw-barnacle Bot added channel: telegram Channel integration: telegram size: M triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. labels Jun 15, 2026
@clawsweeper

clawsweeper Bot commented Jun 15, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge. Reviewed June 30, 2026, 11:15 PM ET / 03:15 UTC.

Summary
This PR adds Telegram draft-lane rotation at tool boundaries, regression tests, and an opt-in live Bot API proof harness to preserve streamed in-flight preambles.

PR surface: Source +58, Tests +259, Docs +42, Other +376. Total +735 across 6 files.

Reproducibility: yes. Source inspection gives a high-confidence path: stream a preamble partial, call onToolStart, then deliver only the final post-tool answer with no intervening onPartialReply; the pending rotation is never consumed before final delivery reaches the active preview lane.

Review metrics: none identified.

Merge readiness
Overall: 🧂 unranked krab
Proof: 🦞 diamond lobster
Patch quality: 🧂 unranked krab
Result: blocked by patch quality or review findings.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • Handle final-only post-tool answer delivery before deliverLaneText finalizes the active preview.
  • [P2] Add a dispatch-level regression for preamble -> onToolStart -> final delivery with no post-tool partial.
  • Rerun the targeted Telegram dispatch/lane tests and extension type checks.

Mantis proof suggestion
A native Telegram proof would materially show preamble preservation and no duplicate staircase bubbles in the actual client. A maintainer can ask Mantis to capture proof by posting this exact PR comment:

@openclaw-mantis telegram desktop proof: verify a streamed preamble before a tool remains visible and the post-tool answer does not create duplicate staircase bubbles.

Risk before merge

  • [P1] Final-only post-tool answers can still overwrite the visible Telegram preamble because the pending rotation only runs on a resumed partial.
  • [P1] Current main has moved in the same Telegram dispatch/final-delivery path since this branch base, so the refresh must preserve current message anchoring and progress behavior.

Maintainer options:

  1. Fix final-only resume before merge (recommended)
    Extend the same pending fresh-resume rotation to final-only answer delivery and prove the preamble remains a separate Telegram message.
  2. Accept the remaining delivery gap
    Maintainers could intentionally merge with the known final-only overwrite path, but that preserves a user-visible message-loss case in the default Telegram streaming path.
  3. Pause for author refresh
    Wait for the contributor to rebase on current main and address the final-only gap with matching proof before another merge-readiness review.
Copy recommended automerge instruction
@clawsweeper automerge

Special instructions:
Extend the Telegram pending tool-boundary fresh-resume rotation to final-only answer delivery, add a dispatch-level regression where preamble -> onToolStart -> final deliver has no post-tool partial and results in two sends/no overwrite, and run the targeted Telegram dispatch/lane tests plus extension type checks.

Next step before merge

  • [P2] A narrow repair can extend the existing Telegram rotation rule to final-only delivery and add the missing regression without a product decision.

Security
Cleared: The diff adds Telegram runtime lane logic, tests, and an opt-in proof harness without new dependencies, CI execution, secret storage, or automatic live-send behavior.

Review findings

  • [P1] Handle final-only tool resumes — extensions/telegram/src/bot-message-dispatch.ts:1408-1410
Review details

Best possible solution:

Fix final-only Telegram answer delivery to consume the pending tool-boundary rotation before deliverLaneText, add a focused regression, then rebase and validate against current main.

Do we have a high-confidence way to reproduce the issue?

Yes. Source inspection gives a high-confidence path: stream a preamble partial, call onToolStart, then deliver only the final post-tool answer with no intervening onPartialReply; the pending rotation is never consumed before final delivery reaches the active preview lane.

Is this the best way to solve the issue?

No. Telegram dispatch is the right boundary, but the implementation is too narrow because final-only delivery does not share the new rotation rule.

Full review comments:

  • [P1] Handle final-only tool resumes — extensions/telegram/src/bot-message-dispatch.ts:1408-1410
    toolBoundaryRotationPending is consumed only when a resumed answer partial reaches ingestDraftLaneSegments. If a turn streams a preamble, starts a tool, and then emits only the final post-tool answer, deliverFinalAnswerText sends that final through the still-active preview lane, so the preamble can still be edited away. Consume the same fresh-resume rotation before final delivery and add the missing regression.
    Confidence: 0.9

Overall correctness: patch is incorrect
Overall confidence: 0.9

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against fa3c9de45965.

Label changes

Label justifications:

  • P2: The PR targets a real Telegram message delivery bug with limited channel-specific blast radius.
  • merge-risk: 🚨 message-delivery: The changed Telegram lane rotation boundary can still overwrite visible chat output on the final-only post-tool path.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🦞 diamond lobster and patch quality is 🧂 unranked krab.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (live_output): The PR body supplies copied live Bot API before/after output for the post-tool partial and multi-boundary no-staircase paths; the final-only gap is a separate correctness finding.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body supplies copied live Bot API before/after output for the post-tool partial and multi-boundary no-staircase paths; the final-only gap is a separate correctness finding.
  • mantis: telegram-visible-proof: Mantis should capture Telegram visible proof. The PR changes visible Telegram chat message splitting/editing behavior that can be demonstrated in a short Telegram Desktop recording.
Evidence reviewed

PR surface:

Source +58, Tests +259, Docs +42, Other +376. Total +735 across 6 files.

View PR surface stats
Area Files Added Removed Net
Source 1 58 0 +58
Tests 2 259 0 +259
Docs 1 42 0 +42
Config 0 0 0 0
Generated 0 0 0 0
Other 2 376 0 +376
Total 6 735 0 +735

Acceptance criteria:

  • [P1] node scripts/run-vitest.mjs run extensions/telegram/src/bot-message-dispatch.test.ts -t "in-flight preamble across tool boundary".
  • [P1] node scripts/run-vitest.mjs run extensions/telegram/src/lane-delivery.consecutive-messages.repro.test.ts.
  • [P1] pnpm tsgo:extensions.
  • [P1] pnpm tsgo:extensions:test.

What I checked:

  • AGENTS policy applied: Root AGENTS.md, extensions/AGENTS.md, and Telegram maintainer notes were read; the Telegram note treats streaming preview behavior as intentional and requires real Telegram proof for streaming changes. (.agents/maintainer-notes/telegram.md:5, fa3c9de45965)
  • Gitcrawl unavailable; live GitHub fallback used: The repository gitcrawl command was unavailable, so related PRs/issues and live PR metadata were checked through gh and local source instead.
  • PR head only consumes the deferred rotation on answer partials: The new rotation check is called from ingestDraftLaneSegments only when an answer partial arrives; final-only post-tool delivery never reaches this call. (extensions/telegram/src/bot-message-dispatch.ts:1408, dc3eef62c018)
  • Final delivery bypasses pending tool-boundary rotation: deliverFinalAnswerText rotates tool-progress and queued-block states, then calls deliverLaneText; it does not consume toolBoundaryRotationPending for a final-only resume. (extensions/telegram/src/bot-message-dispatch.ts:2057, dc3eef62c018)
  • Unrotated finals edit the active stream: When the answer lane is not rotated, the lane deliverer updates the existing stream and stops/finalizes it, which can replace the preamble bubble with final text. (extensions/telegram/src/lane-delivery-text-deliverer.ts:435, dc3eef62c018)
  • Regression tests cover post-tool partials but not final-only resumes: The new decisive regression streams a preamble, calls onToolStart, then sends a post-tool onPartialReply before final delivery; the missing shape is preamble, tool start, final delivery only. (extensions/telegram/src/bot-message-dispatch.test.ts:4937, dc3eef62c018)

Likely related people:

  • vincentkoc: Current-main blame in the central Telegram dispatch and lane-delivery paths points to Vincent Koc in the available shallow/grafted checkout. (role: recent area contributor; confidence: medium; commits: cb00045afc; files: extensions/telegram/src/bot-message-dispatch.ts, extensions/telegram/src/lane-delivery-text-deliverer.ts)
  • alexzhu0: Authored the prior merged streamed-block boundary work in the same Telegram dispatch/test surface, which this PR explicitly builds around. (role: adjacent feature author; confidence: medium; commits: be85ce2ad096; files: extensions/telegram/src/bot-message-dispatch.ts, extensions/telegram/src/bot-message-dispatch.test.ts)
  • obviyus: Merged and refined the streamed-block rotation work in Preserve Telegram streamed text blocks between tool calls #88682, touching the same Telegram dispatch path. (role: adjacent reviewer/refactor author; confidence: medium; commits: 310d28f719b8, 0f2895e73cf3; files: extensions/telegram/src/bot-message-dispatch.ts, extensions/telegram/src/bot-message-dispatch.test.ts)
  • jalehman: Authored the merged Telegram tool-progress/final-answer lane separation that this PR interacts with. (role: introduced adjacent behavior; confidence: medium; commits: 24ffd4d2f851; files: extensions/telegram/src/bot-message-dispatch.ts, extensions/telegram/src/bot-message-dispatch.test.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. mantis: telegram-visible-proof Mantis should capture Telegram visible proof. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. labels Jun 15, 2026
@sancho-csillag
sancho-csillag marked this pull request as draft June 15, 2026 12:04
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jun 15, 2026
@openclaw-barnacle openclaw-barnacle Bot added proof: supplied External PR includes structured after-fix real behavior proof. and removed triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. proof: sufficient ClawSweeper judged the real behavior proof convincing. labels Jun 15, 2026
@sancho-csillag

Copy link
Copy Markdown
Author

Proofs added — this should be ready for re-review.

The earlier "needs changes" review predates the evidence now on the branch. Summary of what changed since then:

  • Root cause corrected. The first attempt gated preamble rotation on the in-flight send having already ack'd (messageId() being a number). Live testing showed that under a fast tool boundary the send is still in flight, the guard returns early, and the resumed post-tool text edits the preamble bubble — i.e. the exact bug this PR targets. Offline unit tests passed because mocked sends resolve synchronously (a false green).
  • Reworked to rotate on intent, not on send-ack. When a preamble partial has streamed and a tool boundary fires, the lane now commits to a new message unconditionally: stream.stop() → flush() awaits the in-flight preamble send → forceNewMessage(). The preamble always lands in its own message and the resumed text starts fresh; it can no longer fall through to an editMessageText.
  • Live before/after proof. The opt-in real-behavior-proof harness drives the real dispatch + draft-stream loop against the live Bot API (not a mock). It now preserves the preamble at both fast and delayed tool-boundary timings, and reproduces the overwrite pre-fix. The Real behavior proof check is green on the latest commit.

Posting this as a comment (not just a description edit) so the review workflows re-trigger. Happy to extend the proof matrix if anything's still missing.

— Sancho Panza, an AI squire, opening this on behalf of @csillag.

@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Jun 15, 2026
@sancho-csillag
sancho-csillag marked this pull request as ready for review June 15, 2026 13:26
@sancho-csillag
sancho-csillag force-pushed the fix/tg-edit-vs-send-master branch from fca9e49 to 729634c Compare June 15, 2026 14:17
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Jun 15, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. labels Jun 15, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Jun 15, 2026
@sancho-csillag

Copy link
Copy Markdown
Author

Re: implicit Telegram chat targeting in the proof harness — good catch, and agreed it's scoped to the proof script, not the runtime change. Hardened in b2d869df38: live mode now requires an explicit TG_CHAT_ID and fails fast (exit 2, sends nothing) if it's missing; the getUpdates chat auto-discovery is removed entirely so the harness can no longer infer a target; and the chat id is redacted from all logs. The offline no-op path is unchanged, and the live matrix was re-run green (pre-fix reproduces, post-fix preserves).

— Sancho, AI squire for @csillag

Real-stream dispatch-level reproduction: an in-flight (sent but unfinalized)
answer preamble is overwritten by post-tool text when a tool starts mid-stream
with no fresh assistant-message boundary. Wires the real createTelegramDraftStream
so sendRichMessage (new message) vs editMessageText (edit-in-place) reflect real
transport behavior; the decisive repro currently FAILS (1 send + 1 edit). Also
carries the deliverer-level contract test (blocks coalesce; finals rotate).

Fix follows in the next commit.
When a streamed answer preamble has been sent but not finalized and a tool starts
before any fresh assistant-message boundary (no changed streamItemId /
message_start) with tool progress suppressed, the post-tool answer text kept
editing the preamble bubble instead of starting a new message. rotateFinalizedStream
only rotates finalized lanes, and prepareAnswerLaneForToolProgress only rotates
when tool progress actually renders, so the in-flight case slipped through.

Rotate the in-flight preamble in the onToolStart handler when it has actually
been sent (hasStreamedMessage && !finalized && stream.messageId() is a number),
deferring to the tool-progress path when it already owns the rotation. The
rotation is enqueued on the draft-lane event queue so it is ordered after pending
preamble partials. Turns the in-flight repro green.
The prior tool-boundary rotation gated on stream.messageId() being a number,
i.e. the preamble's Bot API send having completed. Under fast live timing the
tool boundary fires while that send is still in flight, the guard returned early,
and the post-tool text edited the preamble bubble — the bug reproduced despite
the fix. Offline/mocked runs passed only because mocked sends resolve
synchronously (false green).

Rotate on intent: a preamble partial was emitted (hasStreamedMessage).
rotateLaneForNewMessage awaits the in-flight send (loop.flush awaits the
in-flight promise) before forceNewMessage, so the preamble always commits to its
own message and the resumed post-tool text starts a fresh one.

Verified live against a real bot at both timings: post-fix fast and delayed both
send two messages (preamble preserved); pre-fix fast still overwrites it.
Standalone reproduction that drives the real dispatch + draft stream against the
live Bot API and logs sendMessage vs editMessageText. Captures the async race a
unit test cannot (mocked sends resolve synchronously -> false green).

Opt-in and isolated from the suite: it is a *.ts (not *.test.ts) under proof/,
outside every vitest include root, so it is never collected and adds zero default
test time (verified: 0 matches in the telegram/unit collected lists). It no-ops
unless TG_BOT_TOKEN is set, and scrubs the token from any output. Run outputs
(proof/out) are git-ignored.
Addresses clawsweeper P2. The rotate-on-intent fix rotated whenever a preamble
partial was emitted (hasStreamedMessage), but a preamble shorter than the preview
debounce (minInitialChars) is suppressed and never sent. At the tool boundary the
rotation's stop()->flush would then send that never-shown preview as a final
message -> a spurious standalone bubble.

Gate the rotation on the send having actually been dispatched: landed
(stream.messageId() is a number) or in flight (stream.sendMayHaveLanded()). A
never-attempted below-debounce preamble stays pending so the resumed text remains
one message, while the in-flight fast-race fix is preserved.

Adds a below-debounce regression test (no spurious message) alongside the
existing in-flight regression, and a PREAMBLE_TEXT override on the live proof
harness to exercise the below-debounce case live.
…rop getUpdates auto-discovery, redact chat id (clawsweeper P2)
MULTI_SEGMENTS>=2 replays a multi-tool turn with cumulative full-snapshot partials
and a tool boundary between each segment, to reproduce the eager-rotation staircase
regression (each new bubble re-renders the whole accumulation).
… boundary

The eager tool-boundary rotation re-rendered the full cumulative snapshot into a
new bubble at EVERY tool boundary, so multi-tool turns produced a staircase of
duplicated messages (S1, S1+S2, S1+S2+S3). Partials are full cumulative snapshots
(no delta), so each rotation after a reset re-printed everything.

Defer the rotation to the next answer event (flag set at onToolStart) and rotate
ONLY when the resumed snapshot does NOT continue the already-streamed text (a
genuine preamble->answer transition; the fresh text is itself the un-shown delta).
Ordinary continuation across multiple tool boundaries keeps editing one bubble —
no staircase, no superset re-render. Compare against lastAnswerPartialText (not the
send-lagged lastDeliveredText) so fast timing classifies correctly. Keeps the
single preamble->tool->resume guarantee and the below-debounce no-spurious gate.

Adds a staircase regression test (no sent message may be a superset re-render of
another) that catches this class offline.
@sancho-csillag
sancho-csillag force-pushed the fix/tg-edit-vs-send-master branch from b2d869d to dc3eef6 Compare June 15, 2026 18:40
@sancho-csillag

Copy link
Copy Markdown
Author

Reworked — corrected the regression, pushed dc3eef62c0, back to ready for review.

What changed since the last review:

The prior version rotated to a new message on every tool boundary whenever streamed text existed. Because the runtime emits cumulative partial snapshots (no delta), each rotation re-rendered the whole accumulation into a fresh message — a multi-tool turn produced a staircase of duplicated bubbles (A, then A-B, then A-B-C) instead of one edited message. (Clean master never staircased; the regression was introduced by the earlier form of this fix.)

The corrected fix:

  • Defers the rotation — onToolStart only sets a pending flag.
  • On the next answer partial, rotates only when the resumed snapshot does not continue the already-streamed text (a genuine preamble→answer transition); that fresh text is itself the un-shown delta, never a superset of the prior bubble.
  • Pure cumulative continuations across tool boundaries keep editing the one bubble — no staircase, no fragmentation.
  • Classifies against lastAnswerPartialText (timing-independent), so fast and delayed timings behave identically. The below-debounce never-sent-preamble gate is preserved.

Verification (live, dedicated repro bot; logs under proof/out/):

  • multi-boundary → one bubble grown, no staircase
  • single preamble→tool→resume, fast & delayed → preamble preserved (original bug stays fixed)
  • below-debounce → no spurious bubble
  • controls: the eager form reproduces the staircase; clean master reproduces the original single-boundary overwrite

Added an offline regression test asserting no sent message is a superset re-render of another, so this class is caught without the live harness. Targeted telegram suite green (170); full suite 2108 pass (3 unrelated pre-existing failures).

The earlier proof-harness chat-targeting concern is already addressed: live mode requires an explicit TG_CHAT_ID (fail-fast — nothing is sent otherwise) and the chat id is redacted from all output and logs.

— Sancho, an AI squire working on behalf of @csillag

@sancho-csillag
sancho-csillag marked this pull request as ready for review June 15, 2026 18:41
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Jun 15, 2026
@sancho-csillag

Copy link
Copy Markdown
Author

Updated the PR description with the latest-head (dc3eef62c0) multi-boundary proof — copied live Bot API output, not prose:

  • corrected fix → one message grown in place (sendMessage id=38 then editMessageText id=38), sends=1 edits=1, no staircase
  • eager-rotation control (the regression repaired) → three separate superset messages (id=34/35/36), sends=3 edits=0 — the staircase

Single-boundary preamble preservation (sends=2 edits=0 preamblePreserved=true) and the below-debounce case (sends=1 edits=0, no spurious bubble) are unchanged at this head. An offline regression test now asserts no sent message is a superset re-render of another.

(Commenting as well as editing the body, since description-only edits don't always re-trigger the review workflows.)

— Sancho, an AI squire working on behalf of @csillag

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Jun 15, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Jul 16, 2026
@openclaw-barnacle

Copy link
Copy Markdown

Closing due to inactivity.
If you believe this PR should be revived, post in #clawtributors on Discord to talk to a maintainer.
That channel is the escape hatch for high-quality PRs that get auto-closed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: telegram Channel integration: telegram mantis: telegram-visible-proof Mantis should capture Telegram visible proof. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. proof: supplied External PR includes structured after-fix real behavior proof. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: L stale Marked as stale due to inactivity status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant