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.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
Coach: chat, log and Undo snapshots merge per entry across devices, no false nochange (#779)
Duarte Santosb82284109275
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 71cbf937f..f58ab07de 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -51,6 +51,10 @@ per muscle. Settings → Workout → Fine-tuning turns it off.- **Discard means discard, on the Apple Watch too** (#776). Discarding a workout on the phonewhile the watch follows it used to save it to Apple Health anyway, calories and all. Now thewatch drops it and Apple Health never hears about it.+- **The Coach remembers both devices** (#779, thanks for tracing it). With the Coach open on two+ devices, the one that synced last could wipe the other's chat, log and Undo history. Now they+ merge message by message, and a plan you already applied on your phone no longer gets a+ "nothing I would change" reply on your laptop.- **Imported weigh-ins stay put.** Weigh-ins you import (an Apple Health export, a Google Healthor Health Connect CSV, Strong, Hevy) are no longer written back to Apple Health or HealthConnect, where they landed a second time. Only weigh-ins you enter in openGym go out.diff --git a/api/sync-stamps.js b/api/sync-stamps.jsindex e44a55bfa..45c0e3c03 100644--- a/api/sync-stamps.js+++ b/api/sync-stamps.js@@ -31,6 +31,9 @@// device changed it loses to that change, one that sends no record of edits at all (it never// read a copy from an updated app) still wins as before, and the older app shows its own// value until it next reads the profile;+// 2b. for a writer that does not stamp: the Coach's chat, log and Undo snapshots are joined with+// the stored ones (mergeCoach), since its whole `coach` is a copy from before the other+// device's messages (#779);// 3. for every writer: an entry the document holds while a removal on record says it was// deleted after its last edit is kept, and marked as added back. An updated app never sends// such a document, so this is an older app's merge (or its Coach undo, or a backup it@@ -333,6 +336,61 @@ function stampUnstamped(cur, next, sent, now, own = null) {}}+// The Coach's chat, log and Undo snapshots (sync-merge.js mergeCoach): joined with the stored+// ones rather than replaced, for a writer that does not stamp. It keeps `coach` as one value it read+// earlier, so its push dropped every line another device had added since (#779). An Undo's log+// entry names the snapshot it used, which then stays out.+export const COACH_CAPS = { chat: 40, log: 50, snapshots: 3 };+const COACH_NAMESPACE_MAX = 256 * 1024;+export const snapshotKey = x => (isMap(x) ? (x.id != null ? String(x.id) : `${Number(x.at) || 0}|${x.proposalId ?? ''}`) : null);+const coachKey = { chat: x => (isMap(x) && x.id != null ? String(x.id) : null), log: x => (isMap(x) && x.id != null ? String(x.id) : null), snapshots: snapshotKey };+function unionInTime(xs, ys, key) {+ const seen = new Set(), out = [];+ let i = 0;+ for (const [from, l] of [[0, list(xs)], [1, list(ys)]]) {+ let at = 0;+ for (const x of l) {+ if (x == null) continue;+ const k = key(x);+ if (Number(x?.at) > 0) at = Number(x.at);+ if (k == null) { if (!from) out.push({ x, at, from, i: i++ }); continue; }+ if (seen.has(k)) continue;+ seen.add(k);+ out.push({ x, at, from, i: i++ });+ }+ }+ out.sort((a, b) => a.at - b.at || a.from - b.from || a.i - b.i);+ return out.map(e => e.x);+}+/** `win`'s Coach namespace with its chat, log and snapshots joined with `other`'s (sync-merge.js mergeCoach). */+export function mergeCoach(win, other) {+ if (!isMap(win) || !isMap(other)) return win === undefined ? win : clone(win);+ const out = clone(win);+ for (const f of ['chat', 'log', 'snapshots']) {+ if (!Array.isArray(win[f]) && !Array.isArray(other[f])) continue;+ out[f] = clone(unionInTime(win[f], other[f], coachKey[f]));+ }+ const used = new Set(), byProposal = [];+ for (const e of list(out.log)) {+ if (!isMap(e) || e.kind !== 'revert') continue;+ if (e.snap != null) used.add(String(e.snap));+ else if (e.proposalId != null) byProposal.push(e);+ }+ if (out.snapshots) {+ out.snapshots = out.snapshots.filter(x => !used.has(snapshotKey(x)) &&+ !byProposal.some(e => x?.proposalId === e.proposalId && (Number(x?.at) || 0) <= (Number(e.at) || 0)));+ }+ for (const [f, max] of Object.entries(COACH_CAPS)) if (Array.isArray(out[f]) && out[f].length > max) out[f] = out[f].slice(-max);+ let guard = 0;+ while (JSON.stringify(out).length > COACH_NAMESPACE_MAX && guard++ < 60) {+ if (list(out.chat).length > 8) out.chat.shift();+ else if (list(out.snapshots).length > 1) out.snapshots.shift();+ else if (list(out.log).length > 1) out.log.shift();+ else break;+ }+ return out;+}+const ORDER_KEY = 'routineOrder';/** Whether two lists hold the routines both have in a different order (sync-merge.js orderMoved). */export function orderMoved(a, b) {@@ -506,6 +564,7 @@ export function stampPut(cur, next, { overRead = false, stamped = false, now = Dconst rec = ownRecord(next, NaN, prevOwn, prevOwn.fp);if (rec) next._unstamped = rec;}+ if (!stamped && isMap(next.coach) && isMap(cur.coach)) next.coach = mergeCoach(next.coach, cur.coach);if (before != null && content(next) !== before) report.changed = true;}keepHeld(next, t);diff --git a/api/test/sync-stamps.test.js b/api/test/sync-stamps.test.jsindex fe62f4761..1e4e4ba99 100644--- a/api/test/sync-stamps.test.js+++ b/api/test/sync-stamps.test.js@@ -411,3 +411,24 @@ test('PUT /api/data: an older app\'s two changes of one setting in a row both laassert.ok(onDisk._unstamped?.ed?.restSec > 0);assert.equal(onDisk._prior?.restSec?.length, 2); // 100, then 120});++// #779: an older app keeps `coach` as one value read earlier, so its push dropped every Coach line,+// log entry and Undo snapshot another device had added since. They are joined with the stored ones.+test('an unstamped push keeps the Coach lines another device added, and an Undo stays used', () => {+ const cur = { ...stored(), coach: {+ cadence: 'off',+ chat: [{ id: 'c1', at: NOW - 900 }, { id: 'c2', at: NOW - 800 }],+ log: [{ id: 'l1', at: NOW - 800, kind: 'review' }],+ snapshots: [{ at: NOW - 850, proposalId: 'p1', routines: [] }, { at: NOW - 700, proposalId: 'p2', routines: [] }],+ } };+ const next = clone({ ...stored(), coach: {+ cadence: 'off',+ chat: [{ id: 'c1', at: NOW - 900 }, { id: 'a1', at: NOW - 100 }],+ log: [{ id: 'r1', at: NOW - 100, kind: 'revert', proposalId: 'p2' }],+ snapshots: [{ at: NOW - 850, proposalId: 'p1', routines: [] }],+ } });+ stampPut(cur, next, { overRead: true, stamped: false, now: NOW });+ assert.deepEqual(next.coach.chat.map(m => m.id), ['c1', 'c2', 'a1']);+ assert.deepEqual(next.coach.log.map(e => e.id), ['l1', 'r1']);+ assert.deepEqual(next.coach.snapshots.map(x => x.proposalId), ['p1']); // p2 was undone+});diff --git a/frontend/src/lib/coach.js b/frontend/src/lib/coach.jsindex 58a7351b1..672d673d1 100644--- a/frontend/src/lib/coach.js+++ b/frontend/src/lib/coach.js@@ -19,6 +19,7 @@ import { mergePlan } from './plan-share.js'import { deleteRoutine } from './routines.js'import { POLICIES } from './progression.js'import { t, tn } from './i18n.js'+import { snapshotKey } from './sync-merge.js'// Bumping this re-prompts everyone: it means what we share, or who we share it with, changed.// 2: the training line names the session notes, which the payload carries and version 1 never@@ -279,7 +280,9 @@ export function revertLast(s) {s.week = clone(snap.week)// Snapshots taken before this field existed have nothing to put back.if (snap.dayPlanRestore) Object.assign(s.dayPlan, snap.dayPlanRestore)- appendLog(s, { kind: 'revert', at: Date.now(), proposalId: snap.proposalId, summary: t('Reverted the last Coach changes.') })+ // Which snapshot this used (`snap`): the sync merge keeps it off the ring when another device's+ // copy still holds it, so the same Undo is not offered twice (lib/sync-merge.js mergeCoach).+ appendLog(s, { kind: 'revert', at: Date.now(), proposalId: snap.proposalId, snap: snapshotKey(snap), summary: t('Reverted the last Coach changes.') })return true}export const canRevert = S => !!(S?.coach?.snapshots || []).lengthdiff --git a/frontend/src/lib/sync-merge.coach.test.js b/frontend/src/lib/sync-merge.coach.test.jsnew file mode 100644index 000000000..e46c0048f--- /dev/null+++ b/frontend/src/lib/sync-merge.coach.test.js@@ -0,0 +1,173 @@+/* The Coach's history across two devices (#779). `coach` is one stamped setting, so the copy that+ changed it last used to win it whole: a device that wrote one line into its older copy dropped+ the other device's messages, log entries and Undo snapshots. These merge two diverged copies in+ both directions, the way a 409 does on either device. */+import { describe, expect, it } from 'vitest'+import { COACH_CAPS, mergeCoach, mergeStates, stampChange } from './sync-merge.js'+import { appendChat, appendLog, pushSnapshot, revertLast, CHAT_MAX, LOG_MAX, SNAPSHOT_MAX, CONSENT_VERSION } from './coach.js'+import * as server from '../../../api/sync-stamps.js'++const T = 1_800_000_000_000+const clone = o => JSON.parse(JSON.stringify(o))+const base = () => ({+ _ts: T, unit: 'kg', lang: 'en', workouts: [], bodyweight: [], customEx: [], exWeights: {}, dayPlan: {},+ routines: [{ id: 'r1', name: 'Push', ex: [{ id: '0001', sets: 3, reps: 10 }], _ts: T }], week: { 1: ['r1'] },+ coach: {+ consent: { agreedAt: '2026-07-01T00:00:00Z', version: CONSENT_VERSION }, profile: { goal: 'muscle' }, cadence: 'off',+ chat: [{ id: 'c0', role: 'user', kind: 'intake', at: T - 100 }], log: [], snapshots: [], timings: []+ },+ edited: { coach: T - 100 },+})+// A change made on one device, stamped the way the store stamps it. `wall` is that device's clock.+const change = (prev, wall, mut) => { const n = clone(prev); mut(n); n._ts = stampChange(prev, n, wall); return n }+const chatIds = S => S.coach.chat.map(m => m.id)+const logIds = S => S.coach.log.map(e => e.id)++describe('two devices talking to the Coach', () => {+ // Device A asks, B gets the proposal, applies it, asks again and applies that too; A then+ // writes its stale "nothing to change" line (the exact sequence in #779).+ const diverged = () => {+ const S0 = base()+ const B = change(change(S0, T + 10, s => {+ appendChat(s, { id: 'b1', role: 'user', kind: 'text', text: 'more legs', at: T + 10 })+ pushSnapshot(s, 'p1', 'before p1')+ s.coach.snapshots.at(-1).at = T + 11+ appendLog(s, { id: 'l1', kind: 'review', at: T + 11, proposalId: 'p1' })+ appendChat(s, { id: 'b2', role: 'coach', kind: 'applied', ref: 'l1', at: T + 12 })+ }), T + 20, s => {+ appendChat(s, { id: 'b3', role: 'user', kind: 'text', text: 'and arms', at: T + 20 })+ pushSnapshot(s, 'p2', 'before p2')+ s.coach.snapshots.at(-1).at = T + 21+ appendLog(s, { id: 'l2', kind: 'review', at: T + 21, proposalId: 'p2' })+ appendChat(s, { id: 'b4', role: 'coach', kind: 'applied', ref: 'l2', at: T + 22 })+ })+ const A = change(S0, T + 800, s => {+ appendChat(s, { id: 'a1', role: 'coach', kind: 'nochange', text: 'all good', at: T + 800 })+ })+ return { A, B }+ }++ it('keeps every line, log entry and snapshot of both, in either direction', () => {+ const { A, B } = diverged()+ for (const out of [mergeStates(A, B), mergeStates(B, A)]) {+ expect(chatIds(out)).toEqual(['c0', 'b1', 'b2', 'b3', 'b4', 'a1'])+ expect(logIds(out)).toEqual(['l1', 'l2'])+ expect(out.coach.snapshots.map(x => x.proposalId)).toEqual(['p1', 'p2'])+ }+ expect(mergeStates(A, B).coach).toEqual(mergeStates(B, A).coach)+ })++ it('the rest of the namespace still comes from the copy that changed it last', () => {+ const { A, B } = diverged()+ const B2 = change(B, T + 900, s => { s.coach.cadence = { everyWorkouts: 4 } })+ for (const out of [mergeStates(A, B2), mergeStates(B2, A)]) {+ expect(out.coach.cadence).toEqual({ everyWorkouts: 4 })+ expect(chatIds(out)).toContain('a1')+ }+ })++ it('merging again changes nothing: shared entries once', () => {+ const { A, B } = diverged()+ const once = mergeStates(A, B)+ const twice = mergeStates(once, B)+ expect(twice.coach).toEqual(once.coach)+ expect(new Set(chatIds(twice)).size).toBe(chatIds(twice).length)+ })++ it('keeps the newest ones within the caps', () => {+ const S0 = base()+ const many = (prev, wall, tag) => change(prev, wall, s => {+ for (let i = 0; i < 35; i++) {+ appendChat(s, { id: `${tag}${i}`, role: 'user', kind: 'text', text: 'x', at: wall + i * 2 })+ appendLog(s, { id: `L${tag}${i}`, kind: 'review', at: wall + i * 2 })+ }+ for (let i = 0; i < 3; i++) { pushSnapshot(s, `${tag}p${i}`); s.coach.snapshots.at(-1).at = wall + i }+ })+ const A = many(S0, T + 1, 'a'), B = many(S0, T + 2, 'b')+ for (const out of [mergeStates(A, B), mergeStates(B, A)]) {+ expect(out.coach.chat).toHaveLength(CHAT_MAX)+ expect(out.coach.log).toHaveLength(LOG_MAX)+ expect(out.coach.snapshots).toHaveLength(SNAPSHOT_MAX)+ expect(chatIds(out).at(-1)).toBe('b34') // the newest stays+ expect(chatIds(out)).not.toContain('c0') // the oldest goes first+ }+ })++ it('an Undo used on one device is not offered again by the other', () => {+ const { B } = diverged()+ // Both devices synced; then A undoes p2 while B, offline, chats on.+ const A = change(B, T + 1000, s => { expect(revertLast(s)).toBe(true) })+ const B2 = change(B, T + 1001, s => { appendChat(s, { id: 'b5', role: 'user', kind: 'text', at: T + 1001 }) })+ for (const out of [mergeStates(A, B2), mergeStates(B2, A)]) {+ expect(out.coach.snapshots.map(x => x.proposalId)).toEqual(['p1'])+ expect(chatIds(out)).toContain('b5')+ expect(out.coach.log.some(e => e.kind === 'revert')).toBe(true)+ }+ })++ it('an older app’s Undo (no snapshot named) still takes its snapshot off', () => {+ const { B } = diverged()+ const A = change(B, T + 1000, s => {+ s.coach.snapshots.pop()+ s.coach.log.push({ id: 'r', kind: 'revert', at: T + 1000, proposalId: 'p2' })+ })+ expect(mergeStates(B, A).coach.snapshots.map(x => x.proposalId)).toEqual(['p1'])+ })++ it('a reset this copy has not seen takes its Coach history with it', () => {+ const { B } = diverged()+ const R = change(base(), T + 2000, s => { s.coach.chat = []; s.coach.log = []; s.coach.snapshots = [] })+ R.resetAt = T + 2000+ const R2 = change(R, T + 2100, s => appendChat(s, { id: 'n1', role: 'user', kind: 'text', at: T + 2100 }))+ const B2 = change(B, T + 2200, s => appendChat(s, { id: 'late', role: 'user', kind: 'text', at: T + 2200 }))+ for (const out of [mergeStates(R2, B2), mergeStates(B2, R2)]) {+ expect(chatIds(out)).toEqual(['n1', 'late']) // only what came after the reset+ expect(out.coach.snapshots).toEqual([])+ }+ })++ it('a sign-in (prefer) keeps the preferred side as it is', () => {+ const { A, B } = diverged()+ expect(chatIds(mergeStates(A, B, { prefer: 'b' }))).toEqual(chatIds(B))+ })+})++describe('the server joins what an older app sends', () => {+ it('an unstamped push of an older coach copy keeps the stored lines', () => {+ const stored = base()+ stored.coach.chat.push({ id: 'b1', role: 'user', kind: 'text', at: T + 10 })+ stored.coach.log.push({ id: 'l1', kind: 'review', at: T + 11 })+ const sent = clone(base())+ sent.coach.chat.push({ id: 'a1', role: 'coach', kind: 'nochange', at: T + 20 })+ server.stampPut(stored, sent, { overRead: true, stamped: false, now: T + 30 })+ expect(sent.coach.chat.map(m => m.id)).toEqual(['c0', 'b1', 'a1'])+ expect(sent.coach.log.map(e => e.id)).toEqual(['l1'])+ })++ it('an app that stamps its own changes merged already, and is taken as sent', () => {+ const stored = base()+ stored.coach.chat.push({ id: 'b1', role: 'user', kind: 'text', at: T + 10 })+ const sent = clone(base())+ server.stampPut(stored, sent, { overRead: true, stamped: true, now: T + 30 })+ expect(sent.coach.chat.map(m => m.id)).toEqual(['c0'])+ })++ it('matches the app’s mergeCoach and caps', () => {+ expect(server.COACH_CAPS).toEqual(COACH_CAPS)+ expect(COACH_CAPS).toEqual({ chat: CHAT_MAX, log: LOG_MAX, snapshots: SNAPSHOT_MAX })+ let seed = 7+ const R = () => { seed = (seed * 1103515245 + 12345) % 2147483648; return seed / 2147483648 }+ for (let n = 0; n < 200; n++) {+ const side = () => ({+ cadence: R() < 0.5 ? 'off' : { everyWorkouts: 4 },+ chat: Array.from({ length: Math.floor(R() * 50) }, () => ({ id: 'c' + Math.floor(R() * 60), at: Math.floor(R() * 100) })),+ log: Array.from({ length: Math.floor(R() * 60) }, () => R() < 0.1+ ? { id: 'r' + Math.floor(R() * 9), kind: 'revert', at: Math.floor(R() * 100), ...(R() < 0.5 ? { snap: `${Math.floor(R() * 5)}|p` } : { proposalId: 'p' }) }+ : { id: 'l' + Math.floor(R() * 70), at: Math.floor(R() * 100) }),+ snapshots: Array.from({ length: Math.floor(R() * 4) }, () => ({ at: Math.floor(R() * 5), proposalId: 'p', routines: [] })),+ })+ const a = side(), b = side()+ expect(server.mergeCoach(clone(a), clone(b))).toEqual(mergeCoach(clone(a), clone(b)))+ }+ })+})diff --git a/frontend/src/lib/sync-merge.js b/frontend/src/lib/sync-merge.jsindex 8bd5b7db8..8a900675c 100644--- a/frontend/src/lib/sync-merge.js+++ b/frontend/src/lib/sync-merge.js@@ -219,6 +219,82 @@ export function stampWorkout(w, now = Date.now()) {const stampOf = v => (v && typeof v === 'object' ? Number(v._ts) || 0 : 0)const isMap = v => !!v && typeof v === 'object' && !Array.isArray(v)+// ---- The Coach's history (`coach.chat`, `coach.log`, `coach.snapshots`) -----------------------+//+// `coach` is one setting to the stamps (`edited.coach`), so the copy that changed it last used to+// win it whole: a device that had sat on the Coach screen wrote one line into its older copy, and+// the other device's messages, log entries and Undo snapshots were gone (#779). These three lists+// only ever grow at the end, so they are joined instead: every entry of either copy once (by `id`,+// a snapshot by when it was taken and for which proposal), in the order they were written (`at`),+// and the newest few kept as lib/coach.js keeps them. The rest of `coach` (consent, profile,+// cadence) still comes from the copy that changed it last.+//+// An Undo takes a snapshot off the ring. Its log entry names the snapshot it used (`snap`, or for+// an older app the proposal it put back), and a snapshot so named never comes back from the copy+// that still holds it: that would offer the same Undo twice.+// The bounds of lib/coach.js (SNAPSHOT_MAX, LOG_MAX, CHAT_MAX, NAMESPACE_MAX), copied rather than+// imported: coach.js pulls in the plan code, the merge must not. sync-merge.test.js checks them.+export const COACH_CAPS = { chat: 40, log: 50, snapshots: 3 }+const COACH_NAMESPACE_MAX = 256 * 1024+export const snapshotKey = x => (isMap(x) ? (x.id != null ? String(x.id) : `${Number(x.at) || 0}|${x.proposalId ?? ''}`) : null)+const coachKey = { chat: x => (isMap(x) && x.id != null ? String(x.id) : null), log: x => (isMap(x) && x.id != null ? String(x.id) : null), snapshots: snapshotKey }++// `xs` then `ys`, each key once (first wins), in the order written: by `at`, and an entry without+// one where it stood after its predecessor. Keyless entries stay, from `xs` only.+function unionInTime(xs, ys, key) {+ const seen = new Set(), out = []+ let i = 0+ for (const [from, l] of [[0, list(xs)], [1, list(ys)]]) {+ let at = 0+ for (const x of l) {+ if (x == null) continue+ const k = key(x)+ if (Number(x?.at) > 0) at = Number(x.at)+ if (k == null) { if (!from) out.push({ x, at, from, i: i++ }); continue }+ if (seen.has(k)) continue+ seen.add(k)+ out.push({ x, at, from, i: i++ })+ }+ }+ out.sort((a, b) => a.at - b.at || a.from - b.from || a.i - b.i)+ return out.map(e => e.x)+}++/**+ * The Coach namespace of two copies: `win`'s (the copy that changed it last), with its chat, log+ * and Undo snapshots joined with `other`'s (see above). Returns a new object, or `win` as it is+ * when either side has no namespace to join.+ */+export function mergeCoach(win, other) {+ if (!isMap(win) || !isMap(other)) return win === undefined ? win : clone(win)+ const out = clone(win)+ for (const f of ['chat', 'log', 'snapshots']) {+ if (!Array.isArray(win[f]) && !Array.isArray(other[f])) continue+ out[f] = clone(unionInTime(win[f], other[f], coachKey[f]))+ }+ // Snapshots an Undo on either side already used.+ const used = new Set(), byProposal = []+ for (const e of list(out.log)) {+ if (!isMap(e) || e.kind !== 'revert') continue+ if (e.snap != null) used.add(String(e.snap))+ else if (e.proposalId != null) byProposal.push(e)+ }+ if (out.snapshots) {+ out.snapshots = out.snapshots.filter(x => !used.has(snapshotKey(x)) &&+ !byProposal.some(e => x?.proposalId === e.proposalId && (Number(x?.at) || 0) <= (Number(e.at) || 0)))+ }+ for (const [f, max] of Object.entries(COACH_CAPS)) if (Array.isArray(out[f]) && out[f].length > max) out[f] = out[f].slice(-max)+ // The namespace's own size guard (lib/coach.js trim), the same oldest-first order.+ let guard = 0+ while (JSON.stringify(out).length > COACH_NAMESPACE_MAX && guard++ < 60) {+ if (list(out.chat).length > 8) out.chat.shift()+ else if (list(out.snapshots).length > 1) out.snapshots.shift()+ else if (list(out.log).length > 1) out.log.shift()+ else break+ }+ return out+}+// ---- Entries merged field by field ----------------------------------------------------------//// A workout, routine, custom exercise, equipment profile or gym card edited on two devices kept@@ -479,6 +555,13 @@ export function sinceReset(S, at, ids) {}}out.exWeights = ex+ // The Coach's history is joined, not replaced (mergeCoach), so what this copy said to the Coach+ // before the reset goes here: only lines, log entries and snapshots from after it stay.+ if (isMap(out.coach)) {+ for (const f of ['chat', 'log', 'snapshots']) {+ if (Array.isArray(out.coach[f])) out.coach[f] = out.coach[f].filter(x => (Number(x?.at) || 0) > at)+ }+ }// The reset copy's settings, plan and unit win whatever this copy's own stamps say (the file's// header): stamps from before the reset would otherwise outrank the fresh profile's defaults,// a unit switch made long ago would bring the old unit back over the reset's.@@ -870,6 +953,12 @@ export function mergeStates(a0, b0, { prefer } = {}) {if (m && !(k in bumps)) undone[k] = clone(m)}if (Object.keys(undone).length) out.undone = undone; else delete out.undone+ // The Coach's conversation, log and Undo snapshots from both copies (mergeCoach), whichever+ // changed `coach` last.+ if (isMap(out.coach)) {+ const other = sameJSON(out.coach, n.coach) ? o.coach : n.coach+ if (isMap(other)) out.coach = mergeCoach(out.coach, other)+ }}if (deleted) out.deleted = deleted; else delete out.deletedout._ts = Math.max(a._ts || 0, b._ts || 0)diff --git a/frontend/src/views/CoachChat.jsx b/frontend/src/views/CoachChat.jsxindex 705066f83..3a8e1b496 100644--- a/frontend/src/views/CoachChat.jsx+++ b/frontend/src/views/CoachChat.jsx@@ -90,7 +90,10 @@ export default function CoachChat() {update(s => {// A run that ended unseen has no duration worth learning from.if (was) recordTiming(s, ms)- if (!pending) {+ // A proposal already applied or discarded was settled on another device (#779): its reply is+ // in that device's thread, which syncs here. "Nothing I would change" would be wrong.+ const settled = last?.outcome === 'applied' || last?.outcome === 'dismissed' || last?.outcome === 'ready'+ if (!pending && !settled) {const cls = lastError?.errorClass || (last?.outcome === 'failed' ? (last.errorClass || 'internal') : null)appendChat(s, cls? { role: 'coach', kind: 'error', text: jobErrorText(cls, lastError?.detail) }diff --git a/frontend/src/views/CoachChat.settled-elsewhere.test.jsx b/frontend/src/views/CoachChat.settled-elsewhere.test.jsxnew file mode 100644index 000000000..220ded6f2--- /dev/null+++ b/frontend/src/views/CoachChat.settled-elsewhere.test.jsx@@ -0,0 +1,123 @@+// @vitest-environment happy-dom+import React, { act } from 'react'+import { createRoot } from 'react-dom/client'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import CoachChat from './CoachChat.jsx'+import { CONSENT_VERSION } from '../lib/coach.js' // the consent a fixture grants is the current one, whatever its number+import { requestPlan, settleAwaited } from '../lib/coach-api.js'++// A run that fails before the first status poll. A provider that refuses the connection fails+// the job in milliseconds, so by the time the chat asks for the status the job is already gone+// and the server's last outcome is `failed` / `provider`. The chat used to write a reply only+// when it had seen the job running and then gone, so these runs ended with no reply at all —+// three questions in a row, three silences. The real lib/coach-api.js runs here; only the HTTP+// layer is faked, answering the way the server does.+const mocks = vi.hoisted(() => {+ const state = { S: null, nav: vi.fn(), toast: vi.fn(), openSheet: vi.fn(), server: null, statusGate: null }+ state.storeSnapshot = () => ({+ S: state.S, user: { id: 'u1' }, ready: true,+ config: { coach: { enabled: true } }, coachLocal: null,+ update: mut => mut(state.S),+ })+ state.uiSnapshot = () => ({ toast: state.toast, openSheet: state.openSheet })+ return state+})++vi.mock('../store/useStore.js', () => {+ const useStore = selector => selector(mocks.storeSnapshot())+ useStore.getState = mocks.storeSnapshot+ return { useStore }+})+vi.mock('../store/useUI.js', () => {+ const useUI = selector => (selector ? selector(mocks.uiSnapshot()) : mocks.uiSnapshot())+ useUI.getState = mocks.uiSnapshot+ return { useUI }+})+vi.mock('react-router-dom', () => ({ useNavigate: () => mocks.nav }))+vi.mock('../sheets.jsx', () => ({ startFlow: vi.fn(), confirmSheet: vi.fn() }))+vi.mock('../coach.css', () => ({}))+// The server: a start bumps the day's count and the run ends at once, with `server.outcome`.+vi.mock('../lib/api.js', () => ({+ IS_APPLE: false, IS_ANDROID: false, BIO: 'biometrics',+ api: vi.fn(async (path, opts) => {+ const srv = mocks.server+ if (path === '/api/coach/status') {+ const snap = { job: null, pending: null, cap: { used: srv.used, limit: 10 }, last: srv.last, maxMessageLen: 1000 }+ if (mocks.statusGate) { const gate = mocks.statusGate; mocks.statusGate = null; await gate }+ return snap+ }+ if (opts?.method === 'POST' && /^\/api\/coach\/(review|plan|debrief)$/.test(path)) {+ const id = 'job' + (++srv.n)+ srv.used+++ srv.last = { id, kind: path.endsWith('plan') ? 'create' : 'review', outcome: srv.outcome, errorClass: null, at: Date.now() }+ return { job: { id } }+ }+ return {}+ }),+}))++let root, container++function installDom() {+ document.body.innerHTML = '<div id="root"></div>'+ globalThis.IS_REACT_ACT_ENVIRONMENT = true+ container = document.getElementById('root')+ root = createRoot(container)+}+const flush = async () => { for (let i = 0; i < 30; i++) await Promise.resolve() }+const settle = async () => { await act(async () => { await flush() }) }+const chip = re => [...container.querySelectorAll('.qchip')].find(b => re.test(b.textContent || ''))+async function click(el) {+ expect(el).toBeTruthy()+ await act(async () => { el.dispatchEvent(new MouseEvent('click', { bubbles: true })); await flush() })+}+async function mount() {+ installDom()+ await act(async () => { root.render(React.createElement(CoachChat)) })+ await settle()+}++const state = routines => ({+ unit: 'kg', lang: 'en', customEx: [], workouts: [{ id: 'w1', name: 'Push Day', d: '2026-09-01', entries: [] }], bodyweight: [], exWeights: {},+ dayPlan: {}, routines, week: {},+ coach: {+ consent: { agreedAt: '2026-07-01T00:00:00Z', version: CONSENT_VERSION },+ profile: { goal: 'muscle', experience: 'new', daysPerWeek: 3, sessionMin: 60, preferredDays: [1, 3, 5], equipment: [] },+ log: [], snapshots: [], chat: [{ id: 'c1', role: 'user', kind: 'intake', at: 1 }], timings: []+ },+})+const routine = { id: 'r1', name: 'Day A', ex: [{ id: '0001', sets: 3, reps: 10 }, { id: '0002', sets: 3, reps: 10 }] }+const replies = () => mocks.S.coach.chat.filter(m => m.role === 'coach')++beforeEach(() => {+ vi.clearAllMocks()+ settleAwaited()+ mocks.statusGate = null+ mocks.server = { n: 0, used: 4, outcome: 'nochange', last: { id: 'old', kind: 'review', outcome: 'nochange', at: 1 } }+})+afterEach(async () => {+ if (root) { await act(async () => { root.unmount() }); root = null }+ container = null+})++describe('a Coach run settled on another device', () => {+ it('a run that really found nothing says so', async () => {+ mocks.S = state([routine])+ await mount()+ await click(chip(/Review my training/))+ expect(replies()).toHaveLength(1)+ expect(replies()[0]).toMatchObject({ kind: 'nochange' })+ })++ for (const outcome of ['applied', 'dismissed']) {+ it(`a proposal already ${outcome} elsewhere gets no false "nothing to change"`, async () => {+ mocks.S = state([routine])+ mocks.server.outcome = outcome+ await mount()+ await click(chip(/Review my training/))+ await settle()+ expect(mocks.S.coach.chat.at(-1)).toMatchObject({ role: 'user', kind: 'text' })+ expect(replies()).toHaveLength(0)+ })+ }+})