Skip to content

feat(telegram): refine generated private topic names once - #183368

Open
dankarization wants to merge 64 commits into
openclaw:mainfrom
dankarization:feat/telegram-topic-refinement-20261025
Open

dankarization wants to merge 64 commits into
openclaw:mainfrom
dankarization:feat/telegram-topic-refinement-20261025

Conversation

@dankarization

@dankarization dankarization commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

Related: #174317 (landed as eb6a328b).

What Problem This Solves

Generated private Telegram topic names can stay tied to the opening message after a conversation settles on a more specific task. This is the separate Telegram follow-up to Peter's narrowed Dashboard implementation.

User Impact

With existing autoTopicLabel enabled, newly generated private topic names receive one refinement attempt after six follow-up task messages. Control-only, unknown, and disabled skill commands do not count. A failed attempt consumes the attempt and preserves the name. Observed manual topic names, manual session names, legacy topics without generated provenance, reset sessions, group forums, and channel Direct Messages remain protected.

Implementation and Scope

Telegram uses its existing account/metadata-owner-scoped topic cache, persists the countdown before inference, and rechecks the session and observed name before editing. It shares Dashboard task classification and the bounded 40-message/32 KB context reader. No transcript excerpts or database schema are added.

The SDK addition is two helpers and their state type through existing reply-dispatch-runtime: advanceConversationLabelRefinement and readConversationLabelRefinementSource. Neither writes state nor invokes a model. No new subpath, RPC, settings, or configurable threshold is introduced. Later automatic Telegram renaming and this narrow SDK surface still need a maintainer decision; landing Dashboard does not imply acceptance.

The branch integrates landed main 192947de, preserves contributor history, and leaves #174317's branch untouched. Remaining feature diff: 13 files, +390/-68, including the database-worker test registration. Current head: 1cd8d4e00a9815056e7ffdbbdbe03219468ff5ed.

Evidence

  • All 56 focused cases passed on the integrated runtime tree: 39 Dashboard, 13 Telegram metadata/cache, and four dispatch regressions.
  • Final fixture bytes pass all four cases in the database-worker lane, including sixth-task refinement, effective skill filtering, reopen persistence, manual rename during inference, session reset, and metadata-owner isolation.
  • Prior-head CI failure exposed missing host-broker admission for the new persistence test. The test now belongs to the existing database-worker lane; typed spies also resolve its unbound-method lint errors.
  • Core and Telegram package types, the exact extension test-type gate, targeted core/Telegram lint, formatting, and whitespace checks pass under Node 24.22.1.
  • Full supported-runtime build passed in 16m 32.6s, including CLI metadata, runtime postbuild, and all 160 SDK export checks. Subsequent commits change only test routing/fixtures. The transferred runtime declares build 421a0af; its production source is byte-identical to final head 1cd8d4e. UI asset diagnostics reported 100 B startup gzip and 76 B total CSS raw over budget while the build exited successfully.
  • Built Telegram import screening passes; Windows cannot qualify process-group closure, which remains an explicit screening limitation.
  • Original-dispatch red proof: at 8bc21e5, the sixth follow-up retains Topic label instead of Fix release signing. Disabled-skill countdown also has observed red/green proof.
  • Exact-head CI 40181000819 passed, including full test types and both extension bundles. All eight companion workflows also passed. Earlier runs exposed the repaired fixture issues and a repeated cron failure; the final run is green without rerunning or changing cron code.
  • Independent narrative review found no remaining actionable P0–P2 issue after the metadata-scope, bounded-read, skill-filter, and integration repairs.

Live Proof Still Pending

The existing HP QA source runtime has been refreshed to the published source, with its previous files/config preserved for recovery. Its established local model broker and QA bot are reachable. A full HP build refused the available memory before removing output. Supported narrow AI/package builds passed, but the source-Gateway route found stale old runtime bundles and a retained agent database requiring schema 31→34 migration. The Gateway/model smoke exited before inference. The passing Windows-built JavaScript artifacts were checksum-verified, extracted into the same stopped QA candidate, and verified to load on Linux as 2026.10.7 (421a0af). Previous runtime and state are preserved for recovery. The narrower session-import command reported zero targets and left schema 31 unchanged with quick_check=ok; broad Doctor repair awaits approval. The original QA configuration was restored byte-for-byte, and no candidate Gateway/poller or heavy HP build remains running.

No live Telegram refinement, model-flow verdict, latest-stable upgrade verdict, or screenshot is claimed yet. Telegram desktop interaction approval timed out before a QA message or deliverable screenshot; the required retained-database schema repair also awaits approval. Existing mocked transport/model tests and older proof packets do not replace that evidence. Current npm stable was verified as 2026.10.7.

