Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

feat: save a completed session as an independent routine

Space-Hermesad0e201023a3
diff --git a/frontend/src/lib/pt-br-locale.test.js b/frontend/src/lib/pt-br-locale.test.js
index f692c6095..f205af923 100644
--- a/frontend/src/lib/pt-br-locale.test.js
+++ b/frontend/src/lib/pt-br-locale.test.js
@@ -27,7 +27,7 @@ describe('Brazilian Portuguese locale', () => {
.sort(byCodeUnit)
const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex')
- expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(644)
+ expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(647)
expect(inherited).toHaveLength(647)
// If this fails, review the changed keys and wording before accepting a new hash. From
// frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --list
diff --git a/frontend/src/lib/session-routines.js b/frontend/src/lib/session-routines.js
new file mode 100644
index 000000000..46fa6398b
--- /dev/null
+++ b/frontend/src/lib/session-routines.js
@@ -0,0 +1,106 @@
+import { uid } from './format.js'
+import { modeOf, defaultConfig, isPerSide } from './history.js'
+import { isSideSet, isWarmupRow } from './workout-model.js'
+
+// A saved workout is evidence of what was logged, not a live routine. Copy only its flat
+// exercise setup on this explicit action; finishing a workout never calls this helper.
+const sessionEntries = session => Array.isArray(session?.entries) ? session.entries : []
+
+function groupIds(ex) {
+ const next = ex.map(entry => ({ ...entry }))
+ let i = 0
+ while (i < next.length) {
+ const raw = next[i].sg
+ if (raw == null || raw === '') { delete next[i].sg; i++; continue }
+ const start = i
+ while (i + 1 < next.length && next[i + 1].sg === raw) i++
+ const end = i
+ if (end === start) delete next[start].sg
+ else {
+ const mapped = `sg-${uid()}`
+ for (let j = start; j <= end; j++) next[j].sg = mapped
+ }
+ i++
+ }
+ return next
+}
+
+const scalarGroup = value => {
+ if (typeof value !== 'string' && typeof value !== 'number') return null
+ const text = String(value)
+ return text ? text : null
+}
+
+const finite = value => Number.isFinite(Number(value)) ? Number(value) : null
+const positive = value => {
+ const n = finite(value)
+ return n != null && n > 0 ? n : null
+}
+
+// A flat per-side routine stores the total across both limbs. makeSideSet() then splits that
+// total into two equal planned sides, so an odd/asymmetric logged total is rounded to the nearest
+// representable even total. The copy keeps the target when only one limb was completed: a flat
+// routine cannot encode partial completion or two different side prescriptions.
+function perSideReps(row, target) {
+ if (!isSideSet(row)) return positive(row?.r)
+ const done = ['L', 'R'].filter(key => row.sides[key]?.done === true)
+ if (done.length === 1) return evenTotal(target?.reps) ?? evenTotal(row.sides[done[0]]?.r)
+ if (done.length < 2) return null
+ return evenTotal(done.reduce((total, key) => total + (positive(row.sides[key]?.r) || 0), 0))
+}
+
+function evenTotal(value) {
+ const n = positive(value)
+ return n == null ? null : Math.max(2, 2 * Math.round(n / 2))
+}
+
+function perSideWeight(row) {
+ if (!isSideSet(row)) return finite(row?.w)
+ const done = ['L', 'R'].filter(key => row.sides[key]?.done === true)
+ const weights = done.map(key => finite(row.sides[key]?.w)).filter(value => value != null)
+ return weights.length ? Math.max(...weights) : null
+}
+
+function copiedEntry(entry) {
+ const rows = Array.isArray(entry?.sets) ? entry.sets : []
+ const work = rows.filter(row => !isWarmupRow(row))
+ // A saved entry can retain planned rows after an early finish. Match history.js lastEntryFor:
+ // only a fully completed work row may seed the copied target. A partially checked per-side row
+ // is still retained by buildCompletedWorkout, but its two-limb state cannot fit a flat routine.
+ const row = work.filter(candidate => candidate?.done === true).at(-1) || null
+ const target = entry?.target && typeof entry.target === 'object'
+ ? structuredClone(entry.target)
+ : {}
+ const cfg = { ...defaultConfig(entry?.id), ...target, id: entry?.id, sets: Math.max(1, work.length || 1), warmupSets: rows.filter(isWarmupRow).length }
+ const mode = modeOf(cfg)
+ if (mode === 'time' && row) Object.assign(cfg, { sec: row.sec ?? cfg.sec, weight: row.w ?? cfg.weight ?? 0 })
+ else if (mode === 'cardio' && row) Object.assign(cfg, { min: row.min ?? cfg.min, speed: row.speed ?? cfg.speed })
+ else if (mode === 'reps') {
+ const reps = row && isPerSide(cfg) ? perSideReps(row, cfg) : positive(row?.r)
+ if (reps != null) cfg.reps = reps
+ if (row) {
+ const weight = perSideWeight(row)
+ if (weight != null) cfg.weight = weight
+ }
+ if (isPerSide(cfg) && row == null) cfg.reps = evenTotal(cfg.reps) ?? cfg.reps
+ }
+
+ // buildCompletedWorkout carries setup.sg inside target, while older records may carry it on
+ // the entry. Keep either form, but never copy session-only ownership fields such as rid.
+ const sg = scalarGroup(entry?.sg ?? target.sg)
+ if (sg) cfg.sg = sg
+ else delete cfg.sg
+ return cfg
+}
+
+export function routineFromSession(session, name = session?.name) {
+ const ex = groupIds(sessionEntries(session).filter(entry => entry?.sets?.length).map(copiedEntry))
+ if (!ex.length) throw new Error('This session has no exercises to save.')
+ return { id: uid(), name: String(name || 'Workout').trim() || 'Workout', ex }
+}
+
+export function saveSessionAsRoutine(state, session, name) {
+ const routine = routineFromSession(session, name)
+ state.routines.push(routine)
+ return routine.id
+}
diff --git a/frontend/src/lib/session-routines.test.js b/frontend/src/lib/session-routines.test.js
new file mode 100644
index 000000000..2aa04007b
--- /dev/null
+++ b/frontend/src/lib/session-routines.test.js
@@ -0,0 +1,137 @@
+import { describe, expect, it } from 'vitest'
+import { routineFromSession, saveSessionAsRoutine } from './session-routines.js'
+import { buildCompletedWorkout } from './finish-workout.js'
+import { buildSessionEntries } from './session-start.js'
+import { makeSideSet, setSideField, toggleSide } from './workout-model.js'
+
+const row = (patch = {}) => ({ w: 40, r: 8, done: true, ...patch })
+const entry = (id, target, sets, extra = {}) => ({ id, target, sets, ...extra })
+const completeSides = set => toggleSide(toggleSide(set, 'L'), 'R')
+const rebuild = cfg => buildSessionEntries(
+ { unit: 'kg', workouts: [], exWeights: {}, routines: [] },
+ { id: 'copied-routine', prog: 'off', ex: [cfg] },
+)[0]
+
+describe('routineFromSession', () => {
+ it('copies the saved setup and derives current reps, weight, warm-ups, and per-side state', () => {
+ const session = {
+ name: 'Evening push',
+ entries: [entry('bench', {
+ id: 'stale', mode: 'reps', sets: 9, reps: 6, weight: 35, side: true,
+ bodyweight: true, inc: 2.5, note: 'controlled', sg: 'source-group'
+ }, [
+ row({ phase: 'warmup', w: 20, r: 8 }),
+ row({ w: 40, r: 8 }),
+ row({ w: 45, r: 10 })
+ ])]
+ }
+
+ const routine = routineFromSession(session)
+ expect(routine.name).toBe('Evening push')
+ expect(routine.ex).toEqual([expect.objectContaining({
+ id: 'bench', sets: 2, warmupSets: 1, reps: 10, weight: 45,
+ mode: 'reps', side: true, bodyweight: true, inc: 2.5, note: 'controlled'
+ })])
+ expect(routine.ex[0].id).toBe('bench')
+ expect(routine.ex[0].sg).toBeUndefined() // one item is not a superset
+ })
+
+ it('keeps repeated occurrences and remaps adjacent groups within the new copy', () => {
+ const session = {
+ name: 'Repeated work',
+ entries: [
+ entry('a', { reps: 5, sg: 'target-group' }, [row({ r: 5 })]),
+ entry('a', { reps: 7, sg: 'target-group' }, [row({ r: 7 })]),
+ entry('b', { reps: 9 }, [row({ r: 9 })]),
+ entry('c', { reps: 11, sg: 'target-group' }, [row({ r: 11 })]),
+ entry('d', { reps: 12, sg: 'target-group' }, [row({ r: 12 })]),
+ entry('e', { reps: 13 }, [row({ r: 13 })], { sg: 'entry-group' }),
+ ]
+ }
+
+ const ex = routineFromSession(session).ex
+ expect(ex.map(e => e.id)).toEqual(['a', 'a', 'b', 'c', 'd', 'e'])
+ expect(ex[0].sg).toBeTruthy()
+ expect(ex[0].sg).toBe(ex[1].sg)
+ expect(ex[0].sg).not.toBe('target-group')
+ expect(ex[3].sg).toBeTruthy()
+ expect(ex[3].sg).toBe(ex[4].sg)
+ expect(ex[3].sg).not.toBe(ex[0].sg)
+ expect(ex[5].sg).toBeUndefined()
+ })
+
+ it('uses entry scalar group ids when present and supports timed and cardio targets', () => {
+ const session = {
+ entries: [
+ entry('hold', { mode: 'time', sec: 20, weight: 5, sg: 'target-group' }, [
+ row({ phase: 'warmup', sec: 10, w: 0 }),
+ row({ sec: 35, w: 7 })
+ ], { sg: 'entry-group' }),
+ entry('run', { mode: 'cardio', min: 15, speed: 7, sg: 'target-group' }, [row({ min: 22, speed: 9 })], { sg: 'entry-group' }),
+ ]
+ }
+
+ const [hold, run] = routineFromSession(session).ex
+ expect(hold).toMatchObject({ mode: 'time', sec: 35, weight: 7, sets: 1, warmupSets: 1 })
+ expect(run).toMatchObject({ mode: 'cardio', min: 22, speed: 9, sets: 1, warmupSets: 0 })
+ expect(hold.sg).toBe(run.sg)
+ expect(hold.sg).not.toBe('entry-group')
+ })
+
+ it('round-trips a real bilateral per-side row as a flat total, not 16 per side', () => {
+ const logged = completeSides(makeSideSet({ w: 20, r: 16 })) // 8 + 8, aggregate r is 16
+ const saved = buildCompletedWorkout({
+ id: 'workout-1', d: '2026-09-14', start: 1,
+ entries: [entry('0025', { id: '0025', mode: 'reps', side: true, reps: 16, weight: 20 }, [logged])],
+ })
+
+ expect(saved.entries[0].sets[0]).toMatchObject({ r: 16, done: true })
+ expect(saved.entries[0].sets[0].sides).toMatchObject({ L: { r: 8, done: true }, R: { r: 8, done: true } })
+
+ const cfg = routineFromSession(saved).ex[0]
+ expect(cfg).toMatchObject({ side: true, reps: 16, weight: 20 })
+ const rebuilt = rebuild(cfg)
+ expect(rebuilt.sets[0].sides.L.r).toBe(8)
+ expect(rebuilt.sets[0].sides.R.r).toBe(8)
+ })
+
+ it('uses only fully completed work for values and makes asymmetric sides representable', () => {
+ let asymmetric = setSideField(makeSideSet({ w: 20, r: 16 }), 'R', 'r', 7)
+ asymmetric = setSideField(asymmetric, 'R', 'w', 22.5)
+ asymmetric = completeSides(asymmetric) // logged 8 + 7; a flat routine cannot encode that split
+ const savedAsymmetric = buildCompletedWorkout({
+ id: 'workout-2', entries: [entry('0025', { mode: 'reps', side: true, reps: 16, weight: 20 }, [asymmetric])],
+ })
+ const cfg = routineFromSession(savedAsymmetric).ex[0]
+ expect(cfg).toMatchObject({ reps: 16, weight: 22.5 }) // nearest even total; exact 8/7 and 20/22.5 are not claimed
+ expect(rebuild(cfg).sets[0].sides).toMatchObject({ L: { w: 22.5, r: 8 }, R: { w: 22.5, r: 8 } })
+
+ const complete = completeSides(makeSideSet({ w: 20, r: 16 }))
+ let partial = makeSideSet({ w: 30, r: 12 })
+ partial = toggleSide(partial, 'L') // retained in the saved boundary, but not a completed row
+ const savedPartial = buildCompletedWorkout({
+ id: 'workout-3', entries: [entry('0025', { mode: 'reps', side: true, reps: 16, weight: 20 }, [complete, partial])],
+ })
+ const partialCfg = routineFromSession(savedPartial).ex[0]
+ expect(partialCfg).toMatchObject({ sets: 2, reps: 16, weight: 20 })
+ expect(rebuild(partialCfg).sets.map(set => [set.sides.L.w, set.sides.L.r])).toEqual([[20, 8], [20, 8]])
+ })
+
+ it('rejects a saved session with no exercise setup', () => {
+ expect(() => routineFromSession({ name: 'Empty', entries: [] })).toThrow('This session has no exercises to save.')
+ })
+})
+
+describe('saveSessionAsRoutine', () => {
+ it('adds an independent routine without mutating the saved workout', () => {
+ const session = { id: 'w', name: 'Push', entries: [entry('bench', { reps: 5 }, [row({ r: 5 })])] }
+ const before = structuredClone(session)
+ const state = { routines: [] }
+ const id = saveSessionAsRoutine(state, session)
+
+ expect(id).toBe(state.routines[0].id)
+ expect(state.routines[0].name).toBe('Push')
+ state.routines[0].ex[0].reps = 99
+ expect(session).toEqual(before)
+ })
+})
diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js
index fad9cba71..bfab5029d 100644
--- a/frontend/src/locales/de.js
+++ b/frontend/src/locales/de.js
@@ -1256,4 +1256,7 @@ export default {
'already added': 'schon drin',
'no exercises': 'keine Übungen',
'Pick equipment': 'Gerät wählen',
+ 'Save as routine?': 'Als Routine speichern?',
+ 'Save as routine': 'Als Routine speichern',
+ 'Create an independent routine from these exercise targets. Your workout history is kept.': 'Eine unabhängige Routine aus diesen Trainingszielen erstellen. Dein Trainingsverlauf bleibt erhalten.',
}
diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js
index 68e2144a4..0a34340b1 100644
--- a/frontend/src/locales/es.js
+++ b/frontend/src/locales/es.js
@@ -1236,4 +1236,7 @@ export default {
'already added': 'ya añadido',
'no exercises': 'sin ejercicios',
'Pick equipment': 'Elegir equipamiento',
+ 'Save as routine?': '¿Guardar como rutina?',
+ 'Save as routine': 'Guardar como rutina',
+ 'Create an independent routine from these exercise targets. Your workout history is kept.': 'Crea una rutina independiente a partir de estos objetivos. Tu historial de entrenamientos se conserva.',
}
diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js
index ff4b17cfd..a96adfcca 100644
--- a/frontend/src/locales/fr.js
+++ b/frontend/src/locales/fr.js
@@ -1236,4 +1236,7 @@ export default {
'already added': 'déjà ajouté',
'no exercises': 'aucun exercice',
'Pick equipment': 'Choisir l’équipement',
+ 'Save as routine?': 'Enregistrer comme routine ?',
+ 'Save as routine': 'Enregistrer comme routine',
+ 'Create an independent routine from these exercise targets. Your workout history is kept.': 'Créer une routine indépendante à partir de ces objectifs. Votre historique reste conservé.',
}
diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js
index da466b3f2..30a229c4b 100644
--- a/frontend/src/locales/hi.js
+++ b/frontend/src/locales/hi.js
@@ -1236,4 +1236,7 @@ export default {
'already added': 'पहले से जोड़ा हुआ',
'no exercises': 'कोई व्यायाम नहीं',
'Pick equipment': 'उपकरण चुनें',
+ 'Save as routine?': 'रूटीन के रूप में सहेजें?',
+ 'Save as routine': 'रूटीन के रूप में सहेजें',
+ 'Create an independent routine from these exercise targets. Your workout history is kept.': 'इन व्यायाम लक्ष्यों से एक स्वतंत्र रूटीन बनाएँ। आपका वर्कआउट इतिहास सुरक्षित रहेगा।',
}
diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.js
index f99fa4ff9..946f2d569 100644
--- a/frontend/src/locales/hu.js
+++ b/frontend/src/locales/hu.js
@@ -1239,4 +1239,7 @@ export default {
'already added': 'már hozzáadva',
'no exercises': 'nincs gyakorlat',
'Pick equipment': 'Eszköz kiválasztása',
+ 'Save as routine?': 'Mentés rutinként?',
+ 'Save as routine': 'Mentés rutinként',
+ 'Create an independent routine from these exercise targets. Your workout history is kept.': 'Független rutin létrehozása ezekből a célokból. Az edzéstörténeted megmarad.',
}
diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js
index 3c8c8415f..38fa87da8 100644
--- a/frontend/src/locales/it.js
+++ b/frontend/src/locales/it.js
@@ -1236,4 +1236,7 @@ export default {
'already added': 'già aggiunto',
'no exercises': 'nessun esercizio',
'Pick equipment': 'Scegli l’attrezzatura',
+ 'Save as routine?': 'Salvare come routine?',
+ 'Save as routine': 'Salva come routine',
+ 'Create an independent routine from these exercise targets. Your workout history is kept.': 'Crea una routine indipendente da questi obiettivi. La cronologia degli allenamenti resta invariata.',
}
diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js
index 48ea492ff..2c55d8301 100644
--- a/frontend/src/locales/ko.js
+++ b/frontend/src/locales/ko.js
@@ -1236,4 +1236,7 @@ export default {
'already added': '이미 추가됨',
'no exercises': '운동 없음',
'Pick equipment': '기구 선택',
+ 'Save as routine?': '루틴으로 저장할까요?',
+ 'Save as routine': '루틴으로 저장',
+ 'Create an independent routine from these exercise targets. Your workout history is kept.': '이 운동 목표로 독립 루틴을 만듭니다. 운동 기록은 그대로 유지됩니다.',
}
diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js
index 213baab72..4a450eab1 100644
--- a/frontend/src/locales/pl.js
+++ b/frontend/src/locales/pl.js
@@ -1236,4 +1236,7 @@ export default {
'already added': 'już dodano',
'no exercises': 'brak ćwiczeń',
'Pick equipment': 'Wybierz sprzęt',
+ 'Save as routine?': 'Zapisać jako rutynę?',
+ 'Save as routine': 'Zapisz jako rutynę',
+ 'Create an independent routine from these exercise targets. Your workout history is kept.': 'Utwórz niezależną rutynę z tych celów ćwiczeń. Historia treningów pozostanie bez zmian.',
}
diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js
index 324b0f2ae..a1014d7f4 100644
--- a/frontend/src/locales/pt-BR.js
+++ b/frontend/src/locales/pt-BR.js
@@ -671,6 +671,9 @@ export const PT_BR_OVERRIDES = {
'Download & Install': 'Baixar e instalar',
'Starting download…': 'Iniciando download…',
'Downloading update…': 'Baixando atualização…',
+ 'Save as routine?': 'Salvar como rotina?',
+ 'Save as routine': 'Salvar como rotina',
+ 'Create an independent routine from these exercise targets. Your workout history is kept.': 'Criar uma rotina independente a partir destes objetivos. O histórico de treinos será mantido.',
}
export default { ...pt, ...PT_BR_OVERRIDES }
diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js
index ea44d465c..b6105fde5 100644
--- a/frontend/src/locales/pt.js
+++ b/frontend/src/locales/pt.js
@@ -1236,4 +1236,7 @@ export default {
'already added': 'já adicionado',
'no exercises': 'sem exercícios',
'Pick equipment': 'Escolher equipamento',
+ 'Save as routine?': 'Guardar como rotina?',
+ 'Save as routine': 'Guardar como rotina',
+ 'Create an independent routine from these exercise targets. Your workout history is kept.': 'Criar uma rotina independente a partir destes objetivos. O teu histórico de treinos é mantido.',
}
diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js
index 46ce8efb2..21b2fcf40 100644
--- a/frontend/src/locales/ru.js
+++ b/frontend/src/locales/ru.js
@@ -1236,4 +1236,7 @@ export default {
'already added': 'уже добавлено',
'no exercises': 'нет упражнений',
'Pick equipment': 'Выбрать оборудование',
+ 'Save as routine?': 'Сохранить как тренировку?',
+ 'Save as routine': 'Сохранить как тренировку',
+ 'Create an independent routine from these exercise targets. Your workout history is kept.': 'Создать отдельную тренировку из этих целей. История тренировок сохранится.',
}
diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.js
index f2b372dbd..66ac86fbf 100644
--- a/frontend/src/locales/th.js
+++ b/frontend/src/locales/th.js
@@ -1247,4 +1247,7 @@ export default {
'already added': 'เพิ่มแล้ว',
'no exercises': 'ไม่มีท่าออกกำลังกาย',
'Pick equipment': 'เลือกอุปกรณ์',
+ 'Save as routine?': 'บันทึกเป็นรูทีนไหม',
+ 'Save as routine': 'บันทึกเป็นรูทีน',
+ 'Create an independent routine from these exercise targets. Your workout history is kept.': 'สร้างรูทีนอิสระจากเป้าหมายเหล่านี้ ประวัติการออกกำลังกายของคุณจะยังคงอยู่',
}
diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js
index 95720d15e..e1405d25f 100644
--- a/frontend/src/locales/tr.js
+++ b/frontend/src/locales/tr.js
@@ -1236,4 +1236,7 @@ export default {
'already added': 'zaten ekli',
'no exercises': 'egzersiz yok',
'Pick equipment': 'Ekipman seç',
+ 'Save as routine?': 'Rutin olarak kaydedilsin mi?',
+ 'Save as routine': 'Rutin olarak kaydet',
+ 'Create an independent routine from these exercise targets. Your workout history is kept.': 'Bu egzersiz hedeflerinden bağımsız bir rutin oluştur. Antrenman geçmişin korunur.',
}
diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js
index f45110eec..72cd246d0 100644
--- a/frontend/src/locales/zh.js
+++ b/frontend/src/locales/zh.js
@@ -1236,4 +1236,7 @@ export default {
'already added': '已添加',
'no exercises': '没有动作',
'Pick equipment': '选择器械',
+ 'Save as routine?': '要保存为训练计划吗?',
+ 'Save as routine': '保存为训练计划',
+ 'Create an independent routine from these exercise targets. Your workout history is kept.': '根据这些训练目标创建独立训练计划。你的训练记录会保留。',
}
diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx
index 4c04e4720..32d1458e2 100644
--- a/frontend/src/sheets.jsx
+++ b/frontend/src/sheets.jsx
@@ -30,6 +30,7 @@ import { normalizeRepRange } from './lib/rep-range.js'
import { MOBILE, shareExport, printHtml } from './lib/mobile.js'
import { buildCompletedWorkout } from './lib/finish-workout.js'
import { isWarmupRow, hasCompletedWork } from './lib/workout-model.js'
+import { saveSessionAsRoutine } from './lib/session-routines.js'
import { nextUnfinishedUnit } from './lib/supersetFlow.js'
import { swapActiveExercise } from './lib/active-exercise-swap.js'
import { useSheetKeyboard, useRevealActiveChip, tappable } from './lib/use-sheet-keyboard.js'
@@ -1690,6 +1691,19 @@ function WorkoutDetail({ w, close }) {
placeholder={t('How the session went as a whole.')}
onFocus={onNoteFocus} onChange={e => setNote(e.target.value)} onBlur={saveNote} />
<div style={{ height: 14 }} />
+ <Button icon="plus" onClick={() => confirmSheet({
+ title: t('Save as routine?'),
+ message: t('Create an independent routine from these exercise targets. Your workout history is kept.'),
+ confirmText: t('Save'),
+ onConfirm: () => {
+ let id
+ try { update(s => { id = saveSessionAsRoutine(s, w, w.name) }) }
+ catch (e) { toast(t(e.message)); return }
+ close()
+ nav('/plan/r/' + id)
+ }
+ })}>{t('Save as routine')}</Button>
+ <div style={{ height: 10 }} />
<Button variant="danger" onClick={() => confirmSheet({ title: t('Delete workout?'), message: t('This removes it from your history for good.'), confirmText: t('Delete'), danger: true, onConfirm: () => { update(s => { s.workouts = s.workouts.filter(x => x.id !== w.id) }); close(); toast(t('Workout deleted')) } })}>{t('Delete workout')}</Button>
</>
}
diff --git a/frontend/src/sheets.session-routine.test.jsx b/frontend/src/sheets.session-routine.test.jsx
new file mode 100644
index 000000000..75be314c0
--- /dev/null
+++ b/frontend/src/sheets.session-routine.test.jsx
@@ -0,0 +1,65 @@
+// @vitest-environment happy-dom
+import React, { act } from 'react'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { createRoot } from 'react-dom/client'
+import { useStore } from './store/useStore.js'
+import { useUI } from './store/useUI.js'
+import { workoutDetailSheet } from './sheets.jsx'
+import { setNav } from './lib/nav.js'
+
+const mounted = []
+const workout = () => ({
+ id: 'w-routine', d: '2026-09-10', start: 1, end: 2, name: 'Push', prs: [],
+ entries: [
+ { id: 'bench', target: { mode: 'reps', reps: 5, weight: 40, side: true, sg: 'source' }, sets: [{ phase: 'warmup', w: 20, r: 5 }, { w: 45, r: 8, done: true }] },
+ { id: 'row', target: { mode: 'reps', reps: 8, weight: 30, sg: 'source' }, sets: [{ w: 35, r: 9, done: true }] },
+ ],
+})
+
+function renderTop() {
+ const sheet = useUI.getState().sheets.at(-1)
+ const host = document.createElement('div')
+ document.body.appendChild(host)
+ const root = createRoot(host)
+ mounted.push(root)
+ act(() => root.render(sheet.render(() => useUI.getState().closeSheet(sheet.id))))
+ return host
+}
+
+const button = (host, label) => [...host.querySelectorAll('button')].find(b => b.textContent.trim() === label)
+
+describe('WorkoutDetail — save as routine', () => {
+ let navigated
+
+ beforeEach(() => {
+ globalThis.IS_REACT_ACT_ENVIRONMENT = true
+ navigated = null
+ setNav(to => { navigated = to })
+ useUI.setState({ sheets: [], toastMsg: '' })
+ useStore.setState(s => ({ S: { ...s.S, workouts: [], routines: [], active: null } }))
+ document.body.innerHTML = ''
+ })
+
+ afterEach(() => { act(() => { mounted.splice(0).forEach(root => root.unmount()) }) })
+
+ it('requires an explicit confirmation, then creates a flat routine and keeps history unchanged', () => {
+ const saved = workout()
+ useStore.setState(s => ({ S: { ...s.S, workouts: [saved] } }))
+ const host = (workoutDetailSheet(saved), renderTop())
+ expect(button(host, 'Save as routine')).toBeTruthy()
+
+ act(() => { button(host, 'Save as routine').click() })
+ const confirm = renderTop()
+ expect(confirm.textContent).toContain('Create an independent routine')
+ expect(useStore.getState().S.routines).toHaveLength(0)
+
+ act(() => { button(confirm, 'Save').click() })
+ const routine = useStore.getState().S.routines[0]
+ expect(routine).toMatchObject({ name: 'Push' })
+ expect(routine.ex.map(e => e.id)).toEqual(['bench', 'row'])
+ expect(routine.ex[0].side).toBe(true)
+ expect(routine.ex[0].warmupSets).toBe(1)
+ expect(useStore.getState().S.workouts[0]).toEqual(saved)
+ expect(navigated).toBe('/plan/r/' + routine.id)
+ })
+})