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.

fix(import): a re-import keeps an exercise on the custom id an earlier import gave it

Duarte Santos3afe9d1d790c
diff --git a/frontend/src/lib/import-csv.js b/frontend/src/lib/import-csv.js
index 553cc0937..9d75f396c 100644
--- a/frontend/src/lib/import-csv.js
+++ b/frontend/src/lib/import-csv.js
@@ -459,7 +459,19 @@ export function importId(prefix, text) {
return prefix + (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36)
}
-export function parseWorkoutCSV(text, { unit = 'kg' } = {}) {
+// The custom exercise the user already has for what an import names: the one an earlier import
+// made under the same id, else one with the same name. A name the catalogue did not know when it
+// was first imported became a custom exercise, and the catalogue may know it now; matched afresh,
+// the next import would put its new days on the catalogue id and split the history in two. So an
+// exercise the user already has keeps its id, and only a name that is new is matched.
+const nameKey = n => String(n || '').toLowerCase().replace(/\s+/g, ' ').trim()
+export function priorCustom(customEx, id, name) {
+ const list = Array.isArray(customEx) ? customEx.filter(c => c && c.id) : []
+ return list.find(c => c.id === id) || list.find(c => nameKey(c.n) === nameKey(name)) || null
+}
+
+// `customEx`: the custom exercises already in state (priorCustom above).
+export function parseWorkoutCSV(text, { unit = 'kg', customEx = [] } = {}) {
const rows = parseCSV(text)
if (rows.length < 2) return { error: 'empty' }
const map = mapHeader(rows[0])
@@ -479,6 +491,7 @@ export function parseWorkoutCSV(text, { unit = 'kg' } = {}) {
}
const resolved = new Map() // exercise name -> dataset id | null, resolved once
+ const prior = new Map() // exercise name -> the user's own custom exercise for it
const byDate = new Map()
const created = new Map()
const unmatched = new Set()
@@ -525,9 +538,11 @@ export function parseWorkoutCSV(text, { unit = 'kg' } = {}) {
const key = keyOf(name)
let id = resolved.get(key)
if (id === undefined) {
+ const own = priorCustom(customEx, importId('im', source + '|' + name.toLowerCase()), name)
+ if (own) prior.set(key, own)
// Hevy CSV: prefer the generated English-title map (same table as the API import).
// Localized titles still fall through to the word-bag matcher.
- id = (source === 'Hevy' ? matchHevyTitle(name) : null) || matchExercise(name)
+ id = own ? own.id : (source === 'Hevy' ? matchHevyTitle(name) : null) || matchExercise(name)
resolved.set(key, id)
}
if (id) matched++
@@ -554,7 +569,7 @@ export function parseWorkoutCSV(text, { unit = 'kg' } = {}) {
// catalogue match decides; any other file also needs the name to say what it is, because a
// loose match ("Walking" → walking lunge) would turn a walk into a hold.
const nameBp = bpFromName(name.toLowerCase())
- const exCardio = isCardioEx(id) || created.get(key)?.bp === 'cardio' || nameBp === 'cardio'
+ const exCardio = isCardioEx(id) || (created.get(key) || prior.get(key))?.bp === 'cardio' || nameBp === 'cardio'
const timed = secs > 0 && !km && !reps && !exCardio && (source === 'Strong' || !!nameBp)
const isCardio = !timed && (km > 0 || mins > 0) && !reps
// `u` carries the row's own unit into the conversion pass below and is dropped there —
@@ -763,7 +778,6 @@ export function mergeImport(S, parsed) {
// the way mergeHevyRoutines and mergePlan do; otherwise the Library lists "Grip Trainer" twice,
// each with half the history. Only a name with no match becomes a new exercise.
S.customEx = S.customEx || []
- const nameKey = n => String(n || '').toLowerCase().replace(/\s+/g, ' ').trim()
const exIdMap = {}
parsed.customEx.forEach(c => {
const same = S.customEx.find(x => x.id !== c.id && nameKey(x.n) === nameKey(c.n))
diff --git a/frontend/src/lib/import-hevy.js b/frontend/src/lib/import-hevy.js
index 851aa74c0..e537fd376 100644
--- a/frontend/src/lib/import-hevy.js
+++ b/frontend/src/lib/import-hevy.js
@@ -9,7 +9,7 @@ import { EXIDX } from './exercises.js'
import { uid } from './format.js'
import { isWarmupRow } from './workout-model.js'
import { HEVY_ID_MAP, HEVY_TITLE_MAP } from './hevy-id-map.js'
-import { daysBetween, importId } from './import-csv.js'
+import { daysBetween, importId, priorCustom } from './import-csv.js'
export { HEVY_ID_MAP, HEVY_TITLE_MAP }
export const HEVY_API = 'https://api.hevyapp.com'
@@ -158,24 +158,30 @@ function bpOfTemplate(t) {
return HEVY_BP[g] || 'upper legs'
}
-/** Shared resolver: HEVY_ID_MAP hit, else one custom exercise per Hevy template id. */
-function makeResolver(templates) {
+/**
+ * Shared resolver: the user's own custom exercise when an earlier import made one (priorCustom,
+ * so one exercise keeps one id once the map learns it), else a HEVY_ID_MAP hit, else one custom
+ * exercise per Hevy template id. `customEx`: the custom exercises already in state.
+ */
+function makeResolver(templates, customEx) {
const byId = new Map((templates || []).map(t => [t.id, t]))
const created = new Map()
const titleOf = new Map() // custom id → the name Hevy showed for it
const matchedIds = new Set()
const resolve = (templateId, fallbackTitle) => {
+ const key = templateId || String(fallbackTitle || '').toLowerCase()
+ if (!key) return null
+ const t = templateId ? byId.get(templateId) : null
+ const own = priorCustom(customEx, importId('im', 'Hevy|' + key), t?.title || fallbackTitle)
+ if (own) return own.id
const pinned = templateId && HEVY_ID_MAP[templateId]
if (pinned && EXIDX[pinned]) {
matchedIds.add(pinned)
return pinned
}
- const key = templateId || String(fallbackTitle || '').toLowerCase()
- if (!key) return null
let c = created.get(key)
if (!c) {
- const t = templateId ? byId.get(templateId) : null
const name = (t?.title || fallbackTitle || 'exercise').toLowerCase()
c = {
id: importId('im', 'Hevy|' + key), n: name, custom: true, eq: 'custom', tg: '', desc: '',
@@ -214,8 +220,8 @@ const toProfileWeight = (wKg, unit) => {
* Mapping is by `exercise_template_id` through `HEVY_ID_MAP` only — localized
* titles on each set are never used to pick a catalogue entry.
*/
-export function parseHevyWorkouts(workouts, templates, { unit = 'kg' } = {}) {
- const R = makeResolver(templates)
+export function parseHevyWorkouts(workouts, templates, { unit = 'kg', customEx = [] } = {}) {
+ const R = makeResolver(templates, customEx)
const byDate = new Map()
let sets = 0, skipped = 0, matched = 0, warmups = 0, rpeSets = 0
@@ -318,8 +324,8 @@ export function parseHevyWorkouts(workouts, templates, { unit = 'kg' } = {}) {
* Work sets become `sets`×`reps`/`weight`; warm-ups become `warmupSets`;
* supersets keep adjacency via `sg`. Always imported as *new* routines.
*/
-export function parseHevyRoutines(routines, templates, { unit = 'kg' } = {}) {
- const R = makeResolver(templates)
+export function parseHevyRoutines(routines, templates, { unit = 'kg', customEx = [] } = {}) {
+ const R = makeResolver(templates, customEx)
const out = []
for (const r of routines || []) {
@@ -458,12 +464,12 @@ export function parseHevyBodyweight(measurements, { unit = 'kg' } = {}) {
* Fetch + parse. Returns `{ workouts, routines, bodyweight }` ready to merge,
* or throws `HevyApiError`. The apiKey is only read here — never written.
*/
-export async function importHevyData(apiKey, { unit = 'kg', onProgress } = {}) {
+export async function importHevyData(apiKey, { unit = 'kg', onProgress, customEx = [] } = {}) {
const { templates, workouts, routines, bodyMeasurements } = await fetchHevyAccount(apiKey, { onProgress })
onProgress && onProgress({ stage: 'parse' })
return {
- workouts: parseHevyWorkouts(workouts, templates, { unit }),
- routines: parseHevyRoutines(routines, templates, { unit }),
+ workouts: parseHevyWorkouts(workouts, templates, { unit, customEx }),
+ routines: parseHevyRoutines(routines, templates, { unit, customEx }),
bodyweight: parseHevyBodyweight(bodyMeasurements, { unit }),
templateCount: templates.length,
}
diff --git a/frontend/src/lib/import-reimport.test.js b/frontend/src/lib/import-reimport.test.js
new file mode 100644
index 000000000..f9d139fda
--- /dev/null
+++ b/frontend/src/lib/import-reimport.test.js
@@ -0,0 +1,62 @@
+/* A name the 1,324-exercise catalogue did not know was imported as a custom exercise (an `im…`
+ id). The new catalogue may know it, and the next import of the same account matched it afresh:
+ new days on the catalogue id, old ones on the custom one, one exercise's history in two. An
+ exercise the user already has keeps its id. */
+import { describe, expect, it } from 'vitest'
+import { importId, matchExercise, mergeImport, parseWorkoutCSV } from './import-csv.js'
+import { HEVY_ID_MAP, mergeHevyRoutines, parseHevyRoutines, parseHevyWorkouts } from './import-hevy.js'
+import { EXIDX } from './exercises.js'
+
+const base = customEx => ({ _ts: 1, workouts: [], customEx, bodyweight: [], exWeights: {}, routines: [] })
+const custom = (id, n) => ({ id, n, custom: true, eq: 'custom', tg: '', desc: '', bp: 'chest' })
+const ids = S => new Set(S.workouts.flatMap(w => w.entries.map(e => e.id)))
+
+const CSV = day => [
+ 'Date,Workout Name,Duration,Exercise Name,Set Order,Weight,Reps,Distance,Seconds,Notes,Workout Notes,RPE',
+ `${day} 18:00:00,Push,1h,Bench Press (Barbell),1,80,5,0,0,,,`,
+].join('\n')
+
+describe('re-importing an exercise an earlier import made a custom one', () => {
+ it('the catalogue knows the name now; the custom one keeps the history', () => {
+ expect(EXIDX[matchExercise('Bench Press (Barbell)')]).toBeTruthy()
+ const own = custom(importId('im', 'Strong|bench press (barbell)'), 'bench press (barbell)')
+ const S = base([own])
+ S.workouts = [{ id: 'w0', d: '2026-08-01', entries: [{ id: own.id, sets: [{ w: 75, r: 5 }] }] }]
+ const parsed = parseWorkoutCSV(CSV('2026-09-01'), { unit: 'kg', customEx: S.customEx })
+ expect(parsed.customEx).toEqual([])
+ mergeImport(S, parsed)
+ expect(ids(S)).toEqual(new Set([own.id]))
+ expect(S.customEx).toEqual([own])
+ })
+
+ it('found by its name too, renamed only in case and spacing, whatever id it got', () => {
+ const own = custom('k3x9old', 'Bench Press (barbell)')
+ const S = base([own])
+ mergeImport(S, parseWorkoutCSV(CSV('2026-09-01'), { unit: 'kg', customEx: S.customEx }))
+ expect(ids(S)).toEqual(new Set(['k3x9old']))
+ })
+
+ it('without a custom one of that name it is matched as before', () => {
+ const S = base([])
+ mergeImport(S, parseWorkoutCSV(CSV('2026-09-01'), { unit: 'kg', customEx: S.customEx }))
+ expect(ids(S)).toEqual(new Set([matchExercise('Bench Press (Barbell)')]))
+ })
+
+ it('Hevy: a template the id map has learnt since stays on the custom exercise it was imported as', () => {
+ const hid = Object.keys(HEVY_ID_MAP).find(k => EXIDX[HEVY_ID_MAP[k]])
+ const templates = [{ id: hid, title: 'Some Lift', type: 'weight_reps', primary_muscle_group: 'chest' }]
+ const own = custom(importId('im', 'Hevy|' + hid), 'renamed by the user')
+ const S = base([own])
+ const workout = {
+ id: 'w1', title: 'Push', start_time: '2026-09-01T10:00:00+00:00', end_time: '2026-09-01T11:00:00+00:00',
+ exercises: [{ title: 'Some Lift', exercise_template_id: hid, sets: [{ type: 'normal', weight_kg: 50, reps: 8 }] }],
+ }
+ const parsed = parseHevyWorkouts([workout], templates, { customEx: S.customEx })
+ mergeImport(S, parsed)
+ expect(ids(S)).toEqual(new Set([own.id]))
+ const routines = parseHevyRoutines([{ id: 'r1', title: 'Push', exercises: [{ exercise_template_id: hid, title: 'Some Lift', sets: [{ type: 'normal', reps: 8 }] }] }], templates, { customEx: S.customEx })
+ mergeHevyRoutines(S, routines)
+ expect(S.routines[0].ex.map(e => e.id)).toEqual([own.id])
+ expect(S.customEx).toEqual([own])
+ })
+})
diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx
index ad98d2fb8..3ccdbdcfa 100644
--- a/frontend/src/sheets.jsx
+++ b/frontend/src/sheets.jsx
@@ -491,7 +491,7 @@ export function importFromApp(file, onDone) {
const rd = new FileReader()
rd.onload = () => {
let parsed
- try { parsed = parseImport(String(rd.result), { unit: S().unit }) }
+ try { parsed = parseImport(String(rd.result), { unit: S().unit, customEx: S().customEx }) }
catch (e) { toast(t('Could not read that file')); return }
if (parsed.error === 'empty') { toast(t('That file is empty')); return }
if (parsed.error) { toast(t("We don't recognise that file's columns. Check the docs for supported apps.")); return }
@@ -547,7 +547,7 @@ function HevyImportSheet({ close }) {
setProgress({ stage: 'templates', page: 1, pageCount: 1 })
setPayload(null)
try {
- const data = await importHevyData(key, { unit: st.unit, onProgress: setProgress })
+ const data = await importHevyData(key, { unit: st.unit, customEx: st.customEx, onProgress: setProgress })
wipeKey()
const empty = !data.workouts.workouts.length && !data.routines.routines.length && !data.bodyweight.bodyweight.length
if (empty) {