No production deployment or merge is requested.

…ic names

Adds a bounded refinement pass after the initial automatic name in both
naming surfaces, off by default and always exactly once per session/topic:

- GUI/dashboard sessions: session.autoTitle.refine +
  session.autoTitle.refineAfterMessages (1-100, default 6). Runs after
  several later task messages, refines only generated titles, never
  explicit labels or manual names. Durable per-session state is bound to
  sessionId, so resets and stale async writers cannot cross-refine.
- Telegram DM topics: channels.telegram(.accounts).autoTopicLabel.refine
  + refineAfterMessages. Armed when the bot generates the initial topic
  label; later turns count toward the threshold, then the label is
  refined once via editForumTopic. A manual rename (live topic name no
  longer matches the generated label) permanently skips refinement;
  generation failure consumes the single attempt without retries.

Includes unit coverage for the state machine, config resolution and
clamping, exactly-once behavior, reset/stale guards, manual-rename
precedence, and failure handling; plus Telegram docs for the new keys.
…nerated dashboard names

Addresses Codex review findings on openclaw#174317:

- scheduleDmTopicLabel now routes non-first DM-topic turns through the
  refinement branch before the first-turn-only early return; previously
  the isFirstTurnInSession guard made the refinement path unreachable
  and the Telegram half of the feature a no-op.
- Dashboard refinement no longer relies on !hasExplicitSessionName for
  its writes: that predicate treats the generated displayName itself as
  explicit, which rejected every counter/rename write. Ownership of the
  generated value is now tracked in titleRefinement.generatedName;
  writes require the live displayName to still match the owned name,
  so later manual renames orphan the state and stop refinement, while
  refinementDone blocks any second run (exactly-once).
- Topic refinement: use the keyed-store lookup API (get does not exist),
  pass the dedicated refinement prompt to the label generator, and
  export that prompt; fixes unused-constant and type errors flagged by CI.
- Regenerate bundled channel config metadata for the new autoTopicLabel
  keys (check-bundled-channel-config-metadata CI failure).

Adds owning-entry-point regression tests: dashboard persistence of the
threshold counter under a generated name, threshold refinement write,
exactly-once stop, manual-rename precedence, reset/stale-writer guard,
and opt-out default.
…x CI attributable failures

Review findings resolved (Codex current-HEAD):
- 4297106986: DM manual rename observable via account-scoped live topic-name guard
- 4297106998: service authority revalidated (accountAbortSignal) before Bot API effect
- 4297107009: durable attempt claim persisted BEFORE external edit; outcome best-effort
- 4297107020: refinement store keyed by accountId:chatId:threadId (cross-bot isolation)
- 4297107032: per-DM boolean/enabled:false now disables refinement vs account default
- 4297107041: node-* autoLabel metadata no longer blocks refinement eligibility
- 4297107053: atomic increment+claim in one guarded patch before inference (threshold=1, concurrency)
- 4297107062: refinement uses utilityOnly mode (no random slug fallback on provider failure)
- 4297107072: initial-title turn skipped; control-only slash turns do not count

CI attribution (run 38933973068):
- prod-types/test-types/test-types-core-4/core-5/package-boundary: TS2322 string|null
  (topic-label-refinement.ts) — fixed via string|null declaration and claim-first flow
- docs + ratchets(config-docs): baseline regenerated via pnpm config:docs:gen
- ratchets(mock-exports): mock-isolation annotations added above vi.mock factories
- lint-core-4: no-param-reassign fixed in countTitleRefinementMessage
- lint max-lines: refinement extracted to dashboard-session-title-refinement.ts

Pre-existing, not attributable (verified identical at clean HEAD 6d1e1f8):
- chat-send-title-preparation settlement tests time out (2/7) with and without changes
…r-topic re-arm guard

Codex 20:12Z findings:
- 4298900014 (P1): claim patch now compares state.taskMessagesSinceTitle < afterMessages
  and persists the counter only below threshold; inference/claim happens at the
  configured threshold (default 6), not the first later turn.
- 4298900019 (P2): the validated triggering-turn source is appended to the
  refinement excerpt when the transcript has not published it yet.
- 4298900026 (P2): armTopicLabelRefinement preserves done entries — a completed
  refinement for a topic survives /reset or new-session re-arming (once-per-topic).

Regressions (owning entry points): below-threshold no-claim test (fail-before:
first turn consumed the attempt), triggering-source excerpt test, re-arm
preservation test. Refinement tests split to
dashboard-session-title-refinement.test.ts (max-lines ratchet).

Verification: tsgo core EXIT=0; oxlint changed files 0 errors; vitest 5 suites
66/66 pass.
…precedence, docs paths; concurrent-safe counting
…nement-20261016

# Conflicts:
#	src/cli/update-cli/update-command-service-maintenance-native.test-support.ts
…nement-20261016

# Conflicts:
#	docs/.generated/config-baseline.sha256
…heck service authority

- refinementKey prefixes the bot user id so token rotation cannot let a prior
  bot's unfinished entry drive a replacement bot's topic rename (4301074602)
- arm the refinement counter before the async first-turn label and attach the
  generated label afterwards, so a fast follow-up is counted (4300868452)
- retain intermediate user excerpts below the threshold and feed them to the
  refinement prompt instead of only the first/last message (4300799475)
- assert service authority before consuming the durable done claim so a stopped
  account does not spend its single attempt (4300799472)
- document exactly-once vs 2048-entry eviction semantics (4300868455)
- factor per-key enablement into a helper, removing the boolean literal
  comparison that failed check-lint-core-2 (no-unnecessary-boolean-literal-compare)
…16' into feat/chat-naming-refinement-20261016
…ings

- resolveAutoTopicLabelKeyEnabled takes the single autoTopicLabel type instead
  of a duplicated union constituent (no-duplicate-type-constituents, CI
  run39037128774 check-lint-core-2 job117409566464)
- topic-label-refinement.test.ts: optional-chained mock.calls accesses and the
  missing botId on the /reset re-arm call (check-test-types job117409566502)
… in worktree provenance

- resolveAutoTopicLabelConfig: a per-DM object without its own prompt now
  inherits the account-level prompt instead of falling back to the default
  (Codex 4302677497); enablement ladder unchanged
- dashboard-session-title.ts: worktree/dashboard title persistence initialises
  titleRefinement with skipNextMessage so the title-producing turn is not
  counted as the first later message (Codex 4302677494)
…nement-20261016

# Conflicts:
#	docs/.generated/config-baseline.counts.json
#	docs/.generated/config-baseline.sha256
…er inference

- Blank armed label (first turn still generating) no longer claims the
  single refinement attempt; claiming would spend it on a title that was
  never actually set (Codex 4302875130)
- After the awaited inference, re-read the live topic name and skip the
  rename when a human renamed during the wait; the pre-inference guard
  alone cannot cover the in-flight window (Codex 4303083920)
- Topic-name cache scope namespaced by account id at every caller
  (context ingestion, media mention policy, refinement guard, bot topic
  creation, editForumTopic action): two accounts on the same owner agent
  no longer share one cache namespace (Codex 4302875118)
- First-turn DM auto label is written into the cache and metadata
  ingestion extends to dm-scope topics, so the manual-rename guard can
  observe human renames of DM topics (Codex 4302875124)
- chat.send joiners of an in-flight title request did not persist the
  title, so their message counts toward refinement; sessionTitleRequests
  reports joiner-ness via markJoined (Codex 4303083912)
- topic-label-refinement test mock keeps the real account-scope helper
- 4304147104: one-time legacy bare-path namespace import in topic-name-cache
- 4304147107: preserve titleRefinement across same-session upserts
- 4304147108: defer pending-label refinement before the rename guard
- 4304147110: per-DM autoTopicLabel object takes precedence over account false
- 4304147111: attachment-only dashboard turns count toward refinement
- update bot-threads/outbound-adapter tests to account-scoped cache reads
- chat-send-background.test.ts: importOriginal spreads (mock-exports ratchet)
…nement-20261016

# Conflicts:
#	docs/.generated/config-baseline.counts.json
#	docs/.generated/config-baseline.sha256
@clawsweeper clawsweeper Bot added the status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. label Oct 25, 2026
@clawsweeper

clawsweeper Bot commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: stale review; fresh review needed.

Summary
The latest durable ClawSweeper review was for head 1f1ceb7adc66faa8ade9c2991e396ee19336db59, but the PR head is now 1cd8d4e00a9815056e7ffdbbdbe03219468ff5ed. Its old verdict and PR readiness labels are no longer current.

Next step
Comment @clawsweeper re-review when the current head is ready; pushes after the first review are not reviewed automatically.

Review history (1 earlier review cycle)
  • reviewed 2026-10-25T07:18:07.560Z sha 1f1ceb7 :: needs real behavior proof before merge. :: none

@dankarization
dankarization marked this pull request as ready for review October 25, 2026 08:35
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-25T08:39:49.852721Z
We couldn’t complete this review. Comment @codex review to try again.
3fcfa53 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@openclaw-barnacle openclaw-barnacle Bot added size: M and removed app: web-ui App: web-ui size: L labels Oct 25, 2026
@openclaw-barnacle openclaw-barnacle Bot added the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Oct 25, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Oct 25, 2026
@clawsweeper clawsweeper Bot removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 27, 2026

dankarization commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor Author

I'm coordinating this with #184821 and the Dashboard refinement originally merged in #174317. The full user-facing scenario is here: #184821 (comment)

A topic gets its first name from a real message. After six follow-up task messages, refinement can keep that name or improve it. Later, /reset clears the context while preserving the topic name. The first real message after reset should compare the new task with that existing name and keep it when the subject is the same.

For example, resetting “Email” and asking another mail question should preserve “Email,” rather than generating another opening-message title. The comparison should consider the current name, including one edited by hand; stale inference must not overwrite a later manual edit.

This PR currently excludes manual names and reset sessions, so that integration is not implemented by its current head. I'd like us to agree on one naming lifecycle across #183368 and #184821, sharing the existing command classification/provenance and preventing an old six-message countdown or in-flight result from crossing a reset. No naming update will be added to my Gateway candidate before that agreement.

Current-main history changes the integration plan: #185337 deliberately removed that Dashboard countdown and retired titleRefinement. We should discuss this against that policy before restoring the old implementation. My request is to preserve useful existing names by comparing them with the task, including after reset; the six-message refinement should be brought back only as part of that agreed lifecycle. A straight rebase of this older branch would silently undo the later decision.

obviyus added a commit that referenced this pull request Nov 11, 2026
…ds (#184821)

fix(telegram): name topics from the first real message, including after reset

Telegram topic naming in DM topics had two bugs. Control commands such as /model started the naming task, so a new topic or a topic after /reset was named from the command. And the background naming task ran inside the finished turn's async work scope, so naming from a real message failed with "Async work scope is closed"; on main a topic could only ever be named from a command. Control commands no longer trigger naming, the naming task starts with runInDetachedAsyncContext (already exported from openclaw/plugin-sdk/concurrency-runtime), and topicName survives /reset and session rollover. Comparing an old title with a new one after reset is left to #183368. No text changes.

Evidence: the Telegram Test Server through the userbot runner in a DM topic, a built Gateway in Docker with a mock provider, sending /model, a real message, /reset, /model and a real message, two runs each. On main the topic was named from /model as a new topic and again after /reset, and naming from the real messages failed with the scope error. With this change commands never triggered naming and the topic was named from the first real message, again after /reset. Plain DMs and /reset itself behave the same on both. The topic-label recovery regression and the reset and rollover topicName assertions fail on main, at -1 net test lines. Details: #184821 (comment).

Thanks @dankarization.

Co-authored-by: Ayaan Zaidi <[email protected]>
@dankarization

dankarization commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor Author

Follow-up proposal: #197334 brings the naming lifecycle together for Telegram private topics and Dashboard conversations.

The first ordinary message gives the conversation a title. After six more ordinary user messages, the utility model can refine it once; assistant replies and control commands do not count. After /reset, the first ordinary message compares with the existing title: keep it if it still fits, change it if the subject has moved on. This comparison would also apply to a title chosen manually.

This is a proposed policy and needs maintainer agreement, particularly for manual titles. Related work: #184821, #174317 and #183368.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 12, 2026
…ds (openclaw#184821)

fix(telegram): name topics from the first real message, including after reset

Telegram topic naming in DM topics had two bugs. Control commands such as /model started the naming task, so a new topic or a topic after /reset was named from the command. And the background naming task ran inside the finished turn's async work scope, so naming from a real message failed with "Async work scope is closed"; on main a topic could only ever be named from a command. Control commands no longer trigger naming, the naming task starts with runInDetachedAsyncContext (already exported from openclaw/plugin-sdk/concurrency-runtime), and topicName survives /reset and session rollover. Comparing an old title with a new one after reset is left to openclaw#183368. No text changes.

Evidence: the Telegram Test Server through the userbot runner in a DM topic, a built Gateway in Docker with a mock provider, sending /model, a real message, /reset, /model and a real message, two runs each. On main the topic was named from /model as a new topic and again after /reset, and naming from the real messages failed with the scope error. With this change commands never triggered naming and the topic was named from the first real message, again after /reset. Plain DMs and /reset itself behave the same on both. The topic-label recovery regression and the reset and rollover topicName assertions fail on main, at -1 net test lines. Details: openclaw#184821 (comment).

Thanks @dankarization.

Co-authored-by: Ayaan Zaidi <[email protected]>
@roboclaw-bot roboclaw-bot added the clawtributors PR from a clawtributor label Nov 13, 2026

This branch has not been deployed

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

Labels

channel: telegram Channel integration: telegram clawtributors PR from a clawtributor docs Improvements or additions to documentation gateway Gateway runtime P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. plugin: file-transfer size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants