diff --git a/AGENTS.md b/AGENTS.md index d38f5f1..5b7849e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -109,7 +109,7 @@ reasons behind the design, and the things that have been removed on purpose. | The session sheet | `app/src/sheet.jsx`, `app/src/sheetparts.jsx` | `SessionSheet` (header, body, footer) and `runnable`; Today (`tabs.jsx`) opens it. `sheetparts.jsx` is what every sheet of a workout shares (#80): `DoneChip`, `useDoneFlip` (the flip and its Undo toast) and `SheetStart` (the one footer action), used by the owner's sheet and `PersonEntrySheet`. The row meta line both use is `app/src/metaline.jsx`. Twins: `mobile/src/features/sheet.tsx`, `sheetparts.tsx`. | | Prescription editor | `app/src/editor.jsx` | `PrescriptionEditor` (`doing` on the sheet, #79), its blocks and items, `BlockMenu` (a block's ⋯), `blockTag`, `PieceAdder`, `BlockQuota`: the one editor Plan a workout and the sheet share. Block operations are `addBlock`, `renameBlock`, `noteBlock`, `removeBlock`, `moveBlock` in `lib/prescription.js`. Twin: `mobile/src/features/editor.tsx` (the ⋯ is the system action sheet). | | Day switcher | `app/src/tabs.jsx` (`DaySwitcher`; `dayWords`, `isoShift` in `lib/dates.js`) | ‹ day › in words; Today's title and the rest day's date (§10.9). The phone's is `mobile/src/ui/DayStepper.tsx`. | -| Session history | `app/src/lib/history.js` | `priorSessions`: which earlier entries are THIS workout ("The last 5 times you did this"). A card by its ids (`aka`, `priorIds`); a planned workout by its title or mostly the same exercises; a free-form one by its activity (#74). | +| Session history | `app/src/lib/history.js` | `priorSessions`: which earlier entries are THIS workout ("The last 5 times you did this"), before the one shown in the day list's order (#96: an earlier day, or an earlier session of the same day). A card by its ids (`aka`, `priorIds`); a planned workout by its title or mostly the same exercises; a free-form one by its activity (#74). | | Toasts | `app/src/toast.jsx`, `app/src/lib/toast.js` | Mobile's API (`pushToast`, `pushError`) on the web: a removal's Undo, a failed save's Retry. | | Log feed | `app/src/log.jsx` | Newest first; the open sheet is keyed by ID and is `LogSheet`: Today's `SessionSheet`, with no Start (#79). | | Progress | `app/src/lib/scope.js`, `app/src/lib/metrics.js`, `app/src/progress.jsx` | Charts declare when they apply. | @@ -444,9 +444,33 @@ section keeps only the keys `blank()` names, so a removed setting is dropped on through the owner's store or cache, so logs still never mix on a device. The server refuses non-owners, acting-as, the owner's own log, and any live entry without `sharedFrom` (`not-shared`); a sync never writes into an entry they logged themselves. - Those writes fire no habit sync and no push. Taking someone off tombstones their copy - only if they have marked nothing (`hasOwnMarks`; copied lifts with nothing marked on - them are not marks), otherwise it asks. WHOOP/Strava stay off on their side. + Those writes fire no habit sync and no push. **Taking someone off never deletes what + they logged** (#96): a copy they have marked (`hasOwnMarks`; copied lifts with nothing + marked on them are not marks) stays in their log as their own workout, unlinked (the + server flags it not in step); one they never touched is tombstoned. No question either + way: a toast says which, with Undo (`removePerson`, `takeOffWords`, `undoTakeOff`). It + used to tombstone a logged copy after a bare browser confirm, with no Undo. A kept copy + is then theirs: the server stamps it `sharedFrom.off` when the link goes (`flagCopy`, + `withOff`; cleared when a link is back) and refuses the owner's writes to it through the + people route (409 `not-linked`). A copy never linked yet is not refused, because adding + someone writes the copy first and links it second. WHOOP/Strava stay off on their side. + - **A copy shows its person nothing the planner wrote for the owner** (#96): the plan's + `why`, `notes`, `thread`, `ask` and `changed`, and the note on each exercise and set + ("3x10 at 95 was RPE 6 last time"), are the owner's (the owner's recovery and weights, + in the owner's words). A share leaves them out (`theirPlan`), and the sheet and the + runner read a plan through `planShown(entry)`, which hides them on any entry with + `sharedFrom`, so copies shared before the share stripped them are covered without + rewriting them. A block's note stays: it is the workout's prose and shared structure. + **Display only**: every write from those screens (the editor on either side, the + runner's added set) goes through `withStoredWords`, which puts each hidden word back + byte for byte, so an edit lands on the stored plan and erases nothing (review 2: the + first version saved the filtered plan and lost the notes for good). What the person + asks the model on their own copy is theirs: + the sheet stamps it `ownWords` (`ownWordsOn`) and such a plan is shown whole. + An older copy's form also reads the activity its plan files it under (`formOut` in + lib/category.js, the form's twin of `filedOut`), so it no longer asks "What kind of + workout was this?" with nothing picked. A removal on the other person's own copy says + the synced line about the owner (`syncedSides`), because it reaches the owner's log too. - Pinned by `server/sharedsync.test.js`, the `shared workouts:` and `sync:` steps in `server/http.test.js`, `app/shared.test.js`, and the `SessionSheet(… sharing chip …)`, `SharePanel(…)`, person bar, `PersonSwitch(…)` and `TheirSide` smoke cases. @@ -513,6 +537,11 @@ section keeps only the keys `blank()` names, so a removed setting is dropped on as "Sam already logged it" / "Sam is running it": not a miss, no Retry. Totals are read off what is there (`run.circuitTimes`, set per block), never added to. The shared-sync rule again: logged data is never removed by anyone else's write. + A blank is filled in the shape the CLOCK ran it (#96): the result names how each + exercise was timed (`togetherItems`, `by`), and one counted in reps on the side that + ran it is a count where this side's own timing is blank (`endCircuit` `counted`), + never a hold of the seconds spent on its reps. A side that says reps or seconds + keeps its own shape. 2. **It decides from fresh data.** Someone else's side is re-read from the server right before it is written and rule 1 applied to THAT, never to a copy on screen that may hold a write that never landed. This run's key (the clock's `startedAt`, diff --git a/app/circuit.test.js b/app/circuit.test.js index 5095ab2..c138063 100644 --- a/app/circuit.test.js +++ b/app/circuit.test.js @@ -22,7 +22,7 @@ import { import { localIso } from './src/lib/dates.js' import { liftMeasure, liftSummary } from './src/lib/lifts.js' import { - shareCircuit, togetherWrite, togetherSides, togetherWords, togetherSaid, applyRun, notePending, pendingFor, retryPending, + shareCircuit, togetherItems, togetherWrite, togetherSides, togetherWords, togetherSaid, applyRun, notePending, pendingFor, retryPending, sideTaken, PENDING_KEY, STALE_CLOCK_MS, } from './src/lib/trainer.js' import { fillOut } from './src/lib/prescription.js' @@ -487,6 +487,48 @@ ta('together, finished: both done and ended, the same seconds, one write each, e assert.deepEqual(togetherSaid('you', [{ id: 'sam', name: 'Sam', status: 'logged' }]).head, 'Logged for you and Sam') }) +ta('together: a count on the side that ran it is a count on the other, even where it arrived blank (#96)', async () => { + const { result: old, owner } = finished() + // How the runner names the exercises now: how the clock ran each one. + const result = { ...old, items: togetherItems(owner.data.plan.blocks[0]) } + assert.deepEqual(result.items.map(x => x.by), ['reps', 'time']) + // Sam's crunch came over the sync blank (no reps, no seconds): the circuit's own timing on Sam's side. + const sam = samOf() + const blankPlan = normalizePrescription({ title: 'Abs', blocks: [{ uid: 'B1', name: 'Abs', circuit: { work: 40, rest: 20, rounds: 2, countIn: 0 }, items: [ + { uid: 'CR', kind: 'lift', name: 'Crunch', exercise: 'crunch', sets: [{}] }, + { uid: 'PL', kind: 'lift', name: 'Plank', exercise: 'plank', sets: [{ seconds: 30 }] }, + ] }] }, { liftField }) + assert.equal(circuitTiming(blankPlan.blocks[0].items[0]).by, 'circuit', 'the fixture is not a blank arrival') + const srv = server({ ...sam, data: { ...sam.data, plan: blankPlan } }) + await share(srv, result, owner) + assert.deepEqual(rowsOf(srv.entry), [['crunch', [[null, '', ''], [null, '', '']]], ['plank', [[30, null, ''], [30, null, '']]]], + 'the crunches landed as holds of the seconds spent on them') + assert.equal(srv.entry.data.run.sets[blankPlan.blocks[0].items[0].sets[0].id].seconds, undefined) +}) + +ta('together: a side that holds what the other counted keeps its own shape, seconds (#96 review)', async () => { + const { result: old, owner } = finished() + const result = { ...old, items: togetherItems(owner.data.plan.blocks[0]) } + // The owner counts the crunches; Sam holds them 45 s (a wall sit counted one way, held the other). + const sam = samOf() + const held = normalizePrescription({ title: 'Abs', blocks: [{ uid: 'B1', name: 'Abs', circuit: { work: 40, rest: 20, rounds: 2, countIn: 0 }, items: [ + { uid: 'CR', kind: 'lift', name: 'Crunch', exercise: 'crunch', sets: [{ seconds: 45 }] }, + { uid: 'PL', kind: 'lift', name: 'Plank', exercise: 'plank', sets: [{ seconds: 30 }] }, + ] }] }, { liftField }) + assert.equal(circuitTiming(held.blocks[0].items[0]).by, 'time') + const srv = server({ ...sam, data: { ...sam.data, plan: held } }) + await share(srv, result, owner) + assert.deepEqual(rowsOf(srv.entry)[0], ['crunch', [[25, null, ''], [25, null, '']]], 'Sam\'s hold became blank reps') + // And Sam counting what the owner held stays a count. + const counts = normalizePrescription({ title: 'Abs', blocks: [{ uid: 'B1', name: 'Abs', circuit: { work: 40, rest: 20, rounds: 2, countIn: 0 }, items: [ + { uid: 'CR', kind: 'lift', name: 'Crunch', exercise: 'crunch', sets: [{ reps: 15 }] }, + { uid: 'PL', kind: 'lift', name: 'Plank', exercise: 'plank', sets: [{ reps: 10 }] }, + ] }] }, { liftField }) + const srv2 = server({ ...sam, data: { ...sam.data, plan: counts } }) + await share(srv2, result, owner) + assert.deepEqual(rowsOf(srv2.entry)[1], ['plank', [[null, '', ''], [null, '', '']]], 'Sam\'s count became a hold') +}) + ta('together, stopped early: what was done lands on both, the same, one write', async () => { // The crunches tapped at 25 s, 20 s rest, then stopped 12 s into the plank. const { result, owner } = hosted(throughTo(25 + 20 + 12)) diff --git a/app/history.test.js b/app/history.test.js index 82da906..90d947f 100644 --- a/app/history.test.js +++ b/app/history.test.js @@ -79,6 +79,34 @@ test('times you DID it: not a plan still to come or untouched today, not one mar assert.deepEqual(dates(priorSessions([...LOGBOOK, ahead, undone], PLANNED, PULL.id)), ['2026-10-20 Pull day', '2026-10-10 Pull day']) }) +test('a past workout’s last times are the ones before it, never after (#96)', () => { + const oct20 = LOGBOOK.find(e => e.date === '2026-10-20') + assert.deepEqual(dates(priorSessions(LOGBOOK, PLANNED, oct20.id)), ['2026-10-10 Pull day'], 'Nov 7’s Pull listed as an earlier time') + // The same day, in the day list's order: the main session, then the extras by id. + const day = (id, slot, name) => ({ ...planned('2026-11-12', name, ['bent-over-row', 'dumbbell-curl', 'pull-up'], {}), id, + data: { ...planned('2026-11-12', name, ['bent-over-row', 'dumbbell-curl', 'pull-up']).data, slot } }) + const am = day('daily-2026-11-12', 'main', 'Pull AM') + const pm = day('daily-2026-11-12-planned', 'extra', 'Pull PM') + const late = day('daily-2026-11-12-planned-2', 'extra', 'Pull late') + const log = [...LOGBOOK, am, pm, late] + assert.deepEqual(dates(priorSessions(log, PLANNED, pm.id)).slice(0, 2), ['2026-11-12 Pull AM', '2026-11-07 Pull'], 'earlier today is gone, or not first') + assert.deepEqual(dates(priorSessions(log, PLANNED, late.id)).slice(0, 3), ['2026-11-12 Pull PM', '2026-11-12 Pull AM', '2026-11-07 Pull']) + assert.equal(dates(priorSessions(log, PLANNED, am.id)).some(d => d.startsWith('2026-11-12')), false, 'a later session of the same day listed as before') + // Where both say when they started, that decides: an extra done at seven beats the main one at six in the evening. + const at = (e, iso, how) => ({ ...e, data: { ...e.data, ...(how === 'run' ? { run: { startedAt: Date.parse(iso) } } : { out: { ...e.data.out, whoop: { start: iso } } }) } }) + const timed = [...LOGBOOK, at(am, '2026-11-12T18:00:00Z', 'run'), at(pm, '2026-11-12T07:00:00Z', 'whoop'), late] + assert.deepEqual(dates(priorSessions(timed, PLANNED, am.id)).slice(0, 2), ['2026-11-12 Pull PM', '2026-11-07 Pull'], 'the earlier start is not "before"') + assert.equal(dates(priorSessions(timed, PLANNED, pm.id)).some(d => d.startsWith('2026-11-12')), false) + // Untimed itself, the late extra still comes after both by the day list; between them, their times say + // the main one (18:00) is the newer. + assert.deepEqual(dates(priorSessions(timed, PLANNED, late.id)).slice(0, 3), ['2026-11-12 Pull AM', '2026-11-12 Pull PM', '2026-11-07 Pull']) + // A card with no entry to stand on is not bounded. + const board = { id: 'board' } + const e = (date) => ({ id: date, kind: 'daily', date, data: { optId: 'board', done: true, out: {} } }) + assert.equal(priorSessions([e('2026-11-01'), e('2026-10-01')], board, null).length, 2) + assert.deepEqual(priorSessions([e('2026-11-01'), e('2026-10-01')], board, '2026-10-01').map(x => x.date), []) +}) + test('a card that is not a container is still its own history, renames and splits included', () => { const board = { id: 'board', aka: ['old-board'], priorIds: ['hard-home'] } assert.deepEqual(priorIdsOf(board), ['board', 'old-board', 'hard-home']) diff --git a/app/shared.test.js b/app/shared.test.js index e2bc7d5..5736a11 100644 --- a/app/shared.test.js +++ b/app/shared.test.js @@ -1,12 +1,15 @@ // Shared workouts: one workout, two logs. What is copied, which id the copy // takes, and when taking someone off asks first. See src/lib/shared.js. import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' import { sharePeople, sharedWithOf, sharedPeopleOn, withLine, sharedOut, hasOwnMarks, copyIdFor, sharedCopy, withSharedPerson, addPerson, removePerson, copyExercises, hasExercises, - isSynced, withSync, openSide, inStep, inStepLine, shareSummary, + isSynced, withSync, openSide, inStep, inStepLine, shareSummary, takeOffWords, undoTakeOff, + planShown, syncedSides, ownWordsOn, withStoredWords, } from './src/lib/shared.js' import { withAck, adoptAcks } from './src/lib/store.js' +import { formOut, categoryOf } from './src/lib/category.js' import { createCopyQueue, openedCopy } from './src/lib/copyqueue.js' import { patchSet, dropEmptyBlocks, keepTyped } from './src/lib/prescription.js' @@ -150,25 +153,53 @@ test('adding over their own session lands as an extra on their day', async () => assert.equal(sharedWithOf(ownerEntry)[0].entryId, 'daily-2026-10-05-log-workout') }) -test('taking them off: quiet when they have marked nothing, asks first when they have', async () => { +test('taking them off: an untouched copy goes; a logged one stays in their log, unlinked, never asked about (#96)', async () => { const api = fakeApi() const added = (await addPerson({ ownerEntry: ride, person: PEOPLE[1], session: workoutCard, api })).ownerEntry - let asked = 0 - const no = async () => { asked++; return false } - const quiet = await removePerson({ ownerEntry: added, person: PEOPLE[1], session: workoutCard, api, confirmFn: no }) - assert.equal(asked, 0, 'asked about an untouched copy') - assert.equal(api.log.get(ride.id).deleted, true, 'not a tombstone') - assert.equal(quiet.data.sharedWith, undefined) + const quiet = await removePerson({ ownerEntry: added, person: PEOPLE[1], session: workoutCard, api }) + assert.equal(api.log.get(ride.id).deleted, true, 'an untouched copy is not a tombstone') + assert.equal(quiet.kept, false) + assert.equal(quiet.ownerEntry.data.sharedWith, undefined) + assert.equal(takeOffWords(PEOPLE[1], quiet), 'Took Sam off this workout') const api2 = fakeApi() const added2 = (await addPerson({ ownerEntry: ride, person: PEOPLE[1], session: workoutCard, api: api2 })).ownerEntry - api2.log.set(ride.id, { ...api2.log.get(ride.id), data: { ...api2.log.get(ride.id).data, done: true } }) - assert.equal(await removePerson({ ownerEntry: added2, person: PEOPLE[1], session: workoutCard, api: api2, confirmFn: no }), null) - assert.equal(asked, 1) - assert.equal(api2.log.get(ride.id).deleted, undefined, 'a no still removed their done session') - const yes = await removePerson({ ownerEntry: added2, person: PEOPLE[1], session: workoutCard, api: api2, confirmFn: async () => true }) - assert.equal(api2.log.get(ride.id).deleted, true) - assert.equal(yes.data.sharedWith, undefined) + const logged = { ...api2.log.get(ride.id), data: { ...api2.log.get(ride.id).data, done: true, out: { rpe: 6 } } } + api2.log.set(ride.id, logged) + const puts = api2.calls.filter(c => c[0] === 'put').length + const taken = await removePerson({ ownerEntry: added2, person: PEOPLE[1], session: workoutCard, api: api2 }) + assert.equal(taken.kept, true) + assert.equal(api2.log.get(ride.id).deleted, undefined, 'their logged workout was deleted from the owner\'s phone') + assert.equal(api2.log.get(ride.id).data.out.rpe, 6) + assert.equal(api2.calls.filter(c => c[0] === 'put').length, puts, 'a kept copy was written') + assert.equal(taken.ownerEntry.data.sharedWith, undefined, 'the link stayed') + assert.match(takeOffWords(PEOPLE[1], taken), /stays in Sam\u2019s log with what Sam logged/) + assert.equal(await removePerson({ ownerEntry: taken.ownerEntry, person: PEOPLE[1], api: api2 }), null, 'not on it') +}) + +test('Undo of taking them off puts back the link as it was, and an untouched copy (#96)', async () => { + const api = fakeApi() + const added = (await addPerson({ ownerEntry: ride, person: PEOPLE[1], session: workoutCard, api })).ownerEntry + const unsynced = withSync(added, 'sam', false) + const copyBefore = api.log.get(ride.id) + const taken = await removePerson({ ownerEntry: unsynced, person: PEOPLE[1], session: workoutCard, api }) + assert.equal(api.log.get(ride.id).deleted, true) + const back = await undoTakeOff({ ownerEntry: taken.ownerEntry, person: PEOPLE[1], taken, api, now: 'zz' }) + assert.deepEqual(sharedWithOf(back), [{ id: 'sam', entryId: ride.id }], 'sync came back on, or the link changed') + const restored = api.log.get(ride.id) + assert.equal(restored.deleted, undefined) + assert.equal(restored.updatedAt, 'zz', 'not stamped past the tombstone') + assert.deepEqual(restored.data, copyBefore.data) + + // A kept copy is never written by Undo: only the link comes back. + const api2 = fakeApi() + const added2 = (await addPerson({ ownerEntry: ride, person: PEOPLE[1], session: workoutCard, api: api2 })).ownerEntry + api2.log.set(ride.id, { ...api2.log.get(ride.id), data: { ...api2.log.get(ride.id).data, out: { rpe: 6 } } }) + const taken2 = await removePerson({ ownerEntry: added2, person: PEOPLE[1], session: workoutCard, api: api2 }) + const puts = api2.calls.filter(c => c[0] === 'put').length + const back2 = await undoTakeOff({ ownerEntry: taken2.ownerEntry, person: PEOPLE[1], taken: taken2, api: api2 }) + assert.equal(api2.calls.filter(c => c[0] === 'put').length, puts) + assert.deepEqual(sharedWithOf(back2), [{ id: 'sam', entryId: ride.id, sync: true }]) }) /* --------------------------------------------- copying the owner's exercises */ @@ -480,6 +511,34 @@ test('a shared planned workout carries what KIND of workout it is, so their log assert.equal(hasOwnMarks(copy, planCard), false, 'the kind of workout counted as their own mark') }) +test('an older copy names no activity; its form shows the one its plan files it under, nothing written (#96)', () => { + const old = { ...pull, data: { ...pull.data, sharedFrom: { id: 'owner', name: 'Alex' }, out: { rpe: 6 } } } + assert.deepEqual(formOut(old), { rpe: 6, activity: 'lift' }) + assert.deepEqual(old.data.out, { rpe: 6 }, 'reading the form rewrote the copy') + assert.equal(categoryOf(old, []), 'lift', 'and it files where the form says') + // Its own answer always wins; nothing to read from, nothing made up. + assert.equal(formOut({ ...old, data: { ...old.data, out: { activity: 'run' } } }).activity, 'run') + assert.deepEqual(formOut({ id: 'x', data: { out: { rpe: 2 } } }), { rpe: 2 }) + assert.deepEqual(formOut(null), {}) +}) + +test('a copy whose plan names only the lifting category reads Lift too; support alone still asks (#96 review)', () => { + const fixture = JSON.parse(readFileSync(new URL('../test/fixtures/plan.json', import.meta.url), 'utf8')) + const card = fixture.dailyMenu.find(m => m.id === 'planned') + // daily-2026-10-16's shape: plan category lift, no activity anywhere, nothing in out. + const oct16 = { id: 'daily-2026-10-16', kind: 'daily', date: '2026-10-16', data: { optId: 'planned', done: false, + sharedFrom: { id: 'owner', name: 'Alex' }, out: {}, + plan: { title: 'Push/Pull', category: 'lift', activity: null, blocks: [ + { id: 'b0', name: 'Push', category: 'lift', activity: null, items: [] }, + { id: 'b1', name: 'Pull', category: 'lift', activity: null, items: [] }, + { id: 'b2', name: 'Accessory', category: null, activity: null, items: [] }] } } } + assert.equal(formOut(oct16, card).activity, 'lift') + assert.deepEqual(oct16.data.out, {}, 'reading the form rewrote the copy') + assert.equal(formOut(oct16).activity, undefined, 'no card, nothing made up') + const support = { ...oct16, data: { ...oct16.data, plan: { ...oct16.data.plan, category: 'support', blocks: [] } } } + assert.equal(formOut(support, card).activity, undefined, 'support names no one activity') +}) + test('a number they typed into their plan is their own mark; a target is not', () => { const copy = sharedCopy(pull, { session: planCard, owner: PEOPLE[0] }) assert.equal(hasOwnMarks(copy, planCard), false) @@ -518,7 +577,7 @@ test('the owner\'s one sharing row: who, and whether they are in sync (#80)', () assert.deepEqual(shareSummary(e([{ id: 'sam', sync: true }, { id: 'jo' }]), two), { title: 'with Sam and Jo', sync: 'Sam in sync' }) }) -test('a weight on their copy is their mark, typed or not: taking them off asks first (#80)', () => { +test('a weight on their copy is their mark, typed or not: taking them off keeps it (#80, #96)', () => { const plan = (sets) => ({ blocks: [{ id: 'b0', items: [{ id: 'b0i0', kind: 'lift', name: 'Hip thrust', sets }] }] }) const copy = (sets) => ({ id: 'daily-2026-11-04', data: { optId: 'planned', done: false, sharedFrom: { id: 'owner' }, plan: plan(sets), out: {} } }) assert.equal(hasOwnMarks(copy([{ reps: 10, weight: null }])), false, 'the share\'s target reps are not theirs') @@ -527,6 +586,121 @@ test('a weight on their copy is their mark, typed or not: taking them off asks f assert.equal(hasOwnMarks(own), false, 'an unmarked weight on an entry that is no copy may be a target') }) +/* ------------------------------------------- what a copy shows its person (#96) */ + +// The shape of a copy shared before `theirPlan` stripped the planner's words: the +// owner's reasoning, notes (the owner's recovery and weights), request and conversation. +const oldCopy = { + id: 'daily-2026-10-13', kind: 'daily', date: '2026-10-13', + data: { + optId: 'planned', done: false, sharedFrom: { id: 'owner', name: 'Alex' }, + out: { activity: 'lift' }, + plan: { + v: 1, title: 'Legs', category: 'lift', activity: 'lift', focus: null, minutes: 50, + why: 'Your recovery is 51% today, so loads stay flat.', changed: 'Swapped the squat.', + notes: ['Yellow/red recovery today (51%): holding loads flat.', 'Row has sat at 50 lb for two sessions.'], + ask: 'legs, my knee is sore', thread: [{ role: 'you', text: 'easier please' }, { role: 'model', text: 'Done.' }], + createdAt: 'x', model: 'm', + blocks: [{ id: 'b0', name: 'Main', note: 'Chest and shoulders.', items: [ + { id: 'b0i0', kind: 'lift', name: 'Squat', note: '3x10 at 95 was RPE 6 last time — bump up 5 lb.', + sets: [{ id: 's0', reps: 5, weight: null, note: 'Last logged 125/125/150, hold it.' }] }] }], + }, + }, +} + +test('a copy never shows the owner\'s notes, reasoning, request or conversation, older copies included (#96)', () => { + const shown = planShown(oldCopy) + assert.deepEqual(shown.notes, []) + assert.equal(shown.why, '') + for (const k of ['ask', 'thread', 'changed']) assert.equal(k in shown, false, `${k} shown on a copy`) + const it = shown.blocks[0].items[0] + assert.equal(it.note, '', 'the planner\'s note on an exercise shown on a copy') + assert.equal(it.sets[0].note, '', 'the planner\'s note on a set shown on a copy') + assert.deepEqual([it.name, it.sets[0].reps], ['Squat', 5], 'the exercises are the copy\'s own') + assert.equal(shown.blocks[0].note, 'Chest and shoulders.', 'a block\'s own prose is the workout, shared structure') + assert.equal(planShown(oldCopy), shown, 'a new object every render') + assert.equal(oldCopy.data.plan.notes.length, 2, 'the stored copy was rewritten') + assert.match(oldCopy.data.plan.blocks[0].items[0].note, /RPE 6/, 'the stored copy was rewritten') + // Words the person wrote with the model on their own copy are theirs. + const theirs = ownWordsOn(oldCopy, { ...oldCopy.data.plan, why: 'Sam\'s own reasoning' }) + assert.equal(planShown({ ...oldCopy, data: { ...oldCopy.data, plan: theirs } }).why, 'Sam\'s own reasoning') + assert.equal(ownWordsOn({ id: 'x', data: {} }, oldCopy.data.plan), oldCopy.data.plan, 'stamped on the owner\'s own plan') + // The owner's own plan, and one planned for them alone (written from their own log), show as they are. + const { sharedFrom: _f, ...own } = oldCopy.data + assert.equal(planShown({ ...oldCopy, data: own }), own.plan) + assert.equal(planShown({ ...oldCopy, data: { ...own, plannedBy: { id: 'owner', name: 'Alex' } } }).notes.length, 2) + assert.equal(planShown({ id: 'x', data: {} }), null) +}) + +test('the filter is display only: an edit from her sheet lands on the stored plan, every hidden note byte for byte (#96 review 2)', () => { + // daily-2026-10-20-planned's shape: an older copy, no uids, notes on the plan, each exercise and some sets. + const set = (id, note = '') => ({ id, reps: 12, weight: 10, seconds: null, distance: null, restSec: null, unit: null, note }) + const item = (i, name, note, notes) => ({ id: `b0i${i}`, kind: 'lift', name, note, exercise: name.toLowerCase(), group: 'core', + implement: 'dumbbell', implementLabel: 'Dumbbell', weightLabel: 'per hand', unit: null, + sets: notes.map((n, j) => set(`b0i${i}s${j}`, n)) }) + const stored = { + v: 1, title: 'Core & hips', category: 'support', activity: null, focus: null, minutes: 25, + why: 'Your recovery was 48% this morning.', notes: ['Keep it light after Saturday.'], changed: null, + createdAt: '2026-10-20T07:00:00Z', model: 'm', ask: 'something easy', + blocks: [{ id: 'b0', name: 'Core', note: 'Slow and controlled.', category: 'support', activity: null, items: [ + item(0, 'Dead bug', 'Last logged 3x12 at bodyweight; add the 10 lb plate.', ['Owner: slow on the way down.', 'Owner: slow on the way down.', 'Owner: slow on the way down.']), + item(1, 'Side plank', 'You skipped these on 10-16.', ['', '', '']), + item(2, 'Bird dog', 'RPE 4 last time, go 2 more reps.', ['', '', '']), + ] }], + } + const copy = { id: 'daily-2026-10-20-planned', kind: 'daily', date: '2026-10-20', + data: { optId: 'planned', slot: 'extra', done: false, out: {}, sharedFrom: { id: 'owner', name: 'Alex' }, plan: stored } } + const before = JSON.stringify(stored) + // Her sheet shows the filtered plan; she edits a weight on it, and the sheet writes. + const shown = planShown(copy) + const edited = patchSet(shown, 'b0i1', 'b0i1s0', { weight: 15 }) + const written = withStoredWords(copy, edited) + assert.equal(JSON.stringify(stored), before, 'the stored plan object was mutated') + assert.deepEqual(written, patchSet(stored, 'b0i1', 'b0i1s0', { weight: 15 }), 'the write is not the stored plan with her edit') + const notesOf = (p) => JSON.stringify(p.blocks.map(b => b.items.map(i => [i.note, i.sets.map(x => x.note)]))) + assert.equal(notesOf(written), notesOf(stored), 'an exercise or set note was lost') + for (const k of ['why', 'notes', 'changed', 'ask']) assert.equal(JSON.stringify(written[k]), JSON.stringify(stored[k]), `${k} lost`) + assert.equal('thread' in written, false, 'a key the stored plan never had was added') + assert.equal(written.blocks[0].items[1].sets[0].weight, 15) + // And what she sees after it is still the filtered plan. + const after = planShown({ ...copy, data: { ...copy.data, plan: written } }) + assert.equal(notesOf(after), JSON.stringify([[['', ['', '', '']], ['', ['', '', '']], ['', ['', '', '']]]])) + assert.equal(after.why, '') + // Moved, removed and added: each stored note follows its own exercise; a new one has nothing to take. + const moved = { ...shown, blocks: [{ ...shown.blocks[0], items: [shown.blocks[0].items[2], shown.blocks[0].items[0], + { ...shown.blocks[0].items[0], id: 'new', name: 'Plank', exercise: 'plank' }] }] } + const w2 = withStoredWords(copy, moved) + assert.deepEqual(w2.blocks[0].items.map(i => i.note), ['RPE 4 last time, go 2 more reps.', 'Last logged 3x12 at bodyweight; add the 10 lb plate.', '']) + // Not a copy, or words that are hers: nothing put back. + const { sharedFrom: _f, ...own } = copy.data + assert.equal(withStoredWords({ ...copy, data: own }, edited), edited) + const hers = { ...edited, ownWords: true, why: 'Sam\'s own' } + assert.equal(withStoredWords(copy, hers), hers) +}) + +test('a new share leaves out the owner\'s request too, not only the reasoning (#96)', () => { + const { sharedFrom: _f, ...data } = oldCopy.data + const copy = sharedCopy({ ...oldCopy, data }, { owner: PEOPLE[0] }) + for (const k of ['ask', 'thread', 'changed', 'draftId']) assert.equal(k in copy.data.plan, false, `${k} copied`) + assert.equal(copy.data.plan.blocks[0].items[0].note, '', 'the planner\'s note on an exercise copied') + assert.equal(copy.data.plan.blocks[0].items[0].sets[0].note, '', 'the planner\'s note on a set copied') + assert.equal(copy.data.plan.why, '') + assert.deepEqual(copy.data.plan.notes, []) +}) + +test('who a removal says the exercises stay in step with, from where the sheet stands (#96)', () => { + const owners = { id: 'daily-2026-11-08', data: { sharedWith: [{ id: 'sam', entryId: 'daily-2026-11-08', sync: true }, { id: 'jo', entryId: 'x' }] } } + const on = [{ id: 'sam', name: 'Sam' }, { id: 'jo', name: 'Jo' }] + assert.deepEqual(syncedSides(owners, on, null), ['Sam'], 'the owner\'s side: only those in sync') + assert.deepEqual(syncedSides(owners, on, on[0]), ['you'], 'Sam\'s side, from the owner\'s phone') + assert.equal(syncedSides(owners, on, on[1]), null, 'Jo is not in sync') + // Sam's own phone: the copy names nobody, and its removal reaches the owner's log too. + const theirs = { id: 'daily-2026-11-08', data: { sharedFrom: { id: 'owner', name: 'Alex', sync: true } } } + assert.deepEqual(syncedSides(theirs, [], null), ['Alex']) + assert.equal(syncedSides({ ...theirs, data: { sharedFrom: { id: 'owner', name: 'Alex', sync: false } } }, [], null), null) + assert.equal(syncedSides({ id: 'x', data: {} }, [], null), null) +}) + for (const [name, fn] of tests) { try { await fn(); console.log(` ok ${name}`) } catch (err) { failed++; console.log(` FAIL ${name}\n ${err.message}`) } } diff --git a/app/smoke/people.jsx b/app/smoke/people.jsx index b6eb97e..1d2b25f 100644 --- a/app/smoke/people.jsx +++ b/app/smoke/people.jsx @@ -270,6 +270,43 @@ export default [ if (/last \d+ sessions?|nothing written down/i.test(t)) throw new Error('the history header is back to "sessions"') if (/last time \(/.test(draw([]).replace(/<[^>]+>/g, ''))) throw new Error('a last time with no history') }], + ['SessionSheet(an older copy never shows the owner\'s notes or reasoning, and its form reads its kind (#96))', null, () => { + const plannedOpt = plan.dailyMenu.find(m => m.id === 'planned') + // The seed's shape: shared before the share stripped the planner's words, and before #74 filed it. + const pres = { title: 'Legs', category: 'lift', activity: 'lift', why: 'Your recovery is 51% today, so loads stay flat.', + notes: ['Yellow recovery today (51%): holding loads flat.'], ask: 'legs please', thread: [{ role: 'you', text: 'my knee hurts' }], + blocks: [{ id: 'b0', name: 'Legs', items: [{ id: 'b0i0', kind: 'lift', name: 'Goblet squat', + note: '3x10 at 95 was RPE 6 last time — bump up 5 lb.', sets: [{ id: 'b0i0s0', reps: 10, weight: null, note: 'Last logged 125/125/150.' }] }] }] } + const copy = (date) => ({ ...entry, id: `daily-${date}`, date, data: { optId: 'planned', name: 'Legs', done: false, out: {}, plan: pres, + sharedFrom: { id: 'owner', name: 'Alex', sync: true } } }) + const samMe = { id: 'sam', owner: false, acting: false, real: { id: 'sam', name: 'Sam', admin: false }, people: [], features: { ai: true } } + const actingMe = { ...ownerMe, id: 'sam', acting: true, features: { ai: true } } + const draw = (me, e, own = false) => text(renderToString( TODAY} me={me} onLog={noop} onSave={noop} onSetDone={noop} onRemove={noop} onClose={noop} + onSaveEntry={own ? noop : null} />)) + for (const [who, me] of [['Sam', samMe], ['the owner acting as Sam', actingMe]]) { + for (const date of [TODAY, '2999-01-01']) { + const t = draw(me, copy(date)).replace(/<[^>]+>/g, ' ') + if (/51%|recovery|knee|legs please|RPE 6 last time|125\/125\/150/i.test(t)) throw new Error(`${who} reads the owner's planner words (${date}): ${t.slice(0, 400)}`) + if (!/Goblet squat/.test(t)) throw new Error(`${who}'s copy lost its exercise (${date})`) + } + const t = draw(me, copy(TODAY)) + if (/What kind of workout was this/.test(t)) throw new Error(`${who}'s older copy asks what kind of workout it was`) + if (!/Lift/.test(t)) throw new Error(`${who}'s older copy does not read Lift`) + } + // The notes line and an exercise's note are still there, on the owner's own plan. + const { sharedFrom: _f, ...mine } = copy(TODAY).data + const own = draw({ ...ownerMe, features: { ai: true } }, { ...copy(TODAY), data: mine }, true) + if (!/Yellow recovery today/.test(own)) throw new Error('the plan\'s notes went from the owner\'s own sheet') + if (!/RPE 6 last time/.test(own)) throw new Error('an exercise\'s note went from the owner\'s own sheet') + // The runner on a copy: the step's cue is never the owner's note on it. + const mixed = normalizePrescription({ title: 'Row', blocks: [{ name: 'Main', items: [ + { kind: 'interval', name: 'Row easy', note: 'Last time 2:05/500m at your recovery 51%.', sets: [{ seconds: 600, note: 'Owner held 2:05.' }] }] }] }) + const run = (data) => text(renderToString()).replace(/<[^>]+>/g, ' ') + if (/2:05|51%/.test(run(copy(TODAY).data))) throw new Error('the runner shows the owner\'s note on a copy\'s step') + if (!/Owner held 2:05/.test(run(mine))) throw new Error('the runner lost a step\'s cue on the owner\'s own plan') + }], ['SessionSheet(their own copy says it is in step with the owner\'s, and only while it is)', null, () => { const samMe = { id: 'sam', owner: false, acting: false, real: { id: 'sam', name: 'Sam', admin: false }, people: [] } const hers = (from) => ({ ...entry, data: { ...entry.data, sharedFrom: from } }) diff --git a/app/src/lib/category.js b/app/src/lib/category.js index b5b20c5..8cfdbe0 100644 --- a/app/src/lib/category.js +++ b/app/src/lib/category.js @@ -55,3 +55,33 @@ function filedOut(entry) { const activity = plan.activity || named.activity || null return { ...out, ...(category ? { category } : {}), ...(activity ? { activity } : {}) } } + +/** + * `out` as a logging form shows it (#96): an older copy's own `out`, with the + * activity its plan files it under when it names none, so its "What kind of + * workout was this?" reads Lift, as a new copy's does, instead of asking with + * nothing picked. Only the activity, and only for the form: what is stored is + * written when the person saves, never by reading. + * + * A plan that names only a category (`lift`, no activity) reads the content's + * lifting activity when that category is the lifting activity's own: the first + * catalog activity whose shape the session's lift field asks for, the rule a + * plan with no filing is placed by (prescription.js `circuitFiling`). Any other + * category alone (support, a run) names no one activity and is left to ask. + */ +export function formOut(entry, session = null) { + const out = entry?.data?.out || {} + if (out.activity) return out + const filed = filedOut(entry) + const activity = filed.activity || liftingActivityFor(filed.category, session) + return activity ? { ...out, activity } : out +} + +function liftingActivityFor(category, session) { + if (!category) return null + const outputs = session?.outputs || [] + const shapes = outputs.find(o => o?.type === 'lifts')?.when?.shape || [] + const field = outputs.find(o => o?.type === 'activity') + const act = (field?.activities || []).find(a => shapes.includes(a?.shape)) + return act && act.category === category ? act.key : null +} diff --git a/app/src/lib/history.js b/app/src/lib/history.js index b9362ed..46216b9 100644 --- a/app/src/lib/history.js +++ b/app/src/lib/history.js @@ -70,17 +70,54 @@ export function samePlanned(entry, e) { return sameExercises(exercisesOf(entry), exercisesOf(e)) } +/** + * Where an entry sits in its day, as the day list shows it (tabs.jsx): the main + * session first, then the extras by id. + */ +const dayPlace = (e) => [e?.data?.slot === 'extra' ? 1 : 0, String(e?.id || '')] + +/** + * When a session started, in ms, where something measured or stamped it: its + * run, the WHOOP or Strava workout attached to it, then its done tap. Null when + * nothing did (a lift typed on the sheet): a day carries no other clock. + */ +function startedAt(e) { + const d = e?.data || {} + for (const v of [d.run?.startedAt, d.out?.whoop?.start, d.out?.strava?.start, d.doneAt]) { + const t = typeof v === 'number' ? v : Date.parse(v) + if (Number.isFinite(t) && t > 0) return t + } + return null +} + +/** + * Is `e` before `me`: an earlier day, or earlier the same day, by when each + * started where both say, else by the day list's order. + */ +function before(e, me) { + if (String(e.date) !== String(me.date)) return String(e.date) < String(me.date) + const [ta, tb] = [startedAt(e), startedAt(me)] + if (ta !== null && tb !== null && ta !== tb) return ta < tb + const [a, b] = [dayPlace(e), dayPlace(me)] + return a[0] !== b[0] ? a[0] < b[0] : a[1] < b[1] +} + /** * Every time you DID this workout (`isDone`: not a plan still to come, not one - * marked undone), newest first, the entry being shown left out. `entry` is that - * entry; without it, it is looked up by `excludeId`, and a container's history - * without an entry to compare is none, never a guess. + * marked undone) BEFORE the one being shown, newest first, that one left out. + * `entry` is that entry; without it, it is looked up by `excludeId`, and a + * container's history without an entry to compare is none, never a guess. + * + * Before is by day, then by time (#96: a Nov 7 workout listed Nov 8's as "the + * last time"): an earlier day, or a session that started earlier the same day + * (`before`), so a second lift in the evening still says "earlier today". With + * no entry (a card not yet on a day) nothing is bounded. */ export function priorSessions(entries, session, excludeId, entry = null) { const ids = priorIdsOf(session) if (!ids.length) return [] - const all = (entries || []).filter(e => e?.kind === 'daily' && e.id !== excludeId && isDone(e)) const me = entry || (entries || []).find(e => e?.id === excludeId) || null + const all = (entries || []).filter(e => e?.kind === 'daily' && e.id !== excludeId && isDone(e) && (!me?.date || before(e, me))) let hits if (!session?.sched?.repeatVia) hits = all.filter(e => ids.includes(e.data?.optId)) else if (me?.data?.plan) hits = all.filter(e => samePlanned(me, e)) @@ -88,5 +125,5 @@ export function priorSessions(entries, session, excludeId, entry = null) { const activity = me?.data?.out?.activity hits = activity ? all.filter(e => ids.includes(e.data?.optId) && !e.data?.plan && e.data?.out?.activity === activity) : [] } - return hits.sort((a, b) => String(b.date).localeCompare(String(a.date))) + return hits.sort((a, b) => String(b.date).localeCompare(String(a.date)) || (before(a, b) ? 1 : before(b, a) ? -1 : 0)) } diff --git a/app/src/lib/prescription.js b/app/src/lib/prescription.js index d4d2d71..79cde36 100644 --- a/app/src/lib/prescription.js +++ b/app/src/lib/prescription.js @@ -769,7 +769,8 @@ export function circuitMinutes(pres) { function circuitRow(it, mark) { const rounds = Array.isArray(mark?.rounds) ? mark.rounds.filter(n => Number(n) > 0) : [] if (!rounds.length) return null - const byReps = circuitTiming(it).by === 'reps' + // A mark with no seconds was a count (`endCircuit`), whatever the item says now. + const byReps = circuitTiming(it).by === 'reps' || mark.seconds == null // The planned weight is what it was done with: a plan says "15 @ 10 lb". const weight = num(it.sets[0]?.weight) ?? '' return { @@ -796,7 +797,7 @@ function circuitRow(it, mark) { * write of a circuit done together (lib/trainer.js `togetherWrite`) can never * add its minutes twice. */ -export function endCircuit(run, pres, blockId, done = [], { at = Date.now(), seconds = 0, key = null, fill = false } = {}) { +export function endCircuit(run, pres, blockId, done = [], { at = Date.now(), seconds = 0, key = null, fill = false, counted = [] } = {}) { if (key != null && run?.circuitKeys?.[blockId] === key) return run const base = run || emptyRun(at) const block = (pres?.blocks || []).find(b => b.id === blockId) @@ -811,7 +812,12 @@ export function endCircuit(run, pres, blockId, done = [], { at = Date.now(), sec if (fill && (sets[setId] || skipped.includes(setId))) return const rounds = (done[i] || []).map(n => Math.round(n)).filter(n => n > 0) if (rounds.length) { - sets[setId] = { ...(circuitTiming(it).by === 'reps' ? {} : { seconds: rounds.reduce((a, b) => a + b, 0) }), rounds, at } + // A count is marked without seconds. `counted` (by index, a result from another + // side's clock): it counted this one, which decides only where this side's own + // timing is blank; a side that says reps or seconds keeps its own shape. + const own = circuitTiming(it).by + const byReps = own === 'reps' || (own === 'circuit' && counted[i] === true) + sets[setId] = { ...(byReps ? {} : { seconds: rounds.reduce((a, b) => a + b, 0) }), rounds, at } skipped = skipped.filter(id => id !== setId) } else if (!sets[setId] && !skipped.includes(setId)) skipped.push(setId) }) diff --git a/app/src/lib/shared.js b/app/src/lib/shared.js index 4dbb804..0f8a0dd 100644 --- a/app/src/lib/shared.js +++ b/app/src/lib/shared.js @@ -191,11 +191,15 @@ const noMode = ({ weightMode: _m, weightLabel: _l, ...rest }) => rest /** A copy of their own last set: its numbers as a start, but not typed until they type into it. */ const untypedCopy = ({ typed: _t, ...s }) => ({ ...s, note: '' }) -/** One of the owner's sets on their side: the target, not the owner's weight, and nothing they typed. */ -const theirSet = ({ typed: _t, ...s }) => ({ ...s, weight: null }) +/** One of the owner's sets on their side: the target, not the owner's weight, cue or anything they typed. */ +const theirSet = ({ typed: _t, ...s }) => ({ ...s, weight: null, note: '' }) -/** One of the owner's exercises on their side: the target, not the owner's weight or what it meant. */ -const theirItem = (item) => ({ ...noMode(item), sets: (item.sets || []).map(theirSet) }) +/** + * One of the owner's exercises on their side: the target, not the owner's + * weight, what it meant, or the planner's note on it ("3x10 at 95 was RPE 6 + * last time", written from the owner's log). + */ +const theirItem = (item) => ({ ...noMode(item), note: '', sets: (item.sets || []).map(theirSet) }) /** * The owner's plan as the start of theirs: the exercises, never the owner's @@ -205,8 +209,131 @@ const theirItem = (item) => ({ ...noMode(item), sets: (item.sets || []).map(thei * log (`thread`, `why`, `notes`, `changed`). */ function theirPlan(mine) { - const { draftId: _d, thread: _t, why: _w, notes: _n, changed: _c, ...plan } = mine - return { ...plan, why: '', notes: [], blocks: mine.blocks.map(b => ({ ...b, items: (b.items || []).map(theirItem) })) } + const { draftId: _d, ...plan } = ownerWordsOff(mine) + return { ...plan, blocks: mine.blocks.map(b => ({ ...b, items: (b.items || []).map(theirItem) })) } +} + +/** + * A plan without the words the planner wrote for the person it was made for: + * its reasoning (`why`), notes, the conversation (`thread`), the request (`ask`), + * what a revision changed, and its note on each exercise and set. On a copy + * those are the OWNER's: written from the owner's log, WHOOP recovery and + * weights included ("Yellow recovery today (51%)…", "3x10 at 95 was RPE 6 last + * time"), and nothing on them is about the person whose copy it is. A block's + * note stays: it is the workout's own prose (a warm-up block exists by it) and + * shared structure (server/sharedsync.js BLOCK_KEYS). + */ +function ownerWordsOff({ why: _w, notes: _n, thread: _t, ask: _a, changed: _c, ...plan }) { + const blocks = Array.isArray(plan.blocks) ? plan.blocks.map(b => ({ + ...b, + items: (Array.isArray(b?.items) ? b.items : []).map(it => ({ + ...it, note: '', sets: (Array.isArray(it?.sets) ? it.sets : []).map(x => ({ ...x, note: '' })), + })), + })) : plan.blocks + return { ...plan, why: '', notes: [], blocks } +} + +/** One shown plan per stored plan, so a screen given it keeps one object while nothing changed. */ +const shownOf = new WeakMap() + +/** + * The plan as THIS log's person sees it (#96): every screen that draws a plan + * reads it through here (the sheet's editor, notes and model panel, the + * runner), on the web and the phone. On a copy (`sharedFrom`) the owner's + * words are left out at display time, because copies shared before + * `theirPlan` stripped them still carry them. Display only: nothing stored is + * rewritten (AGENTS.md §4), by reading or by writing. Every write from such a + * screen goes back through `withStoredWords`, which puts each hidden word back + * exactly as stored, so the person's edit lands on the stored plan. + * + * Words the person wrote with the model on their own copy are theirs, and the + * sheet stamps them so (`ownWords`, `ownWordsOn`): such a plan is shown whole. + */ +export function planShown(entry) { + const plan = entry?.data?.plan + if (!plan || typeof plan !== 'object') return null + if (!entry.data.sharedFrom || plan.ownWords === true) return plan + if (!shownOf.has(plan)) shownOf.set(plan, ownerWordsOff(plan)) + return shownOf.get(plan) +} + +const WORD_KEYS = ['why', 'notes', 'thread', 'ask', 'changed'] + +/** `to` with `key` exactly as `from` has it: the same value, or no key when `from` has none. */ +function sameKey(to, from, key) { + if (from && Object.prototype.hasOwnProperty.call(from, key)) return to[key] === from[key] ? to : { ...to, [key]: from[key] } + if (!Object.prototype.hasOwnProperty.call(to, key)) return to + const { [key]: _gone, ...rest } = to + return rest +} + +/** + * A plan edited on a screen that was SHOWN `planShown`, made a write to the + * stored plan (#96 review 2): the filter is for what is drawn, never for what + * is stored (AGENTS.md §4). Every word it hid comes back exactly as stored, + * byte for byte, a key the stored plan never had included: the plan's own + * (`why`, `notes`, `thread`, `ask`, `changed`) and each exercise's and set's + * `note`. An exercise is the stored one by its uid, else by its name and which + * of that name it is (`keyed`), else by its id; a set by its place in it. What + * the person added has nothing stored to take, and keeps its blank. Anything + * the filter did not touch (not a copy, or words that are the person's own, + * `ownWords`, which a model revision on their copy writes) is `next` as it is. + * Used by every write from those screens: the sheet's editor, on the person's + * own side and on the owner's view of it, and the runner. + */ +export function withStoredWords(entry, next) { + const stored = entry?.data?.plan + if (!next || typeof next !== 'object' || !stored || typeof stored !== 'object') return next + if (!entry.data.sharedFrom || stored.ownWords === true || next.ownWords === true) return next + const byUid = new Map() + const byKey = new Map() + const byId = new Map() + for (const { key, item } of keyed(stored)) { + if (item?.uid) byUid.set(item.uid, item) + byKey.set(key, item) + if (item?.id) byId.set(item.id, item) + } + const claimed = new Set() + const claim = (m) => (m && !claimed.has(m) ? (claimed.add(m), m) : null) + const seen = new Map() + let plan = next + for (const k of WORD_KEYS) plan = sameKey(plan, stored, k) + if (!Array.isArray(next.blocks)) return plan + const blocks = next.blocks.map(b => ({ + ...b, + items: (Array.isArray(b?.items) ? b.items : []).map(it => { + const name = String(it?.name || '') + const n = (seen.get(name) || 0) + 1 + seen.set(name, n) + const was = claim(it?.uid && byUid.get(it.uid)) || claim(byKey.get(`${name}#${n}`)) || claim(it?.id && byId.get(it.id)) + if (!was) return it + const sets = (Array.isArray(it.sets) ? it.sets : []).map((x, i) => (was.sets?.[i] ? sameKey(x, was.sets[i], 'note') : x)) + return { ...sameKey(it, was, 'note'), sets } + }), + })) + return { ...plan, blocks } +} + +/** + * A plan written by the model panel on this person's own copy: its words are + * now theirs (`planShown` shows them). Anything that is not a copy is as it is. + */ +export const ownWordsOn = (entry, plan) => (entry?.data?.sharedFrom && plan ? { ...plan, ownWords: true } : plan) + +/** + * Who a removal's toast says the exercises stay in step with (lib/removal.js + * `syncLine`), or null: the other sides of this synced workout, from where the + * sheet stands (#96, folded out of both sheets). On the owner's side, everyone + * on it with sync on (`on`, `sharedPeopleOn`); on someone else's side, the owner + * ("you"); and on the other person's OWN copy, whoever shared it, when the + * server says it is in step (`inStep`): a removal there reaches the owner's log too. + */ +export function syncedSides(entry, on = [], side = null) { + if (side) return isSynced(entry, side.id) ? ['you'] : null + const names = on.filter(p => isSynced(entry, p.id)).map(p => p.name) + if (names.length) return names + if (!on.length && inStep(entry)) return [String(entry.data.sharedFrom.name || '').trim() || 'the person who shared it'] + return null } /** Their plan with every exercise and set of the owner's that it lacks. Never takes anything out. */ @@ -392,21 +519,49 @@ export async function addPerson({ ownerEntry, person, session = null, owner = nu } /** - * Take someone off the owner's workout. Their copy is tombstoned only if they - * have put nothing of their own on it; otherwise `confirmFn` is asked first, and - * a no leaves both entries as they were. Resolves the owner's entry to write, - * or null when nothing should change. + * Take someone off the owner's workout (#96). Nothing they logged is ever lost + * by it: a copy they have put something of their own on (`hasOwnMarks`) is KEPT + * in their log as their workout, only no longer linked (the server then flags + * it not in step, `flagChanges`); one they have not touched is tombstoned, as + * it holds nothing but the owner's exercises. No question either way: the toast + * says which (`takeOffWords`), with Undo (`undoTakeOff`). + * + * This used to tombstone a logged copy too, after a bare "take it out of Sam's + * log anyway?" with no Undo: one tap on the owner's phone deleted someone + * else's sets and weights. + * + * Resolves `{ ownerEntry, link, copy, kept }`, or null when they are not on it: + * the owner's entry to write, the link as it was, and their copy as it was read. */ -export async function removePerson({ ownerEntry, person, session = null, api, confirmFn }) { +export async function removePerson({ ownerEntry, person, session = null, api }) { const link = sharedWithOf(ownerEntry).find(s => s.id === person.id) if (!link) return null const copy = await api.getPersonEntry(person.id, link.entryId) - if (copy && !copy.deleted) { - if (hasOwnMarks(copy, session)) { - const yes = await confirmFn(`${person.name} has already logged some of this. Take it out of ${person.name}'s log anyway?`) - if (!yes) return null - } - await api.putPersonEntry(person.id, tombstoneOf(copy)) + const live = Boolean(copy && !copy.deleted) + const kept = live && hasOwnMarks(copy, session) + if (live && !kept) await api.putPersonEntry(person.id, tombstoneOf(copy)) + return { ownerEntry: withSharedPerson(ownerEntry, person.id, null, { remove: true }), link, copy: live ? copy : null, kept } +} + +/** What taking someone off did, in the toast: only what is certain. */ +export function takeOffWords(person, { kept = false } = {}) { + return kept + ? `Took ${person.name} off this workout. It stays in ${person.name}\u2019s log with what ${person.name} logged.` + : `Took ${person.name} off this workout` +} + +/** + * Undo of `removePerson`: their copy back if it was tombstoned (the copy as it + * was, stamped now so it wins over the tombstone), then the owner's entry with + * the link exactly as it was, sync flag included. Resolves the owner's entry to + * write. `ownerEntry` is the owner's entry NOW, not as it was taken off. + */ +export async function undoTakeOff({ ownerEntry, person, taken, api, now = new Date().toISOString() }) { + const { link, copy, kept } = taken + if (copy && !kept) { + const { deleted: _d, ...back } = copy + await api.putPersonEntry(person.id, { ...back, updatedAt: now }) } - return withSharedPerson(ownerEntry, person.id, null, { remove: true }) + const rest = sharedWithOf(ownerEntry).filter(s => s.id !== person.id) + return { ...ownerEntry, data: { ...(ownerEntry.data || {}), sharedWith: [...rest, link] } } } diff --git a/app/src/lib/trainer.js b/app/src/lib/trainer.js index 9634c95..8740953 100644 --- a/app/src/lib/trainer.js +++ b/app/src/lib/trainer.js @@ -29,7 +29,7 @@ import { optFor } from './menu.js' import { sharePeople, sharedPeopleOn, addPerson } from './shared.js' import { isLiftOnly, followWeightModes, endCircuit, circuitOnly, circuitEnded, runProgress, prescriptionSteps, finishRun, - runOutputs, fillOut, blockTimer, remapRun, + runOutputs, fillOut, blockTimer, remapRun, circuitTiming, } from './prescription.js' import { compile, settle } from './timer.js' import { liftFieldIn } from './lifts.js' @@ -568,6 +568,15 @@ export const togetherWords = (sides = [], here = null) => { return names.length ? `Together with ${andWords(names)}` : '' } +/** + * A circuit's exercises as a result done together names them: the sync's uid, + * the name, and how the clock ran each one (`by`, prescription.js + * `circuitTiming`), so a side whose copy of an exercise arrived blank logs a + * counted exercise as a count, never as a hold of the seconds spent on its reps. + */ +export const togetherItems = (block) => (block?.items || []) + .map(it => ({ uid: it.uid || null, name: it.name, by: circuitTiming(it).by })) + /** * What one side's own entry gets from a circuit done together, by rule 1: * @@ -577,7 +586,8 @@ export const togetherWords = (sides = [], here = null) => { * { kind: 'running' } its own clock is going: leave it be * { kind: 'none' } it has no such circuit * - * `result` is `{ block: { uid, id, name }, items: [{ uid, name }], done, at, seconds, key, with }` + * `result` is `{ block: { uid, id, name }, items: [{ uid, name, by }], done, at, seconds, key, with }` + * (`togetherItems`; `by` is how the clock ran each exercise, absent on a miss kept from before #96) * from the side that ran the clock; `with` is who was offered Together when it * started (side ids, null for the owner), and only they are written. The block and each exercise are found here * by uid (the sync's identity), then by name, each of this side's exercises @@ -604,16 +614,20 @@ export function togetherWrite(entry, result, now = Date.now()) { if (circuitEnded(block, run) || run?.endedAt) return { kind: 'already' } } const taken = new Set() - const done = block.items.map(it => { + const match = block.items.map(it => { let j = it.uid ? result.items.findIndex((x, n) => !taken.has(n) && x.uid === it.uid) : -1 if (j < 0) j = result.items.findIndex((x, n) => !taken.has(n) && x.name === it.name) - if (j < 0) return [] - taken.add(j) - return result.done[j] || [] + if (j >= 0) taken.add(j) + return j }) + const done = match.map(j => (j < 0 ? [] : result.done[j] || [])) + // A count on the side that ran the clock is a count here too where this side's own + // timing is blank (#96): its seconds were time spent on reps, never a hold. A side + // that says reps or seconds keeps its own shape (`endCircuit`). + const counted = match.map(j => j >= 0 && result.items[j]?.by === 'reps') const base = run?.circuitKeys?.[block.id] === result.key ? { ...run, circuitKeys: { ...run.circuitKeys, [block.id]: null } } : run - let next = endCircuit(base, pres, block.id, done, { at: result.at, seconds: result.seconds, key: result.key, fill: true }) + let next = endCircuit(base, pres, block.id, done, { at: result.at, seconds: result.seconds, key: result.key, fill: true, counted }) const finished = circuitOnly(pres) && runProgress(next, prescriptionSteps(pres)).left === 0 if (finished) next = finishRun(next, { at: result.at }) const out = fillOut(entry.data.out || {}, runOutputs(pres, next, {})) diff --git a/app/src/runner.jsx b/app/src/runner.jsx index d4b50e6..ce4beac 100644 --- a/app/src/runner.jsx +++ b/app/src/runner.jsx @@ -64,7 +64,8 @@ import { ExerciseBody, musclesOf, muscleWords } from './lib/bodymap.jsx' import { usePlan } from './lib/planctx.jsx' import { TimerRun, WorkHead, LeaveDialog, leaveActions, ControlRow, setsWord } from './timer.jsx' import { timingWords } from './circuit.jsx' -import { andWords, togetherSaid } from './lib/trainer.js' +import { andWords, togetherSaid, togetherItems } from './lib/trainer.js' +import { planShown, withStoredWords } from './lib/shared.js' const mmss = (s) => `${Math.floor(s / 60)}:${String(Math.abs(s) % 60).padStart(2, '0')}` @@ -96,7 +97,8 @@ const mmss = (s) => `${Math.floor(s / 60)}:${String(Math.abs(s) % 60).padStart(2 * is written to every side when it ends (`write`, which says who it missed). */ export function WorkoutRunner({ session, entry, entries = [], onRun, onExit, onFinish = null, who = null, switcher = null, shown = true, together = null }) { - const pres = entry?.data?.plan || null + // As this log's person sees it: never the owner's notes on a copy (lib/shared.js `planShown`, #96). + const pres = planShown(entry) const steps = useMemo(() => prescriptionSteps(pres), [pres]) const liftField = liftFieldOf(usePlan()) const run = entry?.data?.run || null @@ -273,7 +275,7 @@ export function WorkoutRunner({ session, entry, entries = [], onRun, onExit, onF */ const addAnother = () => { if (!step) return - write(run, { plan: addSetLike(pres, step.itemId, { ...step.set, ...(draft || {}) }) }) + write(run, { plan: withStoredWords(entry, addSetLike(pres, step.itemId, { ...step.set, ...(draft || {}) })) }) } // What this exercise's weight means (#58), on the plan, and on the log in the @@ -515,7 +517,7 @@ function CircuitRun({ if (withThem && onShare) { onShare({ block: { uid: block.uid || null, id: block.id, name: block.name }, - items: block.items.map(it => ({ uid: it.uid || null, name: it.name })), + items: togetherItems(block), done, at, seconds, key, ...(withIds ? { with: withIds } : {}), }) } diff --git a/app/src/sessionlog.jsx b/app/src/sessionlog.jsx index 6fad868..b56a6f5 100644 --- a/app/src/sessionlog.jsx +++ b/app/src/sessionlog.jsx @@ -16,6 +16,7 @@ import { activityOf, activityLabel } from './lib/activities.js' import { liftsLine, liftsDone, liftFieldIn } from './lib/lifts.js' import { priorSessions } from './lib/history.js' import { climbLine, mootHardest } from './lib/grades.js' +import { formOut } from './lib/category.js' import { asksItsOwnDuration, minutesFor, minutesSourceOf } from './lib/minutes.js' import { visibleOutputs, pruneHidden, derivedValue, filledBy } from './lib/outputs.js' import { gateResolver } from './lib/activities.js' @@ -556,7 +557,8 @@ export function SessionLog({ }) { const declared = session?.outputs || [] const hasSets = Boolean(session?.logSpec?.exercises?.length) - const out = entry?.data?.out || {} + // An older copy names no activity; its plan does: the form shows that one (#96, category.js `formOut`). + const out = formOut(entry, session) // Which fields are questions today. On the free-form cards the answer to the // first one decides that: miles and incline are the point of a run and noise diff --git a/app/src/sharedwith.jsx b/app/src/sharedwith.jsx index b832c94..f771fe1 100644 --- a/app/src/sharedwith.jsx +++ b/app/src/sharedwith.jsx @@ -28,12 +28,14 @@ */ import { useCallback, useEffect, useRef, useState } from 'react' +import { Undo2 } from 'lucide-react' import { Icon } from './lib/icons.jsx' +import { UNDO_MS } from './exercises.jsx' import { Popover } from './modal.jsx' import { SessionLog } from './sessionlog.jsx' import { withLine, inStepLine, openSide, shareSummary, isSynced, addPerson, removePerson, withSharedPerson, - withSync, copyExercises, hasExercises, + withSync, copyExercises, hasExercises, takeOffWords, undoTakeOff, } from './lib/shared.js' import * as peopleApi from './lib/peopleapi.js' import { createCopyQueue, openedCopy } from './lib/copyqueue.js' @@ -73,8 +75,8 @@ export function ShareChip({ entry, on = [], people = [], onOpen }) { * Everything that changes who is on a workout, and how, behind the sharing chip: * per person their sync switch, "Copy my exercises to Sam" while sync is off, * and "Take Sam off this workout"; then a row for everyone who could be added. - * Taking someone off asks first when they have logged on their copy - * (lib/shared.js `removePerson`). + * Taking someone off never deletes what they logged: their copy stays in + * their log, unlinked, and the toast has Undo (lib/shared.js `removePerson`). */ export function SharePanel({ entry, on = [], people = [], busy = null, error = null, onAdd, onRemove, onSync, onCopy = null, onClose }) { const free = people.filter(p => !on.some(o => o.id === p.id)) @@ -166,12 +168,24 @@ export function useSharing({ entry, opt, me, onSaveEntry, side, setSide, theirs, owner: { id: me.real.id, name: me.real.name }, api: peopleApi }) onSaveEntry(withSharedPerson(latest.current, person.id, copy.id)) }) - const remove = (person) => run('Taking off', person, async () => { - const next = await removePerson({ ownerEntry: latest.current, person, session: opt, api: peopleApi, - confirmFn: async (q) => typeof window !== 'undefined' && window.confirm(q) }) - if (!next) return + /* Nothing they logged goes (lib/shared.js `removePerson`): a copy with their + marks stays in their log, unlinked. Said in a toast, with Undo. */ + const remove = (person) => { + // Closed first, as on the phone: the toast's Undo must not sit under the panel's scrim. + setState(s => ({ ...s, isOpen: false })) + return takeOff(person) + } + const takeOff = (person) => run('Taking off', person, async () => { + const taken = await removePerson({ ownerEntry: latest.current, person, session: opt, api: peopleApi }) + if (!taken) return if (side === person.id) setSide(null) onSaveEntry(withSharedPerson(latest.current, person.id, null, { remove: true })) + pushToast(takeOffWords(person, taken), 'info', { + duration: UNDO_MS, + action: { label: 'Undo', icon: Undo2, onClick: () => run('Adding', person, async () => { + onSaveEntry(await undoTakeOff({ ownerEntry: latest.current, person, taken, api: peopleApi })) + }) }, + }) }) /* Sync lives on the owner's link; the server does the keeping-the-same (server/sharedsync.js). */ const sync = (person, v) => onSaveEntry(withSync(latest.current, person.id, v)) diff --git a/app/src/sheet.jsx b/app/src/sheet.jsx index 8f9e499..650515a 100644 --- a/app/src/sheet.jsx +++ b/app/src/sheet.jsx @@ -26,7 +26,7 @@ import { titleFor } from './lib/naming.js' import { loggedActivity } from './lib/activities.js' import { currentMe } from './lib/whoami.js' import { applyOut, applyPlan, canStart, plannedLine, toneFor } from './lib/trainer.js' -import { sharePeople, sharedPeopleOn, isSynced } from './lib/shared.js' +import { sharePeople, sharedPeopleOn, syncedSides, planShown, ownWordsOn, withStoredWords } from './lib/shared.js' import { aiOffered } from './lib/plannerapi.js' import { PersonSwitch, SharedNote, TheirSide, usePersonCopy, useSide, TogetherPending, @@ -101,7 +101,9 @@ export function SessionSheet({ const done = planned && isDone(entry) // The prescription, if this session has one. Its presence is what turns the // sheet from a protocol you read into a workout you edit — see runner.jsx. - const pres = entry?.data?.plan || null + // As this log's person sees it: on a copy, never the owner's planner words, the + // exercises' notes included (lib/shared.js `planShown`, #96). Every use below reads it. + const pres = planShown(entry) /* * DOING MODE (#79, D9). A planned workout on its day or after is where the * lifting is done, so the sheet opens on the work: the first exercise with a @@ -134,7 +136,6 @@ export function SessionSheet({ const sidePerson = (side && on.find(p => p.id === side)) || null const theirs = usePersonCopy(sidePerson?.id, sidePerson?.entryId, sidePerson?.name) const theirLog = usePersonLog(sidePerson?.id || null) - const synced = Boolean(sidePerson && isSynced(entry, sidePerson.id)) // The entry as of the latest render, for writes that land after a tap. const latestEntry = useRef(entry) latestEntry.current = entry @@ -147,8 +148,10 @@ export function SessionSheet({ entry, and their log is theirs to keep. */ const saveTheirs = (out) => { setDirty(true); theirs.update(cur => applyOut(cur, opt, out)) } /* Their plan, edited from their side: the same write `savePlan` makes on the owner's. */ - const saveTheirPlan = (next) => { setDirty(true); theirs.update(cur => applyPlan(cur, opt, next)) } - const theirPres = theirs.entry?.data?.plan || null + /* What the sheet shows is `planShown`; what it writes is the stored plan with the + edit in it, every hidden word back as stored (lib/shared.js `withStoredWords`). */ + const saveTheirPlan = (next) => { setDirty(true); theirs.update(cur => applyPlan(cur, opt, withStoredWords(cur, next))) } + const theirPres = planShown(theirs.entry) const theirDone = Boolean(theirs.entry && isDone(theirs.entry)) /* A flip says what it did, with Undo (sheetparts.jsx). Their copy's names whose it was and goes with the sheet: it is written through this sheet's queue. */ @@ -230,15 +233,14 @@ export function SessionSheet({ if (planned && !isFuture && onSetDone) status = if (startable) footer = start() } - /* The other sides of a synced workout, for a removal toast's one line about them - (lib/removal.js: never a claim about what happened there). */ const planTalk = pres && ( { setDirty(true); onSavePlan?.(latestEntry.current, next) }} /> + // What this person asks the model on their own copy is theirs to read (`ownWordsOn`). + onChange={(next) => { setDirty(true); onSavePlan?.(latestEntry.current, ownWordsOn(latestEntry.current, next)) }} /> ) - const syncedWith = sidePerson - ? (synced ? ['you'] : null) - : (() => { const s = on.filter(p => isSynced(entry, p.id)).map(p => p.name); return s.length ? s : null })() + /* The other sides of a synced workout, for a removal toast's one line about them + (lib/removal.js: never a claim about what happened there). */ + const syncedWith = syncedSides(entry, on, sidePerson) /* Under the title: the done chip, then who is on it ("with Sam · in sync ›", #80). */ const shareChip = const statusRow = status || (people.length > 0) @@ -333,7 +335,7 @@ export function SessionSheet({ {planTalkWhere({ ai, doing }) === 'sheet' && planTalk} { setDirty(true); onSavePlan?.(latestEntry.current, next) }} syncedWith={syncedWith} compact + onChange={(next) => { setDirty(true); onSavePlan?.(latestEntry.current, withStoredWords(latestEntry.current, next)) }} syncedWith={syncedWith} compact doing={doing} asWritten={asWritten(entry)} /> {pres.notes?.length > 0 && (
    diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 476e900..82cb849 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -52,7 +52,7 @@ this is the map, kept short on purpose. | Not shared | — | — | — | — | | Shared, in step | Add someone (sync on by default); switch on (aligns once, add-only) | Carried both ways by uid | Never cross | "Exercises stay in step with Alex's" | | Shared, not in step | Switch off; a share from before sync | Stays where it is; Copy my exercises adds the owner's | Never cross | "with Alex" only | -| Taken off | Take off (asks first if they logged anything) | The copy is tombstoned, or kept as theirs | Theirs | not in step | +| Taken off | Take off (a toast with Undo, no question, #96) | Tombstoned if they logged nothing, else kept in their log as theirs, unlinked; the owner's devices no longer write it (`sharedFrom.off`) | Theirs | not in step | **A write to a synced entry** (`intentOf`): a device sends back the base it was given. diff --git a/mobile/AGENTS.md b/mobile/AGENTS.md index 71c4c35..cd869f1 100644 --- a/mobile/AGENTS.md +++ b/mobile/AGENTS.md @@ -89,7 +89,8 @@ Use `npx expo install ` for dependencies so versions match the SDK. `DoneChip`, `useDoneFlip` (the flip and its Undo toast) and `SheetStart` (the footer's one action), used by the session sheet and `PersonEntrySheet`. Who is on a shared workout is `ShareChip` under the title, opening `SharePanel` (a `Popover`, so a page sheet over the - session sheet); taking someone off closes the panel before the system alert asks. + session sheet); taking someone off closes the panel, then says what it did in a toast with Undo (it never + deletes what they logged, so it no longer asks). - **A workout with more than one side** (`features/trainer.tsx` `SidesWorkout`) presents ONE full-screen modal and renders each side's runner or workout mode inside it with `embedded`, because iOS presents one modal at a time; the hidden sides stay mounted so their clocks run. diff --git a/mobile/src/features/runner.tsx b/mobile/src/features/runner.tsx index 89541a3..eb6d295 100644 --- a/mobile/src/features/runner.tsx +++ b/mobile/src/features/runner.tsx @@ -68,6 +68,7 @@ import { clock } from '../lib/workout.js' import { TimerRun, WorkHead, LeaveDialog, leaveActions, ControlRow, setsWord, KIND_COLOR } from './timer' import { timingWords } from './circuit' import * as trainerLib from '../lib/trainer.js' +import { planShown, withStoredWords } from '../lib/shared.js' import { Stepper, boxFor, stepBox, TimeInput, weightSwitch, ExerciseSheet, type WeightSwap } from './exercises' import { ExerciseBody, musclesOf, muscleWords } from '../lib/bodymap' import { usePlan } from '../lib/planctx.jsx' @@ -122,7 +123,8 @@ export function WorkoutRunner({ session, entry, entries = [], onRun, onExit, onF }) { void session const insets = useSafeAreaInsets() - const pres = entry?.data?.plan || null + // As this log's person sees it: never the owner's notes on a copy (lib/shared.js `planShown`, #96). + const pres: any = planShown(entry) const steps: any[] = useMemo(() => prescriptionSteps(pres), [pres]) const liftField = liftFieldOf(usePlan()) const run = entry?.data?.run || null @@ -296,7 +298,7 @@ export function WorkoutRunner({ session, entry, entries = [], onRun, onExit, onF const addAnother = () => { if (!step) return impact() - write(run, { plan: (addSetLike as any)(pres, step.itemId, { ...step.set, ...(draft || {}) }) }) + write(run, { plan: withStoredWords(entry, (addSetLike as any)(pres, step.itemId, { ...step.set, ...(draft || {}) })) }) } // What this exercise's weight means (#58), on the plan, and on the log in the @@ -562,7 +564,7 @@ function CircuitRun({ pres, block, run, only, intro, who, switcher, shown, onRun if (withThem && onShare) { onShare({ block: { uid: block.uid || null, id: block.id, name: block.name }, - items: block.items.map((it: any) => ({ uid: it.uid || null, name: it.name })), + items: (trainerLib as any).togetherItems(block), done, at, seconds, key, ...(withIds ? { with: withIds } : {}), }) } diff --git a/mobile/src/features/sessionlog.tsx b/mobile/src/features/sessionlog.tsx index 7c4179e..a185d11 100644 --- a/mobile/src/features/sessionlog.tsx +++ b/mobile/src/features/sessionlog.tsx @@ -21,6 +21,7 @@ import { ActivityPicker } from './activitypicker' import { liftsLine, liftsDone, liftFieldIn } from '../lib/lifts.js' import { priorSessions } from '../lib/history.js' import { climbLine, mootHardest } from '../lib/grades.js' +import { formOut } from '../lib/category.js' import { asksItsOwnDuration, minutesFor, minutesSourceOf } from '../lib/minutes.js' import { visibleOutputs, pruneHidden, derivedValue, filledBy } from '../lib/outputs.js' import { gateResolver, activityOf, activityLabel } from '../lib/activities.js' @@ -475,7 +476,8 @@ export function SessionLog({ }: any) { const declared = session?.outputs || [] const hasSets = Boolean(session?.logSpec?.exercises?.length) - const out = entry?.data?.out || {} + // An older copy names no activity; its plan does: the form shows that one (#96, category.js `formOut`). + const out = formOut(entry, session) // The catalog resolver, so a field may gate on what the CATALOG says about the // picked activity rather than on a list of ninety-one keys. See lib/outputs.js. diff --git a/mobile/src/features/sharedwith.tsx b/mobile/src/features/sharedwith.tsx index ac5b91d..7c99b53 100644 --- a/mobile/src/features/sharedwith.tsx +++ b/mobile/src/features/sharedwith.tsx @@ -20,7 +20,8 @@ * Native: the person bar goes in the sheet's header (`sub`), which sits outside * the ScrollView, so it stays put while the body scrolls (the web pins it with * `position: sticky`). The sync switch is the system Switch; taking someone off - * asks with a system alert (`confirm`), and switching sides gives a haptic. + * never deletes what they logged and says so in a toast with Undo, and + * switching sides gives a haptic. */ import React, { useCallback, useEffect, useRef, useState } from 'react' @@ -29,11 +30,11 @@ import { colors, font, mix, radius, space, TAP } from '../theme' import { T } from '../ui/Text' import { Btn, IconBtn, Press, Spinner, Toggle, s as kit } from '../ui/kit' import { Popover } from '../ui/Sheet' -import { confirm } from '../ui/menu' import { toneColor } from '../ui/Person' import { success, tap } from '../ui/haptics' import { Icon } from '../lib/icons' import { pushToast } from '../lib/toast' +import { UNDO_MS } from './exercises' import { SessionLog } from './sessionlog' import * as sharedLib from '../lib/shared.js' import * as peopleApi from '../lib/peopleapi.js' @@ -46,7 +47,7 @@ type Person = { id: string; name: string; entryId?: string; tone?: number } const { withLine, inStepLine, openSide, shareSummary, isSynced, addPerson, removePerson, withSharedPerson, - withSync, copyExercises, hasExercises, + withSync, copyExercises, hasExercises, takeOffWords, undoTakeOff, } = sharedLib as any /** How often an open side re-reads their copy, for changes made on their own phone. */ @@ -86,8 +87,8 @@ export function ShareChip({ entry, on = [], people = [], onOpen }: { /** * Everything that changes who is on a workout, and how, behind the sharing chip: * per person their sync switch, "Copy my exercises to Sam" while sync is off, - * and "Take Sam off this workout" (which asks first when they have logged on - * their copy); then a row for everyone who could be added. A page sheet over + * and "Take Sam off this workout" (which keeps their copy in their log when + * they have logged on it, lib/shared.js `removePerson`); then a row for everyone who could be added. A page sheet over * the session sheet, like the exercise sheet. */ export function SharePanel({ entry, on = [], people = [], busy = null, error = null, onAdd, onRemove, onSync, onCopy = null, onClose }: { @@ -192,11 +193,19 @@ export function useSharing({ entry, opt, me, onSaveEntry, side, setSide, theirs, const remove = (person: Person) => { setState((s) => ({ ...s, isOpen: false })) void run('Taking off', person, async () => { - const next = await removePerson({ ownerEntry: latest.current, person, session: opt, api: peopleApi, - confirmFn: (q: string) => confirm(q, { confirmLabel: 'Take it out' }) }) - if (!next) return false + // Nothing they logged goes (lib/shared.js `removePerson`): a copy with their + // marks stays in their log, unlinked. Said in a toast, with Undo. + const taken = await removePerson({ ownerEntry: latest.current, person, session: opt, api: peopleApi }) + if (!taken) return false if (side === person.id) setSide(null) onSaveEntry?.(withSharedPerson(latest.current, person.id, null, { remove: true })) + pushToast(takeOffWords(person, taken), 'info', { + duration: UNDO_MS, + action: { label: 'Undo', icon: null, onClick: () => { void run('Adding', person, async () => { + onSaveEntry?.(await undoTakeOff({ ownerEntry: latest.current, person, taken, api: peopleApi })) + return true + }) } }, + }) return true }) } diff --git a/mobile/src/features/sheet.tsx b/mobile/src/features/sheet.tsx index ba154e9..d72db2d 100644 --- a/mobile/src/features/sheet.tsx +++ b/mobile/src/features/sheet.tsx @@ -30,7 +30,7 @@ import { loggedMinutes } from '../lib/minutes.js' import { titleFor } from '../lib/naming.js' import { loggedActivity } from '../lib/activities.js' import { currentMe } from '../lib/whoami.js' -import { sharePeople, sharedPeopleOn, isSynced } from '../lib/shared.js' +import { sharePeople, sharedPeopleOn, syncedSides, planShown, ownWordsOn, withStoredWords } from '../lib/shared.js' import { PersonSwitch, SharedNote, TheirSide, usePersonCopy, useSide, TogetherPending, ShareChip, SharePanel, useSharing, useSidesDone, @@ -136,7 +136,9 @@ export function SessionSheet({ const done = planned && isDone(entry) // The prescription, if this session has one. Its presence turns the sheet from // a protocol you read into a workout you edit. - const pres = entry?.data?.plan || null + // As this log's person sees it: on a copy, never the owner's planner words, the + // exercises' notes included (lib/shared.js `planShown`, #96). Every use below reads it. + const pres: any = planShown(entry) /* * DOING MODE (#79, D9). A planned workout on its day or after is where the * lifting is done, so the sheet opens on the work: the first exercise with a @@ -169,7 +171,6 @@ export function SessionSheet({ const sidePerson = (side && on.find((p) => p.id === side)) || null const theirs = usePersonCopy(sidePerson?.id, sidePerson?.entryId, sidePerson?.name) const theirLog = usePersonLog(sidePerson?.id || null) - const synced = Boolean(sidePerson && isSynced(entry, sidePerson.id)) // The entry as of the latest render, for writes that land after a tap. const latestEntry = useRef(entry) latestEntry.current = entry @@ -187,8 +188,10 @@ export function SessionSheet({ const flipMine = useDoneFlip({ read: () => latestEntry.current, outlives: true, write: (v: any) => { setDirty(true); onSetDone?.(latestEntry.current, v) } }) /* Their plan, edited from their side: the same write `savePlan` makes on the owner's. */ - const saveTheirPlan = (next: any) => { setDirty(true); theirs.update((cur: any) => applyPlan(cur, opt, next)) } - const theirPres = theirs.entry?.data?.plan || null + /* What the sheet shows is `planShown`; what it writes is the stored plan with the + edit in it, every hidden word back as stored (lib/shared.js `withStoredWords`). */ + const saveTheirPlan = (next: any) => { setDirty(true); theirs.update((cur: any) => applyPlan(cur, opt, withStoredWords(cur, next))) } + const theirPres: any = planShown(theirs.entry) /* A write to their log that did not land says so, with the way to send it again. It stays only while it is true: the cleanup takes it down when the error @@ -258,15 +261,14 @@ export function SessionSheet({ if (planned && !isFuture && onSetDone) status = if (startable) footer = start() } - /* The other sides of a synced workout, for a removal toast's one line about them - (lib/removal.js: never a claim about what happened there). */ const planTalk = pres ? ( { setDirty(true); onSavePlan?.(latestEntry.current, next) }} /> + // What this person asks the model on their own copy is theirs to read (`ownWordsOn`). + onChange={(next: any) => { setDirty(true); onSavePlan?.(latestEntry.current, ownWordsOn(latestEntry.current, next)) }} /> ) : null - const syncedWith = sidePerson - ? (synced ? ['you'] : null) - : (() => { const s = on.filter((p) => isSynced(entry, p.id)).map((p) => p.name); return s.length ? s : null })() + /* The other sides of a synced workout, for a removal toast's one line about them + (lib/removal.js: never a claim about what happened there). */ + const syncedWith = syncedSides(entry, on, sidePerson) /* Under the title: the done chip, then who is on it ("with Sam · in sync ›", #80). */ /* Whose copy this sheet is filling in (only on a shared workout) sits in the header too, so it stays put while the body scrolls (the web pins it with @@ -367,7 +369,7 @@ export function SessionSheet({ {planTalkWhere({ ai, doing }) === 'sheet' ? planTalk : null} { setDirty(true); onSavePlan?.(latestEntry.current, next) }} syncedWith={syncedWith} compact + onChange={(next: any) => { setDirty(true); onSavePlan?.(latestEntry.current, withStoredWords(latestEntry.current, next)) }} syncedWith={syncedWith} compact doing={doing} asWritten={asWritten(entry)} /> {pres.notes?.length > 0 && ( diff --git a/mobile/src/lib/category.js b/mobile/src/lib/category.js index b5b20c5..8cfdbe0 100644 --- a/mobile/src/lib/category.js +++ b/mobile/src/lib/category.js @@ -55,3 +55,33 @@ function filedOut(entry) { const activity = plan.activity || named.activity || null return { ...out, ...(category ? { category } : {}), ...(activity ? { activity } : {}) } } + +/** + * `out` as a logging form shows it (#96): an older copy's own `out`, with the + * activity its plan files it under when it names none, so its "What kind of + * workout was this?" reads Lift, as a new copy's does, instead of asking with + * nothing picked. Only the activity, and only for the form: what is stored is + * written when the person saves, never by reading. + * + * A plan that names only a category (`lift`, no activity) reads the content's + * lifting activity when that category is the lifting activity's own: the first + * catalog activity whose shape the session's lift field asks for, the rule a + * plan with no filing is placed by (prescription.js `circuitFiling`). Any other + * category alone (support, a run) names no one activity and is left to ask. + */ +export function formOut(entry, session = null) { + const out = entry?.data?.out || {} + if (out.activity) return out + const filed = filedOut(entry) + const activity = filed.activity || liftingActivityFor(filed.category, session) + return activity ? { ...out, activity } : out +} + +function liftingActivityFor(category, session) { + if (!category) return null + const outputs = session?.outputs || [] + const shapes = outputs.find(o => o?.type === 'lifts')?.when?.shape || [] + const field = outputs.find(o => o?.type === 'activity') + const act = (field?.activities || []).find(a => shapes.includes(a?.shape)) + return act && act.category === category ? act.key : null +} diff --git a/mobile/src/lib/history.js b/mobile/src/lib/history.js index b9362ed..46216b9 100644 --- a/mobile/src/lib/history.js +++ b/mobile/src/lib/history.js @@ -70,17 +70,54 @@ export function samePlanned(entry, e) { return sameExercises(exercisesOf(entry), exercisesOf(e)) } +/** + * Where an entry sits in its day, as the day list shows it (tabs.jsx): the main + * session first, then the extras by id. + */ +const dayPlace = (e) => [e?.data?.slot === 'extra' ? 1 : 0, String(e?.id || '')] + +/** + * When a session started, in ms, where something measured or stamped it: its + * run, the WHOOP or Strava workout attached to it, then its done tap. Null when + * nothing did (a lift typed on the sheet): a day carries no other clock. + */ +function startedAt(e) { + const d = e?.data || {} + for (const v of [d.run?.startedAt, d.out?.whoop?.start, d.out?.strava?.start, d.doneAt]) { + const t = typeof v === 'number' ? v : Date.parse(v) + if (Number.isFinite(t) && t > 0) return t + } + return null +} + +/** + * Is `e` before `me`: an earlier day, or earlier the same day, by when each + * started where both say, else by the day list's order. + */ +function before(e, me) { + if (String(e.date) !== String(me.date)) return String(e.date) < String(me.date) + const [ta, tb] = [startedAt(e), startedAt(me)] + if (ta !== null && tb !== null && ta !== tb) return ta < tb + const [a, b] = [dayPlace(e), dayPlace(me)] + return a[0] !== b[0] ? a[0] < b[0] : a[1] < b[1] +} + /** * Every time you DID this workout (`isDone`: not a plan still to come, not one - * marked undone), newest first, the entry being shown left out. `entry` is that - * entry; without it, it is looked up by `excludeId`, and a container's history - * without an entry to compare is none, never a guess. + * marked undone) BEFORE the one being shown, newest first, that one left out. + * `entry` is that entry; without it, it is looked up by `excludeId`, and a + * container's history without an entry to compare is none, never a guess. + * + * Before is by day, then by time (#96: a Nov 7 workout listed Nov 8's as "the + * last time"): an earlier day, or a session that started earlier the same day + * (`before`), so a second lift in the evening still says "earlier today". With + * no entry (a card not yet on a day) nothing is bounded. */ export function priorSessions(entries, session, excludeId, entry = null) { const ids = priorIdsOf(session) if (!ids.length) return [] - const all = (entries || []).filter(e => e?.kind === 'daily' && e.id !== excludeId && isDone(e)) const me = entry || (entries || []).find(e => e?.id === excludeId) || null + const all = (entries || []).filter(e => e?.kind === 'daily' && e.id !== excludeId && isDone(e) && (!me?.date || before(e, me))) let hits if (!session?.sched?.repeatVia) hits = all.filter(e => ids.includes(e.data?.optId)) else if (me?.data?.plan) hits = all.filter(e => samePlanned(me, e)) @@ -88,5 +125,5 @@ export function priorSessions(entries, session, excludeId, entry = null) { const activity = me?.data?.out?.activity hits = activity ? all.filter(e => ids.includes(e.data?.optId) && !e.data?.plan && e.data?.out?.activity === activity) : [] } - return hits.sort((a, b) => String(b.date).localeCompare(String(a.date))) + return hits.sort((a, b) => String(b.date).localeCompare(String(a.date)) || (before(a, b) ? 1 : before(b, a) ? -1 : 0)) } diff --git a/mobile/src/lib/prescription.js b/mobile/src/lib/prescription.js index d4d2d71..79cde36 100644 --- a/mobile/src/lib/prescription.js +++ b/mobile/src/lib/prescription.js @@ -769,7 +769,8 @@ export function circuitMinutes(pres) { function circuitRow(it, mark) { const rounds = Array.isArray(mark?.rounds) ? mark.rounds.filter(n => Number(n) > 0) : [] if (!rounds.length) return null - const byReps = circuitTiming(it).by === 'reps' + // A mark with no seconds was a count (`endCircuit`), whatever the item says now. + const byReps = circuitTiming(it).by === 'reps' || mark.seconds == null // The planned weight is what it was done with: a plan says "15 @ 10 lb". const weight = num(it.sets[0]?.weight) ?? '' return { @@ -796,7 +797,7 @@ function circuitRow(it, mark) { * write of a circuit done together (lib/trainer.js `togetherWrite`) can never * add its minutes twice. */ -export function endCircuit(run, pres, blockId, done = [], { at = Date.now(), seconds = 0, key = null, fill = false } = {}) { +export function endCircuit(run, pres, blockId, done = [], { at = Date.now(), seconds = 0, key = null, fill = false, counted = [] } = {}) { if (key != null && run?.circuitKeys?.[blockId] === key) return run const base = run || emptyRun(at) const block = (pres?.blocks || []).find(b => b.id === blockId) @@ -811,7 +812,12 @@ export function endCircuit(run, pres, blockId, done = [], { at = Date.now(), sec if (fill && (sets[setId] || skipped.includes(setId))) return const rounds = (done[i] || []).map(n => Math.round(n)).filter(n => n > 0) if (rounds.length) { - sets[setId] = { ...(circuitTiming(it).by === 'reps' ? {} : { seconds: rounds.reduce((a, b) => a + b, 0) }), rounds, at } + // A count is marked without seconds. `counted` (by index, a result from another + // side's clock): it counted this one, which decides only where this side's own + // timing is blank; a side that says reps or seconds keeps its own shape. + const own = circuitTiming(it).by + const byReps = own === 'reps' || (own === 'circuit' && counted[i] === true) + sets[setId] = { ...(byReps ? {} : { seconds: rounds.reduce((a, b) => a + b, 0) }), rounds, at } skipped = skipped.filter(id => id !== setId) } else if (!sets[setId] && !skipped.includes(setId)) skipped.push(setId) }) diff --git a/mobile/src/lib/shared.js b/mobile/src/lib/shared.js index 4dbb804..0f8a0dd 100644 --- a/mobile/src/lib/shared.js +++ b/mobile/src/lib/shared.js @@ -191,11 +191,15 @@ const noMode = ({ weightMode: _m, weightLabel: _l, ...rest }) => rest /** A copy of their own last set: its numbers as a start, but not typed until they type into it. */ const untypedCopy = ({ typed: _t, ...s }) => ({ ...s, note: '' }) -/** One of the owner's sets on their side: the target, not the owner's weight, and nothing they typed. */ -const theirSet = ({ typed: _t, ...s }) => ({ ...s, weight: null }) +/** One of the owner's sets on their side: the target, not the owner's weight, cue or anything they typed. */ +const theirSet = ({ typed: _t, ...s }) => ({ ...s, weight: null, note: '' }) -/** One of the owner's exercises on their side: the target, not the owner's weight or what it meant. */ -const theirItem = (item) => ({ ...noMode(item), sets: (item.sets || []).map(theirSet) }) +/** + * One of the owner's exercises on their side: the target, not the owner's + * weight, what it meant, or the planner's note on it ("3x10 at 95 was RPE 6 + * last time", written from the owner's log). + */ +const theirItem = (item) => ({ ...noMode(item), note: '', sets: (item.sets || []).map(theirSet) }) /** * The owner's plan as the start of theirs: the exercises, never the owner's @@ -205,8 +209,131 @@ const theirItem = (item) => ({ ...noMode(item), sets: (item.sets || []).map(thei * log (`thread`, `why`, `notes`, `changed`). */ function theirPlan(mine) { - const { draftId: _d, thread: _t, why: _w, notes: _n, changed: _c, ...plan } = mine - return { ...plan, why: '', notes: [], blocks: mine.blocks.map(b => ({ ...b, items: (b.items || []).map(theirItem) })) } + const { draftId: _d, ...plan } = ownerWordsOff(mine) + return { ...plan, blocks: mine.blocks.map(b => ({ ...b, items: (b.items || []).map(theirItem) })) } +} + +/** + * A plan without the words the planner wrote for the person it was made for: + * its reasoning (`why`), notes, the conversation (`thread`), the request (`ask`), + * what a revision changed, and its note on each exercise and set. On a copy + * those are the OWNER's: written from the owner's log, WHOOP recovery and + * weights included ("Yellow recovery today (51%)…", "3x10 at 95 was RPE 6 last + * time"), and nothing on them is about the person whose copy it is. A block's + * note stays: it is the workout's own prose (a warm-up block exists by it) and + * shared structure (server/sharedsync.js BLOCK_KEYS). + */ +function ownerWordsOff({ why: _w, notes: _n, thread: _t, ask: _a, changed: _c, ...plan }) { + const blocks = Array.isArray(plan.blocks) ? plan.blocks.map(b => ({ + ...b, + items: (Array.isArray(b?.items) ? b.items : []).map(it => ({ + ...it, note: '', sets: (Array.isArray(it?.sets) ? it.sets : []).map(x => ({ ...x, note: '' })), + })), + })) : plan.blocks + return { ...plan, why: '', notes: [], blocks } +} + +/** One shown plan per stored plan, so a screen given it keeps one object while nothing changed. */ +const shownOf = new WeakMap() + +/** + * The plan as THIS log's person sees it (#96): every screen that draws a plan + * reads it through here (the sheet's editor, notes and model panel, the + * runner), on the web and the phone. On a copy (`sharedFrom`) the owner's + * words are left out at display time, because copies shared before + * `theirPlan` stripped them still carry them. Display only: nothing stored is + * rewritten (AGENTS.md §4), by reading or by writing. Every write from such a + * screen goes back through `withStoredWords`, which puts each hidden word back + * exactly as stored, so the person's edit lands on the stored plan. + * + * Words the person wrote with the model on their own copy are theirs, and the + * sheet stamps them so (`ownWords`, `ownWordsOn`): such a plan is shown whole. + */ +export function planShown(entry) { + const plan = entry?.data?.plan + if (!plan || typeof plan !== 'object') return null + if (!entry.data.sharedFrom || plan.ownWords === true) return plan + if (!shownOf.has(plan)) shownOf.set(plan, ownerWordsOff(plan)) + return shownOf.get(plan) +} + +const WORD_KEYS = ['why', 'notes', 'thread', 'ask', 'changed'] + +/** `to` with `key` exactly as `from` has it: the same value, or no key when `from` has none. */ +function sameKey(to, from, key) { + if (from && Object.prototype.hasOwnProperty.call(from, key)) return to[key] === from[key] ? to : { ...to, [key]: from[key] } + if (!Object.prototype.hasOwnProperty.call(to, key)) return to + const { [key]: _gone, ...rest } = to + return rest +} + +/** + * A plan edited on a screen that was SHOWN `planShown`, made a write to the + * stored plan (#96 review 2): the filter is for what is drawn, never for what + * is stored (AGENTS.md §4). Every word it hid comes back exactly as stored, + * byte for byte, a key the stored plan never had included: the plan's own + * (`why`, `notes`, `thread`, `ask`, `changed`) and each exercise's and set's + * `note`. An exercise is the stored one by its uid, else by its name and which + * of that name it is (`keyed`), else by its id; a set by its place in it. What + * the person added has nothing stored to take, and keeps its blank. Anything + * the filter did not touch (not a copy, or words that are the person's own, + * `ownWords`, which a model revision on their copy writes) is `next` as it is. + * Used by every write from those screens: the sheet's editor, on the person's + * own side and on the owner's view of it, and the runner. + */ +export function withStoredWords(entry, next) { + const stored = entry?.data?.plan + if (!next || typeof next !== 'object' || !stored || typeof stored !== 'object') return next + if (!entry.data.sharedFrom || stored.ownWords === true || next.ownWords === true) return next + const byUid = new Map() + const byKey = new Map() + const byId = new Map() + for (const { key, item } of keyed(stored)) { + if (item?.uid) byUid.set(item.uid, item) + byKey.set(key, item) + if (item?.id) byId.set(item.id, item) + } + const claimed = new Set() + const claim = (m) => (m && !claimed.has(m) ? (claimed.add(m), m) : null) + const seen = new Map() + let plan = next + for (const k of WORD_KEYS) plan = sameKey(plan, stored, k) + if (!Array.isArray(next.blocks)) return plan + const blocks = next.blocks.map(b => ({ + ...b, + items: (Array.isArray(b?.items) ? b.items : []).map(it => { + const name = String(it?.name || '') + const n = (seen.get(name) || 0) + 1 + seen.set(name, n) + const was = claim(it?.uid && byUid.get(it.uid)) || claim(byKey.get(`${name}#${n}`)) || claim(it?.id && byId.get(it.id)) + if (!was) return it + const sets = (Array.isArray(it.sets) ? it.sets : []).map((x, i) => (was.sets?.[i] ? sameKey(x, was.sets[i], 'note') : x)) + return { ...sameKey(it, was, 'note'), sets } + }), + })) + return { ...plan, blocks } +} + +/** + * A plan written by the model panel on this person's own copy: its words are + * now theirs (`planShown` shows them). Anything that is not a copy is as it is. + */ +export const ownWordsOn = (entry, plan) => (entry?.data?.sharedFrom && plan ? { ...plan, ownWords: true } : plan) + +/** + * Who a removal's toast says the exercises stay in step with (lib/removal.js + * `syncLine`), or null: the other sides of this synced workout, from where the + * sheet stands (#96, folded out of both sheets). On the owner's side, everyone + * on it with sync on (`on`, `sharedPeopleOn`); on someone else's side, the owner + * ("you"); and on the other person's OWN copy, whoever shared it, when the + * server says it is in step (`inStep`): a removal there reaches the owner's log too. + */ +export function syncedSides(entry, on = [], side = null) { + if (side) return isSynced(entry, side.id) ? ['you'] : null + const names = on.filter(p => isSynced(entry, p.id)).map(p => p.name) + if (names.length) return names + if (!on.length && inStep(entry)) return [String(entry.data.sharedFrom.name || '').trim() || 'the person who shared it'] + return null } /** Their plan with every exercise and set of the owner's that it lacks. Never takes anything out. */ @@ -392,21 +519,49 @@ export async function addPerson({ ownerEntry, person, session = null, owner = nu } /** - * Take someone off the owner's workout. Their copy is tombstoned only if they - * have put nothing of their own on it; otherwise `confirmFn` is asked first, and - * a no leaves both entries as they were. Resolves the owner's entry to write, - * or null when nothing should change. + * Take someone off the owner's workout (#96). Nothing they logged is ever lost + * by it: a copy they have put something of their own on (`hasOwnMarks`) is KEPT + * in their log as their workout, only no longer linked (the server then flags + * it not in step, `flagChanges`); one they have not touched is tombstoned, as + * it holds nothing but the owner's exercises. No question either way: the toast + * says which (`takeOffWords`), with Undo (`undoTakeOff`). + * + * This used to tombstone a logged copy too, after a bare "take it out of Sam's + * log anyway?" with no Undo: one tap on the owner's phone deleted someone + * else's sets and weights. + * + * Resolves `{ ownerEntry, link, copy, kept }`, or null when they are not on it: + * the owner's entry to write, the link as it was, and their copy as it was read. */ -export async function removePerson({ ownerEntry, person, session = null, api, confirmFn }) { +export async function removePerson({ ownerEntry, person, session = null, api }) { const link = sharedWithOf(ownerEntry).find(s => s.id === person.id) if (!link) return null const copy = await api.getPersonEntry(person.id, link.entryId) - if (copy && !copy.deleted) { - if (hasOwnMarks(copy, session)) { - const yes = await confirmFn(`${person.name} has already logged some of this. Take it out of ${person.name}'s log anyway?`) - if (!yes) return null - } - await api.putPersonEntry(person.id, tombstoneOf(copy)) + const live = Boolean(copy && !copy.deleted) + const kept = live && hasOwnMarks(copy, session) + if (live && !kept) await api.putPersonEntry(person.id, tombstoneOf(copy)) + return { ownerEntry: withSharedPerson(ownerEntry, person.id, null, { remove: true }), link, copy: live ? copy : null, kept } +} + +/** What taking someone off did, in the toast: only what is certain. */ +export function takeOffWords(person, { kept = false } = {}) { + return kept + ? `Took ${person.name} off this workout. It stays in ${person.name}\u2019s log with what ${person.name} logged.` + : `Took ${person.name} off this workout` +} + +/** + * Undo of `removePerson`: their copy back if it was tombstoned (the copy as it + * was, stamped now so it wins over the tombstone), then the owner's entry with + * the link exactly as it was, sync flag included. Resolves the owner's entry to + * write. `ownerEntry` is the owner's entry NOW, not as it was taken off. + */ +export async function undoTakeOff({ ownerEntry, person, taken, api, now = new Date().toISOString() }) { + const { link, copy, kept } = taken + if (copy && !kept) { + const { deleted: _d, ...back } = copy + await api.putPersonEntry(person.id, { ...back, updatedAt: now }) } - return withSharedPerson(ownerEntry, person.id, null, { remove: true }) + const rest = sharedWithOf(ownerEntry).filter(s => s.id !== person.id) + return { ...ownerEntry, data: { ...(ownerEntry.data || {}), sharedWith: [...rest, link] } } } diff --git a/mobile/src/lib/trainer.js b/mobile/src/lib/trainer.js index 9634c95..8740953 100644 --- a/mobile/src/lib/trainer.js +++ b/mobile/src/lib/trainer.js @@ -29,7 +29,7 @@ import { optFor } from './menu.js' import { sharePeople, sharedPeopleOn, addPerson } from './shared.js' import { isLiftOnly, followWeightModes, endCircuit, circuitOnly, circuitEnded, runProgress, prescriptionSteps, finishRun, - runOutputs, fillOut, blockTimer, remapRun, + runOutputs, fillOut, blockTimer, remapRun, circuitTiming, } from './prescription.js' import { compile, settle } from './timer.js' import { liftFieldIn } from './lifts.js' @@ -568,6 +568,15 @@ export const togetherWords = (sides = [], here = null) => { return names.length ? `Together with ${andWords(names)}` : '' } +/** + * A circuit's exercises as a result done together names them: the sync's uid, + * the name, and how the clock ran each one (`by`, prescription.js + * `circuitTiming`), so a side whose copy of an exercise arrived blank logs a + * counted exercise as a count, never as a hold of the seconds spent on its reps. + */ +export const togetherItems = (block) => (block?.items || []) + .map(it => ({ uid: it.uid || null, name: it.name, by: circuitTiming(it).by })) + /** * What one side's own entry gets from a circuit done together, by rule 1: * @@ -577,7 +586,8 @@ export const togetherWords = (sides = [], here = null) => { * { kind: 'running' } its own clock is going: leave it be * { kind: 'none' } it has no such circuit * - * `result` is `{ block: { uid, id, name }, items: [{ uid, name }], done, at, seconds, key, with }` + * `result` is `{ block: { uid, id, name }, items: [{ uid, name, by }], done, at, seconds, key, with }` + * (`togetherItems`; `by` is how the clock ran each exercise, absent on a miss kept from before #96) * from the side that ran the clock; `with` is who was offered Together when it * started (side ids, null for the owner), and only they are written. The block and each exercise are found here * by uid (the sync's identity), then by name, each of this side's exercises @@ -604,16 +614,20 @@ export function togetherWrite(entry, result, now = Date.now()) { if (circuitEnded(block, run) || run?.endedAt) return { kind: 'already' } } const taken = new Set() - const done = block.items.map(it => { + const match = block.items.map(it => { let j = it.uid ? result.items.findIndex((x, n) => !taken.has(n) && x.uid === it.uid) : -1 if (j < 0) j = result.items.findIndex((x, n) => !taken.has(n) && x.name === it.name) - if (j < 0) return [] - taken.add(j) - return result.done[j] || [] + if (j >= 0) taken.add(j) + return j }) + const done = match.map(j => (j < 0 ? [] : result.done[j] || [])) + // A count on the side that ran the clock is a count here too where this side's own + // timing is blank (#96): its seconds were time spent on reps, never a hold. A side + // that says reps or seconds keeps its own shape (`endCircuit`). + const counted = match.map(j => j >= 0 && result.items[j]?.by === 'reps') const base = run?.circuitKeys?.[block.id] === result.key ? { ...run, circuitKeys: { ...run.circuitKeys, [block.id]: null } } : run - let next = endCircuit(base, pres, block.id, done, { at: result.at, seconds: result.seconds, key: result.key, fill: true }) + let next = endCircuit(base, pres, block.id, done, { at: result.at, seconds: result.seconds, key: result.key, fill: true, counted }) const finished = circuitOnly(pres) && runProgress(next, prescriptionSteps(pres)).left === 0 if (finished) next = finishRun(next, { at: result.at }) const out = fillOut(entry.data.out || {}, runOutputs(pres, next, {})) diff --git a/server/http.test.js b/server/http.test.js index f40a480..2fedaf0 100644 --- a/server/http.test.js +++ b/server/http.test.js @@ -995,6 +995,44 @@ async function waitFor(fn, label, ms = 8000) { eq(ownOn(id).data.sharedFrom, undefined, 'the owner\'s own entry was flagged') }) + /* + * Taking someone off (#96, lib/shared.js removePerson / undoTakeOff): a copy Sam + * logged on is never deleted, only unlinked; Undo puts the link back exactly and + * Sam's numbers are as they were. An untouched copy is tombstoned and Undo writes + * it back through the people route, over its own tombstone. + */ + await step('take off (#96): Sam\'s logged copy stays and Undo relinks it; an untouched one comes back over its tombstone', async () => { + const { id } = await freshShare('2026-09-14', { sync: true }) + const logged = replan(theirsOn(id), bs => { bs[0].items[0] = { ...bs[0].items[0], sets: bs[0].items[0].sets.map(x => ({ ...x, reps: 8, weight: 40, typed: true })) }; return bs }) + eq((await saveSams({ ...logged, data: { ...logged.data, out: { rpe: 6 } } })).status, 200) + const sams = () => itemsIn(theirsOn(id)).map(i => [i.name, i.sets.map(x => [x.reps, x.weight])]) + const before = sams() + const link = ownOn(id).data.sharedWith[0] + eq((await saveOwn({ ...ownOn(id), data: { ...ownOn(id).data, sharedWith: [] } })).status, 200) + ok(!theirsOn(id).deleted, 'taking Sam off deleted what Sam logged') + eq([sams(), theirsOn(id).data.out.rpe, theirsOn(id).data.sharedFrom.sync], [before, 6, false]) + // Sam's now: the owner's devices can no longer write it (a stale sheet, a Together retry). + const kept = JSON.stringify(theirsOn(id)) + const refused = await post('sam', { ...theirsOn(id), updatedAt: tick(), data: { ...theirsOn(id).data, out: { rpe: 1 } } }) + eq([refused.status, (await refused.json()).code], [409, 'not-linked'], 'the owner wrote a copy Sam was taken off') + eq(JSON.stringify(theirsOn(id)), kept, 'a refused write changed Sam\'s copy') + eq((await saveSams({ ...theirsOn(id), data: { ...theirsOn(id).data, out: { rpe: 7 } } })).status, 200, 'Sam cannot write Sam\'s own copy') + eq((await saveOwn({ ...ownOn(id), data: { ...ownOn(id).data, sharedWith: [link] } })).status, 200) + eq((await post('sam', { ...theirsOn(id), updatedAt: tick() })).status, 200, 'relinked, the owner still cannot write it') + eq([sams(), theirsOn(id).data.sharedFrom.sync, ownOn(id).data.sharedWith, theirsOn(id).data.out.rpe], [before, true, [link], 7], 'Undo did not put it back as it was') + + const fresh = await freshShare('2026-09-15', { sync: true }) + const copy = theirsOn(fresh.id) + eq((await post('sam', { ...copy, deleted: true, updatedAt: tick() })).status, 200) + eq((await saveOwn({ ...ownOn(fresh.id), data: { ...ownOn(fresh.id).data, sharedWith: [] } })).status, 200) + ok(theirsOn(fresh.id).deleted, 'not tombstoned') + const { deleted: _d, ...back } = copy + eq((await post('sam', { ...back, updatedAt: tick() })).status, 200) + eq((await saveOwn({ ...ownOn(fresh.id), data: { ...ownOn(fresh.id).data, sharedWith: [{ id: 'sam', entryId: fresh.id, sync: true }] } })).status, 200) + ok(!theirsOn(fresh.id).deleted, 'Undo did not bring the copy back') + eq([namesIn(theirsOn(fresh.id)), theirsOn(fresh.id).data.sharedFrom.sync, theirsOn(fresh.id).data.done], [['Squat', 'Deadlift'], true, false]) + }) + /* ------------------------------------------ the owner as trainer (peopleRoute) */ const planned = { id: 'daily-2026-10-08', kind: 'daily', date: '2026-10-08', updatedAt: '2026-10-08T07:00:00Z', data: { optId: 'planned', slot: 'main', done: true, name: 'Legs', plan: { title: 'Legs', blocks: [] }, out: {}, plannedBy: { id: 'sam', name: 'forged' } } } diff --git a/server/server.js b/server/server.js index a4c3b93..cf2e22f 100644 --- a/server/server.js +++ b/server/server.js @@ -1517,6 +1517,10 @@ function proxySettingsRefusal(mode, req, p) { * they logged themselves, and the owner must never overwrite it (409 * `not-shared`; the app picks another id). * Both markers are stamped here from users.json, never taken from the request. + * - A copy whose person was taken off is theirs now (409 `not-linked`, #96): + * the server stamps it `sharedFrom.off` when the owner's link to it goes and + * clears that when one comes back. A copy never linked yet is not refused, + * because adding someone writes the copy first and links it second. * - A planned session is a daily entry with a derivable id. (Planning someone's * week, their `quota-`, went with the quotas on 2026-10-25.) * - A new daily entry is `done: false` whatever the request said, so it never @@ -1557,6 +1561,16 @@ function syncLinksFor(space) { } } +/** + * Is this copy still on one of the owner's workouts (a link in `sharedWith`, sync + * on or off)? A copy whose person was taken off is theirs now (#96): it stays in + * their log, and the owner's devices no longer write to it (`peopleRoute`). + */ +function copyLinked(ownerLog, personId, copy) { + return Object.values(ownerLog).some(e => e?.kind === 'daily' && e.date === copy.date + && sharedSync.allLinks(e).some(l => l.id === personId && l.entryId === copy.id)) +} + /** The owner's entry that links this copy with sync on, or null. */ function ownerEntryLinking(ownerLog, personId, copy) { for (const e of Object.values(ownerLog)) { @@ -1582,7 +1596,7 @@ async function commitSynced(space, ids, merge) { const r = sharedSync.onWrite(base, next, ids, syncLinksFor(space)) carries = r.carries acks = r.acks - return space.owner ? r.state : flagWritten(space, r.state, ids) + return space.owner ? r.state : flagWritten(space, r.state, ids, base) }) for (const c of carries) { try { await carryShared(space, c) } catch (err) { console.error('[bushido] shared workout sync failed:', err.message) } @@ -1592,7 +1606,7 @@ async function commitSynced(space, ids, merge) { for (const f of sharedSync.flagChanges(before, doc.state, ids)) { const person = users.get(f.personId) try { - if (person) await commit(spaceFor(person), st => (isCopy(st.entries?.[f.entryId] || {}) ? sharedSync.flagCopy(st, f.entryId, f.sync) : st)) + if (person) await commit(spaceFor(person), st => (isCopy(st.entries?.[f.entryId] || {}) ? sharedSync.flagCopy(st, f.entryId, f.sync, f.linked) : st)) } catch (err) { console.error('[bushido] shared workout flag failed:', err.message) } } } @@ -1606,7 +1620,7 @@ async function commitSynced(space, ids, merge) { * device sent. A stale phone cannot say "in step" over a link switched off, or * rename who it was shared by. */ -function flagWritten(space, state, ids) { +function flagWritten(space, state, ids, before = null) { let ownerLog = null let out = state const owner = users.owner() @@ -1615,7 +1629,10 @@ function flagWritten(space, state, ids) { const e = out.entries?.[id] if (!e || e.deleted || !isCopy(e)) continue ownerLog = ownerLog || readStateSync(OWNER_SPACE).state.entries || {} - const data = sharedSync.flagged(e.data, Boolean(ownerEntryLinking(ownerLog, space.id, e)), stamp) + // Taken off stays taken off while no link is back, whatever a stale device sent (#96). + const was = before?.entries?.[id] + const off = !copyLinked(ownerLog, space.id, e) && (e.data.sharedFrom.off === true || (!was?.deleted && was?.data?.sharedFrom?.off === true)) + const data = sharedSync.withOff(sharedSync.flagged(e.data, Boolean(ownerEntryLinking(ownerLog, space.id, e)), stamp), off) if (data !== e.data) out = { ...out, entries: { ...out.entries, [id]: { ...e, data } } } } return out @@ -1714,6 +1731,7 @@ async function peopleRoute(req, res, url, ctx) { } const owner = users.owner() const NOT_SHARED = 'not-shared' + const NOT_LINKED = 'not-linked' let doc let acks try { @@ -1722,6 +1740,12 @@ async function peopleRoute(req, res, url, ctx) { const live = cur && !cur.deleted // Thrown, not returned: a refusal must not write a new version or a backup. if (live && !fromOwner(cur.data)) throw new Error(NOT_SHARED) + // A copy they were taken off is theirs now (#96): only they write it. Known by + // the server's own stamp (`sharedFrom.off`), because a copy whose link has not + // been written yet (adding writes the copy first, then the link) has no link either. + if (live && cur.data.sharedFrom?.off === true && !copyLinked(readStateSync(OWNER_SPACE).state.entries || {}, person.id, cur)) { + throw new Error(NOT_LINKED) + } const stamp = { id: owner.id, name: owner.name } const data = { ...entry.data } if (data.sharedFrom) data.sharedFrom = stamp @@ -1731,6 +1755,9 @@ async function peopleRoute(req, res, url, ctx) { return mergeState(base, { entries: { [entry.id]: stamped } }) })) } catch (err) { + if (err.message === NOT_LINKED) { + return send(res, 409, { error: `${person.name} is no longer on this workout; it is ${person.name}'s own now`, code: NOT_LINKED }) + } if (err.message !== NOT_SHARED) throw err return send(res, 409, { error: `${person.name} already logged something else under that id`, diff --git a/server/sharedsync.js b/server/sharedsync.js index d090071..897a477 100644 --- a/server/sharedsync.js +++ b/server/sharedsync.js @@ -966,7 +966,7 @@ function allLinks(entry) { /** * The copies whose flag an owner's write changed (`prev` → `next`, the ids it * carried): sync switched, someone added or taken off, the entry removed. - * `[{ personId, entryId, sync }]`. + * `[{ personId, entryId, sync, linked }]`; `linked` false is taken off. */ function flagChanges(prev, next, ids) { const out = [] @@ -974,24 +974,37 @@ function flagChanges(prev, next, ids) { const was = new Map(allLinks(prev.entries?.[id]).map(l => [`${l.id}\n${l.entryId}`, l.sync])) const now = new Map(allLinks(next.entries?.[id]).map(l => [`${l.id}\n${l.entryId}`, l.sync])) for (const key of new Set([...was.keys(), ...now.keys()])) { - if (Boolean(was.get(key)) === Boolean(now.get(key))) continue + if (was.has(key) === now.has(key) && Boolean(was.get(key)) === Boolean(now.get(key))) continue const [personId, entryId] = key.split('\n') - out.push({ personId, entryId, sync: Boolean(now.get(key)) }) + out.push({ personId, entryId, sync: Boolean(now.get(key)), linked: now.has(key) }) } } return out } +/** + * `data` with `sharedFrom.off` saying whether its person was taken off the + * workout (#96): true once a link to it is removed, gone once one is back. A + * copy with it is theirs; the owner's devices no longer write it (server.js + * `peopleRoute`). A copy never linked yet (adding writes the copy first) has none. + */ +function withOff(data, off) { + const from = data?.sharedFrom + if (!isObj(from) || Boolean(from.off) === Boolean(off)) return data + const { off: _o, ...rest } = from + return { ...data, sharedFrom: off ? { ...rest, off: true } : rest } +} + /** A copy in `state` flagged, stamped a millisecond past its own time; `state` unchanged if nothing moves. */ -function flagCopy(state, entryId, synced) { +function flagCopy(state, entryId, synced, linked = true) { const e = state.entries?.[entryId] if (!e || e.deleted || !isObj(e.data)) return state - const data = flagged(e.data, synced) + const data = withOff(flagged(e.data, synced), !linked) if (data === e.data) return state return { ...state, entries: { ...state.entries, [entryId]: { ...e, data, updatedAt: bump(e.updatedAt) } } } } module.exports = { shapeOf, stampData, carry, rebase, intentOf, nextBase, align, syncedLinks, onWrite, receive, bump, - flagged, flagChanges, flagCopy, liftedOf, + flagged, flagChanges, flagCopy, liftedOf, allLinks, withOff, } diff --git a/server/sharedsync.test.js b/server/sharedsync.test.js index f420fd8..b74d963 100644 --- a/server/sharedsync.test.js +++ b/server/sharedsync.test.js @@ -246,13 +246,21 @@ check('a copy says whether it is in step (#80): set on a carry, switched with th const entry = (links) => ({ id: 'o', kind: 'daily', date: '2026-10-01', data: { sharedWith: links } }) const prev = { entries: { o: entry([{ id: 'sam', entryId: 'c1', sync: true }, { id: 'jo', entryId: 'c2' }]) } } const next = { entries: { o: entry([{ id: 'sam', entryId: 'c1' }, { id: 'kim', entryId: 'c3', sync: true }]) } } - eq(flagChanges(prev, next, ['o']), [{ personId: 'sam', entryId: 'c1', sync: false }, { personId: 'kim', entryId: 'c3', sync: true }]) + // Jo's link had sync off: taking Jo off still reaches Jo's copy (#96, `linked`). + eq(flagChanges(prev, next, ['o']), [{ personId: 'sam', entryId: 'c1', sync: false, linked: true }, + { personId: 'jo', entryId: 'c2', sync: false, linked: false }, { personId: 'kim', entryId: 'c3', sync: true, linked: true }]) eq(flagChanges(prev, prev, ['o']), []) - eq(flagChanges(prev, { entries: { o: { ...prev.entries.o, deleted: true } } }, ['o']), [{ personId: 'sam', entryId: 'c1', sync: false }]) + eq(flagChanges(prev, { entries: { o: { ...prev.entries.o, deleted: true } } }, ['o']), + [{ personId: 'sam', entryId: 'c1', sync: false, linked: false }, { personId: 'jo', entryId: 'c2', sync: false, linked: false }]) const log = { entries: { c1: { id: 'c1', updatedAt: '2026-10-01T00:00:00.000Z', data: copy } } } const f = flagCopy(log, 'c1', false) eq([f.entries.c1.data.sharedFrom.sync, f.entries.c1.updatedAt], [false, '2026-10-01T00:00:00.001Z']) ok(flagCopy(f, 'c1', false) === f, 'an unchanged flag wrote again') + // Taken off (#96): stamped `off`, and the stamp goes when a link is back. + const off = flagCopy(f, 'c1', false, false) + eq(off.entries.c1.data.sharedFrom, { id: 'owner', name: 'Alex', sync: false, off: true }) + eq(flagCopy(off, 'c1', true, true).entries.c1.data.sharedFrom, { id: 'owner', name: 'Alex', sync: true }) + ok(flagCopy(off, 'c1', false, false) === off, 'an unchanged stamp wrote again') }) check('a carry that changes something fills in what kind of workout it is on a side that names none (#74)', () => {