Skip to content

fix(telegram): drop the markup on a retry only when it was rejected - #19014

Merged
iamwhatever merged 2 commits into
kirodotdev:mainfrom
javenciu:fix/telegram-resends-plain-only-on-rejected-markup
Oct 11, 2026
Merged

iamwhatever merged 2 commits into
kirodotdev:mainfrom
javenciu:fix/telegram-resends-plain-only-on-rejected-markup

Conversation

@javenciu

@javenciu javenciu commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Problem / Motivation

Goal: When a Telegram send with markup has to be retried, the retry drops the markup only if Telegram rejected the markup, so a message is never shown with its HTML tags as literal text.

TelegramClient.send_message re-sends once after a failed first send, and that re-send always dropped the parse_mode. The drop exists for one case, a send Telegram rejected for its markup ("so a parse failure never re-sends the literal tags"). But _api_request returns nothing for a timeout, a connection reset or a 5xx as well as for a rejected request. After a timeout or a reset the first message may already be in the chat, because Telegram processed the request and only its response was lost. The plain re-send then posted a copy with the markup shown as literal tags.

The tool-approval card (TelegramRenderer.on_prompt_choice) and Markdown command replies (_reply_markdown) send HTML with this fallback on. A lost response to an approval card put the card in the chat twice, the second time as raw HTML (🔐 Approve <code>bash</code>?).

Why it matters

A user on a slow or flaky network sees an approval request rendered as raw HTML, next to the card it duplicates, and has to work out which of the two to press. The fallback was firing on exactly the failures it was not written for.

Not a goal

  • The duplicate after a lost response stays, as a known limit. Telegram's Bot API offers no idempotency key for sendMessage, so a client cannot tell a send that landed from one that did not when the response is lost. The retry is kept on purpose: a missing approval card would be worse than a second one, because without a card the request is refused (the renderer's undelivered-prompt branch) and the user cannot approve the tool call. With this change the copy renders like the first card.
  • The number of sends is unchanged: one re-send after a failed first send, as before.
  • edit_message has the same fallback, but an edit applies to the one message it names, so it cannot post a copy. It is left as is.
  • The streaming renderer's sends are unchanged, and they keep their own fallback on purpose. They pass retry_plain=False, and when an HTML send or edit returns nothing, TelegramRenderer._seal_text and _seal_chunk_html send the same part once more as clean plain text (_strip_md), so a completed answer is "never silently lost" (telegram/renderer.py, _seal_text). The client does not report the error code to the renderer, so after a lost response that re-send carries the same duplicate limit stated above, in plain text. Applying this change's rule there needs the error code passed up to the renderer, which is a separate change.
  • Telegram's 429 handling in _api_request (one wait, then a retry) is unchanged.

What changed (motivation → approach → change)

  • Symptom: after a lost response (or a reset, a 5xx, a 403), the retry of a message sent with a parse_mode posts it without formatting, so its tags show as text.
  • Root cause: the fallback could not tell a rejected request from a send whose outcome is unknown, because _api_request returns None for both, and it dropped the markup in both cases.
  • Change, in src/kiro_crew/telegram/client.py, TelegramClient.send_message: the first _api call passes err_out, as send_rich_message already does. The single re-send drops parse_mode only when err_out reports error_code == 400: Telegram rejected the request, so nothing was posted. After any other failure (a timeout, a reset, a 5xx, a 429 after its own retry, a 403) the re-send keeps the original parse_mode. A copy of a message that landed then renders like the first, and a message that never landed still arrives.
  • The check keys on the error code, not the description text. The repository holds no copy of Telegram's parse-error description, and the same code-based split is how send_rich_message classifies its failures.
  • Callers see what they saw before: the re-send's message id, or None if it fails too. The approval card is refused only when both sends fail, as before.
  • Second commit, .github/coverage-baselines/backend.txt: this PR's tests bring src/kiro_crew/telegram/client.py to 83.4% in CI's Coverage Gate, over the 80% per-file floor, so its baseline row (61.8% when it was recorded) is deleted, as the gate requires of a file that graduates. No other line in the baseline changes.

Rejected alternative:

  • Not re-sending after an unknown outcome (return None at once): it removes the duplicate, but a card that never reached the chat would then be refused at once by the renderer's undelivered-prompt branch, so a network blip would deny a tool call.

Backwards compatibility

Compatible: only the retry of a send with a parse_mode whose first attempt failed for a reason other than a 400 behaves differently. It goes out with the original parse_mode instead of as plain text. A successful send, a 400 rejection (still re-sent as plain text), a retry_plain=False send and every send without a parse_mode are unchanged.

Removes nothing: no field, parameter or function is removed.

Tests

test/test_telegram.py, new class TestPlainRetryOnlyOnRejectedMarkup, next to TestLinkPreviewSuppression. It runs the real send_message and _api_request against a fake session that records every sendMessage the server receives.

  • test_a_retry_after_an_unknown_outcome_keeps_the_markup[response-lost], [connection-reset], [server-error], [forbidden]: the first request is received, then its response is lost (asyncio.TimeoutError), the connection resets (aiohttp.ServerDisconnectedError), or the server answers 500 or 403. Both sends carry parse_mode="HTML" and the re-send's id is returned.
  • test_a_rejected_markup_is_re_sent_once_as_plain_text (control): a 400 is followed by one plain send, with link previews disabled on both.
  • test_a_send_that_lands_is_sent_once (control).
  • test_a_caller_that_opts_out_is_never_re_sent (control): retry_plain=False with a 400 sends once.
  • test_the_approval_card_is_not_refused_after_a_lost_response (control): the real TelegramRenderer.on_prompt_choice over the real client; after a lost first response the card is re-sent and the approval is not refused.
  • Coverage, for the second commit: on the previous head, cd1500c, CI's Coverage Gate measured src/kiro_crew/telegram/client.py at 83.4% and failed with "1 baselined file(s) now meet the floor". Run alone with coverage, the eight test/test_telegram*.py files cover 613 of the file's 758 lines (80.9%) on main 7bb9d57 and 634 of 760 (83.4%) on this branch. Those local rates are not CI's full-suite rate; they show only that this PR's tests raise it. scripts/check_per_file_coverage.py --update-baseline, run on that CI run's own coverage-backend report, deletes this same row and nothing else, and the gate passes on that report with the result.

Red on main (7bb9d57; this branch's test/test_telegram.py copied into a detached checkout of it), pytest test/test_telegram.py -k "TestPlainRetryOnlyOnRejectedMarkup or TestLinkPreviewSuppression" -p no:cacheprovider -q -n 0: RC=1 in 3 of 3 runs, 4 failed, 7 passed (the four controls and the three preview tests):

FAILED ...::test_a_retry_after_an_unknown_outcome_keeps_the_markup[response-lost] - AssertionError: the retry shows the tags as text: ['HTML', None]
FAILED ...::test_a_retry_after_an_unknown_outcome_keeps_the_markup[connection-reset] - AssertionError: the retry shows the tags as text: ['HTML', None]
FAILED ...::test_a_retry_after_an_unknown_outcome_keeps_the_markup[server-error] - AssertionError: the retry shows the tags as text: ['HTML', None]
FAILED ...::test_a_retry_after_an_unknown_outcome_keeps_the_markup[forbidden] - AssertionError: the retry shows the tags as text: ['HTML', None]
=========== 4 failed, 7 passed, 496 deselected, 2 warnings in 3.90s ============

Green on this branch, rebased onto 7bb9d57, the same command, RC=0 in 3 of 3 runs:

================ 11 passed, 496 deselected, 2 warnings in 3.29s ================

Every test/test_telegram*.py file and the other test files that name retry_plain, _api_request or the Telegram client or renderer, 28 files run serially: 3956 passed, 6 skipped, exit 0. mypy src/kiro_crew/telegram/client.py: no issues. flake8, isort, black, scripts/check_black_formatting.py, scripts/check_comment_history.py (with COMMENT_HISTORY_BASE_REF=origin/main), scripts/check_harness_parity.py and scripts/docs-lint.sh pass.

Manual verification

N/A — unit coverage sufficient: the tests drive the real send_message, _api_request and approval renderer, with only the HTTP session faked, and record what the server receives.

Related Issues

Open PRs that change src/kiro_crew/telegram/client.py or test/test_telegram.py were listed with gh pr list --repo kirodotdev/KiroCrew --state open --limit 1000 --json number,files (668 open PRs; for those whose file list stops at 100, the rest were read page by page from gh api repos/kirodotdev/KiroCrew/pulls/<n>/files): #6595, #7626, #15111, #15273, #17582 and #18215, all on test/test_telegram.py. Each patch was checked with git apply --check (exact context) against main and against this branch, with the same result on both (#7626 already fails on main).
GitHub search (gh search issues and gh search prs --repo kirodotdev/KiroCrew, open and merged) for "telegram duplicate message timeout" and "telegram parse_mode retry plain" found nothing.

Pattern harvest

Rule candidate: review-prompt
Pattern: a fallback written for one failure ("the server rejected the markup") must check that it is handling that failure; a lost response and a rejection both read as "nothing came back", and only the rejection justifies changing what is sent.

Checklist

  • At most two commits (one is the norm), with a Conventional Commits title (feat|fix|docs|style|refactor|perf|test|chore|ci|build|revert: ...)
  • Existing tests pass and new tests added for new functionality
  • Self-review completed; code follows project style guidelines
  • Documentation updated (if applicable)
  • No secrets, credentials, or internal references in the diff

@javenciu
javenciu requested review from a team and KiroCrewCaptain as code owners October 11, 2026 02:27
@javenciu
javenciu requested a review from buluoray October 11, 2026 02:27
@github-actions github-actions Bot added fork Pull request from a fork (external contributor) readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running and removed readiness: action required A blocking check or review needs attention labels Oct 11, 2026
@github-actions

github-actions Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

First Principles Review (Opus 5.5, fork) — ✅ PASS

Premise-level review of b69d8b28487c96b79dfc035f3765e1788d7064e9 via the fork AI-review pipeline — why this exists and whether the shipped surface is the smallest honest version. Updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

First-Principles-Verdict: PASS

Check that CI's Coverage Gate on this head still measures telegram/client.py at 80% or more, because the baseline row for it is now deleted.

What this change ships

Inventory (2 items) — 2 justified

Intent: when a Telegram message with markup is retried, show it as plain text only when Telegram rejected the markup. Otherwise the duplicate sent after a lost response shows raw HTML tags as text. FIX.

  1. When the first send fails with a timeout, a connection reset, a 5xx or a 403, the re-sent message keeps its formatting. Only a 400 rejection still falls back to plain text. — justified
  2. The coverage-baseline exemption for src/kiro_crew/telegram/client.py is removed. — justified

[FIRST-PRINCIPLES-REVIEWED] b69d8b2

Description read

[DESCRIPTION-READ] 1e61784a041ff343678efbe115dbe5d1733d22b8e4464f130dcd1212aee853d5

That sha256 names the PR description this verdict read. Recompute it with .github/scripts/pr-description-capture.sh; if it differs, the description changed after this verdict was formed and any finding drawn from the description is unproven.

@github-actions

github-actions Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

UX Review (Opus 5.5, fork) — ⏭️ skipped

Revision b69d8b28487c96b79dfc035f3765e1788d7064e9 touches no user-facing surface (no changes under website/ or committed screenshots), so the UX review was skipped. Advisory — does not block merge.

@github-actions

github-actions Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Design Review (Opus 5.5, fork) — ✅ PASS

Design-level review of b69d8b28487c96b79dfc035f3765e1788d7064e9 via the fork AI-review pipeline — updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

Design-Verdict: PASS

Nothing to check.

[DESIGN-REVIEWED] b69d8b2

Description read

[DESCRIPTION-READ] 5b14c3bb51b3c3114b17409793b05254fb2257aee97c1bacb6020f56b3d19e52

That sha256 names everything this verdict read: the PR description, plus the 1 evidence file(s) the workflow collected from it and handed this review. It covers that evidence because the media strip replaces every attachment URL with the same placeholder, so an edit swapping one attachment for another would leave the description's captured text identical while what this review judged changed. Recompute it with .github/scripts/pr-description-capture.sh over the same inputs; if it differs, the description or that evidence changed after this verdict was formed and any finding drawn from either is unproven.

@github-actions

github-actions Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

GPT 6.1 Review (fork) — ✅ no blocking findings

Reviewed b69d8b28487c96b79dfc035f3765e1788d7064e9 via the fork AI-review pipeline; updated in place on each push.

Review details

No findings.
[GPT-REVIEWED] b69d8b2

@github-actions

github-actions Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Opus 5.5 Review (fork) — ✅ no blocking findings

Reviewed b69d8b28487c96b79dfc035f3765e1788d7064e9 via the fork AI-review pipeline; updated in place on each push.

Review details

FINDING (advisory, does not block): a send that fails twice can now lose a message the old code would have delivered.

FINDING — src/kiro_crew/telegram/client.py:39 — if err.get("error_code") == 400: only ever looks at the first attempt's error, and the retry is sent without err_out. So when an HTML send first fails on the network (timeout or connection reset, where _api_request returns None and leaves err empty) and the markup is also bad, the retry keeps parse_mode. Telegram then rejects it with a 400 and send_message returns None. Before this change, that retry went out as plain text and arrived. This hits _reply_markdown command replies, which are converted from markdown by md_to_telegram_html_safe. → Fix: pass err_out to the retry too. If the retry kept parse_mode and comes back 400, send one last time as plain text.

[OPUS-REVIEWED] b69d8b2

@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention and removed readiness: checking Automated validation is still running labels Oct 11, 2026
@javenciu
javenciu force-pushed the fix/telegram-resends-plain-only-on-rejected-markup branch from 75e8183 to cd1500c Compare October 11, 2026 11:29
@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Oct 11, 2026
TelegramClient.send_message re-sends once after a failed first send,
and that re-send always dropped the parse_mode. The drop is meant for a
send Telegram rejected for its markup. _api_request returns nothing for
a timeout, a connection reset or a 5xx as well, and after those the
first message may already be in the chat. The plain re-send then posted
a copy with the markup shown as literal tags. The tool-approval card
sends this way, so a lost response put the card in the chat twice, the
second time as raw HTML.

send_message asks _api_request for the failure (err_out, as
send_rich_message already does). After a 400, Telegram rejected the
request and nothing was posted, so the re-send drops the parse_mode as
before. After any other failure the re-send keeps it. The number of
sends is unchanged: one re-send after a failed first send. Telegram has
no idempotency key, so a lost response can still produce a second copy,
which renders like the first; a card that never landed still arrives
instead of the approval being refused.
@javenciu
javenciu force-pushed the fix/telegram-resends-plain-only-on-rejected-markup branch from cd1500c to b69d8b2 Compare October 11, 2026 13:19
@github-actions github-actions Bot added readiness: passed Eligible automated validation passed for the current revision and removed readiness: action required A blocking check or review needs attention labels Oct 11, 2026

@iamwhatever iamwhatever left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This makes TelegramClient.send_message drop parse_mode on its one retry only when Telegram answered 400, so a retry after a lost response (timeout, reset, 5xx) no longer posts a copy of an approval card with its HTML shown as literal tags, and that is the root cause: _api returns None for both a rejection and an unknown outcome, and the old code treated them the same. I read _api_request on the head: err_out is filled only on a Telegram-level error answer, so a transport exception leaves it empty and the retry keeps HTML, a 429 that is still limited after its one back-off keeps HTML, and a 400 (bad markup, too long, chat not found) still retries as plain text exactly as before. The number of sends is unchanged, retry_plain=False callers still never retry, and the streaming renderer is untouched. The parametrized tests (timeout, connection reset, 500, 403) assert the retry keeps HTML and would fail on base, which always popped parse_mode; the 400, single-send, opt-out and approval-card cases pin the rest. All checks are green and both review lanes report no findings, so it is safe to merge. — crew-pr-reviewer (deep re-check)

@iamwhatever
iamwhatever enabled auto-merge (squash) October 11, 2026 17:34
@iamwhatever
iamwhatever merged commit febbcdd into kirodotdev:main Oct 11, 2026
104 checks passed
@github-actions github-actions Bot removed the readiness: passed Eligible automated validation passed for the current revision label Oct 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

fork Pull request from a fork (external contributor)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants