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.

Follow-up to #303: a profile that never picked a language is shown in DEFAULT_LANG or the device's browser language without writing it into the synced state, so two devices no longer push it back and forth, and the Coach writes in the language the app is showing

Duarte Santos739e0841f79c
diff --git a/api/coach/core/payload.js b/api/coach/core/payload.js
index 30b2bfbe6..0f427350a 100644
--- a/api/coach/core/payload.js
+++ b/api/coach/core/payload.js
@@ -50,6 +50,10 @@ export const PROFILE_EQUIPMENT_MAX = 40;
export const NAME_MAX = 80;
const text = (v, n) => (typeof v === 'string' ? v.slice(0, n) : '');
const word = (v, n) => (typeof v === 'string' && v ? v.slice(0, n) : null);
+
+/** A language tag's shape ('de', 'pt-BR', 'zh_Hant'), or null — for a language that arrives with
+ * a request or from the environment rather than from the state (#303). */
+export const langTag = v => (typeof v === 'string' && /^[A-Za-z]{2,3}([-_][A-Za-z0-9]{2,8})?$/.test(v.trim()) ? v.trim() : null);
// Zero reads as absent, as `|| null` always made it; anything else is clamped into range.
const count = (v, lo, hi) => {
const n = typeof v === 'number' || typeof v === 'string' ? Number(v) : NaN;
@@ -445,7 +449,7 @@ export function workoutMeta(S, workoutId) {
* Build a job payload.
*
* @param {object} S the profile's synced state
- * @param {object} opts { handle, kind, intake?, note?, refine?, previous?, workoutId?, cohort? }
+ * @param {object} opts { handle, kind, intake?, note?, refine?, previous?, workoutId?, cohort?, lang? }
*
* `handle` is the opaque per-profile pseudonym the payload carries instead of a uid. It is
* supplied rather than derived because the two runtimes mint it differently: the server keys
@@ -462,7 +466,9 @@ export function build(S, opts = {}) {
meta: {
profile: opts.handle,
// Both are short codes in any real state; cut anyway, since the state is the client's.
- lang: word(S.lang, 16) || 'en',
+ // `opts.lang` is the language the app is showing when it asked: a profile that never
+ // picked one has it worked out per device and never stored (#303).
+ lang: langTag(opts.lang) || word(S.lang, 16) || 'en',
unit: word(S.unit, 8) || 'kg',
effortScale: effortOf(S),
today: iso(new Date())
diff --git a/api/coach/jobs.js b/api/coach/jobs.js
index d92bd9a91..cb4797a52 100644
--- a/api/coach/jobs.js
+++ b/api/coach/jobs.js
@@ -245,6 +245,7 @@ export function enqueue(uid, opts) {
intake: opts.intake || null,
note: clampMessage(opts.note),
refine: clampMessage(opts.refine),
+ lang: payloadLib.langTag(opts.lang), // the language the app was showing (#303)
state: 'queued',
startedAt: Date.now()
};
@@ -329,6 +330,9 @@ async function execute(job) {
refine: job.refine,
previous: pendingCreate?.bundle || null,
workoutId: job.workoutId,
+ // The app says which language it is in. A scheduled review has no app behind it: a profile
+ // that never picked a language then gets the instance's DEFAULT_LANG, like its screens do.
+ lang: job.lang || (S.langAuto === true ? payloadLib.langTag(process.env.DEFAULT_LANG) : null),
// The room's medians ride along on a review or a debrief when the admin allows it and
// this person opted in; null otherwise, and the payload then carries no `cohort` at all.
cohort: (job.kind === 'review' || job.kind === 'debrief') ? cohortForPayload(job.uid) : null
diff --git a/api/coach/routes.js b/api/coach/routes.js
index 5a98b78be..bcf992b59 100644
--- a/api/coach/routes.js
+++ b/api/coach/routes.js
@@ -74,6 +74,7 @@ export function coachRoutes({ json, readBody, readSession, requireAdmin }) {
const job = jobs.enqueue(user.id, {
kind: 'create',
intake: body.intake || null,
+ lang: body.lang,
refine: body.refine ? String(body.refine).slice(0, cfgStore.MAX_MESSAGE_LEN_CEILING) : null
});
json(res, 202, { job });
@@ -86,6 +87,7 @@ export function coachRoutes({ json, readBody, readSession, requireAdmin }) {
try {
const job = jobs.enqueue(user.id, {
kind: 'review',
+ lang: body.lang,
note: body.note ? String(body.note).slice(0, cfgStore.MAX_MESSAGE_LEN_CEILING) : null
});
json(res, 202, { job });
@@ -97,7 +99,7 @@ export function coachRoutes({ json, readBody, readSession, requireAdmin }) {
const user = guard(req, res); if (!user) return;
const body = await readBody(req);
try {
- const job = jobs.enqueue(user.id, { kind: 'debrief', workoutId: body.workoutId ? String(body.workoutId).slice(0, 40) : null });
+ const job = jobs.enqueue(user.id, { kind: 'debrief', lang: body.lang, workoutId: body.workoutId ? String(body.workoutId).slice(0, 40) : null });
json(res, 202, { job });
} catch (e) { failEnqueue(res, e); }
},
diff --git a/api/openapi.yaml b/api/openapi.yaml
index 81992bc64..b780fdf43 100644
--- a/api/openapi.yaml
+++ b/api/openapi.yaml
@@ -2280,6 +2280,12 @@ paths:
description: |
A change asked for in plain words, applied to the proposal now waiting. Cut to
the instance's `maxMessageLen` (1000 unless the admin changed it; 200–4000).
+ lang:
+ type: string
+ pattern: '^[A-Za-z]{2,3}([-_][A-Za-z0-9]{2,8})?$'
+ description: |
+ The language the app is showing, which the Coach writes in. Absent or not a
+ language tag, the profile's stored `lang` is used.
example: { intake: { goal: muscle, experience: novice, daysPerWeek: 3, equipment: [dumbbell, barbell] } }
responses:
'202': { $ref: '#/components/responses/CoachJobQueued' }
@@ -2311,6 +2317,12 @@ paths:
description: |
Anything the profile wants the Coach to know this time round. Cut to the
instance's `maxMessageLen` (1000 unless the admin changed it; 200–4000).
+ lang:
+ type: string
+ pattern: '^[A-Za-z]{2,3}([-_][A-Za-z0-9]{2,8})?$'
+ description: |
+ The language the app is showing, which the Coach writes in. Absent or not a
+ language tag, the profile's stored `lang` is used.
responses:
'202': { $ref: '#/components/responses/CoachJobQueued' }
'401': { $ref: '#/components/responses/Unauthorized' }
@@ -2338,6 +2350,12 @@ paths:
workoutId:
oneOf: [{ type: string, maxLength: 40 }, { type: 'null' }]
description: The workout to read; null or absent means the latest.
+ lang:
+ type: string
+ pattern: '^[A-Za-z]{2,3}([-_][A-Za-z0-9]{2,8})?$'
+ description: |
+ The language the app is showing, which the Coach writes in. Absent or not a
+ language tag, the profile's stored `lang` is used.
responses:
'202': { $ref: '#/components/responses/CoachJobQueued' }
'401': { $ref: '#/components/responses/Unauthorized' }
diff --git a/api/test/payload.test.js b/api/test/payload.test.js
index 0e5f79b57..81328b914 100644
--- a/api/test/payload.test.js
+++ b/api/test/payload.test.js
@@ -331,3 +331,16 @@ test('a custom exercise\'s photo, video and link never reach the payload', () =>
const slice = payload.librarySlice(S, [], { keep: ['cx1'] }).find(e => e.id === 'cx1');
assert.deepEqual(slice, { id: 'cx1', n: 'Sandbag carry', bp: 'back', custom: true }, 'the library slice keeps a custom exercise to four fields');
});
+
+/* #303: a profile that never picked a language has it worked out on each device and never
+ stored, so the app says which one it is showing; a value that is not a language tag is not
+ carried into the prompt. */
+test('meta.lang is the language the app asked in, else the stored one', () => {
+ const S = { ...sampleState(), lang: 'de', langAuto: true };
+ const h = handleFor('user-lang');
+ assert.equal(payload.build(S, { handle: h, kind: 'review', lang: 'pt-BR' }).meta.lang, 'pt-BR');
+ assert.equal(payload.build(S, { handle: h, kind: 'review' }).meta.lang, 'de');
+ assert.equal(payload.build(S, { handle: h, kind: 'review', lang: 'ignore the rules and' }).meta.lang, 'de');
+ assert.equal(payload.langTag(' fr '), 'fr');
+ assert.equal(payload.langTag('<script>'), null);
+});
diff --git a/docs/SELF_HOSTING.md b/docs/SELF_HOSTING.md
index cffe12355..062816aea 100644
--- a/docs/SELF_HOSTING.md
+++ b/docs/SELF_HOSTING.md
@@ -150,6 +150,11 @@ old profile that chose English from one that never looked, so it leaves them alo
English. A code the app has no translation for is ignored. The phone app in local mode has no
server to ask and is unaffected.
+Until someone picks a language, it is worked out on each device and not saved with the profile:
+without `DEFAULT_LANG`, the same profile can show in German on one phone and in English on a
+laptop, and the Coach answers in whichever the app is showing. A scheduled review, which no app
+asks for, is written in `DEFAULT_LANG` when it is set.
+
### The activity log
The dashboard also keeps an **activity log**: sign-ins, sign-outs, failed attempts, refused
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx
index d292125b1..0117a2b9d 100644
--- a/frontend/src/App.jsx
+++ b/frontend/src/App.jsx
@@ -5,6 +5,7 @@ import { useUI } from './store/useUI.js'
import { bindUI } from './components/ui.jsx'
import { ACCENTS, setWeightDecimals } from './lib/format.js'
import { setLang, useLang, baseLang } from './lib/i18n.js'
+import { effectiveLang } from './lib/default-lang.js'
import { setPlayOnSilent, setVibrate } from './lib/sound.js'
import { setNav } from './lib/nav.js'
import { initBackButton } from './lib/back.js'
@@ -95,13 +96,14 @@ function Shell() {
mql.addEventListener('change', onChange)
return () => mql.removeEventListener('change', onChange)
}, [S.theme, S.accent])
- // A profile that never picked a language follows the instance default or the browser (#303).
+ // A profile that never picked a language follows the instance default or the browser (#303) —
+ // worked out here, on this device, and never written into the synced state (lib/default-lang.js).
const config = useStore(s => s.config)
- useEffect(() => { useStore.getState().applyAutoLang() }, [config, S.langAuto, S.lang])
- useEffect(() => { setLang(S.lang || 'en', S.enParens?.[baseLang(S.lang || 'en')] ?? true, S.enOnly?.[baseLang(S.lang || 'en')] === true) }, [S.lang, S.enParens, S.enOnly])
+ const lang = effectiveLang(S, config)
+ useEffect(() => { setLang(lang, S.enParens?.[baseLang(lang)] ?? true, S.enOnly?.[baseLang(lang)] === true) }, [lang, S.enParens, S.enOnly])
// Same shape as the language: a module-level display setting, pushed when it changes (#139).
useEffect(() => { setWeightDecimals(S.wdec) }, [S.wdec])
- useEffect(() => { document.documentElement.lang = S.lang || 'en' }, [langV, S.lang])
+ useEffect(() => { document.documentElement.lang = lang }, [langV, lang])
// Forward navigation starts at the top; going back lands where you left off.
// The position is recorded from scroll events rather than read at route
// change, because by then a shorter page may already have clamped it.
diff --git a/frontend/src/lib/coach-api.js b/frontend/src/lib/coach-api.js
index b6f1a7fb7..0db547cde 100644
--- a/frontend/src/lib/coach-api.js
+++ b/frontend/src/lib/coach-api.js
@@ -9,7 +9,7 @@ import { useEffect, useState, useCallback, useRef } from 'react'
import { api } from './api.js'
import { DEMO } from './demo.js'
import { MOBILE } from './mobile.js'
-import { t } from './i18n.js'
+import { t, getLang } from './i18n.js'
import { useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
@@ -23,6 +23,9 @@ const IDLE_MS = 60000 // a Coach screen is open but nothing is running
let demoMod = null
const demo = async () => (demoMod = demoMod || await import('./coach-demo.js'))
const S = () => useStore.getState().S
+// Each request says which language the app is in: a profile that never picked one has no stored
+// `lang` worth trusting — it is worked out per device (#303, lib/default-lang.js) — and the
+// Coach should answer in what the person is reading.
// The mobile build's third answer: a phone that brought its own API key runs the Coach itself
// (lib/coach-local.js — the same core the server runs, imported lazily so the catalogue and the
@@ -44,10 +47,10 @@ const local = async () => {
}
export const coachStatus = async () => DEMO ? (await demo()).demoStatus() : LOCAL() ? (await local()).localStatus() : api('/api/coach/status')
-export const requestReview = async note => DEMO ? (await demo()).demoReview(S()) : LOCAL() ? (await local()).localReview(S(), note) : api('/api/coach/review', { method: 'POST', body: JSON.stringify({ note: note || '' }) })
-export const requestPlan = async intake => DEMO ? (await demo()).demoPlan(S(), intake) : LOCAL() ? (await local()).localPlan(S(), intake) : api('/api/coach/plan', { method: 'POST', body: JSON.stringify({ intake }) })
-export const refinePlan = async text => DEMO ? (await demo()).demoRefine(S()) : LOCAL() ? (await local()).localRefine(S(), text) : api('/api/coach/plan', { method: 'POST', body: JSON.stringify({ refine: text }) })
-export const requestDebrief = async workoutId => DEMO ? (await demo()).demoDebrief(S(), workoutId) : LOCAL() ? (await local()).localDebrief(S(), workoutId) : api('/api/coach/debrief', { method: 'POST', body: JSON.stringify({ workoutId: workoutId || null }) })
+export const requestReview = async note => DEMO ? (await demo()).demoReview(S()) : LOCAL() ? (await local()).localReview(S(), note) : api('/api/coach/review', { method: 'POST', body: JSON.stringify({ note: note || '', lang: getLang() }) })
+export const requestPlan = async intake => DEMO ? (await demo()).demoPlan(S(), intake) : LOCAL() ? (await local()).localPlan(S(), intake) : api('/api/coach/plan', { method: 'POST', body: JSON.stringify({ intake, lang: getLang() }) })
+export const refinePlan = async text => DEMO ? (await demo()).demoRefine(S()) : LOCAL() ? (await local()).localRefine(S(), text) : api('/api/coach/plan', { method: 'POST', body: JSON.stringify({ refine: text, lang: getLang() }) })
+export const requestDebrief = async workoutId => DEMO ? (await demo()).demoDebrief(S(), workoutId) : LOCAL() ? (await local()).localDebrief(S(), workoutId) : api('/api/coach/debrief', { method: 'POST', body: JSON.stringify({ workoutId: workoutId || null, lang: getLang() }) })
// The room: anonymous medians across the profiles on this instance that opted in. Only a
// server has a room; a phone with its own key and the demo both answer locally.
export const cohortStats = async () => DEMO ? (await demo()).demoCohort(S()) : LOCAL() ? { ok: false, enabled: false } : api('/api/coach/cohort')
diff --git a/frontend/src/lib/coach-local.js b/frontend/src/lib/coach-local.js
index 8be7303e4..9f7c3e64b 100644
--- a/frontend/src/lib/coach-local.js
+++ b/frontend/src/lib/coach-local.js
@@ -27,7 +27,7 @@ import { getApiKey } from './coach-secrets.js'
import { loadCoachDevice, saveCoachDevice } from './coach-device.js'
import { planHash } from './coach.js'
import { todayISO } from './format.js'
-import { t } from './i18n.js'
+import { t, getLang } from './i18n.js'
export const ADAPTERS = { anthropic, openai, gemini, compatible }
export const LOCAL_DAILY_CAP = 10
@@ -142,7 +142,8 @@ async function start(S, kind, opts) {
async function run(S, kind, opts, d, adapter) {
const key = await getApiKey()
const payload = payloadLib.build(S, {
- handle: await handle(), kind, intake: opts.intake, note: opts.note, refine: opts.refine, previous: opts.previous, workoutId: opts.workoutId
+ handle: await handle(), kind, intake: opts.intake, note: opts.note, refine: opts.refine, previous: opts.previous, workoutId: opts.workoutId,
+ lang: getLang() // what the app shows, which a profile that never picked a language does not store (#303)
})
const attempt = await runPipeline({
adapter, cfg: cfgOf(d), kind, payload,
diff --git a/frontend/src/lib/default-lang.js b/frontend/src/lib/default-lang.js
index 96b8812de..d8857af47 100644
--- a/frontend/src/lib/default-lang.js
+++ b/frontend/src/lib/default-lang.js
@@ -8,6 +8,12 @@
//
// For a marked copy, the instance's DEFAULT_LANG (GET /api/config `default_lang`) comes first,
// then the first of the browser's languages this app speaks, then English.
+//
+// That answer is worked out where the language is used (effectiveLang) and never written back
+// into the state. It depends on the device — two phones of one profile can have browsers in two
+// languages — and the state is synced: a derived language stored in it would be pushed by one
+// device, pulled by the other, re-derived there and pushed back, round after round. `lang` is
+// only written when someone picks one in Settings, which also clears the mark.
import { LANGS } from './i18n-core.js'
const KEYS = Object.keys(LANGS)
@@ -31,6 +37,34 @@ export function autoLang(S, config, navLangs = []) {
|| 'en'
}
+// The instance's DEFAULT_LANG as last seen on this device, so a boot does not show the browser's
+// language (or the copy's stored one) until /api/config answers and then switch. '' means the
+// instance has none; null means this device has not asked yet.
+const CACHE_KEY = 'gym_default_lang'
+export function rememberDefaultLang(config) {
+ try { localStorage.setItem(CACHE_KEY, typeof config?.default_lang === 'string' ? config.default_lang : '') } catch { /* ignore */ }
+}
+function cachedDefaultLang() {
+ try { return localStorage.getItem(CACHE_KEY) } catch { return null }
+}
+
+/**
+ * The language to show this copy in, on this device: its own `lang`, or for a copy that never
+ * picked one, what autoLang says. Before the config is in, the default this device last saw
+ * stands in for it; with none seen yet the copy's stored language is used unchanged.
+ */
+export function effectiveLang(S, config, navLangs = browserLangs()) {
+ const own = (S && typeof S.lang === 'string' && S.lang) || 'en'
+ if (!S || S.langAuto !== true) return own
+ let cfg = config
+ if (!cfg) {
+ const seen = cachedDefaultLang()
+ if (seen === null) return own
+ cfg = { default_lang: seen }
+ }
+ return autoLang(S, cfg, navLangs) || own
+}
+
export function browserLangs() {
try {
const list = navigator.languages && navigator.languages.length ? navigator.languages : [navigator.language]
diff --git a/frontend/src/store/useStore.default-lang.test.jsx b/frontend/src/store/useStore.default-lang.test.jsx
index 12246282f..ac00e9017 100644
--- a/frontend/src/store/useStore.default-lang.test.jsx
+++ b/frontend/src/store/useStore.default-lang.test.jsx
@@ -2,17 +2,26 @@
// #303: DEFAULT_LANG from /api/config sets the language of a fresh copy — the sign-in screen,
// and a profile created from it — and nothing else. A copy saved before the mark existed keeps
// its language even when that is the old default, 'en': it may well have been chosen.
+//
+// The language worked out for such a copy is the device's own and is never written into the
+// synced state: two devices with browsers in different languages would otherwise push their
+// answers over each other on every sync round.
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
vi.mock('../lib/api.js', () => ({ api: vi.fn() }))
+vi.mock('./useUI.js', () => ({ useUI: { getState: () => ({ toast: vi.fn() }) } }))
import { api } from '../lib/api.js'
+import { effectiveLang } from '../lib/default-lang.js'
import { useStore, freshState, DEF } from './useStore.js'
+const clone = v => JSON.parse(JSON.stringify(v))
const nav = langs => Object.defineProperty(navigator, 'languages', { value: langs, configurable: true })
+const shown = () => { const { S, config } = useStore.getState(); return effectiveLang(S, config) }
+const puts = () => api.mock.calls.filter(([, o]) => o?.method === 'PUT')
-beforeEach(() => { api.mockReset(); nav(['en-US']); useStore.setState({ config: null }) })
-afterEach(() => { useStore.setState({ config: null }) })
+beforeEach(() => { localStorage.clear(); api.mockReset(); nav(['en-US']); useStore.setState({ config: null }) })
+afterEach(() => { localStorage.clear(); useStore.setState({ S: clone(DEF), user: null, ready: false, config: null }) })
describe('instance default language', () => {
it('a fresh copy is marked as not having picked a language; DEF is not', () => {
@@ -20,39 +29,65 @@ describe('instance default language', () => {
expect(DEF.langAuto).toBeUndefined()
})
- it('a fresh copy takes DEFAULT_LANG once the config is in', async () => {
+ it('a fresh copy is shown in DEFAULT_LANG once the config is in, and its state is left alone', async () => {
useStore.setState({ S: freshState() })
- useStore.getState().applyAutoLang()
- expect(useStore.getState().S.lang).toBe('en') // nothing to go on before the config
+ expect(shown()).toBe('en') // nothing to go on before the config
+ const before = clone(useStore.getState().S)
api.mockResolvedValueOnce({ invite_only: false, allow_guest: true, default_lang: 'pt-BR' })
await useStore.getState().refreshConfig()
- useStore.getState().applyAutoLang()
- expect(useStore.getState().S.lang).toBe('pt-BR')
- expect(useStore.getState().S.langAuto).toBe(true)
+ expect(shown()).toBe('pt-BR')
+ expect(useStore.getState().S).toEqual(before)
+ })
+
+ it('the next boot uses the default this device last saw, before the config answers', async () => {
+ nav(['de-DE'])
+ api.mockResolvedValueOnce({ invite_only: false, default_lang: 'pt-BR' })
+ await useStore.getState().refreshConfig()
+ useStore.setState({ S: freshState(), config: null })
+ expect(shown()).toBe('pt-BR') // not the browser's German first
+ // An instance known to have none: the browser's language at once.
+ api.mockResolvedValueOnce({ invite_only: false })
+ await useStore.getState().refreshConfig()
+ useStore.setState({ config: null })
+ expect(shown()).toBe('de')
})
it('without DEFAULT_LANG a fresh copy follows the browser when the app speaks it', () => {
nav(['de-DE', 'en'])
useStore.setState({ S: freshState(), config: { invite_only: false, allow_guest: true } })
- useStore.getState().applyAutoLang()
- expect(useStore.getState().S.lang).toBe('de')
+ expect(shown()).toBe('de')
})
it('an existing copy with lang "en" and no mark is left in English', () => {
nav(['de-DE'])
- useStore.setState({ S: { ...JSON.parse(JSON.stringify(DEF)), lang: 'en' }, config: { default_lang: 'pt-BR' } })
- useStore.getState().applyAutoLang()
- expect(useStore.getState().S.lang).toBe('en')
+ useStore.setState({ S: { ...clone(DEF), lang: 'en' }, config: { default_lang: 'pt-BR' } })
+ expect(shown()).toBe('en')
})
it('a language picked in Settings wins over DEFAULT_LANG from then on', () => {
useStore.setState({ S: freshState(), config: { default_lang: 'pt-BR' } })
- useStore.getState().applyAutoLang()
- expect(useStore.getState().S.lang).toBe('pt-BR')
+ expect(shown()).toBe('pt-BR')
// What the Settings picker does.
useStore.getState().update(s => { s.lang = 'en'; s.langAuto = false })
- useStore.getState().applyAutoLang()
- expect(useStore.getState().S.lang).toBe('en')
+ expect(shown()).toBe('en')
+ })
+
+ it('two devices with browsers in different languages do not push the profile back and forth', async () => {
+ // Device B's browser is English; the server copy was last written from device A (German).
+ nav(['en-US'])
+ const server = { ...clone(DEF), _ts: 100, lang: 'de', langAuto: true, workouts: [{ id: 'w1', d: '2026-09-01', start: 1, entries: [] }] }
+ useStore.setState({ S: clone(server), user: { id: 'u1' }, ready: true, config: { invite_only: false } })
+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 5, ts: 100 }))
+ expect(shown()).toBe('en')
+ expect(useStore.getState().S.lang).toBe('de')
+
+ // The next poll: the server has not moved, and this device owes it nothing.
+ api.mockResolvedValue({ state: { ...server, _rev: 5 }, rev: 5 })
+ await useStore.getState().pullState()
+ await useStore.getState().pullState()
+ expect(puts()).toHaveLength(0)
+ expect(useStore.getState().S.lang).toBe('de')
+ expect(shown()).toBe('en')
})
})
diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.js
index c7175e9f6..3e5fe6e04 100644
--- a/frontend/src/store/useStore.js
+++ b/frontend/src/store/useStore.js
@@ -4,7 +4,7 @@ import { localTZ } from '../lib/format.js'
import { t } from '../lib/i18n.js'
import { registerCustom } from '../lib/exercises.js'
import { DEMO, DEMO_SEEDED } from '../lib/demo.js'
-import { autoLang, browserLangs } from '../lib/default-lang.js'
+import { rememberDefaultLang } from '../lib/default-lang.js'
import { guestAllowed } from '../lib/guest.js'
import { MOBILE, initReminderSync, nativeLoad, nativeSave, onAppActive, readJsonFile, syncReminder, writeAutoBackup, writeJsonFile } from '../lib/mobile.js'
import { mergeStates, localExtras, stampRoutines, stampCustomEx } from '../lib/sync-merge.js'
@@ -823,21 +823,10 @@ export const useStore = create((set, get) => {
// while a paired phone sits on the setup screen — that screen wants today's answer.
// Two callers that ask at once get one request: signing in re-asks (setUser) and the pairing
// flow awaits a refresh of its own immediately after, and there is one answer to have.
- // A copy whose language nobody picked follows DEFAULT_LANG, else the browser (#303). Written
- // without a push: the value is derived, and a profile's next real change carries it — a
- // sync round per boot per device, possibly with differing browser languages, would be churn.
- // Only once the server's config is in hand, so a boot does not flip to the browser's
- // language and back while it is being fetched.
- applyAutoLang() {
- const { S, config } = get()
- if (!config) return
- const l = autoLang(S, config, browserLangs())
- if (l && l !== S.lang) get().update(s => { s.lang = l }, false)
- },
async refreshConfig() {
if (configFetch) return configFetch
configFetch = (async () => {
- try { const c = await api('/api/config'); set({ config: c }); return c }
+ try { const c = await api('/api/config'); rememberDefaultLang(c); set({ config: c }); return c }
catch { return null }
finally { configFetch = null }
})()
diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsx
index 69de60a6e..b83fe942e 100644
--- a/frontend/src/views/Settings.jsx
+++ b/frontend/src/views/Settings.jsx
@@ -14,6 +14,7 @@ import { api, webauthnOK, passkeyRegister, IS_ANDROID } from '../lib/api.js'
import { pushSupported, enablePush, disablePush, sendTestPush, syncPushSubscription } from '../lib/push.js'
import { wakeLockSupported } from '../lib/wakelock.js'
import { t, LANGS, INSTR_LANGS, EXERCISE_NAME_LANGS, baseLang } from '../lib/i18n.js'
+import { effectiveLang } from '../lib/default-lang.js'
import { DEMO, REPO } from '../lib/demo.js'
import { MOBILE, isAndroid, shareExport, shareExportBlob, syncReminder } from '../lib/mobile.js'
import { referencedFiles } from '../lib/media-refs.js'
@@ -37,7 +38,11 @@ export default function Settings() {
const user = useStore(s => s.user)
const coachLocal = useStore(s => s.coachLocal)
// Name-and-password sign-in, where the instance offers it (#118).
- const pwOn = passwordOn(useStore(s => s.config))
+ const config = useStore(s => s.config)
+ const pwOn = passwordOn(config)
+ // What the app is showing, which for a profile that never picked a language is worked out on
+ // this device rather than stored (#303).
+ const lang = effectiveLang(S, config)
// This profile's passkeys and the code for another device (#95). A change to them is read back
// here and by the password row, whose "Remove" depends on there being a passkey.
const passkeys = usePasskeys(!!user && !MOBILE && !DEMO)
@@ -313,23 +318,23 @@ export default function Settings() {
<Section title={t('General')} footer={t('Switching the unit offers to convert every stored weight.')}>
<SelectRow
icon="globe" iconTint="var(--blue)" title={t('Language')}
- value={S.lang || 'en'} onChange={v => update(s => { s.lang = v; s.langAuto = false })}
+ value={lang} onChange={v => update(s => { s.lang = v; s.langAuto = false })}
options={Object.entries(LANGS).map(([k, name]) => ({
value: k, label: name,
subtitle: INSTR_LANGS.includes(k) ? null : t("Exercise instructions aren't available in this language yet — they stay in English."),
}))}
/>
- {EXERCISE_NAME_LANGS.includes(baseLang(S.lang || 'en')) && <>
+ {EXERCISE_NAME_LANGS.includes(baseLang(lang)) && <>
<Row icon="dumbbell" iconTint="var(--purple)" title={t('English exercise names')}
subtitle={t('Show the English name in parentheses next to the translated one.')}>
- <Switch checked={S.enParens?.[baseLang(S.lang || 'en')] ?? true}
- disabled={S.enOnly?.[baseLang(S.lang || 'en')] === true}
- onChange={v => update(s => { s.enParens = { ...(s.enParens || {}), [baseLang(S.lang || 'en')]: v } })} />
+ <Switch checked={S.enParens?.[baseLang(lang)] ?? true}
+ disabled={S.enOnly?.[baseLang(lang)] === true}
+ onChange={v => update(s => { s.enParens = { ...(s.enParens || {}), [baseLang(lang)]: v } })} />
</Row>
<Row icon="globe" iconTint="var(--purple)" title={t('English names only')}
subtitle={t('Replace the translated names with the original English ones.')}>
- <Switch checked={S.enOnly?.[baseLang(S.lang || 'en')] === true}
- onChange={v => update(s => { s.enOnly = { ...(s.enOnly || {}), [baseLang(S.lang || 'en')]: v } })} />
+ <Switch checked={S.enOnly?.[baseLang(lang)] === true}
+ onChange={v => update(s => { s.enOnly = { ...(s.enOnly || {}), [baseLang(lang)]: v } })} />
</Row>
</>}
<Row icon="scale" iconTint="var(--teal)" title={t('Weight unit')}>