Skip to content

Telegram message_tool_only replies bypass normal reply decorator, so /usage footer is not shown #87392

Closed

Description

@fionn77

Summary

On 2026.5.26 (10ad3aa), /usage tokens / /usage full can be persisted for a Telegram session and model usage is recorded, but Telegram replies sent through the message tool path do not show the usage footer.

This appears to happen because Telegram message_tool_only source replies bypass the normal internal source-reply/final-payload path where responseUsage is appended. The same path is only used for webchat today.

Environment

  • OpenClaw: 2026.5.26 (10ad3aa)
  • Install: npm global under ~/.local/lib/node_modules/openclaw
  • Runtime: gateway systemd user service
  • Channel: Telegram DM
  • Session key: agent:main:telegram:direct:<telegram-user-id>
  • Session setting observed: responseUsage: "tokens"
  • Recent session usage observed: nonzero inputTokens / outputTokens

Expected behavior

After running /usage tokens or /usage full, Telegram agent replies should include the usage footer, e.g.

Usage: 404 in / 8 out

or the full footer with session information when full is selected.

Actual behavior

Telegram visible replies are delivered, but no usage footer is appended. The session store shows that the usage setting is saved and usage metadata exists, so this is not a command persistence issue.

Source-level findings

1. Telegram source replies do not use the internal source-reply sink

In the built package, message-action-runner-kdd1czMt.js has:

function shouldUseInternalSourceReplySink(input, params) {
  return input.action === "send" &&
    input.sourceReplyDeliveryMode === "message_tool_only" &&
    normalizeOptionalLowercaseString(input.toolContext?.currentChannelProvider) === "webchat" &&
    Boolean(input.sessionKey?.trim()) &&
    !hasExplicitRouteParam(params);
}

Because this is gated to webchat, Telegram current-source replies in message_tool_only mode fall through to the normal channel message action instead of becoming an internal source reply payload.

Local dry-run probe:

import { n as runMessageAction } from './dist/message-action-runner-kdd1czMt.js';

await runMessageAction({
  cfg: { tools: { message: { actions: { send: true } } } },
  action: 'send',
  params: { message: 'OK', dryRun: true },
  toolContext: { currentChannelProvider: 'webchat', currentChannelId: 'source-chat' },
  sourceReplyDeliveryMode: 'message_tool_only',
  sessionKey: 'agent:main:telegram:direct:8223071058',
  agentId: 'main',
  dryRun: true
});
// => handledBy: internal-source

await runMessageAction({
  cfg: { tools: { message: { actions: { send: true } } } },
  action: 'send',
  params: { message: 'OK', dryRun: true },
  toolContext: { currentChannelProvider: 'telegram', currentChannelId: 'source-chat' },
  sourceReplyDeliveryMode: 'message_tool_only',
  sessionKey: 'agent:main:telegram:direct:8223071058',
  agentId: 'main',
  dryRun: true
});
// => falls through into Telegram target resolution instead of internal-source

The second call failed locally with Unknown target "source-chat" for Telegram, which is useful evidence that Telegram did not take the internal source-reply sink path. In a real Telegram turn, the current channel id is resolvable, so the reply can still be sent, but it is sent before the normal reply decorator can append usage.

2. The usage footer is appended only in the normal final payload path

In agent-runner.runtime-BWGj8NfM.js:

const responseUsageMode = resolveResponseUsageMode(
  activeSessionEntry?.responseUsage ??
  (sessionKey ? activeSessionStore?.[sessionKey]?.responseUsage : void 0)
);
if (responseUsageMode !== "off" && hasNonzeroUsage(usage) && !preserveUserFacingSessionState) {
  // builds responseUsageLine
}
...
if (responseUsageLine) finalPayloads = appendUsageLine(finalPayloads, responseUsageLine);

So if the visible Telegram reply is delivered directly by message(action=send), the footer is not appended to that already-sent visible message.

3. Potential secondary issue: footer append replaces payload object

appendUsageLine currently creates a replacement object:

const next = {
  ...existing,
  text: `${existingText}${separator}${line}`
};

If the source reply has WeakMap metadata such as deliverDespiteSourceReplySuppression or sourceReplyTranscriptMirror, replacing the object without copying metadata can drop the metadata needed by message_tool_only delivery. This may matter if Telegram source replies are routed back through the internal sink.

Suggested fix direction

For message_tool_only turns, default current-source replies from any channel with current source context should probably use the internal source-reply sink, not only webchat, while preserving explicit-target sends as direct channel sends.

A narrow shape would be:

  • In shouldUseInternalSourceReplySink, replace the currentChannelProvider === "webchat" condition with a check for current source context (currentChannelProvider, currentChannelId, currentThreadTs, or currentMessageId).
  • Keep !hasExplicitRouteParam(params) so explicit target / to / channel sends still go through normal message delivery.
  • In appendUsageLine, preserve reply payload metadata when replacing the payload object, e.g. via copyReplyPayloadMetadata(existing, next).

