Skip to content

fix(telegram): avoid duplicate history replies for queued messages - #169019

Merged
obviyus merged 5 commits into
mainfrom
fix/telegram-queued-duplicate-mirror
Oct 11, 2026
Merged

obviyus merged 5 commits into
mainfrom
fix/telegram-queued-duplicate-mirror

Conversation

@obviyus

@obviyus obviyus commented Oct 11, 2026 •

Copy link
Copy Markdown
Collaborator

What Problem This Solves

Fixes duplicate assistant replies in chat.history when a second Telegram message arrives during a streamed answer.

User Impact

Each delivered answer appears once in history, including queued answers. Telegram delivery and the next model request are unchanged. No configuration or storage migration is required.

Why This Change Was Made

Delivery can settle after multiple answers have already been committed. Bind Telegram mirrors to their producing run rather than only the latest transcript message, and let history resolve an explicit source identity across intervening rows. Keep existing text, media, and source-isolation checks, idempotent delivery replay, and the legacy fallback for callers without a run identity.

Run-scoped lookups select only active-path events for the producing run before decoding message payloads, rather than materializing the whole transcript.

Discord and Slack use the shared dispatch ownership guard rather than Telegram's preview mirror path; their existing delivery behavior is unchanged.

Evidence

  • Real Telegram Test Server, partial streaming, second input sent only after observing the first preview: before, five assistant history rows for three delivered answers; after, three rows, one per answer.
  • The recorded follow-up provider assistant input is byte-for-byte equivalent before and after. Both runs showed one settled Telegram message per answer, and all run-owned messages were deleted and read back absent.
  • Regression tests fail on the original correlation and projection behavior; focused SDK, Gateway projection, and Telegram delivery tests pass after the fix. Includes repeated identical answers, an intervening run, wrong-run rejection, replay, and media guards.
  • Final candidate: 60 focused SDK, Gateway, SQLite lifecycle, and Telegram assertions pass; extension test typecheck and pnpm build pass.
  • Source-run records share the existing mirror-facts query; assertion-safety and database-worker ratchets pass without growing the SQL call count. Removed the obsolete assertion baseline entry after documenting the stored-event decode invariant.
  • Fact queries preserve the captured physical/logical target and forward only declared query fields. Existing worker target-binding regressions pass. Run provenance SQL is shared at the transcript-payload owner with existing history readers.
  • Extracted the existing mirror correlation helpers to keep the SDK runtime within its line cap. Complete local line/assertion/database-dialect/worker/import-cycle/Kysely/test-mock/timeout checks, core and extension types, focused regressions, and build pass before publication.
  • The built CLI SQLite sessions/transcripts lifecycle proof passes (1 case, 99.7 seconds; total 121.6 seconds). The earlier CI lifecycle failure returned an error despite a visible terminal answer; no cause is claimed from this passing local run.
  • Final real Telegram capture: delivered Bot API message IDs 80707, 80709, 80712; history contains exactly three assistant rows. All six run-owned raw input/output IDs were deleted and read back absent. Follow-up provider assistant messages exactly equal the pre-fix capture.

Merge danger: two-way door. Reverting restores the old correlation/projection behavior without a schema or config change. Blast radius: Telegram queued-answer history and Gateway presentation of explicitly correlated channel-final mirrors; the provider transcript and transport sends are unchanged.

@clawsweeper

clawsweeper Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@obviyus

obviyus commented Oct 11, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper review

@clawsweeper

clawsweeper Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation channel: telegram Channel integration: telegram gateway Gateway runtime plugin: file-transfer size: S labels Oct 11, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 11, 2026
@clawsweeper

clawsweeper Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR correlates Telegram delivery mirrors with their producing run so queued answers appear once in Gateway history.

Example: “The train leaves at noon.” is committed before a second answer, and its delivery mirror settles afterward.

  • Before: History displays the noon answer twice.
  • After: History retains the delivery record while displaying the noon answer once.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The repair is coherent, relevant boundary coverage exists, and prior blockers are resolved; independently inspectable runtime evidence remains limited.
Proof confidence 🦐 gold shrimp (3/6) The supplied maintainer-author classification exempts ordinary contributor proof; the reported queued-turn result has no inspectable trace, and the inspected historical images cover the earlier adjacent-mirror repair.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A Telegram answer can appear twice in Control UI history when another input arrives during streaming.
Reason: Restoring one displayed answer per correlated delivery has clear value, and the supplied maintainer-author classification establishes direction for the optional SDK extension.

Merge readiness

✅ Ready for maintainer review

This PR fixes a queued-history defect still present on main, and both prior review findings are resolved; no new actionable defect was found.

Priority: P2
Reviewed head: de8079bb4662cadd914efd162d5f1b44609ebb8e

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The reported queued Telegram capture and provider-input comparison lack inspectable artifacts; baseline regression failures are reported in the body rather than independently demonstrated here.
Agent review details

How this fits together

Telegram dispatch supplies run provenance to the existing transcript writer, and Gateway history consumes the writer-owned correlation for presentation.

flowchart LR
  A[Telegram input] --> B[Agent run]
  B --> C[Assistant transcript]
  B --> D[Telegram delivery]
  C --> E[Transcript mirror writer]
  D --> E
  E --> F[Gateway history projection]
  F --> G[Control UI history]
Loading

Technical review

Best possible solution:

Keep run correlation in the existing transcript writer and consume explicit source identities in the shared history projection.

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

Current-main source shows that intervening queued rows defeat latest-message correlation and adjacent-row suppression; no target code was executed during this read-only review.

Is this the best way to solve the issue?

The patch repairs correlation at its producer and presentation at the shared owner, preserving keyed replay, distinct repeated answers, media guards, and provider exclusion.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 48a348028fb0.

Provenance checked

  • Writer-owned mirror correlation changes intended behavior with a stated reason (1fb49c4: Retain both assistant and delivery records while correlating new mirrors and preserving strict replay conflicts.)
  • Adjacent-only history suppression changes intended behavior with a stated reason (fix(chat): stop duplicating a channel reply into two bubbles when it used reasoning #121871: Hide matching adjacent text mirrors while preserving distinct replies, media, forwarding, and fieldless history; this PR explains why queued settlement needs explicit source lookup.)
  • Worker-owned transcript facts keeps the original intent (a10773f: Keep transcript reads and mutations with existing worker owners, captured physical identity, current authority, FIFO settlement, and acknowledged publication.)
  • Telegram mirror construction keeps the original intent (3923174: Consolidate channel helpers while preserving wire and transcript shapes, admission, transport deadlines, cleanup, and lazy boundaries.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Aadi: Raw commit 1fb49c4 adds src/plugin-sdk/session-transcript-runtime.ts:364 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 1fb49c451023; files: src/plugin-sdk/session-transcript-runtime.ts)
  • Ayaan Zaidi: Raw commit f04aa55 adds src/plugin-sdk/session-transcript-runtime.ts:85 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: f04aa558115b; files: src/plugin-sdk/session-transcript-runtime.ts)

PR surface

Source +139, Tests +92, Docs +13, Other -1. Total +243 across 20 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 15 228 89 +139
Tests 3 94 2 +92
Docs 1 13 0 +13
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 2 -1
Total 20 336 93 +243

Labels

Label changes:

  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: Duplicate history entries cause limited user-facing confusion while Telegram delivery remains intact.
  • merge-risk: 🚨 compatibility: The public SDK gains optional sourceRunId behavior; supplied maintainer-author direction covers the extension, and callers without it retain the existing path.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Optionally link redacted queued-turn history and provider-input traces from the reported Telegram capture.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only; repair and merge need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

History

Review history (3 earlier review cycles)
  • reviewed 2026-10-11T08:48:37.763Z sha 63d86e9 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-11T09:12:26.204Z sha 10f32fb :: needs changes before merge. :: [P2] Extract mirror matching to satisfy the enforced SDK line cap
  • reviewed 2026-10-11T09:22:24.736Z sha f832e57 :: needs changes before merge. :: [P2] Extract mirror matching to satisfy the enforced SDK line cap | [P2] Use a justified Kysely primitive for the run-ID lookup

Reviewed October 11, 2026, 5:53 AM ET / 09:53 UTC (Revision 4).

@obviyus

obviyus commented Oct 11, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper review

@clawsweeper

clawsweeper Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus

obviyus commented Oct 11, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper review

@clawsweeper

clawsweeper Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. 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: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 11, 2026
@obviyus

obviyus commented Oct 11, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper review

@clawsweeper

clawsweeper Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus

obviyus commented Oct 11, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper review

@clawsweeper

clawsweeper Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 11, 2026
@obviyus

obviyus commented Oct 11, 2026

Copy link
Copy Markdown
Collaborator Author

Final head de8079b: build-artifacts, all typechecks, architecture and baseline ratchets pass. CI remains red only in checks-node-changed-extensions-bundle-2 (Codex steering/steering-settlement timeouts, missing receipt assertion, and database-resources-closing teardown cascade), plus aggregate ci-gate; cancelled jobs: 0. The same cases fail independently in https://github.com/openclaw/openclaw/actions/runs/38126796377/job/114432980545. This patch does not change those Codex tests or their steering lifecycle. Pausing for maintainer disposition; no rerun requested. Exact-head ClawSweeper reports zero findings. Final real Telegram capture has three history rows for three delivered answers, unchanged provider replay, and all run-owned messages deleted/read back absent.

@obviyus

obviyus commented Oct 11, 2026

Copy link
Copy Markdown
Collaborator Author

Maintainer override: the only red job is checks-node-changed-extensions-bundle-2 (Codex run-attempt.steering-settlement / run-attempt.steering: missing receipt, hook timeouts, then database-resources-closing). The same 6 tests fail identically on pure origin/main ac8a432 in 3 of 3 matched secretless Linux runs, and also 3 of 3 on this head; this PR does not change Codex steering. ci-gate is red only through that shard. ClawSweeper on this exact head reports zero findings.

@obviyus
obviyus merged commit 8e2a683 into main Oct 11, 2026
142 of 146 checks passed
@obviyus
obviyus deleted the fix/telegram-queued-duplicate-mirror branch October 11, 2026 10:44
@obviyus

obviyus commented Oct 11, 2026

Copy link
Copy Markdown
Collaborator Author

Landed in 8e2a683. Queued Telegram turns no longer duplicate answers in chat history.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 12, 2026
…penclaw#169019)

When a Telegram user sent a second message while the first answer was still streaming, chat.history showed both answers twice, although the user and the model each saw them once. Delivery mirrors were correlated only against the latest transcript message, so the queued order (answer A, queued user turn, answer B, mirror A, mirror B) broke correlation, and the history projection hid a mirror only when its source row was adjacent. Telegram now passes the producing run id with each mirror; the SDK mirror append matches the unused equivalent assistant occurrence within that run (falling back to the previous behavior without a run id), and the history projection resolves explicit source ids across intervening rows. Real Telegram Test Server proof: before, five assistant rows for three delivered answers; after, three rows, one per answer; provider replay unchanged.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Oct 12, 2026
Since #169019, the transcript mirror lookup by run id scanned and decoded events across the whole session history, because the JSON-extracted run id inside an OR kept SQLite off its index. Telegram delivery mirroring therefore got slower as a persistent session grew. The lookup now combines the indexed idempotency-key probe and a bounded run lookup with UNION ALL, filters by role in SQL before decoding bodies, and needs no schema change. The count of direct SQLite call sites stays at 605. Measured at 50k events: median 178.00 ms down to 4.39 ms, and run-metadata evaluations from 50,003 to 2,049, with the same row selected. Telegram Test Server proof with 50k historical events: the queued-turn scenario still stores one history row per delivered answer. Fixes #169643.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 13, 2026
…w#169663)

Since openclaw#169019, the transcript mirror lookup by run id scanned and decoded events across the whole session history, because the JSON-extracted run id inside an OR kept SQLite off its index. Telegram delivery mirroring therefore got slower as a persistent session grew. The lookup now combines the indexed idempotency-key probe and a bounded run lookup with UNION ALL, filters by role in SQL before decoding bodies, and needs no schema change. The count of direct SQLite call sites stays at 605. Measured at 50k events: median 178.00 ms down to 4.39 ms, and run-metadata evaluations from 50,003 to 2,049, with the same row selected. Telegram Test Server proof with 50k historical events: the queued-turn scenario still stores one history row per delivered answer. Fixes openclaw#169643.

Co-authored-by: Ayaan Zaidi <[email protected]>
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Oct 19, 2026
First-parent upstream 069a5b8..75df19c (17 commits, including
openclaw#169043 entry lifecycle queries, openclaw#169034, openclaw#169058 memory index facts,
openclaw#168950, openclaw#169019 telegram queued history replies, openclaw#168790/openclaw#168756/
openclaw#168759/openclaw#168739 Solid UI ports, openclaw#168813 codex metadata/startup
lifecycles, openclaw#168981, openclaw#168992 agent preparation SQLite work).

Only conflict: worker-access inventory, regenerated (631 files, 2436
calls). Auto-merged files carrying our overlay, reviewed: snapshot.ts
(upstream's block-reply reconcile reads through index-1; our per-part
continuation-marker strip in extractAssistantStreamSnapshot unchanged),
codex side-question.ts (upstream's request-scoped client lease; our
disableContinuationTools and the extracted dynamic-tool-call helper
unaffected), subagent-registry-restore.ts, session-sharing-store.native.ts.

Refs #1475

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: telegram Channel integration: telegram docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. plugin: file-transfer rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant