Skip to content

client: Persist draft messages optimistically and on draft events - #6625

Open
gpunto wants to merge 3 commits into
developfrom
fix/draft-events-write-through-to-database
Open

client: Persist draft messages optimistically and on draft events#6625
gpunto wants to merge 3 commits into
developfrom
fix/draft-events-write-through-to-database

Conversation

@gpunto

@gpunto gpunto commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Goal

Stop draft messages from being lost when a request does not complete, and from reappearing after they have been deleted.

Closes AND-1373

Contributes to #6388

Implementation

Aligns three gaps with the iOS SDK (DraftMessagesRepository, DraftUpdaterMiddleware):

  • Create and delete are optimistic. New onCreateDraftMessageRequest / onDeleteDraftMessagesRequest listener hooks, dispatched from doOnStart, so the local write no longer waits for the response and survives a process death mid-request.
  • Result handlers no longer roll back. Success stores the server copy, failure leaves the local draft as is. Previously a permanent create error dropped the draft and a permanent delete error kept it forever.
  • Draft events reach the database. draft.updated / draft.deleted only touched MutableGlobalState, so a draft deleted on another device left its Room row behind and SyncManager re-pushed it on every reconnect. draft.deleted has an empty message id, so deletion keys on cid (or parentId for threads), which needed a new DAO query.

No public API change: neither DraftMessageListener nor MessageRepository is in the API dump.

Testing

Two emulators against the demo backend:

  • Draft deleted on a second device: reappeared after restart on develop, now stays gone.
  • Create and delete failing with an injected 403: draft is kept / removed respectively, and survives a restart.

Unit tests cover both precommit paths and the channel and thread cases for draft.deleted.

Summary by CodeRabbit

  • New Features
    • Added draft message lifecycle callbacks for creation and deletion requests.
    • Drafts now update local state and offline storage immediately when created or deleted.
    • Added support for deleting both channel drafts and thread drafts.
    • Draft update and deletion events now synchronize local state and storage.
  • Bug Fixes
    • Improved draft consistency during request failures by preserving optimistic local changes.
  • Tests
    • Expanded coverage for draft events, persistence, callbacks, and channel/thread draft handling.

@gpunto gpunto added the pr:bug Bug fix label Aug 7, 2026
@github-actions

github-actions Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

PR checklist ✅

All required conditions are satisfied:

  • Title length is OK (or ignored by label).
  • At least one pr: label exists.
  • Sections ### Goal, ### Implementation, and ### Testing are filled, or the PR is bot-authored.
  • An issue is linked (Linear ticket or GitHub issue), or the PR is bot-authored.

🎉 Great job! This PR is ready for review.

@github-actions

github-actions Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

SDK Size Comparison 📏

SDK Before After Difference Status
stream-chat-android-client 5.96 MB 5.96 MB 0.00 MB 🟢
stream-chat-android-ui-components 11.25 MB 11.26 MB 0.01 MB 🟢
stream-chat-android-compose 12.74 MB 12.74 MB 0.00 MB 🟢

@gpunto
gpunto force-pushed the fix/draft-events-write-through-to-database branch 3 times, most recently from d293859 to 536adab Compare August 10, 2026 07:42
@gpunto
gpunto force-pushed the fix/draft-events-write-through-to-database branch from 4ec056e to 5241e1d Compare August 10, 2026 08:34
@gpunto
gpunto marked this pull request as ready for review August 10, 2026 08:54
@gpunto
gpunto requested a review from a team as a code owner August 10, 2026 08:54
@gpunto
gpunto enabled auto-merge August 10, 2026 08:54
@coderabbitai

coderabbitai Bot commented Aug 10, 2026

Copy link
Copy Markdown

Review Change Stack

Walkthrough

Draft creation and deletion now notify plugins before results, update local state and offline storage optimistically, and support channel or thread draft deletion. Draft events update offline storage. Tests cover callbacks, persistence, event handling, and isolation.

Changes

Draft message flow

Layer / File(s) Summary
Request callbacks and API wiring
stream-chat-android-client/src/main/java/io/getstream/chat/android/client/plugin/..., stream-chat-android-client/src/main/java/io/getstream/chat/android/client/ChatClient.kt, stream-chat-android-client/src/test/java/io/getstream/chat/android/client/ChatClientDraftsApiTests.kt
Draft create and delete requests now invoke plugin callbacks before result callbacks. Tests verify callback order and arguments.
Optimistic state and database updates
stream-chat-android-client/src/main/java/io/getstream/chat/android/client/internal/.../DraftMessageListener*.kt, stream-chat-android-client/src/test/java/io/getstream/chat/android/client/internal/.../DraftMessageListener*Test.kt
Create requests insert drafts immediately. Delete requests remove drafts immediately. Result handling no longer rolls back these request-time changes.
Draft deletion routing and event synchronization
stream-chat-android-client/src/main/java/io/getstream/chat/android/client/internal/offline/repository/..., stream-chat-android-client/src/main/java/io/getstream/chat/android/client/internal/state/event/..., stream-chat-android-client/src/main/java/io/getstream/chat/android/client/persistance/repository/..., stream-chat-android-client/src/test/java/io/getstream/chat/android/client/internal/...
Repositories and DAOs delete channel or thread drafts by location. Draft update and delete events update local state and storage. Integration tests cover retrieval, deletion, and draft isolation.
Draft event fixtures
stream-chat-android-client-test/src/main/java/io/getstream/chat/android/client/test/Mother.kt
Test factories now create draft update and deletion events.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Suggested reviewers: aleksandar-apostolov

Poem

A rabbit taps “send” with a hop and a cheer,
Drafts bloom in local burrows before results appear.
Threads and channels each follow their trail,
Updates persist while deletions prevail.
Plugins speak first, then responses arrive—
Spring-green draft logic keeps storage alive.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 17.31% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main changes: optimistic draft persistence and handling of draft events.
Description check ✅ Passed The description covers the goal, implementation, issue links, testing, and relevant behavior; omitted UI and checklist sections are non-critical for this non-UI change.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/draft-events-write-through-to-database

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
stream-chat-android-client/src/main/java/io/getstream/chat/android/client/plugin/listeners/DraftMessageListener.kt (1)

40-44: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Add default implementations for DraftMessageListener.

The existing direct listeners are already updated, but adding no-op bodies to the new DraftMessageListener methods still protects external Kotlin implementations that extend only this interface.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@stream-chat-android-client/src/main/java/io/getstream/chat/android/client/plugin/listeners/DraftMessageListener.kt`
around lines 40 - 44, Add no-op default method bodies to the methods declared by
DraftMessageListener, including onCreateDraftMessageRequest, so external Kotlin
implementations can implement only the callbacks they need. Preserve the
existing method signatures and behavior of direct listeners.

Source: Coding guidelines

stream-chat-android-client/src/test/java/io/getstream/chat/android/client/internal/state/event/handler/internal/EventHandlerSequentialTest.kt (1)

356-375: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a thread draft state assertion.

This test verifies repository routing only. Seed the thread draft in MutableGlobalState, then assert that the thread draft state is empty after handleEvents. This validates the local-state half of thread deletion.

As per coding guidelines, “add or refresh tests for changed behavior.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@stream-chat-android-client/src/test/java/io/getstream/chat/android/client/internal/state/event/handler/internal/EventHandlerSequentialTest.kt`
around lines 356 - 375, Update the test around EventHandlerSequentialTest’s
thread DraftMessageDeletedEvent case to seed the thread draft in
MutableGlobalState before handling the event, then assert that the corresponding
thread draft state is empty afterward. Retain the existing repository
deleteDraftMessage verification so both local-state removal and repository
routing are covered.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@stream-chat-android-client/src/main/java/io/getstream/chat/android/client/internal/state/plugin/listener/internal/DraftMessageListenerState.kt`:
- Around line 66-67: The draft create-result handlers can restore a draft after
a later delete; enforce per-draft mutation ordering or deletion tombstones
before applying successful create results. Update DraftMessageListenerState.kt
lines 66-67 and DraftMessageListenerDatabase.kt lines 64-65 so server drafts are
applied or persisted only when no later delete exists, and add deterministic
coverage for create, delete, then delayed successful create.

In
`@stream-chat-android-client/src/main/java/io/getstream/chat/android/client/plugin/listeners/DraftMessageListener.kt`:
- Around line 33-39: Correct the KDoc for the delete operation near
DraftMessageListener by replacing update-related wording with deletion-specific
descriptions, and remove duplicated “the” wording in the channel ID
documentation. Ensure the parameter and operation descriptions consistently
describe deleting a draft message.

---

Nitpick comments:
In
`@stream-chat-android-client/src/main/java/io/getstream/chat/android/client/plugin/listeners/DraftMessageListener.kt`:
- Around line 40-44: Add no-op default method bodies to the methods declared by
DraftMessageListener, including onCreateDraftMessageRequest, so external Kotlin
implementations can implement only the callbacks they need. Preserve the
existing method signatures and behavior of direct listeners.

In
`@stream-chat-android-client/src/test/java/io/getstream/chat/android/client/internal/state/event/handler/internal/EventHandlerSequentialTest.kt`:
- Around line 356-375: Update the test around EventHandlerSequentialTest’s
thread DraftMessageDeletedEvent case to seed the thread draft in
MutableGlobalState before handling the event, then assert that the corresponding
thread draft state is empty afterward. Retain the existing repository
deleteDraftMessage verification so both local-state removal and repository
routing are covered.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: cb36cdad-1957-4434-b80c-8fc36492f13d

📥 Commits

Reviewing files that changed from the base of the PR and between a111c2c and 5241e1d.

📒 Files selected for processing (17)
  • stream-chat-android-client-test/src/main/java/io/getstream/chat/android/client/test/Mother.kt
  • stream-chat-android-client/src/main/java/io/getstream/chat/android/client/ChatClient.kt
  • stream-chat-android-client/src/main/java/io/getstream/chat/android/client/internal/offline/plugin/listener/internal/DraftMessageListenerDatabase.kt
  • stream-chat-android-client/src/main/java/io/getstream/chat/android/client/internal/offline/repository/domain/message/internal/DatabaseMessageRepository.kt
  • stream-chat-android-client/src/main/java/io/getstream/chat/android/client/internal/offline/repository/domain/message/internal/MessageDao.kt
  • stream-chat-android-client/src/main/java/io/getstream/chat/android/client/internal/state/event/handler/internal/EventHandlerSequential.kt
  • stream-chat-android-client/src/main/java/io/getstream/chat/android/client/internal/state/plugin/listener/internal/DraftMessageListenerState.kt
  • stream-chat-android-client/src/main/java/io/getstream/chat/android/client/persistance/repository/MessageRepository.kt
  • stream-chat-android-client/src/main/java/io/getstream/chat/android/client/persistance/repository/noop/NoOpMessageRepository.kt
  • stream-chat-android-client/src/main/java/io/getstream/chat/android/client/plugin/Plugin.kt
  • stream-chat-android-client/src/main/java/io/getstream/chat/android/client/plugin/listeners/DraftMessageListener.kt
  • stream-chat-android-client/src/test/java/io/getstream/chat/android/client/ChatClientDraftsApiTests.kt
  • stream-chat-android-client/src/test/java/io/getstream/chat/android/client/internal/offline/plugin/listener/internal/DraftMessageListenerDatabaseTest.kt
  • stream-chat-android-client/src/test/java/io/getstream/chat/android/client/internal/offline/repository/DraftMessageRepositoryIntegrationTest.kt
  • stream-chat-android-client/src/test/java/io/getstream/chat/android/client/internal/state/channel/controller/attachment/UploadAttachmentsIntegrationTests.kt
  • stream-chat-android-client/src/test/java/io/getstream/chat/android/client/internal/state/event/handler/internal/EventHandlerSequentialTest.kt
  • stream-chat-android-client/src/test/java/io/getstream/chat/android/client/internal/state/plugin/listener/internal/DraftMessageListenerStateTest.kt

@sonarqubecloud

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
78.6% Coverage on New Code (required ≥ 80%)

See analysis details on SonarQube Cloud

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr:bug Bug fix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant