Skip to content

fix(imessage): plain-send fallback for threaded replies + db-scoped recovery cursor (#99638) - #100446

Merged
omarshahine merged 2 commits into
mainfrom
fix/imessage-99638-reply-fallback-recovery-cursor
Jul 5, 2026
Merged

omarshahine merged 2 commits into
mainfrom
fix/imessage-99638-reply-fallback-recovery-cursor

Conversation

@omarshahine

@omarshahine omarshahine commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

Closes #99638

What Problem This Solves

Issue #99638 reported three failures on the dedicated bot-user / SSH-wrapped iMessage deployment. The primary one (every DM after the first failing with reply session initialization conflicted) was already fixed by #98835. This PR fixes the two remaining reported failures:

  • Threaded replies were dropped when the private-API bridge was unavailable. When a reply carried reply_to but only AppleScript transport was available, imsg hard-errored (reply_to requires bridge transport; ...) and OpenClaw rethrew, so the reply was lost — for both text and media replies.
  • Repointing dbPath silently stopped all inbound. The downtime-recovery cursor was keyed per account, not per database, and is monotonic. After pointing dbPath at a different chat.db with lower rowids (e.g. a fresh bot-user DB, max rowid ~15), the stale high-water (~12396) was still sent as since_rowid, so imsg replayed/emitted nothing and inbound was silently lost forever.

Why This Change Was Made

Both fixes stay entirely within extensions/imessage (no core or config-surface changes):

  • Plain-send fallback (send.ts): the send catch now detects the specific "threaded reply unsupported" error and, when a reply_to was set, retries the send once with reply_to stripped — delivering the message unthreaded instead of dropping it. This covers text and media replies alike (both carry reply_to through the same send path), keeps any attached file on the retry, and clears the reply id so the receipt reports the unthreaded send that was actually delivered. The match is a closed error class, so unrelated send failures still propagate.
  • DB-scoped recovery cursor (recovery-cursor.ts): the cursor is keyed per (account, database identity). The identity is derived from remoteHost / dbPath / custom cliPath, with local paths canonicalized (leading ~ expanded, then resolved) so the implicit default and an explicit path to the same chat.db map to one identity. A cursor recorded against a different database no longer seeds since_rowid, advance is monotonic only within the same database, and a pre-scoping (account-only) cursor is adopted once for the active database on upgrade so downtime replay still works. This is cache-class state (rebuilds safely via GUID dedupe), so no migration is required.

User Impact

  • On no-SIP / AppleScript-only deployments, text and media replies are delivered (unthreaded) instead of being silently dropped.
  • Changing dbPath (or moving to/from a remote host, or spelling the default path explicitly) no longer wedges inbound message delivery; recovery resumes from the correct database.

Evidence

Unit + integration tests — all green (92 passed across the 3 touched files):

node scripts/run-vitest.mjs \
  extensions/imessage/src/monitor/recovery-cursor.test.ts \
  extensions/imessage/src/send.test.ts \
  extensions/imessage/src/monitor.last-route.test.ts
 Test Files  3 passed (3)
      Tests  92 passed (92)

These exercise the exact runtime paths the fix changes:

  • send.test.ts: text and media replies that hit the upstream reply_to-unsupported error retry once with reply_to stripped, deliver the message/media unthreaded, and report a non-threaded receipt.
  • recovery-cursor.test.ts: cursor scoped per (account, database); ignores a cursor from a different database; re-scopes on advance without losing the other database's high-water; adopts a pre-scoping legacy cursor once for the active database; unifies the implicit default with explicit/~ spellings of the same chat.db; keeps distinct DBs/wrappers/remotes separate.
  • monitor.last-route.test.ts: existing downtime-recovery integration tests updated to the DB-scoped cursor (local + remote paths) and still passing.

Typecheck: pnpm tsgo:extensions and pnpm tsgo:extensions:test both clean.

Codex review (autoreview, gpt-5.5) run to clean over several rounds — it flagged and I fixed: legacy-cursor upgrade-drop, per-database cursor overwrite, custom-cliPath identity aliasing, unthreaded-fallback receipt accuracy, media-reply fallback coverage, and default-vs-explicit-path identity normalization. Final pass reports no actionable findings.

Live behavior proof (real two-Mac SSH deployment) — captured and posted in a PR comment:

  • Fallback: replicating the gateway's send RPC against the real imsg binary, reply_to + AppleScript transport returns the exact reply_to requires bridge transport; ... error, and the same send with reply_to stripped delivers (ok:true, transport:applescript). The PR performs that retry automatically.
  • Cursor: a real leftover pre-scoping (account-only) cursor {"lastRowid":6597} was adopted and re-scoped by the fixed gateway into a db-scoped composite key default\x00remote:<host>:.../chat.db; the persisted key embeds the database identity, and a repoint left it untouched while the new database started fresh.

Primary bug (#98835) also verified live for context: three sequential multi-turn DMs on the same SSH deployment all delivered replies with outcome=completed and zero reply session initialization conflicted.

🤖 Generated with Claude Code

@clawsweeper

clawsweeper Bot commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed July 5, 2026, 4:42 PM ET / 20:42 UTC.

Summary
The branch adds an iMessage RPC send retry that strips reply_to after an unsupported threaded-reply error and changes the downtime recovery cursor from account-only to account-plus-database identity with tests.

PR surface: Source +140, Tests +182. Total +322 across 6 files.

Reproducibility: yes. source-reproducible: current main rethrows the upstream reply_to unsupported send error and stores recovery cursor state by account only, while the linked report and PR comments provide real deployment evidence. I did not run a live macOS/iMessage repro in this read-only pass.

Review metrics: 1 noteworthy metric.

  • Persisted cursor keying: 1 key shape changed. The recovery cursor moves from account-only to account-plus-database identity, so upgrade and dbPath/remoteHost behavior need maintainer attention before merge.

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #99638
Summary: This PR is the candidate fix for the remaining iMessage threaded-reply fallback and recovery-cursor parts of the canonical report; a separate merged PR fixed the primary reply-session initialization conflict.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge readiness
Overall: 🐚 platinum hermit
Proof: 🦞 diamond lobster
Patch quality: 🐚 platinum hermit
Result: ready for maintainer review.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • none.

Risk before merge

  • [P1] Merging intentionally changes iMessage delivery semantics: AppleScript-only threaded replies fall back to unthreaded sends instead of failing, and legacy account-only recovery cursors are consumed into one database identity on first upgraded start.

Maintainer options:

  1. Accept live-proven iMessage behavior (recommended)
    Merge after maintainer review if the team accepts unthreaded fallback and db-scoped cursor adoption as the intended upgrade-safe behavior.
  2. Require maintainer topology proof
    Delay merge until a maintainer independently validates the two-Mac SSH/iMessage setup and confirms no delivery regression.
  3. Pause if the fallback policy is not desired
    Keep this PR unmerged if maintainers do not want AppleScript-only threaded replies to degrade to unthreaded sends by default.

Next step before merge

  • [P2] No narrow code repair remains; a maintainer needs to review and accept the protected, compatibility-sensitive iMessage delivery change.

Maintainer decision needed

  • Question: Should maintainers accept this live-proven iMessage unthreaded fallback and db-scoped recovery cursor behavior for merge?
  • Rationale: The code shape and proof are now strong, but fallback behavior and persisted cursor keying affect message delivery and upgrades, and the PR carries a protected maintainer label.
  • Likely owner: steipete — Recent adjacent iMessage runtime work makes steipete the best available owner for accepting or narrowing this compatibility-sensitive delivery change.
  • Options:
    • Accept the proven behavior (recommended): Approve this direction if maintainers are comfortable with unthreaded fallback as the delivery-preserving behavior and with one-time adoption of the legacy cursor into the active database identity.
    • Ask for maintainer-run proof: Keep the PR open until someone with the dedicated bot-user topology independently repeats the fallback and dbPath-repoint checks.
    • Narrow the behavior further: Request a smaller fallback/error match or different cursor migration shape if maintainers do not want this compatibility behavior as the default.

Security
Cleared: The diff stays in iMessage runtime and tests and does not add dependencies, workflows, package-resolution changes, secrets handling, or downloaded code execution.

Review details

Best possible solution:

Land after a maintainer accepts the compatibility-sensitive fallback and cursor-upgrade behavior and exact-head checks remain green.

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

Yes, source-reproducible: current main rethrows the upstream reply_to unsupported send error and stores recovery cursor state by account only, while the linked report and PR comments provide real deployment evidence. I did not run a live macOS/iMessage repro in this read-only pass.

Is this the best way to solve the issue?

Yes, this appears to be the best code shape: the fix stays inside the iMessage plugin boundary, covers text and media on the shared send path, and scopes cursor state to the watched database instead of adding config or a core shim.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 5e0504aa437e.

Label changes

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. The PR now includes redacted live output from a real two-Mac SSH iMessage deployment showing both after-fix changed behaviors.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR now includes redacted live output from a real two-Mac SSH iMessage deployment showing both after-fix changed behaviors.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: 📣 needs proof: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P1: This PR targets a documented iMessage deployment where replies and inbound recovery can be silently lost for real users.
  • merge-risk: 🚨 compatibility: The PR changes persisted iMessage recovery cursor keying and one-time legacy cursor adoption during upgrades or dbPath/remoteHost changes.
  • merge-risk: 🚨 message-delivery: The PR changes outbound reply fallback and inbound since_rowid recovery, both of which affect whether iMessage replies or missed inbound messages are delivered.
  • 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): The PR now includes redacted live output from a real two-Mac SSH iMessage deployment showing both after-fix changed behaviors.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR now includes redacted live output from a real two-Mac SSH iMessage deployment showing both after-fix changed behaviors.
Evidence reviewed

PR surface:

Source +140, Tests +182. Total +322 across 6 files.

View PR surface stats
Area Files Added Removed Net
Source 3 180 40 +140
Tests 3 209 27 +182
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 389 67 +322

What I checked:

  • Root policy read: Root AGENTS.md and extensions/AGENTS.md were read fully; the review applied plugin-boundary and compatibility-sensitive guidance for fallback behavior, persisted state, and channel delivery. (AGENTS.md:31, 5e0504aa437e)
  • Current main send gap: Current main sends reply_to through the RPC path and rethrows non-timeout send errors, so an upstream threaded-reply unsupported error still drops the reply. (extensions/imessage/src/send.ts:1057, 5e0504aa437e)
  • PR send fallback: The PR head retries the same send once with reply_to removed when the specific threaded-reply unsupported error is seen, preserving media files and clearing the effective reply id for receipts. (extensions/imessage/src/send.ts:1071, 3a233c860125)
  • Current main cursor gap: Current main stores the downtime recovery cursor by account only, matching the stale high-water failure mode reported when dbPath points at a different Messages database. (extensions/imessage/src/monitor/recovery-cursor.ts:28, 5e0504aa437e)
  • PR cursor scoping: The PR derives a database identity from remoteHost/dbPath/cliPath, keys cursor state by account plus database identity, and adopts a legacy account-only cursor once for the active database. (extensions/imessage/src/monitor/recovery-cursor.ts:68, 3a233c860125)
  • Live proof comment: The contributor posted redacted live output from a real two-Mac SSH iMessage deployment showing reply_to rejection followed by delivered plain send, plus legacy account-only cursor adoption and dbPath repoint behavior. (3a233c860125)

Likely related people:

  • omarshahine: Prior merged iMessage work touched outbound send transport and always-on inbound recovery, including the same send, monitor, recovery-cursor, docs, and config surfaces affected here. (role: recent iMessage send and recovery contributor; confidence: high; commits: bfccbc3fee9a, fc6400ede389; files: extensions/imessage/src/send.ts, extensions/imessage/src/send.test.ts, extensions/imessage/src/monitor/recovery-cursor.ts)
  • HOYALIM: Authored the merged iMessage DM media handoff work that shaped the media/file send path covered by the threaded-reply fallback. (role: media send-path contributor; confidence: medium; commits: 044f7f3790a0; files: extensions/imessage/src/send.ts, extensions/imessage/src/send.test.ts, extensions/imessage/src/monitor/deliver.ts)
  • steipete: Recent merged iMessage monitor and docs work touches adjacent runtime behavior and makes this the best available owner for the compatibility-sensitive merge-risk decision. (role: recent adjacent iMessage runtime contributor; confidence: medium; commits: c00d79a1d1f8; files: extensions/imessage/src/monitor/monitor-provider.ts, docs/channels/imessage.md)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

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.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.
Review history (2 earlier review cycles)
  • reviewed 2026-07-05T19:54:11.388Z sha f2fb769669deeff25102e427262eb7063d6d1f6e :: needs real behavior proof before merge. :: [P2] Retry media replies without reply_to as well
  • reviewed 2026-07-05T20:25:09.077Z sha 3a233c8 :: needs real behavior proof before merge. :: none

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. labels Jul 5, 2026
@omarshahine
omarshahine force-pushed the fix/imessage-99638-reply-fallback-recovery-cursor branch from f2fb769 to 3a233c8 Compare July 5, 2026 20:14
@omarshahine

Copy link
Copy Markdown
Contributor Author

Addressed the review (head 3a233c8601):

  • [P2] Retry media replies without reply_to as well — the fallback no longer gates on !filePath. It now covers text and media replies (both carry reply_to through the same send path); the retry keeps any attached file and delivers it unthreaded, and the receipt reports the unthreaded send. New test: resends a media reply unthreaded when threaded replies are unsupported (#99638).
  • Local identity normalization (found in the follow-up Codex pass) — the recovery-cursor DB identity now canonicalizes local paths (expands a leading ~, then resolves) and maps the implicit default to the same concrete chat.db path an explicit config would spell, so switching between implicit and explicit default no longer drops the cursor and skips downtime rows.

92 unit + integration tests green across the touched files, pnpm tsgo:extensions / :test clean, and a fresh Codex autoreview reports no actionable findings. PR body updated with the expanded evidence.

The two behaviors here are transport-error and persisted-cursor paths, proven deterministically by tests that drive the real imsg RPC rejection and the cross-database cursor scoping; the primary conflict fix (#98835) was additionally verified live on the two-Mac SSH deployment. Happy to add a live AppleScript-only fallback + dbPath-repoint capture if that's required for the proof gate.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Jul 5, 2026
@omarshahine

Copy link
Copy Markdown
Contributor Author

Live behavior proof (real deployment)

Captured on a real two-Mac SSH deployment: the fixed gateway on one Mac driving imsg on a second Mac over the SSH wrapper, against that Mac's live Messages database. Phone number and bot-user host/path redacted.

1. AppleScript-only threaded-reply fallback (send.ts)

Replicated the exact send RPC the gateway issues, against the real imsg binary on the deployment:

reply_to + AppleScript transport → imsg rejects (the exact error the fallback keys on):

req:  send {"to":"+1XXX","service":"auto","transport":"applescript","reply_to":"<inbound-guid>","text":"..."}
resp: {"error":{"code":-32602,"data":"reply_to requires bridge transport; AppleScript fallback cannot send threaded replies","message":"Invalid params"}}

Same send, reply_to stripped (what the fallback retries) → delivered:

resp: {"result":{"ok":true,"message_id":"A6CB8877-…","transport":"applescript","id":6610,"service":"iMessage"}}

Before this PR, the first error propagated and the reply was dropped. The PR catches that exact error class and performs the second send automatically — now for text and media replies (unit tests: resends unthreaded when the transport cannot deliver a threaded reply, resends a media reply unthreaded …).

2. DB-scoped recovery cursor (recovery-cursor.ts)

Real persisted state left by an earlier run held a pre-scoping, account-only cursor:

key = 'default'                          value = {"lastRowid":6597}

Starting the fixed gateway pointed at the Messages DB adopted and re-scoped it (the legacy account-only key was consumed):

key = 'default\x00remote:<host>:/Users/<botuser>/Library/Messages/chat.db'   value = {"lastRowid":6610}

The persisted key now embeds the database identity, so a different dbPath resolves to a different key and cannot inherit this high-water. Repointing dbPath to a second database and restarting left this cursor untouched (retained per-database) and started the new database from a fresh cursor — no stale since_rowid reuse. The reporter's exact low-rowid repoint (advance to a high rowid on db-a, then db-b sees null → uses db-b's own watermark) is covered deterministically in recovery-cursor.test.ts and the monitor.last-route.test.ts integration tests that drive the real monitor.

Both remaining #99638 items are now verified live and by test; pnpm tsgo:extensions/:test clean and Codex autoreview reports no actionable findings.

@omarshahine

Copy link
Copy Markdown
Contributor Author

Live AppleScript-only fallback + dbPath-repoint proof added above, and PR body updated. @clawsweeper re-review

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 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 Jul 5, 2026
@omarshahine
omarshahine merged commit 91f5a65 into main Jul 5, 2026
146 of 156 checks passed
@omarshahine
omarshahine deleted the fix/imessage-99638-reply-fallback-recovery-cursor branch July 5, 2026 21:58
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 6, 2026
…ecovery cursor (openclaw#99638) (openclaw#100446)

* fix(imessage): retry unthreaded when a threaded reply is unsupported (openclaw#99638)

* fix(imessage): scope downtime-recovery cursor to the watched database (openclaw#99638)

---------

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

Labels

channel: imessage Channel integration: imessage maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M 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.

iMessage: every DM after the first fails with 'reply session initialization conflicted' (dedicated bot-user SSH deployment)

1 participant