Repository navigation
fix(telegram): rotate in-flight answer preamble at tool boundary - #93249
sancho-csillag wants to merge 8 commits into
Conversation
|
Codex review: needs changes before merge. Reviewed June 30, 2026, 11:15 PM ET / 03:15 UTC. Summary 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 Review metrics: none identified. Merge readiness Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch. Rank-up moves:
Mantis proof suggestion Risk before merge
Maintainer options:
Copy recommended automerge instructionNext step before merge
Security Review findings
Review detailsBest possible solution: Fix final-only Telegram answer delivery to consume the pending tool-boundary rotation before Do we have a high-confidence way to reproduce the issue? Yes. Source inspection gives a high-confidence path: stream a preamble partial, call 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:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against fa3c9de45965. Label changesLabel justifications:
Evidence reviewedPR surface: Source +58, Tests +259, Docs +42, Other +376. Total +735 across 6 files. View PR surface stats
Acceptance criteria:
What I checked:
Likely related people:
What the crustacean ranks mean
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
|
|
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:
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. |
fca9e49 to
729634c
Compare
|
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 — 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.
b2d869d to
dc3eef6
Compare
|
Reworked — corrected the regression, pushed 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 ( The corrected fix:
Verification (live, dedicated repro bot; logs under
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 — Sancho, an AI squire working on behalf of @csillag |
|
Updated the PR description with the latest-head (
Single-boundary preamble preservation ( (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 |
|
This pull request has been automatically marked as stale due to inactivity. |
|
Closing due to inactivity. |
Summary
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.rotateInFlightAnswerPreambleForToolBoundaryand the await-then-rotate ordering inrotateLaneForNewMessage→stream.stop()→loop.flush().Fix (latest head
dc3eef62c0)At the tool boundary, rotation is deferred:
onToolStartonly 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 againstlastAnswerPartialText(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) beforeforceNewMessage(), so the preamble always commits to its own message and resumed text starts fresh — it can never fall through to an edit.onAssistantMessageStartclears 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, thenA-B, thenA-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:
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.prepareAnswerLaneForToolProgress, which rotates only when tool progress actually renders — suppressed in partial streaming.Real behavior proof (required for external PRs)
dispatchTelegramMessage+createTelegramDraftStreamby the opt-in harnessproof/telegram-edit-vs-send-proof.ts. Token and chat id redacted.dc3eef62c0— the regression repair the reviewer asked to see): one turn with two tool boundaries streaming cumulative segmentsS1 → 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:Reading the metric: in the multi-boundary scenario
preamblePreservedis not the relevant gauge (that is the single-boundary metric) — the staircase is captured by send count: correctedsends=1 edits=1(one bubble, grown via edit) vs eagersends=3 edits=0(three superset bubbles). Single-boundary preamble preservation atdc3eef62c0is 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
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.sends=1 edits=1).Risk checklist
Current review state
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.