Skip to content

fix: keep tool-finalizer placeholders private in message-only groups - #138645

Merged
omarshahine merged 14 commits into
openclaw:mainfrom
razvangirgiz:fix/settled-fallback-source-suppression
Sep 8, 2026
Merged

omarshahine merged 14 commits into
openclaw:mainfrom
razvangirgiz:fix/settled-fallback-source-suppression

Conversation

@razvangirgiz

@razvangirgiz razvangirgiz commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes an issue where users in message-tool-only groups could see an internal placeholder when a tool finished but its finalizer returned no answer or failed. Queued delivery could replace that private diagnostic with another empty-response message. A recovered answer could also repeat the answer and completed action.

Why This Change Was Made

Finalization now distinguishes recovered answers from synthetic diagnostics. The shared recovery path recognizes answers already awaiting delivery. The payload producer preserves delivery permission for genuine errors when no message-tool result exists, while respecting completed replies and approval precedence. Telegram fallback paths retain send-policy denial.

The repair reuses existing outcomes, transcript identity and writer authority. It adds no configuration, persistence layer, retry mechanism or text filter.

User Impact

Private finalizer diagnostics stay private. Recovered answers, genuine failures and yield acknowledgments remain deliverable exactly once. Automatic-mode replies and explicit message-tool sends keep their existing behavior.

Evidence

Real Telegram Test Server group delivery was recorded for 60 seconds per control, using an isolated Gateway and a deterministic provider at the normal model protocol boundary. Runtime proof used build f37c526; the later changes at c5d137f correct tests only and leave product code, dependencies and assets unchanged.

Scenario Observed group result
Empty or failed finalizer, message-tool-only Main sent the placeholder; repaired runtime sends no message
Recovered answer One substantive answer and one completed action
Direct and queued provider failure One classified error each; partial text stays private
Direct and queued yield One waiting acknowledgment each; private notes stay private
Ordinary nonterminal message-tool send One reply; actual private final text and diagnostic stay private
Denial in both visibility modes; ambient room event No public reply
Cancellation and session reset Only the expected command acknowledgment; no late finalizer reply
Automatic empty and failed finalization One existing fallback each

Transcript identities and action markers confirm one diagnostic per existing key and no completed-action replay. One completed recording was recovered after interrupted teardown; its original process failure remains recorded.

  • Real Telegram Test Server group reproductions showed both finalizer leaks on main at 3fb2ef2e972d244f36e03f4e0a0d0914f33a5ed4 before repair.
  • All 16 independent Telegram behavior controls pass: both finalizer outcomes, recovered answers, direct/queued errors and yields, ordinary message-tool delivery, both visibility modes, denial, room events, cancellation and session reset. A separate owner review confirms the existing writer/delivery fences and absence of a new retry system or text filter.
  • New producer regressions fail on the old producer for the intended permission defects and pass on the candidate. The hosted embedded-run group passes 113 files and 1,755 tests.
  • The ordered queued-error regression reaches the delivery assertion: old source returns silence, corrected source delivers the genuine error. The corrected owned-child yield regression passes its exactly-once checks.
  • Production, core-test, extension-test and script/root typing passed in hosted CI. Earlier memory failures and all unsuccessful attempts remain recorded. Other CI failures retain their separate causal evidence and unresolved limits. Final exact-head CI and review remain required.

Thanks @razvangirgiz for the original repair and investigation. AI-assisted.

@clawsweeper

clawsweeper Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

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

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Sep 4, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 4, 2026
@clawsweeper

clawsweeper Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 8, 2026, 11:36 AM ET / 15:36 UTC.

ClawSweeper review

What this changes

The PR keeps synthetic tool-finalizer diagnostics private in message-only chats while preserving recovered answers, genuine errors, waiting acknowledgments, and Telegram send-policy denial.

Merge readiness

✅ Ready for maintainer review

This fix remains necessary: current main and v2026.9.3 still permit synthetic finalizer placeholders through source-reply suppression. The related merged work addresses a different failure, and the reviewed patch has no actionable correctness findings.

Priority: P2
Reviewed head: 8112a31f78369cbfdb1901922241fca9236925ae

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused owner-level repair with strong real-delivery evidence and meaningful regressions; no actionable patch defects were found.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Recorded Telegram Test Server observations exercise the finalizer, shared recovery, and actual chat delivery through an isolated Gateway, showing private placeholders suppressed while answers, errors, and yields remain visible once; denial, cancellation, and reset controls remain quiet. Independent iMessage deployment logs corroborate the central finalizer repair.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): Recorded Telegram Test Server observations exercise the finalizer, shared recovery, and actual chat delivery through an isolated Gateway, showing private placeholders suppressed while answers, errors, and yields remain visible once; denial, cancellation, and reset controls remain quiet. Independent iMessage deployment logs corroborate the central finalizer repair.
Evidence reviewed 9 items Current main still needs the repair: Current main unconditionally marks finalizer payloads for delivery through source-reply suppression and retains fallback text as the final answer.
Latest supplied release retains the defect: The v2026.9.3 implementation also unconditionally marks finalizer payloads for source-suppression delivery.
Existing visibility contract: The group documentation defines message-tool mode as keeping ordinary assistant final text private; automatic delivery remains a separate supported mode.
Findings None None.
Security None None.

How this fits together

OpenClaw finalizes completed tool runs and passes their replies through shared immediate or queued delivery. Source-reply policy determines which payloads reach the originating chat, and Telegram applies that decision to its fallback messages.

flowchart TD
  A[Completed tool run] --> B[Tool-free finalizer]
  B --> C{Answer or diagnostic}
  C --> D[Reply payload preparation]
  D --> E[Immediate or queued delivery]
  E --> F{Visibility and send policy}
  F --> G[Visible chat reply]
  F --> H[Private diagnostic]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +36, Tests +352. Total +388 across 23 files.

View PR surface stats
Area Files Added Removed Net
Source 12 63 27 +36
Tests 11 594 242 +352
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 23 657 269 +388

Review metrics

None.

Technical review

Best possible solution:

Keep visibility decisions at the payload producer and shared recovery owner, with genuine terminal outcomes delivered once under the existing send and lifecycle policies.

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

Yes: a message-tool-only turn whose settled-tool finalizer returns empty or fails reaches an unconditional delivery override on current main; supplied Telegram and iMessage observations corroborate that path. No runtime reproduction was executed in this review.

Is this the best way to solve the issue?

Yes: distinguishing real answers from synthetic diagnostics at their producer, then reusing shared recovery and delivery policy, addresses the cause without new configuration or retry machinery.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: This repairs unwanted group-chat diagnostics and duplicate recovery in the optional message-tool-only delivery mode.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): Recorded Telegram Test Server observations exercise the finalizer, shared recovery, and actual chat delivery through an isolated Gateway, showing private placeholders suppressed while answers, errors, and yields remain visible once; denial, cancellation, and reset controls remain quiet. Independent iMessage deployment logs corroborate the central finalizer repair.
  • proof: sufficient: Contributor real behavior proof is sufficient. Recorded Telegram Test Server observations exercise the finalizer, shared recovery, and actual chat delivery through an isolated Gateway, showing private placeholders suppressed while answers, errors, and yields remain visible once; denial, cancellation, and reset controls remain quiet. Independent iMessage deployment logs corroborate the central finalizer repair.
  • proof: telegram-e2e: This PR needs Telegram Test Server proof with the repository E2E skill. The PR changes visible Telegram fallback messages, and the supplied Test Server observations cover that behavior.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Josh Lehman: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • obviyus: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

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

History

Review history (7 earlier review cycles)
  • reviewed 2026-09-04T21:56:37.359Z sha f91d712 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-04T22:15:27.584Z sha a55ecc0 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-04T22:52:39.332Z sha a55ecc0 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-06T16:43:46.725Z sha c5d137f :: needs maintainer review before merge. :: none
  • reviewed 2026-09-08T14:00:44.932Z sha de28db7 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-08T14:24:03.974Z sha ee60c09 :: blocked before merge. :: none
  • reviewed 2026-09-08T14:42:41.714Z sha fceb8d1 :: needs maintainer review before merge. :: none

@razvangirgiz
razvangirgiz marked this pull request as ready for review September 4, 2026 22:06
@clawsweeper clawsweeper Bot added the proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. label Sep 4, 2026
@obviyus obviyus self-assigned this Sep 6, 2026
@openclaw-barnacle openclaw-barnacle Bot added channel: telegram Channel integration: telegram size: L and removed size: S labels Sep 6, 2026
@obviyus obviyus changed the title fix: keep settled-tool placeholders out of message-tool-only chats fix: keep tool-finalizer placeholders private in message-only groups Sep 6, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. labels Sep 6, 2026
@clawsweeper clawsweeper Bot added status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 6, 2026
@VACInc

VACInc commented Sep 6, 2026

Copy link
Copy Markdown
Member

Related merge: #140367 landed in main on September 6, 2026 (04081aa). It fixes entry into tool-free finalization after truncated completions streams and pre-tool commentary.

It intentionally reuses the existing recovered-answer and empty-finalizer fallback behavior. It does not implement the message-tool-only placeholder privacy, queued-delivery, or exactly-once delivery changes proposed here. The shared finalization area makes this related work, not a duplicate. Leaving this PR open.

@omarshahine

Copy link
Copy Markdown
Contributor

Production evidence from a maintainer deployment (macOS, OpenClaw 2026.9.1 ad6fe23, built-in openclaw harness, openai/gpt-5.6-terra via openai-chatgpt-responses, iMessage channel with messages.groupChat.visibleReplies: "message_tool").

Before this change (unpatched 2026.9.1). In a group chat where the agent is instructed to answer brief acknowledgements with a tapback only, every tapback-only turn entered settled-turn finalization and the synthetic sentence was delivered to the group. Three leaks in one evening:

2026-09-08T03:46:36.911Z settled-turn finalization completed without a visible answer … attempts=2/2 — using terminal fallback reply
2026-09-08T03:46:58Z  [group chat] "The tool run finished, but no final summary was produced. I did not repeat any completed actions."
2026-09-08T03:48:56.302Z … using terminal fallback reply   → delivered to the group
2026-09-08T03:50:21.962Z … using terminal fallback reply   → delivered to the group

The message-tool outcome for each of those runs was recorded as outcome: "mute" (react succeeded, no visible assistant text).

Patch applied. Only the settled-turn-finalization.ts hunk of this PR, backported by hand onto the installed 2026.9.1 bundle: gate markReplyPayloadForSourceSuppressionDelivery on finalizationOutcome === "answered", and blank finalAssistantVisibleText / finalAssistantRawText when the outcome is not answered and sourceReplyDeliveryMode === "message_tool_only". Gateway restarted.

After. The next message-tool-only turn in a different group (a fresh session, so it took the same finalization path) still reached the fallback in the log, and nothing was delivered:

2026-09-08T05:02:33.881Z settled post-tool turn lacked a final answer … running isolated finalization
2026-09-08T05:02:35.306Z settled-turn finalization completed without a visible answer … retrying 1/1 with tools disabled
2026-09-08T05:02:36.507Z settled-turn finalization completed without a visible answer … attempts=2/2 — using terminal fallback reply

The chat transcript for that window contains only the agent's intended message-tool send and the user's reactions. No placeholder, and no replacement diagnostic from stranded-reply recovery either, although note that the followup-delivery and stranded-reply hunks of this PR were not part of the backport, so that path is only exercised as it exists in 2026.9.1.

Observation that may help scope the fix: sessions created before the 2026.9.1 upgrade never enter settled-turn finalization on identical tapback-only calls (12 such mute runs, zero finalizations), while sessions created after it do every time. The leak therefore surfaces on any fresh message-tool-only group session.

The merged settled-turn-finalization.test.ts exceeds the 1000-line test
max-lines limit against current main. Move the
resolveSettledTurnFinalizationRequest cases to
terminal-resolution.settled-request.test.ts; no test changes.
# Conflicts:
#	src/agents/embedded-agent-runner/run/settled-turn-finalization.test.ts
@omarshahine
omarshahine merged commit 73ca607 into openclaw:main Sep 8, 2026
212 checks passed
@omarshahine

Copy link
Copy Markdown
Contributor

Merged via squash.