Impact

/usage appears to work from the command reply and session state, but users on Telegram do not see the configured usage footer for Codex/OpenClaw bridge replies. This makes the command misleading and removes the intended per-reply token/cost visibility.

Activity

  1. WarrenJones commented on May 27, 2026

    @WarrenJones
  2. clawsweeper commented on May 27, 2026

    @clawsweeper
    Contributor

    Codex review: keeping this open for maintainer follow-up; there is still a little grit to resolve. Reviewed May 27, 2026, 3:46 PM ET / 19:46 UTC.

    Summary
    Keep open: current main and the latest release still have the webchat-only internal source-reply gate, while the documented /usage behavior promises a per-response footer. The report is narrow, source-backed, and not superseded by the related issues in the provided context.

    Reproducibility: yes. Source inspection gives a high-confidence path: a Telegram message_tool_only send with no explicit route does not satisfy the webchat-only internal sink condition, so it can be delivered before appendUsageLine decorates final payloads; I did not run a live Telegram probe in this read-only pass.

    Next step
    The bug is narrow and source-reproducible with clear implementation and test files; the provided context has a contributor offer to investigate but no linked fix PR.

    Review details

    Best possible solution:

    Route implicit current-source message_tool_only sends for Telegram and other channels through the internal source-reply payload path, preserve explicit target sends as normal outbound delivery, copy reply payload metadata when appending usage, and cover Telegram DM/topic plus explicit-route exceptions in tests.

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

    Yes. Source inspection gives a high-confidence path: a Telegram message_tool_only send with no explicit route does not satisfy the webchat-only internal sink condition, so it can be delivered before appendUsageLine decorates final payloads; I did not run a live Telegram probe in this read-only pass.

    Is this the best way to solve the issue?

    Yes. The narrow maintainable direction is to generalize the implicit current-source sink beyond webchat, keep explicit-route sends on the outbound path, and preserve reply payload metadata when appending the usage footer.

    AGENTS.md: found and applied where relevant.

    Remaining risk / open question:

    • No live Telegram probe was run in this read-only review; the reproduction is source-level plus the reporter's shipped-release dry-run evidence.
    • A fix must preserve explicit message.send targets and Telegram topic routing, because maintainer notes treat wrong-surface Telegram delivery as worse than a loud failure.

    Codex review notes: model gpt-5.5, reasoning high; reviewed against b789e71e57d9.

    Label changes

    Label changes:

    • add P2: This is a confirmed, limited-blast-radius Telegram reply formatting bug in an existing documented /usage feature.
    • add impact:message-loss: The visible Telegram reply is delivered without the configured usage footer, so part of the expected user-visible message content is suppressed.
    • add impact:session-state: The issue is specifically about persisted per-session responseUsage state not affecting the Telegram message-tool delivery path.
    • add issue-rating: 🦞 diamond lobster: Current issue advisory state selects this label.
    • add clawsweeper:source-repro: Current issue advisory state selects this label.
    • add clawsweeper:queueable-fix: Current issue advisory state selects this label.
    • add clawsweeper:fix-shape-clear: Current issue advisory state selects this label.

    Label justifications:

    • P2: This is a confirmed, limited-blast-radius Telegram reply formatting bug in an existing documented /usage feature.
    • impact:message-loss: The visible Telegram reply is delivered without the configured usage footer, so part of the expected user-visible message content is suppressed.
    • impact:session-state: The issue is specifically about persisted per-session responseUsage state not affecting the Telegram message-tool delivery path.
    Evidence reviewed

    Acceptance criteria:

    • node scripts/run-vitest.mjs src/infra/outbound/message-action-runner.send-validation.test.ts
    • node scripts/run-vitest.mjs src/auto-reply/reply/agent-runner.misc.runreplyagent.test.ts
    • node scripts/run-vitest.mjs src/agents/embedded-agent-runner/run/payloads.test.ts

    What I checked:

    • Current source keeps internal source replies webchat-only: shouldUseInternalSourceReplySink requires currentChannelProvider to normalize to the internal webchat channel, so Telegram message_tool_only sends with no explicit route do not use handledBy: internal-source. (src/infra/outbound/message-action-runner.ts:546, b789e71e57d9)
    • Usage footer is appended after final payload assembly: runReplyAgent resolves responseUsage from session state and appends the formatted usage line to finalPayloads, which does not affect a visible message already sent directly through the normal message tool channel path. (src/auto-reply/reply/agent-runner.ts:1883, b789e71e57d9)
    • Metadata is not copied when appending usage: appendUsageLine replaces the selected payload object with a spread copy and updated text, but it does not call copyReplyPayloadMetadata, so source-reply metadata can be lost when this path starts handling message-tool source replies. (src/auto-reply/reply/agent-runner-usage-line.ts:54, b789e71e57d9)
    • Docs define the expected /usage behavior: The token-use docs say /usage off|tokens|full appends a per-response usage footer to every reply and persists per session as responseUsage. Public docs: docs/reference/token-use.md. (docs/reference/token-use.md:76, b789e71e57d9)
    • Latest shipped release has the same gate: The v2026.5.26 tag points at 10ad3aa16068baa84a1bd9ac4f7d42ae725cedb7, and the tagged message-action-runner.ts keeps the same webchat-only source-reply condition. (src/infra/outbound/message-action-runner.ts:546, 10ad3aa16068)
    • History points to the current reply/action surface owners: Blame on the current source-reply gate and usage append block maps to 11dfef201f81a0cdbcf5688962036a704e1c0615; usage reporting itself traces through 151523f47b9b0ef9e2d63cbcdcc6621d91b60dfc and the helper split through 3392558b42ab48cc219e9ae47bdb24b4d8fc11ac. (src/infra/outbound/message-action-runner.ts:546, 11dfef201f81)

    Likely related people:

    • @vincentkoc: Current blame for shouldUseInternalSourceReplySink, responseUsage resolution, and appendUsageLine in this checkout points to commit 11dfef201f81a0cdbcf5688962036a704e1c0615, and 3392558b42ab48cc219e9ae47bdb24b4d8fc11ac split the usage-line helper. (role: recent area contributor; confidence: high; commits: 11dfef201f81, 3392558b42ab; files: src/infra/outbound/message-action-runner.ts, src/auto-reply/reply/agent-runner.ts, src/auto-reply/reply/agent-runner-usage-line.ts)
    • @steipete: git log -S appendUsageLine traces usage cost reporting to 151523f47b9b0ef9e2d63cbcdcc6621d91b60dfc, and bb46b79d3c1479f194a90afcf3dd69a1858a7898 recently refactored the OpenClaw agent runtime surface. (role: feature-history contributor; confidence: medium; commits: 151523f47b9b, bb46b79d3c14; files: src/auto-reply/reply/agent-runner.ts, src/auto-reply/reply/agent-runner-usage-line.ts)
    • @Takhoffman: Commit 4360a59c6d3f705ae86aebf6fefa19d3de595b20 changed /usage session-entry behavior and tests, which is adjacent to the persisted responseUsage side of this bug. (role: related usage-session contributor; confidence: medium; commits: 4360a59c6d3f; files: src/auto-reply/reply/commands-session.ts, src/auto-reply/reply/commands-session-usage.test.ts)
    How this review workflow works
    • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
    • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
    • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
    • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
    • Maintainers can also comment @clawsweeper review to request a fresh review only.
    • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
    • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
    • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.
  3. added
    P2Normal backlog priority with limited blast radius.
    impact:message-lossChannel message delivery can be lost, duplicated, or misrouted.
    impact:session-stateSession, memory, transcript, context, or agent state can drift or corrupt.
    issue-rating: 🦞 diamond lobsterVery strong issue quality with high-confidence source-level or clear reproduction.
    clawsweeper:source-reproClawSweeper found a high-confidence source-level issue reproduction.
    clawsweeper:queueable-fixClawSweeper marked this issue as an existing queue_fix_pr work candidate.
    clawsweeper:fix-shape-clearClawSweeper found a clear likely implementation shape for this issue.
    on May 27, 2026
  4. steipete commented on May 31, 2026

    @steipete
    Contributor

    Fixed on main by 8f941ea0acb.

    The fix routes implicit non-webchat message_tool_only current-source sends through the internal source-reply sink, so Telegram tool-only replies stay on the final source-reply payload path where /usage decoration runs. It also preserves reply payload metadata while appending usage text, so the transcript mirror stores the footer-bearing reply.

    Proof:

    Closing as fixed.

  5. locked as resolved and limited conversation to collaborators on Jun 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P2Normal backlog priority with limited blast radius.clawsweeper:fix-shape-clearClawSweeper found a clear likely implementation shape for this issue.clawsweeper:queueable-fixClawSweeper marked this issue as an existing queue_fix_pr work candidate.clawsweeper:source-reproClawSweeper found a high-confidence source-level issue reproduction.impact:message-lossChannel message delivery can be lost, duplicated, or misrouted.impact:session-stateSession, memory, transcript, context, or agent state can drift or corrupt.issue-rating: 🦞 diamond lobsterVery strong issue quality with high-confidence source-level or clear reproduction.

    Type

    No type

    Fields

    Priority

    None yet

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions