Skip to content

Commit f050a66

Browse files
committed
fix(native): review: a reload read before a send does not apply, a later start writes changes a lock kept, a successful settle is not cancellable
1 parent 46cfe69 commit f050a66

5 files changed

Lines changed: 36 additions & 5 deletions

File tree

‎README.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1114,7 +1114,7 @@ node --no-warnings native/tools/golden/generate-editor.mjs native/shared/src/com
11141114

11151115
#### Drafts and schedules
11161116

1117-
- Local draft per account, reply drafts per parent. The quick reply sheet and the editor's reply mode share the slot; the sheet's model is kept app-wide (see the post screen), so whenever the editor's reply mode writes a reply draft that model reads it again in place (`AppEnvironment.replyDraftWrittenElsewhere`, `ComposeReplyModel.draftChangedElsewhere`; a sheet showing it stays alive), except while it sends, uploads an image or has typing not saved yet (on a two pane window the later save wins), and keeps what it shows when nothing could be read back. Text the sheet is given back (iOS sets its field and echoes it) saves nothing. A reload never drops a permlink a failed send of the sheet left, and Send reads the saved draft's permlink when the sheet has none (its own save may still be waiting). The editor tells the sheet when it saves the permlink of a send, before the broadcast (`theSheetKnowsTheEditorsPermlinkBeforeItsBroadcastAnswers`), and the sheet's own save keeps such a permlink, so for a send whose answer was lost a retry from the sheet asks the chain first and never posts a second reply. An edit of a reply writes its own slot and leaves the quick replies under it alone. Before this a reply continued in the editor ("Open editor") came back in the sheet as it was before, or empty, and the next keystroke wrote that over the editor's text (Android 4.0.0 user report; `EditorModelTest.theQuickReplySheetShowsWhatTheEditorWroteAfterIt`, `aQuickReplyBeingSentKeepsItsModelWhenTheEditorSaves`, `editingAReplyLeavesTheQuickRepliesToItAlone`, `QuickReplyToolsTest.aDraftSavedElsewhereNeverReplacesAnUploadOrUnsavedTyping`, `aReloadKeepsTheSheetOnAFailedReadAndAnEchoNeverBlocksTheNext`, `EditorModelTest.aReplyTheEditorSentIsNeverSentAgainFromTheSheet`, `theSheetsOwnSaveKeepsThePermlinkTheEditorSentUnder`).
1117+
- Local draft per account, reply drafts per parent. The quick reply sheet and the editor's reply mode share the slot; the sheet's model is kept app-wide (see the post screen), so whenever the editor's reply mode writes a reply draft that model reads it again in place (`AppEnvironment.replyDraftWrittenElsewhere`, `ComposeReplyModel.draftChangedElsewhere`; a sheet showing it stays alive), except while it sends, uploads an image or has typing not saved yet (on a two pane window the later save wins), and keeps what it shows when nothing could be read back. Text the sheet is given back (iOS sets its field and echoes it) saves nothing. A reload never drops a permlink a failed send of the sheet left, nor applies a read made before a send of the sheet ran, and Send reads the saved draft's permlink when the sheet has none (its own save may still be waiting). The editor tells the sheet when it saves the permlink of a send, before the broadcast (`theSheetKnowsTheEditorsPermlinkBeforeItsBroadcastAnswers`), and the sheet's own save keeps such a permlink, so for a send whose answer was lost a retry from the sheet asks the chain first and never posts a second reply. An edit of a reply writes its own slot and leaves the quick replies under it alone. Before this a reply continued in the editor ("Open editor") came back in the sheet as it was before, or empty, and the next keystroke wrote that over the editor's text (Android 4.0.0 user report; `EditorModelTest.theQuickReplySheetShowsWhatTheEditorWroteAfterIt`, `aQuickReplyBeingSentKeepsItsModelWhenTheEditorSaves`, `editingAReplyLeavesTheQuickRepliesToItAlone`, `QuickReplyToolsTest.aDraftSavedElsewhereNeverReplacesAnUploadOrUnsavedTyping`, `aReloadKeepsTheSheetOnAFailedReadAndAnEchoNeverBlocksTheNext`, `EditorModelTest.aReplyTheEditorSentIsNeverSentAgainFromTheSheet`, `theSheetsOwnSaveKeepsThePermlinkTheEditorSentUnder`).
11181118
- Save draft (update or save as new), save on leaving. Difference from RN: a draft deleted elsewhere (the web, another phone) is saved as a new draft, which later saves update; RN failed every save, as the private API answers the update with 404 (Sentry ECENCY-MOBILE-3R2). Only a 404 that the drafts list confirms (the draft id is no longer in it; `EditorApi.hasDraft`, strict where `allDrafts` is lenient: a body that does not parse, has no list, or has a row without a string `_id` answers nothing) does that: a 404 from a broken route with the draft still there, or a list that cannot be read, fails the save and makes no second draft; any other failure stays a failure; a replacement that failed to be created is tried again by the next save (`EditorModelTest.aDraftDeletedElsewhereIsSavedAsANewDraft`, `aBrokenUpdateRouteNeverDuplicatesAnExistingDraft`, `aFailedReplacementIsTriedAgainByTheNextSave`, `anUnreadableDraftsListNeverConfirmsADraftGone`, `anotherDraftUpdateFailureIsStillAFailure`).
11191119
- Drafts screen: Drafts, Schedules, Templates, paging by 20, unsynced local draft row, open, delete, clone, batch delete. Each row shows RN's summary (`postBodySummary` of 100: plain text, links as their text, cut at a word; `DraftsState.summaries`, made off the main thread)
11201120
- Schedules: status, delete, move to drafts
@@ -1567,7 +1567,7 @@ RN `screens/wallet`, `assetDetails`, `assetsSelect`, `transfer`, `trade`, `redee
15671567
- **Leaving a running send**: back asks first ("Still sending"); the send goes on without its screen (`WalletSends` counts the screens that own it, `SendOwnership`) and a send nobody owns any more reports its outcome as one toast and is forgotten. An account that leaves (logout, logout-all, wipe) stops its sends at once: nothing signs again for it.
15681568
- **Links**: hive:// and ecency://sign operations go through the same `WalletSends` (one action per confirmed link, "check your wallet", same transaction); the requesting app hears only the final word: `status=success&id=...`, `user_cancelled`, `unconfirmed` when the chain cannot tell, else `qr.transaction_failed`.
15691569
- **One amount reading**: every amount, the checks and the signed text alike, goes through `Amounts.normalize` / `Dec.of`: ".5" is 0.5 (read as 0.000 it would delete a schedule when sent as a recurrent transfer), "", "." and "1e3" are not amounts. Single-recipient kinds refuse several typed names instead of sending to the first.
1570-
- **Restart journal** (`SendJournal`): when a key account's send turns uncertain, `{account, actionId, txId, expiration, operation name}` goes into the secure store entry `wallet.sendJournal` (no key, signature, amount, recipient or memo; `WalletModelsTest` checks the stored text); it is removed when the send settles in this run. At launch (`env.sendJournal.start()`, called by both apps at launch) every entry left is resolved with `transaction_status_api.find_transaction`: in a block or the mempool "went through", `expired_irreversible` "did not go through", `too_old` or the chain's head time past expiration + 10 minutes "could not confirm"; anything else keeps checking (after 5, 10, 20 s, then every 30 s for about 10 minutes while the app runs, again at the next start). The result shows as a notice on the account's Wallet tab until dismissed. Logout removes the account's entries, undecided ones included (the account's sends stop at the same time; the user checks that account's wallet after signing in again). Stopping a send does not take back a request already on the wire: a broadcast a node had received before the logout may still land; a wipe removes the store. A change the store refuses (iOS before the first unlock: a send journaled, settled, dismissed or forgotten while the Keychain is locked) is kept in memory and in an ordered list of unsaved changes; the next read that works (the next change, or `start()` again at the next activation) applies them again, in order, to the stored list before its own change and writes the result, so an entry recorded while locked keeps its notice and its place in the 32 below, and one removed while locked is not brought back by the stored copy (every change is idempotent, so one applied twice after a failed write is the same; `WalletDeltaFixesTest.aSendRecordedWhileLockedSurvivesTheStartAfterTheUnlock`, `theFirstChangeAfterTheUnlockKeepsTheSendRecordedWhileLocked`, `removalsWhileLockedAreNotBroughtBackByTheStoredCopy`). Updates run one at a time, from taking the queued changes to clearing them, so two at once after the unlock replay a change once and never write back what the other settled (`twoChangesAtOnceAfterTheUnlockNeverBringASettledSendBack`). At most 32 entries: past that, decided entries whose notice was not read give way, oldest first; undecided ones never do, and while 32 undecided entries wait no new value send starts ("Too many earlier sends are still being checked...").
1570+
- **Restart journal** (`SendJournal`): when a key account's send turns uncertain, `{account, actionId, txId, expiration, operation name}` goes into the secure store entry `wallet.sendJournal` (no key, signature, amount, recipient or memo; `WalletModelsTest` checks the stored text); it is removed when the send settles in this run. At launch (`env.sendJournal.start()`, called by both apps at launch) every entry left is resolved with `transaction_status_api.find_transaction`: in a block or the mempool "went through", `expired_irreversible` "did not go through", `too_old` or the chain's head time past expiration + 10 minutes "could not confirm"; anything else keeps checking (after 5, 10, 20 s, then every 30 s for about 10 minutes while the app runs, again at the next start). The result shows as a notice on the account's Wallet tab until dismissed. Logout removes the account's entries, undecided ones included (the account's sends stop at the same time; the user checks that account's wallet after signing in again). Stopping a send does not take back a request already on the wire: a broadcast a node had received before the logout may still land; a wipe removes the store. A change the store refuses (iOS before the first unlock: a send journaled, settled, dismissed or forgotten while the Keychain is locked) is kept in memory and in an ordered list of unsaved changes; the next read that works (the next change, or `start()` again at the next activation) applies them again, in order, to the stored list before its own change and writes the result, so an entry recorded while locked keeps its notice and its place in the 32 below, and one removed while locked is not brought back by the stored copy (every change is idempotent, so one applied twice after a failed write is the same; `WalletDeltaFixesTest.aSendRecordedWhileLockedSurvivesTheStartAfterTheUnlock`, `theFirstChangeAfterTheUnlockKeepsTheSendRecordedWhileLocked`, `removalsWhileLockedAreNotBroughtBackByTheStoredCopy`). Updates run one at a time, from taking the queued changes to clearing them, so two at once after the unlock replay a change once and never write back what the other settled (`twoChangesAtOnceAfterTheUnlockNeverBringASettledSendBack`). A start after a good launch writes the changes a later lock kept in memory (`aChangeRefusedAfterAGoodLaunchIsWrittenAtTheNextStart`), and a send's settle on success is not cancellable, as on the failure paths. At most 32 entries: past that, decided entries whose notice was not read give way, oldest first; undecided ones never do, and while 32 undecided entries wait no new value send starts ("Too many earlier sends are still being checked...").
15711571

15721572
Differences from RN
15731573
- Link decoding wants JSON numbers for percents, recurrence and executions.

‎shared/src/commonMain/kotlin/com/ecency/core/app/ComposeReplyModel.kt‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,9 @@ class ComposeReplyModel internal constructor(
6868
) : StateModel<ReplyState>(ReplyState(), env.dispatchers), AiTextTarget {
6969

7070
private var pending: PendingPublish? = null
71+
72+
/** Sends started (main thread): a reload that read the draft before one ran does not apply its older record. */
73+
private var sends = 0
7174
private var conflictChoice: Boolean? = null
7275

7376
// ---- RN quick reply's toolbar: dictation and AI assist (the editor's models), image and clipboard (the wave composer's upload) ----
@@ -250,10 +253,12 @@ class ComposeReplyModel internal constructor(
250253
scope.launch {
251254
// after the first read, which would otherwise put its older text back over this one
252255
draftRead.await()
256+
val sendsBefore = sends
253257
// the editor just saved it: none read back is a read that failed, and the sheet keeps what it shows
254258
val local = env.localDrafts.load(user, slot) ?: return@launch
255-
// checked again after the load: a keystroke meanwhile started a save (setText), a send or an upload began
256-
if (current.isSending || current.isAttaching || saveJob?.isActive == true) return@launch
259+
// checked again after the load: a keystroke meanwhile started a save (setText), a send or an upload began, or a
260+
// send ran and ended (its newer pending record is not replaced by this older read)
261+
if (sends != sendsBefore || current.isSending || current.isAttaching || saveJob?.isActive == true) return@launch
257262
// a permlink a failed send left is kept until a send settles it: a read from before it was saved has none
258263
pending = local.pending ?: pending
259264
setState { it.copy(text = local.body, imageUrl = local.replyImage, draftPermlink = pending?.permlink, sent = null, error = null, prefillSeq = it.prefillSeq + 1) }
@@ -352,6 +357,7 @@ class ComposeReplyModel internal constructor(
352357
setState { it.copy(error = AppError(ErrorKind.AUTH, ACCOUNT_CHANGED, false)) }
353358
return
354359
}
360+
sends++
355361
setState { it.copy(isSending = true, error = null, sent = null, conflict = false, authorityPrompt = false) }
356362
val authorityRetry = authority.takeRetry()
357363
val text = bodyOf(state)

‎shared/src/commonMain/kotlin/com/ecency/core/app/SendJournal.kt‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,8 @@ class SendJournal internal constructor(private val env: AppEnvironment) : StateM
8686
// iOS starts it again on becoming active (after an unlock): one asked while the launch read is in flight
8787
// reads once more if that read fails, rather than waiting for the next foreground
8888
if (reading) startAgain = true
89+
// after a good launch, changes the store refused since (a lock later in the run) are written now
90+
else if (unsaved.isNotEmpty()) scope.launch { update(null) }
8991
return
9092
}
9193
started = true

‎shared/src/commonMain/kotlin/com/ecency/core/app/SigningModel.kt‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,9 @@ class SigningModel internal constructor(private val env: AppEnvironment) :
142142
send: suspend () -> com.ecency.core.api.broadcast.BroadcastResult,
143143
): com.ecency.core.api.broadcast.BroadcastResult {
144144
try {
145-
return send().also { env.sendJournal.settle(username, actionId) }
145+
// not cancellable, as the failure paths: a settle cut off after its write would leave the queued record
146+
// of this send to be replayed over it (CodeRabbit on #3756)
147+
return send().also { withContext(kotlinx.coroutines.NonCancellable) { env.sendJournal.settle(username, actionId) } }
146148
} catch (e: com.ecency.core.api.broadcast.BroadcastException.Network) {
147149
val pending = e.pending
148150
val tx = pending?.signed

‎shared/src/commonTest/kotlin/com/ecency/core/app/WalletDeltaFixesTest.kt‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -443,6 +443,27 @@ class WalletDeltaFixesTest {
443443
assertEquals(setOf("a1", "c1"), w.env.sendJournal.current.entries.map { it.actionId }.toSet())
444444
}
445445

446+
/** CodeRabbit on #3756: a change the store refused after a good launch is written at the next start (the unlock). */
447+
@Test
448+
fun aChangeRefusedAfterAGoodLaunchIsWrittenAtTheNextStart() = runTest {
449+
val w = WalletWorld(this)
450+
w.statusAnswer = { "\"unknown\"" }
451+
w.app.store.putString(SendJournal.ENTRY, "[${storedEntry("spike-voter", "a1", "ab")},${storedEntry("spike-voter", "a2", "aa")}]")
452+
w.env.sendJournal.start()
453+
testScheduler.runCurrent()
454+
assertEquals(setOf("a1", "a2"), w.env.sendJournal.current.entries.map { it.actionId }.toSet())
455+
// locked later: the settle of a2 is kept in memory only
456+
w.app.store.failingReads[SendJournal.ENTRY] = locked
457+
w.env.sendJournal.settle("spike-voter", "a2")
458+
testScheduler.runCurrent()
459+
// unlocked: nothing else changes the journal, the app comes to the front
460+
w.app.store.failingReads.clear()
461+
assertEquals(setOf("a1", "a2"), storedIds(w).toSet(), "not written while locked")
462+
w.env.sendJournal.start()
463+
testScheduler.runCurrent()
464+
assertEquals(setOf("a1"), storedIds(w).toSet(), "the settle is written once the store reads again")
465+
}
466+
446467
/** iOS starts the journal again on becoming active: one that comes while the launch read is in flight is not lost. */
447468
@Test
448469
fun aStartDuringAnInFlightReadThatFailsReadsOnceMore() = runTest {

0 commit comments

Comments
 (0)