Skip to content

fix(telegram): first DM message lands in root chat when the client creates the topic separately - #169444

Merged
obviyus merged 14 commits into
openclaw:mainfrom
aspalagin:fix/telegram-dm-topic-adopt-created
Nov 13, 2026
Merged

obviyus merged 14 commits into
openclaw:mainfrom
aspalagin:fix/telegram-dm-topic-adopt-created

Conversation

@aspalagin

@aspalagin aspalagin commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Closes #169443

What Problem This Solves

Fixes: the first message of a new private bot topic is answered in the main chat, and the new topic stays empty, when the Telegram client creates the topic and sends the message as two separate updates.

User Impact

User impact: a new private topic started from such a client (Telegram for Android, for example) gets its first reply, typing indicator, session and auto label inside that topic. Later messages sent to the main chat still stay in the main chat.

Why This Change Was Made

The bot receives forum_topic_created for the new topic, then the user's first message without message_thread_id. Nothing linked the two, so the message ran in the main DM session.

The receiving account's ingress monitor now links them once, at admission: a threadless private message from the same user, with a larger message id, within 3 seconds of a topic that user created, joins that topic. The decision is stored on the spooled update (adoptedDmThreadId), so the lane, authorization, session, delivery and restart replay all read the same topic. Bot-created topics, groups and channel direct-message topics are unchanged. Old spool rows without the field replay unchanged.

Accepted edge case: if Telegram itself drops the new topic (as during the 2026-11-09 Bot API incident), the reply fails loudly with "message thread not found" instead of silently landing in the main chat. That matches the existing rule not to retry topic sends without topic metadata.

Evidence

  • Live Telegram Test Server E2E, before and after, real Gateway + deterministic mock model, leased QA user, Threaded Mode on:
    • Scenario: the QA user creates a topic with TDLib createForumTopic, then ~200 ms later sends PING:adopt to the main chat (the exact two-update shape from [Bug]: Telegram threaded mode: first DM message lands in root chat when the client creates the topic separately #169443).
    • main at 8ebe740925ca: reply PONG:adopt arrived in the main chat; session agent:main:main. The new topic stayed empty.
    • This head cb3709c0e1f3: reply PONG:adopt arrived in the new topic (topicId=199227); model request session agent:main:main:thread:<user>:199227. Controls in the same run: a later main-chat message PING:rootlater was answered in the main chat (session agent:main:main), and PING:infresh sent inside the new topic was answered in that topic.
  • Focused tests: dm-topic-adopt, thread-spec, telegram-ingress-drain (admission, account isolation, failed-append redelivery, restart replay, legacy rows) and the native-pipeline inbound-handler cases. The restart-replay case fails without the durable restore.
  • The branch is merged with current main (conflicts with the widget-tap topic preparation from fix(telegram): route widgets in private topics #198022 resolved by keeping both payload fields).
  • Earlier production Bot API evidence from the author (topic sessions, requireTopic isolation, disabled-topic replay, upgrade from 2026.11.1) remains in the PR history.

@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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation channel: telegram Channel integration: telegram size: M labels Oct 11, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. 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 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 associates a threadless first private message with its sender’s newly created Telegram topic and preserves that route through replay.

Example: User 1001 creates topic 500, then sends message 501 without message_thread_id in the same second.

  • Before: The first turn and reply use the root DM.
  • After: The first turn and reply use topic 500; subsequent root messages remain in the root DM.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful and proven through the shipped Telegram path, with no blocking code findings and a small amount of redundant test coverage; failed QA remains an unresolved landing gate.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The reviewed-head Telegram Test Server run exercises the built Gateway’s adoption path with a real leased user, confirms the topic session and delivered reply, and includes root-chat and explicit-topic controls; earlier production Bot API traces additionally cover account isolation, typing, and disabled-topic replay.
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 client creates a private topic separately from its first message, leaving that topic empty while the first reply and session land in the root DM.
Reason: The demonstrated client flow violates the existing topic-routing contract, and the repair adds no user configuration or public API.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR repairs a current Telegram routing bug with no blocking code findings; the failed QA check still needs attribution before landing.

Priority: P2
Reviewed head: cb3709c0e1f316c93f6043dab7cf3c709ec2c539

Before merge

None.

Findings

None.

Tests

  • Low-value test extensions/telegram/src/dm-topic-adopt.test.ts: Remove the helper case beginning at line 40: native-topic arrival followed by service-update redelivery and a later root message is already covered through the real ingress monitor, with no distinct failure added here.
Agent review details

How this fits together

Telegram polling and webhook updates enter the account ingress monitor, which persists their conversation lane before dispatching them through authorization, session routing, and Telegram delivery.

flowchart LR
  A[Telegram updates] --> B[Account ingress monitor]
  B --> C[Durable spool and topic fact]
  C --> D[Thread resolver]
  D --> E[Topic authorization]
  E --> F[Agent session]
  F --> G[Telegram topic reply]
Loading

Technical review

Best possible solution:

Keep one account-owned adoption decision in ingress and carry its recorded topic through the existing spool, resolver, authorization, and delivery owners.

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

The supplied topic-creation update followed by a threadless message deterministically selects the root DM on current main, and the submitted live before/after run demonstrates the same failure through Telegram; this review ran no target code.

Is this the best way to solve the issue?

The repair uses the correct ingress owner, retains existing authorization and transport policy, and persists the association needed for replay rather than re-deriving it downstream.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 32527d0af043.

Provenance checked

  • Telegram topic resolution keeps the original intent (d7133e7: Preserve distinct channel Direct Messages destinations while bot-private and forum topics continue using message_thread_id.)
  • Durable ingress ownership keeps the original intent (f7786a1: Both transports durably enqueue before acknowledgment and delegate claim, replay, and retry ownership to the shared drain.)
  • Shared ingress monitor keeps the original intent (ee0e3a4: Centralize durable-ingress lifecycle while leaving Telegram-specific admission and transport policy local.)
  • Bot-private topic session eligibility keeps the original intent (aa117ec: Use Telegram’s has_topics_enabled capability as the source of truth for DM topic session splitting instead of configuration overrides.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit ee0e3a4 adds extensions/telegram/src/telegram-ingress-drain.ts:95 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: ee0e3a4d478e; files: extensions/telegram/src/telegram-ingress-drain.ts)

PR surface

Source +208, Tests +597, Docs +2, Other +2. Total +809 across 11 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 4 212 4 +208
Tests 5 602 5 +597
Docs 1 2 0 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 1 2 0 +2
Total 11 818 9 +809

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
Production versus test changes Production +212/-4; tests and support +602/-5 Production growth carries the missing association and durable replay fact; most test growth covers distinct restart, append-failure, account-isolation, and inbound-routing boundaries, with one redundant helper case noted.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Affected Telegram clients split a new conversation between the root DM and its topic; replies remain visible and no general channel outage is established.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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 execution lanes are retired.

History

Review history (12 earlier review cycles; latest 8 shown)
  • reviewed 2026-10-12T07:33:09.013Z sha 1aa3ad2479a3684bcb869907791cde4cc5daf555 :: needs real behavior proof before merge. :: [P3] Replace restart-test polling with owned completion signals
  • reviewed 2026-10-12T07:42:18.814Z sha 1aa3ad2479a3684bcb869907791cde4cc5daf555 :: needs real behavior proof before merge. :: [P2] Retire the service update when a native topic message clears adoption | [P3] Replace restart-test polling with owned completion signals
  • reviewed 2026-10-14T10:47:04.092Z sha acc470db13012b8ce2709b2969a765c5373bd269 :: needs real behavior proof before merge. :: [P2] Retire the service update when a native topic message clears adoption | [P3] Replace restart-test polling with owned completion signals
  • reviewed 2026-10-20T16:08:47.362Z sha 53a8af1 :: needs real behavior proof before merge. :: [P2] Register the adoption suite outside the sticker test
  • reviewed 2026-10-20T16:26:09.779Z sha 80225bd :: needs real behavior proof before merge. :: none
  • reviewed 2026-11-05T19:32:01.253Z sha 0ca9985 :: needs real behavior proof before merge. :: none
  • reviewed 2026-11-05T19:39:39.323Z sha 0ca9985 :: needs real behavior proof before merge. :: none
  • reviewed 2026-11-05T21:07:29.515Z sha 0ca9985 :: needs maintainer review before merge. :: none

Reviewed November 13, 2026, 5:32 AM ET / 10:32 UTC (Revision 13).

@aspalagin

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot removed merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. labels Oct 12, 2026
@aspalagin

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added the merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. label Oct 12, 2026
@aspalagin

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@aspalagin
aspalagin force-pushed the fix/telegram-dm-topic-adopt-created branch 2 times, most recently from acc470d to c7bdd28 Compare October 15, 2026 03:25
…s the topic separately

Some Telegram clients in threaded mode send a forum_topic_created service
message carrying the new message_thread_id and then deliver the user's
first message without any thread id. The resolver treated that message as
a root DM, so the reply went to the main chat and the new topic stayed
empty. Adopt a root message from the same user into the topic they created
within the last 3 seconds; bot-created topics and groups are untouched.
- drop the redundant boolean literal compare flagged by oxlint
- type the forum flag in the group-chat test fixture as the literal true
…nd persist it for replay

The first version kept the pending/adopted maps in module state shared by
every bot account of the process and re-derived the decision on every
resolver call, so a topic observed by one account could admit another
account's root message, the decision was lost on durable replay after a
restart (lane telegram:<chat> no longer matched the stored topic lane and
claim inspection rejected the row), and re-inspecting the consumed
forum_topic_created update rearmed the adoption window.

Decide once in the receiving account's ingress monitor at admission, record
the adopted thread on the message and in the spool payload
(adoptedDmThreadId), and restore it before lane inspection on replay. The
resolver only reads that fact.
… dm topic adopt

- document the two type assertions on spooled updates with SAFETY invariants
- return a frame outcome from every path of the restart-replay test dispatch
@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. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. labels Nov 5, 2026
@aspalagin

Copy link
Copy Markdown
Contributor Author

Upgrade proof for the remaining compatibility item from the review of 0ca9985: the latest stable release [email protected] from npm → this head on the same state directory, with existing settings, sessions and pending ingress rows intact. The PR body now has the section Upgrade from latest stable v2026.11.1 (npm) to this head; the earlier 2026.10.10 section is kept and marked as supplementary. Head unchanged (0ca998590e8ec657766553054037cb060debc856), no code changes.

Upgrade from latest stable v2026.11.1 (npm) to this head (2026-11-05)

Release side: the official npm package [email protected] (dist-tags.latest, https://registry.npmjs.org/openclaw/-/openclaw-2026.11.1.tgz, integrity sha512-2pSbt/taBKM/…VXptw==, openclaw --version → OpenClaw 2026.11.1 (4ffdd20)), installed with npm i [email protected] (npm 11.19.1, Node 24.22.2) on the same WSL2 Ubuntu 24.04 host. Candidate side: this head built from source (OpenClaw 2026.11.1 (0ca9985), dist/build-info.json commit 0ca998590e8ec657766553054037cb060debc856). One profile and one state directory for both binaries (--profile stand-169444-rel, fresh state created by the release's own onboard --non-interactive), Gateway on loopback, polling transport, the same two bot accounts as above (account a = @openclaw_stand_proof_c_7960_bot, account b = @openclaw_stand_proof_b_7973_bot); only one Gateway polled these bots at any time. Witness: the user's own Telegram account over MTProto (Telethon), as in the sections above. Redaction: user id → <user>, host/home paths → <host>/<home>, Gateway token and bot tokens removed.

Settings, sessions and pending rows written by v2026.11.1

  • Settings (release CLI: config patch + config set, validated): channels.telegram with account a and account b (dmPolicy: allowlist with one user, groupPolicy: disabled, tokenFile, account b with direct.<user>.requireTopic: true), logging (level: debug, file, consoleLevel: info), agents.defaults.model (LM Studio, local), agents.defaults.thinkingDefault: off, agents.defaults.heartbeat.every: "0m", tools.profile: minimal, gateway.port/bind/auth.mode. Snapshot taken with config get <key> --json per key.
  • Sessions (release Gateway, replies read back by the witness): root DM p3 rel root one (1936315) → ack: p3 rel root one (1936316, root, reply_to: None) in agent:stand:main (sessionId e4c4c4fe-…); a DM topic created by the client with the first message inside the topic (1936318 + 1936319, not an adoption) → ack: p3 rel topic one (1936320, reply_to_top_id = 1936318) in agent:stand:main:thread:<user>:1936318 (sessionId ace51559-…). sessions list (2 sessions), sessions.describe and chat.history (2 messages each) recorded through the release Gateway.
  • Pending ingress rows: the client sent a root message p3 rel pending root (1936332) and a message inside topic 1936318 (p3 rel pending topic, 1936333) back-to-back at 20:17:22Z. A watcher polling channel_ingress_events every 4 ms sent SIGSTOP + SIGKILL to the release Gateway as soon as both rows existed (no reply had been sent; the witness saw no typing and no bot message):
row status (written by v2026.11.1) lane payload keys message
0000000348475071 claimed by the killed release process (attempts: 0) telegram:<user> [receivedAt, update, updateId, version] bot message_id 45, message_thread_id: null
0000000348475072 pending telegram:<user>:topic:1936318 [receivedAt, update, updateId, version] bot message_id 46, message_thread_id: 1936318

Neither row carries adoptedDmThreadId (the release does not know the field).

Upgrade

  1. The candidate started on that state directory refuses to start before any channel work: OpenClaw agent database … uses schema version 27; stop active agents and run openclaw doctor --fix to upgrade it to schema version 40 before using it. Sessions remain unavailable. and agents.defaults: Unrecognized key: "heartbeat". Nothing is drained or sent (spool unchanged, witness silent). Both migrations come from main since the 2026.11.1 release branch point, not from this PR (its 11 files: Telegram extension sources and tests — dm-topic-adopt, ingress spool payload/drain, bot/helpers.ts, thread spec — plus one doc paragraph and one test-lines allocation file).
  2. openclaw --profile stand-169444-rel doctor --fix --non-interactive (candidate binary), exactly as the message says: Saved pre-migration SQLite backup for the agent and state databases, Upgraded agent database schema …: v27 -> v40, Retired heartbeat configuration after ordinary automation data was verified, Updated config (backup openclaw.json.bak); config validate → valid. The spool is not touched by the doctor (claimed 1, pending 1, completed 3 before and after).
  3. Candidate Gateway started on the migrated state: channels status → accounts a and b running/connected; health RPC ok: true, channels.telegram lifecycle ready, no error codes.
v2026.11.1 (before) this head after doctor --fix
channels.telegram (both accounts, allowlists, requireTopic, token files) config get --json, sha256 f3e5c6551b81… identical (f3e5c6551b81…, read by the head's CLI)
logging, agents.defaults.model, agents.defaults.thinkingDefault, tools.profile, gateway.port/bind/auth.mode, agents.list snapshot identical value for every key
agents.defaults.heartbeat.every: "0m" present retired by the doctor's heartbeat migration (main, not this PR); the key no longer exists in the head's schema
sessions (sessions list, sessions.describe, chat.history) agent:stand:main (e4c4c4fe-…), agent:stand:main:thread:<user>:1936318 (ace51559-…), 2 messages each same keys and session ids, read by the head (session-init store-load … session=agent:stand:main / …:thread:<user>:1936318); the replayed turns are appended to the release-written transcripts (chat.history 2 → 4 messages in each: the release's exchange followed by the replayed message and its reply)
pending row …071 (root, claimed by a dead process) not answered taken over from the dead release process and dispatched in agent:stand:main; typing top_msg_id: null; reply 1936355 ack: p3 rel pending root in the root chat (reply_to: None, 20:46:52Z); row completed (20:40:05.370Z, attempts: 0)
pending row …072 (topic 1936318, pending) not answered dispatched in agent:stand:main:thread:<user>:1936318; typing top_msg_id: 1936318; reply 1936356 ack: p3 rel pending topic in topic 1936318 (reply_to_top_id = 1936318, forum_topic = True, 20:52:28Z); row completed (20:40:05.427Z, attempts: 0)
rows without adoptedDmThreadId — both replayed in the lanes the release derived (telegram:<user>, telegram:<user>:topic:1936318); failed 0, no dead-letter, no invalid-event
new adoption on the upgraded state — topic 1936352 created with an implicit name + root message 1936353 sent 0.000 s later with reply_to: None → adopted root DM message into client-created topic {chatId: <user>, messageId: 48, threadId: 1936352, topicCreatedMessageId: 47, delaySec: 0}; rows …073/…074 in lane telegram:<user>:topic:1936352; session agent:stand:main:thread:<user>:1936352; typing top_msg_id: 1936352; reply 1936373 ack: p3 up adopt root in topic 1936352 (reply_to_top_id = 1936352, forum_topic = True, 20:58:06Z); chat.history of the new session: 2 messages
spool completed 3, claimed 1, pending 1 completed 7 (3 release rows, the 2 replayed rows, 2 adoption rows), failed 0

Run note (stand model, not the head): the stand answers with a local LM Studio model on a desktop GPU that was busy with another application during this run, so prompt processing ran at ~20 tokens/s. The first candidate start after the doctor (attempt 1) drained both rows the same way (rows completed, typing in the root chat and in topic 1936318, the release session ids reused) but the model call stalled; that Gateway was stopped before any reply was sent (witness: nothing delivered), and steps 2–3 were repeated from a byte copy (cp -a) of the state directory taken after the release was killed and before the candidate first touched it. The table above is that second run; the doctor output was the same (v27 -> v40, heartbeat retired, spool unchanged). Attempt-1 logs are kept with the rest of the raw material.

Raw material (release and candidate debug logs, console log, both doctor outputs, spool dumps before/after, config before/after, per-key config get snapshots, sessions list/sessions.describe/chat.history snapshots, watcher log, user-side JSON dumps, scripts) is kept by the author, redacted as above.

@aspalagin

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@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. 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. labels Nov 5, 2026
@obviyus

obviyus commented Nov 13, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 13, 2026
@obviyus
obviyus merged commit 90c620b into openclaw:main Nov 13, 2026
121 of 124 checks passed
@obviyus

obviyus commented Nov 13, 2026

Copy link
Copy Markdown
Collaborator

Merged via explicitly authorized admin squash with attributed pre-existing CI failures.

roboclaw-bot added a commit that referenced this pull request Nov 14, 2026
* fix(ci): keep unused dependency exports module-private

The check-dependencies job reported six unused exports. Keep the five
unclaimed implementation details private without changing their behavior;
PR #198306 by vincentkoc covers the separate release waiver table, which
remains untouched here.

QA_UX_STREAM_END_MARKER and TELEPORT_PT were introduced by #198293.
adoptTelegramDmTopicMessage and TELEGRAM_DM_TOPIC_ADOPT_WINDOW_SEC came
from #169444; migrate their direct tests to adoptTelegramDmTopicUpdate
and retain the explicit three-second accepted/four-second rejected window.
ChatModelRuntimeControl came from #192137 and keeps its local renderer.

Pinned formatting passes and independent P0-P2 review is clean. Named
tests could not collect without runtime dependencies; scoped lint could
not start with a wrapper import outside the requested sparse checkout.

Co-authored-by: obviyus <[email protected]>
Co-authored-by: steipete <[email protected]>

* fix(ci): unused exports fail the dependency check

Worked on by:
- @obviyus
- @steipete

Co-authored-by: obviyus <[email protected]>
Co-authored-by: steipete <[email protected]>
OpenClaw-Publication: 3bcacc77-7216-8f2e-9e43-4c1cf827724f

---------

Co-authored-by: obviyus <[email protected]>
Co-authored-by: steipete <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 14, 2026
…eates the topic separately (openclaw#169444)

* fix(telegram): first DM message lands in root chat when client creates the topic separately

Some Telegram clients in threaded mode send a forum_topic_created service
message carrying the new message_thread_id and then deliver the user's
first message without any thread id. The resolver treated that message as
a root DM, so the reply went to the main chat and the new topic stayed
empty. Adopt a root message from the same user into the topic they created
within the last 3 seconds; bot-created topics and groups are untouched.

* fix(telegram): satisfy lint and test typing in dm topic adopt

- drop the redundant boolean literal compare flagged by oxlint
- type the forum flag in the group-chat test fixture as the literal true

* fix(telegram): own DM topic adoption in the account ingress monitor and persist it for replay

The first version kept the pending/adopted maps in module state shared by
every bot account of the process and re-derived the decision on every
resolver call, so a topic observed by one account could admit another
account's root message, the decision was lost on durable replay after a
restart (lane telegram:<chat> no longer matched the stored topic lane and
claim inspection rejected the row), and re-inspecting the consumed
forum_topic_created update rearmed the adoption window.

Decide once in the receiving account's ingress monitor at admission, record
the adopted thread on the message and in the spool payload
(adoptedDmThreadId), and restore it before lane inspection on replay. The
resolver only reads that fact.

* fix(telegram): satisfy assertion-safety and consistent-return lint in dm topic adopt

- document the two type assertions on spooled updates with SAFETY invariants
- return a frame outcome from every path of the restart-replay test dispatch

* test(telegram): narrow per-account record keys in DM topic adoption test

check-test-types failed with TS2532 under noUncheckedIndexedAccess because
the per-account `lanes`/`resolved` records were typed with `string` keys.

* fix(telegram): carry the adopted DM topic through inbound message normalization

withResolvedTelegramForumFlag spreads a private message without chat.is_forum
into a copy before authorization, so a WeakMap keyed by the admitted message
object lost the adopted topic and the root message still routed to the root
session (or was dropped under requireTopic). Record the decision on the message
under a module-private symbol: spread copies keep it, JSON and structuredClone
drop it, and durable rows keep carrying it as explicit payload metadata.

Regressions run the two-update flow through the real account ingress monitor
and inbound handler (topic session and reply thread, requireTopic admit/drop),
cover legacy spool rows without adoptedDmThreadId, and pin the normalization
and serialization behaviour at the resolver boundary.

* test(telegram): pass the payload label to requireRecord in DM topic adoption test

* fix(telegram): keep the adopted DM topic for redelivery after a failed durable append

Admission consumed the pending topic before the spool append succeeded, so when
every append attempt failed and Telegram redelivered the root message as a
freshly parsed object, the retry no longer matched a pending topic and routed
to the root session (or was dropped under requireTopic). Record each decision
per account by chat:message_id as well, so the redelivered copy joins the same
topic; the per-account map is bounded like the others.

The ingress regression admits the service message, fails every append for the
root message, re-admits it as a new object and verifies the topic lane, the
persisted adoptedDmThreadId and the resolved thread. The helper-level
per-account case was dropped in favour of the two-account ingress test.

* fix(telegram): retire the service message once a native topic message clears adoption

When the client delivers the first message inside the topic, the pending
adoption was cleared but the service message stayed unspent, so a redelivered
forum_topic_created update rearmed the window and a later root message within
three seconds was adopted. Mark the cleared service message consumed through
the existing bounded map.

The restart replay regression now waits on owned signals (a dispatch-entered
promise and the owner's abort event) instead of polling, and releases its gate
and stops the monitor in finally. Helper-level cases duplicated by the ingress
and inbound-handler regressions were removed.

* test(telegram): adapt DM topic adoption ingress tests to the shared fixture and idle-claim admission

The ingress drain test file now hands withTempState a fixture object, and a
single durable admission on an idle drain appends through enqueueAndClaim.
The adoption tests take stateDir from the fixture and the append-failure
regression fails both append paths; scenarios and assertions are unchanged.

* test(telegram): move DM topic adoption inbound tests out of the sticker test

The rebase onto main placed the adoption describe block inside the sticker
regression after upstream dropped the file's outer describe, so the group
never registered. Declare it at file level and import describe again.

* test(telegram): allocate test lines for DM topic adoption coverage

---------

Co-authored-by: obviyus <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 14, 2026
* fix(ci): keep unused dependency exports module-private

The check-dependencies job reported six unused exports. Keep the five
unclaimed implementation details private without changing their behavior;
PR openclaw#198306 by vincentkoc covers the separate release waiver table, which
remains untouched here.

QA_UX_STREAM_END_MARKER and TELEPORT_PT were introduced by openclaw#198293.
adoptTelegramDmTopicMessage and TELEGRAM_DM_TOPIC_ADOPT_WINDOW_SEC came
from openclaw#169444; migrate their direct tests to adoptTelegramDmTopicUpdate
and retain the explicit three-second accepted/four-second rejected window.
ChatModelRuntimeControl came from openclaw#192137 and keeps its local renderer.

Pinned formatting passes and independent P0-P2 review is clean. Named
tests could not collect without runtime dependencies; scoped lint could
not start with a wrapper import outside the requested sparse checkout.

Co-authored-by: obviyus <[email protected]>
Co-authored-by: steipete <[email protected]>

* fix(ci): unused exports fail the dependency check

Worked on by:
- @obviyus
- @steipete

Co-authored-by: obviyus <[email protected]>
Co-authored-by: steipete <[email protected]>
OpenClaw-Publication: 3bcacc77-7216-8f2e-9e43-4c1cf827724f

---------

Co-authored-by: obviyus <[email protected]>
Co-authored-by: steipete <[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 P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L 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.

[Bug]: Telegram threaded mode: first DM message lands in root chat when the client creates the topic separately

2 participants