diff --git a/frontend/src/lib/active-exercise-swap.js b/frontend/src/lib/active-exercise-swap.js
new file mode 100644
index 0000000..114dbb9
--- /dev/null
+++ b/frontend/src/lib/active-exercise-swap.js
@@ -0,0 +1,44 @@
+import { supersetUnits, unitOf } from './history.js'
+
+function hasLoggedSet(entry) {
+ return Array.isArray(entry?.sets) && entry.sets.some(set => set?.done === true)
+}
+
+/**
+ * Swap one exact active-workout occurrence.
+ *
+ * Unlogged occurrences are replaced in place. Logged results are never relabelled: after explicit
+ * confirmation, the replacement is inserted beside the original. A logged group member also
+ * requires an explicit choice to keep the replacement in the group or detach it after the group.
+ */
+export function swapActiveExercise(active, index, replacement, {
+ loggedConfirmed = false,
+ groupDisposition
+} = {}) {
+ if (!active || !Array.isArray(active.entries) || !replacement || index < 0 || index >= active.entries.length) return null
+
+ const current = active.entries[index]
+ if (!hasLoggedSet(current)) {
+ const metadata = Object.fromEntries(Object.entries(current).filter(([key]) => (
+ !['id', 'target', 'plan', 'sets', 'sg'].includes(key)
+ )))
+ active.entries[index] = { ...metadata, ...replacement, ...(current.sg ? { sg: current.sg } : {}) }
+ active.cur = index
+ return { inserted: false, index }
+ }
+
+ if (!loggedConfirmed) return { needsConfirmation: true, grouped: !!current.sg, index }
+ if (current.sg && !['keep', 'detach'].includes(groupDisposition)) {
+ return { needsConfirmation: true, grouped: true, index }
+ }
+
+ const unit = unitOf(supersetUnits(active.entries), index)
+ const keepGroup = current.sg && groupDisposition === 'keep'
+ const insertAt = keepGroup ? index + 1 : (unit.length > 1 ? unit.at(-1) + 1 : index + 1)
+ active.entries.splice(insertAt, 0, {
+ ...replacement,
+ ...(keepGroup ? { sg: current.sg } : {})
+ })
+ active.cur = insertAt
+ return { inserted: true, index: insertAt }
+}
diff --git a/frontend/src/lib/active-exercise-swap.test.js b/frontend/src/lib/active-exercise-swap.test.js
new file mode 100644
index 0000000..c3f7eee
--- /dev/null
+++ b/frontend/src/lib/active-exercise-swap.test.js
@@ -0,0 +1,88 @@
+import { describe, expect, it } from 'vitest'
+import { swapActiveExercise } from './active-exercise-swap.js'
+
+const entry = (id, { sg, done = false, target, sets } = {}) => ({
+ id,
+ ...(sg ? { sg } : {}),
+ target: target || { mode: 'reps', sets: 1, reps: 5, weight: 40 },
+ sets: sets || [{ w: 40, r: 5, done }]
+})
+
+const replacement = () => entry('incline', {
+ target: { mode: 'reps', sets: 2, reps: 8, weight: 32.5, note: 'Keep elbows tucked.', intensifier: { type: 'dropset', count: 1, pct: 20 } },
+ sets: [{ w: 32.5, r: 8, done: false }, { w: 32.5, r: 8, done: false }]
+})
+
+describe('safe active exercise swap', () => {
+ it('replaces only the selected duplicate occurrence and preserves its group and replacement metadata', () => {
+ const first = entry('bench', { sg: 'pair' })
+ const selected = entry('bench', { sg: 'pair' })
+ selected.occurrenceId = 'bench#2'
+ selected.provenance = { routineIndex: 4 }
+ const unrelated = entry('row')
+ const active = { cur: 1, entries: [first, selected, unrelated] }
+ const next = replacement()
+
+ expect(swapActiveExercise(active, 1, next)).toEqual({ inserted: false, index: 1 })
+ expect(active.entries.map(value => value.id)).toEqual(['bench', 'incline', 'row'])
+ expect(active.entries[0]).toBe(first)
+ expect(active.entries[2]).toBe(unrelated)
+ expect(active.entries[1]).toEqual({
+ ...next,
+ occurrenceId: 'bench#2',
+ provenance: { routineIndex: 4 },
+ sg: 'pair'
+ })
+ expect(active.cur).toBe(1)
+ })
+
+ it('fails closed before a logged standalone occurrence is explicitly confirmed', () => {
+ const logged = entry('bench', { sets: [{ w: 42.5, r: 7, done: true, rir: 1 }] })
+ const active = { cur: 0, entries: [logged, entry('row')] }
+
+ expect(swapActiveExercise(active, 0, replacement())).toEqual({ needsConfirmation: true, grouped: false, index: 0 })
+ expect(active.entries).toEqual([logged, active.entries[1]])
+ expect(active.cur).toBe(0)
+ })
+
+ it('preserves a confirmed logged occurrence and inserts the replacement after it', () => {
+ const logged = entry('bench', { sets: [{ w: 42.5, r: 7, done: true, rir: 1 }] })
+ const unrelated = entry('row')
+ const active = { cur: 0, entries: [logged, unrelated] }
+
+ expect(swapActiveExercise(active, 0, replacement(), { loggedConfirmed: true })).toEqual({ inserted: true, index: 1 })
+ expect(active.entries[0]).toBe(logged)
+ expect(active.entries[0].sets[0]).toEqual({ w: 42.5, r: 7, done: true, rir: 1 })
+ expect(active.entries[1].id).toBe('incline')
+ expect(active.entries[2]).toBe(unrelated)
+ expect(active.cur).toBe(1)
+ })
+
+ it('requires an explicit grouped disposition before changing a logged group member', () => {
+ const active = { cur: 0, entries: [entry('bench', { sg: 'pair', done: true }), entry('row', { sg: 'pair' }), entry('curl')] }
+ const before = [...active.entries]
+
+ expect(swapActiveExercise(active, 0, replacement(), { loggedConfirmed: true }))
+ .toEqual({ needsConfirmation: true, grouped: true, index: 0 })
+ expect(active.entries).toEqual(before)
+ })
+
+ it.each([
+ ['keep', ['bench', 'incline', 'row', 'curl'], ['pair', 'pair', 'pair', undefined], 1],
+ ['detach', ['bench', 'row', 'incline', 'curl'], ['pair', 'pair', undefined, undefined], 2]
+ ])('%s confirmation preserves logged group data and unrelated entries', (groupDisposition, ids, groups, cursor) => {
+ const logged = entry('bench', { sg: 'pair', sets: [{ w: 45, r: 6, done: true }] })
+ const partner = entry('row', { sg: 'pair' })
+ const unrelated = entry('curl')
+ const active = { cur: 0, entries: [logged, partner, unrelated] }
+
+ expect(swapActiveExercise(active, 0, replacement(), { loggedConfirmed: true, groupDisposition }))
+ .toEqual({ inserted: true, index: cursor })
+ expect(active.entries.map(value => value.id)).toEqual(ids)
+ expect(active.entries.map(value => value.sg)).toEqual(groups)
+ expect(active.entries[0]).toBe(logged)
+ expect(active.entries.includes(partner)).toBe(true)
+ expect(active.entries.at(-1)).toBe(unrelated)
+ expect(active.cur).toBe(cursor)
+ })
+})
diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js
index f099cd4..c3d967e 100644
--- a/frontend/src/locales/de.js
+++ b/frontend/src/locales/de.js
@@ -97,6 +97,12 @@ export default {
'Weight ({0})': 'Gewicht ({0})',
'Add to routine': 'Zur Routine hinzufügen',
'Remove exercise': 'Übung entfernen',
+ 'Swap exercise': 'Übung wechseln',
+ 'Swap exercise?': 'Übung tauschen?',
+ 'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'Aufgezeichnete Sätze bleiben bei der ursprünglichen Übung. Wähle, wo die Ersatzübung hingehört.',
+ 'Keep replacement in this group': 'Ersatzübung in dieser Gruppe behalten',
+ 'Insert after this group': 'Nach dieser Gruppe einfügen',
+ 'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'Aufgezeichnete Sätze bleiben bei der ursprünglichen Übung. Die Ersatzübung wird danach eingefügt.',
'Remove {0}?': '{0} entfernen?',
'The sets you logged for this exercise in this session will be lost.': 'Die in dieser Einheit für diese Übung protokollierten Sätze gehen verloren.',
'This removes the exercise from your current session.': 'Dadurch wird die Übung aus deiner aktuellen Einheit entfernt.',
diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js
index 9fe5f2f..b9759ef 100644
--- a/frontend/src/locales/es.js
+++ b/frontend/src/locales/es.js
@@ -93,6 +93,12 @@ export default {
'Weight ({0})': 'Peso ({0})',
'Add to routine': 'Añadir a la rutina',
'Remove exercise': 'Quitar ejercicio',
+ 'Swap exercise': 'Cambiar ejercicio',
+ 'Swap exercise?': '¿Cambiar ejercicio?',
+ 'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'Las series registradas permanecen con el ejercicio original. Elige dónde colocar el reemplazo.',
+ 'Keep replacement in this group': 'Mantener el reemplazo en este grupo',
+ 'Insert after this group': 'Insertar después de este grupo',
+ 'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'Las series registradas permanecen con el ejercicio original. El reemplazo se insertará después.',
'Remove {0}?': '¿Quitar {0}?',
'The sets you logged for this exercise in this session will be lost.': 'Se perderán las series que registraste para este ejercicio en esta sesión.',
'This removes the exercise from your current session.': 'Esto quita el ejercicio de tu sesión actual.',
diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js
index 13829ee..b83d465 100644
--- a/frontend/src/locales/fr.js
+++ b/frontend/src/locales/fr.js
@@ -93,6 +93,12 @@ export default {
'Weight ({0})': 'Poids ({0})',
'Add to routine': 'Ajouter à la routine',
'Remove exercise': "Retirer l'exercice",
+ 'Swap exercise': 'Remplacer l’exercice',
+ 'Swap exercise?': 'Remplacer l’exercice ?',
+ 'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'Les séries enregistrées restent avec l’exercice d’origine. Choisis où placer le remplacement.',
+ 'Keep replacement in this group': 'Garder le remplacement dans ce groupe',
+ 'Insert after this group': 'Insérer après ce groupe',
+ 'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'Les séries enregistrées restent avec l’exercice d’origine. Le remplacement sera inséré après.',
'Remove {0}?': 'Retirer {0} ?',
'The sets you logged for this exercise in this session will be lost.': 'Les séries enregistrées pour cet exercice pendant cette séance seront perdues.',
'This removes the exercise from your current session.': 'Cela retire l’exercice de ta séance actuelle.',
diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js
index 2e9b169..882082f 100644
--- a/frontend/src/locales/hi.js
+++ b/frontend/src/locales/hi.js
@@ -93,6 +93,12 @@ export default {
'Weight ({0})': 'वज़न ({0})',
'Add to routine': 'रूटीन में जोड़ें',
'Remove exercise': 'व्यायाम हटाएँ',
+ 'Swap exercise': 'व्यायाम बदलें',
+ 'Swap exercise?': 'एक्सरसाइज़ बदलें?',
+ 'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'रिकॉर्ड किए गए सेट मूल एक्सरसाइज़ के साथ रहेंगे। बदलने वाली एक्सरसाइज़ की जगह चुनें।',
+ 'Keep replacement in this group': 'बदलने वाली एक्सरसाइज़ इसी समूह में रखें',
+ 'Insert after this group': 'इस समूह के बाद जोड़ें',
+ 'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'रिकॉर्ड किए गए सेट मूल एक्सरसाइज़ के साथ रहेंगे। बदलने वाली एक्सरसाइज़ बाद में जोड़ी जाएगी।',
'Remove {0}?': '{0} हटाएँ?',
'The sets you logged for this exercise in this session will be lost.': 'इस सत्र में इस व्यायाम के लिए लॉग किए गए सेट मिट जाएँगे।',
'This removes the exercise from your current session.': 'यह व्यायाम आपके मौजूदा सत्र से हट जाएगा।',
diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js
index 4427b65..98c6264 100644
--- a/frontend/src/locales/it.js
+++ b/frontend/src/locales/it.js
@@ -93,6 +93,12 @@ export default {
'Weight ({0})': 'Peso ({0})',
'Add to routine': 'Aggiungi alla routine',
'Remove exercise': 'Rimuovi esercizio',
+ 'Swap exercise': 'Sostituisci esercizio',
+ 'Swap exercise?': 'Sostituire l’esercizio?',
+ 'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'Le serie registrate restano con l’esercizio originale. Scegli dove inserire il sostituto.',
+ 'Keep replacement in this group': 'Mantieni il sostituto in questo gruppo',
+ 'Insert after this group': 'Inserisci dopo questo gruppo',
+ 'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'Le serie registrate restano con l’esercizio originale. Il sostituto verrà inserito dopo.',
'Remove {0}?': 'Rimuovere {0}?',
'The sets you logged for this exercise in this session will be lost.': 'Le serie registrate per questo esercizio in questa sessione andranno perse.',
'This removes the exercise from your current session.': 'Questo rimuove l’esercizio dalla sessione corrente.',
diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js
index a679ef8..31daee0 100644
--- a/frontend/src/locales/ko.js
+++ b/frontend/src/locales/ko.js
@@ -93,6 +93,12 @@ export default {
'Weight ({0})': '무게 ({0})',
'Add to routine': '루틴에 추가',
'Remove exercise': '운동 제거',
+ 'Swap exercise': '운동 바꾸기',
+ 'Swap exercise?': '운동을 바꿀까요?',
+ 'Logged sets stay with the original exercise. Choose where the replacement belongs.': '기록한 세트는 원래 운동에 남습니다. 대체 운동을 넣을 위치를 선택하세요.',
+ 'Keep replacement in this group': '대체 운동을 이 그룹에 유지',
+ 'Insert after this group': '이 그룹 뒤에 삽입',
+ 'Logged sets stay with the original exercise. The replacement will be inserted afterward.': '기록한 세트는 원래 운동에 남습니다. 대체 운동은 뒤에 삽입됩니다.',
'Remove {0}?': '{0}을(를) 제거할까요?',
'The sets you logged for this exercise in this session will be lost.': '이 세션에서 이 운동에 기록한 세트가 사라집니다.',
'This removes the exercise from your current session.': '현재 세션에서 이 운동을 제거합니다.',
diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js
index 4a9dae1..a078303 100644
--- a/frontend/src/locales/pl.js
+++ b/frontend/src/locales/pl.js
@@ -93,6 +93,12 @@ export default {
'Weight ({0})': 'Ciężar ({0})',
'Add to routine': 'Dodaj do planu',
'Remove exercise': 'Usuń ćwiczenie',
+ 'Swap exercise': 'Zamień ćwiczenie',
+ 'Swap exercise?': 'Zamienić ćwiczenie?',
+ 'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'Zapisane serie pozostają przy oryginalnym ćwiczeniu. Wybierz miejsce dla zamiennika.',
+ 'Keep replacement in this group': 'Zachowaj zamiennik w tej grupie',
+ 'Insert after this group': 'Wstaw za tą grupą',
+ 'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'Zapisane serie pozostają przy oryginalnym ćwiczeniu. Zamiennik zostanie wstawiony za nim.',
'Remove {0}?': 'Usunąć {0}?',
'The sets you logged for this exercise in this session will be lost.': 'Serie zapisane dla tego ćwiczenia w tej sesji zostaną utracone.',
'This removes the exercise from your current session.': 'Spowoduje to usunięcie ćwiczenia z bieżącej sesji.',
diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js
index 7cf9b90..af40057 100644
--- a/frontend/src/locales/pt-BR.js
+++ b/frontend/src/locales/pt-BR.js
@@ -28,6 +28,12 @@ export const PT_BR_OVERRIDES = {
'Search {0} exercises…': 'Buscar entre {0} exercícios…',
'Nothing chosen yet — add exercises and they’ll show up here.': 'Nenhum exercício escolhido — adicione exercícios e eles aparecerão aqui.',
'The sets you logged for this exercise in this session will be lost.': 'As séries registradas para este exercício nesta sessão serão perdidas.',
+ 'Swap exercise': 'Trocar exercício',
+ 'Swap exercise?': 'Trocar exercício?',
+ 'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'As séries registradas ficam com o exercício original. Escolha onde colocar o substituto.',
+ 'Keep replacement in this group': 'Manter o substituto neste grupo',
+ 'Insert after this group': 'Inserir depois deste grupo',
+ 'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'As séries registradas ficam com o exercício original. O substituto será inserido depois.',
'This removes the exercise from your current session.': 'Isso remove o exercício da sua sessão atual.',
'Which exercise in this superset do you want to remove?': 'Qual exercício deste superset você quer remover?',
'Pick an icon': 'Escolha um ícone',
diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js
index 7ccddec..9b77e75 100644
--- a/frontend/src/locales/pt.js
+++ b/frontend/src/locales/pt.js
@@ -93,6 +93,12 @@ export default {
'Weight ({0})': 'Peso ({0})',
'Add to routine': 'Adicionar à rotina',
'Remove exercise': 'Remover exercício',
+ 'Swap exercise': 'Trocar exercício',
+ 'Swap exercise?': 'Trocar exercício?',
+ 'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'As séries registadas ficam com o exercício original. Escolhe onde colocar o substituto.',
+ 'Keep replacement in this group': 'Manter o substituto neste grupo',
+ 'Insert after this group': 'Inserir depois deste grupo',
+ 'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'As séries registadas ficam com o exercício original. O substituto será inserido depois.',
'Remove {0}?': 'Remover {0}?',
'The sets you logged for this exercise in this session will be lost.': 'As séries registadas para este exercício nesta sessão serão perdidas.',
'This removes the exercise from your current session.': 'Isto remove o exercício da tua sessão atual.',
diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js
index c7e74c7..fb1c853 100644
--- a/frontend/src/locales/ru.js
+++ b/frontend/src/locales/ru.js
@@ -93,6 +93,12 @@ export default {
'Weight ({0})': 'Вес ({0})',
'Add to routine': 'Добавить в программу',
'Remove exercise': 'Убрать упражнение',
+ 'Swap exercise': 'Заменить упражнение',
+ 'Swap exercise?': 'Заменить упражнение?',
+ 'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'Записанные подходы останутся у исходного упражнения. Выберите место для замены.',
+ 'Keep replacement in this group': 'Оставить замену в этой группе',
+ 'Insert after this group': 'Вставить после этой группы',
+ 'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'Записанные подходы останутся у исходного упражнения. Замена будет вставлена после него.',
'Remove {0}?': 'Удалить {0}?',
'The sets you logged for this exercise in this session will be lost.': 'Подходы, записанные для этого упражнения в этой сессии, будут потеряны.',
'This removes the exercise from your current session.': 'Упражнение будет удалено из текущей сессии.',
diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js
index ea9b6ff..e200921 100644
--- a/frontend/src/locales/tr.js
+++ b/frontend/src/locales/tr.js
@@ -93,6 +93,12 @@ export default {
'Weight ({0})': 'Ağırlık ({0})',
'Add to routine': 'Rutine ekle',
'Remove exercise': 'Egzersizi kaldır',
+ 'Swap exercise': 'Egzersizi değiştir',
+ 'Swap exercise?': 'Egzersiz değiştirilsin mi?',
+ 'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'Kaydedilen setler özgün egzersizde kalır. Yeni egzersizin nereye geleceğini seç.',
+ 'Keep replacement in this group': 'Yeni egzersizi bu grupta tut',
+ 'Insert after this group': 'Bu gruptan sonra ekle',
+ 'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'Kaydedilen setler özgün egzersizde kalır. Yeni egzersiz sonrasına eklenir.',
'Remove {0}?': '{0} kaldırılsın mı?',
'The sets you logged for this exercise in this session will be lost.': 'Bu seansta bu egzersiz için kaydettiğin setler kaybolacak.',
'This removes the exercise from your current session.': 'Bu işlem egzersizi mevcut seansından kaldırır.',
diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js
index ac0cc54..a772a5a 100644
--- a/frontend/src/locales/zh.js
+++ b/frontend/src/locales/zh.js
@@ -93,6 +93,12 @@ export default {
'Weight ({0})': '重量({0})',
'Add to routine': '加入训练日',
'Remove exercise': '移除动作',
+ 'Swap exercise': '更换动作',
+ 'Swap exercise?': '要更换动作吗?',
+ 'Logged sets stay with the original exercise. Choose where the replacement belongs.': '已记录的组数会保留在原动作上。请选择替换动作的位置。',
+ 'Keep replacement in this group': '将替换动作保留在此组',
+ 'Insert after this group': '插入到此组之后',
+ 'Logged sets stay with the original exercise. The replacement will be inserted afterward.': '已记录的组数会保留在原动作上。替换动作将插入其后。',
'Remove {0}?': '移除 {0}?',
'The sets you logged for this exercise in this session will be lost.': '本次训练中为该动作记录的组数将丢失。',
'This removes the exercise from your current session.': '这会从当前训练中移除该动作。',
diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx
index 7ce77be..00509b5 100644
--- a/frontend/src/sheets.jsx
+++ b/frontend/src/sheets.jsx
@@ -25,6 +25,7 @@ import { MOBILE, shareExport } from './lib/mobile.js'
import { buildCompletedWorkout } from './lib/finish-workout.js'
import { isWarmupRow } from './lib/workout-model.js'
import { nextUnfinishedUnit } from './lib/supersetFlow.js'
+import { swapActiveExercise } from './lib/active-exercise-swap.js'
const S = () => useStore.getState().S
const update = (...a) => useStore.getState().update(...a)
@@ -709,6 +710,60 @@ function ExercisePicker({ onPick, close }) {
}
export const exercisePicker = onPick => ui().openSheet(close =>