Commit Graph

36 Commits

Author SHA1 Message Date
Jonas Bark
c0ee01f4d8 fix(permissions): let the onboarding wizard always win at launch
The Local Network warning fired at startup and the wizard then opened over it.
_NavigationState.initState calls startEnabledConnectionMethod() synchronously,
while the onboarding push happens later in an async block — so the toast lands
first.

The deferral rule required *both* "onboarding not yet run" and "no connection
method enabled", so a pending wizard on a device that already had a method
switched on still probed. Every method setting defaults to false, so that
conjunction only ever differed in exactly this case: a rider re-entering the
wizard with an existing configuration. Drop it — if the wizard is about to take
the screen, defer, full stop. That also makes this gate and the
getScanRequirements one identical.

Guard inside startEnabledConnectionMethod() rather than at the navigation call
site, so trainer_setup.dart's two calls are covered as well; the wizard hits
those when the rider picks a trainer app, which is the same bug one step later.
Nothing is lost while onboarding runs: setOnboardingMethodEnabled starts its
servers directly.

hasAnyConnectionMethodEnabled goes with it — it existed only to feed the clause
that is now gone.

The regression test was checked both ways: with the guard stubbed out it fails
with Expected: empty / Actual: ['check'].

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
(cherry picked from commit 1eee7644213e93201f7073d97c74f13c593b4cde)
2026-08-21 10:31:20 +02:00
Jonas Bark
b011e0e19d fix(permissions): check at launch, but not on a fresh unconfigured install
Checking a permission means *asking* for it on Apple platforms — instantiating
the BLE stack raises the Bluetooth dialog, and probing Bonjour raises the Local
Network one. Connection.initialize() runs from _StarterState.initState, so a
fresh install got both before the wizard had explained anything.

Launch-time checks are still the right thing for everyone else: a rider who
revoked a permission in System Settings should find out then, not from a
connection that silently does nothing. So defer only the case with nothing to
check for — onboarding not yet run *and* no connection method switched on:

  deferLaunchPermissionChecks(onboardingAction:, anyConnectionMethodEnabled:)

kept as a pure function beside decideOnboardingTrigger so navigation and
Connection cannot drift, and reachable as core.logic.deferLaunchPermissions.
Reading it during Connection.initialize() is safe: setLastSeenVersion is
written later (navigation.dart), so the pref still holds the previous launch's
value. An existing install upgrading reads markCompleted and is not degraded.

hasAnyConnectionMethodEnabled is new rather than !hasNoConnectionMethod: that
one mixes in show* visibility predicates, so it answers "should the UI nag"
rather than "did the rider turn something on".

startEnabledConnectionMethod() now gates the three network methods on Local
Network, mirroring what the BLE branches already did. They previously started
regardless and failed silently when the permission was off — the shape behind
the support tickets. The probe only runs when one of them is enabled, so a
BLE-only rider never sees the dialog, and a denial raises a warning instead of
a server listening into a black hole.

Third path, found only because a test that should have passed did not:
PermissionsSnapshot.gather() forced a probe, and _persistCrash builds a
diagnostics bundle on every recorded error —

  LocalNetworkAccess.status <- PermissionsSnapshot.gather <- DebugDiagnostics.gather
    <- debugText (menu.dart) <- _persistCrash (main.dart)

so any error at launch could pop the dialog past every gate above. Tie the
probe to the existing includeDiscovery seam, which the crash handler already
passes false for precisely because it must not do live network work.
User-initiated support bundles still get a fresh probe.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-21 09:58:33 +02:00
Jonas Bark
fb86df9841 fix(requirements): stop probing Local Network before onboarding is shown
getScanRequirements() runs on Connection init (connection.dart:548), long
before the onboarding wizard appears, so putting LocalNetworkRequirement in
that list popped the system Local Network dialog at app launch.

Probing it there was the wrong call twice over. Every consumer of that list
treats a non-empty result as "don't scan":

  connection.dart:424    skips performScanning()
  connection.dart:548    skips performScanning()
  onboarding_page.dart   shows the *Bluetooth* permission phase (_onAllowBluetooth)
  scan.dart:132          skips performScanning()

so a denied Local Network permission would also have silently stopped all BLE
scanning — the rider could no longer find their shifter at all. It is a
Bluetooth-scan gate; a network permission does not belong in it.

Gate OnboardingMethod.network on it instead, mirroring how .local already gates
on getLocalControlRequirements(), with the probe-prompt-recheck logic factored
into a shared satisfy() helper. The permission is then asked exactly when the
rider picks a network method, which is also where a denial is actionable. The
three network tiles keep their own gate.

getScanRequirements() gains a doc comment recording why Local Network is
deliberately absent, so it doesn't get added back.

Tests: the network method must consult the permission and must not report
itself enabled on a denial; getScanRequirements must neither carry the
requirement nor probe it at all — probing is what raises the system prompt, so
that one is the direct regression test for the launch-time dialog.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-21 09:37:04 +02:00
Jonas Bark
fcd277e3ba fix(local-network): don't let a pre-Settings probe repopulate the cache
invalidate() cleared the cached status but did nothing about a probe already in
flight. That probe then completed and wrote its answer back — the answer from
before whatever prompted the invalidation.

The case that matters is the one invalidate() exists for: the user is told
Local Network is off, taps through to System Settings, grants it and comes back.
If a probe was in flight when they left, its stale "denied" lands afterwards and
becomes the cached truth, so the app still claims the permission is off.

Tag each probe with a generation, bump it in invalidate(), and only write the
cache when the generation is still current. Whoever is awaiting the stale probe
still gets its result — it just doesn't become the shared answer. invalidate()
also drops _inFlight now, so the next caller starts a fresh probe instead of
being handed the pre-invalidation one.

Found while chasing an intermittent test failure. That turned out to be an
unrelated ambient issue (a MissingPluginException on the app_links EventChannel
that attaches to whichever test is in flight, which already fails ten other
files), but the race it exposed here was real.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-21 09:07:18 +02:00
Jonas Bark
20788e46b6 fix(requirements): stop the permission sheet opening for a granted permission
Toggling the "Direct connection" card could wedge: the sheet opened for a
permission that was already granted, and then sat there, because PermissionList
only re-probes on app resume.

ConnectionMethod probed one requirement list, awaited, then re-read
`widget.requirements` on the far side of the gap:

    Future.wait(widget.requirements.map((e) => e.getStatus())).then((_) async {
      final notDone = widget.requirements.filter((e) => !e.status).toList();

The tiles build that list inside `build()`, so any rebuild in that window hands
back fresh objects whose mutable `status` is still false — and these tiles
rebuild on every isConnected/isStarted tick, plus onChange's own setState. The
probe result was read off objects that were never probed.

Capture the list once per operation instead. This was pre-existing and not
specific to Local Network: di2_ble_tile and openbikecontrol_ble_tile pass
getRemoteControlRequirements() the same way, so they had the same latent race.

Also hoist the requirement lists out of build() into State fields across the
five tiles, so a probed `status` is not discarded every frame.

Separately: LocalNetworkRequirement was only wired into the network tiles, so
onboarding, app start and scanning never checked it at all — every one of those
reads getScanRequirements(). Add it there for iOS and macOS. The list is
filtered to unsatisfied requirements, so it surfaces only on an actual denial.

Note for macOS: keyboard-control-only users will now see a Local Network prompt
they do not need. Accepted deliberately in favour of one list over a
platform-split.

The regression test drives the real race — gate the probe, force a rebuild
mid-flight, release — and fails with "Found 1 widget with type PermissionList"
without the capture fix.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-21 08:55:04 +02:00
Jonas Bark
c4c48dff07 Merge remote-tracking branch 'origin/6.5' into 6.5 2026-08-21 08:03:17 +02:00
Jonas Bark
905c2641cd feat(ios/macos): detect the Local Network permission instead of failing silently
Denial of Apple's Local Network privacy permission is the most common cause of
"BikeControl can't see my trainer app" on iOS and macOS, and it fails
completely silently: Bonjour browses return nothing forever, advertisements
never leave the device, nothing throws. An app watching only for errors cannot
tell "permission is off" from "there is nothing out there".

Apple ships no authorization-status API for it (not iOS 14...26, not macOS
15...26), so the new local_network_permission plugin measures it: an NWListener
and an NWBrowser on _bikecontrol-preflight._tcp, then

  browser discovers the listener        -> granted
  kDNSServiceErr_PolicyDenied (-65570)  -> denied
  neither, before the deadline          -> unknown

unknown is a real outcome, not an error — a device with no usable network never
completes the round trip even when the permission is fine — so everything fails
open on it and only a positive denial blocks the user.

The probe *is* the request: the system prompt fires on the first Bonjour
operation, so there is no separate request step, and after the user answers,
System Settings is the only way back.

- LocalNetworkAccess caches the result (probes cost a real round trip while
  getStatus() runs on every tile mount, tap and resume) and collapses
  concurrent probes into one, since two listeners on the same service type
  would resolve each other.
- LocalNetworkRequirement gates the three LAN tiles: MyWhoosh Link, Zwift mDNS
  and OpenBikeControl mDNS. Suppressed in screenshot/demo mode like the rest.
- Diagnostics drop the old guess (inferred from whether a discovery scan
  returned anything, which could not tell denied from an empty LAN) for the
  measured local-network=granted|denied|unknown.
- _bikecontrol-preflight._tcp added to NSBonjourServices on both platforms;
  without it the browse fails for a reason unrelated to the permission.

The Xcode project deployment-target bumps (ios 13.0->15.0, macos 10.15->12.0)
are Flutter's own migration aligning project defaults with the Podfiles; they
happen on any first build.

Verified with real builds on both platforms, not just analysis: flutter build
macos --debug and flutter build ios --no-codesign both succeed, the framework
is linked in, and the preflight service type is present in both built
Info.plists. 35 tests cover the mapping, cache, concurrency and fail-open
behaviour.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-21 07:58:18 +02:00
Jonas Bark
8170cd97b9 fix(trainingpeaks): direction and face buttons now reach the app
The TPV profile mapped navigationUp and the coloured face buttons to a
keyboard key / touch position only. _handleDirectConnect forwards a KeyPair
solely when it carries an inGameAction, so those presses never left the
phone — and an actionless default is worse than no default at all, because
it shadows the action the button would otherwise inherit from
ControllerButton.action via Keymap.addNewButtons (which is exactly why
navigationDown, absent from the profile, worked).

Same gap hit the HUD-toggle and difficulty defaults. Steer Left/Right are
added to defaultObpSupportedButtons as well: TPV advertises them in its
live app-info frame, but without them the button editor hid steering
before a connection.

Reported by a rider on Android with TPV on an iPad, whose log showed
"Sent Down button press" next to "No connection method active".

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-18 12:54:00 +02:00
Jonas Bark
7e3a48d162 feat(attribution): report the Play install referrer once per install
The referrer source is behind an interface so the reporting logic is unit
tested without the Play plugin, which needs a real device.

The done-flag is only written after a successful send, so a failed report
retries on the next launch instead of vanishing. A missing referrer still
reports, because an install with no attribution is still an install and the
organic baseline is what paid gets compared against.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-16 20:29:42 +02:00
Jonas Bark
5d4a00e96a fix(attribution): normalise malformed-referrer errors to FormatException
Uri.splitQueryString throws ArgumentError, not FormatException, for
malformed percent-encoding (e.g. a truncated '%' or invalid escape) --
verified against the project's Dart SDK. The doc comment and Task 3's
brief both promise FormatException so callers can catch a single type
and route it through recordError. Catch the mismatch and rethrow as
FormatException; add a test proving the contract holds.
2026-08-16 20:26:46 +02:00
Jonas Bark
89f8638797 feat(attribution): parse UTMs from a Play install referrer
Pure function, no plugin dependency, so it is fully unit tested. Keeps Play's
organic referrer rather than discarding it -- that is how paid and organic
installs get told apart.

Lets FormatException escape on malformed encoding so the caller can record it
rather than silently losing an install.
2026-08-16 20:22:02 +02:00
Jonas Bark
56a8e87f7d i18n(home): translate the setup chain, align its checklist, stop billing
undelivered shifts

Three things.

The chain's 68 strings existed only in English, so five locales fell back
to it on the app's main screen. Now translated, in each file's own register
— informal second person throughout, matching the copy already around
them. Polish needed a `few` plural category for the step and day counters:
it uses a distinct form for 2-4, so `other` would have rendered "Zostały 2
kroków" instead of "kroki". Two keys written speculatively and never wired
up are dropped rather than sent to five translators.

The checklist's summary row sat inside a Button whose own padding inset it
past the steps below, and the leading glyphs differed in both width (15px
icon, 17px tick) and gap, so matching the outer inset alone would not have
lined them up. One _rowInset / _leadingSize / _leadingGap now governs both,
with the glyphs centred in a box of equal width. Two tests pin the tick and
the label columns, because this is exactly what drifts back unnoticed.

Finally, shifting with a trainer connected but no app holding the bridge
was charged to the daily command budget. Those shifts reach nothing. The
existing exemption only covered the case where the 20-minute
virtual-shifting budget was already ticking — that avoids double-billing —
so it grows a second reason: a command that was never delivered anywhere is
not a command the rider spent.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 14:39:07 +02:00
Jonas Bark
e310adbceb Merge branch '6.2' into 6.3
Brings SRAM AXS shifter support, beta-access/Shorebird track, and the
battery-saver timeout fix into 6.3. Merged the prop submodule (83f4bf9) so the
SRAM parser/button-tables and the Climb protocol coexist. Resolved: CHANGELOG
(SRAM AXS folded into 6.3.0), the prop pointer, and repointed the SRAM
integration test to the fake-BLE harness that 6.3 promoted into lib/.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 12:04:00 +02:00
Jonas Bark
2f5373cc60 feat: add beta_access entitlement flag and Shorebird track mapping
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-07 11:02:23 +02:00
Jonas Bark
c648705949 feat(core): showLocalKeyboardCard/showLocalTouchCard visibility getters
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VRVXtrmcgtKKz46AVDyqQp
2026-07-02 08:51:00 +02:00
Jonas Bark
50d9eea27d feat(iap): exempt internal trainer commands from daily limit during free testing
When the active FitnessBikeDefinition handles a trainer action internally
(gear shift, front shift, mode switch, intensity), don't count it against
the daily command limit for a free tester whose bridge session is still
counting down — no Pro on this device, no full version, and the 20-minute
budget not yet exhausted. All other counting paths are unchanged.

The increment now runs after handleTrainerAction so the decision can key
off whether the FBD actually handled the action. Gating lives in the pure,
testable BaseActions.isExemptInternalTrainerAction and is applied in both
the performAction trainer branch and the both-shifters combo path. Bumps
the prop submodule to its 6.3 branch for the new isCountingDown getter.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VRVXtrmcgtKKz46AVDyqQp
2026-06-30 10:17:02 +02:00
Jonas Bark
786621a11b Localize TrainerConnection titles (re-evaluate per locale)
The connection titles ("Connect using Bluetooth", "Connect directly over
Network", "Connect using MyWhoosh Link", ...) were captured once at object
construction in English, so they didn't follow the active locale. Back the
title with a builder (String Function()) and expose it via a getter so it
re-localizes — fixing the English titles in the localized store screenshots.
Updated all 10 subclasses and the fake connection in the bridge-transport test.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 11:47:43 +02:00
Jonas Bark
5d06ffa65f feat(iap): add freeAgainFromBuild gate (isPurchasedBuild helper) + tests 2026-06-17 20:20:10 +02:00
Jonas Bark
b5c25c5b21 Clearer log message when a trainer-app action can't be delivered (issue #367)
Pressing a virtual-shifting button after the trainer app (Zwift) had
disconnected logged the misleading "Could not perform <key>: No action
assigned" — but an action *is* assigned; the trainer app just isn't
connected to receive it.

Root cause: a pure in-game action (gear shift) has no keyboard/touch
fallback, so when no trainer app accepts it the press fell through to the
platform keyboard path, which reports "no action assigned". This only
surfaced with local control enabled, because `local` counts as a
"connected" trainer connection yet its sendAction always returns
NotHandled — so isTrainerConnected() was true and the generic
"no connection method active" guard was bypassed.

Fix: detect delivery failure after _handleDirectConnect. When a
trainer-app-only keypair (KeyPair.isTrainerAppActionOnly — an in-game
action with no keyboard/touch/command/screenshot fallback, excluding
headwind/trainer-control which target a proxy/accessory) goes unhandled,
report "Could not perform <key>: <app> is not connected" instead. Such
keypairs also now skip the generic isTrainerConnected early-return so the
specific message wins consistently. Keypairs with a keyboard fallback are
untouched and still fall through to the keyboard.

Tests: KeyPair.isTrainerAppActionOnly discrimination (keyboard/touch/
command fallback and outside-trainer-app actions excluded) and an
end-to-end regression covering the exact #367 trigger (local control on).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-13 09:46:38 +02:00
Jonas Bark
e9e7425c29 Integration tests: controller connections + virtual shifting through fake platform seams
Add test/integration with platform fakes installed at the plugin seams
(UniversalBle.setInstance, NsdPlatformInterface.instance); everything
above them — Connection, device classification, protocol parsers, press
state machine, keymaps, ProxyDevice — is the real code:

- controller_connection_test: scan→classification (Zwift Click/Ride via
  manufacturer data, Di2 via service UUID, FTMS trainer→ProxyDevice,
  ignored names/devices), connect lifecycle (device-info reads, battery,
  RideOn handshake, subscriptions), drops, dedupe, forget list.
- controller_button_chain_test: byte-accurate BLE notifications through
  the full reaction chain — single/double/long press, trigger remapping,
  duplicate-frame dedupe, unmapped-button error surfacing, multi-button
  Ride presses.
- virtual_shifting_connection_logic_test: retrofit-mode defaults (WiFi /
  BT-wins / proxy for power meters), auto-connect consent gating,
  in-place "No connection" disconnect + in-place reconnect, WiFi trainer
  discovery rules (found/lost/connected-survives-flap, self-exclusion),
  and an end-to-end Click-press → real action pipeline → gear shift.

Protocol-level coverage (DirCon over real TCP, BLE peripheral) lives in
the prop submodule's own tests — no prop internals in this repo.

Bug fix found by these tests: Connection.disconnect(keepInList: true)
was defeated — UniversalBle.disconnect resolves only after the platform
disconnect event, so the still-attached connectionStream listener
re-entered disconnect() without keepInList and dropped the device,
orphaning the object the open details page holds (the exact bug
0db8cf0c addressed). Guarded via _inPlaceDisconnects.

Also update stale tests to current behavior: sim-mode shifts return
Ignored since e0e4494d (handled by the bridge, not forwarded, logged
neutrally), ControllerButton.initials direction arrows, and skip the
third BC2 state-machine test consistently with its siblings.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 18:59:14 +02:00
Jonas Bark
a68b68a1b4 fix button mapping popup 2026-06-01 11:53:55 +02:00
Jonas Bark
661b63107a feat(overlay): persist overlay enabled, fields, and desktop position 2026-05-08 22:55:13 +02:00
Jonas Bark
b87056c20b support imperial / metric 2026-05-05 14:15:27 +02:00
Jonas Bark
596c89bbb5 feat: add settings keys for in-app review prompt tracking
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 12:06:16 +02:00
Jonas Bark
642fc754a1 UI adjustments, BLE advertisement fix 2026-04-26 09:14:00 +02:00
Jonas Bark
60036fe92f test: drop unused buttons import from preferredBridgeTransport test
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 21:44:15 +02:00
Jonas Bark
5bc7ae5531 test: drop unused foundation import from preferredBridgeTransport test 2026-04-25 20:36:46 +02:00
Jonas Bark
c5c5d85b67 feat: add CoreLogic.preferredBridgeTransport resolver
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-25 20:31:57 +02:00
Jonas Bark
b7d9fba548 compatibility changes 2026-04-25 19:23:34 +02:00
Jonas Bark
238fdf0df3 feat(controller): add ControllerButton.initials getter 2026-04-24 10:33:38 +02:00
Jonas Bark
03e1727d6a feat(supported-app): add per-app trainer connection types 2026-04-23 08:52:09 +02:00
Jonas Bark
1e79c31ff8 feat(settings): per-trainer retrofit-mode persistence 2026-04-21 09:32:39 +02:00
Jonas Bark
df937d7fec feat(keymap): add virtualGearAmount on SupportedApp (MyWhoosh=30, default=24) 2026-04-20 09:14:06 +02:00
Jonas Bark
365c29ac52 test(shifting): remove obsolete settings_proxy_test.dart
The file exercised getProxy*/setProxy*/clearProxyGearRatios accessors
deleted alongside the ShiftingConfig migration. Equivalent coverage
now lives in test/models/shifting_config_test.dart (defaults,
clamping, 24-entry gear-ratios guard) and
test/services/shifting_configs_controller_test.dart (persistence
round-trip, active invariant).
2026-04-20 08:06:40 +02:00
Jonas Bark
650b4737c4 feat(settings): persist custom 24-step gear ratios
Adds getProxyGearRatios/setProxyGearRatios/clearProxyGearRatios on
the Settings class, bumps the prop submodule to pick up the mutable
table and public gear constants on FitnessBikeDefinition, and covers
the roundtrip + edge cases with tests.
2026-04-15 23:02:19 +02:00
Jonas Bark
f14c9ff01e feat(settings): add proxy bike/rider weight, grade smoothing, VS mode 2026-04-15 21:02:38 +02:00