Skip to content

fix(wallet): pause background refresh until the locked-launch fix lands - #1148

Merged
romchornyi merged 2 commits into
developfrom
fix/pause-background-refresh
Sep 24, 2026
Merged

romchornyi merged 2 commits into
developfrom
fix/pause-background-refresh

Conversation

@romchornyi

@romchornyi romchornyi commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Issue being fixed or feature implemented

A background app refresh can launch the app while the device is locked. The mnemonic keychain items are kSecAttrAccessibleWhenUnlockedThisDeviceOnly, so the wallet-presence read at launch fails and is treated as "no wallet". The root controller then shows Create a New Wallet / Recover Wallet over a funded wallet, and the SDK runtime never starts in that process. If the user opens the same process later, they land on setup. Going through Create from there ends on a home screen with no runtime: zero balance, core tab layout, no sync.

This became reachable with the notifications rework (#1088), which introduced the BGAppRefreshTask. Before that, the app never scheduled background fetches. The fix is in #1147 (tri-state wallet presence plus a launch hold that waits for protected data), and it needs a device test before it can ship.

This PR is a release safety valve: while it is in, no App Store build cut from develop can do a locked background launch.

What was done?

  • BackgroundRefreshCoordinator.isEnabledInThisBuild = false pauses background refresh in this build. The flag is injected into the coordinator (isEnabled:), so its tests cover both modes.
  • While paused:
    • start() withdraws the pending request (BGTaskScheduler.cancel(taskRequestWithIdentifier:)) and logs once.
    • scheduleNextRefresh() submits nothing.
    • A task that is still delivered (from a request an earlier build submitted) completes immediately as a success, without starting the runtime or re-submitting. Nothing failed, and reporting a failure would only count against the app's refresh budget.
  • Unchanged: the BGTaskScheduler registration in start(), the Info.plist permitted identifier and the fetch background mode. A request from an earlier build can still launch this one, and the scheduler requires a registered handler for every permitted identifier at that moment.
  • The rest of the coordinator (lifecycle observers, foreground catch-up stamp, become-active rearm) is unchanged.
  • To re-enable, flip isEnabledInThisBuild to true once fix(wallet): hold the launch decision while the keychain is locked #1147 has landed and been verified on a device.

How Has This Been Tested?

  • BackgroundRefreshCoordinatorTests: 21/21 pass.
    • The 18 existing tests now construct the coordinator with isEnabled: true explicitly.
    • 3 new tests for the paused mode: start still registers and withdraws the pending request; backgrounding submits nothing, even with a wallet or a locked device; a delivered task completes without touching the runtime or submitting.
  • SwiftDashSDKCoreLifecycleTests as a baseline: unchanged, only the two known balance-message failures.
  • dashpay Debug on an arm64 simulator: builds.
  • Not exercised on a device. A cold background launch cannot be triggered on demand; the behaviour covered here is that no request is submitted and a delivered task completes without work.

Breaking Changes

None, apart from the pause itself: while it is in, incoming-transaction notifications are not produced while the app is closed. BackgroundTaskScheduling gains cancel(identifier:), an internal seam.

Checklist:

  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have added or updated relevant unit/integration/functional/e2e tests
  • I have made corresponding changes to the documentation

For repository code-owners and collaborators only

  • I have assigned this pull request to a milestone

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Changes
    • Automatic background wallet refresh is paused in this build. The app will not start a background sync when a refresh task runs, and pending background refresh requests are canceled. This affects automatic updates while the app is in the background; the change does not describe or alter refresh behavior while the app is open.

A BGAppRefresh task launches the app while the device is locked. The
mnemonic keychain items are kSecAttrAccessibleWhenUnlockedThisDeviceOnly,
so the launch-time presence read fails and is taken as "no wallet": the
root controller offers Create/Recover over a funded wallet, and the SDK
runtime never starts in that process. Reachable since the refresh task
was introduced with the notifications rework (#1088); the fix — a
tri-state presence and a launch hold that waits for protected data — is
in progress in a separate PR (#1147) and needs a device test before it
can ship.

Until then background refresh is paused as a build-level switch
(BackgroundRefreshCoordinator.isEnabledInThisBuild = false):

- start() withdraws the pending request and submits nothing; a task
  delivered anyway (an earlier build's request) completes at once —
  as a success, so nothing counts against the app's refresh budget —
  without starting the runtime or re-submitting.
- The BGTask handler stays registered and the Info.plist permitted
  identifier and `fetch` mode stay: a request submitted by an earlier
  build can still launch this one, and BGTaskScheduler requires a
  handler for every permitted identifier at that moment.
- Everything else in the coordinator (observers, catch-up stamp,
  become-active rearm) behaves as before.

Re-enable by flipping the switch to true once #1147 has landed and been
verified on a device. The switch is injected into the coordinator so its
tests cover both modes.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Advanced

Run ID: 518bd869-9daa-43c5-848d-e3b1f385faec

📥 Commits

Reviewing files that changed from the base of the PR and between 780ea49 and f8fd5f6.

📒 Files selected for processing (3)
  • DashWallet/Sources/Infrastructure/Notifications/BackgroundRefreshCoordinator.swift
  • DashWalletTests/Notifications/BackgroundRefreshCoordinatorTests.swift
  • DashWalletTests/Notifications/NotificationTestDoubles.swift

Included review availability: Your plan provides up to 1 included review per hour; 0 remain after this review.


📝 Walkthrough

Walkthrough

This change disables background refresh in this build. The coordinator cancels pending requests, skips new submissions, and completes delivered tasks successfully without starting a runtime or sync.

Changes

Background refresh pause

Layer / File(s) Summary
Pause setting and cancellation contract
DashWallet/Sources/Infrastructure/Notifications/BackgroundRefreshCoordinator.swift
The coordinator adds a build-level enablement setting and an injectable setting. The scheduler protocol and system scheduler add request cancellation.
Paused coordinator behavior and tests
DashWallet/Sources/Infrastructure/Notifications/BackgroundRefreshCoordinator.swift, DashWalletTests/Notifications/BackgroundRefreshCoordinatorTests.swift, DashWalletTests/Notifications/NotificationTestDoubles.swift
When disabled, the coordinator cancels pending requests, skips future submissions, and completes delivered tasks successfully without running refresh work. Tests and test doubles verify these behaviors.

Priority: ➖ Normal

Estimated code review effort: 2 (Simple) | ~15 minutes

Change: Bug fix

Suggested reviewers: thepastaclaw, jeanpierreroma

Merge Risk: ⚪ Minimal · up to f8fd5

Background refresh is paused, so incoming-transaction notifications will not be produced while the app is closed. No additional actionable issue is established here; the separately reported locked-launch concern still warrants resolution before relying on the pause as a safe-release fix.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 53.85% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 13 functions across 3 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: pausing background refresh until the locked-launch fix is available.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR

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

❤️ Share

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

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

LGTM. The valve is tight: scheduleNextRefresh() is the only path to submit, so its guard covers the didEnterBackground call and both in-run calls. Registration staying unconditional is correct, since the permitted identifier and the fetch mode are still in both plists. A delivered task completes synchronously with success: true and never reaches run, so there's no runtime bring-up and no re-submit. The three new tests cover all of that.

I checked that the "no App Store build" claim holds: #1088 (84229f9) isn't an ancestor of tf-9.0.0__11 or v8.6.0, so no shipped or tagged TestFlight build ever submitted a request. One FYI: cancel in start() can't help a process that the stale request itself launched. The launch-path "no wallet" read happens before the handler runs. So a dev device that ran an internal #1088 build could still hit the setup screen once after installing this. That's internal only, so it doesn't block.

Non-blocking doc nits (these lines are outside the diff hunks, so I'm leaving them here instead of inline):

  • BackgroundRefreshCoordinator.swift:92-93: the BackgroundTaskScheduling doc still says "registration and request submission are the only calls the coordinator makes". cancel makes that out of date.
  • :354 and :384: "skipped only when no wallet exists" / "Skipped only when a wallet is provably absent". With the pause in, those skips are no longer the "only" ones. Worth a clause, or at least worth fixing when the switch is flipped back.

@thepastaclaw

thepastaclaw commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

⛔ Final review complete — 1 blocking finding(s) (commit f8fd5f6)

Review follow-up on the pause: the BackgroundTaskScheduling seam now also
cancels, and scheduleNextRefresh has a second skip while background
refresh is paused.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

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

Final validation — Phase 1 + Phase 2

At f8fd5f6, the coordinator correctly prevents new submissions and completes delivered tasks without coordinator work. However, it does not meet the stated release-safety guarantee for an upgrade first launched while locked by an earlier build's pending request: ordinary application startup still makes the unsafe wallet-presence decision. Verification was source-based; no independent build or device-smoke result is asserted.

🔴 1 blocking

Review provenance

Source: reviewer 1: glm-5.3-flash (agent: phase1-reviewer, role: general); reviewer 2: gpt-6-astra (agent: phase2-reviewer, role: general); final verifier: gpt-6-astra (agent: astra-verifier, role: final-verifier)

  • Triage: low by gpt-6-astra (effort low) — The diff adds a contained background-refresh kill switch, cancellation seam, and focused tests without changing wallet presence detection, key handling, runtime lifecycle logic, or funds movement.
  • Phase 1 reviewers: glm-5.3-flash — general (completed, effort high); agent phase1-reviewer
  • Phase 1 model: glm-5.3-flash — zai quota: 5h 99% left, weekly 45% left; passed over gemini-3.8-flash-high (antigravity below 15% reserve: weekly 1% left, 5h 100% left)
  • Fresh verifier: gpt-6-astra — final-verifier; agent astra-verifier
  • Phase 2 reviewers: gpt-6-astra — general (completed, effort medium); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.

In `DashWallet/Sources/Infrastructure/Notifications/BackgroundRefreshCoordinator.swift`:
- [BLOCKING] DashWallet/Sources/Infrastructure/Notifications/BackgroundRefreshCoordinator.swift:325-331: Cancellation during startup cannot protect an upgrade's first locked launch
  An earlier build's pending request can launch the updated app while locked before this cancellation runs, as the PR description explicitly acknowledges. Completing that task without coordinator work does not bypass AppDelegate's normal startup: it still calls startIfReady, installs DWInitialViewController, and makes the window visible. SwiftDashSDKHost.hasPersistedSDKWallet maps a keychain-read error to false, and DWAppRootViewController selects setup when that result is false and no legacy migration is pending. For an existing SDK wallet with the migration-done sentinel, the legacy hold is bypassed, so this residual delivery can still leave Create/Recover over a funded wallet. Foregrounding does not repair that decision: the root only checks the lock screen, and the coordinator rearms the runtime only when it previously stopped it. The pause reduces future exposure but does not satisfy the stated safe-release guarantee. Protect or defer normal startup for this remaining locked-launch path, and add coverage that launches through the app/root decision rather than invoking only the task handler.
Out-of-scope follow-up suggestions (1)

These are valid observations, but they are outside this PR's scope and should be handled in separate issues or author/maintainer-requested PRs rather than blocking this review.

  • The pinned DashUIKit requires a newer toolchain than the documented minimum — The pinned DashUIKit revision 83cf65a84834f6a7a1f0a82446ea1258ea86f37d declares swift-tools-version 6.3, while this machine's Xcode 16.4 provides Swift 6.1.2. This conflicts with the repository's Xcode 16+ setup guidance. The dependency pin and guidance are unchanged by this PR, so this is a separate reproducible-build concern, not a defect in the refresh pause.
    • Follow-up: Track toolchain/dependency alignment separately: document a compatible Xcode minimum or select a dependency revision supporting the intended minimum.

Comment on lines +325 to +331
// Registration above is unconditional even while paused: a request
// an earlier build submitted can still launch this one, and
// `BGTaskScheduler` requires a handler for every permitted
// identifier at that moment. The handler then only completes the
// task; here the pending request is withdrawn so it does not.
if !isEnabled {
scheduler.cancel(identifier: Self.taskIdentifier)

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.

🔴 Blocking: Cancellation during startup cannot protect an upgrade's first locked launch

An earlier build's pending request can launch the updated app while locked before this cancellation runs, as the PR description explicitly acknowledges. Completing that task without coordinator work does not bypass AppDelegate's normal startup: it still calls startIfReady, installs DWInitialViewController, and makes the window visible. SwiftDashSDKHost.hasPersistedSDKWallet maps a keychain-read error to false, and DWAppRootViewController selects setup when that result is false and no legacy migration is pending. For an existing SDK wallet with the migration-done sentinel, the legacy hold is bypassed, so this residual delivery can still leave Create/Recover over a funded wallet. Foregrounding does not repair that decision: the root only checks the lock screen, and the coordinator rearms the runtime only when it previously stopped it. The pause reduces future exposure but does not satisfy the stated safe-release guarantee. Protect or defer normal startup for this remaining locked-launch path, and add coverage that launches through the app/root decision rather than invoking only the task handler.

source: gpt-6-astra (phase2-reviewer: general)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed that this is the remaining path, and it is stated in the PR description. It is out of scope here by design. This PR only stops new requests from being submitted. The launch-path decision itself is fixed in #1147, which holds the root decision and the runtime start until protected data is available, and it includes a DEBUG harness that goes through the app and root decision. The residual can only happen on a device that ran a build containing #1088. Every TestFlight build since #1088 merged has been internal, and no tagged or App Store build contains it, so no user outside the team can have a pending request. The pause does what it claims for every build cut from develop from now on.

🤖 Addressed with Claude Code

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.

I confirmed that the pause prevents new submissions and that no locally available tag contains #1088; given your clarification that the affected TestFlight builds were internal-only, I accept leaving the residual upgrade-launch path to #1147 rather than blocking this pause on that fix.

Noted as intentionally deferred; I will not press it further here.

@romchornyi

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@romchornyi
romchornyi merged commit 30ae177 into develop Sep 24, 2026
4 checks passed
@romchornyi
romchornyi deleted the fix/pause-background-refresh branch September 24, 2026 11:02
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.

4 participants