vincentkoc added a commit that referenced this pull request Sep 8, 2026
* commit '04869ae4899ad0524c3287759798362b0d62fef8': (677 commits)
  fix(release): pin Kova census refresh (#142104)
  fix: doctor read-only database inspections time out on large agent databases (#142179)
  docs: align v2026.9.3 framing with release announcement (#142307)
  fix(ui): discover models when default-model pickers open (#142105)
  fix(ci): keep Docker upgrade seed baseline older than target (#142273)
  refactor(tests): reuse named OAuth credential fixtures (#142272)
  fix(ci): keep mobile release helpers out of source checks (#142115)
  chore(ui): refresh control ui locales (#142147)
  fix(active-memory): explain why recall was skipped (#138658)
  fix(media): preserve converted images with HEIC filenames (#142263)
  docs: add v2026.9.3 release notes (#142277)
  fix(ui): retire picker focus listeners together (#142258)
  fix(ui): keep menu hover colors consistent across themes (#142243)
  fix(release): keep changelog credits within verified history (#142261)
  fix: keep tool-finalizer placeholders private in message-only groups (#138645)
  perf(tui): carry prepared URL membership through rendering (#142262)
  test(ui): await activity cache imports before teardown (#142282)
  fix(qa): align auth and Workshop proofs with runtime contracts (#142280)
  feat(xai): use one curated catalog and concrete setup default (#142136)
  refactor(outbound): reuse prepared sendability facts (#142252)
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 9, 2026
…penclaw#138645)

* fix: keep settled-tool placeholders out of message-tool-only chats

* test: consolidate private terminal completion coverage

* fix: preserve terminal delivery outcomes in message-only groups

* test: assert terminal payloads before inspecting metadata

* test(reply): cover queued provider failure delivery

* fix(reply): deliver terminal errors before source reply completes

* test(reply): preserve the active authority in queued failure fixture

* test(agents): keep yield context on its private callback

* test: cover heartbeat runs in terminal failure classification

* test: split settled-turn finalization request coverage into its own file

The merged settled-turn-finalization.test.ts exceeds the 1000-line test
max-lines limit against current main. Move the
resolveSettledTurnFinalizationRequest cases to
terminal-resolution.settled-request.test.ts; no test changes.

---------

Co-authored-by: Ayaan Zaidi <[email protected]>
Co-authored-by: Omar Shahine <[email protected]>
obviyus added a commit that referenced this pull request Oct 1, 2026
…ht after it (#162367)

Related: #110565, #115104, #119605

## What Problem This Solves

Fixes: a chat gets two nearly identical messages when a turn sends a progress update with `message(final=false)` and then ends without a final answer.

In our setup a group turn sent "started the run, I'll report back" as progress and stopped empty. Settled-turn finalization then made an extra model call, which restated the same progress, and both messages landed 12 s apart.

## User Impact

If the last thing a turn does is post progress to the current conversation and then it stops empty or with `NO_REPLY`, that progress message is the reply. No second model call, no duplicate. Turns that did more work after or alongside the progress, or that sent nothing, still get finalization.

## Why This Change Was Made

Provenance:

- Settled-turn finalization (#110565, closes #108738) exists so users are never left with no reply after tools ran but the model said nothing. Fallback text after an empty finalizer came later in #133520; #138645 keeps that fallback private in message-tool-only groups.
- `final:false` vs `final:true` (#105365, then the shared contract in #119605) keeps progress from ending a run early and keeps a later failure visible after progress.
- #115104 (fixing #111764) made marked progress *permit* finalization. #111764's caveat was progress sent early in a long tool run, followed by an empty final completion, which was swallowed silently. #127070 applied the same rule to queued follow-ups.

Root cause: none of these checks look at order. A progress message sent as the turn's **last** tool batch was written after the model had seen every other tool result. When the model then stops empty, the finalizer gets the same transcript and no new information, so all it can do is restate the progress. That is the duplicate. The #111764 case is different: there, tool work came after the progress, and that case is unchanged.

Fix: the decision happens when the runtime settles the attempt (`completeEmbeddedAttemptResult`), not per assistant message. The embedded subscriber only records, per provider turn (reset on `turn_start`), whether every tool that finished in that turn was a complete, non-error, non-partial `final:false` text send to the current source, and it keeps that fact for the latest turn that ran tools. At settlement, if that holds, the run ended normally (`terminal.kind === "ok"`), and the terminal assistant response stopped with empty text or `NO_REPLY`, the attempt result marks that latest progress send final and sets `sourceReplyDeliveryState: "delivered"`. Every downstream consumer (finalization gate, terminal resolution, follow-up delivery, run-entry terminal reply) then sees the same completed-reply fact an explicit `final:true` produces. No consumer special case, no prompt or tool-text change. Native-async fragments do not split a turn: an async send followed by a later tool turn, or async work and progress in the same response, still finalizes. Progress reactions, partial or errored sends, closing text, and work in the same batch keep today's behavior.

Options considered:
- Give the finalizer the sent text and accept `NO_REPLY`: this still costs a model call, depends on the model's judgment, and needs a new "empty finalizer is fine" path next to the #133520 fallback.
- Tighten the `final` tool description: models already end empty after progress, so this cannot guarantee anything.

Hermes (`agent/turn_empty_response.py`) handles this the same way. When an empty response follows visible content with only housekeeping tools after it, Hermes reuses that content as the final answer and marks it as already shown so it is not re-sent. It nudges once only when substantive tools ran after the content.

Scope: this changes only the embedded runner. Codex app-server turns can plausibly hit the same duplicate: Codex marks `final:false` in `dynamic-tools.ts` and can complete a turn with no agent message. But "nothing ran after the progress" there depends on item order across native Codex items (shell, apply_patch) that never pass through the OpenClaw dynamic-tool bridge. That makes the Codex event projector a separate owner, so it is a follow-up.

No overlap with Pash/Sarah changes: `a2bbcbf40684` and #154217 touch unrelated hunks in these files, and intentional `NO_REPLY` after a delivered message stays honored.

## Bounded cost

- The new path only removes a model call: when the latest tool batch was only complete progress sends and the model then stops empty, settled finalization is skipped (0 extra calls instead of up to 2).
- Every other path is unchanged: settled finalization keeps its existing cap of 2 tool-free attempts (`MAX_EMPTY_SETTLED_FINALIZATION_ATTEMPTS`, covered by `settled-turn-finalization.test.ts`). The finalizer has no tools, so it cannot send progress and cannot re-enter this path.
- The settlement check runs once per attempt result and does not schedule retries, runs, or model calls.
- Tested: `attempt-result.test.ts` drives the real `runAgentLoop` with the real subscriber, then the real `completeEmbeddedAttemptResult` and `resolveSettledToolTerminalContinuationInstruction`. Progress-last followed by an empty terminal gives a delivered reply and no finalizer. Two cases still finalize: an async progress send, then an empty tail, then a read, then an empty terminal; and async read plus progress in one response, then an empty terminal. Each failed on the head before its fix with `expected 'delivered' to be 'missing'`. The QA scenario asserts 2 model requests (no finalization request) for progress-then-empty and 3 for the write-then-empty control.

## Evidence

QA lab, mock-openai, isolated gateway child, qa-channel group with `visibleReplies: message_tool`. New scenario `group-progress-then-empty-finalization`:

- Before (origin/main + scenario): fail. The progress room got `["Started the run, I will report back. QA-GROUP-PROGRESS-OK", "Still running, I will report back. QA-GROUP-PROGRESS-OK"]`.
- After: pass. The progress room got 1 post and made 2 model requests (no finalization request). The control room (write, then empty stop, nothing sent) still ran finalization, made 3 model requests, and posted `QA-GROUP-WRITE-FINALIZED-OK` once.

Settlement regressions in `attempt-result.test.ts` (real agent loop): on the previous per-message head, the async-continuation case fails with `expected 'delivered' to be 'missing'`. Subscriber batch-fact table: only-progress is true; same-batch work, a later batch, a reaction, and a partial/errored send are false. Focused suites pass: attempt-result (43), suppression (32), tools handler, settled-tool evidence, settled-turn finalization, attempt-execution-phase, and lifecycle.

Real gateway (qa-channel, round 3 head): the scenario passes with 1 progress post and 2 requests, and the write control finalizes with 3 requests. The scenario is the only CI-runnable check of the consumer chain after the attempt result: run-loop finalization admission, terminal resolution, payload building, and channel delivery. The loop tests stop at the delivery fact, so a consumer that ignored it would still pass them, but here it would post a second message.

### Live model, Telegram Test Server group

Setup: a real user in the QA group, `messages.groupChat.visibleReplies: message_tool`, live OpenAI `gpt-5.5` through a pass-through proxy, isolated gateway. The prompt asked the model to post a `final:false` progress update saying the report run started and then stop. In both runs below the model did that unsteered: one successful `message(final:false)`, then an empty stop. In each run the bot's transient status draft (`Working`) appears and is deleted after delivery; that is existing progress-draft behavior and the same before and after.

| Run | Bot posts that remain | Model requests (main agent) | Finalizer |
|---|---|---|---|
| Before, origin/main `7dd6ab7` | 2: `Monthly report run has started — I’ll report back here when it finishes.` (t=13.1 s), then `Done.` (t=17.7 s) | 3 | ran (`settled post-tool turn lacked a final answer`) |
| After, `e27810b` | 1: `Monthly report run started. I’ll report back here when it finishes.` (t=13.8 s) | 2 | not run |

Control on `e27810b` (finalizer must still run after real work): the model posted `Checking the clock now.` with `final:false`, then ran `exec date -u`. The proxy replaced only the model's next response with an empty turn, which is the incident's "ends empty" shape; the finalizer request itself went to the live model. The finalizer ran and the group received `The UTC time is Thu Oct 1 13:08:11 UTC 2026.`

An earlier variant that told the model to end with `NO_REPLY` produced one post on both refs: on main the live finalizer also answered `NO_REPLY` twice, and the private fallback stayed private per #138645. Main still spent 2 extra model calls there; the fix spends none.

LOC vs merge base: production +47/-3 (`src/agents` subscriber + attempt-result), docs +5/-1, tests and QA fixtures +441.

Test cost (`pnpm test <file> --maxWorkers=1`, wall, head e27810b, shared loaded host): `attempt-result.test.ts` 46.4 s for 44 tests, with the 3 new real-loop cases at 0.2 to 0.6 s each; `embedded-agent-subscribe.subscribe-embedded-agent-session.source-reply-suppression.test.ts` 53.4 s for 32 tests, with the 5 batch-fact cases at 4 to 160 ms each. Most of the wall time is import and transform. The new cases use no timers, sleeps, or gateway boots. No attributable CI timing exists yet for this head.

CI on 959c8b0 (run 36873121248, after one rerun of failed jobs):
- `gateway-timeout-recovery-subagent.e2e.test.ts`: fails 2 of 2 locally on clean origin/main. Known flake #161139, with fixture fix #162260 open. The scenario never uses the message tool.
- `src/gateway/server.chat-steer-direct-command.test.ts` (skills watchers left open): fails the same way on four unrelated PRs today: `steipete/session-store-agent-db-drain`, `chore/chrome-devtools-mcp-1.10.1`, `chore/npm-12-1-20261001`, `codex/repair-child-completion`.
- `node-worker-launch-wire.e2e.test.ts` and `telegram-model-picker-prepared-gateway.e2e.test.ts`: red on the first attempt and green on rerun; both pass locally on head and on main.
- `src/auto-reply/reply/dispatch-from-config.secrets.test.ts` "quiet group link": still red. Only the file's first case fails, at its default 1 s `vi.waitFor`; that case took 1437 ms in CI while the following cases took about 60 ms. The same three-file shard passes locally on the head, on head merged with current main, with `CI=true`, and twice on main under `taskpolicy -b`. The test drives the `secrets` tool, which never touches the message-tool progress path, the new `turn_start` reset, or attempt-result settlement. I could not reproduce it on main or find it on another PR's CI from the last two days (93 failed node jobs scanned), so this one is not proven unrelated.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 2, 2026
…ht after it (openclaw#162367)

Related: openclaw#110565, openclaw#115104, openclaw#119605

## What Problem This Solves

Fixes: a chat gets two nearly identical messages when a turn sends a progress update with `message(final=false)` and then ends without a final answer.

In our setup a group turn sent "started the run, I'll report back" as progress and stopped empty. Settled-turn finalization then made an extra model call, which restated the same progress, and both messages landed 12 s apart.

## User Impact

If the last thing a turn does is post progress to the current conversation and then it stops empty or with `NO_REPLY`, that progress message is the reply. No second model call, no duplicate. Turns that did more work after or alongside the progress, or that sent nothing, still get finalization.

## Why This Change Was Made

Provenance:

- Settled-turn finalization (openclaw#110565, closes openclaw#108738) exists so users are never left with no reply after tools ran but the model said nothing. Fallback text after an empty finalizer came later in openclaw#133520; openclaw#138645 keeps that fallback private in message-tool-only groups.
- `final:false` vs `final:true` (openclaw#105365, then the shared contract in openclaw#119605) keeps progress from ending a run early and keeps a later failure visible after progress.
- openclaw#115104 (fixing openclaw#111764) made marked progress *permit* finalization. openclaw#111764's caveat was progress sent early in a long tool run, followed by an empty final completion, which was swallowed silently. openclaw#127070 applied the same rule to queued follow-ups.

Root cause: none of these checks look at order. A progress message sent as the turn's **last** tool batch was written after the model had seen every other tool result. When the model then stops empty, the finalizer gets the same transcript and no new information, so all it can do is restate the progress. That is the duplicate. The openclaw#111764 case is different: there, tool work came after the progress, and that case is unchanged.

Fix: the decision happens when the runtime settles the attempt (`completeEmbeddedAttemptResult`), not per assistant message. The embedded subscriber only records, per provider turn (reset on `turn_start`), whether every tool that finished in that turn was a complete, non-error, non-partial `final:false` text send to the current source, and it keeps that fact for the latest turn that ran tools. At settlement, if that holds, the run ended normally (`terminal.kind === "ok"`), and the terminal assistant response stopped with empty text or `NO_REPLY`, the attempt result marks that latest progress send final and sets `sourceReplyDeliveryState: "delivered"`. Every downstream consumer (finalization gate, terminal resolution, follow-up delivery, run-entry terminal reply) then sees the same completed-reply fact an explicit `final:true` produces. No consumer special case, no prompt or tool-text change. Native-async fragments do not split a turn: an async send followed by a later tool turn, or async work and progress in the same response, still finalizes. Progress reactions, partial or errored sends, closing text, and work in the same batch keep today's behavior.

Options considered:
- Give the finalizer the sent text and accept `NO_REPLY`: this still costs a model call, depends on the model's judgment, and needs a new "empty finalizer is fine" path next to the openclaw#133520 fallback.
- Tighten the `final` tool description: models already end empty after progress, so this cannot guarantee anything.

Hermes (`agent/turn_empty_response.py`) handles this the same way. When an empty response follows visible content with only housekeeping tools after it, Hermes reuses that content as the final answer and marks it as already shown so it is not re-sent. It nudges once only when substantive tools ran after the content.

Scope: this changes only the embedded runner. Codex app-server turns can plausibly hit the same duplicate: Codex marks `final:false` in `dynamic-tools.ts` and can complete a turn with no agent message. But "nothing ran after the progress" there depends on item order across native Codex items (shell, apply_patch) that never pass through the OpenClaw dynamic-tool bridge. That makes the Codex event projector a separate owner, so it is a follow-up.

No overlap with Pash/Sarah changes: `77fbaa7ae43d` and openclaw#154217 touch unrelated hunks in these files, and intentional `NO_REPLY` after a delivered message stays honored.

## Bounded cost

- The new path only removes a model call: when the latest tool batch was only complete progress sends and the model then stops empty, settled finalization is skipped (0 extra calls instead of up to 2).
- Every other path is unchanged: settled finalization keeps its existing cap of 2 tool-free attempts (`MAX_EMPTY_SETTLED_FINALIZATION_ATTEMPTS`, covered by `settled-turn-finalization.test.ts`). The finalizer has no tools, so it cannot send progress and cannot re-enter this path.
- The settlement check runs once per attempt result and does not schedule retries, runs, or model calls.
- Tested: `attempt-result.test.ts` drives the real `runAgentLoop` with the real subscriber, then the real `completeEmbeddedAttemptResult` and `resolveSettledToolTerminalContinuationInstruction`. Progress-last followed by an empty terminal gives a delivered reply and no finalizer. Two cases still finalize: an async progress send, then an empty tail, then a read, then an empty terminal; and async read plus progress in one response, then an empty terminal. Each failed on the head before its fix with `expected 'delivered' to be 'missing'`. The QA scenario asserts 2 model requests (no finalization request) for progress-then-empty and 3 for the write-then-empty control.

## Evidence

QA lab, mock-openai, isolated gateway child, qa-channel group with `visibleReplies: message_tool`. New scenario `group-progress-then-empty-finalization`:

- Before (origin/main + scenario): fail. The progress room got `["Started the run, I will report back. QA-GROUP-PROGRESS-OK", "Still running, I will report back. QA-GROUP-PROGRESS-OK"]`.
- After: pass. The progress room got 1 post and made 2 model requests (no finalization request). The control room (write, then empty stop, nothing sent) still ran finalization, made 3 model requests, and posted `QA-GROUP-WRITE-FINALIZED-OK` once.

Settlement regressions in `attempt-result.test.ts` (real agent loop): on the previous per-message head, the async-continuation case fails with `expected 'delivered' to be 'missing'`. Subscriber batch-fact table: only-progress is true; same-batch work, a later batch, a reaction, and a partial/errored send are false. Focused suites pass: attempt-result (43), suppression (32), tools handler, settled-tool evidence, settled-turn finalization, attempt-execution-phase, and lifecycle.

Real gateway (qa-channel, round 3 head): the scenario passes with 1 progress post and 2 requests, and the write control finalizes with 3 requests. The scenario is the only CI-runnable check of the consumer chain after the attempt result: run-loop finalization admission, terminal resolution, payload building, and channel delivery. The loop tests stop at the delivery fact, so a consumer that ignored it would still pass them, but here it would post a second message.

### Live model, Telegram Test Server group

Setup: a real user in the QA group, `messages.groupChat.visibleReplies: message_tool`, live OpenAI `gpt-5.5` through a pass-through proxy, isolated gateway. The prompt asked the model to post a `final:false` progress update saying the report run started and then stop. In both runs below the model did that unsteered: one successful `message(final:false)`, then an empty stop. In each run the bot's transient status draft (`Working`) appears and is deleted after delivery; that is existing progress-draft behavior and the same before and after.

| Run | Bot posts that remain | Model requests (main agent) | Finalizer |
|---|---|---|---|
| Before, origin/main `449f5a8` | 2: `Monthly report run has started — I’ll report back here when it finishes.` (t=13.1 s), then `Done.` (t=17.7 s) | 3 | ran (`settled post-tool turn lacked a final answer`) |
| After, `e27810b` | 1: `Monthly report run started. I’ll report back here when it finishes.` (t=13.8 s) | 2 | not run |

Control on `e27810b` (finalizer must still run after real work): the model posted `Checking the clock now.` with `final:false`, then ran `exec date -u`. The proxy replaced only the model's next response with an empty turn, which is the incident's "ends empty" shape; the finalizer request itself went to the live model. The finalizer ran and the group received `The UTC time is Thu Oct 1 13:08:11 UTC 2026.`

An earlier variant that told the model to end with `NO_REPLY` produced one post on both refs: on main the live finalizer also answered `NO_REPLY` twice, and the private fallback stayed private per openclaw#138645. Main still spent 2 extra model calls there; the fix spends none.

LOC vs merge base: production +47/-3 (`src/agents` subscriber + attempt-result), docs +5/-1, tests and QA fixtures +441.

Test cost (`pnpm test <file> --maxWorkers=1`, wall, head e27810b, shared loaded host): `attempt-result.test.ts` 46.4 s for 44 tests, with the 3 new real-loop cases at 0.2 to 0.6 s each; `embedded-agent-subscribe.subscribe-embedded-agent-session.source-reply-suppression.test.ts` 53.4 s for 32 tests, with the 5 batch-fact cases at 4 to 160 ms each. Most of the wall time is import and transform. The new cases use no timers, sleeps, or gateway boots. No attributable CI timing exists yet for this head.

CI on 959c8b0 (run 36873121248, after one rerun of failed jobs):
- `gateway-timeout-recovery-subagent.e2e.test.ts`: fails 2 of 2 locally on clean origin/main. Known flake openclaw#161139, with fixture fix openclaw#162260 open. The scenario never uses the message tool.
- `src/gateway/server.chat-steer-direct-command.test.ts` (skills watchers left open): fails the same way on four unrelated PRs today: `steipete/session-store-agent-db-drain`, `chore/chrome-devtools-mcp-1.10.1`, `chore/npm-12-1-20261001`, `codex/repair-child-completion`.
- `node-worker-launch-wire.e2e.test.ts` and `telegram-model-picker-prepared-gateway.e2e.test.ts`: red on the first attempt and green on rerun; both pass locally on head and on main.
- `src/auto-reply/reply/dispatch-from-config.secrets.test.ts` "quiet group link": still red. Only the file's first case fails, at its default 1 s `vi.waitFor`; that case took 1437 ms in CI while the following cases took about 60 ms. The same three-file shard passes locally on the head, on head merged with current main, with `CI=true`, and twice on main under `taskpolicy -b`. The test drives the `secrets` tool, which never touches the message-tool progress path, the new `turn_start` reset, or attempt-result settlement. I could not reproduce it on main or find it on another PR's CI from the last two days (93 failed node jobs scanned), so this one is not proven unrelated.

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

agents Agent runtime and tooling channel: telegram Channel integration: telegram P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants