Skip to content

fix: let send reach spark before the node runs - #2244

Open
jvsena42 wants to merge 41 commits into
masterfrom
fix/send-overlay-recipient
Open

jvsena42 wants to merge 41 commits into
masterfrom
fix/send-overlay-recipient

Conversation

@jvsena42

@jvsena42 jvsena42 commented Dec 3, 2026 •

Copy link
Copy Markdown
Member

Source: qa, mainnet QA of 3.2.0 RC3 (#2160 (comment))
Twin: synonymdev/bitkit-ios#1578

Spark is ready about 0.4 s after launch, but the Send sheet kept its sync overlay up until the node ran. After 20 s in the background, Send was blocked for 24 s, even for invoices Spark could pay (#2032 comment).

Description

  • The sync overlay no longer covers the recipient steps (Recipient, Scan, Enter Manually, Contact, and Contact's Coming Soon fallback while Paykit UI is off). Decoding needs no node. An invoice Spark can pay goes straight to review, and anything else shows the overlay on the next step.
  • A scanned payment Spark can't cover still waits for the node from the recipient step, as do the own-invoice check's node-id wait on a cold start and LNURL pay. AppViewModel.isSendWaitingForNode counts these waits, and the overlay shows on the recipient step only while one runs.
  • On the Amount step, an amountless Lightning invoice takes its amount without the node when Spark can send. Both the sheet overlay and the Amount screen's own sync view let it through. LNURL pay still waits for the node. While the node is down, the amount is capped at Spark's sendable balance, because the cached Spending limit isn't refreshed then.
  • For an amountless invoice, the overlay and Confirm decide whether Spark pays from the entered amount, so a Spark-payable amount reaches review without the node.
  • Amount validation accepts an amount Spark can pay, with the routing-fee reserve kept, even above the cached Spending limit, and SendAmountScreen passes the Spark-capped balances to the pad. The max routing fee is quoted from Spark's live sendable amount when the cached limit trails it.
  • A fixed invoice typed into Enter Manually that Spark can't cover waits for the node's channels, with the overlay up, before the capacity check. It waits only while the node isn't running, and first waits through a stop with a start queued behind it (the app foregrounded during its background stop). Closing Send or leaving Enter Manually cancels the wait.
  • After a payment is submitted (Pending, Success, Error, QuickPay), the overlay stays off.

Out of Scope

  • LightningRepo.earlierNodeSend: before each Spark send, the duplicate-send check lists node payments on ServiceQueue.LDK. While a node exists and that queue is busy with start or an Electrum sync, the swipe waits behind it. That is payment-safety code, so it is left for a separate change.
  • SpendingAmountScreen, SendQuickPayScreen, LightningConnectionsScreen: their sync views stay, since those flows need the node.
  • bug: send sheet stays locked while an ldk call stalls #2032's confirm-swipe deadlines: this PR references the issue but does not close it.
  • A typed invoice that a channel covers was not driven on a device: a local channel to the app stayed ChannelPending in LDK for over 6 minutes. The unit tests cover the wait and the check.

Design

N/A — no design available.

Preview

Recipient, node down Review, node down Amountless amount entry Pending, node down
Recipient step without overlay Review without overlay Amount entry without overlay Pending screen without overlay

QA Notes

Setup

Dev (regtest) build of this branch on a phone with a funded Spark balance. A wallet with a channel shows the Lightning variant of the overlay; without one, the Bitcoin variant.

Journeys

  • J1. On-chain connecting view. Hold node startup, check Recipient, paste an on-chain address and check the overlay on Amount until startup completes.

Manual Tests

  1. Background the app for 30 s or more so the node stops, return, and open Send right away: the Recipient step shows at once with Scan, Paste, Contact and Enter Manually, and no sync overlay.

  2. During 1., paste an invoice with an amount Spark can pay: review opens before the node runs, and the payment completes.

  3. During 1., paste an amountless invoice: amount entry shows without the overlay. Enter an amount within the Spark balance, continue, and pay.

  4. During 1., paste an on-chain address: the overlay shows on the Amount step and clears once the node runs.

  5. With the node running and a usable channel, a normal Lightning send still works.

  6. With Spark funded and the node stopped, open an external amountless invoice when the cached channel limit is higher than Spark capacity. Tap Available during the Max quote. Once the reserve arrives, verify that the previous full amount cannot continue, the revised Available amount can, and a fee-bearing Max payment settles.

  7. Hold the Max quote for invoice A, close Send and open invoice B. Let B’s quote return first, then release A’s quote. Check that B keeps its Available amount and Continue state. Repeat by reopening the same invoice in a fresh Send session.

Evidence

Follow-up at c03deaae. The Android JVM suite recorded 7,046 passes, two live-node skips and zero failures. The regressions cover the live Spark and running-node limits, delayed fee validation, and late success and failure after an invoice or session change. Compile, Detekt, Android lint and J1 XML parsing passed. J1 and the manual cases await candidate device testing.

Emulator (API 37.1) and local Spark regtest (bitkit-docker spark profile), node held down by blocking Electrum. Build 0ad84e6e9 (#2244 at 272067dfa + #2245) and rerun 4fad15073 (#2244 at 106456253 + #2245). Clipboard paste does not work on the emulator, so invoices went in by deeplink.

  • 1. Recipient, Enter Manually and Scan show no overlay while the node is down (PASS).
  • 2. An invoice Spark can pay reaches review ~1.2 s after the deeplink with the node down (PASS). The payment itself failed with Tree service error: insufficient funds: the local SSP has no 8,192-sat leaves, so swaps fail. After that "Payment pending" result, the first build covered the Pending screen with the overlay; 106456253 fixed it and the rerun shows Pending uncovered at 1 s and 30 s (PASS).
  • 3. An amountless invoice opens amount entry without the overlay; 20,000 above Spark's 17,087 sendable is refused; 2,000 reaches review (PASS).
  • 4. An on-chain address shows the overlay on Amount while the node is down and clears ~4 s after Node started (PASS).
  • 5. With the node running, a 1,500-sat Spark payment completes (PASS).
spark-send.mp4
  • Extra: an invoice above Spark's balance shows "Insufficient Spending Balance" ~10 s after the deeplink; LNURL pay shows the overlay until the node runs (PASS).

Amount cap On-chain overlay

Gaps: payments made while the node is down are blocked by the local SSP's leaf pool, not by this change. The recipient-step overlay during a node wait was not observed, since deeplinks skip that step.

Review round (Greptile, ovi-reviewer)

Device runs on the emulator (API 37.1), local Spark regtest, node held down by blocking Electrum. Builds 02e8b79 (#2244 at 90fddb07c + #2245) and a6f2e7dbd (#2244 at 7c9ab3653 + #2245).

  • Stale cache below Spark: cached limit 19,950, Spark 40,000. Available showed 39,863, and 30,000 reached review with no overlay (PASS).
  • Typed invoice Spark covers: no overlay, Continue enabled ~3 s after the last character (PASS).
  • Typed invoice above Spark, node down: overlay ~3 s, then "Insufficient Spending Balance" (PASS). Typed as the node came back: Node started 16:04:57.1, toast ~16:05:00 (PASS).
  • Closing Send or pressing Back during that wait: no stuck overlay, and no late toast within 30 s of Node started (PASS).
Stale cache: Available Stale cache: review

Typed invoice while the node starts:

typed-invoice-node-start.mp4

Closing Send during the wait:

close-during-wait.mp4

Unit tests: 7,034 pass, and detekt is clean. Each new test failed before its fix.

Review round 2 (piotr-iohk)

Device runs at 37f8ec486 on the emulator (API 37), local Spark regtest, node held down.

  • Paykit UI off, Contact while the node is down: Coming Soon with no overlay, and Back returns to Recipient (PASS).
  • Fresh wallet, Spark 50,000, cached limit 0: Spark sendable 49,875, and Available filled 49,798 (77-sat reserve). 49,875 and 49,799 were refused and 49,798 accepted. Review showed 49,798 with "Instant (± 201)", and the Spark payment succeeded (PASS).
  • Controls: a typed invoice Spark covers validates with no wait, and Recipient, Enter Manually and the scanner show no overlay (PASS).
  • Typed invoice during a background stop with a start queued: ovi-reviewer verified it on a device with a held stop and a channel. A 200,000-sat invoice stayed pending through the restart, then reached Confirm. My emulator could not land the input inside the stop window (the stop took 1.3 to 4.2 s), so I have no independent run of this case.
Coming Soon, node down Spark max at review

Unit tests: 7,038 pass, detekt is clean and androidTest compiles.

Review round 3 (coreyphillips)

  • A queued, stopping or slow node start is waited for, up to 1 min, before every capacity check that waits for channels (paste, scan, unified, LNURL, typed). Typed entry also waits while a running node's channels reconnect. Continue waits for any in-flight Max quote.
  • Unit tests: 7,052 pass, detekt is clean and androidTest compiles.
  • Not device-verified: a queued or slow start, reconnecting channels and the running-node Max quote. They need a usable channel, a start slower than 15 s or a held quote, which the local regtest setup did not provide. Case 6 at c03deaae4 was verified by ovi-reviewer. My rerun failed because the local Spark operator refused both spends ("Tree service error: insufficient funds").

🤖 Generated with Claude Code

Models used

  • Planning/scoping and implementation of this follow-up used gpt-6.2-astra (reasoning: high). Earlier implementation model and effort are unrecorded in the PR.
  • Review used gpt-6.2-sol (reasoning: high) and gpt-6.1-sol (reasoning: high). Greptile did not identify its model or effort in the review.

Hide the sync overlay on the recipient steps, so a Lightning invoice
Spark can pay is decoded without waiting for the node. Let Spark take
an amountless invoice's amount, and check the entered amount when
deciding whether the review can skip the node.

Refs #2032

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jvsena42 and others added 3 commits December 3, 2026 07:53
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A scanned payment Spark can't cover still waits for the node from the
recipient steps, so show the sync overlay there while that wait runs.
While the node is down, cap amount entry for an amountless invoice at
Spark's sendable balance, since the cached limit is not refreshed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
On a cold start the own-invoice check waits for the node id, so count
that wait like the channel wait and show the overlay meanwhile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions

github-actions Bot commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Regtest APK

Built from 0022954 (run).

Download bitkit-dev-debug universal APK (expires in 30 days).

A Spark payment can be submitted before the node runs, and its balance
then no longer covers it, so the overlay came back over the pending or
result screen. Skip it on the routes after submission.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@jvsena42
jvsena42 marked this pull request as ready for review December 3, 2026 13:49
@jvsena42
jvsena42 requested review from a team, ovitrif and piotr-iohk and removed request for a team December 3, 2026 13:49
@greptile-apps

greptile-apps Bot commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5RetriggerView in Greptile

[Medium impact] The PR appears safe to merge; no new blocking issue was found.

Summary

The PR lets users choose recipients and enter Spark-payable amounts before the Lightning node runs.

The latest changes:

  • Recipient steps open before the Lightning node is ready.
  • Amountless invoices use Spark’s available balance for amount entry.
  • Typed invoices wait for usable channels when Spark cannot cover them.

No new actionable issues were found. Tests and device flows were not run during this review.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Choose or enter recipient] --> B{Spark covers payment?}
  B -->|Yes| C[Review without node wait]
  B -->|No| D[Wait for pending node start]
  D --> E[Wait for usable channels]
  E --> F[Check capacity]
  G[Enter amountless invoice amount] --> H[Wait for Max fee quote]
  H --> I[Check amount with fee reserve]
  I --> C
Loading

Reviews (6) · Last reviewed commit: "refactor: share the recipient route list..." · Reviewed by Greptile

@ovitrif ovitrif added this to the 3.2.0 milestone Dec 3, 2026
@ovitrif

ovitrif commented Dec 3, 2026 •

Copy link
Copy Markdown
Collaborator

Placed in 3.2.0 for RC4: Send blocking Spark-payable invoices until the node runs (synonymdev/bitkit-android#2032 comment) was agreed into RC4 in the release thread, with its iOS twin synonymdev/bitkit-ios#1578. This PR closes no issue, so it carries the milestone.

@jvsena42
jvsena42 marked this pull request as draft December 3, 2026 14:03
jvsena42 and others added 2 commits December 3, 2026 11:05
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@ovi-reviewer ovi-reviewer 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.

Verdict: ⚠️ Not verified — two MEDIUM defects reproduced; the PR returned to draft before device QA.

Findings:

MEDIUM — Apply Spark capacity throughout amount entry (app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt:532). The new balance override is not forwarded by SendAmountScreen to SendAmountContent. With a 10,000-sat explicit limit and a 100,000-sat ambient cache, the real amount-screen wrapper accepts 20,000 sats. The ViewModel also retains the cached limit: with cached zero and Spark able to send 500 sats, entering 500 leaves Continue disabled. Forward the balance through the wrapper and use live Spark capacity in amount validation while the node is down.

These reproduce the existing reports, with focused failing-test evidence:

MEDIUM — Wait for node capacity during manual invoice validation (app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt:173). Manual entry is now reachable while the node restarts, but validateLightningInvoice calls syncState and canSend without waiting for usable channels. A fixed invoice beyond Spark's balance is rejected as insufficient spending balance even when a channel can cover it after startup. Apply the scan/paste path's node wait to manual validation, then revalidate against loaded capacity.

QA for 1064562:

Check: sync overlay policy ✅ The exact-head build and SendSheetSyncOverlayTest passed.

Built the reviewed commit in both standard dev and local Spark configurations. The overlay checks executed without failures or skips.

Check: amount entry uses Spark capacity ❌ Focused regressions reproduced the dropped screen cap and cached-limit rejection.

Temporary JVM tests exercised the actual screen wrapper and AppViewModel. The wrapper accepted 20,000 with a supplied maximum of 10,000; a separate 500-sat input stayed invalid with cached zero despite Spark being able to pay. Reproduction tests were not pushed.

Check: manual invoice validation during restart ❌ Manual validation checked insufficient capacity without awaiting the restarting node.

A focused AppViewModel test entered a foreign fixed invoice with a known own-node ID, a Starting node and insufficient Spark capacity. It called syncState and canSend, but never waitForUsableChannels. Reproduction test was not pushed.

Pay a fixed invoice through Spark while the node is stopped ⏭️ Manual case 2 was not driven after the PR returned to draft.

The existing report reaches review but does not prove payment completion with the node down.

Pay an amountless invoice through Spark while the node is stopped ⏭️ Manual case 3 was not driven after the PR returned to draft.

The existing report proves amount entry and review, but not payment completion with the node down.

Send Lightning with the node and channel running ⏭️ Manual case 5 was not driven after the PR returned to draft.

The existing successful Spark send does not establish a channel-funded send.

Show the recipient overlay during a node-dependent scan ⏭️ This gap in the existing evidence was not driven after the PR returned to draft.

Manual cases 1 and 4 were not repeated: the PR's evidence covers recipient access and the on-chain overlay clearing at this head plus the companion logging change. No device journey ran in this review.

Full review: fc82f5c..1064562, including recipient routes, node waits, amount validation, QuickPay and submitted-payment routes. Device behavior remains unverified for the four cases above.

Twin: synonymdev/bitkit-ios#1578 implements the same recipient, amountless-entry and submitted-payment overlay exemptions; payment parity was not exercised.


Reviewed by gpt-6.1-sol-high

jvsena42 and others added 2 commits December 3, 2026 11:26
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@ovi-reviewer ovi-reviewer 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.

Verdict: ⛔️ Request changes — two MEDIUM regressions reproduced at 90fddb0.

The PR moved to 652c67b after this run; these results are for 90fddb0.

Findings:

  • MEDIUM — Cancel manual validation when leaving Send (app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt:3696). The new node wait survives dismissal because hideSheet does not cancel addressValidationJob. A held-wait regression leaves isSendWaitingForNode true after closing Send; releasing the wait then marks the dismissed invoice valid. System Back from manual entry also leaves the wait active on Recipient.
  • MEDIUM — Preserve the routing-fee reserve for Spark amounts (app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt:5579). The new Spark branch bypasses estimatedRoutingFee, including with a fresh cached limit. With 10,000 sendable and a 100-sat routing reserve, entering 9,950 remains valid although Available is 9,900. An existing amount can survive a Savings-to-Spending switch above that limit.

QA for 90fddb0:

Check: overlay policy and earlier regressions ✅ The exact-head build and focused checks pass.

Built standard dev and local Spark configurations. SendSheetSyncOverlayTest and AppViewModelSendFlowTest pass, including the stale spending-limit and manual node-wait regressions. The temporary test of the actual amount-screen wrapper now enforces the explicit Spark cap over a larger ambient cache.

Check: cancel manual validation when Send closes ❌ A dismissed validation retains its wait and publishes a late result.

Temporary JVM regressions suspend the real ViewModel's manual channel wait, close Send, then release it. The wait flag stays true after dismissal and the late result sets isAddressInputValid to true. Both assertions fail; the tests were not pushed.

Check: reserve routing fees for Spark amounts ❌ The Spark branch accepts an amount above capacity after the routing reserve.

A temporary JVM regression sets a 10,000-sat spending limit, a 100-sat routing reserve and Spark coverage of 9,950 sats. AmountChange(9,950) remains valid. The assertion fails; the test was not pushed.

Pay a fixed invoice through Spark while the node is stopped ⏭️ Payment completion was not driven.

Manual case 2 remains unverified: the earlier report proves reaching review, but its payment did not complete.

Pay an amountless invoice through Spark while the node is stopped ⏭️ Payment completion was not driven.

Manual case 3 remains unverified: the earlier report proves amount entry and review, but not payment completion.

Send Lightning with the node and channel running ⏭️ The channel-funded send was not driven.

Manual case 5 remains unverified: the earlier successful send used Spark.

Show the recipient overlay during a node-dependent scan ⏭️ The recipient wait was not driven.

The earlier report used deeplinks, which skip the recipient step.

Cap amountless entry at Spark capacity during restart ⏭️ The device case was not driven.

The wrapper cap passes its focused JVM regression; its live restart behavior was not driven.

Validate a manual invoice while the node restarts ⏭️ The device case was not driven.

The initial channel-wait ordering passes its focused regression; restarting-node behavior was not driven.

The six device cases above were left unrun when the head advanced to 652c67b before payment QA began. No device journey ran in this review. Manual cases 1 and 4 rely on the PR's earlier evidence: recipient access and the on-chain overlay clearing were proved at 1064562 plus the companion logging change, and this delta leaves those paths unchanged.

Reviewed the contiguous delta from 1064562 to 90fddb0, all three changed files and the earlier open findings. The newer head 652c67b was not reviewed here.

Twin: synonymdev/bitkit-ios#1578 has the same recipient, amountless-entry and submitted-payment overlay exemptions, with platform-specific validation; device parity was not exercised.


Reviewed by gpt-6.1-sol-high

jvsena42 and others added 2 commits December 3, 2026 13:40
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@jvsena42
jvsena42 marked this pull request as ready for review December 3, 2026 17:14
@jvsena42
jvsena42 requested a review from a team December 3, 2026 17:14
@jvsena42
jvsena42 marked this pull request as draft December 3, 2026 17:19
@jvsena42
jvsena42 marked this pull request as ready for review December 3, 2026 17:35
@jvsena42
jvsena42 requested a review from pwltr December 4, 2026 15:34

@piotr-iohk piotr-iohk left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

QA review

Scope: Code-only follow-up on Android #2244 at 488b7de, covering Savings admission and Back from manual entry since the verified full baseline at 6c6e88c. Unchanged coverage comes from that baseline. The read-only iOS comparison at ca601a8 covered manual entry, loading, Savings fallback and cancellation. Back during a recipient replacement remains a runtime comparison. Android #2244 · Android 488b7de · Verified baseline · iOS ca601a8

5 prior concerns need a decision.

Remaining decisions

  • running-node-max-quote-disables-confirm-swipe — The gate fixes the original case where the quote is already pending. The documented replacement quote from the outgoing Amount screen can still invalidate Confirm after that gate. This is the previously reported transition case. Scope Max fee writes to active Amount entry, or show the changed limit and a recovery path on Confirm. Exercise a ceiling change after Continue's final guard during the Amount exit.
  • paykit-amountless-contact-live-spark-validation-cached-routing-limit — The author deferred the verified mixed-endpoint routing mismatch to the Paykit refactor. A reviewer already acknowledged the deferral. The router can still refuse an amount the pad accepted. Decide where live Spending capacity will be passed to the router and identify the Paykit work item if the change remains deferred.
  • [HIGH] send-contact-scan-outlives-dismissal-and-loses-quickpay-guard — The reply defers ownership to the Paykit refactor. The extended startup wait still lets abandoned contact preparation reach automatic submission in a later Send visit under the reported conditions. Decide where the visit-ownership guard will ship. Bind contact preparation to the originating Send visit and cancel or invalidate it at dismissal before it can reach QuickPay.
  • unified-send-savings-snapshot-survives-lightning-startup-wait — The earlier discussion addressed refusing a direct on-chain recipient before startup. F1 covers the unified-invoice fallback after the Lightning leg has given startup time to complete. The insufficient-balance verdict can still use the old snapshot even after Savings has been published. The new refresh runs when the fallback still sees the node down. Unified preparation can move the lifecycle to Running before the helper receives the old balance. At 488b7de, AppViewModel.kt:6652–6666 takes the new refresh branch for a direct node-down scan. A local Kotlin/JVM 2.3.21 probe returned 50,000 sats on that branch, then returned the earlier zero when the repository already held 50,000 sats and the lifecycle was Running. Re-read Savings when evaluating the unified fallback and exercise the ordering where sufficient Savings is published during the Lightning check.
  • send-review-recipient-back-retains-cancelled-onchain-draft — The cancellation prevents late navigation. F2 addresses Back from a recipient edit initiated by Confirm, after the replacement has already written its data to the shared state. The original Confirm route can return with the abandoned recipient and amount. The new Savings wait adds a cancellation point after replacement data reaches shared state. The Back fix cancels work before the pop and leaves those earlier writes in place. At 488b7de, AppViewModel.kt:5908–5926 resets the state and 6387–6404 publishes the new draft before the added wait at 6497–6504. AppViewModel.kt:3722–3726 cancels jobs without restoring review state. The passing test at 12209–12231 cancels earlier during decode and asserts only navigation effects. Keep replacement data separate until preparation succeeds or restore the original review on Back. Assert the original recipient and amount when Back cancels a held Savings wait.

Android CI passed both new JVM regressions on merge af8a6278b307a84c70a55498f41cd6ccaf4e7d24, which includes the reviewed head and CI base 831672b0d26a41cb437f02e65209483d4b21d754. The tests cover Savings published immediately by sync and Back during decode. Local checks included a Kotlin/JVM 2.3.21 probe with stubbed repository state and XML parsing of both connecting-view journeys. The source comparison used the pinned scanner, wallet sync and manual-entry fixtures. Android JVM report · Bitkit Core 045c7ff · LDK Node 3f45b8e · Appium source 9a64fa3

Device testing was not performed in this review. The runtime plan retains Android J1 and manual cases 1–7 on funded regtest. J1 requires a controllable startup hold and release, case 5 requires usable channel liquidity, and cases 6–7 require control over fee-quote delivery. Author QA plan

Suggested additional test cases

  • On Android, confirm a Savings deposit that is absent from the app cache. Paste a fixed-amount unified invoice while startup is held, with neither Spark nor a channel able to pay its Lightning leg. Let the node publish a sufficient Savings balance before releasing the Lightning check. Verify that Confirm shows the requested amount from Savings without an insufficient-balance toast.
  • On Android, open a Spark-payable invoice on Confirm while the node is held down. Open the recipient from review details and continue with a different fixed-amount on-chain request above cached Savings. Press system Back during the wait, then release startup. Verify that Confirm retains the original recipient and amount and that the replacement never routes.

Earlier findings reconciled at this revision: 1 still present, 3 verified fixed.

Existing concerns

  • [LOW] Document the startup hold and release for J1 — J1 still asks the tester to hold startup through Paste and then release it. Candidate QA Setup gives the funded regtest prerequisites but supplies no hold-and-release recipe or link to one. Earlier device reviewers disclosed temporary test hooks on older builds. Link a reproducible procedure for the candidate from QA Setup.

Reviewer model: gpt-6.2-sol
Reasoning effort: high

@piotr-iohk piotr-iohk left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Android regtest device QA

Tested 488b7dea4f7c324be101a14e1bb52aa36bd1fe8e on the Android 13 Spark emulator. The debug test build used a file-controlled hold before native Lightning startup.

  • Savings deposit during startup failed. The app had zero cached Savings when I used Paste Invoice for a 30,000-sat fixed unified request. After release it returned to the Send scanner and showed Insufficient Savings while the fresh 80,000-sat deposit appeared. LDK reported 80,000 sats spendable on-chain, and the same request reached Confirm → Savings → 30,000 sats once sync completed.
  • Back during recipient replacement failed. I opened a 12,000-sat Spark-payable invoice and changed its recipient to a 120,000-sat fixed on-chain request above the cached Savings balance. With the keyboard closed, I pressed system Back during Connecting to network, then released startup. Confirm showed Savings, 120,000 sats, and the replacement recipient. The original 12,000-sat Spending review was lost.

No payments were submitted from the tested reviews. Both findings block device sign-off. QA Watch test plan

Device screenshots, recordings, and trace

@piotr-iohk

Copy link
Copy Markdown
Collaborator

Android device evidence

Device findings at 488b7de

Startup rejection Same request after sync
Insufficient Savings alongside the 80,000-sat receipt Confirm from Savings for 30,000 sats

Back from the recipient replacement

Confirm shows the 120,000-sat replacement after Back

Screen recordings and device trace

Savings timing

android-f1-timing.mp4

Recipient replacement and system Back

android-f2-back-and-release.mp4
Android #2244 regtest device evidence
Tested revision 488b7dea4f7c324be101a14e1bb52aa36bd1fe8e

Savings timing
Lightning startup hold released at 2026-12-04T17:15:26Z.
2026-12-04 17:15:29.660 INFO    [ldk_node:2535]                      Balance changed: onchain 0 -> 80000 (spendable), 0 -> 80000 (total), lightning 0 -> 0
2026-12-04 17:15:32.355 VERBOSE [DeriveBalanceStateUseCase.kt:84]    Balances in state at block height=232: {"totalOnchainSats":80000,"channelFundableBalance":79890,"totalLightningSats":0,"maxSendLightningSats":0,"maxSendOnchainSats":79890
Video shows Connecting to network, Insufficient Savings on the 30,000-sat request, then the 80,000-sat deposit.
The identical request opened Savings Confirm with 30,000 sats after sync.

Recipient replacement cancellation
Before editing: Confirm, Spending, 12,000 sats, original regtest Lightning invoice.
Android system Back sent at 2026-12-04T17:25:05Z with the keyboard hidden and the replacement waiting.
After release, the accessibility hierarchy showed Confirm, Savings, 120,000 sats, regtest recipient ending 3phe8m2.
The runner submitted no payment.

jvsena42 and others added 2 commits December 4, 2026 14:36
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@jvsena42

jvsena42 commented Dec 4, 2026

Copy link
Copy Markdown
Member Author

@piotr-iohk thanks for the device run at 488b7de. Both failures came from that commit; fixed at b156c2b:

  • Savings deposit during startup (78481b0): for a unified request the Lightning check starts the node first, so by the Savings check the node was running and 488b7de trusted the cached balance. Savings now counts as fresh only once the started node has completed a sync (lastSuccessfulSyncAt); until then a refusal waits behind the connecting view and syncs balances first. The same rule now drives manual entry. Test an address refused by savings a just-started node has not synced waits for fresh balances (0 cached, 80,000 after sync, 30,000 request) fails at 488b7de and passes now.
  • Back during recipient replacement (b156c2b): the scan wrote the replacement recipient and amount into the send state before waiting, so Back cancelled the scan but left Confirm holding "Savings, 120,000 sats", which could still be swiped. The wait now runs before the send state is filled, so a cancelled replacement never reaches Confirm. Test back during the savings wait never fills the review with the abandoned recipient fails at 488b7de and passes now.

One part is not met: Confirm does not get the original 12,000-sat review back. Every new scan resets the send state when it starts (resetSendState, "always reset state on new scan"), and master does the same; a replacement refused for any reason also drops the old review there. Keeping it would mean deferring that reset until a scan succeeds, which touches every scan path, so I'd rather track that separately unless you see it as blocking.

7,062 unit tests pass, detekt is clean, androidTest compiles.

@jvsena42
jvsena42 requested a review from piotr-iohk December 4, 2026 17:38

@ovi-reviewer ovi-reviewer 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.

Verdict: ⛔️ Request changes

The PR moved to b156c2b after this run; these results are for 488b7de.

The PR advanced to b156c2b while this review was finishing; the findings and QA below apply to 488b7de.

Findings:

  • [MEDIUM] Wait for fresh Savings when Running precedes the balance update — app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt:6660. Running can precede balance publication, so manual entry still rejects a fresh deposit. A real 100,000-sat deposit remained refused until publication. Unified fallback also keeps the balance captured before its Lightning wait; on device, the fresh maximum had reached 1,099,753 sats when a 900,000-sat request was refused using the older 799,821-sat maximum. Re-read Savings after the wait and wait for fresh publication before refusing during startup.

  • [MEDIUM] Keep outgoing Amount quotes from invalidating Confirm — app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt:9441. A replacement Max quote can start after Continue's final guard while Amount is exiting, then silently disable Confirm. The actual ViewModel accepted 39,950 sats with a 20-sat reserve; dropping the ceiling from 100,000 to 40,000 still left it valid, but the post-navigation 120-sat quote invalidated it. Scope Max updates to active Amount entry, or show the changed limit and a recovery path on Confirm.

  • [MEDIUM] Restore Confirm after cancelling its recipient replacement — app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt:3725. Immediate cancellation holds for both tested Back controls and both jobs, but it does not restore the review being edited. AddressContinue overwrites shared state before the Savings wait. On device, cancelling a different 150,000-sat on-chain recipient returned to Confirm with that replacement address and amount instead of the original 35,000-sat Lightning request. Keep the replacement separate until preparation succeeds or restore the original review on Back.

QA for 488b7de:

Android regtest builds on Android 15 (API 35), with the real local Spark and Lightning fixtures. Device cases used the uncommitted controls disclosed below; the pristine head was built and checked separately.

Keep unified Lightning available through a queued restart ✅ A unified 200,000-sat request waited through a held stop and queued restart, then reached uncovered Confirm on Spending after channel recovery.

case18-2x.2x.mp4

Keep a typed invoice pending through a queued restart ✅ A typed 200,000-sat invoice became valid after queued startup without editing and reached uncovered Confirm, checked in the follow-up UI snapshot and still after the recording ended.

case19-2x.2x.mp4

Restore Amount capacity after a channel reconnects ✅ Available rose from 49,798 to 489,998 after the real peer reconnected, and 200,000 sats reached uncovered Confirm.

case20-2x.2x.mp4

Keep payment progress visible before its result arrives ✅ Confirm kept progress after the real 400,000-sat Spark payment and moved to success on release; logs verify native startup stayed held and live Spark capacity fell below the amount, and the recipient independently confirmed settlement.

case21-2x.2x.mp4

Dismiss the connection toast before payment feedback ✅ Connecting gave way to Insufficient Spending Balance after real recovery and stayed gone after the error cleared.

case22-2x.2x.mp4

Use a deposit received while the node was stopped ❌ Manual entry refused a real 100,000-sat deposit while Running with stale Savings; releasing publication and editing the same address enabled Continue and reached Amount.

case23-2x.2x.mp4

Cancel manual preparation as soon as Back returns ✅ Toolbar Back cancelled held validation and Continue decode during the exit transition, and system Back cancelled the real LNURL startup wait without late navigation or feedback after recovery.

case24-2x.2x.mp4

Check: Build and run existing regressions ✅ The pristine build and existing focused send-flow, overlay and node regression classes passed.
Check: Keep Confirm valid when an outgoing Amount quote returns ❌ A replacement Max quote started after navigation and silently invalidated Confirm in an actual ViewModel regression.

The temporary regression uses the actual ViewModel with controlled repository responses. Navigation was observed before the replacement quote began; no production implementation was changed.

    @Test
    fun `review late Amount quote keeps Confirm valid after navigation`() = test {
        val bolt11 = "lnbcrt1reviewlatequote"
        val channel = createChannelDetails().copy(channelId = "quote-channel", isUsable = true)
        val lifecycle = MutableStateFlow(LightningState(
            nodeLifecycleState = NodeLifecycleState.Running,
            channels = persistentListOf(channel),
        ))
        whenever(lightningRepo.lightningState).thenReturn(lifecycle)
        balanceState.value = BalanceState(maxSendLightningSats = 100_000u)
        whenever(lightningRepo.canSendWithSpark(any())).thenReturn(false)
        whenever(lightningRepo.canSendWithSpark(1u)).thenReturn(true)
        whenever(lightningRepo.canSendWithSpark(39_950u)).thenReturn(true)
        whenever(lightningRepo.canSendWithSpark(39_970u)).thenReturn(true)
        whenever(lightningRepo.canSendWithSpark(40_000u)).thenReturn(true)
        whenever(lightningRepo.canSend(any())).thenReturn(true)
        whenever(lightningRepo.estimateRoutingFeesForAmount(bolt11, 39_950u))
            .thenReturn(Result.success(20u))
        val quote = CompletableDeferred<Result<ULong>>()
        whenever(lightningRepo.estimateMaxSendFee(bolt11, 40_000u)).doSuspendableAnswer { quote.await() }
        setSendState(SendUiState(
            payMethod = SendMethod.LIGHTNING,
            decodedInvoice = lightningInvoice(bolt11, 0u),
            amount = 39_950u,
            estimatedRoutingFee = 20u,
            isAmountInputValid = true,
        ))
        sut.sendEffect.test {
            sut.setSendEvent(SendEvent.AmountContinue)
            advanceUntilIdle()
            assertEquals(SendEffect.NavigateToConfirm, awaitItem())
        }
        assertTrue(sut.sendUiState.value.isAmountInputValid)
        // Channel loss changes the displayed ceiling during Amount's exit; the old reserve still fits.
        lifecycle.value = lifecycle.value.copy(channels = persistentListOf(channel.copy(isUsable = false)))
        balanceState.value = BalanceState(maxSendLightningSats = 40_000u)
        advanceUntilIdle()
        assertTrue(sut.sendUiState.value.isAmountInputValid, "Capacity change alone rejected the amount")
        assertEquals(20uL, sut.sendUiState.value.estimatedRoutingFee)
        // Amount stays composed during its exit and can emit the replacement ceiling quote.
        sut.setSendEvent(SendEvent.EstimateMaxRoutingFee(bolt11, 40_000u))
        runCurrent()
        quote.complete(Result.success(120u))
        advanceUntilIdle()
        assertEquals(39_950uL, sut.sendUiState.value.amount)
        assertTrue(sut.sendUiState.value.isAmountInputValid, "Late Amount quote disabled the accepted Confirm")
    }

Use Savings published during a unified Lightning wait ❌ The 900,000-sat unified fallback reported a 100,179-sat shortfall after Savings was published at 1,100,000; logs and cache snapshots verify publication during its Lightning wait.

case26-2x.2x.mp4

Restore the reviewed recipient when its replacement is cancelled ❌ Back during the held recipient replacement returned to Confirm with the abandoned 150,000-sat address and amount instead of the original 35,000-sat Lightning request.

case27-2x.2x.mp4

Temporary ViewModel regressions

Ran against pristine production sources; only these test methods were added locally.

    @Test
    fun `review unified fallback uses Savings published during Lightning wait`() = test {
        val bolt11 = "lnbcrt1reviewfreshunified"
        val uri = "bitcoin:$REGTEST_ADDRESS?amount=0.0015&lightning=$bolt11"
        stubUnifiedScan(uri, bolt11, 150_000u, FOREIGN_NODE_ID.fromHex())
        balanceState.value = BalanceState(maxSendOnchainSats = 0u)
        val lifecycle = MutableStateFlow(LightningState())
        whenever(lightningRepo.lightningState).thenReturn(lifecycle)
        whenever(lightningRepo.awaitNodeId()).thenReturn(OWN_NODE_ID)
        whenever(lightningRepo.canSend(any())).thenReturn(false)
        whenever(lightningRepo.waitForUsableChannels()).doSuspendableAnswer {
            lifecycle.value = LightningState(nodeLifecycleState = NodeLifecycleState.Running)
            balanceState.value = BalanceState(maxSendOnchainSats = 200_000u)
            Unit
        }
        sut.setIsAuthenticated(true)
        clearInvocations(toastManager)
        sut.onScanResult(uri)
        advanceUntilIdle()
        assertEquals(200_000uL, balanceState.value.maxSendOnchainSats)
        val toasts = argumentCaptor<Toast>()
        verify(toastManager, atLeastOnce()).enqueue(toasts.capture())
        assertFalse(toasts.allValues.any { it.testTag == "InsufficientSavingsToast" },
            "Unified fallback refused freshly published Savings")
        assertTrue(sut.currentSheet.value is Sheet.Send)
        assertEquals(150_000uL, sut.sendUiState.value.amount)
    }

    @Test
    fun `review Back restores the confirmed recipient after a held replacement`() = test {
        val input = stubOnchainAmountScan(amountSats = 150_000u)
        val entered = CompletableDeferred<Unit>()
        val release = CompletableDeferred<Unit>()
        whenever(lightningRepo.awaitPendingNodeStart()).doSuspendableAnswer {
            entered.complete(Unit)
            release.await()
            Unit
        }
        sut.showSheet(Sheet.Send())
        advanceUntilIdle()
        val original = SendUiState(
            address = "lnbcrt1originalconfirmed",
            decodedInvoice = lightningInvoice("lnbcrt1originalconfirmed", 35_000u),
            amount = 35_000u,
            isAmountInputValid = true,
            payMethod = SendMethod.LIGHTNING,
        )
        setSendState(original)
        sut.setSendEvent(SendEvent.AddressContinue(input))
        advanceUntilIdle()
        assertTrue(entered.isCompleted)
        assertEquals(150_000uL, sut.sendUiState.value.amount)
        sut.onAddressBack()
        release.complete(Unit)
        advanceUntilIdle()
        assertEquals(original.address, sut.sendUiState.value.address,
            "Back retained the cancelled replacement recipient")
        assertEquals(original.amount, sut.sendUiState.value.amount)
    }

Earlier device coverage relied on, where the later delta leaves the tested path unchanged:

The Savings and recipient-replacement failures are also reported in @piotr-iohk’s device QA.

Reviewed the contiguous delta from 6c6e88c to 488b7de, all three changed files and the unresolved concerns. The explicitly deferred Paykit concerns and declined checks remain closed.

The post-navigation Max quote ordering was checked with the actual ViewModel; a device ceiling change during the exit animation was not driven.

Pair PR synonymdev/bitkit-ios#1578 matches the admission and submission intent; its manual Savings change at ca601a8 also treats Running as fresh. This was a source comparison; no iOS device case ran here.

Test controls

Not pushed. Debug/E2E-only file holds pause real native start/stop, balance publication, real send-result delivery through both the return and success event, scan decode or validation. Shell-only controls copy input and reconnect the real peer. They do not replace a payment result or balance; earlier cases used the relevant subset of these controls.

diff --git a/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt b/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
index 289131a72..d94b9fb9d 100644
--- a/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
+++ b/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
@@ -14,6 +14,8 @@ import kotlinx.serialization.Serializable
 import kotlinx.serialization.json.Json
 import to.bitkit.async.ServiceQueue
 import to.bitkit.models.msatCeilOf
+import to.bitkit.env.Env // test hook
+import to.bitkit.services.LightningService // test hook
 import to.bitkit.nfc.NfcDevOverride
 import to.bitkit.repositories.LightningRepo
 import to.bitkit.repositories.ProbeOutcome
@@ -34,6 +36,7 @@ class DevToolsProvider : ContentProvider() {
     @InstallIn(SingletonComponent::class)
     interface Dependencies {
         fun lightningRepo(): LightningRepo
+        fun lightningService(): LightningService // test hook
     }
 
     private val deps: Dependencies by lazy {
@@ -44,6 +47,17 @@ class DevToolsProvider : ContentProvider() {
     override fun call(method: String, arg: String?, extras: Bundle?): Bundle {
         check(Binder.getCallingUid() == SHELL_UID) { "Only ADB shell callers are allowed" }
         return runCatching {
+            if (Env.isE2eTest && method == "reviewCopy") { // test hook
+                val clipboard = requireNotNull(context).getSystemService(android.content.ClipboardManager::class.java) // test hook
+                clipboard.setPrimaryClip(android.content.ClipData.newPlainText("review", requireNotNull(arg))) // test hook
+                return@runCatching DevResult.Ack() // test hook
+            } // test hook
+            if (Env.isE2eTest && method == "reviewReconnect") { // test hook
+                return@runCatching ServiceQueue.LDK.blocking { // test hook
+                    requireNotNull(deps.lightningService().node).connect(requireNotNull(arg), "127.0.0.1:42645", persist = true) // test hook
+                    DevResult.Ack() // test hook
+                } // test hook
+            } // test hook
             // Needs no node, so it does not wait behind LDK work.
             if (method == OverrideNfc.METHOD) return@runCatching OverrideNfc.execute(arg)
             val command = requireNotNull(DevCommand.parse(method, arg)) { "Unknown command: '$method'" }
diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt
index cfef315d0..0cd85d0e4 100644
--- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt
+++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt
@@ -544,6 +544,14 @@ class LightningRepo @Inject constructor(
                     return@withLock adoptRunningNode()
                 }
 
+                if (Env.isDebug && Env.isE2eTest) { // test hook
+                    val hold = File(Env.ldkStoragePath(0), "review-node-hold") // test hook
+                    if (hold.exists()) { // test hook
+                        Logger.info("Holding native node start for review test", context = TAG) // test hook
+                        while (hold.exists()) delay(100.milliseconds) // test hook
+                        Logger.info("Released native node start for review test", context = TAG) // test hook
+                    } // test hook
+                } // test hook
                 lightningService.start(timeout, ::onEvent)
 
                 _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Running) }
@@ -896,6 +904,14 @@ class LightningRepo @Inject constructor(
                 // so it is dropped before the state change that ends its review.
                 reviewedPreparedSend.getAndSet(null)?.release()
                 _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Stopping) }
+                if (Env.isDebug && Env.isE2eTest) { // test hook
+                    val hold = File(Env.ldkStoragePath(0), "review-stop-hold") // test hook
+                    if (hold.exists()) { // test hook
+                        Logger.info("Holding stopping node for review test", context = TAG) // test hook
+                        while (hold.exists()) delay(100.milliseconds) // test hook
+                        Logger.info("Released stopping node for review test", context = TAG) // test hook
+                    } // test hook
+                } // test hook
                 lightningService.stop()
                 clearProbeOutcomes()
                 _lightningState.update {
diff --git a/app/src/main/java/to/bitkit/repositories/WalletRepo.kt b/app/src/main/java/to/bitkit/repositories/WalletRepo.kt
index 72f5b9125..514061f59 100644
--- a/app/src/main/java/to/bitkit/repositories/WalletRepo.kt
+++ b/app/src/main/java/to/bitkit/repositories/WalletRepo.kt
@@ -64,6 +64,7 @@ import javax.inject.Inject
 import javax.inject.Singleton
 import kotlin.coroutines.cancellation.CancellationException
 import kotlin.time.Duration.Companion.seconds
+import kotlin.time.Duration.Companion.milliseconds
 
 @Singleton
 class WalletRepo @Inject constructor(
@@ -460,6 +461,14 @@ class WalletRepo @Inject constructor(
     }
 
     suspend fun syncBalances() {
+        if (Env.isDebug && Env.isE2eTest) { // test hook
+            val hold = java.io.File(Env.ldkStoragePath(0), "review-balances-hold") // test hook
+            if (hold.exists()) { // test hook
+                Logger.info("Holding balance publication for review", context = TAG) // test hook
+                while (hold.exists()) delay(100.milliseconds) // test hook
+                Logger.info("Released balance publication for review", context = TAG) // test hook
+            } // test hook
+        } // test hook
         deriveBalanceStateUseCase().onSuccess { balanceState ->
             runCatching { cacheStore.cacheBalance(balanceState) }
             _balanceState.update { balanceState }
diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt
index 0a1cbc11b..f70346605 100644
--- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt
+++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt
@@ -3370,6 +3370,14 @@ class AppViewModel @Inject constructor(
     }
 
     private suspend fun handlePaymentSuccessful(event: Event.PaymentSuccessful) {
+        if (Env.isDebug && Env.isE2eTest) { // test hook
+            val hold = java.io.File(Env.ldkStoragePath(0), "review-result-hold") // test hook
+            if (hold.exists()) { // test hook
+                Logger.info("Holding real payment event for review; running=${isSendSwipeRunning.value}; sparkCoversAcceptedAmount=${lightningRepo.canSendWithSpark(_sendUiState.value.amount)}", context = TAG) // test hook
+                while (hold.exists()) delay(100.milliseconds) // test hook
+                Logger.info("Released real payment event for review", context = TAG) // test hook
+            } // test hook
+        } // test hook
         val paymentHash = event.paymentHash
         viewModelScope.launch {
             paykitPaymentProofRepo.completeLightningPayment(paymentHash, event.paymentPreimage)
@@ -3721,6 +3729,7 @@ class AppViewModel @Inject constructor(
 
     /** Back from manual entry drops the request its Continue was preparing, so it cannot open Amount later. */
     fun onAddressBack() {
+        if (Env.isDebug && Env.isE2eTest) Logger.info("Review Address Back cancels both jobs", context = TAG) // test hook
         cancelAddressValidation()
         cancelSendVisitScan()
     }
@@ -3837,6 +3846,17 @@ class AppViewModel @Inject constructor(
                 waitForUsableChannels(amountSats = invoice.amountSatoshis)
                 lightningRepo.syncState()
             }
+            if (Env.isDebug && Env.isE2eTest) { // test hook
+                val hold = java.io.File(Env.ldkStoragePath(0), "review-validation-hold") // test hook
+                if (hold.exists()) { // test hook
+                    Logger.info("Holding manual capacity result for review", context = TAG) // test hook
+                    try { // test hook
+                        while (hold.exists()) delay(100.milliseconds) // test hook
+                    } finally { // test hook
+                        Logger.info("Ended manual capacity result hold for review", context = TAG) // test hook
+                    } // test hook
+                } // test hook
+            } // test hook
             if (!lightningRepo.canSend(invoice.amountSatoshis)) {
                 val maxSendLightning = walletRepo.balanceState.value.maxSendLightningSats
                 val shortfall = invoice.amountSatoshis.safe() - maxSendLightning.safe()
@@ -5988,6 +6008,17 @@ class AppViewModel @Inject constructor(
             }
         }
 
+        if (Env.isDebug && Env.isE2eTest) { // test hook
+            val hold = java.io.File(Env.ldkStoragePath(0), "review-scan-hold") // test hook
+            if (hold.exists()) { // test hook
+                Logger.info("Holding Continue scan decode for review", context = TAG) // test hook
+                try { // test hook
+                    while (hold.exists()) delay(100.milliseconds) // test hook
+                } finally { // test hook
+                    Logger.info("Ended Continue scan decode hold for review", context = TAG) // test hook
+                } // test hook
+            } // test hook
+        } // test hook
         val scan = runSuspendCatching { coreService.decode(input) }
             .onFailure {
                 if (isPaymentRequest) {
@@ -9044,6 +9075,14 @@ class AppViewModel @Inject constructor(
         } else {
             lightningRepo.payInvoice(bolt11, amount, paymentDeadlineAt, onBeforeSend)
         }
+        if (Env.isDebug && Env.isE2eTest) { // test hook
+            val hold = java.io.File(Env.ldkStoragePath(0), "review-result-hold") // test hook
+            if (hold.exists()) { // test hook
+                Logger.info("Holding actual send result for review; running=${isSendSwipeRunning.value}; sparkCoversAcceptedAmount=${lightningRepo.canSendWithSpark(_sendUiState.value.amount)}", context = TAG) // test hook
+                while (hold.exists()) delay(100.milliseconds) // test hook
+                Logger.info("Released actual send result for review", context = TAG) // test hook
+            } // test hook
+        } // test hook
         return sent.onSuccess { hash ->
             fun outcome(event: Event): Result<PaymentId>? = when (event) {
                 is Event.PaymentSuccessful if event.paymentHash == hash -> Result.success(hash)


Reviewed by gpt-6.1-sol-high

jvsena42 and others added 2 commits December 4, 2026 14:57
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@piotr-iohk

piotr-iohk commented Dec 4, 2026 •

Copy link
Copy Markdown
Collaborator

Android regtest device retest at b156c2b

Tested b156c2b2ed2f47f33b575d22881f2b47957aff30 on an Android 13 emulator with a debug-only hold immediately before native Lightning startup. The head advanced during the run. These results cover the tested commit.

  • FAIL · Fresh Savings during startup. A fixed 30,000-sat unified invoice fell back to Savings and showed Insufficient Savings as a confirmed 80,000-sat deposit appeared. The identical invoice opened Confirm → Savings → 30,000 sats after sync.
  • PASS · Back cancels the replacement. From a 12,000-sat Spending review, I entered a 120,000-sat on-chain replacement and pressed system Back during Connecting to network with the keyboard hidden. After startup, Confirm showed zero and an empty recipient. The replacement never became payable. The original draft cleared, which is tracked separately. Author’s explanation

The tested build captured the Savings limit before checking the Lightning leg. The trace shows native sync and wallet balance publication as separate events. The newer Savings fix will get its own retest.

Savings failure and same-invoice control
During startup Same request after sync
Insufficient Savings over the 80,000-sat deposit receipt Savings Confirm for 30,000 sats after sync
f1-timing.mp4
17:58:23.393 UTC  Pasted unified invoice
17:58:29.658 UTC  Startup hold released
17:58:33.345 UTC  LDK on-chain spendable balance changed from 0 to 80,000 sats
17:58:34.269 UTC  LDK reported its sync completed
17:58:35.126 UTC  AppViewModel fell back from Lightning to on-chain
17:58:36.276 UTC  Derived wallet balance showed 80,000 sats, 79,890 sats maximum sendable
17:59:38.681 UTC  Pasted the same invoice and reached 30,000-sat Savings Confirm

The false error is visible about 14–16 seconds into the recording.

Back cancellation before and after releasing startup
Original Spending review After Back and startup release
Original Spending Confirm for 12,000 sats Confirm shows zero and a blank recipient after cancellation
f2-back-and-release.mp4

System Back at 18:02:37 UTC. Startup released at 18:02:43 UTC. No payment was submitted from either tested review.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@jvsena42

jvsena42 commented Dec 4, 2026

Copy link
Copy Markdown
Member Author

@piotr-iohk thanks for the retest at b156c2b. Your timeline showed one more gap: LDK reported its sync complete (:34.269) before the derived balance was published (:36.276), and the fallback checked in between (:35.126). 5ef6500 re-reads the published balance, but in that window it still read 0.

Fixed in 31b8a8a: when cached Savings would refuse and the node has already synced, the check now derives balances from the node (syncBalances) before deciding, instead of waiting for the next publication. Before the first sync it still waits for the node and syncs. Test a refusal after the node synced derives savings the sync has not yet published (0 published, 79,890 in the node, 30,000 request) fails without the fix and passes with it. 7,065 unit tests pass, detekt is clean.

@piotr-iohk

Copy link
Copy Markdown
Collaborator

Android regtest device retest at 31b8a8a

Both targeted checks passed on 31b8a8a84faf52d6cfd87c69f37a7ce66717fc05 on an Android 13 emulator with local Spark regtest. A debug-only file hold paused native Lightning startup. Neither test submitted a payment.

  • PASS · Fresh Savings during startup. With zero cached Savings, I pasted a fixed unified invoice for 30,000 sats while startup was held. Lightning could not cover it. The initial paste reached Confirm → Savings → 30,000 sats as the confirmed 80,000-sat deposit became available, without an Insufficient Savings error or a second paste. The logs show that native sync still completed before the wallet published its balance.
  • PASS · Back cancels the replacement. I opened a 12,000-sat Spending review, entered a 120,000-sat on-chain replacement and pressed system Back during Connecting to network with the keyboard hidden. After startup, Confirm showed zero and a blank recipient. The replacement never became payable. The original draft cleared, as it does on a new scan at the PR base.

Previous recorded failure on b156c2b

Savings startup evidence
Confirmed deposit Savings confirmation
80,000-sat deposit receipt 30,000-sat Savings Confirm
f1-timing.mp4
18:17:21.288 UTC  Pasted unified invoice
18:17:26.955 UTC  Startup hold released
18:17:29.752 UTC  LDK on-chain spendable balance changed from zero to 80,000 sats
18:17:30.115 UTC  Native Lightning sync completed
18:17:30.284 UTC  Unified invoice fell back to Savings
18:17:33.141 UTC  Derived wallet balance showed 80,000 sats, 79,890 sats maximum sendable
Back cancellation evidence
Before replacement After Back and startup release
Original 12,000-sat Spending Confirm Zero and an empty recipient after startup
f2-back-and-release.mp4

System Back at 18:19:42 UTC. Startup released at 18:19:49 UTC.

@ovi-reviewer ovi-reviewer 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.

Verdict: 💬 Comment — reviewed 187e507; superseded by 31b8a8a.

The PR moved to 31b8a8a after this run; these results are for 187e507.

The existing Savings issue reproduced on this head. The author subsequently fixed the publication gap, and @piotr-iohk’s device retest passed on 31b8a8a. This review records the older-head evidence and does not approve or request changes on the newer implementation.

Findings: The existing MEDIUM Savings issue reproduced at 187e507; no duplicate inline finding.

  • MEDIUM — Native sync completes before Savings is published (app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt:6661, also manual validation at :3903). hasSyncedSavings() trusts the node’s successful-sync timestamp, which can precede WalletRepo.syncBalances(). With a real 100,000-sat deposit, native sync healthy and published Savings held at zero, manual entry rejected a 30,000-sat request. Releasing publication enabled the identical input and reached Confirm. The new re-read handles balances already published during the Lightning wait, but this intermediate window still fails at the reviewed head. This is the existing Savings thread, addressed by the superseding fix linked above.

QA for 187e507: Android 15 regtest, with real on-chain funds. The pristine head was built separately; the device copy added only the temporary controls disclosed below.

Check: Build and run existing regressions ✅ The pristine app build and existing send-flow, overlay and node regression classes passed.

Built assembleDevDebug and ran AppViewModelSendFlowTest, SendSheetSyncOverlayTest and LightningRepoTest. A separate temporary test of the actual ViewModel reproduced the Savings rejection with a non-null native-sync timestamp and a zero published balance.

Use a deposit received while the node was stopped ❌ Manual entry refused 30,000 sats before Savings publication; the same input became valid after publication and reached Confirm.

Additional case 23. A real 100,000-sat deposit confirmed while the app was stopped. After restart, the native node completed sync while balance publication remained held at zero. Device logs and the readiness query establish that ordering. Releasing publication produced a 99,890-sat sendable balance. No payment was submitted.

The warning still captures Insufficient Savings. The recording shows manual entry and recovery to enabled Continue; the final still shows the subsequent Confirm screen.

case23-2x.2x.mp4

Check: Keep Confirm valid when a queued Amount quote returns ⏭️ The transition check was not completed before the head advanced.

Additional case 25. The first actual-ViewModel probe, queuing a quote while Continue awaited its fee, was correctly caught by the final navigation guard. A narrower probe of a quote arriving during that final guard did not complete. No further quote defect is claimed from those probes, and no device exit-animation case ran.

Use Savings published during a unified Lightning wait ⏭️ Not started on this head before the superseding push.

Additional case 26. The new re-read and its existing regression were checked, but this run did not independently drive the changed fallback on a device. The newer-head device report linked above covers its subsequent fix.

Discard a cancelled recipient replacement ✅ Carried from the recorded b156c2b device retest; this delta leaves the tested cancellation and write ordering unchanged.

Additional case 27. @piotr-iohk’s b156c2b report proves that Back during the held replacement returns an empty, zero-amount review and never makes the abandoned recipient payable. The original draft clearing was explicitly deferred; it is not re-raised here. The relevant existing regression also passes at 187e507.

Other earlier device evidence retained where the implementation is unchanged:

Reviewed all four files in the contiguous b156c2b..187e507 delta, their callers and the earlier open Savings, quote and Back concerns. Cases 25 and 26 remain unrun on this head after the push. The Paykit deferrals and other explicitly declined checks remain closed.

Twin: synonymdev/bitkit-ios#1578 matches the recipient, amountless-entry and submitted-payment intent. Source comparison at ca601a8 shows platform-specific Savings validation and fee handling; no iOS device case ran here.

Temporary device controls

Not pushed. Debug/E2E-only file holds pause native startup and derived balance publication until explicit release. A shell-only helper copies the request to the clipboard. No balance, payment result or Send decision is replaced.

diff --git a/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt b/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
index 289131a72..e7815154c 100644
--- a/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
+++ b/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
@@ -44,6 +44,12 @@ class DevToolsProvider : ContentProvider() {
     override fun call(method: String, arg: String?, extras: Bundle?): Bundle {
         check(Binder.getCallingUid() == SHELL_UID) { "Only ADB shell callers are allowed" }
         return runCatching {
+            if (to.bitkit.env.Env.isE2eTest && method == "reviewCopy") {
+                val clipboard = requireNotNull(context).getSystemService(android.content.ClipboardManager::class.java)
+                clipboard.setPrimaryClip(android.content.ClipData.newPlainText("review", requireNotNull(arg)))
+                return@runCatching DevResult.Ack()
+            }
+
             // Needs no node, so it does not wait behind LDK work.
             if (method == OverrideNfc.METHOD) return@runCatching OverrideNfc.execute(arg)
             val command = requireNotNull(DevCommand.parse(method, arg)) { "Unknown command: '$method'" }
diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt
index cfef315d0..a99e418ee 100644
--- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt
+++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt
@@ -544,6 +544,14 @@ class LightningRepo @Inject constructor(
                     return@withLock adoptRunningNode()
                 }
 
+                if (Env.isDebug && Env.isE2eTest) {
+                    val hold = File(Env.ldkStoragePath(0), "review-node-hold")
+                    if (hold.exists()) {
+                        Logger.info("Holding native node start for review", context = TAG)
+                        while (hold.exists()) delay(100.milliseconds)
+                        Logger.info("Released native node start for review", context = TAG)
+                    }
+                }
                 lightningService.start(timeout, ::onEvent)
 
                 _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Running) }
diff --git a/app/src/main/java/to/bitkit/repositories/WalletRepo.kt b/app/src/main/java/to/bitkit/repositories/WalletRepo.kt
index 72f5b9125..942ffdbb3 100644
--- a/app/src/main/java/to/bitkit/repositories/WalletRepo.kt
+++ b/app/src/main/java/to/bitkit/repositories/WalletRepo.kt
@@ -64,6 +64,7 @@ import javax.inject.Inject
 import javax.inject.Singleton
 import kotlin.coroutines.cancellation.CancellationException
 import kotlin.time.Duration.Companion.seconds
+import kotlin.time.Duration.Companion.milliseconds
 
 @Singleton
 class WalletRepo @Inject constructor(
@@ -460,6 +461,14 @@ class WalletRepo @Inject constructor(
     }
 
     suspend fun syncBalances() {
+        if (Env.isDebug && Env.isE2eTest) {
+            val hold = java.io.File(Env.ldkStoragePath(0), "review-balances-hold")
+            if (hold.exists()) {
+                Logger.info("Holding balance publication for review; nativeSync=${lightningRepo.lightningState.value.lastSuccessfulSyncAt}", context = TAG)
+                while (hold.exists()) delay(100.milliseconds)
+                Logger.info("Released balance publication for review", context = TAG)
+            }
+        }
         deriveBalanceStateUseCase().onSuccess { balanceState ->
             runCatching { cacheStore.cacheBalance(balanceState) }
             _balanceState.update { balanceState }

Reviewed by gpt-6.1-sol-high

@piotr-iohk

Copy link
Copy Markdown
Collaborator

Original Spark Send issue · Android regtest

Tested 31b8a8a84faf52d6cfd87c69f37a7ce66717fc05 on the Android 13 emulator with a disposable wallet funded in Spark. Before each run I left the app in the background for over 30 seconds, verified that the native Lightning node stopped, and held its next startup with a debug-only file marker.

Case Result while Lightning startup was held Controlled recipient
Fixed Lightning invoice PASS. Recipient opened, Spending Confirm showed 1,200 sats, and the sender showed Bitcoin Sent. 1,200 sats settled at 18:37:36 UTC.
Amountless Lightning invoice PASS. Bitcoin Amount and its keypad opened, 1,300 sats reached Spending Confirm, and the sender showed Bitcoin Sent. 1,300 sats settled at 18:40:33 UTC.

On the fixed run the first tap occurred during the foreground transition. I tapped Send again once Home was visible. Startup stayed held through both taps and the payment. The run verifies that Send works with the native node stopped.

Fixed invoice recording and sender receipt
ORIGINAL-FIXED.mp4

Bitcoin Sent for 1,200 sats

Amountless invoice recording and sender receipt
ORIGINAL-AMOUNTLESS.mp4
Entered with Lightning held Sender receipt
Bitcoin Amount with 1,300 sats entered Bitcoin Sent for 1,300 sats
Independent LDK receiver receipts
18:37:36 UTC  fixed       1,200 sats  INBOUND  SUCCEEDED  hash 34c01e8f0f4f…
18:40:33 UTC  amountless  1,300 sats  INBOUND  SUCCEEDED  hash cec0c6a300d2…
Both receipts were verified before releasing native startup.

Same-head Savings and Back regression retests

@piotr-iohk

Copy link
Copy Markdown
Collaborator

Send E2E failure on 31b8a8a

@send_2 timed out at ReviewAmount on all three attempts. The test enables QuickPay and later expects a 10,000-sat invoice to exceed its $5 limit. The timeout screenshots show Bitcoin Sent for 10,000 sats and values of $4.99, $4.99 and $4.98. Attempt 3 logged Using QuickPay for '10000' sats and Appium saw SendSuccess. Send E2E job · Pinned E2E assertion

The $5 default and fiat-based eligibility check match the PR base. To exercise manual review with QuickPay enabled, pin the exchange rate and use an invoice that exceeds the configured limit.

Three E2E timeout screenshots showing Bitcoin Sent for 10,000 sats

@jvsena42

jvsena42 commented Dec 4, 2026

Copy link
Copy Markdown
Member Author

@piotr-iohk thanks. Agreed it isn't from this PR: @send_2 assumes 10,000 sats is above the $5 QuickPay limit, and at today's rate it converts to $4.98–4.99, so QuickPay pays it, as it would on the base. The fix belongs in bitkit-e2e-tests (pin the rate or use an amount clearly above the limit); I'll leave that to a separate change there rather than this PR.

@piotr-iohk piotr-iohk left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

QA review

Scope: RC4 code-only follow-up on Android #2244 from 488b7de through 31b8a8a, including all changes after b156c2b and affected callers. Unchanged coverage comes from the completed Android baseline. The read-only iOS #1578 comparison at ca601a8 covered recipient loading, manual Continue and cancellation, native Savings fallback, and Amount fee state. Android PR · Baseline revision · Completed baseline · Reviewed Android revision · iOS comparison revision

2 actionable findings — resolve or provide an evidence-backed rebuttal. 2 from earlier unpublished work appear here for the first time.

Remaining decisions

  • amountless-lightning-max-quote-crosses-confirm-navigation — The resolved thread's latest fix drops callbacks after Amount leaves the destination. The same swipe invalidation can still follow a callback admitted after Continue's final check emits navigation and before Confirm becomes current. The destination guard eliminates callbacks from an Amount screen after the route has changed. A callback before the collector applies the route is allowed even though Continue already committed to navigation. The frozen discovery's Kotlin coroutine probe reproduced dispatch between the final check and destination update. The pinned test in SendSheetSyncOverlayTest.kt:17–22 checks the predicate with a supplied destination flag and does not exercise collection timing. Bind quote completion to the active amount edit or settle the quote before committing navigation. Exercise a ceiling change between the emission and route change.
  • paykit-amountless-contact-live-spark-validation-cached-routing-limit — The resolved thread records a deferral that another reviewer acknowledged. A mixed-endpoint contact can still accept an amount on the pad and refuse it at routing. Identify the Paykit work item and decide where the effective Spending capacity will be passed to the router.
  • [HIGH] send-contact-scan-outlives-dismissal-and-loses-quickpay-guard — The resolved thread records a refactor deferral. The abandoned-contact QuickPay path in L4 remains reachable under the stated unlocked, reopened-visit conditions. Decide where the visit-ownership guard will ship. Bind contact preparation to the originating Send visit and cancel or invalidate it at dismissal before it can reach QuickPay.
  • manual-recipient-savings-refusal-before-balance-publication — The resolved thread discussed manual entry alongside the direct and unified routes. The derived refresh now works after dispatch reaches scan preparation. Manual validation can still present a terminal refusal before the user can dispatch Continue. The new live derivation happens after Continue, while the manual validator still treats a native success marker as sufficient to refuse using the earlier wallet snapshot. At 31b8a8a, the added syncBalances branch at AppViewModel.kt:6662–6664 sits downstream of Address validation. AppViewModelSendFlowTest.kt:12832–12854 dispatches AddressContinue directly, bypassing SendAddressScreen.kt:74–78. Refresh the software Savings refusal before disabling Continue, or revalidate unchanged input when the fresh balance publishes. Retest through the actual manual button with wallet publication held.

Validation. Local diff checks and both connecting-journey XML parses passed. Frozen discovery recorded a focused Kotlin coroutine probe with simulated UI dispatch. Its local Android JVM suite stopped before running tests because GitHub Packages dependencies required credentials. The GitHub CI JVM report includes passing Savings, Back, and Max regressions on merge 28a32ec, which includes the reviewed head and CI base 831672b. CI run · JVM report

Pinned source used in reconciliation included LDK Node 3f45b8ec4eabca452697405518114beb001ffa02, its locked lightning 0.2.8, Bitkit Core 045c7ff68529d9ffb8135de3b27916447f64b0c4, and Spark SDK a273276885f94cdc52366b9c85993648cd1d7445. Frozen discovery also inspected Paykit 0b9c63d25dbd0cd5e7cf6ec577bc170732d350be and Appium specs 9a64fa31399d4a148a0bc105f47e17966c2430b5. LDK Node · Bitkit Core · Spark SDK · Paykit · Appium specs

Device testing was not performed in this review. Piotr reports that 31b8a8a passed the 30,000-sat unified Savings retest with an 80,000-sat deposit and the system Back safety check on Android 13 regtest. Neither targeted check submitted a payment. Piotr separately observed settlement of a 1,200-sat fixed and a 1,300-sat amountless Spark send with startup held on the same revision. The prior Savings refusal was observed at b156c2b. Matching-head Savings and Back · Matching-head Spark settlement · Earlier device evidence

Suggested additional test cases

  • Retain J1 and manual cases 1–7 for the candidate run. Author QA plan
  • Stage the 80,000-sat deposit against the 30,000-sat unified request on Android regtest. Control publication during the Lightning wait and hold the first sync before the native wallet applies the deposit in separate runs. Assert that the initial request reaches Savings Confirm with the exact recipient and amount. For Enter Manually, hold wallet publication after native sync and assert that the unchanged input can Continue.
  • Repeat the held 120,000-sat replacement with toolbar Back, then release the refresh with sufficient funds. Assert that the abandoned recipient never opens Confirm or becomes payable.
  • Change the available Lightning balance during Continue's fee estimate on an amountless invoice. Deliver the new Max quote across the transition to Confirm and verify that the same invoice retains a usable swipe.

Earlier findings reconciled at this revision: 3 still present, 2 verified fixed.

Findings

  • [MEDIUM] Wait for startup sync to publish Savings before refusing the send — inline at app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt:6668. Still present from an earlier unpublished review.
  • [LOW] Reject below-minimum Paykit requests before waiting for Savings — inline at app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt:6390. Still present from an earlier unpublished review.

Existing concerns

  • [LOW] Document the startup hold and release for J1 — J1 still asks the tester to hold startup through Paste and then release it. Candidate QA Setup lists the regtest prerequisites but gives no executable hold-and-release recipe or link to one. The same-head device comment identifies a debug-only file hold used for those targeted retests.

Reviewer model: gpt-6.2-sol
Reasoning effort: high

jvsena42 and others added 2 commits December 4, 2026 16:48
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@ovi-reviewer ovi-reviewer 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.

Verdict: ⛔️ Request changes — the existing manual Savings refusal still reproduces at 0022954.

Findings:

  • MEDIUM — Refresh Savings before manual validation refuses the recipient (app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt:3903–3931). Native sync had applied a real 80,000-sat deposit, with 79,890 sats sendable, while derived balance publication was held at zero. Enter Manually rejected a 30,000-sat request and left Continue disabled. The refresh in liveMaxSendOnchain runs only after Continue, so this path cannot reach it. After publication and re-entering the same final digit, the identical request reached Savings Confirm. This adds device evidence to the existing Savings discussion, rather than a duplicate inline finding. Refresh or defer the manual refusal too.

The two changes in this delta hold: the active-sync wait preserves both direct and unified requests, and a below-minimum contact request skips that wait.

QA for 0022954: Android 15 regtest, with real on-chain deposits. The pristine head was built separately; the device copy used the uncommitted controls disclosed below. No payment was submitted from these confirmation screens. Savings as the selected rail was checked in the device log: native fee preparation built on-chain transactions for the respective 30,000-, 150,000- and 300,000-sat recipients.

Use fresh Savings during manual recipient validation ❌ A payable 30,000-sat request stayed invalid until its input was edited after publication.

Additional case 23. Only derived balance publication was held; native sync was healthy and had already applied the 80,000-sat deposit. Tapping the disabled Continue did nothing. Releasing publication and restoring the same final digit enabled Continue and opened Savings Confirm for 30,000 sats. A temporary actual-ViewModel regression independently reproduces the stale refusal.

manual-savings2x.2x.mp4

Wait for an active Savings sync before refusing a request ✅ The initial 150,000-sat request remained pending and reached Confirm after the new deposit was applied.

Additional case 28, verifying the active-sync fix. Savings initially held 80,000 sats. A real repository sync was held before its native call, and Electrum was stopped while a further 100,000-sat deposit confirmed. Paste showed Connecting without refusing the request. Restoring Electrum and releasing sync applied the deposit. The final 150,000-sat Confirm was checked in the follow-up snapshot after dismissing the receipt, after the recording ended.

active-sync2x.2x.mp4

Use fresh Savings after a unified Lightning fallback ✅ A 300,000-sat unified request waited through the active sync and reached Savings Confirm without a second paste.

Additional case 26. Neither Spark nor a channel could cover the Lightning leg. Savings still held 180,000 sats while a further 200,000-sat deposit awaited native sync. The request remained behind Connecting; after restoring Electrum and releasing sync, dismissing the deposit receipt revealed Confirm for 300,000 sats.

unified-sync2x.2x.mp4

Reject a below-minimum contact request without waiting for startup ✅ The empty wallet showed Amount Too Low before the queued restart completed.

Additional case 29, verifying the minimum-amount fix. A debug entry point supplied a synthetic 100-sat on-chain Paykit request to the normal openContactPayment path. Amount Too Low showed the 547-sat minimum before native startup was released; Home remained clear afterward. The existing regression also checks preparation cleanup and that no Savings sync is requested.

minimum-request2x.2x.mp4

Check: keep Continue behind a queued Max quote ✅ The actual ViewModel withheld Confirm when a queued reserve made the entered amount invalid.

Additional case 30. A controlled repository fee estimate kept Continue in flight while a 40,000-sat Max quote was queued. The final gate withheld navigation, and the returned 120-sat reserve invalidated 39,950 sats. The outgoing-destination predicate also refused the callback once Amount was no longer current. This was a JVM check, not a device exit-animation run.

Keep confirmation valid when a final Amount quote arrives ⏭️ The narrower window after the final guard and before the destination update remains unverified.

Additional case 25. No device run achieved a controlled ceiling update in that exact scheduling window. The valid queued-quote check above is caught by the final guard. No additional quote defect is claimed.

Check: build and run Send regressions ✅ The pristine pinned-head app build and focused existing regressions passed.

Ran assembleDevDebug, AppViewModelSendFlowTest, SendSheetSyncOverlayTest and LightningRepoTest, without failures or skips. The separate temporary manual-publication regression fails as described above; the queued-quote regression passes.

Earlier passing device evidence is retained where the reached behavior is unchanged:

Reviewed the contiguous 31b8a8a..0022954 delta, both changed files, their callers and the prior unresolved Savings and quote concerns. Read the full description, comments, reviews and inline discussion. Both new behaviors were driven; the exact quote/navigation window above was not. The explicit Paykit and original-draft-restoration deferrals remain closed.

Twin: synonymdev/bitkit-ios#1578, inspected at b3a1cda. Recipient/submission exemptions and the minimum-request short circuit match in intent; Savings freshness and deferred validation use platform-specific state. No iOS device case ran here.

Temporary test controls

Not pushed. Debug/E2E-only file holds pause real native startup, repository sync or derived balance publication until explicit release. Shell controls copy input and request a real sync; an extra launch argument supplies the synthetic 100-sat incoming request through the normal contact-payment entry point. The build points Electrum at the local regtest fixture. No SDK result, balance or send decision is replaced.

diff --git a/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt b/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
index 289131a72..e0be80ae9 100644
--- a/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
+++ b/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
@@ -44,6 +44,14 @@ class DevToolsProvider : ContentProvider() {
     override fun call(method: String, arg: String?, extras: Bundle?): Bundle {
         check(Binder.getCallingUid() == SHELL_UID) { "Only ADB shell callers are allowed" }
         return runCatching {
+            if (method == "reviewCopy" && to.bitkit.env.Env.isE2eTest) { // test hook
+                requireNotNull(context).getSystemService(android.content.ClipboardManager::class.java).setPrimaryClip(android.content.ClipData.newPlainText("review", requireNotNull(arg))) // test hook
+                return@runCatching DevResult.Ack() // test hook
+            } // test hook
+            if (method == "reviewSync" && to.bitkit.env.Env.isE2eTest) { // test hook
+                deps.lightningRepo().syncAsync() // test hook
+                return@runCatching DevResult.Ack() // test hook
+            } // test hook
             // Needs no node, so it does not wait behind LDK work.
             if (method == OverrideNfc.METHOD) return@runCatching OverrideNfc.execute(arg)
             val command = requireNotNull(DevCommand.parse(method, arg)) { "Unknown command: '$method'" }
diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt
index cfef315d0..240a3cb3a 100644
--- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt
+++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt
@@ -544,6 +544,14 @@ class LightningRepo @Inject constructor(
                     return@withLock adoptRunningNode()
                 }
 
+                if (Env.isDebug && Env.isE2eTest) { // test hook
+                    val hold = File(Env.ldkStoragePath(0), "review-node-hold") // test hook
+                    if (hold.exists()) { // test hook
+                        Logger.info("Holding native startup for review", context = TAG) // test hook
+                        while (hold.exists()) delay(100.milliseconds) // test hook
+                        Logger.info("Released native startup for review", context = TAG) // test hook
+                    } // test hook
+                } // test hook
                 lightningService.start(timeout, ::onEvent)
 
                 _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Running) }
@@ -958,6 +966,14 @@ class LightningRepo @Inject constructor(
             do {
                 syncPending.set(false)
                 _lightningState.update { it.copy(isSyncingWallet = true) }
+                if (Env.isDebug && Env.isE2eTest) { // test hook
+                    val hold = File(Env.ldkStoragePath(0), "review-sync-hold") // test hook
+                    if (hold.exists()) { // test hook
+                        Logger.info("Holding native sync for review", context = TAG) // test hook
+                        while (hold.exists()) delay(100.milliseconds) // test hook
+                        Logger.info("Released native sync for review", context = TAG) // test hook
+                    } // test hook
+                } // test hook
                 lightningService.sync()
                 refreshChannelCache()
                 syncState()
diff --git a/app/src/main/java/to/bitkit/repositories/WalletRepo.kt b/app/src/main/java/to/bitkit/repositories/WalletRepo.kt
index 72f5b9125..80a1d1c5a 100644
--- a/app/src/main/java/to/bitkit/repositories/WalletRepo.kt
+++ b/app/src/main/java/to/bitkit/repositories/WalletRepo.kt
@@ -64,6 +64,7 @@ import javax.inject.Inject
 import javax.inject.Singleton
 import kotlin.coroutines.cancellation.CancellationException
 import kotlin.time.Duration.Companion.seconds
+import kotlin.time.Duration.Companion.milliseconds // test hook
 
 @Singleton
 class WalletRepo @Inject constructor(
@@ -462,6 +463,14 @@ class WalletRepo @Inject constructor(
     suspend fun syncBalances() {
         deriveBalanceStateUseCase().onSuccess { balanceState ->
             runCatching { cacheStore.cacheBalance(balanceState) }
+            if (Env.isDebug && Env.isE2eTest) { // test hook
+                val hold = java.io.File(Env.ldkStoragePath(0), "review-balances-hold") // test hook
+                if (hold.exists()) { // test hook
+                    Logger.info("Holding derived publication max=${balanceState.maxSendOnchainSats} nativeSync=${lightningRepo.lightningState.value.lastSuccessfulSyncAt}", context = TAG) // test hook
+                    while (hold.exists()) delay(100.milliseconds) // test hook
+                    Logger.info("Released derived publication for review", context = TAG) // test hook
+                } // test hook
+            } // test hook
             _balanceState.update { balanceState }
         }.onFailure {
             if (it !is CancellationException) {
diff --git a/app/src/main/java/to/bitkit/ui/MainActivity.kt b/app/src/main/java/to/bitkit/ui/MainActivity.kt
index 8779a86cd..a2aca0760 100644
--- a/app/src/main/java/to/bitkit/ui/MainActivity.kt
+++ b/app/src/main/java/to/bitkit/ui/MainActivity.kt
@@ -306,6 +306,18 @@ class MainActivity : FragmentActivity() {
     }
 
     private fun handleLaunchIntent(intent: Intent) {
+        if (to.bitkit.env.Env.isDebug && to.bitkit.env.Env.isE2eTest && intent.hasExtra("reviewRequestAddress")) { // test hook
+            val address = requireNotNull(intent.getStringExtra("reviewRequestAddress")) // test hook
+            val key = "pubky3rsduhcxpw74snwyct86m38c63j3pq8x4ycqikxg64roik8yw5xy" // test hook
+            val request = to.bitkit.repositories.PaykitPaymentRequest( // test hook
+                paymentRequestId = "review-minimum", counterparty = key, paymentReference = "review-minimum", // test hook
+                amount = to.bitkit.models.PaykitAmount(to.bitkit.models.PaykitAsset.BTC, 100uL), expiresAt = null, // test hook
+                acceptedPaymentEndpointIdentifiers = listOf("p2wpkh"), // test hook
+            ) // test hook
+            appViewModel.openContactPayment(address, key, incomingPaymentRequest = request) // test hook
+            intent.removeExtra("reviewRequestAddress") // test hook
+            return // test hook
+        } // test hook
         if (intent.getBooleanExtra(EXTRA_SPARK_EXIT, false)) {
             intent.removeExtra(EXTRA_SPARK_EXIT)
             appViewModel.onSparkExitNotificationTapped()

Reviewed by gpt-6.1-sol-high

@ovitrif

ovitrif commented Dec 5, 2026

Copy link
Copy Markdown
Collaborator

The @send_2 timeouts here came from the BTC price: at today's rate, 10,000 sats is just under the $5 QuickPay limit, so QuickPay paid the invoice the test expected to stop at review. The test now sizes its invoices from the wallet's USD quote: synonymdev/bitkit-e2e-tests#326 for Android and synonymdev/bitkit-e2e-tests#327 for iOS. e2e-status passes on this PR again.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants