Skip to content

fix: record an announced send in the chat it reached - #208169

Merged
obviyus merged 1 commit into
mainfrom
fix/visible-send-one-destination
Nov 29, 2026
Merged

obviyus merged 1 commit into
mainfrom
fix/visible-send-one-destination

Conversation

@obviyus

@obviyus obviyus commented Nov 29, 2026

Copy link
Copy Markdown
Collaborator

Follows #208049 and #208130.

What Problem This Solves

When an isolated agent run (for example gateway call agent with channel/to set, a cron announce or a recovery send) delivers a message to a chat, the user sees the message but the chat's own conversation does not record it. When the user replies, the agent in that chat does not know what it just sent.

Cause: the request's channel/to routing hint is stored on the isolated session as its delivery route. The conversation registry derives an address binding from every session's delivery route, so the chat address then has two current sessions: the chat's own (inbound) session and the isolated one. commitConfirmedVisibleMessage (src/sessions/confirmed-visible-message.ts) asks the registry which conversation owns the address, gets two, and skips with "Conversation context skipped: multiple current destinations match." Sends that carry their own route (plugin receipts) were not affected; announce, gateway send and recovery sends were. #208130's E2E saw this skip.

User Impact

A message delivered to a chat from an isolated run now lands once in that chat's conversation, so the chat's agent can see and quote it on the next turn. No config, schema, stored-row, protocol or SDK change.

Why This Change Was Made

The registry's address lookup answers "which conversation does inbound for this address use?". Only chat sessions can answer that. Inbound (initSessionState) and exact outbound route binding (bindOutboundSessionEntry) always record the session's chat type; a request hint records only a delivery address. The lookup (resolveCurrentConversationByDelivery, its only caller is the confirmed-send commit) now ignores sessions without a recorded chat type: s.chat_type IS NOT NULL in the SQLite reader (session_windows.chat_type already exists) and entry.chatType in the memory reader.

  • The isolated session keeps its delivery route and its own conversation binding; its replies still go to the chat.
  • Nothing is written differently; only the lookup reads one existing column.
  • Two real chat sessions for one address (rare: for example a dmScope change that leaves an old DM session current) still skip as ambiguous unless the caller pins one. That case is the pinned-session test, unchanged.

Considered and rejected: stop the hint from creating a binding at the producer. The binding and the reply route come from the same delivery field, so splitting them needs a new stored field (schema). Preferring the channel plugin's route when several match adds a second resolution path.

Accepted edge cases:

  • A chat session row written before chat type was recorded and never touched by inbound since would not answer the lookup. The next inbound message records the chat type. Such a send falls through to the channel route lookup as before.
  • A non-chat session that copies a full chat origin (with chat type) still counts as a chat session.

Evidence

  • Red on base, green here: src/sessions/confirmed-visible-message.integration.test.ts "records an announce in the chat inbound uses, not an isolated session hinted at it". It records a DM inbound session and an isolated session whose delivery is built by normalizeSessionDeliveryState from a channel/to hint (what agent-session-patch.ts writes), then calls deliverOutboundPayloads with the isolated producer and no route. Base: DM history empty (skipped as ambiguous). Head: one row in the DM session, none in the isolated session.

  • Stays green: fix: keep confirmed sends in the receiving chat's model history #208049's and fix(outbound): record a plugin action's visible send once #208130's tests, the pinned-session test ("records a shared address in the conversation the caller pinned"), topic, cross-agent and producer tests in the same file.

  • Consumer tests (one ocx test run, vitest-source): 26 files passed. That covers every test file importing a changed registry/reader module (conversation registry SQLite + memory, conversation list/send/turn, route ownership, outbound session, session lifecycle) plus the confirmed-send consumers (deliver.test.ts, delivery-queue.transcript.test.ts, outbound-send-service.integration.test.ts, deliver-confirmed-visible.test.ts, subagent announce delivery/mirror).

  • Real Telegram (Test Server, source Gateway, deterministic mock model, real transport and transcript). The DM user first got READY, so the DM session (agent:main:main) existed. Then gateway call agent {sessionKey: "agent:main:vod-e2e", channel: "telegram", to: "telegram:<dm>", deliver: true} ran, with the final reply as the marker (announce path, no message tool). After that, the user asked "What did you last send me?"

    Side SUT marker messages DM assistant rows with marker Follow-up model request contains marker "multiple current destinations match" lines
    base 5b7efcd4c02e 1 0 no 4
    head a47b58323 1 1 yes 0

    On base the user saw the message, but the DM agent had no record of it. On head the DM agent's next request includes it.

Follow-ups (out of scope)

  • Store the not-recorded reason on the delivery queue row (schema change).
  • Route direct channel notices (Telegram bot-message/dm-access/native commands, Discord native-command-reply, Signal/Matrix approvals) through the history owner.
  • Inbound "accepted ⇒ in transcript" guarantee.
  • Failed-delivery history.

Merge risk

Two-way door: a revert restores the skip. No stored format change. Blast radius: the confirmed-send history commit's address lookup only (resolveCurrentConversationByDelivery has no other caller).

A channel/to hint on an isolated session (gateway agent call, cron) gave the
chat address a second current session, so the confirmed-send commit skipped
as ambiguous and the chat's conversation never saw the message.

The registry's address lookup now only counts chat sessions: inbound and exact
outbound routes record a chat type, a request hint does not.
@clawsweeper

clawsweeper Bot commented Nov 29, 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.

View the workflow run.

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. impact:session-state Session, memory, transcript, context, or agent state can drift or corrupt. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. 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 clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 29, 2026
@clawsweeper

clawsweeper Bot commented Nov 29, 2026

Copy link
Copy Markdown
Contributor

Codex review: passed.

What this changes

This PR excludes sessions without recorded chat type from destination-address lookup so isolated announcements enter the receiving chat’s history.

Example: An isolated Telegram run sends “The announced result” to DM 123, which already has an inbound session.

  • Before: Both sessions match the address, so history recording skips the message as ambiguous.
  • After: The inbound chat owns the lookup and receives one history row; the isolated session receives none.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A worthwhile, focused repair with a distinct regression test and reported shipped-entry-point proof; no blocking findings.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The body supplies base/head results through a source Gateway and real Telegram Test Server transport with a deterministic model: one visible announcement becomes one receiving-history row and appears in the next model request only on the head; independent runtime execution was outside this read-only review.
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 user receives an announcement, replies to it, and the chat’s agent cannot see the message it delivered.
Reason: The change restores the documented receiving-history contract, follows previously recorded work, and has maintainer-authored direction.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR fixes a current conversation-history defect with a focused change; no actionable introduced bugs were found.

Reviewed head: a47b5832397f726de1a1e0e219b8fd35b8558750

Before merge

None.

Findings

None.

Agent review details

How this fits together

Confirmed outbound delivery asks the conversation registry to identify the receiving session, then appends the delivered payload to that session’s model-visible history.

flowchart TD
  A[Isolated agent announcement] --> B[Outbound delivery]
  B --> C[Confirmed message owner]
  C --> D[Conversation registry]
  D --> E[SQLite or memory reader]
  E --> F[Receiving chat session]
  F --> G[Next model request]
Loading

Technical review

Best possible solution:

Keep destination selection in the existing registry and distinguish chat owners from delivery hints using the already-recorded chat type.

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

Current-main source admits both the inbound session and an isolated session carrying the same delivery hint, causing the registry’s ambiguity branch; the author supplies a matching base/head Telegram result, which was not independently rerun.

Is this the best way to solve the issue?

The filter is a small, coherent repair in both existing readers, preserves genuine ambiguity and carried-route handling, and avoids introducing a second resolver or stored field.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Destination-address lookup in durable and memory conversation readers keeps the original intent (3fe7f1e: Record confirmed cross-conversation sends in receiving model history while refusing ambiguous destinations; the new filter preserves that purpose by excluding delivery-only hints.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Ayaan Zaidi: Raw commit 1782ab0 adds src/sessions/confirmed-visible-message.integration.test.ts:397 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 1782ab014036; files: src/sessions/confirmed-visible-message.integration.test.ts)

PR surface

Source +5, Tests +61. Total +66 across 4 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 8 3 +5
Tests 1 61 0 +61
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 69 3 +66

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.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit 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.

Reviewed November 29, 2026, 4:04 AM ET / 09:04 UTC.

@obviyus
obviyus merged commit b904594 into main Nov 29, 2026
140 checks passed
@obviyus
obviyus deleted the fix/visible-send-one-destination branch November 29, 2026 09:11
@obviyus

obviyus commented Nov 29, 2026

Copy link
Copy Markdown
Collaborator Author

Landed as b904594. Bug: when an isolated run's request set channel/to, that session also became a binding for the chat address, so a confirmed announce was skipped as ambiguous and never reached the chat's conversation. Fix: the registry's address lookup now counts only chat sessions, meaning sessions with a recorded chat type. Proof: integration test red on base, green on head. On real Telegram, base had 0 DM rows, and head has 1 row that the DM agent's next request includes.

obviyus added a commit that referenced this pull request Nov 29, 2026
…ory (#208204)

Follows #208049, #208130 and #208169.

## What Problem This Solves

When an agent run needs approval (exec, plugin or OpenClaw change) and Telegram or Signal shows the approval prompt in a different chat than the one that asked (for example the approver's DM, for a cron job, background run or another chat's turn), the user sees the prompt but that chat's agent has no record of it. Asking the DM agent "what did that approval ask?" gets a blank stare.

Cause: the Telegram and Signal approval adapters sent the prompt straight through their own platform clients (`sendMessageTelegram`, `sendMessageSignal`), bypassing core delivery, so the confirmed-send history owner (`src/sessions/confirmed-visible-message.ts`) never saw it.

## User Impact

- Telegram and Signal approval prompts for another conversation now enter the receiving chat's model history once, so the agent there can quote and explain them on the next turn.
- A prompt in the chat whose own turn asked for approval adds no row (that turn already owns its history), so there is no duplicate.
- Signal's approval outcome ("approved", "expired") is a new message (Signal cannot edit), so it is recorded the same way. Telegram edits its prompt in place; edits add no row.
- What the user sees does not change: same text, buttons, topic/thread, reactions, and the same monitor endpoint for Signal. No config, schema, stored-row, protocol or SDK change.

## Why This Change Was Made

The goal: every message a user sees is in that chat's model history, through one owner. The adapters now send through `sendDurableMessageBatch` (as other plugin sends already do) and the direct client calls are deleted, so the existing owner records the prompt. No new hook, flag, guard or state.

- `skipQueue: true`: approval prompts are not replayed after a restart, same as before (a replayed prompt would carry dead buttons for an approval that no longer exists).
- The requesting session is passed as the producer, so the owner's existing same-session rule skips the requesting chat.
- Signal keeps the monitor's `baseUrl`/`account` through the send dependency, as before.
- Side effect: `message_sending` hooks now see approval prompts, like every other core send.

### Direct sends reviewed (classified, not moved)

- **Reply of the turn running in that chat (its turn owns history):** Discord interaction replies (`native-command-reply.ts`), Telegram native command replies, Telegram system-agent approval outcome sent back to the origin chat.
- **Access control before a conversation exists (must never enter a transcript):** Telegram pairing codes and "not allowed" (`dm-access.ts`), "You are not authorized to use this command." (`bot-native-command-dispatch.ts`), provider login device codes (`bot-native-command-login.ts`).
- **Last-resort failure notices:** Telegram "Something went wrong…" after dispatch itself threw (`bot-message.ts`) and "Configured ACP binding is unavailable" (`bot-native-command-dispatch.ts`). They bypass core delivery on purpose so they still arrive when delivery is what failed. Default chosen: keep them direct.

`docs/refactor/conversation-transcript-ownership.md` now lists these classes.

## Evidence

- Red on base, green here (real core delivery, real history owner, SQLite session store; only the platform send function is mocked):
  - `extensions/telegram/src/approval-handler.runtime.test.ts` "records a DM approval prompt: another conversation's approval enters the approver chat once": base 0 rows, head exactly 1 row with the prompt. "…the requesting chat's approval stays with its own turn": 0 rows on both.
  - `extensions/signal/src/approval-handler.runtime.test.ts` "adds a prompt for another conversation's approval to the approver chat once": base 0 rows, head 1. "leaves a prompt in the requesting chat to that chat's own turn": 0 rows.
- Existing Telegram approval cases (topics, Direct Messages topics, fan-out, terminal edits, origin fallback) stay green; their send assertions now check the routed target (`telegram:<chat>:topic:<n>`), which the real sender resolves.
- Both test files moved to the `extension-database-workers` lane (forks pool), since history writes need the main-thread SQLite broker.
- Real Telegram (Test Server, source Gateway, deterministic mock model, real transport and history). The DM user first got READY, so the DM session (`agent:main:main`) existed. Then `gateway call agent {sessionKey: "agent:main:vcn-e2e"}` ran with no channel delivery; the mock made one `exec` call with a marker, and Telegram exec approvals (approver = the DM user, target DM, ask always) showed the prompt with Allow Once / Deny buttons in the DM. After that, the user asked "What did the approval prompt say?" The prompt was left unanswered.

  | Side | Prompts in the DM | DM history rows with marker | Follow-up model request contains marker |
  |---|---:|---:|---|
  | base `b904594b0377` | 1 | 0 | no |
  | head `5462cde7ee6a` | 1 | 1 | yes |

  On base the user saw the approval prompt, but the DM agent had no record of it. On head the DM agent's next request includes it. This proves delivery and history inclusion, not visual rendering.

## Follow-ups (out of scope)

- Approval prompts on Discord, Slack, Matrix, WhatsApp, iMessage, Microsoft Teams and Google Chat still send directly; each needs its native presentation (components, blocks, cards, reactions) through core delivery.
- Matrix shared-DM context notice (`m.notice`; core delivery has no notice message type).
- Storing not-recorded reasons (schema); inbound accepted ⇒ transcript; failed-delivery history and overlap dedupe.

## Merge risk

Two-way door: a revert restores the direct sends. No stored format, schema or contract change. Blast radius: Telegram and Signal native approval prompt delivery (and Signal approval outcome messages).

Co-authored-by: Ayaan Zaidi <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 29, 2026
…ory (#208204)

Follows #208049, #208130 and #208169.

## What Problem This Solves

When an agent run needs approval (exec, plugin or OpenClaw change) and Telegram or Signal shows the approval prompt in a different chat than the one that asked (for example the approver's DM, for a cron job, background run or another chat's turn), the user sees the prompt but that chat's agent has no record of it. Asking the DM agent "what did that approval ask?" gets a blank stare.

Cause: the Telegram and Signal approval adapters sent the prompt straight through their own platform clients (`sendMessageTelegram`, `sendMessageSignal`), bypassing core delivery, so the confirmed-send history owner (`src/sessions/confirmed-visible-message.ts`) never saw it.

## User Impact

- Telegram and Signal approval prompts for another conversation now enter the receiving chat's model history once, so the agent there can quote and explain them on the next turn.
- A prompt in the chat whose own turn asked for approval adds no row (that turn already owns its history), so there is no duplicate.
- Signal's approval outcome ("approved", "expired") is a new message (Signal cannot edit), so it is recorded the same way. Telegram edits its prompt in place; edits add no row.
- What the user sees does not change: same text, buttons, topic/thread, reactions, and the same monitor endpoint for Signal. No config, schema, stored-row, protocol or SDK change.

## Why This Change Was Made

The goal: every message a user sees is in that chat's model history, through one owner. The adapters now send through `sendDurableMessageBatch` (as other plugin sends already do) and the direct client calls are deleted, so the existing owner records the prompt. No new hook, flag, guard or state.

- `skipQueue: true`: approval prompts are not replayed after a restart, same as before (a replayed prompt would carry dead buttons for an approval that no longer exists).
- The requesting session is passed as the producer, so the owner's existing same-session rule skips the requesting chat.
- Signal keeps the monitor's `baseUrl`/`account` through the send dependency, as before.
- Side effect: `message_sending` hooks now see approval prompts, like every other core send.

### Direct sends reviewed (classified, not moved)

- **Reply of the turn running in that chat (its turn owns history):** Discord interaction replies (`native-command-reply.ts`), Telegram native command replies, Telegram system-agent approval outcome sent back to the origin chat.
- **Access control before a conversation exists (must never enter a transcript):** Telegram pairing codes and "not allowed" (`dm-access.ts`), "You are not authorized to use this command." (`bot-native-command-dispatch.ts`), provider login device codes (`bot-native-command-login.ts`).
- **Last-resort failure notices:** Telegram "Something went wrong…" after dispatch itself threw (`bot-message.ts`) and "Configured ACP binding is unavailable" (`bot-native-command-dispatch.ts`). They bypass core delivery on purpose so they still arrive when delivery is what failed. Default chosen: keep them direct.

`docs/refactor/conversation-transcript-ownership.md` now lists these classes.

## Evidence

- Red on base, green here (real core delivery, real history owner, SQLite session store; only the platform send function is mocked):
  - `extensions/telegram/src/approval-handler.runtime.test.ts` "records a DM approval prompt: another conversation's approval enters the approver chat once": base 0 rows, head exactly 1 row with the prompt. "…the requesting chat's approval stays with its own turn": 0 rows on both.
  - `extensions/signal/src/approval-handler.runtime.test.ts` "adds a prompt for another conversation's approval to the approver chat once": base 0 rows, head 1. "leaves a prompt in the requesting chat to that chat's own turn": 0 rows.
- Existing Telegram approval cases (topics, Direct Messages topics, fan-out, terminal edits, origin fallback) stay green; their send assertions now check the routed target (`telegram:<chat>:topic:<n>`), which the real sender resolves.
- Both test files moved to the `extension-database-workers` lane (forks pool), since history writes need the main-thread SQLite broker.
- Real Telegram (Test Server, source Gateway, deterministic mock model, real transport and history). The DM user first got READY, so the DM session (`agent:main:main`) existed. Then `gateway call agent {sessionKey: "agent:main:vcn-e2e"}` ran with no channel delivery; the mock made one `exec` call with a marker, and Telegram exec approvals (approver = the DM user, target DM, ask always) showed the prompt with Allow Once / Deny buttons in the DM. After that, the user asked "What did the approval prompt say?" The prompt was left unanswered.

  | Side | Prompts in the DM | DM history rows with marker | Follow-up model request contains marker |
  |---|---:|---:|---|
  | base `b904594b0377` | 1 | 0 | no |
  | head `5462cde7ee6a` | 1 | 1 | yes |

  On base the user saw the approval prompt, but the DM agent had no record of it. On head the DM agent's next request includes it. This proves delivery and history inclusion, not visual rendering.

## Follow-ups (out of scope)

- Approval prompts on Discord, Slack, Matrix, WhatsApp, iMessage, Microsoft Teams and Google Chat still send directly; each needs its native presentation (components, blocks, cards, reactions) through core delivery.
- Matrix shared-DM context notice (`m.notice`; core delivery has no notice message type).
- Storing not-recorded reasons (schema); inbound accepted ⇒ transcript; failed-delivery history and overlap dedupe.

## Merge risk

Two-way door: a revert restores the direct sends. No stored format, schema or contract change. Blast radius: Telegram and Signal native approval prompt delivery (and Signal approval outcome messages).

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

(cherry picked from commit 94ee07a)

Companion mentions reviewed for #208204: 34d4f8f improve: list Docker streams and flag unconfirmed cleanup in Doctor (#201292); 21786f6 refactor(ui): stop sending 28 additional unused labels to translators (#207982); 9cec330 refactor(workboard): group session tiles without rescanning each column (#207380); 16a2d4b refactor(ui): lowercase log search text only once (#207383)

Co-authored-by: RomneyDa <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 29, 2026
)

Supersedes #207992.

## Problem

An isolated automation turn (`gateway call agent` with its own session key, `channel: telegram`, `to: <dm>`, `deliver: false`) sends a Telegram DM with the `message` tool. The user sees the message, replies, and the DM's assistant has no record of it.

Cause: `commitConfirmedVisibleMessage` decided "the producer's own turn already wrote this" by comparing the producer session's stored `delivery.context` with the send address (`createProducerMatcher`), and returned a silent skip. The gateway `agent` request stores its `channel`/`to` routing hint on the isolated session even with `deliver: false`, so the hint matched the DM address and the DM history write was dropped.

## Fix

- Own-turn is decided only by conversation identity: canonical store key of the producer === canonical store key of the resolved destination. The address matcher and both call sites are removed.
- Every remaining not-recorded outcome carries a diagnostic (`skipped()` now requires one).
- The unused `skipDestinationHistory` opt-out is removed (`deliver-contracts.ts`, `message.ts`, `deliver-core.ts`, its test).
- `docs/refactor/conversation-transcript-ownership.md` describes own-turn by key only.

Production diff: 5 files, net negative.

## User impact

A message the user saw from an automation or another session now lands in the destination chat's model history. A same-chat turn's own final reply still gets no second row. No config, schema, protocol or migration change.

## Evidence

- Red on base, green here: `src/sessions/confirmed-visible-message.integration.test.ts` "records an isolated producer's send despite matching DM routing hints=true". The test that asserted the old "context" skip is deleted.
- No duplicate on the real dispatch path (`src/auto-reply/reply/dispatch-visible-history.integration.test.ts`): Telegram DM with `dmScope` `main` and `per-channel-peer`, Telegram forum topic, Discord channel, Control UI/webchat. Each resolves the same outbound route key as the inbound session, so no key-parity fix was needed.
- Affected consumer tests (30 files) passed locally.
- Real Telegram (Test Server, real model), base `a65ac074b3d6`: the isolated producer's DM arrived once; the DM transcript and the DM agent's next model request did not contain it, and the agent answered with an older reply.
- Real Telegram, head `ee6eed48a208` (same entry point): `gateway call agent` with `sessionKey: agent:main:bedtime-e2e`, `channel: telegram`, `deliver: false`; the agent sent "It's 10:15 pm, time for bed. The amber bookmark can wait until morning." once with the `message` tool. The DM session (`agent:main:main`) then had that text as one assistant row (no duplicate). The user asked "what did you just send me?" and the DM agent answered: "I just sent: “It's 10:15 pm, time for bed. The amber bookmark can wait until morning.”"
- Local ClawSweeper review on `ee6eed48a208`: patch correct, zero findings.
- CI: every check passed except `check-lint-core-5`, which fails on three lint errors in Workboard e2e files from #207839 that are on `main` and not in this diff (#208070; override comment on this PR).

## Not changed here (decision recorded)

Plugin-action settlement (`outbound-send-service.ts` `onHandled`): a base test showed a plugin action that sends through durable delivery and also returns a native receipt can write two destination rows (different `deliveryId`s). Deleting the `onHandled` writer would drop history for third-party handlers that send natively and return only a receipt. Routing those through delivery settlement is a new design, so it is a follow-up, not part of this cut.

## Follow-ups

- Exactly-once native receipt settlement that keeps receipt-only plugin handlers.
- Registry-first destination resolver; sessions not created by inbound must not claim chat addresses (removes the "ambiguous" skip).
- Store the not-recorded reason on the delivery queue row (schema change).
- Route direct channel notices through the owner: Telegram `bot-message.ts`, `dm-access.ts`, native command replies; Discord `native-command-reply.ts`; Signal/Matrix approval handlers.
- Inbound "accepted ⇒ in transcript" for queue drop/summarize paths; failed-delivery and overlap-dedupe history on the agent side.

## Merge risk

Revert restores the old skip. Rows already appended stay.

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

(cherry picked from commit 1782ab0)

Later same-path commits from the pinned scan (separate behavior unless named as folded/selected below): a20fd1c fix: avoid competing Gateway test boots and cold agent mutation imports (#208203); edb6820 fix: let the Gateway restart while boot plugin maintenance is running (#208074); 50d7708 fix: keep Claude fork compaction out of the parent chat (#208192); 94ee07a fix: approval prompts sent to another chat now enter that chat's history (#208204); b904594 fix: record an announced send in the chat it reached (#208169); 407b523 fix(slack): thread queued DM replies under the triggering message (#208133); 5b7efcd fix(outbound): record a plugin action's visible send once (#208130).
Later PR-number mentions: `16a2d4b59d75` refactor(ui): lowercase log search text only once (#207383), `21786f65ed93` refactor(ui): stop sending 28 additional unused labels to translators (#207982), `34d4f8f308ba` improve: list Docker streams and flag unconfirmed cleanup in Doctor (#201292), `5b7efcd4c02e` fix(outbound): record a plugin action's visible send once (#208130), `94ee07a60057` fix: approval prompts sent to another chat now enter that chat's history (#208204), `9cec330df50d` refactor(workboard): group session tiles without rescanning each column (#207380), `b904594b0377` fix: record an announced send in the chat it reached (#208169), `eb378faead30` fix(workboard): clear lint errors in the board settings modal (#208113) Later commit-SHA mentions: none

Co-authored-by: RomneyDa <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 29, 2026
Follows #208049.

## Problem

A plugin `send` action can write the same visible message into the destination chat's model history twice.

Telegram's action handler sends through `sendDurableMessageBatch`. Durable delivery records the confirmed send (`deliver-core.ts` `recordConfirmedTranscript`, key `outbound-delivery:<queue id>:0`). The handler then returns a native receipt, and `outbound-send-service.ts` `onHandled` records it again (key `outbound-delivery:<deliveryIntentId ?? idempotencyKey ?? uuid>:0`). The two keys differ, so the destination gets two identical assistant rows. The model then sees one message the user saw once as two messages.

On real Telegram the second row appears when the destination resolves without ambiguity, for example when the producer session does not carry a `channel/to` hint for the DM. (In #208049's E2E the producer carried that hint, so the durable write was skipped as "multiple current destinations match" and only one row landed.)

## Fix

One plugin action is one send, recorded once.

- `executeSendAction` runs the plugin action inside `runPluginActionHistoryScope(…)`.
- `commitConfirmedVisibleMessage` (the history owner) marks the scope when it actually adds a row.
- The action's receipt commit (`onHandled`) skips when the scope is marked: the handler's core-delivery send already recorded the message.
- Core delivery keeps its own queue identity for the row, so restart recovery (which re-commits with the queue entry id) still finds the existing row.
- Receipt-only handlers (send natively, no core delivery) are unchanged: nothing marks the scope, and `onHandled` writes their one row.
- If the core-delivery commit is skipped (for example an ambiguous destination), the scope stays unmarked and `onHandled` still writes with the caller's route, as before.

Why a scope and not a new field: `ChannelMessageActionContext` has no delivery identity field, and each plugin forwards context fields to its runtime by hand (Telegram lists them in `channel-actions.ts`). Threading an id would be a new public Plugin SDK field that every third-party handler must forward. The scope reaches any handler that sends through core delivery, with no SDK change. No config, stored state, table or hook.

Review round 1 changed the mechanism: an earlier head replaced the core row's id with the action id, which broke dedupe on restart recovery (recovery commits under the queue entry id). This head keeps the queue id.

## User impact

A message sent through a plugin action (Telegram `message` tool sends, for example) appears once in the receiving chat's model history, exactly as delivered. No config, schema, protocol, stored-row or SDK change.

## Evidence

- Red on base, green here: `src/infra/outbound/outbound-send-service.integration.test.ts` "records a plugin action's durable send in destination history once" (base: two identical rows).
- Stays green: "records a receipt-only plugin action in destination history once".
- Consumer tests: 19 files passed locally (one `ocx test` set, vitest-source): the new test, `outbound-send-service{,.accepted-outcomes}.test.ts` (their module mocks now pass the scope through), `deliver.test.ts`, `deliver-confirmed-visible.test.ts`, `delivery-queue.transcript.test.ts`, `confirmed-visible-message.integration.test.ts`, `message-action-send{,.core,.media,.mirror-order,.validation}.test.ts`, subagent announce delivery/mirror tests, Telegram `action-runtime.test.ts` + `channel-actions.contract.test.ts`, Discord `actions/runtime.test.ts`, Slack `action-runtime.test.ts`, `test/qa-channel-message-tool-delivery.test.ts`.
- Real Telegram (Test Server, source Gateway) on head `c33cd7f46b40`: the DM user first got a reply ("READY"), so the DM session existed. Then `gateway call agent` ran with an isolated `sessionKey`, `deliver: false` and no `channel`/`to` hints. Its `message` tool sent one marker DM to the user. Results: the recorder saw 1 marker message, and the DM session (`agent:main:main`) had 1 assistant row for it. That row's key is the core-delivery queue id (`outbound-delivery:<uuid>:0`), so the handler's durable write recorded it and the receipt commit skipped. The Gateway logged no "multiple current destinations match" line, so the run took the path that wrote two rows before this fix. The model fixture was deterministic, so the tool call was predictable. Telegram transport and transcript were real.
- Local review: round 1 found the recovery-identity problem described above (fixed). Round 2 on `c33cd7f46b40`: patch correct, no findings.
- Rebased on main to pick up #208120: the base had #207738 without its PR-wrapper inventory fix, so `test/scripts/eager-import-closure.test.ts` was red.

## Follow-ups (out of scope)

- Registry-first destination resolver; remove the "ambiguous" skip.
- Store the not-recorded reason on the delivery queue row (schema change).
- Route direct channel notices through the history owner.
- Inbound "accepted ⇒ in transcript" guarantees.
- Failed-delivery history.

## Merge risk

Two-way door. Revert restores the duplicate row. No stored format change; the idempotency key format is the same, only which id fills it inside a plugin action. Blast radius: plugin-action sends that also go through core delivery (Telegram today).

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

(cherry picked from commit 5b7efcd)

No later same-path companion identified in the bounded scan.
Later PR-number mentions: `16a2d4b59d75` refactor(ui): lowercase log search text only once (#207383), `21786f65ed93` refactor(ui): stop sending 28 additional unused labels to translators (#207982), `34d4f8f308ba` improve: list Docker streams and flag unconfirmed cleanup in Doctor (#201292), `94ee07a60057` fix: approval prompts sent to another chat now enter that chat's history (#208204), `9cec330df50d` refactor(workboard): group session tiles without rescanning each column (#207380), `b904594b0377` fix: record an announced send in the chat it reached (#208169), `eb378faead30` fix(workboard): clear lint errors in the board settings modal (#208113) Later commit-SHA mentions: `16a2d4b59d75` refactor(ui): lowercase log search text only once (#207383), `21786f65ed93` refactor(ui): stop sending 28 additional unused labels to translators (#207982), `34d4f8f308ba` improve: list Docker streams and flag unconfirmed cleanup in Doctor (#201292), `9cec330df50d` refactor(workboard): group session tiles without rescanning each column (#207380), `b904594b0377` fix: record an announced send in the chat it reached (#208169)

Co-authored-by: RomneyDa <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 30, 2026
…ory (#208204)

Follows #208049, #208130 and #208169.

## What Problem This Solves

When an agent run needs approval (exec, plugin or OpenClaw change) and Telegram or Signal shows the approval prompt in a different chat than the one that asked (for example the approver's DM, for a cron job, background run or another chat's turn), the user sees the prompt but that chat's agent has no record of it. Asking the DM agent "what did that approval ask?" gets a blank stare.

Cause: the Telegram and Signal approval adapters sent the prompt straight through their own platform clients (`sendMessageTelegram`, `sendMessageSignal`), bypassing core delivery, so the confirmed-send history owner (`src/sessions/confirmed-visible-message.ts`) never saw it.

## User Impact

- Telegram and Signal approval prompts for another conversation now enter the receiving chat's model history once, so the agent there can quote and explain them on the next turn.
- A prompt in the chat whose own turn asked for approval adds no row (that turn already owns its history), so there is no duplicate.
- Signal's approval outcome ("approved", "expired") is a new message (Signal cannot edit), so it is recorded the same way. Telegram edits its prompt in place; edits add no row.
- What the user sees does not change: same text, buttons, topic/thread, reactions, and the same monitor endpoint for Signal. No config, schema, stored-row, protocol or SDK change.

## Why This Change Was Made

The goal: every message a user sees is in that chat's model history, through one owner. The adapters now send through `sendDurableMessageBatch` (as other plugin sends already do) and the direct client calls are deleted, so the existing owner records the prompt. No new hook, flag, guard or state.

- `skipQueue: true`: approval prompts are not replayed after a restart, same as before (a replayed prompt would carry dead buttons for an approval that no longer exists).
- The requesting session is passed as the producer, so the owner's existing same-session rule skips the requesting chat.
- Signal keeps the monitor's `baseUrl`/`account` through the send dependency, as before.
- Side effect: `message_sending` hooks now see approval prompts, like every other core send.

### Direct sends reviewed (classified, not moved)

- **Reply of the turn running in that chat (its turn owns history):** Discord interaction replies (`native-command-reply.ts`), Telegram native command replies, Telegram system-agent approval outcome sent back to the origin chat.
- **Access control before a conversation exists (must never enter a transcript):** Telegram pairing codes and "not allowed" (`dm-access.ts`), "You are not authorized to use this command." (`bot-native-command-dispatch.ts`), provider login device codes (`bot-native-command-login.ts`).
- **Last-resort failure notices:** Telegram "Something went wrong…" after dispatch itself threw (`bot-message.ts`) and "Configured ACP binding is unavailable" (`bot-native-command-dispatch.ts`). They bypass core delivery on purpose so they still arrive when delivery is what failed. Default chosen: keep them direct.

`docs/refactor/conversation-transcript-ownership.md` now lists these classes.

## Evidence

- Red on base, green here (real core delivery, real history owner, SQLite session store; only the platform send function is mocked):
  - `extensions/telegram/src/approval-handler.runtime.test.ts` "records a DM approval prompt: another conversation's approval enters the approver chat once": base 0 rows, head exactly 1 row with the prompt. "…the requesting chat's approval stays with its own turn": 0 rows on both.
  - `extensions/signal/src/approval-handler.runtime.test.ts` "adds a prompt for another conversation's approval to the approver chat once": base 0 rows, head 1. "leaves a prompt in the requesting chat to that chat's own turn": 0 rows.
- Existing Telegram approval cases (topics, Direct Messages topics, fan-out, terminal edits, origin fallback) stay green; their send assertions now check the routed target (`telegram:<chat>:topic:<n>`), which the real sender resolves.
- Both test files moved to the `extension-database-workers` lane (forks pool), since history writes need the main-thread SQLite broker.
- Real Telegram (Test Server, source Gateway, deterministic mock model, real transport and history). The DM user first got READY, so the DM session (`agent:main:main`) existed. Then `gateway call agent {sessionKey: "agent:main:vcn-e2e"}` ran with no channel delivery; the mock made one `exec` call with a marker, and Telegram exec approvals (approver = the DM user, target DM, ask always) showed the prompt with Allow Once / Deny buttons in the DM. After that, the user asked "What did the approval prompt say?" The prompt was left unanswered.

  | Side | Prompts in the DM | DM history rows with marker | Follow-up model request contains marker |
  |---|---:|---:|---|
  | base `b904594b0377` | 1 | 0 | no |
  | head `5462cde7ee6a` | 1 | 1 | yes |

  On base the user saw the approval prompt, but the DM agent had no record of it. On head the DM agent's next request includes it. This proves delivery and history inclusion, not visual rendering.

## Follow-ups (out of scope)

- Approval prompts on Discord, Slack, Matrix, WhatsApp, iMessage, Microsoft Teams and Google Chat still send directly; each needs its native presentation (components, blocks, cards, reactions) through core delivery.
- Matrix shared-DM context notice (`m.notice`; core delivery has no notice message type).
- Storing not-recorded reasons (schema); inbound accepted ⇒ transcript; failed-delivery history and overlap dedupe.

## Merge risk

Two-way door: a revert restores the direct sends. No stored format, schema or contract change. Blast radius: Telegram and Signal native approval prompt delivery (and Signal approval outcome messages).

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit 94ee07a)

Release adaptation: None; source applies intact to current stable owner.

Companion audit: Use existing destination transcript owners for cross-chat Telegram and Signal approval posts. Preserve expiry and original settlement.

Co-authored-by: RomneyDa <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 30, 2026
Follows #208049 and #208130.

## What Problem This Solves

When an isolated agent run (for example `gateway call agent` with `channel`/`to` set, a cron announce or a recovery send) delivers a message to a chat, the user sees the message but the chat's own conversation does not record it. When the user replies, the agent in that chat does not know what it just sent.

Cause: the request's `channel`/`to` routing hint is stored on the isolated session as its delivery route. The conversation registry derives an address binding from every session's delivery route, so the chat address then has two current sessions: the chat's own (inbound) session and the isolated one. `commitConfirmedVisibleMessage` (`src/sessions/confirmed-visible-message.ts`) asks the registry which conversation owns the address, gets two, and skips with "Conversation context skipped: multiple current destinations match." Sends that carry their own route (plugin receipts) were not affected; announce, gateway `send` and recovery sends were. #208130's E2E saw this skip.

## User Impact

A message delivered to a chat from an isolated run now lands once in that chat's conversation, so the chat's agent can see and quote it on the next turn. No config, schema, stored-row, protocol or SDK change.

## Why This Change Was Made

The registry's address lookup answers "which conversation does inbound for this address use?". Only chat sessions can answer that. Inbound (`initSessionState`) and exact outbound route binding (`bindOutboundSessionEntry`) always record the session's chat type; a request hint records only a delivery address. The lookup (`resolveCurrentConversationByDelivery`, its only caller is the confirmed-send commit) now ignores sessions without a recorded chat type: `s.chat_type IS NOT NULL` in the SQLite reader (`session_windows.chat_type` already exists) and `entry.chatType` in the memory reader.

- The isolated session keeps its delivery route and its own conversation binding; its replies still go to the chat.
- Nothing is written differently; only the lookup reads one existing column.
- Two real chat sessions for one address (rare: for example a dmScope change that leaves an old DM session current) still skip as ambiguous unless the caller pins one. That case is the pinned-session test, unchanged.

Considered and rejected: stop the hint from creating a binding at the producer. The binding and the reply route come from the same `delivery` field, so splitting them needs a new stored field (schema). Preferring the channel plugin's route when several match adds a second resolution path.

Accepted edge cases:
- A chat session row written before chat type was recorded and never touched by inbound since would not answer the lookup. The next inbound message records the chat type. Such a send falls through to the channel route lookup as before.
- A non-chat session that copies a full chat origin (with chat type) still counts as a chat session.

## Evidence

- Red on base, green here: `src/sessions/confirmed-visible-message.integration.test.ts` "records an announce in the chat inbound uses, not an isolated session hinted at it". It records a DM inbound session and an isolated session whose `delivery` is built by `normalizeSessionDeliveryState` from a `channel`/`to` hint (what `agent-session-patch.ts` writes), then calls `deliverOutboundPayloads` with the isolated producer and no route. Base: DM history empty (skipped as ambiguous). Head: one row in the DM session, none in the isolated session.
- Stays green: #208049's and #208130's tests, the pinned-session test ("records a shared address in the conversation the caller pinned"), topic, cross-agent and producer tests in the same file.
- Consumer tests (one `ocx test` run, vitest-source): 26 files passed. That covers every test file importing a changed registry/reader module (conversation registry SQLite + memory, conversation list/send/turn, route ownership, outbound session, session lifecycle) plus the confirmed-send consumers (`deliver.test.ts`, `delivery-queue.transcript.test.ts`, `outbound-send-service.integration.test.ts`, `deliver-confirmed-visible.test.ts`, subagent announce delivery/mirror).
- Real Telegram (Test Server, source Gateway, deterministic mock model, real transport and transcript). The DM user first got READY, so the DM session (`agent:main:main`) existed. Then `gateway call agent {sessionKey: "agent:main:vod-e2e", channel: "telegram", to: "telegram:<dm>", deliver: true}` ran, with the final reply as the marker (announce path, no message tool). After that, the user asked "What did you last send me?"

  | Side | SUT marker messages | DM assistant rows with marker | Follow-up model request contains marker | "multiple current destinations match" lines |
  |---|---:|---:|---|---:|
  | base `5b7efcd4c02e` | 1 | 0 | no | 4 |
  | head `a47b58323` | 1 | 1 | yes | 0 |

  On base the user saw the message, but the DM agent had no record of it. On head the DM agent's next request includes it.

## Follow-ups (out of scope)

- Store the not-recorded reason on the delivery queue row (schema change).
- Route direct channel notices (Telegram bot-message/dm-access/native commands, Discord native-command-reply, Signal/Matrix approvals) through the history owner.
- Inbound "accepted ⇒ in transcript" guarantee.
- Failed-delivery history.

## Merge risk

Two-way door: a revert restores the skip. No stored format change. Blast radius: the confirmed-send history commit's address lookup only (`resolveCurrentConversationByDelivery` has no other caller).

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit b904594)

Companion audit: canonical destination and receipt fallback are earlier lane commits; no later same-path or SHA/PR-linked changes. Kept matching durable and in-memory ownership rules.

Co-authored-by: RomneyDa <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 30, 2026
Follows #208049 and #208130.

## What Problem This Solves

When an isolated agent run (for example `gateway call agent` with `channel`/`to` set, a cron announce or a recovery send) delivers a message to a chat, the user sees the message but the chat's own conversation does not record it. When the user replies, the agent in that chat does not know what it just sent.

Cause: the request's `channel`/`to` routing hint is stored on the isolated session as its delivery route. The conversation registry derives an address binding from every session's delivery route, so the chat address then has two current sessions: the chat's own (inbound) session and the isolated one. `commitConfirmedVisibleMessage` (`src/sessions/confirmed-visible-message.ts`) asks the registry which conversation owns the address, gets two, and skips with "Conversation context skipped: multiple current destinations match." Sends that carry their own route (plugin receipts) were not affected; announce, gateway `send` and recovery sends were. #208130's E2E saw this skip.

## User Impact

A message delivered to a chat from an isolated run now lands once in that chat's conversation, so the chat's agent can see and quote it on the next turn. No config, schema, stored-row, protocol or SDK change.

## Why This Change Was Made

The registry's address lookup answers "which conversation does inbound for this address use?". Only chat sessions can answer that. Inbound (`initSessionState`) and exact outbound route binding (`bindOutboundSessionEntry`) always record the session's chat type; a request hint records only a delivery address. The lookup (`resolveCurrentConversationByDelivery`, its only caller is the confirmed-send commit) now ignores sessions without a recorded chat type: `s.chat_type IS NOT NULL` in the SQLite reader (`session_windows.chat_type` already exists) and `entry.chatType` in the memory reader.

- The isolated session keeps its delivery route and its own conversation binding; its replies still go to the chat.
- Nothing is written differently; only the lookup reads one existing column.
- Two real chat sessions for one address (rare: for example a dmScope change that leaves an old DM session current) still skip as ambiguous unless the caller pins one. That case is the pinned-session test, unchanged.

Considered and rejected: stop the hint from creating a binding at the producer. The binding and the reply route come from the same `delivery` field, so splitting them needs a new stored field (schema). Preferring the channel plugin's route when several match adds a second resolution path.

Accepted edge cases:
- A chat session row written before chat type was recorded and never touched by inbound since would not answer the lookup. The next inbound message records the chat type. Such a send falls through to the channel route lookup as before.
- A non-chat session that copies a full chat origin (with chat type) still counts as a chat session.

## Evidence

- Red on base, green here: `src/sessions/confirmed-visible-message.integration.test.ts` "records an announce in the chat inbound uses, not an isolated session hinted at it". It records a DM inbound session and an isolated session whose `delivery` is built by `normalizeSessionDeliveryState` from a `channel`/`to` hint (what `agent-session-patch.ts` writes), then calls `deliverOutboundPayloads` with the isolated producer and no route. Base: DM history empty (skipped as ambiguous). Head: one row in the DM session, none in the isolated session.
- Stays green: #208049's and #208130's tests, the pinned-session test ("records a shared address in the conversation the caller pinned"), topic, cross-agent and producer tests in the same file.
- Consumer tests (one `ocx test` run, vitest-source): 26 files passed. That covers every test file importing a changed registry/reader module (conversation registry SQLite + memory, conversation list/send/turn, route ownership, outbound session, session lifecycle) plus the confirmed-send consumers (`deliver.test.ts`, `delivery-queue.transcript.test.ts`, `outbound-send-service.integration.test.ts`, `deliver-confirmed-visible.test.ts`, subagent announce delivery/mirror).
- Real Telegram (Test Server, source Gateway, deterministic mock model, real transport and transcript). The DM user first got READY, so the DM session (`agent:main:main`) existed. Then `gateway call agent {sessionKey: "agent:main:vod-e2e", channel: "telegram", to: "telegram:<dm>", deliver: true}` ran, with the final reply as the marker (announce path, no message tool). After that, the user asked "What did you last send me?"

  | Side | SUT marker messages | DM assistant rows with marker | Follow-up model request contains marker | "multiple current destinations match" lines |
  |---|---:|---:|---|---:|
  | base `5b7efcd4c02e` | 1 | 0 | no | 4 |
  | head `a47b58323` | 1 | 1 | yes | 0 |

  On base the user saw the message, but the DM agent had no record of it. On head the DM agent's next request includes it.

## Follow-ups (out of scope)

- Store the not-recorded reason on the delivery queue row (schema change).
- Route direct channel notices (Telegram bot-message/dm-access/native commands, Discord native-command-reply, Signal/Matrix approvals) through the history owner.
- Inbound "accepted ⇒ in transcript" guarantee.
- Failed-delivery history.

## Merge risk

Two-way door: a revert restores the skip. No stored format change. Blast radius: the confirmed-send history commit's address lookup only (`resolveCurrentConversationByDelivery` has no other caller).

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

(cherry picked from commit b904594)
Co-authored-by: RomneyDa <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 30, 2026
Follows openclaw#208049 and openclaw#208130.

## What Problem This Solves

When an isolated agent run (for example `gateway call agent` with `channel`/`to` set, a cron announce or a recovery send) delivers a message to a chat, the user sees the message but the chat's own conversation does not record it. When the user replies, the agent in that chat does not know what it just sent.

Cause: the request's `channel`/`to` routing hint is stored on the isolated session as its delivery route. The conversation registry derives an address binding from every session's delivery route, so the chat address then has two current sessions: the chat's own (inbound) session and the isolated one. `commitConfirmedVisibleMessage` (`src/sessions/confirmed-visible-message.ts`) asks the registry which conversation owns the address, gets two, and skips with "Conversation context skipped: multiple current destinations match." Sends that carry their own route (plugin receipts) were not affected; announce, gateway `send` and recovery sends were. openclaw#208130's E2E saw this skip.

## User Impact

A message delivered to a chat from an isolated run now lands once in that chat's conversation, so the chat's agent can see and quote it on the next turn. No config, schema, stored-row, protocol or SDK change.

## Why This Change Was Made

The registry's address lookup answers "which conversation does inbound for this address use?". Only chat sessions can answer that. Inbound (`initSessionState`) and exact outbound route binding (`bindOutboundSessionEntry`) always record the session's chat type; a request hint records only a delivery address. The lookup (`resolveCurrentConversationByDelivery`, its only caller is the confirmed-send commit) now ignores sessions without a recorded chat type: `s.chat_type IS NOT NULL` in the SQLite reader (`session_windows.chat_type` already exists) and `entry.chatType` in the memory reader.

- The isolated session keeps its delivery route and its own conversation binding; its replies still go to the chat.
- Nothing is written differently; only the lookup reads one existing column.
- Two real chat sessions for one address (rare: for example a dmScope change that leaves an old DM session current) still skip as ambiguous unless the caller pins one. That case is the pinned-session test, unchanged.

Considered and rejected: stop the hint from creating a binding at the producer. The binding and the reply route come from the same `delivery` field, so splitting them needs a new stored field (schema). Preferring the channel plugin's route when several match adds a second resolution path.

Accepted edge cases:
- A chat session row written before chat type was recorded and never touched by inbound since would not answer the lookup. The next inbound message records the chat type. Such a send falls through to the channel route lookup as before.
- A non-chat session that copies a full chat origin (with chat type) still counts as a chat session.

## Evidence

- Red on base, green here: `src/sessions/confirmed-visible-message.integration.test.ts` "records an announce in the chat inbound uses, not an isolated session hinted at it". It records a DM inbound session and an isolated session whose `delivery` is built by `normalizeSessionDeliveryState` from a `channel`/`to` hint (what `agent-session-patch.ts` writes), then calls `deliverOutboundPayloads` with the isolated producer and no route. Base: DM history empty (skipped as ambiguous). Head: one row in the DM session, none in the isolated session.
- Stays green: openclaw#208049's and openclaw#208130's tests, the pinned-session test ("records a shared address in the conversation the caller pinned"), topic, cross-agent and producer tests in the same file.
- Consumer tests (one `ocx test` run, vitest-source): 26 files passed. That covers every test file importing a changed registry/reader module (conversation registry SQLite + memory, conversation list/send/turn, route ownership, outbound session, session lifecycle) plus the confirmed-send consumers (`deliver.test.ts`, `delivery-queue.transcript.test.ts`, `outbound-send-service.integration.test.ts`, `deliver-confirmed-visible.test.ts`, subagent announce delivery/mirror).
- Real Telegram (Test Server, source Gateway, deterministic mock model, real transport and transcript). The DM user first got READY, so the DM session (`agent:main:main`) existed. Then `gateway call agent {sessionKey: "agent:main:vod-e2e", channel: "telegram", to: "telegram:<dm>", deliver: true}` ran, with the final reply as the marker (announce path, no message tool). After that, the user asked "What did you last send me?"

  | Side | SUT marker messages | DM assistant rows with marker | Follow-up model request contains marker | "multiple current destinations match" lines |
  |---|---:|---:|---|---:|
  | base `7e297a980611` | 1 | 0 | no | 4 |
  | head `a47b58323` | 1 | 1 | yes | 0 |

  On base the user saw the message, but the DM agent had no record of it. On head the DM agent's next request includes it.

## Follow-ups (out of scope)

- Store the not-recorded reason on the delivery queue row (schema change).
- Route direct channel notices (Telegram bot-message/dm-access/native commands, Discord native-command-reply, Signal/Matrix approvals) through the history owner.
- Inbound "accepted ⇒ in transcript" guarantee.
- Failed-delivery history.

## Merge risk

Two-way door: a revert restores the skip. No stored format change. Blast radius: the confirmed-send history commit's address lookup only (`resolveCurrentConversationByDelivery` has no other caller).

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 30, 2026
…ory (openclaw#208204)

Follows openclaw#208049, openclaw#208130 and openclaw#208169.

## What Problem This Solves

When an agent run needs approval (exec, plugin or OpenClaw change) and Telegram or Signal shows the approval prompt in a different chat than the one that asked (for example the approver's DM, for a cron job, background run or another chat's turn), the user sees the prompt but that chat's agent has no record of it. Asking the DM agent "what did that approval ask?" gets a blank stare.

Cause: the Telegram and Signal approval adapters sent the prompt straight through their own platform clients (`sendMessageTelegram`, `sendMessageSignal`), bypassing core delivery, so the confirmed-send history owner (`src/sessions/confirmed-visible-message.ts`) never saw it.

## User Impact

- Telegram and Signal approval prompts for another conversation now enter the receiving chat's model history once, so the agent there can quote and explain them on the next turn.
- A prompt in the chat whose own turn asked for approval adds no row (that turn already owns its history), so there is no duplicate.
- Signal's approval outcome ("approved", "expired") is a new message (Signal cannot edit), so it is recorded the same way. Telegram edits its prompt in place; edits add no row.
- What the user sees does not change: same text, buttons, topic/thread, reactions, and the same monitor endpoint for Signal. No config, schema, stored-row, protocol or SDK change.

## Why This Change Was Made

The goal: every message a user sees is in that chat's model history, through one owner. The adapters now send through `sendDurableMessageBatch` (as other plugin sends already do) and the direct client calls are deleted, so the existing owner records the prompt. No new hook, flag, guard or state.

- `skipQueue: true`: approval prompts are not replayed after a restart, same as before (a replayed prompt would carry dead buttons for an approval that no longer exists).
- The requesting session is passed as the producer, so the owner's existing same-session rule skips the requesting chat.
- Signal keeps the monitor's `baseUrl`/`account` through the send dependency, as before.
- Side effect: `message_sending` hooks now see approval prompts, like every other core send.

### Direct sends reviewed (classified, not moved)

- **Reply of the turn running in that chat (its turn owns history):** Discord interaction replies (`native-command-reply.ts`), Telegram native command replies, Telegram system-agent approval outcome sent back to the origin chat.
- **Access control before a conversation exists (must never enter a transcript):** Telegram pairing codes and "not allowed" (`dm-access.ts`), "You are not authorized to use this command." (`bot-native-command-dispatch.ts`), provider login device codes (`bot-native-command-login.ts`).
- **Last-resort failure notices:** Telegram "Something went wrong…" after dispatch itself threw (`bot-message.ts`) and "Configured ACP binding is unavailable" (`bot-native-command-dispatch.ts`). They bypass core delivery on purpose so they still arrive when delivery is what failed. Default chosen: keep them direct.

`docs/refactor/conversation-transcript-ownership.md` now lists these classes.

## Evidence

- Red on base, green here (real core delivery, real history owner, SQLite session store; only the platform send function is mocked):
  - `extensions/telegram/src/approval-handler.runtime.test.ts` "records a DM approval prompt: another conversation's approval enters the approver chat once": base 0 rows, head exactly 1 row with the prompt. "…the requesting chat's approval stays with its own turn": 0 rows on both.
  - `extensions/signal/src/approval-handler.runtime.test.ts` "adds a prompt for another conversation's approval to the approver chat once": base 0 rows, head 1. "leaves a prompt in the requesting chat to that chat's own turn": 0 rows.
- Existing Telegram approval cases (topics, Direct Messages topics, fan-out, terminal edits, origin fallback) stay green; their send assertions now check the routed target (`telegram:<chat>:topic:<n>`), which the real sender resolves.
- Both test files moved to the `extension-database-workers` lane (forks pool), since history writes need the main-thread SQLite broker.
- Real Telegram (Test Server, source Gateway, deterministic mock model, real transport and history). The DM user first got READY, so the DM session (`agent:main:main`) existed. Then `gateway call agent {sessionKey: "agent:main:vcn-e2e"}` ran with no channel delivery; the mock made one `exec` call with a marker, and Telegram exec approvals (approver = the DM user, target DM, ask always) showed the prompt with Allow Once / Deny buttons in the DM. After that, the user asked "What did the approval prompt say?" The prompt was left unanswered.

  | Side | Prompts in the DM | DM history rows with marker | Follow-up model request contains marker |
  |---|---:|---:|---|
  | base `44fae6be5bcd` | 1 | 0 | no |
  | head `5462cde7ee6a` | 1 | 1 | yes |

  On base the user saw the approval prompt, but the DM agent had no record of it. On head the DM agent's next request includes it. This proves delivery and history inclusion, not visual rendering.

## Follow-ups (out of scope)

- Approval prompts on Discord, Slack, Matrix, WhatsApp, iMessage, Microsoft Teams and Google Chat still send directly; each needs its native presentation (components, blocks, cards, reactions) through core delivery.
- Matrix shared-DM context notice (`m.notice`; core delivery has no notice message type).
- Storing not-recorded reasons (schema); inbound accepted ⇒ transcript; failed-delivery history and overlap dedupe.

## Merge risk

Two-way door: a revert restores the direct sends. No stored format, schema or contract change. Blast radius: Telegram and Signal native approval prompt delivery (and Signal approval outcome messages).

Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

impact:session-state Session, memory, transcript, context, or agent state can drift or corrupt. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S 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