Skip to content

armgit / lyftr

Public Imported from GitHub
0

Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.

28.9 KB
Raw Blame
import { test, expect } from './fixtures'
import { API_BASE as API } from './config'
import { cleanupSeed } from './seedHelpers'
const E2E_WORKOUT_NAME = 'Test Workout E2E'
const SEED_WORKOUT_NAME = 'Seeded Test Workout'
const SEED_SEARCH_WORKOUT_NAME = 'ZZZ E2E SearchTarget Workout'
const PROG_PROGRESSION_NAME = 'E2E AutoProgression Routine'
const LAYOUT_KEY = 'lyftr_workout_layout'
const SESSION_KEY = 'lyftr_active_session'

let workoutId: number
let searchWorkoutId: number
let authToken: string

test.describe('Workouts', () => {
  test.beforeAll(async ({ request, workerAuth }) => {
    authToken = workerAuth.token

    // Idempotent seed: clear our own seed names first so the list stays
    // deterministic regardless of how many times beforeAll runs.
    await cleanupSeed(request, authToken, `${API}/workouts?limit=100`, `${API}/workouts`,
      w => w.name === SEED_WORKOUT_NAME || w.name === SEED_SEARCH_WORKOUT_NAME)

    const w = await request.post(`${API}/workouts`, {
      headers: { Authorization: `Bearer ${authToken}` },
      data: {
        name: SEED_WORKOUT_NAME,
        duration: 2700,
        started_at: new Date().toISOString(),
        exercises: []
      }
    })
    const wb = await w.json()
    workoutId = wb.data.id

    const sw = await request.post(`${API}/workouts`, {
      headers: { Authorization: `Bearer ${authToken}` },
      data: {
        name: SEED_SEARCH_WORKOUT_NAME,
        duration: 1800,
        started_at: new Date().toISOString(),
        exercises: []
      }
    })
    const swb = await sw.json()
    searchWorkoutId = swb.data.id
  })

  test.afterAll(async ({ request }) => {
    const headers = { Authorization: `Bearer ${authToken}` }

    // Delete seeded workouts
    if (workoutId) {
      await request.delete(`${API}/workouts/${workoutId}`, { headers })
    }
    if (searchWorkoutId) {
      await request.delete(`${API}/workouts/${searchWorkoutId}`, { headers })
    }

    // Delete any UI-created E2E workouts (serial — SQLite single-writer
    // drops bulk Promise.all requests under load).
    const list = await request.get(`${API}/workouts?limit=100`, { headers })
    const lb = await list.json()
    const toDelete = (lb.data ?? []).filter((w: any) => w.name === E2E_WORKOUT_NAME)
    for (const w of toDelete) {
      await request.delete(`${API}/workouts/${w.id}`, { headers })
    }
  })

  test.beforeEach(async ({ page }) => {
    await page.goto('/workouts')
  })

  test('page loads and shows workouts or empty state', async ({ page }) => {
    await expect(page.getByRole('heading', { name: /workouts/i })).toBeVisible()
    const hasWorkouts = await page.locator('.card').count() > 0
    const hasEmpty = await page.getByText(/no workouts|start your first/i).isVisible().catch(() => false)
    expect(hasWorkouts || hasEmpty).toBe(true)
  })

  test('create workout via add page', async ({ page }) => {
    await page.goto('/workouts/new')
    await expect(page.getByRole('heading', { name: /log workout/i })).toBeVisible()

    await page.getByPlaceholder(/leg day|push day/i).fill(E2E_WORKOUT_NAME)
    const durationInput = page.locator('input[type="number"]').first()
    await durationInput.fill('45')

    // Add exercise
    await page.getByRole('button', { name: /add exercise/i }).click()
    await expect(page.getByPlaceholder(/search exercises/i)).toBeVisible()
    await page.getByPlaceholder(/search exercises/i).fill('bench press')
    await page.getByText(/bench press/i).first().click()

    // Fill in set
    await page.locator('input[placeholder="10"]').first().fill('8')
    await page.locator('input[placeholder="225"]').first().fill('135')

    await page.getByRole('button', { name: /save workout/i }).click()
    await page.waitForURL('/workouts')
    await expect(page.getByText(E2E_WORKOUT_NAME).first()).toBeVisible()
  })

  test('workout list shows volume in correct unit', async ({ page }) => {
    const volumeText = page.locator('text=/\\d+ (lb|kg)/')
    if (await volumeText.count() > 0) {
      await expect(volumeText.first()).toBeVisible()
    }
  })

  test('delete workout shows confirm dialog', async ({ page }) => {
    await expect(page.getByText(SEED_WORKOUT_NAME)).toBeVisible({ timeout: 5000 })
    // On mobile the delete button is behind a kebab (⋯) menu — open it first if present
    const optionsBtn = page.getByRole('button', { name: /options/i }).first()
    if (await optionsBtn.isVisible()) {
      await optionsBtn.click()
      await page.getByRole('button', { name: /delete workout/i }).first().click()
    } else {
      const deleteButtons = page.getByRole('button', { name: /delete/i })
      await expect(deleteButtons.first()).toBeVisible()
      await deleteButtons.first().click()
    }
    await expect(page.getByText(/this cannot be undone/i)).toBeVisible({ timeout: 5000 })
    await page.getByRole('button', { name: /cancel/i }).click()
    await expect(page.getByText(/this cannot be undone/i)).not.toBeVisible()
  })

  test('workout detail page loads', async ({ page }) => {
    await page.goto(`/workouts/${workoutId}`)
    await expect(page.getByRole('heading')).toBeVisible()
    await expect(page.locator('.card').first()).toBeVisible()
  })

  test('search filters workout list', async ({ page }) => {
    await expect(page.getByText(SEED_SEARCH_WORKOUT_NAME).first()).toBeVisible({ timeout: 5000 })
    const searchInput = page.getByPlaceholder(/search workouts/i)
    await searchInput.fill('SearchTarget')
    await expect(page.getByText(SEED_SEARCH_WORKOUT_NAME).first()).toBeVisible()
    // toHaveCount(0) auto-retries until the filtered-out item is fully gone;
    // not.toBeVisible() would strict-mode-throw on the transient 2-node re-render.
    await expect(page.getByText(SEED_WORKOUT_NAME)).toHaveCount(0)
  })

  test('clearing search restores full list', async ({ page }) => {
    const searchInput = page.getByPlaceholder(/search workouts/i)
    await searchInput.fill('SearchTarget')
    await expect(page.getByText(SEED_SEARCH_WORKOUT_NAME).first()).toBeVisible()
    await searchInput.fill('')
    await expect(page.getByText(SEED_WORKOUT_NAME).first()).toBeVisible()
    await expect(page.getByText(SEED_SEARCH_WORKOUT_NAME).first()).toBeVisible()
  })

  test('search input stays focused while typing', async ({ page }) => {
    await expect(page.getByRole('heading', { name: /workouts/i })).toBeVisible()
    const searchInput = page.getByPlaceholder(/search workouts/i)
    await searchInput.click()
    await searchInput.type('S')
    await expect(searchInput).toBeFocused()
  })

  test('weight unit displays consistently', async ({ page }) => {
    await page.goto('/settings')
    const kgButton = page.getByRole('button', { name: 'kg' })
    // Wait for the settings save (PUT /settings) before navigating, so /workouts
    // reads the updated unit — a real signal, not a fixed sleep.
    await Promise.all([
      page.waitForResponse(r => r.url().includes('/api/v1/settings') && r.request().method() === 'PUT'),
      kgButton.click(),
    ])

    await page.goto('/workouts')
    const volumeElements = page.locator('text=/\\d+ kg/')
    const count = await volumeElements.count()
    if (count > 0) {
      await expect(volumeElements.first()).toBeVisible()
    }

    await page.goto('/settings')
    await page.getByRole('button', { name: 'lbs' }).click()
  })

  // Issue #40: finishing a workout that beat a routine's per-set target STAGES a
  // suggestion (target unchanged) + toasts it; approving on the routine applies it.
  test('finishing a workout that beats a routine target stages a suggestion to approve', async ({ page, request }) => {
    const headers = { Authorization: `Bearer ${authToken}` }
    const exId = (await (await request.get(`${API}/exercises?limit=1`, { headers })).json()).data[0].id

    // Routine with one working set targeting 5 × 100.
    const created = await request.post(`${API}/programs`, {
      headers,
      data: {
        name: PROG_PROGRESSION_NAME, notes: '',
        days: [{ order_index: 0, is_rest_day: false, name: '', exercises: [{ exercise_id: exId, notes: '', rest_seconds: 90, sets: [{ set_number: 1, target_reps: 5, target_weight: 100 }] }] }],
      },
    })
    const progId = (await created.json()).data.id
    const psid = (await (await request.get(`${API}/programs/${progId}`, { headers })).json()).data.days[0].exercises[0].sets[0].id

    // Seed a list-mode session where the logged set beat the target (105 > 100).
    const session = {
      program_id: progId,
      name: PROG_PROGRESSION_NAME,
      started_at: new Date(Date.now() - 600000).toISOString(),
      exercises: [{
        exercise_id: exId,
        exercise: { id: exId, name: 'Bench Press', muscle_group: 'Chest', equipment: 'barbell', category: 'strength', secondary_muscles: [], description: '', image_url: null },
        notes: '', rest_seconds: 90,
        sets: [{ set_number: 1, target_reps: 5, target_weight: 100, actual_reps: 5, actual_weight: 105, completed: true, program_set_id: psid }],
      }],
    }
    await page.addInitScript(({ sk, lk, s }: { sk: string; lk: string; s: any }) => {
      localStorage.setItem(sk, JSON.stringify(s))
      localStorage.setItem(lk, 'list')
    }, { sk: SESSION_KEY, lk: LAYOUT_KEY, s: session })

    await page.goto('/workout/active')
    await page.getByRole('button', { name: 'Finish' }).first().click()
    await page.getByRole('button', { name: 'Finish' }).last().click()

    await page.waitForURL('**/workouts')
    // Toast invites a review (PR wording when it's also an all-time best; either is fine).
    await expect(page.getByText(/Tap to review 1 update/)).toBeVisible({ timeout: 5000 })

    // Staged, NOT applied — the routine target is still 100 until approved.
    const staged = await (await request.get(`${API}/programs/${progId}`, { headers })).json()
    expect(staged.data.days[0].exercises[0].sets[0].target_weight).toBe(100)
    expect(staged.data.days[0].exercises[0].sets[0].suggested_weight).toBe(105)

    // Approve on the routine → target becomes 105, suggestion cleared.
    await page.goto(`/programs/${progId}`)
    await expect(page.getByText('New targets from your last workout')).toBeVisible({ timeout: 5000 })
    await page.getByRole('button', { name: /Apply all/ }).click()
    await expect(page.getByText('New targets from your last workout')).toHaveCount(0, { timeout: 5000 })

    const after = await (await request.get(`${API}/programs/${progId}`, { headers })).json()
    expect(after.data.days[0].exercises[0].sets[0].target_weight).toBe(105)
    expect(after.data.days[0].exercises[0].sets[0].suggested_weight ?? null).toBeNull()

    // Cleanup: the workout we just logged + the routine.
    const wl = await (await request.get(`${API}/workouts?limit=20`, { headers })).json()
    for (const w of (wl.data ?? []).filter((x: any) => x.name === PROG_PROGRESSION_NAME)) {
      await request.delete(`${API}/workouts/${w.id}`, { headers })
    }
    await request.delete(`${API}/programs/${progId}`, { headers })
  })
})

// ── Gym Mode (active workout route, alternative layout) ───────────────────────

let gymAuthToken: string
let gymExerciseId: number

// @mobile: Gym Mode is the mobile-first full-screen workout UX — run it on the
// iPhone profile (it also runs on chromium via the full suite).
test.describe('Gym Mode', { tag: '@mobile' }, () => {
  test.beforeAll(async ({ request, workerAuth }) => {
    gymAuthToken = workerAuth.token

    const exRes = await request.get(`${API}/exercises?limit=1`, {
      headers: { Authorization: `Bearer ${gymAuthToken}` }
    })
    gymExerciseId = (await exRes.json()).data[0].id
  })

  function seedGymSession(page: any, name: string, exerciseName: string, sets: any[], extraExercises?: any[]) {
    const exId = gymExerciseId
    const session = {
      name,
      started_at: new Date().toISOString(),
      exercises: [
        {
          exercise_id: exId,
          exercise: { id: exId, name: exerciseName, muscle_group: 'Chest', equipment: 'barbell', category: 'strength', secondary_muscles: [], description: 'Stand with feet shoulder-width apart.', image_url: null },
          notes: '',
          sets,
        },
        ...(extraExercises || []),
      ],
    }
    return page.addInitScript(({ sk, lk, s }: { sk: string; lk: string; s: any }) => {
      localStorage.setItem(sk, JSON.stringify(s))
      localStorage.setItem(lk, 'gym')
    }, { sk: SESSION_KEY, lk: LAYOUT_KEY, s: session })
  }

  test('settings toggle switches layout and persists', async ({ page }) => {
    await page.goto('/settings')
    await expect(page.getByRole('heading', { name: /settings/i })).toBeVisible()

    await page.getByRole('button', { name: /gym mode/i }).click()

    const stored = await page.evaluate((key: string) => localStorage.getItem(key), LAYOUT_KEY)
    expect(stored).toBe('gym')

    await page.reload()
    await expect(page.getByRole('heading', { name: /settings/i })).toBeVisible()
    const storedAfter = await page.evaluate((key: string) => localStorage.getItem(key), LAYOUT_KEY)
    expect(storedAfter).toBe('gym')

    // Switch back to list
    await page.getByRole('button', { name: /^list$/i }).click()
    const storedList = await page.evaluate((key: string) => localStorage.getItem(key), LAYOUT_KEY)
    expect(storedList).toBe('list')
  })

  test('gym mode overlay opens when navigating to active workout', async ({ page }) => {
    await seedGymSession(page, 'E2E Gym Test', 'Bench Press',
      [{ set_number: 1, target_reps: 5, target_weight: 100, actual_reps: 5, actual_weight: 100, completed: false }]
    )

    await page.goto('/workout/active')
    // Overlay header shows "Workout" label above session name
    await expect(page.getByText('Workout').first()).toBeVisible({ timeout: 5000 })
    await expect(page.getByRole('button', { name: /start workout/i })).toBeVisible({ timeout: 3000 })
  })

  // The overlay covers the app but was not announced as covering it. aria-modal tells
  // assistive tech to ignore what is behind; inert is what actually stops Tab walking
  // into it. Both matter: without inert, Finish and Remove set are invisible but still
  // reachable by keyboard, and pressing one of them mid-workout is unrecoverable.
  test('the gym overlay is a modal dialog and the app behind it is inert', async ({ page }) => {
    await seedGymSession(page, 'E2E A11y Test', 'Bench Press',
      [{ set_number: 1, target_reps: 5, target_weight: 100, actual_reps: 5, actual_weight: 100, completed: false }]
    )

    await page.goto('/workout/active')
    const dialog = page.getByRole('dialog', { name: 'Workout' })
    await expect(dialog).toBeVisible({ timeout: 5000 })
    await expect(dialog).toHaveAttribute('aria-modal', 'true')

    // The page behind is marked inert, so nothing inside it can take focus.
    await expect(page.locator('main')).toHaveAttribute('inert', /.*/)

    // Walk the keyboard a while; focus must never land behind the overlay.
    for (let i = 0; i < 25; i++) {
      await page.keyboard.press('Tab')
      const escaped = await page.evaluate(() => {
        const el = document.activeElement
        if (!el || el === document.body) return false
        return el.closest('main') !== null   // main is the inert region
      })
      expect(escaped, `Tab #${i + 1} escaped into the inert page behind the dialog`).toBe(false)
    }
  })

  test('gym mode overview shows exercise list and stats', async ({ page }) => {
    await seedGymSession(page, 'E2E Stats Test', 'Bench Press', [
      { set_number: 1, target_reps: 5, target_weight: 100, actual_reps: 5, actual_weight: 100, completed: false },
      { set_number: 2, target_reps: 5, target_weight: 100, actual_reps: 5, actual_weight: 100, completed: false },
    ])

    await page.goto('/workout/active')
    await expect(page.getByRole('button', { name: /start workout/i })).toBeVisible({ timeout: 5000 })
    await expect(page.getByText('Total Sets')).toBeVisible()
    await expect(page.getByText('Bench Press').first()).toBeVisible()
  })

  test('gym mode cancel button shows confirm dialog', async ({ page }) => {
    await seedGymSession(page, 'E2E Cancel Test', 'Bench Press',
      [{ set_number: 1, target_reps: 5, target_weight: 100, actual_reps: 5, actual_weight: 100, completed: false }]
    )

    await page.goto('/workout/active')
    await expect(page.getByRole('button', { name: /start workout/i })).toBeVisible({ timeout: 5000 })

    // X button (aria-label="Discard workout") in overview header opens the discard confirm
    await page.getByRole('button', { name: 'Discard workout', exact: true }).click()
    await expect(page.getByText('Discard workout?')).toBeVisible({ timeout: 3000 })
    await page.getByRole('button', { name: /keep going/i }).click()
    await expect(page.getByText('Discard workout?')).not.toBeVisible()
  })

  test('gym mode navigates overview → exercise info → sets', async ({ page }) => {
    await seedGymSession(page, 'E2E Navigation Test', 'Squat',
      [{ set_number: 1, target_reps: 5, target_weight: 100, actual_reps: 5, actual_weight: 100, completed: false }]
    )

    await page.goto('/workout/active')
    await expect(page.getByRole('button', { name: /start workout/i })).toBeVisible({ timeout: 5000 })

    // Overview → exercise info
    await page.getByRole('button', { name: /start workout/i }).click()
    await expect(page.getByRole('button', { name: /begin exercise/i })).toBeVisible({ timeout: 3000 })
    await expect(page.getByText('Squat').first()).toBeVisible()

    // Exercise info → sets
    await page.getByRole('button', { name: /begin exercise/i }).click()
    await expect(page.getByText('Reps').first()).toBeVisible({ timeout: 3000 })
    await expect(page.getByRole('button', { name: /complete set/i })).toBeVisible()
  })

  test('gym mode minimize shows active session pill', async ({ page }) => {
    await seedGymSession(page, 'E2E Minimize Test', 'Deadlift',
      [{ set_number: 1, target_reps: 3, target_weight: 150, actual_reps: 3, actual_weight: 150, completed: false }]
    )

    await page.goto('/workout/active')
    await expect(page.getByRole('button', { name: /start workout/i })).toBeVisible({ timeout: 5000 })

    const minimizeBtn = page.getByRole('button', { name: /minimize/i }).first()
    await expect(minimizeBtn).toBeVisible({ timeout: 3000 })
    await minimizeBtn.click()

    // Overlay gone — Start Workout CTA no longer visible
    await expect(page.getByRole('button', { name: /start workout/i })).not.toBeVisible()
    // Session name appears in pill
    await expect(page.getByText('E2E Minimize Test').first()).toBeVisible({ timeout: 3000 })

    // Tap pill → overlay reopens
    await page.getByText('E2E Minimize Test').first().click()
    await expect(page.getByRole('button', { name: /start workout/i })).toBeVisible({ timeout: 3000 })
  })

  test('gym mode set stepper updates reps input', async ({ page }) => {
    await seedGymSession(page, 'E2E Stepper Test', 'OHP',
      [{ set_number: 1, target_reps: 8, target_weight: 60, actual_reps: 0, actual_weight: 0, completed: false }]
    )

    await page.goto('/workout/active')
    await expect(page.getByRole('button', { name: /start workout/i })).toBeVisible({ timeout: 5000 })

    await page.getByRole('button', { name: /start workout/i }).click()
    await page.getByRole('button', { name: /begin exercise/i }).click()
    await expect(page.getByRole('button', { name: /complete set/i })).toBeVisible({ timeout: 3000 })

    // nth(1) — gym overlay renders after main content in DOM, list-mode input is nth(0)
    const repsInput = page.locator('input[inputmode="numeric"]').nth(1)
    await repsInput.fill('7')
    await expect(repsInput).toHaveValue('7', { timeout: 2000 })
  })

  test('gym mode complete set marks it done', async ({ page }) => {
    // Single set — completing it shows "Completed" (no auto-advance to next set)
    await seedGymSession(page, 'E2E Complete Test', 'Row', [
      { set_number: 1, target_reps: 5, target_weight: 80, actual_reps: 5, actual_weight: 80, completed: false },
    ])

    await page.goto('/workout/active')
    await expect(page.getByRole('button', { name: /start workout/i })).toBeVisible({ timeout: 5000 })

    await page.getByRole('button', { name: /start workout/i }).click()
    await page.getByRole('button', { name: /begin exercise/i }).click()
    await expect(page.getByRole('button', { name: /complete set/i })).toBeVisible({ timeout: 3000 })

    await page.getByRole('button', { name: /complete set/i }).click()
    await expect(page.getByRole('button', { name: /completed/i })).toBeVisible({ timeout: 2000 })
  })

  test('gym mode can complete sets while the rest timer is running or paused', async ({ page }) => {
    await seedGymSession(page, 'E2E Complete During Rest', 'Bench Press', [1, 2, 3].map(set_number => ({
      set_number, target_reps: 5, target_weight: 100, actual_reps: 5, actual_weight: 100, completed: false,
    })))
    await page.addInitScript(() => {
      localStorage.setItem('lyftr_rest_enabled', 'true')
      localStorage.setItem('lyftr_rest_seconds', '90')
    })
    await page.goto('/workout/active')
    await page.getByRole('button', { name: /start workout/i }).click()
    await page.getByRole('button', { name: /begin exercise/i }).click()

    const complete = page.getByRole('button', { name: /^complete set$/i })
    await complete.click()
    await expect(page.getByRole('button', { name: 'Pause rest timer' })).toBeVisible()
    await page.getByRole('button', { name: 'Shorten rest by 15 seconds' }).click()
    await page.getByRole('button', { name: 'Shorten rest by 15 seconds' }).click()

    // The next set remains loggable without first skipping the previous rest.
    await complete.click()
    await expect(page.getByText('Set 2 done · set 3 next')).toBeVisible()
    await expect(page.getByText(/^1:(?:2[0-9]|30)$/)).toBeVisible()
    await page.getByRole('button', { name: 'Pause rest timer' }).click()
    await expect(page.getByRole('button', { name: 'Resume rest timer' })).toBeVisible()

    await complete.click()
    await expect(page.getByRole('button', { name: /^completed$/i })).toBeVisible()
    await expect(page.getByRole('button', { name: 'Pause rest timer' })).toBeVisible()
    await expect.poll(() => page.evaluate(key => {
      const session = JSON.parse(localStorage.getItem(key)!)
      return session.exercises[0].sets.filter((set: { completed: boolean }) => set.completed).length
    }, SESSION_KEY)).toBe(3)
  })

  // #193: the rest panel used to float over Begin Exercise / Start Workout. It is docked
  // in-flow below each phase's CTA now, so it must sit under the button, not over it.
  test('gym mode rest panel sits below Begin Exercise and Start Workout', async ({ page }) => {
    await seedGymSession(page, 'E2E Rest Dock Test', 'Bench Press', [
      { set_number: 1, target_reps: 5, target_weight: 100, actual_reps: 5, actual_weight: 100, completed: false },
      { set_number: 2, target_reps: 5, target_weight: 100, actual_reps: 5, actual_weight: 100, completed: false },
    ])

    await page.goto('/workout/active')
    await page.getByRole('button', { name: /start workout/i }).click()
    await page.getByRole('button', { name: /begin exercise/i }).click()
    await page.getByRole('button', { name: /complete set/i }).click()

    const skip = page.getByRole('button', { name: /^skip$/i })
    await expect(skip).toBeVisible({ timeout: 3000 })
    await expect(skip).toHaveCount(1)

    const expectBelow = async (cta: RegExp) => {
      const ctaBox = await page.getByRole('button', { name: cta }).boundingBox()
      const skipBox = await skip.boundingBox()
      expect(ctaBox).not.toBeNull()
      expect(skipBox).not.toBeNull()
      expect(skipBox!.y).toBeGreaterThanOrEqual(ctaBox!.y + ctaBox!.height)
    }

    // Set screen → exercise info
    await page.getByRole('button', { name: /^info$/i }).click()
    await expect(page.getByRole('button', { name: /begin exercise/i })).toBeVisible({ timeout: 3000 })
    await expect(skip).toHaveCount(1)
    await expectBelow(/begin exercise/i)

    // Exercise info → overview
    await page.getByRole('dialog', { name: 'Workout' }).getByRole('button').first().click()
    await expect(page.getByRole('button', { name: /start workout/i })).toBeVisible({ timeout: 3000 })
    await expect(skip).toHaveCount(1)
    await expectBelow(/start workout/i)

    // Both CTAs stay reachable while resting
    await page.getByRole('button', { name: /start workout/i }).click()
    await page.getByRole('button', { name: /begin exercise/i }).click()
    await expect(skip).toBeVisible({ timeout: 3000 })
  })

  test('gym mode restores phase after minimize and reopen', async ({ page }) => {
    const exId = gymExerciseId
    await page.addInitScript(({ sk, lk, id }: { sk: string; lk: string; id: number }) => {
      const session = {
        name: 'E2E Restore Test',
        started_at: new Date().toISOString(),
        exercises: [
          {
            exercise_id: id,
            exercise: { id, name: 'Exercise One', muscle_group: 'Chest', equipment: 'barbell', category: 'strength', secondary_muscles: [], description: '', image_url: null },
            notes: '',
            sets: [{ set_number: 1, target_reps: 5, target_weight: 100, actual_reps: 5, actual_weight: 100, completed: false }],
          },
          {
            exercise_id: id,
            exercise: { id, name: 'Exercise Two', muscle_group: 'Back', equipment: 'barbell', category: 'strength', secondary_muscles: [], description: '', image_url: null },
            notes: '',
            sets: [{ set_number: 1, target_reps: 5, target_weight: 80, actual_reps: 5, actual_weight: 80, completed: false }],
          },
        ],
      }
      localStorage.setItem(sk, JSON.stringify(session))
      localStorage.setItem(lk, 'gym')
    }, { sk: SESSION_KEY, lk: LAYOUT_KEY, id: exId })

    await page.goto('/workout/active')
    await expect(page.getByRole('button', { name: /start workout/i })).toBeVisible({ timeout: 5000 })

    // Navigate to Exercise Two's info page
    await page.getByRole('button', { name: /start workout/i }).click()
    await expect(page.getByRole('button', { name: /begin exercise/i })).toBeVisible({ timeout: 3000 })
    await page.getByRole('button', { name: /begin exercise/i }).click()
    await expect(page.getByRole('button', { name: /next exercise/i })).toBeVisible({ timeout: 3000 })
    await page.getByRole('button', { name: /next exercise/i }).click()
    await expect(page.getByText('Exercise Two').first()).toBeVisible({ timeout: 3000 })

    // Minimize
    await page.getByRole('button', { name: /minimize/i }).first().click()
    await expect(page.getByText('E2E Restore Test').first()).toBeVisible({ timeout: 3000 })

    // Reopen via pill — phase persisted in Zustand store
    await page.getByText('E2E Restore Test').first().click()
    await expect(page.getByText('Exercise Two').first()).toBeVisible({ timeout: 3000 })
  })

  test('gym mode restores phase after page refresh', async ({ page }) => {
    const exId = gymExerciseId
    await page.addInitScript(({ sk, lk, id }: { sk: string; lk: string; id: number }) => {
      const session = {
        name: 'E2E Refresh Test',
        started_at: new Date().toISOString(),
        exercises: [
          {
            exercise_id: id,
            exercise: { id, name: 'Squat', muscle_group: 'Legs', equipment: 'barbell', category: 'strength', secondary_muscles: [], description: '', image_url: null },
            notes: '',
            sets: [{ set_number: 1, target_reps: 5, target_weight: 100, actual_reps: 5, actual_weight: 100, completed: false }],
          },
          {
            exercise_id: id,
            exercise: { id, name: 'Deadlift', muscle_group: 'Back', equipment: 'barbell', category: 'strength', secondary_muscles: [], description: '', image_url: null },
            notes: '',
            sets: [{ set_number: 1, target_reps: 3, target_weight: 140, actual_reps: 3, actual_weight: 140, completed: false }],
          },
        ],
      }
      localStorage.setItem(sk, JSON.stringify(session))
      localStorage.setItem(lk, 'gym')
    }, { sk: SESSION_KEY, lk: LAYOUT_KEY, id: exId })

    await page.goto('/workout/active')
    await expect(page.getByRole('button', { name: /start workout/i })).toBeVisible({ timeout: 5000 })

    // Navigate into sets for exercise 2
    await page.getByRole('button', { name: /start workout/i }).click()
    await page.getByRole('button', { name: /begin exercise/i }).click()
    await page.getByRole('button', { name: /next exercise/i }).click()
    await expect(page.getByText('Deadlift').first()).toBeVisible({ timeout: 3000 })
    await page.getByRole('button', { name: /begin exercise/i }).click()
    await expect(page.getByRole('button', { name: /complete set/i })).toBeVisible({ timeout: 3000 })

    // Minimize then full page refresh
    await page.getByRole('button', { name: /minimize/i }).first().click()
    await page.reload()

    // Tap pill to reopen — should land on sets phase for Deadlift
    await expect(page.getByText('E2E Refresh Test').first()).toBeVisible({ timeout: 5000 })
    await page.getByText('E2E Refresh Test').first().click()
    await expect(page.getByText('Deadlift').first()).toBeVisible({ timeout: 3000 })
    await expect(page.getByRole('button', { name: /complete set/i })).toBeVisible({ timeout: 3000 })
  })
})