Repository navigation
feat(android): durable offline chat with attachments and history-proof retirement - #104089
Conversation
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4e4f9a05c4
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| item: ChatOutboxItem, | ||
| attachments: List<OutgoingAttachment>, | ||
| ) { | ||
| if (normalizeRequestedSessionKey(item.sessionKey) != _sessionKey.value) return |
There was a problem hiding this comment.
Keep ownership for hidden flushed sends
When the outbox flush dispatches a row for a session other than the one currently open, this return skips adding the row id to any pending/unresolved ownership. Accepted rows without local ownership are treated as blockers, and handleChatEvent ignores terminal events for non-current sessions, so if that hidden-session run is still in flight during the two immediate history probes, the row stays Accepted and later queued rows in the same session never flush until the user opens that session or reconnects. Please track non-UI run ownership or otherwise reconcile hidden-session completions before returning here.
Useful? React with 👍 / 👎.
|
Codex review: needs changes before merge. Reviewed July 11, 2026, 1:08 AM ET / 05:08 UTC. Summary PR surface: Docs +1, Other +2317. Total +2318 across 13 files. Reproducibility: yes. Source inspection gives a high-confidence concurrency path: render Delete for a queued row, let reconnect flush claim queued-to-sending, then execute the already-captured Delete callback while the claimed send continues. Review metrics: 2 noteworthy metrics.
Stored data model Root-cause cluster Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Merge readiness Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch. Rank-up moves:
Risk before merge
Maintainer options:
Copy recommended automerge instructionNext step before merge
Security Review findings
Review detailsBest possible solution: Make user deletion a queued-or-failed compare-and-set operation that loses once dispatch claims the row, while preserving canonical-history reconciliation for every request that entered the transport. Do we have a high-confidence way to reproduce the issue? Yes. Source inspection gives a high-confidence concurrency path: render Delete for a queued row, let reconnect flush claim queued-to-sending, then execute the already-captured Delete callback while the claimed send continues. Is this the best way to solve the issue? No, not in its current form. Journal-all admission and canonical-history retirement are the correct maintainable design, but deletion must participate in the same atomic state transition as dispatch so ownership cannot disappear mid-send. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against b09f9b0482fa. Label changesLabel justifications:
Evidence reviewedPR surface: Docs +1, Other +2317. Total +2318 across 13 files. View PR surface stats
Acceptance criteria:
What I checked:
Likely related people:
What the crustacean ranks mean
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
Review history (1 earlier review cycle)
|
…f retirement Every chat send is journaled to the per-gateway Room outbox before any network attempt, so process death always has one durable recovery owner. Rows survive gateway ACKs as 'accepted' and retire only once the turn is proven in canonical chat.history by idempotency key; ambiguous outcomes (lost ACK, kill mid-send, gateway restart before the transcript write) park as delivery-unconfirmed for explicit retry, per the fail-closed model #103273 landed. An unproven accepted head briefly holds only its own session's queue, and retrying a parked head re-orders still-queued successors behind it. Offline sends now accept picked images and voice notes; attachment bytes persist as chunked BLOBs (512 KB chunks, 8 MB per message, 48 MB per gateway) admitted and retired atomically with their row. Pre-hello 'main' rows pin to the canonical session at first dispatch so later default-agent changes cannot retarget captured input; slash commands are connection-gated by a persisted epoch (legacy queued command rows migrate to a never-matching sentinel) and never auto-replay across reconnects. The Room store moves to schema v4 on top of v3's data-parking migration, adding the epoch column and attachment tables while preserving queued rows. The queued->sending claim is an atomic compare-and-set shared by the direct dispatch and the flush loop, the direct path waits for the startup recovery sweep before claiming, and failed reconnect attempts republish outbox rows so queued sends stay visible on offline cold starts. Proof: 1151 Android unit tests and :app:ktlintCheck green (new migration, storage, and controller coverage for admission, restarts, claims, pinning, gating, ordering, and byte round-trips); a live emulator scenario on the pre-integration build queued text+image offline, survived force-stop plus a device reboot, resent exactly once on reconnect (single <rowId>:user turn in the gateway transcript), and drained the outbox after canonical-history confirmation. Closes #104087.
The direct send's network phase now runs in the controller scope, so a cancelled UI scope (leaving the chat screen mid-send) can no longer strand a claimed row in 'sending' with no user action available; the dispatch completes and settles the row exactly once. Direct-path state persistence failures also re-arm the startup recovery sweep, mirroring the flush path's fail-closed handling.
A direct-send claim that fails to persist no longer reads as a lost race: the admitted row is handed to the flush lane so a healthy connection still delivers it, and the flush path's fail-closed handling owns any repeated storage failure instead of the UI reporting success with no active owner.
…ery send path The direct dispatch now rechecks a slash command's connection epoch after its durable claim, so a reconnect between admission and dispatch parks the command instead of replaying it on the new connection. Parking a stale gated row only counts once the write persists; a storage failure drops health, re-arms recovery, and halts the flush pass instead of spinning or dispatching the stale row.
…hip checks A chat.send ACK can return a run id that differs from the row's idempotency key (the direct path transfers local run ownership to it). Ownership, in-flight, backlog, and timeout-park checks now consider both ids, so reconciliation can no longer park — and Retry can no longer duplicate — a turn that is still running on the gateway.
…aps in the outbox Flushed sends acked under a divergent run id now transfer local run ownership like the direct path, so live runs cannot time out and surface spurious errors for delivered turns. A session pin that cannot persist stops the dispatch while the row is still safely queued. Reconcile and timeout parking only report changes their writes actually persisted, failing closed on storage errors.
1bb30d3 to
b1aaa64
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b1aaa64be7
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if (journaled.gatedEpoch != null && journaled.gatedEpoch != currentCacheScope()?.connectionGeneration) { | ||
| // A reconnect landed between admission and this claim; command-shaped input never | ||
| // auto-replays across connection epochs, so the claimed row parks for explicit retry. | ||
| persistJournaledSendState(journaled, ChatOutboxStatus.Failed, OUTBOX_CONNECTION_CHANGED_ERROR) |
There was a problem hiding this comment.
Re-check the connection epoch at send time
When a slash-command row is claimed while healthy, this is the last epoch check before dispatch; the later chat.send is only bound to the stable gateway id, and GatewaySession.readyConnection accepts any ready connection with that same id. If the gateway reconnects after this check but before the request selects a connection, the command is sent on the new connection instead of being parked as connection changed, which defeats the new manual-retry protection for slash commands. Re-check the captured epoch immediately around the actual send (the flush path has the same stable-id-only request gap).
Useful? React with 👍 / 👎.
|
Merged via squash.
|
…f retirement (openclaw#104089) * feat(android): durable offline chat with attachments and history-proof retirement Every chat send is journaled to the per-gateway Room outbox before any network attempt, so process death always has one durable recovery owner. Rows survive gateway ACKs as 'accepted' and retire only once the turn is proven in canonical chat.history by idempotency key; ambiguous outcomes (lost ACK, kill mid-send, gateway restart before the transcript write) park as delivery-unconfirmed for explicit retry, per the fail-closed model openclaw#103273 landed. An unproven accepted head briefly holds only its own session's queue, and retrying a parked head re-orders still-queued successors behind it. Offline sends now accept picked images and voice notes; attachment bytes persist as chunked BLOBs (512 KB chunks, 8 MB per message, 48 MB per gateway) admitted and retired atomically with their row. Pre-hello 'main' rows pin to the canonical session at first dispatch so later default-agent changes cannot retarget captured input; slash commands are connection-gated by a persisted epoch (legacy queued command rows migrate to a never-matching sentinel) and never auto-replay across reconnects. The Room store moves to schema v4 on top of v3's data-parking migration, adding the epoch column and attachment tables while preserving queued rows. The queued->sending claim is an atomic compare-and-set shared by the direct dispatch and the flush loop, the direct path waits for the startup recovery sweep before claiming, and failed reconnect attempts republish outbox rows so queued sends stay visible on offline cold starts. Proof: 1151 Android unit tests and :app:ktlintCheck green (new migration, storage, and controller coverage for admission, restarts, claims, pinning, gating, ordering, and byte round-trips); a live emulator scenario on the pre-integration build queued text+image offline, survived force-stop plus a device reboot, resent exactly once on reconnect (single <rowId>:user turn in the gateway transcript), and drained the outbox after canonical-history confirmation. Closes openclaw#104087. * fix(android): rearm outbox recovery when direct-send state persistence fails * fix(android): keep direct dispatch alive across caller cancellation The direct send's network phase now runs in the controller scope, so a cancelled UI scope (leaving the chat screen mid-send) can no longer strand a claimed row in 'sending' with no user action available; the dispatch completes and settles the row exactly once. Direct-path state persistence failures also re-arm the startup recovery sweep, mirroring the flush path's fail-closed handling. * fix(android): hand claim-persistence failures to the flush lane A direct-send claim that fails to persist no longer reads as a lost race: the admitted row is handed to the flush lane so a healthy connection still delivers it, and the flush path's fail-closed handling owns any repeated storage failure instead of the UI reporting success with no active owner. * fix(android): enforce connection gating and fail-closed parking on every send path The direct dispatch now rechecks a slash command's connection epoch after its durable claim, so a reconnect between admission and dispatch parks the command instead of replaying it on the new connection. Parking a stale gated row only counts once the write persists; a storage failure drops health, re-arms recovery, and halts the flush pass instead of spinning or dispatching the stale row. * fix(android): recognize gateway-acknowledged run ids in outbox ownership checks A chat.send ACK can return a run id that differs from the row's idempotency key (the direct path transfers local run ownership to it). Ownership, in-flight, backlog, and timeout-park checks now consider both ids, so reconciliation can no longer park — and Retry can no longer duplicate — a turn that is still running on the gateway. * fix(android): close remaining ack-ownership and persistence-failure gaps in the outbox Flushed sends acked under a divergent run id now transfer local run ownership like the direct path, so live runs cannot time out and surface spurious errors for delivered turns. A session pin that cannot persist stops the dispatch while the row is still safely queued. Reconcile and timeout parking only report changes their writes actually persisted, failing closed on storage errors. * docs(android): record why acknowledged run ids stay in-memory
What Problem This Solves
Android chat could lose or duplicate submitted user input around process death and reconnects, and offline sends with attachments were rejected outright. Closes #104087.
Confirmed on
mainbefore this change:chat.sendACK. The gateway ACKsstatus:"started"before the user turn is written ([Bug] WebChat: optimistic USER messages are lost (not just hidden) when chat.send returns before the durable transcript lands — full-replace history reconcile drops them #86946), and its idempotency dedupe is an in-memory 5-minute map, so delete-on-ACK loses input on a gateway crash and blind replay can duplicate agent runs.mainrows re-resolved against current defaults at every flush, so a default-agent change could redirect captured input.v2026.7.1-beta.3) holds queued user input: schema bumps dropped unsent messages.Why This Change Was Made
Bring Android to the durability bar iOS (
OpenClawKitoutbox) and web (#102781) already ship, with an Android-native design that matches the verified gateway contract: only achat.historyrow carryingidempotencyKey = "<rowId>:user"proves delivery; an ACK proves nothing durable.Design highlights:
chat.sendidempotency key across every retry and restart.accepted; only canonical-history proof deletes them (late proof also retires parked rows, so a manual retry can never double-send a delivered turn). Ambiguous outcomes — crash mid-send, lost ACK, gateway restart before the transcript write, timeout without proof after a double-read — park asdelivery unconfirmedfor explicit Retry/Delete. An ambiguous row blocks only its own session's queue; retrying it keeps queued same-session successors behind it.mainrows resolve exactly once, at first dispatch, and are pinned; later default-agent changes never retarget captured input.connection changed; retry manually) instead of auto-replaying across reconnects.docs/platforms/android.md), matching iOS and web.Builds on the reviewed fail-closed ambiguous-delivery model from #103862 (its head commit is cherry-picked as the first commit of this branch, with authorship preserved); landing this supersedes #103862 and #103273.
User Impact
Sending a chat message on Android now survives app kills, device reboots, gateway restarts, and reconnects: it is either visible in canonical history exactly once, or visibly parked with explicit Retry/Delete. Offline composing now works with images and voice notes, with bounded on-device storage and actionable queue/storage-full errors that never eat the draft. Queued input survives app upgrades.
Evidence
:app:testPlayDebugUnitTest1135 tests, 0 failures and:app:ktlintCheckclean (local run of the CI lane command; new coverage: Room v2/v1 migration fixtures built from shipped DDL, attachment byte round-trip across reopen, both storage caps with recovery-after-delete, cascade deletes, gated-epoch persistence, retry ordering, restart-orphan confirm-vs-park, not-enqueued direct sends, per-session ambiguity blocking, queue-full draft preservation)."idempotencyKey":"aba661c2-f3c6-407e-9e85-5392779b1880:user"row in the session JSONL, matching the on-device Room row id; device DB after confirmation:0outbox commands /0attachments /0chunks.onDisconnectedand verified live.