Skip to content

fix: tie the scan lock to the scanner visit - #1432

Merged
jvsena42 merged 5 commits into
masterfrom
fix/scanner-visit-ownership
Nov 26, 2026
Merged

jvsena42 merged 5 commits into
masterfrom
fix/scanner-visit-ownership

Conversation

@jvsena42

@jvsena42 jvsena42 commented Nov 25, 2026 •

Copy link
Copy Markdown
Member

Fixes #1400
Fixes #1424

This PR ties scan ownership to the scanner visit, so a slow lookup from a visit the user left neither blocks a new scan nor routes over the screen they moved to.

Description

Untested on a device: manual case 1 (Send camera scan of a slow LNURL-pay, then Enter Manually) needs a physical iPhone camera and was not run. It covers the camera call site in SendOptionsView that fixes #1424; the paste call site (case 2) passed on the simulator.

  • Fixes a new scan being refused after leaving and reopening the scanner (or Enter Manually → Back on Send) while an old LNURL lookup runs, because one isHandlingScan flag stayed set until that lookup returned. The scan lock now belongs to a scan id and holds only while that scan's visit is shown; a newer scan takes over a lock whose visit ended, and a stale scan's completion releases the lock only if it still owns it.
  • Fixes a late camera or paste scan on Send routing after Enter Manually, because those two calls passed no visit check. They now pass isOnThisScannerVisit(), as the NFC, Bluetooth and photo paths in the same view do.
  • Keeps Electrum and Add Contact scans holding the lock until they finish, as on master. An Electrum scan updates the server settings and pops the scanner whatever visit is shown when it ends, so letting a second scan take the lock after Back and reopening gave two toasts, a pop out of Electrum Settings and a spinner that ended early.
  • Fixes the same gap on the main scanner: camera and paste scans now check the sheet presentation and navigation path generation they started on (the check NFC and photo reads already used), so a decode from an earlier visit does not route. This check also covers the app lock, so the separate lock check in those two entry points is removed.

Out of Scope

  • While an Electrum server restart from a scan runs, main and Send scans (camera, paste, photo, NFC, Bluetooth) are ignored with no feedback, because the Electrum scan holds the lock until it finishes. Same as master.

  • AppViewModel.handleScannedData: setup and approval sheets queued before an app lock are tracked in Scanner: a setup sheet queued before the app locks opens after unlock #1425 (separate PR).

  • SendEnterManuallyView: its own lookups do not take the scan lock; unchanged.

  • SendOptionsView: the Send scanner: a late camera or paste scan routes after Enter Manually #1424 wiring (passing isOnThisScannerVisit() for camera and paste) has no test that fails if it is reverted. The view's visit state lives in SwiftUI @State, and moving it behind a helper would still leave a view call that tests cannot see without a view-hosting test. Accepted gap; manual cases 1 and 2 cover it.

Design

N/A — no UI changes.

Preview

Send → paste a slow LNURL-pay → Enter Manually: the address screen stays when the lookup returns.

1432-paste-enter-manually.mp4

Main scanner → paste a slow LNURL-pay → close and reopen → paste an on-chain address: Confirm opens at once, the old lookup opens nothing.

1432-reopen-scanner.mp4

Send → slow LNURL-pay → Enter Manually → Back → on-chain address: it routes at once.

1432-enter-manually-back.mp4

QA Notes

Setup

  • Simulator or device build with E2E_BUILD on local regtest, and the bitkit-docker lnurl-server (see the LNURL row of the Capabilities table in journeys/README.md).
  • The cases need an LNURL-pay endpoint that answers slowly (5 s or more). The standard lnurl-server answers at once; delay it with a proxy or a debugger breakpoint on the decode, or use a slow external LNURL-pay link.

Journeys

N/A — not drivable; see Manual Tests.

Manual Tests

  • 1. Send → scan a slow LNURL-pay QR → tap Enter Manually before it answers → Enter Manually stays; no LNURL amount screen appears when the lookup returns — delayed LNURL response not in Capabilities
  • 2. Send → paste a slow LNURL-pay link (Recipient Invoice) → tap Enter Manually before it answers → Enter Manually stays — delayed LNURL response not in Capabilities
  • 3. Main scanner → scan a slow LNURL-pay QR → close the scanner and open it again before it answers → scan a valid on-chain QR → Send opens for the new QR right away; the old LNURL does not open anything — delayed LNURL response not in Capabilities
  • 4. Send → scan a slow LNURL-pay QR → Enter Manually → Back → scan a valid on-chain QR → the new QR routes right away — delayed LNURL response not in Capabilities
  • 5. regression: Main scanner and Send → scan a valid on-chain QR, an LNURL-pay QR and a Lightning invoice, and paste each → each opens its usual flow — camera QR scanning not in Capabilities

Automated Checks

  • added ScannerManagerTests.swift — a Send camera scan held in decode does not route after the path moves to Enter Manually
  • added ScannerManagerTests.swift — a main camera scan held in decode does not route after leaving and returning to the scanner
  • added ScannerManagerTests.swift — after closing and reopening the scanner, a new scan is decoded and routed while the old lookup is still held
  • added ScannerManagerTests.swift — after Enter Manually → Back on Send, a new scan routes while the old lookup is held, and the old one does not route
  • added ScannerManagerTests.swift — an Electrum scan keeps the lock until it finishes: a second server scanned after Back and reopening the scanner is refused, and is handled once the first ends
  • added ScannerManagerTests.swift — a stale scan's completion neither releases a newer scan's lock (a same-visit scan and a Bluetooth request are still refused) nor blocks it after it ends

Evidence

  • Device run at f1ee713, iPhone 17 simulator (iOS 26.5), Debug build on staging regtest, local LNURL server answering after 10 s, no Spending balance. QR codes were pasted; the simulator has no camera.
    • 2: paste → Enter Manually; 3 s after the lookup returned, the address screen was still shown, with no amount screen and no toast.
    • 3: the old lookup was still pending when the new on-chain paste opened Confirm (0.73 s after the scanner closed, 2.1 s before the old lookup returned); Confirm was unchanged after it returned.
    • 4: Enter Manually → Back → on-chain paste reached Confirm 4 s before the old lookup returned; unchanged afterwards.
    • Regression, by paste: on-chain addresses from the main scanner and from Send open Confirm (about 0.7 s and 2.1 s). LNURL-pay from both entries routes and shows "Unable To Pay (LNURL): Not enough outbound/sending capacity", the expected result without Spending. A second paste on the same scanner visit while a lookup runs is still refused: one request, no Confirm.
    • No crashes, stray toasts, stuck spinners or repeated requests in the logs.
  • At 6b0fc5b (f1ee713 changes only doc comments), iPhone 17e simulator (iOS 26.5): the BitkitTests unit suite with the CI skips ran 4414 tests, 0 failures. With Electrum scans on the visit-scoped lock (the previous revision's behaviour), the new Electrum test fails.
  • At a486b78, iPhone 17e simulator (iOS 26.5): ScannerManagerTests 54/54 passed. The unit suite with the CI selection (BitkitTests, skipping UtxoSelection, AddressTypeIntegration, RNMigrationCleanup) ran 4413 tests, 0 failures. SwiftFormat lint clean on changed files. The follow-up commit only adds the changelog fragment.
  • With ScannerManager.swift reverted to master, 4 of the 5 new tests fail; the Send Enter Manually test passes there too, since the manager already honoured a passed visit check and the fix for Send scanner: a late camera or paste scan routes after Enter Manually #1424 is in the view.

Gaps

  • Manual case 1 (Send camera scan → Enter Manually) not run: the simulator has no camera and photo import fails there (Vision "Could not create inference context"). That camera call site in SendOptionsView is the Send scanner: a late camera or paste scan routes after Enter Manually #1424 fix and needs a physical iPhone.
  • Regression rows run by paste only, without a Spending balance: the LNURL-pay amount screen and Lightning invoices were not reached.
  • The a486b78 run included BitkitUITests: 3 failed (HomeHeaderUITests.testHeaderRowTapsOpenHeaderButtonsAndBalanceStillToggles, UsdtWalletUITests.testReceiveAndInvalidPaymentStaySeparateFromBitcoin, UsdtWalletUITests.testUnknownBalanceAndManualEntryUseConsistentAmountsInCommaRegion), each waiting for the wallet home after onboarding. The same 3 fail on master (7fdf32e) on the same simulator, so this PR does not cause them. BitkitUITests were not rerun at 6b0fc5b.
  • Add Contact scans have no new test: they finish synchronously, so the lock policy does not change what they do.

Models used

  • Planning/scoping: Unknown
  • Implementation: claude-opus-5-5 (reasoning: Not exposed)
  • Review: Not performed

Metadata note: the task brief came from a parent session whose model was not recorded here; this session's reasoning setting is not exposed in its run metadata.

🤖 Generated with Claude Code

A scan held the scan lock until its lookup returned, so after leaving and
reopening the scanner a new scan was refused while an old LNURL fetch ran.
The lock now belongs to a scan id and holds only while that scan's scanner
visit is shown. A newer scan takes over a lock whose visit ended, and a stale
scan's completion releases the lock only if it still owns it.

Camera and paste scans now check their visit: the main scanner through the
sheet and navigation path, and Send Options through its own path, so a late
decode no longer routes after Enter Manually.

Fixes #1400
Fixes #1424

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@jvsena42 jvsena42 self-assigned this Nov 25, 2026
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jvsena42 and others added 2 commits November 25, 2026 12:27
An Electrum scan updates the server settings and pops the scanner when it
finishes, whatever visit is then shown, so a second scan taken after Back and
reopening ran alongside it: two toasts, the second pop leaving Electrum
Settings, and the spinner ending early. Electrum and Add Contact scans now
hold the lock until they finish, as before; the visit-scoped lock applies to
the main and Send scanners only.

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 November 26, 2026 12:39
@jvsena42
jvsena42 requested review from a team, ovitrif and piotr-iohk and removed request for a team November 26, 2026 12:39
@greptile-apps

greptile-apps Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Confidence Score: 5/5 · The PR appears safe to merge; no new actionable issue was found.RetriggerView in GreptileConfidence Score: 5/5

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

Summary

The PR ties scan ownership to each scanner visit, so slow results do not block later visits or open over another screen.

  • A reopened scanner can accept a scan while an old lookup runs.
  • Send camera and paste scans stay with the Options visit.

Accepted scope from jvsena42: Electrum scans still block other scans until completion. The Send view’s camera/paste wiring has no direct automated test; the physical-camera check remains unrun. Queued setup and approval sheets across app lock remain deferred to #1425.

Reviews (2) · Last reviewed commit: "fix: release stale nearby quickpay suppr..." · Reviewed by Greptile

@ovitrif

ovitrif commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator

Added the issues this PR fixes (#1400, #1424) to 3.2.0: a refused or misrouted scan breaks a core send flow, and 3.2.0 ships with no known bugs there.

@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: full PR diff against its merge base, at f1ee713.

1 actionable finding — resolve or provide an evidence-backed rebuttal.

The visit-scoped ScanOwner lock, originCheck() wiring in ScannerManager, isOnThisScannerVisit() wiring in SendOptionsView, and Electrum/Add Contact lock retention match the requirements of #1400 and #1424. One low-severity defect was found in beginNearbyScan where taking over from a stale Bluetooth scan leaves the prior QuickPay suppression active until the earlier decode finishes. Automated CI unit and integration test runs (Run Tests, Run Integration Tests) were still pending at review time, and build-local failed its merge-ref freshness check (Checked-out merge does not match the PR's current base and head).

Parity: Compared against synonymdev/bitkit-android master at 576ac14 (QrScanningScreen.kt, SendSheet.kt, AppViewModel.kt). Android cancels the active Send-visit scan coroutine (sendVisitScanJob) when leaving Send or starting a new scan, matching the user-visible outcome here (source inspection only; no cross-platform runtime run was performed).

Recommended before device testing

  • Wait for Run Tests and Run Integration Tests to finish on f1ee713 (and re-run E2E after refreshing the merge ref if required).
  • Run manual case 1 and camera rows of case 5 on a physical iPhone with a funded Spending balance so the SendOptionsView camera callback, Lightning invoices, and LNURL-pay amount screen are exercised (no automated view-hosting test covers the SendOptionsView wiring).

Device testing: not performed in this review (code-only). The author reports simulator paste checks at f1ee713a5 (cases 2, 3, 4, and partial regression without a Spending balance), with manual case 1 (physical camera) and funded Spending regressions remaining unrun.

Suggested additional test cases

  • iOS (physical device or simulator) — Send Options offline overlay invalidation: Open Send Options, scan or paste a slow LNURL-pay link, immediately enable Airplane Mode so the connection-issues overlay covers Options, wait for the lookup to return (or restore connectivity after it returns), and verify Options remains shown with no stale LNURL amount screen and that a subsequent scan routes right away.
  • iOS (physical device or simulator) — Electrum scan lock while connecting: Open Settings → Electrum Server → Scan, scan a slow or unreachable Electrum server QR, tap Back and reopen the Electrum scanner while the first connection is still pending, then scan a second server; verify the second scan is ignored while the first runs (no duplicate toast or extra pop out of Electrum Settings) and succeeds once the first finishes.

Findings

  • [LOW] Release prior nearbyScanID QuickPay suppression in beginNearbyScan — inline at Bitkit/Managers/ScannerManager.swift:502.

Reviewer model: gemini-4-neon
Reasoning effort: high

Comment thread Bitkit/Managers/ScannerManager.swift Resolved

@talosmachina talosmachina left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

No findings. Ties the scan lock to a scan id that holds only while its scanner visit is shown (Electrum and Add Contact scans keep it until they finish), and passes the visit check from the Send camera and paste paths. Reviewed f1ee713a5a933a6f5007f0bc4fbbdfbedbd47302, full tier, static: iOS does not build on Linux, so this review is reasoned from the code and from CI and nothing was run.

What I checked, and 4 candidates I ruled out

Read in full: Bitkit/Managers/ScannerManager.swift, Bitkit/Views/Wallets/Send/SendOptionsView.swift, the new tests in BitkitTests/ScannerManagerTests.swift, plus AppViewModel.handleScannedData and ensureScannedDataHandlingOwnership, SheetViewModel.showSheet, NavigationViewModel.pathGeneration, ScannerScreen, ScannerSheet, SendEnterManuallyView and Components/Scanner.swift.
Call sites traced: every caller of handleScan, handleSendScan, handleNfcRead, handleSendNfcRead, handleNearbyRequest, handleSendNearbyRequest and handleImageScan, including the contact deep link in MainNavView (.main, no sheet, so it gets the origin check only). The removed lockCheck() has no remaining caller in ScannerManager, and originCheck() already compares lockGeneration, so the PIN-lock drop is kept.
Merge with master: git merge-tree against edce3cdee is clean. #1433 changed AppViewModel and SheetViewModel (lock check on delayed sheet replacements) but not ScannerManager, and none of its new tests call the removed helper.

Ruled out

  • A stale scan's defer frees a newer scan's lock: endUserScan releases only when owns(scanID), and endNearbyScan now goes through the same check.
  • A stale scan writes app send state after a newer scan took the lock: every await in processScan/processSendScan is followed by ensureScannedDataHandlingOwnership, and the new scan's handleScannedData replaces scannedDataHandlingId, so the old one throws CancellationError at its next check, and its own isCurrent closure is false through owns(scanID).
  • Electrum scan pops the wrong screen after Back and reopen: holdsUntilDone keeps the lock for .electrum and .addContact, and handleElectrumScan still checks isCurrentServerConnection. Covered by testElectrumScanKeepsTheLockUntilItFinishes.
  • A Bluetooth request takes the lock from a stale user scan whose visit ended: intended. beginNearbyScan checks isHandlingScan, which is now visit-scoped, so a nearby request on the new visit is no longer blocked by an old lookup, which is the issue being fixed.

CI: build-local failed at "Verify current PR merge checkout" (the checked-out merge did not match the PR's current base and head, since master moved after the run started) and e2e-status failed as a consequence. Neither ran the code. Run Tests and Run Integration Tests were still pending when I read them; SwiftFormat and validate passed.

Merge confidence: 3/5, no findings, but CI is red on the merge-checkout step and the unit tests have not reported on this head.

Reviewer model: claude-opus-5-5
Reasoning effort: Not exposed (the run metadata available to this reviewer does not report an effort setting)

@jvsena42
jvsena42 enabled auto-merge November 26, 2026 13:15

@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: ✅ Approve

Findings: No additional findings.

QA for f1ee713:

Ordinary payment pastes keep their usual routes ✅ On-chain pastes reach Confirm; LNURL-pay and Lightning pastes show the expected empty-Spending warnings from both main Scan and Send.

Self-built Debug/E2E app on staging regtest, iPhone 17e simulator, iOS 26.4. Savings held test funds; Spending was empty. Both on-chain confirmations showed the requested 1,000 sats and destination. LNURL-pay showed “Not enough outbound/sending capacity”; the valid 10-sat Lightning invoice showed “Insufficient Spending Balance.” No payment was submitted.

Main Scan, then Send; recording at 2×:

5-paste2x.2x.mp4

Check: Scanner ownership and stale completion checks ✅ The scanner suite passed in the PR's CI run, including the new ownership, stale-visit and Electrum-lock cases.

Checked the completed ScannerManagerTests CI execution. The scanner implementation and tests in that merge build match the reviewed head. This is existing CI evidence, not a local test execution.

Relied on the author's exact-head report and recordings for slow Send paste → Enter Manually, main scanner close/reopen → new paste, and Send Enter Manually → Back → new paste. Those cases were not repeated.

Not driven: camera variants need a physical iPhone; funded Spending LNURL amount and Lightning confirmation screens were not reached. The suggested offline-overlay journey was also left out: the simulator has no device-scoped Airplane Mode, and failing an endpoint does not change the NWPathMonitor state that displays that overlay. Electrum takeover/refusal was checked by the CI case above rather than another device run.

Full review of the four PR files and reached callers at f1ee713. Device coverage was paste-only; camera, photo, NFC, Bluetooth, app-lock/offline invalidation and Add Contact behavior were inspected in code, with manager tests where present.

Twin: synonymdev/bitkit-android#2035 matches the late Send camera/paste cancellation behavior; this iOS PR additionally changes shared scan-lock ownership.

Other CI status: the unit job failed in ProfileRecoveryUITests.testProfileControlsStayReadOnlyUntilSessionAndProfileRecover, outside the scanner suite. E2E build-local stopped at the merge-checkout freshness check before app tests ran.


Reviewed by gpt-6.1-sol-high

@ovitrif ovitrif 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.

utAck

@jvsena42
jvsena42 marked this pull request as draft November 26, 2026 16:08
auto-merge was automatically disabled November 26, 2026 16:08

Pull request was converted to draft

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@jvsena42
jvsena42 marked this pull request as ready for review November 26, 2026 17:17
@jvsena42
jvsena42 enabled auto-merge November 26, 2026 17:17

@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: ✅ Approve

Findings: None. The earlier nearby QuickPay suppression finding is fixed in d66d908.

QA for d66d908:

Check: Nearby QuickPay suppression and scanner ownership ✅ The new two-visit regression and the scanner suite passed in CI.

Verified the completed ScannerManagerTests execution. The scanner implementation and new regression in that merge build match d66d908; its changes to setup/deep-link handling do not alter the regression's payment path. The regression holds nearby requests across two visits, then confirms the user's NFC read routes without retained QuickPay suppression. This is CI execution evidence.

Funded Spending opens LNURL and Lightning payment review ✅ LNURL pastes opened amount entry and 10-sat Lightning pastes opened Confirm from both main Scan and Send.

Case 5, remaining paste coverage: self-built Debug/E2E app on local regtest, iPhone 17 Pro simulator at 2× resolution, iOS 26.4. Spark Spending held 99,865 test sats; QuickPay was off. Prepared inputs, device logs and runtime UI snapshots confirmed the requests and routes. No payment was submitted.

Main Scan, then Send; recording at 2×:

5-funded-paste2x.2x.mp4

Reused the previous review and recording for on-chain paste regression, and the author's f1ee713 report for slow Send paste → Enter Manually, main scanner close/reopen → new paste, and Send Enter Manually → Back → new paste (cases 2–4, paste variants). This delta leaves those paths unchanged.

Not driven: camera variants of cases 1, 3, 4 and 5, and physical NFC/Bluetooth reads require hardware unavailable to the simulator. The offline-overlay suggestion needs device-scoped network switching, which the simulator does not provide. Device coverage is paste-only; nearby takeover and stale completion behavior were checked in source and CI.

Reviewed f1ee713..d66d908 and the addressed suppression thread, including both main and Send callers and their user-scan/photo takeover paths.

Twin: synonymdev/bitkit-android#2035 matches late Send-result cancellation. Android carries QuickPay suppression per scan; this shared-token handover fix is iOS-specific. Comparison was by source.


Reviewed by gpt-6.1-sol-high

@ovitrif ovitrif 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.

utAck

@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: changes since f1ee713a5, including affected code paths and QuickPay suppression handoff, at d66d908b0. Baseline: previous review.

No new actionable code findings.

ScannerManager.beginNearbyScan now releases any superseded nearbyScanID from AppViewModel.quickPaySuppressions before assigning the new nearby scan ID, preserving the @MainActor invariant across beginNearbyScan, beginUserScan, endNearbyScan, and decodeBeforeNearbyRequests that at most the active nearby request suppresses QuickPay. ScannerManagerTests.testUserScanGetsQuickPayAfterNearbyRequestsFromTwoVisits exercises the two-visit nearby takeover followed by a user NFC read and asserts isQuickPaySuppressed is cleared both when the user scan routes and after both superseded tasks finish.

Android parity check: compared against synonymdev/bitkit-android at 90e9f647b (SendSheet.kt, QrScanningScreen.kt, NearbyScanner.kt). Android scopes QuickPay suppression per onScanResult call (suppressQuickPay = payload.isNearby) rather than holding IDs in a shared AppViewModel set, so releasing a superseded nearby ID in beginNearbyScan aligns iOS QuickPay suppression lifetime with Android's per-scan behavior.

Recommended before device testing: wait for the in-progress Run Tests unit suite (and queued e2e-tests-local - e2e) on d66d908b0 to finish and pass. Local XCTest execution is unavailable in this Linux review environment; SwiftFormat, build-local, and Run Integration Tests have passed on d66d908b0.

Device testing: not performed in this review. Author simulator evidence in the PR description was captured at f1ee713a5 (prior to d66d908b0) and leaves manual case 1 and physical-camera/Spending regression paths to device verification.

Earlier findings reconciled at this revision: 1 verified fixed.

Reviewer model: gemini-4-neon
Reasoning effort: high

@jvsena42
jvsena42 merged commit dc768a8 into master Nov 26, 2026
41 of 42 checks passed
@jvsena42
jvsena42 deleted the fix/scanner-visit-ownership branch November 26, 2026 21:27
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.

Send scanner: a late camera or paste scan routes after Enter Manually Scan lock outlives the scanner visit while an LNURL request is pending

4 participants