From f04028233e1b1615922fd59606edd41bdb4d69dc Mon Sep 17 00:00:00 2001 From: Devil Date: Tue, 17 Nov 2026 21:27:08 -0500 Subject: [PATCH 1/3] fix(workout): anchor rest-transition authority to the entered position while a SetSummary is held (#1413) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Manual "Next Set" on a held Set Summary (Set summary duration = Manual) was rejected with AUTHORITY_REJECTED on every tap once the raw live mirror flows (currentRoutineId / currentRoutineSessionId / _currentExerciseIndex / _currentSetIndex) drifted silently during the hold, freezing the workout on the summary. The same check had passed when the completion job installed the rest plan at set-completion time. The duplicated raw-coordinate conjuncts at the four rest-transition authority gates are replaced by liveRoutinePositionMatchesSource: while a SetSummary is still displayed the position is anchored on the loaded routine and the last explicitly entered RoutineFlowState.SetReady coordinates (written atomically with the index flows by every legitimate transition); in every other state the raw mirrors stay fully authoritative, preserving #1398's PostWriteDrift rest-control revalidation contract exactly. Instrumentation: connection-log diagnostics name the rejecting conjunct and the drifting mirror (privacy-safe; index values only). Tests: Issue1413ManualSummaryDelayedContinueTest — delayed-tap contract, 4 drift regressions (RED pre-fix / GREEN post-fix, sabotage-verified), and a stale-completion guard test proving a genuine successor transition still rejects the superseded completion. --- .../manager/ActiveSessionEngine.kt | 199 ++++++++-- ...sue1413ManualSummaryDelayedContinueTest.kt | 355 ++++++++++++++++++ 2 files changed, 529 insertions(+), 25 deletions(-) create mode 100644 shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/manager/Issue1413ManualSummaryDelayedContinueTest.kt diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/ActiveSessionEngine.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/ActiveSessionEngine.kt index 67632f644..e017ff68f 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/ActiveSessionEngine.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/ActiveSessionEngine.kt @@ -2567,10 +2567,14 @@ class ActiveSessionEngine( document.restTransitionPlan == null && executionGuard.isCurrent(lease) && lease.executionId.toString() == authority.sourceExecutionId && - coordinator.currentRoutineId == document.routineId && - coordinator.currentRoutineSessionId == document.routineSessionId && - coordinator._currentExerciseIndex.value == document.sourceExerciseIndex && - coordinator._currentSetIndex.value == document.sourceSetIndex + // Issue #1413: anchored live position (see liveRoutinePositionMatchesSource). + liveRoutinePositionMatchesSource( + routineId = document.routineId, + routineSessionId = document.routineSessionId, + sourceExerciseIndex = document.sourceExerciseIndex, + sourceSetIndex = document.sourceSetIndex, + sourceRoutineExerciseId = document.routineExerciseId, + ) } private fun consumeNormalTransitionAndDispatch(plan: RestTransitionPlan.NormalAdvance) { @@ -2607,10 +2611,14 @@ class ActiveSessionEngine( return@withLock null } if (!executionGuard.isCurrent(lease) || - coordinator.currentRoutineId != cleared.routineId || - coordinator.currentRoutineSessionId != cleared.routineSessionId || - coordinator._currentExerciseIndex.value != cleared.sourceExerciseIndex || - coordinator._currentSetIndex.value != cleared.sourceSetIndex + // Issue #1413: anchored live position (see liveRoutinePositionMatchesSource). + !liveRoutinePositionMatchesSource( + routineId = cleared.routineId, + routineSessionId = cleared.routineSessionId, + sourceExerciseIndex = cleared.sourceExerciseIndex, + sourceSetIndex = cleared.sourceSetIndex, + sourceRoutineExerciseId = cleared.routineExerciseId, + ) ) { return@withLock null } @@ -2767,13 +2775,17 @@ class ActiveSessionEngine( return false } val routine = coordinator._loadedRoutine.value ?: return false - val sourceExercise = routine.exercises.getOrNull(document.sourceExerciseIndex) ?: return false return (routine.profileId ?: "default") == document.profileId && - coordinator.currentRoutineId == document.routineId && - coordinator.currentRoutineSessionId == document.routineSessionId && - coordinator._currentExerciseIndex.value == document.sourceExerciseIndex && - coordinator._currentSetIndex.value == document.sourceSetIndex && - sourceExercise.id == document.routineExerciseId + // Issue #1413: the live position is anchored by the loaded routine and the + // entered routine-flow position, not the raw mirror flows (see + // liveRoutinePositionMatchesSource). + liveRoutinePositionMatchesSource( + routineId = document.routineId, + routineSessionId = document.routineSessionId, + sourceExerciseIndex = document.sourceExerciseIndex, + sourceSetIndex = document.sourceSetIndex, + sourceRoutineExerciseId = document.routineExerciseId, + ) } private fun liveRestTransitionProfileIsCurrent(document: ActiveWorkoutRuntimeDocument): Boolean = (userProfileRepository.activeProfileContext.value as? ActiveProfileContext.Ready) @@ -4428,6 +4440,10 @@ class ActiveSessionEngine( private set internal var lastInitialRestPlanInstallResultForTest: InitialRestPlanInstallResult? = null private set + + /** Issue #1413 instrumentation: the failing identity-coordinate conjunct name, if any. */ + internal var lastCompletionRestAuthorityFailureForTest: String? = null + private set internal var afterDurableRestPlanClearForTest: (suspend () -> Unit)? = null internal var afterAcceptedRetryPlanConsumedForTest: (suspend () -> Unit)? = null internal var beforeAcceptedRetryGateCaptureForTest: (suspend () -> Unit)? = null @@ -13298,19 +13314,147 @@ class ActiveSessionEngine( ) } + /** + * Issue #1413: live-position match for a plan/identity's source coordinates. + * + * While a SetSummary is still displayed, the raw mirror flows (`currentRoutineId`, + * `currentRoutineSessionId`, `_currentExerciseIndex`, `_currentSetIndex`) can + * drift silently — the #1413 capture proved it (the same check passed when the + * plan installed at set completion; every later tap on the still-displayed summary + * was rejected; zero engine log output in the drift window) — so under a held + * summary the mirror alone must not reject a still-anchored transition. The + * material anchors there are the LOADED ROUTINE (a reload/detach/replace changes + * it; a mirror drift does not) and the last explicitly ENTERED routine-flow + * position ([RoutineFlowState.SetReady], which every legitimate position + * transition writes atomically with the index flows). A genuine successor + * transition re-enters SetReady at the successor coordinates and is still + * rejected. + * + * In every other state the raw mirrors stay fully authoritative — pre-#1413 + * semantics exactly. That strictness is load-bearing: #1398's rest-control + * revalidation deliberately reports a post-write mirror drift during Resting as + * `PostWriteDrift` (Issue1360RestControlOutcomeTest), and that contract is + * preserved. Lease currency, the completion claim, plan/document source + * coherence, cleanup fences and terminal supersession are checked separately at + * every call site and are unchanged. + */ + private fun liveRoutinePositionMatchesSource( + routineId: String, + routineSessionId: String?, + sourceExerciseIndex: Int, + sourceSetIndex: Int, + sourceRoutineExerciseId: String, + reportMirrorDrift: Boolean = false, + ): Boolean { + val routine = coordinator._loadedRoutine.value ?: return false + if (coordinator._workoutState.value !is WorkoutState.SetSummary) { + // Pre-#1413 semantics exactly: the raw mirrors are authoritative. + val sourceExercise = routine.exercises.getOrNull(sourceExerciseIndex) ?: return false + return coordinator.currentRoutineId == routineId && + coordinator.currentRoutineSessionId == routineSessionId && + coordinator._currentExerciseIndex.value == sourceExerciseIndex && + coordinator._currentSetIndex.value == sourceSetIndex && + sourceExercise.id == sourceRoutineExerciseId + } + // Held summary: the loaded routine + entered position anchor. + if (routine.id != routineId) return false + if (routine.exercises.getOrNull(sourceExerciseIndex)?.id != sourceRoutineExerciseId) return false + val indexesMatch = coordinator._currentExerciseIndex.value == sourceExerciseIndex && + coordinator._currentSetIndex.value == sourceSetIndex + if (indexesMatch) return true + val entered = coordinator._routineFlowState.value as? RoutineFlowState.SetReady + val enteredMatches = entered != null && + entered.exerciseIndex == sourceExerciseIndex && + entered.setIndex == sourceSetIndex + if (enteredMatches && reportMirrorDrift) { + recordRoutinePositionMirrorDrift(sourceExerciseIndex, sourceSetIndex) + } + return enteredMatches + } + + /** + * Issue #1413: the anchored routine position while a SetSummary is held — the + * last explicitly entered [RoutineFlowState.SetReady] coordinates whenever they + * disagree with the raw index mirrors (see [liveRoutinePositionMatchesSource]). + * Every other state uses the raw mirrors unchanged. + */ + private fun anchoredRoutinePosition(): Pair { + val rawExercise = coordinator._currentExerciseIndex.value + val rawSet = coordinator._currentSetIndex.value + if (coordinator._workoutState.value !is WorkoutState.SetSummary) { + return rawExercise to rawSet + } + val entered = coordinator._routineFlowState.value as? RoutineFlowState.SetReady + if (entered != null && (entered.exerciseIndex != rawExercise || entered.setIndex != rawSet)) { + return entered.exerciseIndex to entered.setIndex + } + return rawExercise to rawSet + } + + /** + * Issue #1413 instrumentation: name the drifting live mirror when the anchor + * still accepts a transition. Kermit [Logger] never reaches the unified log in + * this build, so the diagnostic rides the observable connection-log channel + * (PHX-CAPTURE-LOG). Privacy-safe: coordinate values only, never identifiers. + */ + private fun recordRoutinePositionMirrorDrift(sourceExerciseIndex: Int, sourceSetIndex: Int) { + connectionLogRepository.info( + LogEventType.WORKOUT_PERSISTENCE, + "Rest transition live mirror drifted; entered position still authoritative", + details = "identityExerciseIndex=$sourceExerciseIndex,identitySetIndex=$sourceSetIndex" + + ",currentExerciseIndex=${coordinator._currentExerciseIndex.value}" + + ",currentSetIndex=${coordinator._currentSetIndex.value}" + + ",enteredPosition=${(coordinator._routineFlowState.value as? RoutineFlowState.SetReady)?.let { "${it.exerciseIndex}:${it.setIndex}" } ?: "none"}", + ) + } + private fun hasCompletionRestAuthority(completion: SetExecutionCompletion): Boolean { val identity = completion.routineIdentity ?: return false - if (!executionGuard.isCurrent(completion.lease) || - completion.lease.profileId != identity.profileId || - coordinator.currentRoutineId != identity.routineId || - coordinator.currentRoutineSessionId != identity.routineSessionId || - coordinator._currentExerciseIndex.value != identity.exerciseIndex || - coordinator._currentSetIndex.value != identity.setIndex + if (!executionGuard.isCurrent(completion.lease)) { + recordCompletionRestAuthorityFailure("lease_not_current", identity) + return false + } + if (completion.lease.profileId != identity.profileId) { + recordCompletionRestAuthorityFailure("profile_id", identity) + return false + } + if (!liveRoutinePositionMatchesSource( + routineId = identity.routineId, + routineSessionId = identity.routineSessionId, + sourceExerciseIndex = identity.exerciseIndex, + sourceSetIndex = identity.setIndex, + sourceRoutineExerciseId = identity.routineExerciseId, + reportMirrorDrift = true, + ) ) { + recordCompletionRestAuthorityFailure("live_routine_position", identity) return false } - val routine = coordinator._loadedRoutine.value ?: return false - return routine.exercises.getOrNull(identity.exerciseIndex)?.id == identity.routineExerciseId + return true + } + + /** + * Issue #1413 instrumentation: name the exact conjunct that rejected a + * completion's rest authority. Privacy-safe: conjunct names and index values + * only; the identifier-valued conjuncts log their name, never their values. + */ + private fun recordCompletionRestAuthorityFailure( + conjunct: String, + identity: com.devil.phoenixproject.domain.model.RoutineExecutionIdentity, + ) { + lastCompletionRestAuthorityFailureForTest = conjunct + val details = when (conjunct) { + "live_routine_position" -> "conjunct=live_routine_position,identityExerciseIndex=${identity.exerciseIndex}" + + ",identitySetIndex=${identity.setIndex}" + + ",currentExerciseIndex=${coordinator._currentExerciseIndex.value}" + + ",currentSetIndex=${coordinator._currentSetIndex.value}" + else -> "conjunct=$conjunct" + } + connectionLogRepository.info( + LogEventType.WORKOUT_PERSISTENCE, + "Rest transition authority check rejected a completion", + details = details, + ) } /** @@ -13549,10 +13693,15 @@ class ActiveSessionEngine( if (nextStep != null) { val (nextExIdx, nextSetIdx) = nextStep val nextExercise = routine.exercises[nextExIdx] - val currentExercise = routine.exercises.getOrNull(coordinator._currentExerciseIndex.value) + // Issue #1413: classify the boundary from the anchored position (see + // liveRoutinePositionMatchesSource), not the raw index mirrors — a silent + // mirror drift would mis-classify an entry boundary as a within-entry + // advance and strand the summary on screen. + val (fromExerciseIndex, _) = anchoredRoutinePosition() + val currentExercise = routine.exercises.getOrNull(fromExerciseIndex) val autoplay = settingsManager.autoplayEnabled.value - val isChangingExercise = nextExIdx != coordinator._currentExerciseIndex.value + val isChangingExercise = nextExIdx != fromExerciseIndex // Issue #572 / #1394: when getNextStep advances to the next entry but the new // entry is the same physical exercise as the current one (e.g. "Sumo Belt Squat // 2x8 OldSchool" -> "Sumo Belt Squat 1x8 TUT" the user intends as a single @@ -13569,7 +13718,7 @@ class ActiveSessionEngine( // the user explicitly starts that set. That manual gate no longer fires for // equivalent settings. val isAdjacentLinearExercise = - nextExIdx == coordinator._currentExerciseIndex.value + 1 && + nextExIdx == fromExerciseIndex + 1 && currentExercise?.supersetId == null && nextExercise.supersetId == null val isSameExerciseContinuation = isChangingExercise && diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/manager/Issue1413ManualSummaryDelayedContinueTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/manager/Issue1413ManualSummaryDelayedContinueTest.kt new file mode 100644 index 000000000..6b98b1bac --- /dev/null +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/manager/Issue1413ManualSummaryDelayedContinueTest.kt @@ -0,0 +1,355 @@ +package com.devil.phoenixproject.presentation.manager + +import com.devil.phoenixproject.domain.model.EccentricLoad +import com.devil.phoenixproject.domain.model.EchoLevel +import com.devil.phoenixproject.domain.model.Exercise +import com.devil.phoenixproject.domain.model.ProgramMode +import com.devil.phoenixproject.domain.model.RepCount +import com.devil.phoenixproject.domain.model.Routine +import com.devil.phoenixproject.domain.model.RoutineExercise +import com.devil.phoenixproject.domain.model.RoutineFlowState +import com.devil.phoenixproject.domain.model.SetEndReason +import com.devil.phoenixproject.domain.model.WarmupSet +import com.devil.phoenixproject.domain.model.WorkoutState +import com.devil.phoenixproject.testutil.DWSMTestHarness +import com.devil.phoenixproject.testutil.TestFixtures +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest + +/** + * Issue #1413: manual "Next Set" on a held Set Summary (Set summary duration = Manual) + * is rejected with `Rest transition install failed reason=AUTHORITY_REJECTED` once the + * tap lands after the machine teardown window. The engine contract test + * `autoplay off keeps manual readiness at duplicate boundary` (Issue1394) taps at +1 s + * and passes; the in-app taps land 20 s+ after set completion and every one is rejected, + * freezing the workout on the summary. + * + * These tests drive the REAL production path (handleSetCompletion -> SetSummary -> + * explicit proceedFromSummary() tap -> rest transition install) with fake BLE, delaying + * the tap past the teardown window exactly as the simulator capture observed. + */ +class Issue1413ManualSummaryDelayedContinueTest { + + private fun entry( + id: String, + order: Int, + exercise: Exercise = TestFixtures.singleArmRow, + programMode: ProgramMode = ProgramMode.OldSchool, + echoLevel: EchoLevel = EchoLevel.HARDER, + eccentricLoad: EccentricLoad = EccentricLoad.LOAD_100, + setReps: List = listOf(10), + warmupSets: List = emptyList(), + ): RoutineExercise = RoutineExercise( + id = id, + // Force a cable accessory: TestFixtures rows with non-cable equipment + // classify as bodyweight and route startWorkout to BodyweightRepEntry, + // which is not the reported machine-connected routine path. + exercise = exercise.copy(equipment = "CABLE"), + orderIndex = order, + setReps = setReps, + weightPerCableKg = 25f, + setRestSeconds = listOf(2), + programMode = programMode, + echoLevel = echoLevel, + eccentricLoad = eccentricLoad, + warmupSets = warmupSets, + ) + + private fun routine(id: String, exercises: List): Routine = + Routine(id = id, name = id, exercises = exercises) + + private suspend fun TestScope.startFirstSet(harness: DWSMTestHarness) { + harness.fakeBleRepo.simulateConnect("Vee_Test") + advanceUntilIdle() + harness.dwsm.enterSetReady(0, 0) + advanceUntilIdle() + harness.dwsm.startWorkout(skipCountdown = true) + advanceUntilIdle() + assertIs(harness.dwsm.coordinator.workoutState.value) + } + + private suspend fun TestScope.completeActiveSetToHeldSummary(harness: DWSMTestHarness) { + harness.dwsm.coordinator._repCount.value = RepCount( + warmupReps = 0, + workingReps = 10, + totalReps = 10, + isWarmupComplete = true, + ) + harness.activeSessionEngine.handleSetCompletion( + harness.activeSessionEngine.currentExecutionLeaseForTest(), + SetEndReason.TARGET_REPS_REACHED, + ) + // handleSetCompletion does delay(summaryDelayMs) then startRestTimer(); use + // advanceTimeBy, never advanceUntilIdle (rest timer has an infinite tick loop). + advanceTimeBy(1_000) + assertIs( + harness.dwsm.coordinator.workoutState.value, + "completed set must show its summary", + ) + } + + /** + * RED/GREEN regression for #1413: the user's explicit "Next Set" tap must install + * the rest transition from the claimed completion and proceed to the successor's + * manual readiness — even when the tap lands long after the machine teardown + * window (the engine contract test taps at +1 s; the in-app taps land 20 s+ after + * set completion and were all rejected with AUTHORITY_REJECTED, freezing the + * workout on the summary). + */ + @Test + fun `manual Next Set tap after the machine teardown window installs the rest plan`() = runTest { + val harness = DWSMTestHarness(this) + try { + harness.setActiveSummaryCountdownSeconds(0) // Manual; summary holds + val row = TestFixtures.singleArmRow + val routine = routine( + "issue-1413-manual-delayed-continue", + listOf( + entry("e1", 0, row), + entry("e2", 1, row), + ), + ) + routine.exercises.forEach { harness.fakeExerciseRepo.addExercise(it.exercise) } + advanceUntilIdle() + harness.dwsm.loadRoutine(routine) + advanceUntilIdle() + + startFirstSet(harness) + completeActiveSetToHeldSummary(harness) + + // The defect window: the tap lands well after the machine teardown + // (teardown completes within the first second; the simulator capture's + // first genuine tap landed ~20 s after set completion). Nothing may + // drift the completion's identity coordinates during the hold. + advanceTimeBy(30_000) + runCurrent() + assertIs( + harness.dwsm.coordinator.workoutState.value, + "the Manual summary must keep holding while the user delays", + ) + + val lease = assertNotNull(harness.activeSessionEngine.currentExecutionLeaseOrNull()) + val completion = assertNotNull( + harness.activeSessionEngine.claimedCompletion(lease), + "the claimed set completion must survive the hold for the manual continue", + ) + val identity = assertNotNull(completion.routineIdentity) + + // Manual summary: the user continues to rest explicitly. + harness.dwsm.proceedFromSummary() + runCurrent() + advanceTimeBy(4_000) + runCurrent() + + assertIs( + harness.activeSessionEngine.lastInitialRestPlanInstallResultForTest, + "the explicit continue must install the rest transition plan " + + "(identity=$identity, " + + "currentExerciseIndex=${harness.dwsm.coordinator._currentExerciseIndex.value}, " + + "currentSetIndex=${harness.dwsm.coordinator._currentSetIndex.value}, " + + "currentRoutineId=${harness.dwsm.coordinator.currentRoutineId}, " + + "currentRoutineSessionId=${harness.dwsm.coordinator.currentRoutineSessionId}, " + + "loadedRoutineExerciseIds=${harness.dwsm.coordinator._loadedRoutine.value?.exercises?.map { it.id }})", + ) + + // Manual readiness at the entry boundary: Idle + SetReady(1, 0), and no + // unsolicited successor CONFIG before the explicit Start (issue #1394's + // autoplay-off contract must survive the delayed tap). + val state = harness.dwsm.coordinator.workoutState.value + assertIs( + state, + "the delayed manual continue must advance off the held summary", + ) + val ready = assertIs( + harness.dwsm.coordinator.routineFlowState.value, + "the successor entry must be ready for the explicit Start", + ) + assertEquals(1, ready.exerciseIndex) + assertEquals(0, ready.setIndex) + assertEquals( + 1, + harness.fakeBleRepo.programCommands.size, + "no unsolicited successor CONFIG before explicit Start", + ) + } finally { + harness.cleanup() + } + } + + /** + * RED/GREEN regression for #1413's observed failure state. The simulator capture + * proved the tap-time rejection is an identity-coordinate conjunct drift in + * [ActiveSessionEngine.hasCompletionRestAuthority]: the same check PASSED when the + * completion job installed the rest plan at set-completion time (zero install + * warnings in the capture log), and every later tap on the still-displayed summary + * was rejected after a silent drift during the hold (zero connection-log entries + * between teardown-ready and the first rejection; the lease gates all passed — no + * `transition=suppressed` entries). The drift writer is app-side and is named by + * the #1413 instrumentation (`conjunct=...` connection-log line) on the next + * simulator run; delaying the tap alone does NOT drift engine state (the sibling + * test above holds green at +30 s), so this test drives the observed end state + * directly: the completion's rest plan is already installed, the summary is still + * displayed, and one live identity coordinate no longer matches the completion. + * + * Contract under test: the user's explicit continue on the still-displayed summary + * of a completion whose rest plan is already installed must install (return + * `Installed(existing)`) and advance — the plan's source-execution + logical-set-key + * match is the stale-completion guard, not live coordinator coordinates. A + * completion whose plan is NOT installed must still be rejected on drift (see + * `stale completion without an installed plan is still rejected after drift`). + */ + @Test + fun `manual continue proceeds when a live coordinate drifted after the plan was installed (setIndex)`() = + assertManualContinueSurvivesDrift { harness, identity -> + harness.dwsm.coordinator._currentSetIndex.value = identity.setIndex + 1 + } + + @Test + fun `manual continue proceeds when a live coordinate drifted after the plan was installed (exerciseIndex)`() = + assertManualContinueSurvivesDrift { harness, identity -> + harness.dwsm.coordinator._currentExerciseIndex.value = identity.exerciseIndex + 1 + } + + @Test + fun `manual continue proceeds when a live coordinate drifted after the plan was installed (routineSessionId)`() = + assertManualContinueSurvivesDrift { harness, _ -> + harness.dwsm.coordinator.currentRoutineSessionId = "drifted-routine-session" + } + + @Test + fun `manual continue proceeds when a live coordinate drifted after the plan was installed (routineId)`() = + assertManualContinueSurvivesDrift { harness, _ -> + harness.dwsm.coordinator.currentRoutineId = "drifted-routine" + } + + private fun assertManualContinueSurvivesDrift( + drift: (DWSMTestHarness, com.devil.phoenixproject.domain.model.RoutineExecutionIdentity) -> Unit, + ) = runTest { + val harness = DWSMTestHarness(this) + try { + harness.setActiveSummaryCountdownSeconds(0) // Manual; summary holds + val row = TestFixtures.singleArmRow + val routine = routine( + "issue-1413-drifted-continue", + listOf( + entry("e1", 0, row), + entry("e2", 1, row), + ), + ) + routine.exercises.forEach { harness.fakeExerciseRepo.addExercise(it.exercise) } + advanceUntilIdle() + harness.dwsm.loadRoutine(routine) + advanceUntilIdle() + + startFirstSet(harness) + completeActiveSetToHeldSummary(harness) + + // Past the machine teardown window (the capture's taps landed 20 s+ + // after set completion), the plan already installed by the completion + // job under full authority. + advanceTimeBy(30_000) + runCurrent() + assertIs(harness.dwsm.coordinator.workoutState.value) + + val lease = assertNotNull(harness.activeSessionEngine.currentExecutionLeaseOrNull()) + val completion = assertNotNull(harness.activeSessionEngine.claimedCompletion(lease)) + val identity = assertNotNull(completion.routineIdentity) + val installedPlan = assertNotNull( + harness.dwsm.coordinator.restTransitionPlan.value, + "the completion job must have installed the rest plan before the summary showed", + ) + + drift(harness, identity) + + harness.dwsm.proceedFromSummary() + runCurrent() + advanceTimeBy(4_000) + runCurrent() + + val result = harness.activeSessionEngine.lastInitialRestPlanInstallResultForTest + assertIs( + result, + "the still-displayed summary's own completion must install despite the drifted " + + "live coordinate (identity=$identity, drift result observed at tap)", + ) + assertEquals( + installedPlan, + (result as InitialRestPlanInstallResult.Installed).plan, + "the already-installed plan must be returned unchanged", + ) + assertIs( + harness.dwsm.coordinator.workoutState.value, + "the manual continue must advance off the held summary", + ) + assertEquals( + 1, + harness.fakeBleRepo.programCommands.size, + "no unsolicited successor CONFIG before explicit Start", + ) + } finally { + harness.cleanup() + } + } + + /** + * Stale-completion guard preservation (the "narrow fix keeps stale-completion + * guards" requirement): a genuine successor transition — the workout re-enters + * SetReady at the successor coordinates exactly as startNextSetOrExercise does, + * moving the index flows AND the routine-flow + * position atomically — must still reject the superseded completion's rest + * install. Only the silent mirror drift is tolerated; a real position transition + * is not. Lease currency and the claim/plan-source guards are unchanged. + */ + @Test + fun `genuine successor transition still rejects the superseded completion`() = runTest { + val harness = DWSMTestHarness(this) + try { + harness.setActiveSummaryCountdownSeconds(0) // Manual; summary holds + val row = TestFixtures.singleArmRow + val routine = routine( + "issue-1413-guard-preservation", + listOf( + entry("e1", 0, row), + entry("e2", 1, row), + ), + ) + routine.exercises.forEach { harness.fakeExerciseRepo.addExercise(it.exercise) } + advanceUntilIdle() + harness.dwsm.loadRoutine(routine) + advanceUntilIdle() + + startFirstSet(harness) + completeActiveSetToHeldSummary(harness) + advanceTimeBy(30_000) + runCurrent() + + val lease = assertNotNull(harness.activeSessionEngine.currentExecutionLeaseOrNull()) + val completion = assertNotNull(harness.activeSessionEngine.claimedCompletion(lease)) + assertNotNull(completion.routineIdentity) + + // The workout genuinely moved on to the successor entry's set. + harness.dwsm.enterSetReady(1, 0) + advanceUntilIdle() + + harness.activeSessionEngine.installInitialRestPlanForTest(completion, 60) + assertIs( + harness.activeSessionEngine.lastInitialRestPlanInstallResultForTest, + "the superseded completion must not install over the successor's position", + ) + assertEquals( + "live_routine_position", + harness.activeSessionEngine.lastCompletionRestAuthorityFailureForTest, + "the rejection must be attributed to the live-position conjunct", + ) + } finally { + harness.cleanup() + } + } +} From dd009d05bd2dfe80739af91dffea250e7e3d1a53 Mon Sep 17 00:00:00 2001 From: Devil Date: Tue, 17 Nov 2026 22:07:29 -0500 Subject: [PATCH 2/3] Revert "fix(workout): anchor rest-transition authority to the entered position while a SetSummary is held (#1413)" This reverts commit f04028233e1b1615922fd59606edd41bdb4d69dc. --- .../manager/ActiveSessionEngine.kt | 199 ++-------- ...sue1413ManualSummaryDelayedContinueTest.kt | 355 ------------------ 2 files changed, 25 insertions(+), 529 deletions(-) delete mode 100644 shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/manager/Issue1413ManualSummaryDelayedContinueTest.kt diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/ActiveSessionEngine.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/ActiveSessionEngine.kt index 36e50786e..3501bb18d 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/ActiveSessionEngine.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/ActiveSessionEngine.kt @@ -2567,14 +2567,10 @@ class ActiveSessionEngine( document.restTransitionPlan == null && executionGuard.isCurrent(lease) && lease.executionId.toString() == authority.sourceExecutionId && - // Issue #1413: anchored live position (see liveRoutinePositionMatchesSource). - liveRoutinePositionMatchesSource( - routineId = document.routineId, - routineSessionId = document.routineSessionId, - sourceExerciseIndex = document.sourceExerciseIndex, - sourceSetIndex = document.sourceSetIndex, - sourceRoutineExerciseId = document.routineExerciseId, - ) + coordinator.currentRoutineId == document.routineId && + coordinator.currentRoutineSessionId == document.routineSessionId && + coordinator._currentExerciseIndex.value == document.sourceExerciseIndex && + coordinator._currentSetIndex.value == document.sourceSetIndex } private fun consumeNormalTransitionAndDispatch(plan: RestTransitionPlan.NormalAdvance) { @@ -2611,14 +2607,10 @@ class ActiveSessionEngine( return@withLock null } if (!executionGuard.isCurrent(lease) || - // Issue #1413: anchored live position (see liveRoutinePositionMatchesSource). - !liveRoutinePositionMatchesSource( - routineId = cleared.routineId, - routineSessionId = cleared.routineSessionId, - sourceExerciseIndex = cleared.sourceExerciseIndex, - sourceSetIndex = cleared.sourceSetIndex, - sourceRoutineExerciseId = cleared.routineExerciseId, - ) + coordinator.currentRoutineId != cleared.routineId || + coordinator.currentRoutineSessionId != cleared.routineSessionId || + coordinator._currentExerciseIndex.value != cleared.sourceExerciseIndex || + coordinator._currentSetIndex.value != cleared.sourceSetIndex ) { return@withLock null } @@ -2775,17 +2767,13 @@ class ActiveSessionEngine( return false } val routine = coordinator._loadedRoutine.value ?: return false + val sourceExercise = routine.exercises.getOrNull(document.sourceExerciseIndex) ?: return false return (routine.profileId ?: "default") == document.profileId && - // Issue #1413: the live position is anchored by the loaded routine and the - // entered routine-flow position, not the raw mirror flows (see - // liveRoutinePositionMatchesSource). - liveRoutinePositionMatchesSource( - routineId = document.routineId, - routineSessionId = document.routineSessionId, - sourceExerciseIndex = document.sourceExerciseIndex, - sourceSetIndex = document.sourceSetIndex, - sourceRoutineExerciseId = document.routineExerciseId, - ) + coordinator.currentRoutineId == document.routineId && + coordinator.currentRoutineSessionId == document.routineSessionId && + coordinator._currentExerciseIndex.value == document.sourceExerciseIndex && + coordinator._currentSetIndex.value == document.sourceSetIndex && + sourceExercise.id == document.routineExerciseId } private fun liveRestTransitionProfileIsCurrent(document: ActiveWorkoutRuntimeDocument): Boolean = (userProfileRepository.activeProfileContext.value as? ActiveProfileContext.Ready) @@ -4440,10 +4428,6 @@ class ActiveSessionEngine( private set internal var lastInitialRestPlanInstallResultForTest: InitialRestPlanInstallResult? = null private set - - /** Issue #1413 instrumentation: the failing identity-coordinate conjunct name, if any. */ - internal var lastCompletionRestAuthorityFailureForTest: String? = null - private set internal var afterDurableRestPlanClearForTest: (suspend () -> Unit)? = null internal var afterAcceptedRetryPlanConsumedForTest: (suspend () -> Unit)? = null internal var beforeAcceptedRetryGateCaptureForTest: (suspend () -> Unit)? = null @@ -13315,147 +13299,19 @@ class ActiveSessionEngine( ) } - /** - * Issue #1413: live-position match for a plan/identity's source coordinates. - * - * While a SetSummary is still displayed, the raw mirror flows (`currentRoutineId`, - * `currentRoutineSessionId`, `_currentExerciseIndex`, `_currentSetIndex`) can - * drift silently — the #1413 capture proved it (the same check passed when the - * plan installed at set completion; every later tap on the still-displayed summary - * was rejected; zero engine log output in the drift window) — so under a held - * summary the mirror alone must not reject a still-anchored transition. The - * material anchors there are the LOADED ROUTINE (a reload/detach/replace changes - * it; a mirror drift does not) and the last explicitly ENTERED routine-flow - * position ([RoutineFlowState.SetReady], which every legitimate position - * transition writes atomically with the index flows). A genuine successor - * transition re-enters SetReady at the successor coordinates and is still - * rejected. - * - * In every other state the raw mirrors stay fully authoritative — pre-#1413 - * semantics exactly. That strictness is load-bearing: #1398's rest-control - * revalidation deliberately reports a post-write mirror drift during Resting as - * `PostWriteDrift` (Issue1360RestControlOutcomeTest), and that contract is - * preserved. Lease currency, the completion claim, plan/document source - * coherence, cleanup fences and terminal supersession are checked separately at - * every call site and are unchanged. - */ - private fun liveRoutinePositionMatchesSource( - routineId: String, - routineSessionId: String?, - sourceExerciseIndex: Int, - sourceSetIndex: Int, - sourceRoutineExerciseId: String, - reportMirrorDrift: Boolean = false, - ): Boolean { - val routine = coordinator._loadedRoutine.value ?: return false - if (coordinator._workoutState.value !is WorkoutState.SetSummary) { - // Pre-#1413 semantics exactly: the raw mirrors are authoritative. - val sourceExercise = routine.exercises.getOrNull(sourceExerciseIndex) ?: return false - return coordinator.currentRoutineId == routineId && - coordinator.currentRoutineSessionId == routineSessionId && - coordinator._currentExerciseIndex.value == sourceExerciseIndex && - coordinator._currentSetIndex.value == sourceSetIndex && - sourceExercise.id == sourceRoutineExerciseId - } - // Held summary: the loaded routine + entered position anchor. - if (routine.id != routineId) return false - if (routine.exercises.getOrNull(sourceExerciseIndex)?.id != sourceRoutineExerciseId) return false - val indexesMatch = coordinator._currentExerciseIndex.value == sourceExerciseIndex && - coordinator._currentSetIndex.value == sourceSetIndex - if (indexesMatch) return true - val entered = coordinator._routineFlowState.value as? RoutineFlowState.SetReady - val enteredMatches = entered != null && - entered.exerciseIndex == sourceExerciseIndex && - entered.setIndex == sourceSetIndex - if (enteredMatches && reportMirrorDrift) { - recordRoutinePositionMirrorDrift(sourceExerciseIndex, sourceSetIndex) - } - return enteredMatches - } - - /** - * Issue #1413: the anchored routine position while a SetSummary is held — the - * last explicitly entered [RoutineFlowState.SetReady] coordinates whenever they - * disagree with the raw index mirrors (see [liveRoutinePositionMatchesSource]). - * Every other state uses the raw mirrors unchanged. - */ - private fun anchoredRoutinePosition(): Pair { - val rawExercise = coordinator._currentExerciseIndex.value - val rawSet = coordinator._currentSetIndex.value - if (coordinator._workoutState.value !is WorkoutState.SetSummary) { - return rawExercise to rawSet - } - val entered = coordinator._routineFlowState.value as? RoutineFlowState.SetReady - if (entered != null && (entered.exerciseIndex != rawExercise || entered.setIndex != rawSet)) { - return entered.exerciseIndex to entered.setIndex - } - return rawExercise to rawSet - } - - /** - * Issue #1413 instrumentation: name the drifting live mirror when the anchor - * still accepts a transition. Kermit [Logger] never reaches the unified log in - * this build, so the diagnostic rides the observable connection-log channel - * (PHX-CAPTURE-LOG). Privacy-safe: coordinate values only, never identifiers. - */ - private fun recordRoutinePositionMirrorDrift(sourceExerciseIndex: Int, sourceSetIndex: Int) { - connectionLogRepository.info( - LogEventType.WORKOUT_PERSISTENCE, - "Rest transition live mirror drifted; entered position still authoritative", - details = "identityExerciseIndex=$sourceExerciseIndex,identitySetIndex=$sourceSetIndex" + - ",currentExerciseIndex=${coordinator._currentExerciseIndex.value}" + - ",currentSetIndex=${coordinator._currentSetIndex.value}" + - ",enteredPosition=${(coordinator._routineFlowState.value as? RoutineFlowState.SetReady)?.let { "${it.exerciseIndex}:${it.setIndex}" } ?: "none"}", - ) - } - private fun hasCompletionRestAuthority(completion: SetExecutionCompletion): Boolean { val identity = completion.routineIdentity ?: return false - if (!executionGuard.isCurrent(completion.lease)) { - recordCompletionRestAuthorityFailure("lease_not_current", identity) - return false - } - if (completion.lease.profileId != identity.profileId) { - recordCompletionRestAuthorityFailure("profile_id", identity) - return false - } - if (!liveRoutinePositionMatchesSource( - routineId = identity.routineId, - routineSessionId = identity.routineSessionId, - sourceExerciseIndex = identity.exerciseIndex, - sourceSetIndex = identity.setIndex, - sourceRoutineExerciseId = identity.routineExerciseId, - reportMirrorDrift = true, - ) + if (!executionGuard.isCurrent(completion.lease) || + completion.lease.profileId != identity.profileId || + coordinator.currentRoutineId != identity.routineId || + coordinator.currentRoutineSessionId != identity.routineSessionId || + coordinator._currentExerciseIndex.value != identity.exerciseIndex || + coordinator._currentSetIndex.value != identity.setIndex ) { - recordCompletionRestAuthorityFailure("live_routine_position", identity) return false } - return true - } - - /** - * Issue #1413 instrumentation: name the exact conjunct that rejected a - * completion's rest authority. Privacy-safe: conjunct names and index values - * only; the identifier-valued conjuncts log their name, never their values. - */ - private fun recordCompletionRestAuthorityFailure( - conjunct: String, - identity: com.devil.phoenixproject.domain.model.RoutineExecutionIdentity, - ) { - lastCompletionRestAuthorityFailureForTest = conjunct - val details = when (conjunct) { - "live_routine_position" -> "conjunct=live_routine_position,identityExerciseIndex=${identity.exerciseIndex}" + - ",identitySetIndex=${identity.setIndex}" + - ",currentExerciseIndex=${coordinator._currentExerciseIndex.value}" + - ",currentSetIndex=${coordinator._currentSetIndex.value}" - else -> "conjunct=$conjunct" - } - connectionLogRepository.info( - LogEventType.WORKOUT_PERSISTENCE, - "Rest transition authority check rejected a completion", - details = details, - ) + val routine = coordinator._loadedRoutine.value ?: return false + return routine.exercises.getOrNull(identity.exerciseIndex)?.id == identity.routineExerciseId } /** @@ -13694,15 +13550,10 @@ class ActiveSessionEngine( if (nextStep != null) { val (nextExIdx, nextSetIdx) = nextStep val nextExercise = routine.exercises[nextExIdx] - // Issue #1413: classify the boundary from the anchored position (see - // liveRoutinePositionMatchesSource), not the raw index mirrors — a silent - // mirror drift would mis-classify an entry boundary as a within-entry - // advance and strand the summary on screen. - val (fromExerciseIndex, _) = anchoredRoutinePosition() - val currentExercise = routine.exercises.getOrNull(fromExerciseIndex) + val currentExercise = routine.exercises.getOrNull(coordinator._currentExerciseIndex.value) val autoplay = settingsManager.autoplayEnabled.value - val isChangingExercise = nextExIdx != fromExerciseIndex + val isChangingExercise = nextExIdx != coordinator._currentExerciseIndex.value // Issue #572 / #1394: when getNextStep advances to the next entry but the new // entry is the same physical exercise as the current one (e.g. "Sumo Belt Squat // 2x8 OldSchool" -> "Sumo Belt Squat 1x8 TUT" the user intends as a single @@ -13719,7 +13570,7 @@ class ActiveSessionEngine( // the user explicitly starts that set. That manual gate no longer fires for // equivalent settings. val isAdjacentLinearExercise = - nextExIdx == fromExerciseIndex + 1 && + nextExIdx == coordinator._currentExerciseIndex.value + 1 && currentExercise?.supersetId == null && nextExercise.supersetId == null val isSameExerciseContinuation = isChangingExercise && diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/manager/Issue1413ManualSummaryDelayedContinueTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/manager/Issue1413ManualSummaryDelayedContinueTest.kt deleted file mode 100644 index 6b98b1bac..000000000 --- a/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/manager/Issue1413ManualSummaryDelayedContinueTest.kt +++ /dev/null @@ -1,355 +0,0 @@ -package com.devil.phoenixproject.presentation.manager - -import com.devil.phoenixproject.domain.model.EccentricLoad -import com.devil.phoenixproject.domain.model.EchoLevel -import com.devil.phoenixproject.domain.model.Exercise -import com.devil.phoenixproject.domain.model.ProgramMode -import com.devil.phoenixproject.domain.model.RepCount -import com.devil.phoenixproject.domain.model.Routine -import com.devil.phoenixproject.domain.model.RoutineExercise -import com.devil.phoenixproject.domain.model.RoutineFlowState -import com.devil.phoenixproject.domain.model.SetEndReason -import com.devil.phoenixproject.domain.model.WarmupSet -import com.devil.phoenixproject.domain.model.WorkoutState -import com.devil.phoenixproject.testutil.DWSMTestHarness -import com.devil.phoenixproject.testutil.TestFixtures -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertIs -import kotlin.test.assertNotNull -import kotlinx.coroutines.test.TestScope -import kotlinx.coroutines.test.advanceTimeBy -import kotlinx.coroutines.test.advanceUntilIdle -import kotlinx.coroutines.test.runCurrent -import kotlinx.coroutines.test.runTest - -/** - * Issue #1413: manual "Next Set" on a held Set Summary (Set summary duration = Manual) - * is rejected with `Rest transition install failed reason=AUTHORITY_REJECTED` once the - * tap lands after the machine teardown window. The engine contract test - * `autoplay off keeps manual readiness at duplicate boundary` (Issue1394) taps at +1 s - * and passes; the in-app taps land 20 s+ after set completion and every one is rejected, - * freezing the workout on the summary. - * - * These tests drive the REAL production path (handleSetCompletion -> SetSummary -> - * explicit proceedFromSummary() tap -> rest transition install) with fake BLE, delaying - * the tap past the teardown window exactly as the simulator capture observed. - */ -class Issue1413ManualSummaryDelayedContinueTest { - - private fun entry( - id: String, - order: Int, - exercise: Exercise = TestFixtures.singleArmRow, - programMode: ProgramMode = ProgramMode.OldSchool, - echoLevel: EchoLevel = EchoLevel.HARDER, - eccentricLoad: EccentricLoad = EccentricLoad.LOAD_100, - setReps: List = listOf(10), - warmupSets: List = emptyList(), - ): RoutineExercise = RoutineExercise( - id = id, - // Force a cable accessory: TestFixtures rows with non-cable equipment - // classify as bodyweight and route startWorkout to BodyweightRepEntry, - // which is not the reported machine-connected routine path. - exercise = exercise.copy(equipment = "CABLE"), - orderIndex = order, - setReps = setReps, - weightPerCableKg = 25f, - setRestSeconds = listOf(2), - programMode = programMode, - echoLevel = echoLevel, - eccentricLoad = eccentricLoad, - warmupSets = warmupSets, - ) - - private fun routine(id: String, exercises: List): Routine = - Routine(id = id, name = id, exercises = exercises) - - private suspend fun TestScope.startFirstSet(harness: DWSMTestHarness) { - harness.fakeBleRepo.simulateConnect("Vee_Test") - advanceUntilIdle() - harness.dwsm.enterSetReady(0, 0) - advanceUntilIdle() - harness.dwsm.startWorkout(skipCountdown = true) - advanceUntilIdle() - assertIs(harness.dwsm.coordinator.workoutState.value) - } - - private suspend fun TestScope.completeActiveSetToHeldSummary(harness: DWSMTestHarness) { - harness.dwsm.coordinator._repCount.value = RepCount( - warmupReps = 0, - workingReps = 10, - totalReps = 10, - isWarmupComplete = true, - ) - harness.activeSessionEngine.handleSetCompletion( - harness.activeSessionEngine.currentExecutionLeaseForTest(), - SetEndReason.TARGET_REPS_REACHED, - ) - // handleSetCompletion does delay(summaryDelayMs) then startRestTimer(); use - // advanceTimeBy, never advanceUntilIdle (rest timer has an infinite tick loop). - advanceTimeBy(1_000) - assertIs( - harness.dwsm.coordinator.workoutState.value, - "completed set must show its summary", - ) - } - - /** - * RED/GREEN regression for #1413: the user's explicit "Next Set" tap must install - * the rest transition from the claimed completion and proceed to the successor's - * manual readiness — even when the tap lands long after the machine teardown - * window (the engine contract test taps at +1 s; the in-app taps land 20 s+ after - * set completion and were all rejected with AUTHORITY_REJECTED, freezing the - * workout on the summary). - */ - @Test - fun `manual Next Set tap after the machine teardown window installs the rest plan`() = runTest { - val harness = DWSMTestHarness(this) - try { - harness.setActiveSummaryCountdownSeconds(0) // Manual; summary holds - val row = TestFixtures.singleArmRow - val routine = routine( - "issue-1413-manual-delayed-continue", - listOf( - entry("e1", 0, row), - entry("e2", 1, row), - ), - ) - routine.exercises.forEach { harness.fakeExerciseRepo.addExercise(it.exercise) } - advanceUntilIdle() - harness.dwsm.loadRoutine(routine) - advanceUntilIdle() - - startFirstSet(harness) - completeActiveSetToHeldSummary(harness) - - // The defect window: the tap lands well after the machine teardown - // (teardown completes within the first second; the simulator capture's - // first genuine tap landed ~20 s after set completion). Nothing may - // drift the completion's identity coordinates during the hold. - advanceTimeBy(30_000) - runCurrent() - assertIs( - harness.dwsm.coordinator.workoutState.value, - "the Manual summary must keep holding while the user delays", - ) - - val lease = assertNotNull(harness.activeSessionEngine.currentExecutionLeaseOrNull()) - val completion = assertNotNull( - harness.activeSessionEngine.claimedCompletion(lease), - "the claimed set completion must survive the hold for the manual continue", - ) - val identity = assertNotNull(completion.routineIdentity) - - // Manual summary: the user continues to rest explicitly. - harness.dwsm.proceedFromSummary() - runCurrent() - advanceTimeBy(4_000) - runCurrent() - - assertIs( - harness.activeSessionEngine.lastInitialRestPlanInstallResultForTest, - "the explicit continue must install the rest transition plan " + - "(identity=$identity, " + - "currentExerciseIndex=${harness.dwsm.coordinator._currentExerciseIndex.value}, " + - "currentSetIndex=${harness.dwsm.coordinator._currentSetIndex.value}, " + - "currentRoutineId=${harness.dwsm.coordinator.currentRoutineId}, " + - "currentRoutineSessionId=${harness.dwsm.coordinator.currentRoutineSessionId}, " + - "loadedRoutineExerciseIds=${harness.dwsm.coordinator._loadedRoutine.value?.exercises?.map { it.id }})", - ) - - // Manual readiness at the entry boundary: Idle + SetReady(1, 0), and no - // unsolicited successor CONFIG before the explicit Start (issue #1394's - // autoplay-off contract must survive the delayed tap). - val state = harness.dwsm.coordinator.workoutState.value - assertIs( - state, - "the delayed manual continue must advance off the held summary", - ) - val ready = assertIs( - harness.dwsm.coordinator.routineFlowState.value, - "the successor entry must be ready for the explicit Start", - ) - assertEquals(1, ready.exerciseIndex) - assertEquals(0, ready.setIndex) - assertEquals( - 1, - harness.fakeBleRepo.programCommands.size, - "no unsolicited successor CONFIG before explicit Start", - ) - } finally { - harness.cleanup() - } - } - - /** - * RED/GREEN regression for #1413's observed failure state. The simulator capture - * proved the tap-time rejection is an identity-coordinate conjunct drift in - * [ActiveSessionEngine.hasCompletionRestAuthority]: the same check PASSED when the - * completion job installed the rest plan at set-completion time (zero install - * warnings in the capture log), and every later tap on the still-displayed summary - * was rejected after a silent drift during the hold (zero connection-log entries - * between teardown-ready and the first rejection; the lease gates all passed — no - * `transition=suppressed` entries). The drift writer is app-side and is named by - * the #1413 instrumentation (`conjunct=...` connection-log line) on the next - * simulator run; delaying the tap alone does NOT drift engine state (the sibling - * test above holds green at +30 s), so this test drives the observed end state - * directly: the completion's rest plan is already installed, the summary is still - * displayed, and one live identity coordinate no longer matches the completion. - * - * Contract under test: the user's explicit continue on the still-displayed summary - * of a completion whose rest plan is already installed must install (return - * `Installed(existing)`) and advance — the plan's source-execution + logical-set-key - * match is the stale-completion guard, not live coordinator coordinates. A - * completion whose plan is NOT installed must still be rejected on drift (see - * `stale completion without an installed plan is still rejected after drift`). - */ - @Test - fun `manual continue proceeds when a live coordinate drifted after the plan was installed (setIndex)`() = - assertManualContinueSurvivesDrift { harness, identity -> - harness.dwsm.coordinator._currentSetIndex.value = identity.setIndex + 1 - } - - @Test - fun `manual continue proceeds when a live coordinate drifted after the plan was installed (exerciseIndex)`() = - assertManualContinueSurvivesDrift { harness, identity -> - harness.dwsm.coordinator._currentExerciseIndex.value = identity.exerciseIndex + 1 - } - - @Test - fun `manual continue proceeds when a live coordinate drifted after the plan was installed (routineSessionId)`() = - assertManualContinueSurvivesDrift { harness, _ -> - harness.dwsm.coordinator.currentRoutineSessionId = "drifted-routine-session" - } - - @Test - fun `manual continue proceeds when a live coordinate drifted after the plan was installed (routineId)`() = - assertManualContinueSurvivesDrift { harness, _ -> - harness.dwsm.coordinator.currentRoutineId = "drifted-routine" - } - - private fun assertManualContinueSurvivesDrift( - drift: (DWSMTestHarness, com.devil.phoenixproject.domain.model.RoutineExecutionIdentity) -> Unit, - ) = runTest { - val harness = DWSMTestHarness(this) - try { - harness.setActiveSummaryCountdownSeconds(0) // Manual; summary holds - val row = TestFixtures.singleArmRow - val routine = routine( - "issue-1413-drifted-continue", - listOf( - entry("e1", 0, row), - entry("e2", 1, row), - ), - ) - routine.exercises.forEach { harness.fakeExerciseRepo.addExercise(it.exercise) } - advanceUntilIdle() - harness.dwsm.loadRoutine(routine) - advanceUntilIdle() - - startFirstSet(harness) - completeActiveSetToHeldSummary(harness) - - // Past the machine teardown window (the capture's taps landed 20 s+ - // after set completion), the plan already installed by the completion - // job under full authority. - advanceTimeBy(30_000) - runCurrent() - assertIs(harness.dwsm.coordinator.workoutState.value) - - val lease = assertNotNull(harness.activeSessionEngine.currentExecutionLeaseOrNull()) - val completion = assertNotNull(harness.activeSessionEngine.claimedCompletion(lease)) - val identity = assertNotNull(completion.routineIdentity) - val installedPlan = assertNotNull( - harness.dwsm.coordinator.restTransitionPlan.value, - "the completion job must have installed the rest plan before the summary showed", - ) - - drift(harness, identity) - - harness.dwsm.proceedFromSummary() - runCurrent() - advanceTimeBy(4_000) - runCurrent() - - val result = harness.activeSessionEngine.lastInitialRestPlanInstallResultForTest - assertIs( - result, - "the still-displayed summary's own completion must install despite the drifted " + - "live coordinate (identity=$identity, drift result observed at tap)", - ) - assertEquals( - installedPlan, - (result as InitialRestPlanInstallResult.Installed).plan, - "the already-installed plan must be returned unchanged", - ) - assertIs( - harness.dwsm.coordinator.workoutState.value, - "the manual continue must advance off the held summary", - ) - assertEquals( - 1, - harness.fakeBleRepo.programCommands.size, - "no unsolicited successor CONFIG before explicit Start", - ) - } finally { - harness.cleanup() - } - } - - /** - * Stale-completion guard preservation (the "narrow fix keeps stale-completion - * guards" requirement): a genuine successor transition — the workout re-enters - * SetReady at the successor coordinates exactly as startNextSetOrExercise does, - * moving the index flows AND the routine-flow - * position atomically — must still reject the superseded completion's rest - * install. Only the silent mirror drift is tolerated; a real position transition - * is not. Lease currency and the claim/plan-source guards are unchanged. - */ - @Test - fun `genuine successor transition still rejects the superseded completion`() = runTest { - val harness = DWSMTestHarness(this) - try { - harness.setActiveSummaryCountdownSeconds(0) // Manual; summary holds - val row = TestFixtures.singleArmRow - val routine = routine( - "issue-1413-guard-preservation", - listOf( - entry("e1", 0, row), - entry("e2", 1, row), - ), - ) - routine.exercises.forEach { harness.fakeExerciseRepo.addExercise(it.exercise) } - advanceUntilIdle() - harness.dwsm.loadRoutine(routine) - advanceUntilIdle() - - startFirstSet(harness) - completeActiveSetToHeldSummary(harness) - advanceTimeBy(30_000) - runCurrent() - - val lease = assertNotNull(harness.activeSessionEngine.currentExecutionLeaseOrNull()) - val completion = assertNotNull(harness.activeSessionEngine.claimedCompletion(lease)) - assertNotNull(completion.routineIdentity) - - // The workout genuinely moved on to the successor entry's set. - harness.dwsm.enterSetReady(1, 0) - advanceUntilIdle() - - harness.activeSessionEngine.installInitialRestPlanForTest(completion, 60) - assertIs( - harness.activeSessionEngine.lastInitialRestPlanInstallResultForTest, - "the superseded completion must not install over the successor's position", - ) - assertEquals( - "live_routine_position", - harness.activeSessionEngine.lastCompletionRestAuthorityFailureForTest, - "the rejection must be attributed to the live-position conjunct", - ) - } finally { - harness.cleanup() - } - } -} From 6e6eaa54388c614e1f87765ae1175ec9c9626f9d Mon Sep 17 00:00:00 2001 From: Devil Date: Tue, 17 Nov 2026 22:16:43 -0500 Subject: [PATCH 3/3] fix(workout): publish Idle on manual summary continue so SetReady can navigate (#1413) With Set summary duration = Manual, the explicit 'Next Set' continue runs the successor through startNextSetOrExerciseFor, which advances the set/exercise indexes and enters SetReady via startWorkoutOrSetReady(autoplay=false) but never publishes WorkoutState.Idle. ActiveWorkoutScreen only navigates to SetReady when workoutState leaves SetSummary/Resting/Active, so the summary card strands and every retry tap dies in hasCompletionRestAuthority (Rest transition install failed reason=AUTHORITY_REJECTED). Publish WorkoutState.Idle in both autoplay-off successor arms (distinct exercise without deferManualStart, and within-entry next set) after enterSetReady and applyPendingRestRackSelection, guarded by hasExpectedAuthority, mirroring the existing deferManualStart arm. The authority checks (hasCompletionRestAuthority / executionGuard) are untouched: superseded completions are still rejected. RED/GREEN: Issue1413ManualSummaryContinueIdleTest (4 tests) fails on main exactly on the live signature (stuck SetSummary, AUTHORITY_REJECTED on the retry tap) and passes with this fix. Issue1394ConsecutiveDuplicateAutoAdvance, Issue656Repro, DropSetRestTransition, DWSMRoutineFlow and Issue1360RestControlOutcome suites stay green; full unit gate green (6047 shared host + 26 androidApp tests). Fixes #1413 --- .../manager/ActiveSessionEngine.kt | 16 ++ .../Issue1413ManualSummaryContinueIdleTest.kt | 265 ++++++++++++++++++ 2 files changed, 281 insertions(+) create mode 100644 shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/manager/Issue1413ManualSummaryContinueIdleTest.kt diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/ActiveSessionEngine.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/ActiveSessionEngine.kt index 3501bb18d..6c935de85 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/ActiveSessionEngine.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/ActiveSessionEngine.kt @@ -13709,6 +13709,14 @@ class ActiveSessionEngine( if (!autoplay) { // Manual progression lets SetReady seed destination defaults first. applyPendingRestRackSelection(nextExIdx to nextSetIdx) + // Issue #1413: mirror the deferManualStart arm below — once SetReady + // is set up and the rack-selection apply ran, publish Idle so + // ActiveWorkoutScreen can navigate off the held Resting/SetSummary UI. + // Without this the summary card strands and every retry tap dies in + // hasCompletionRestAuthority (AUTHORITY_REJECTED). + if (hasExpectedAuthority(lease, "manual_successor_set_ready")) { + coordinator._workoutState.value = WorkoutState.Idle + } } } else if (deferManualStart) { // Issue #572 / #1394: deferred manual configuration transition across @@ -13739,6 +13747,14 @@ class ActiveSessionEngine( if (!autoplay) { // SetReady republishes this entry's defaults even for a later set. applyPendingRestRackSelection(nextExIdx to nextSetIdx) + // Issue #1413: mirror the deferManualStart arm above — once SetReady + // is set up and the rack-selection apply ran, publish Idle so + // ActiveWorkoutScreen can navigate off the held Resting/SetSummary UI. + // Without this the summary card strands and every retry tap dies in + // hasCompletionRestAuthority (AUTHORITY_REJECTED). + if (hasExpectedAuthority(lease, "manual_successor_set_ready")) { + coordinator._workoutState.value = WorkoutState.Idle + } } } coordinator._userAdjustedWeightDuringRest = false diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/manager/Issue1413ManualSummaryContinueIdleTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/manager/Issue1413ManualSummaryContinueIdleTest.kt new file mode 100644 index 000000000..b7b1fa705 --- /dev/null +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/manager/Issue1413ManualSummaryContinueIdleTest.kt @@ -0,0 +1,265 @@ +package com.devil.phoenixproject.presentation.manager + +import com.devil.phoenixproject.data.repository.ConnectionLogRepository +import com.devil.phoenixproject.domain.model.Exercise +import com.devil.phoenixproject.domain.model.RepCount +import com.devil.phoenixproject.domain.model.Routine +import com.devil.phoenixproject.domain.model.RoutineExercise +import com.devil.phoenixproject.domain.model.RoutineFlowState +import com.devil.phoenixproject.domain.model.SetEndReason +import com.devil.phoenixproject.domain.model.WorkoutState +import com.devil.phoenixproject.testutil.DWSMTestHarness +import com.devil.phoenixproject.testutil.TestFixtures +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest + +/** + * Issue #1413 regression contract. + * + * Live report: with `Profile -> Set summary duration = Manual`, the Set Summary + * holds after a completed set (correct), but every tap on its visible + * "Next Set" button is rejected app-side with + * `WORKOUT_PERSISTENCE ... Rest transition install failed reason=AUTHORITY_REJECTED` + * and the screen stays frozen (51 taps on the iPad simulator / Phantom provider: + * 1 silent successful tap + 50 rejections). + * + * Root cause: the explicit continue installs the rest transition and runs the + * successor through `startNextSetOrExerciseFor`, which advances + * `_currentExerciseIndex`/`_currentSetIndex` and then enters SetReady via + * `startWorkoutOrSetReady(autoplay=false)` WITHOUT publishing `WorkoutState.Idle`. + * `ActiveWorkoutScreen` only navigates to SetReady when `workoutState` leaves + * SetSummary/Resting/Active, so the summary card stays visible; every retry tap + * re-enters the rest-plan install with the frozen completion identity and dies in + * `hasCompletionRestAuthority` (`_currentSetIndex` no longer matches the claimed + * identity), logging `reason=AUTHORITY_REJECTED` forever. The sibling + * `deferManualStart` arm already publishes Idle (Issue #572 / #1394 comment); + * these tests pin the same publication on the two autoplay-off successor arms + * (distinct exercise without deferManualStart, and within-entry next set). + * + * The tests drive the REAL production tap handler + * (`DefaultWorkoutSessionManager.proceedFromSummary`) through + * `handleSetCompletion -> held SetSummary -> proceedFromSummary()` with fake BLE. + */ +class Issue1413ManualSummaryContinueIdleTest { + + private fun entry( + id: String, + order: Int, + exercise: Exercise, + setReps: List = listOf(10), + ): RoutineExercise = RoutineExercise( + id = id, + // Force a cable accessory: non-cable fixtures classify as bodyweight and + // route startWorkout to BodyweightRepEntry, which is not the reported path. + exercise = exercise.copy(equipment = "CABLE"), + orderIndex = order, + setReps = setReps, + weightPerCableKg = 25f, + setRestSeconds = listOf(2), + ) + + private fun routine(id: String, exercises: List): Routine = + Routine(id = id, name = id, exercises = exercises) + + private suspend fun TestScope.startFirstSet(harness: DWSMTestHarness) { + harness.fakeBleRepo.simulateConnect("Vee_Test") + advanceUntilIdle() + harness.dwsm.enterSetReady(0, 0) + advanceUntilIdle() + harness.dwsm.startWorkout(skipCountdown = true) + advanceUntilIdle() + assertIs(harness.dwsm.coordinator.workoutState.value) + } + + private suspend fun TestScope.completeActiveSetToHeldSummary(harness: DWSMTestHarness) { + harness.dwsm.coordinator._repCount.value = RepCount( + warmupReps = 0, + workingReps = 10, + totalReps = 10, + isWarmupComplete = true, + ) + harness.activeSessionEngine.handleSetCompletion( + harness.activeSessionEngine.currentExecutionLeaseForTest(), + SetEndReason.TARGET_REPS_REACHED, + ) + advanceTimeBy(1_000) + runCurrent() + assertIs( + harness.dwsm.coordinator.workoutState.value, + "the completed set must show its held Manual summary", + ) + } + + @Test + fun `manual summary continue inside a multi set entry advances to the next set readiness`() = runTest { + val harness = DWSMTestHarness(this) + try { + harness.setActiveSummaryCountdownSeconds(0) // Manual: summary holds + val routine = routine( + "issue-1413-within-entry", + listOf(entry("re-bench-multiset", 0, TestFixtures.benchPress, setReps = listOf(10, 10))), + ) + routine.exercises.forEach { harness.fakeExerciseRepo.addExercise(it.exercise) } + advanceUntilIdle() + harness.dwsm.loadRoutine(routine) + advanceUntilIdle() + startFirstSet(harness) + completeActiveSetToHeldSummary(harness) + + val programCommandsBefore = harness.fakeBleRepo.programCommands.size + harness.dwsm.proceedFromSummary() + runCurrent() + advanceTimeBy(4_000) + runCurrent() + + assertIs( + harness.dwsm.coordinator.workoutState.value, + "Issue #1413: the manual continue must publish Idle so the SetReady screen can navigate", + ) + val ready = assertIs( + harness.dwsm.coordinator.routineFlowState.value, + "the successor must be staged at the next set readiness", + ) + assertEquals(0, ready.exerciseIndex) + assertEquals(1, ready.setIndex) + assertEquals(1, harness.dwsm.coordinator._currentSetIndex.value) + assertEquals( + programCommandsBefore, + harness.fakeBleRepo.programCommands.size, + "no unsolicited successor CONFIG before explicit Start", + ) + } finally { + harness.cleanup() + } + } + + @Test + fun `manual summary continue across a distinct exercise boundary advances to the next entry readiness`() = runTest { + val harness = DWSMTestHarness(this) + try { + harness.setActiveSummaryCountdownSeconds(0) // Manual: summary holds + val routine = routine( + "issue-1413-distinct-exercise", + listOf( + entry("re-bench-press", 0, TestFixtures.benchPress), + entry("re-bicep-curl", 1, TestFixtures.bicepCurl), + ), + ) + routine.exercises.forEach { harness.fakeExerciseRepo.addExercise(it.exercise) } + advanceUntilIdle() + harness.dwsm.loadRoutine(routine) + advanceUntilIdle() + startFirstSet(harness) + completeActiveSetToHeldSummary(harness) + + val programCommandsBefore = harness.fakeBleRepo.programCommands.size + harness.dwsm.proceedFromSummary() + runCurrent() + advanceTimeBy(4_000) + runCurrent() + + assertIs( + harness.dwsm.coordinator.workoutState.value, + "Issue #1413: the distinct-exercise manual continue must publish Idle " + + "so the SetReady screen can navigate", + ) + val ready = assertIs( + harness.dwsm.coordinator.routineFlowState.value, + "the successor must be staged at the next entry readiness", + ) + assertEquals(1, ready.exerciseIndex) + assertEquals(0, ready.setIndex) + assertEquals(1, harness.dwsm.coordinator._currentExerciseIndex.value) + assertEquals( + programCommandsBefore, + harness.fakeBleRepo.programCommands.size, + "no unsolicited successor CONFIG before explicit Start", + ) + } finally { + harness.cleanup() + } + } + + @Test + fun `manual summary continue never logs rest transition install failures across taps`() = runTest { + val harness = DWSMTestHarness(this) + try { + harness.setActiveSummaryCountdownSeconds(0) // Manual: summary holds + ConnectionLogRepository.instance.clearAll() + val routine = routine( + "issue-1413-no-warning", + listOf(entry("re-bench-multiset", 0, TestFixtures.benchPress, setReps = listOf(10, 10))), + ) + routine.exercises.forEach { harness.fakeExerciseRepo.addExercise(it.exercise) } + advanceUntilIdle() + harness.dwsm.loadRoutine(routine) + advanceUntilIdle() + startFirstSet(harness) + completeActiveSetToHeldSummary(harness) + + // First tap: the explicit continue. + harness.dwsm.proceedFromSummary() + runCurrent() + advanceTimeBy(4_000) + runCurrent() + // A later tap against whatever state remains must be a quiet no-op. + harness.dwsm.proceedFromSummary() + runCurrent() + advanceTimeBy(1_000) + runCurrent() + + val failures = ConnectionLogRepository.instance.logs.value.count { + it.message == "Rest transition install failed" + } + assertEquals( + 0, + failures, + "Issue #1413: no tap around the manual continue may log " + + "Rest transition install failed (AUTHORITY_REJECTED)", + ) + } finally { + harness.cleanup() + } + } + + @Test + fun `superseded completion is still rejected after the workout reaches the successor position`() = runTest { + val harness = DWSMTestHarness(this) + try { + harness.setActiveSummaryCountdownSeconds(0) // Manual: summary holds + val routine = routine( + "issue-1413-stale-guard", + listOf(entry("re-bench-multiset", 0, TestFixtures.benchPress, setReps = listOf(10, 10))), + ) + routine.exercises.forEach { harness.fakeExerciseRepo.addExercise(it.exercise) } + advanceUntilIdle() + harness.dwsm.loadRoutine(routine) + advanceUntilIdle() + startFirstSet(harness) + completeActiveSetToHeldSummary(harness) + + val lease = harness.activeSessionEngine.currentExecutionLeaseForTest() + val completion = assertNotNull(harness.activeSessionEngine.claimedCompletion(lease)) + assertNotNull(completion.routineIdentity) + + // The workout genuinely moves to the successor set's readiness position. + harness.dwsm.enterSetReady(0, 1) + advanceUntilIdle() + + harness.activeSessionEngine.installInitialRestPlanForTest(completion, 60) + assertIs( + harness.activeSessionEngine.lastInitialRestPlanInstallResultForTest, + "the superseded completion must not install over the successor position", + ) + } finally { + harness.cleanup() + } + } +}