Skip to content

feat(garmin): watch button controls for workouts — Phase 1 MVP (#1391) - #1407

Open
9thLevelSoftware wants to merge 18 commits into
mainfrom
feat/1391-garmin-watch-controls
Open

9thLevelSoftware wants to merge 18 commits into
mainfrom
feat/1391-garmin-watch-controls

Conversation

@9thLevelSoftware

Copy link
Copy Markdown
Owner

Garmin watch button controls for workouts (Phase 1 MVP) — issue #1391

Implements the signed-off Phase-1 enhancement for #1391 (ticket 1569464719817838833): control a Phoenix workout from the physical buttons on a Garmin watch — Start/Next, Stop set, and a confirmed Cancel exercise — with mandatory on-watch text feedback and a haptic only after APPLIED.

Governance: signoff.md binding corrections 1–8 + escalated decisions (routine watch Start == phone START skipCountdown=true; APPLIED only on commit-path persistence receipt SUCCEEDED/NOT_REQUIRED; iOS selection callback solicited/single-use on a dedicated scheme). Grounded at origin/main f6bf1712 with all spec line citations re-derived.

Fixes #1391

What this contains (packets B1–B8)

  • B1 — shared seam: DefaultWorkoutSessionManager.endCurrentSetAndPrepareNext(expectedExecutionIdentity) with typed RemoteSetControlReceipt (commit-path persistence receipt, teardown observation, prepared-not-started successor, no-autostart suppression) + currentRemoteExecutionIdentityOrNull() manager accessor. Characterization/regression tests extended across Issue869SummaryAfterCommitTest, ManualStopProfileAttributionTest, WorkoutTeardownRecoveryTest, JustLiftCompletionBehaviorTest.
  • B2 — protocol + controller: GarminProtocol.kt (frozen v1 wire codec byte-mirroring garmin/source/PhoenixProtocol.mc: HELLO/STATE/COMMAND/RESULT, bounded validation walk ≤2048 bytes / ≤24 keys / ≤2 container levels / ≤3 array elements / 64-80-32 byte string limits, codec-size estimator, fail-closed key sets) and GarminSessionController internals: per-workout arming with fresh epochs, 3 s grants + 10 s confirmation tokens (bound to epoch+exercise+context+revision), fail-closed dedupe (256 command IDs/epoch, reserve-before-dispatch, identical-duplicate cached outcome, COMMAND_ID_CONFLICT, EPOCH_CAP_REACHED disarm/rekey), single serialized admission with urgent STOP_SET pre-emption, ACCEPTED/APPLIED/REJECTED result semantics with UNKNOWN_RESULT/SAVE_FAILED start-blocks, authority invalidation (logout/profile switch/disconnect/restart) and owner-generation drops of late native callbacks. DI: GarminControlPreferences + holder binding; MainViewModel composes the controller against its single session manager (integration-model §5 — one phone manager only).
  • B3 — phone UI: GarminControlsSettingsCard beside HrmSensorSettingsCard (HR surfaces untouched) + GarminControlsArmStrip on SetReady/Active/JustLift screens; default-OFF release boundary (card shows unavailable until a matched production watch-app UUID is configured).
  • B4/B5/B6 — platform transports: Android CIQ companion transport (GCM relay, paired register/unregister, provenance-before-decode), iOS transport + GarminCompanionBridge.swift (dedicated callback scheme, solicited single-use selection callback, -ObjC), tvOS no-op.
  • B7 — watch app: garmin/ Monkey C app (manifest, protocol, view, delegate, Run-No-Evil tests, static checks) + .github/workflows/garmin-ci.yml. Button map: top-right Start/Next, bottom-right urgent Stop, bottom-left open Cancel confirm, middle-left dismiss; no long-hold destructive action.
  • B8 — regressions: HRM card/session HR unaffected, no MediaSession, coexistence preserved.

Verification (commands run on this branch)

  • ./gradlew -Pskip.supabase.check=true :shared:testAndroidHostTest --tests '*GarminProtocolTest*' --tests '*GarminSessionControllerTest*' — 43/43 PASS (frozen-contract validation rows, grant/confirmation TTLs via fake monotonic clock, dedupe/conflict/cap rekey, provenance rejections, authority invalidation, STOP pre-emption, routing parity, receipt semantics).
  • Targeted B1 seam selection ('*Issue869*' '*ManualStop*' '*Teardown*' '*JustLift*') — known not green at this head; needs triage before merge:
    • ManualStopProfileAttributionTest 2 failures (remoteSetControlSaves*: observed execution identity differs — an extra execution appears in those scenarios);
    • JustLiftCompletionBehaviorTest 2 failures (timed-summary grab/dismiss expectations);
    • Issue1366JustLiftExitNavigationTest 12 failures (untouched by this PR; suspected pre-existing/flaky — please compare against main).
    • Issue869SummaryAfterCommitTest and WorkoutTeardownRecoveryTest pass (receipt honesty incl. stuck-save PENDING/FAILED and no fabricated successor).

Visual evidence (UI-involved)

Final in-app visual QA (settings-card states, Arm strip at default + largest accessibility text sizes, native Active/Rest/Summary frames, cancel-confirm sheet, watch-simulator cycle recording) is in progress and will be posted as PR comments and referenced here before merge. Merge gate: do not merge until final_visual_artifacts exist and are linked.

Release-note draft (from user-instructions.md)

Control your workout from your Garmin watch (beta) — Start/Next, Stop set, and a confirmed Cancel-exercise from the physical buttons on supported Garmin watches, with instant on-watch feedback and a haptic once your set state is saved. Hands stay on the bar between sets. Opt in via Settings → Connected Devices → Garmin controls, Arm for each workout, and keep Phoenix open while you train. Requires the free Phoenix Controls companion app from the Connect IQ Store (Forerunner 255/965, fēnix 7). Off by default; no change to your saved workouts, and the feature is free.

Scope boundary

Phase 1 only. No DB/schema/sync/portal/analytics changes; no background start (backgroundStopSupported=false); no watch-side routine loading/selection/weight editing; no media-key mapping; no HR surface changes. Phone side ships default-OFF until a supported, matched watch app is detected. Garmin developer signing and Connect IQ Store submission are release-time external dependencies and do not block merging default-off code. Phases 2 (on-watch exercise/set/rest dashboard, rest-end haptic) and 3 (button remapping) are deferred to their own cards.

Devil added 8 commits November 17, 2026 12:00
…1-B7

Pinned shared API: RemoteSetControlReceipt (B1 seam result), GarminCompanionTransport
(B2 controller / B4-B6 platform transports), GarminControlPreferences (namespaced
local store), GarminSessionController public UI surface (B2 impl / B3 phone UI).
B1: endCurrentSetAndPrepareNext seam in DefaultWorkoutSessionManager with
ActiveSessionEngine cooperation and RemoteSetControlSeam typed receipts.
B7: garmin/ Monkey C watch app (manifest, protocol, delegate, view, tests,
static-check + simulator-test scripts) and .github/workflows/garmin-ci.yml.
B8: regression/coexistence tests across Issue869SummaryAfterCommitTest,
JustLiftCompletionBehaviorTest, ManualStopProfileAttributionTest,
WorkoutTeardownRecoveryTest.
GarminControlsSettingsCard beside HrmSensorSettingsCard in SettingsTab,
GarminControlsArmStrip integrated into SetReadyScreen/ActiveWorkoutScreen/
JustLiftScreen, additive string resources only.
Android CIQ companion transport + DI binding, iOS transport +
GarminCompanionBridge.swift with dedicated callback scheme and -ObjC,
tvOS no-op transport; version-catalog + build wiring.
…ssthrough

Unblocks :shared:compileAndroidHostTest for the B1/B8 remote set-control tests.
GarminProtocol.kt: frozen v1 wire codec mirroring garmin/source/PhoenixProtocol.mc
(HELLO/STATE/COMMAND/RESULT, bounded validation walk, codec-size estimator,
fail-closed key sets). GarminSessionController: association/arming with fresh
epochs, 3s grants + 10s confirmation binding, fail-closed dedupe (256/epoch,
reserve-before-dispatch, cached identical duplicates, COMMAND_ID_CONFLICT,
EPOCH_CAP_REACHED disarm/rekey), single serialized admission with urgent
STOP_SET pre-emption, ACCEPTED/APPLIED/REJECTED receipt semantics with
UNKNOWN_RESULT/SAVE_FAILED start-block, authority invalidation and owner-
generation callback drops. DI: GarminControlPreferences + holder-based
GarminSessionController binding; MainViewModel composes the controller against
its single session manager (integration-model §5). DWSM gains a manager-level
currentRemoteExecutionIdentityOrNull() accessor. Tests: GarminProtocolTest +
GarminSessionControllerTest (fake monotonic clock, no sleeps).
Copilot AI balanced review requested due to automatic review settings November 17, 2026 19:42

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

Devil added 3 commits November 17, 2026 18:18
- garmin Monkey C: Array.push() does not exist on Monkey C arrays — use .add()
  (fixes all four garmin-ci Build + simulator checks jobs: fenix7/fr255/fr265/fr965)
- iOS KN export visibility: GARMIN_CALLBACK_URL_SCHEME/selection TTL stay internal;
  the deliberate Garmin companion-bridge Swift seam (GarminNativeBridge,
  GarminNativeBridgeEvents, GarminBridgeDeviceInfo, GarminCompanionBridgeRegistry)
  is allowlisted in IosKnExportVisibilityContractTest with rationale
- KoinModuleVerifyTest: extraTypes += GarminCompanionTransport (platformModule)
  and DefaultWorkoutSessionManager (composed in MainViewModel, never a bean)
- GarminControlsArmStrip/SettingsCard: best-effort controller resolution —
  environments without the Garmin Koin bindings hide the controls instead of
  failing composition (fixes Issue1366JustLiftExitNavigationTest 12 failures)
- Remote seam (B1): a deferred bodyweight rep-entry save reports NO_COMPLETION
  (the dialog owns the decision), and a second watch press while the prompt owns
  the completion returns PHONE_INPUT_REQUIRED via an identity-anchored gate
  check that outlives the execution lease
- Tests: the auto-complete race pins honest observed-identity reporting (matches
  WorkoutTeardownRecoveryTest semantics); the timed-set attribution fixture gets
  a second set so 'advance to the exact next set' is a real scenario; the remote
  JustLift end pins the completion machinery's waiting-mode arming (no autostart)
…h-controls

# Conflicts:
#	shared/src/androidMain/kotlin/com/devil/phoenixproject/di/PlatformModule.android.kt
#	shared/src/commonMain/composeResources/values/strings.xml
#	shared/src/iosMain/kotlin/com/devil/phoenixproject/di/PlatformModule.ios.kt
…d migration 64)

ExerciseMediaWiringTest pinned maxSeen <= 63 as 'Phase 1 adds no schema
migration', but main's own #1392 power-loss work added 64.sqm — breaking this
gate on main itself (main CI red at 6f95247, Unit Tests). The gate's intent
('media adds no migration of its own'; ExerciseImage pinned to 43.sqm) is
preserved: unrelated schema work only moves the baseline. Cross-feature
baseline drift flagged to the media Phase-1 owner; supersede freely.
@9thLevelSoftware

Copy link
Copy Markdown
Owner Author

PR follow-up — CI hardening (ticket 1569464719817838833, pr_followup stage)

Pushed head 988deaa5 (was 64e8c084). All branch-caused CI failures triaged and fixed:

garmin-ci — Build + simulator checks (fenix7 / fr255 / fr265 / fr965) — all four jobs failed on Undefined symbol ':push' (Monkey C arrays have no push; it is add). Fixed in garmin/source/PhoenixProtocol.mc + PhoenixView.mc (4 call sites).

Unit Tests — 18 failures at 64e8c084, root-caused to 5 distinct defects:

  1. Koin graph (13 failures) — KoinModuleVerifyTest + all 12 Issue1366JustLiftExitNavigationTest failures were MissingKoinDefinition/NoDefinitionFound: the Garmin arm strip and settings card hard-required koinInject<GarminSessionController>() at composition. Both now resolve best-effort and stay hidden without the bindings (release boundary stays OFF), and KoinModuleVerifyTest.extraTypes gains GarminCompanionTransport (platformModule) + DefaultWorkoutSessionManager (composed in MainViewModel, never a bean).
  2. iOS KN export visibility (1) — IosKnExportVisibilityContractTest found 6 public iosMain leaks. The two protocol constants are now internal; the 4 genuinely Swift-called seam types (GarminNativeBridge, GarminNativeBridgeEvents, GarminBridgeDeviceInfo, GarminCompanionBridgeRegistry — implemented/called by GarminCompanionBridge.swift) are now an explicit documented allowlist entry. Everything else stays hidden as before.
  3. Remote seam bug (1) — a bodyweight set whose save is deferred to the rep-entry dialog reported SAVED_AND_ADVANCED; it now reports NO_COMPLETION (frozen receipt semantics — no completion decision has been reached), and a second watch press while the prompt owns the completion returns PHONE_INPUT_REQUIRED via an identity-anchored gate check that outlives the execution lease (previously SUPERSEDED).
  4. Three test corrections (3) — auto-complete race now pins honest observed-identity reporting (matching WorkoutTeardownRecoveryTest's "reported honestly" semantics — the pressed identity is stale once autoplay has started the successor); the timed-set attribution fixture gains a second set so "advance to the exact next set" is a real scenario (a one-set routine legitimately ends COMPLETE); the remote JustLift end pins the completion machinery's waiting-mode arming (enableJustLiftWaitingMode — no auto-start), which the following assertions verify.

Merged origin/main (3 commits: #1358 media Phase 1, #1405, #1406) — union-resolved PlatformModule.android/ios.kt and values/strings.xml.

Pre-existing main breakage (NOT from this PR): ExerciseMediaWiringTest pins maxSeen <= 63 as "Phase 1 adds no schema migration", but main's own #1392 added 64.sqm — main CI is red at 6f952472 on Unit Tests for this exact test. Baseline moved to 64 with provenance in 988deaa5 so CI can go green here; the media Phase-1 owner should supersede freely. hotspot: shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/ExerciseMediaWiringTest.kt — cross-feature schema-baseline drift (media gate vs #1392 migration 64).

Still required before merge (merge gate must keep holding): the final visual QA capture matrix in this PR's body (GarminControlsSettingsCard states, Arm strip SetReady/Active frames, JustLift strip, cancel-confirm sheet, urgent-stop preemption, save timeout/failure, default + largest text sizes, plus one watch-simulator Start/Next–Stop/Cancel cycle recording). Not yet posted — the merge gate must not merge until it is captured, uploaded to v1.1.0 and linked here.

… delegate signatures

monkeyc rejects untyped Any-signature methods where the SDK expects
Method(msg as Communications.PhoneAppMessage) as Void,
Method(error as Communications.PhoneAppMessageError) as Void and
Method() as Void (registerForPhoneAppMessages / registerForPhoneAppMessageErrors /
Timer.start). Explicitly type the parameters and return Void on
onPhoneMessage / onPhoneMessageError / onTick / onComplete / onError.
phoenixworker added 6 commits November 17, 2026 23:06
- Rename a commonTest backtick test name containing ',' — Kotlin/Native
  rejects ',.:;/<>[]' in names, breaking :shared:compileTestKotlinIosArm64
  (required check 'iOS Test Target Compile').
- garmin-ci: DuckSoft/setup-connectiq-actions@v1 does not support the
  install-simulator-dependencies input (silently ignored), leaving the
  simulator without libwebkit2gtk-4.0.so.37. Install the simulator runtime
  libraries explicitly via apt instead.
…h-controls

# Conflicts:
#	shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/ExerciseMediaWiringTest.kt
…m timeout

- Pin DuckSoft/setup-connectiq-actions to main SHA 64f7145d with
  install-simulator-dependencies=true: the v1 tag predates that input and
  silently ignored it, leaving native deps for bin/simulator AND bin/shell
  unresolved (monkeydo hung until the outer timeout; exit 124). The upstream
  installer apt-installs and ldd-validates the full dependency set.
- Raise run-simulator-tests.sh outer timeout 240s -> 480s for the larger
  Phoenix Run No Evil suite on cold simulator boots.
…nBridge

The installed Connect IQ Mobile SDK renamed the app-message APIs
(registerForAppMessages -> register(forAppMessages:delegate:),
unregisterForAppMessages -> unregister(forAppMessages:delegate:),
unregisterForAllAppMessages -> unregister(forAllAppMessages:),
receivedMessage(_:fromApp:) -> receivedMessage(_:from:)); the old names
fail the PhoenixApp iOS build (no CI job covers the app target, so this
only surfaced in the phantom capture build).
…Connect IQ SDK

Resolved SPM SDK (connectiq-companion-app-sdk-ios) renames vs the spellings
the PR used: IQDevice(id:modelName:friendlyName:),
IQApp(uuid:store:device:) (failable import; unannotated headers),
NS_ENUM cases .connected/.failure_*_style, and receivedMessage(_:from:).
Also move .onOpenURL from the Scene (SwiftUI Scene has no onOpenURL) to the
root view. Verified: xcodebuild iphonesimulator build of PhoenixApp succeeds.
… timeout

- The SPM ConnectIQ binary framework embeds into PhoenixApp.app/Frameworks
  but LD_RUNPATH_SEARCH_PATHS lacked @executable_path/Frameworks, so every
  build crashed at launch with 'Library not loaded:
  @rpath/ConnectIQ.framework/ConnectIQ' (fatalDyldError). Verified fix in
  the simulator build (app launches and renders).
- run-simulator-tests.sh now prints the captured MonkeyDo output in cleanup
  so a timed-out run reveals how far monkeydo progressed (previous runs
  discarded tests.log silently).
@9thLevelSoftware

Copy link
Copy Markdown
Owner Author

PR follow-up status (2026-11-18) — CI hardening + first final visual evidence

CI at head 301ef4db (this run's commits):

  • ce582b2d merged origin/main (6 commits) — resolved the ExerciseMediaWiringTest ratchet conflict (base 65.sqm after [Bug]: Velocity is 10x too low (stored as cm/s, labelled mm/s); set MCV and velocity loss include calibration and ramp reps #1400's migration 65).
  • f24ef439 fixed the required iOS Test Target Compile failure (Kotlin/Native rejects , in a commonTest backtick test name) and pinned DuckSoft/setup-connectiq-actions — its v1 tag silently ignored install-simulator-dependencies, leaving the Linux simulator's native deps uninstalled (libwebkit2gtk-4.0.so.37 load failure).
  • cde79dd6 switched to the upstream dependency installer (ldd-validated for bin/simulator and bin/shell) and raised the monkeydo timeout.
  • 0485972c + 04289f68 + 301ef4db fixed the iOS app build/launch against the resolved Connect IQ Mobile SDK (renamed APIs: register(forAppMessages:), IQDevice(id:...), IQApp(uuid:store:device:), NS_ENUM cases, receivedMessage(_:from:), view-level .onOpenURL) and a crash-on-launch defect: LD_RUNPATH_SEARCH_PATHS lacked @executable_path/Frameworks, so every build died at Library not loaded: @rpath/ConnectIQ.framework/ConnectIQ.

Verified green at 04289f68: CI Tests (Unit Tests / Lint / iOS Test Target Compile / Build Android / Security Hygiene / iOS Schema Sync / static checks), tvOS unsigned build + native tests, native-tv(-device). Full :shared:testAndroidHostTest suite green locally on the merged tree: 6119 tests, 0 failures.

Still red: garmin-ci Build + simulator checks — monkeyc build + -t test compile now pass on all four products (fenix7/fr255/fr265/fr965), but monkeydo hangs on the GitHub runner until the script timeout even with the upstream-tested dependency set (next run will dump the partial MonkeyDo output thanks to 301ef4db, which adds timeout diagnostics). Static checks and both build layers are green.

Final visual evidence (implementation build, iOS Simulator — simulator evidence per owner policy):

Home Settings Garmin controls card (Off / default)
home settings garmin card

Captured from feat/1391-garmin-watch-controls (capture worktree at ce582b2d + local capture-only overlay scratch commits, never published) via the phantom persistent launcher + XCUITest (PHOENIX_SIMULATOR_FIXTURE=just-lift-connected, EULA seeded). State-2 capture: card variant.

Remaining before merge gate (merge gate must keep holding):

  1. garmin-ci monkeydo run green (diagnostics in place for the next tick).
  2. Visual matrix remainder: Arm strip SetReady/Active states, JustLift strip, cancel-confirm sheet, urgent-stop preemption, save timeout/failure, unavailable/setup/connected/armed/error/recovery card states, default + largest text sizes, watch-simulator Start/Next-Stop-Cancel recording — these need runtime-state seeding (matched-watch transport fixture) which was out of this run's budget.

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.

Feature: Garmin watch button controls for workouts

2 participants