Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
coach (built-in): #160 findings 4/5/6/11 — forget keeps today's count, the instance cap is reserved at enqueue from its own counter instead of the 100-entry log, forget drops queued work, aborts the HTTP call and discards a late result, scheduled reviews advance on the server's own record and wait for an unread proposal
Boris Kurktchiev6d9d7a6cba65
diff --git a/api/coach/cadence.js b/api/coach/cadence.jsindex 7c79e388e..c088ea282 100644--- a/api/coach/cadence.js+++ b/api/coach/cadence.js@@ -14,15 +14,21 @@ import * as cfgStore from './config.js';const TICK_MS = 60000;-/** Weekly cadence fires within the minute; everyWorkouts fires as soon as the count is met. */-export function isDue(coach, S, now) {+/** Weekly cadence fires within the minute; everyWorkouts fires as soon as the count is met.+ * `reviewedAt` is when the server last finished a review for this person: the client stamps+ * lastReview only once someone acts on a proposal, and a review nobody has opened yet — or+ * one that found nothing to change — still read those workouts. */+export function isDue(coach, S, now, reviewedAt = 0) {const cadence = coach.cadence;if (!cadence || cadence === 'off') return false;- const lastAt = coach.lastReview?.at || 0;+ const lastAt = Math.max(coach.lastReview?.at || 0, reviewedAt);// Nothing new to read is the most common reason not to run, and it applies to both modes.const workouts = S.workouts || [];- const since = workouts.filter(w => !lastAt || (w.end || 0) > lastAt || w.d > new Date(lastAt).toISOString().slice(0, 10));+ // A workout's `end` is on the same clock as the review's timestamp; its `d` is the phone's+ // local day, which can run ahead of the server's UTC day, so the date only stands in for a+ // workout that has no end.+ const since = workouts.filter(w => !lastAt || (w.end ? w.end > lastAt : w.d > new Date(lastAt).toISOString().slice(0, 10)));if (!since.length) return false;if (cadence.everyWorkouts) {@@ -50,9 +56,21 @@ export function startCadence(deps) {const S = jobs.readState(user.id);const coach = S?.coach;if (!coach?.consent?.agreedAt) continue; // consent revoked ⇒ cadence stops+ // A job still running, or a proposal nobody has answered, is not a reason for another:+ // a second review would only replace the first unread. status() also retires an+ // expired proposal, which a phone that stays closed never polls for.+ const st = jobs.status(user.id);+ if (st.job || st.pending) continue;+ // Reviewed means the model read those workouts and answered — with a proposal, with+ // "nothing to change", or with an answer that failed validation and was paid for all the+ // same. A call that never reached it (timeout, no runtime, consent, switched off) is retried.+ const reviewedAt = Math.max(0, ...jobs.readUser(user.id).history+ .filter(h => h.kind === 'review' && (h.outcome === 'ready' || h.outcome === 'nochange'+ || (h.outcome === 'failed' && h.errorClass === 'unusable')))+ .map(h => h.at || 0));const tz = coach.cadence?.weekly ? (S.reminder?.tz || 'UTC') : null;const now = tz ? deps.userNow(tz) : null;- if (!isDue(coach, S, now)) continue;+ if (!isDue(coach, S, now, reviewedAt)) continue;jobs.enqueue(user.id, { kind: 'review', trigger: 'scheduled' });console.log('coach: scheduled review queued for', user.id);} catch (e) {diff --git a/api/coach/config.js b/api/coach/config.jsindex 88588c873..02abe5f94 100644--- a/api/coach/config.js+++ b/api/coach/config.js@@ -81,6 +81,7 @@ const DEFAULTS = {providerOptions: {}, // { [provider]: { baseUrl } }boundUid: {}, // instance mode: { [provider]: the profile its credential bound to }caps: { perProfileDaily: 10, instanceDaily: 0 }, // 0 = unlimited+ daily: null, // { date, count }: jobs enqueued today across every profile// Anonymous medians across profiles that opt in ("compare with others"). Off by default: it// is the one feature where one person's numbers feed into what another person sees.community: false,diff --git a/api/coach/core/adapters/http.js b/api/coach/core/adapters/http.jsindex 05410e76f..2900e8c63 100644--- a/api/coach/core/adapters/http.js+++ b/api/coach/core/adapters/http.js@@ -42,6 +42,8 @@ async function call(fetchImpl, url, init, timeoutMs, signal) {const ctl = new AbortController();const onOuter = () => ctl.abort();if (signal) signal.addEventListener('abort', onOuter, { once: true });+ // An abort that already landed (during a retry pause, say) must not let a fresh request leave.+ if (signal && signal.aborted) ctl.abort();const timer = setTimeout(() => ctl.abort(), timeoutMs);try {return await fetchImpl(url, { ...init, signal: ctl.signal });diff --git a/api/coach/jobs.js b/api/coach/jobs.jsindex 9bddc270e..f4ab6b050 100644--- a/api/coach/jobs.js+++ b/api/coach/jobs.js@@ -63,9 +63,22 @@ function patchUser(uid, patch) {writeUser(uid, rec);return rec;}-/** Consent revoked, profile deleted, "reset everything" — no server-side residue (FR-51). */+/** Consent revoked, profile deleted, "reset everything" — no server-side residue (FR-51).+ * Today's job count is the one thing that stays: it is the spending record the daily cap+ * reads, not the profile's data, and forgetting must not hand out a fresh cap; the record+ * outlives the day only until the next job or forget touches it, and counts for nothing once+ * the date has passed. A job still waiting in the queue is dropped here; one already mid-call+ * is cancelled where the adapter can be (the HTTP ones — a spawned runtime runs to its end),+ * and either way finishes without writing anything back (see finish). */export function clearUser(uid) {+ const { daily } = readUser(uid);try { fs.unlinkSync(userFile(uid)); } catch { /* nothing to clear */ }+ if (daily?.date === todayISO()) writeUser(uid, { ...EMPTY, daily });+ const queued = queue.findIndex(j => j.uid === uid);+ if (queued >= 0) { queue.splice(queued, 1); inflight.delete(uid); }+ aborts.get(uid)?.abort();+ forgetSeq.set(uid, (forgetSeq.get(uid) || 0) + 1);+ invalidateCohort();}/** Every profile with a state file — the population a cohort is drawn from. */@@ -107,9 +120,16 @@ export function capState(uid) {const used = rec.daily?.date === todayISO() ? rec.daily.count : 0;return { used, limit: caps.perProfileDaily || 0 };}-function instanceUsedToday() {+// The instance-wide count is kept the same way in coach.json, not read off the job log: the+// log keeps its last hundred entries, and a count that stops at a hundred is not a cap.+function bumpInstanceDaily() {+ const cur = cfgStore.load().daily;const d = todayISO();- return (cfgStore.load().log || []).filter(e => (e.at || '').slice(0, 10) === d).length;+ cfgStore.save({ daily: cur?.date === d ? { date: d, count: cur.count + 1 } : { date: d, count: 1 } });+}+function instanceUsedToday() {+ const daily = cfgStore.load().daily;+ return daily?.date === todayISO() ? daily.count : 0;}/* ---------- status ---------- */@@ -148,6 +168,8 @@ function archive(uid, rec, outcome) {const queue = [];let running = 0;const inflight = new Set(); // uids with a job queued or running (FR-07 single-flight)+const forgetSeq = new Map(); // uid → bumped by every clearUser; a job carries the value it saw at enqueue+const aborts = new Map(); // uid → AbortController of the provider call in flight, for clearUser to pullclass CoachError extends Error {constructor(code, message) { super(message); this.code = code; }@@ -197,10 +219,12 @@ export function enqueue(uid, opts) {// of the owner's provider account, and queueing twenty jobs spends it whether or not the// twentieth ever finishes.bumpDaily(uid);+ bumpInstanceDaily();const job = {id: crypto.randomBytes(8).toString('hex'),uid,+ forgetSeq: forgetSeq.get(uid) || 0,kind: opts.kind, // 'create' | 'review' | 'debrief'trigger: opts.trigger || 'manual', // 'manual' | 'scheduled'workoutId: opts.workoutId ? String(opts.workoutId).slice(0, 40) : null,@@ -228,6 +252,14 @@ function pump() {}function finish(job, result) {+ cfgStore.logJob({+ at: new Date().toISOString(), uid: job.uid, kind: job.kind, trigger: job.trigger,+ outcome: result.outcome, errorClass: result.errorClass || null,+ ms: Date.now() - job.startedAt, detail: result.detail || null+ });+ // Forgotten while it ran: the record is gone and stays gone, and nobody is notified. The+ // job still ran and still spent, which is why the instance log above keeps its line.+ if ((forgetSeq.get(job.uid) || 0) !== job.forgetSeq) return;const rec = readUser(job.uid);const history = [...(rec.history || []), {id: job.id, kind: job.kind, trigger: job.trigger, outcome: result.outcome,@@ -244,11 +276,6 @@ function finish(job, result) {pending: result.pending !== undefined ? result.pending : rec.pending,history});- cfgStore.logJob({- at: new Date().toISOString(), uid: job.uid, kind: job.kind, trigger: job.trigger,- outcome: result.outcome, errorClass: result.errorClass || null,- ms: Date.now() - job.startedAt, detail: result.detail || null- });if (result.outcome === 'ready' && onProposal) {try { onProposal(job.uid, result.pending, job); } catch (e) { console.error('coach notify failed', e); }}@@ -266,6 +293,10 @@ async function execute(job) {const S = readState(job.uid);if (!S) return finish(job, { outcome: 'failed', errorClass: 'nostate' });+ // Checked again here, not only at enqueue: a job can wait behind two others, and consent+ // withdrawn or the Coach switched off in the meantime means no payload leaves for it.+ if (!S.coach?.consent?.agreedAt) return finish(job, { outcome: 'failed', errorClass: 'consent' });+ if (!cfgStore.isEnabled()) return finish(job, { outcome: 'failed', errorClass: 'off' });const cfg = cfgStore.load();const adapter = adapterFor(cfg.provider);@@ -292,17 +323,22 @@ async function execute(job) {// An HTTPS provider has no child process, so no directory for one to live in either.const jobDir = adapter.spawns === false ? null : fs.mkdtempSync(path.join(os.tmpdir(), 'coach-'));const env = cfgStore.jobEnv(jobDir || os.tmpdir(), cfgStore.credentialFor(job.uid));+ const ctl = new AbortController();+ aborts.set(job.uid, ctl);try {const ids = jobDir && unprivilegedIds();if (ids) fs.chownSync(jobDir, ids.uid, ids.gid);const attempt = await runPipeline({adapter, cfg, kind: job.kind, payload, model: cfgStore.modelFor(cfg), timeoutMs: TIMEOUT_MS,- // The HTTP adapters take the fetch they are given; the runtime adapters ignore it.- invokeOpts: { jobDir, env, fetch: fetchFor(TIMEOUT_MS) }+ // The HTTP adapters take the fetch and the abort signal they are given; the runtime+ // adapters ignore both.+ invokeOpts: { jobDir, env, fetch: fetchFor(TIMEOUT_MS), signal: ctl.signal }});if (!attempt.ok) {- return finish(job, { outcome: 'failed', errorClass: attempt.errorClass, detail: attempt.detail });+ // Cancelled by a forget, not failed by the provider: the log must not blame the job budget.+ const errorClass = ctl.signal.aborted ? 'forgotten' : attempt.errorClass;+ return finish(job, { outcome: 'failed', errorClass, detail: attempt.detail });}if (attempt.nochange) {return finish(job, { outcome: 'nochange', pending: null, detail: null, reading: attempt.reading });@@ -320,6 +356,7 @@ async function execute(job) {};return finish(job, { outcome: 'ready', pending });} finally {+ aborts.delete(job.uid);if (jobDir) fs.rmSync(jobDir, { recursive: true, force: true });}}diff --git a/api/coach/routes.js b/api/coach/routes.jsindex 32076e3a6..1a9f81081 100644--- a/api/coach/routes.js+++ b/api/coach/routes.js@@ -179,7 +179,8 @@ export function coachRoutes({ json, readBody, readSession, requireAdmin }) {? { ok: true, dropped: false, why: 'this provider runs no child process' }: canDropPrivileges(),// Counts and outcomes only — never intake answers, payloads or proposals (FR-12/A4).- jobsToday: log.filter(e => (e.at || '').slice(0, 10) === today).length,+ // The same counter the instance cap reads, so the card and the cap cannot disagree.+ jobsToday: cfg.daily?.date === today ? cfg.daily.count : 0,lastSuccess: cfgStore.lastSuccess(),lastError: cfgStore.lastError(),recent: log.slice(-20).reverse().map(e => ({ at: e.at, kind: e.kind, trigger: e.trigger, outcome: e.outcome, errorClass: e.errorClass, ms: e.ms }))diff --git a/api/test/adapters-http.test.js b/api/test/adapters-http.test.jsindex dec527be6..583f6c52b 100644--- a/api/test/adapters-http.test.js+++ b/api/test/adapters-http.test.js@@ -18,10 +18,12 @@ const { attemptOnce } = await import('../coach/core/pipeline.js');const { HTTP_PROVIDERS, validateBaseUrl } = await import('../coach/core/providers.js');const { SYSTEM_PROMPT } = await import('../coach/core/system-prompt.js');-/** A fetch that records what it was asked and answers from a script. */+/** A fetch that records what it was asked and answers from a script. Like the real one, it+ * refuses an already-aborted signal without putting anything on the wire. */function fakeFetch(answers) {const calls = [];const f = async (url, init) => {+ if (init.signal?.aborted) throw Object.assign(new Error('aborted'), { name: 'AbortError' });calls.push({ url, method: init.method, headers: init.headers || {}, body: init.body ? JSON.parse(init.body) : null });const a = typeof answers === 'function' ? answers(calls.length, url, init) : answers[Math.min(calls.length, answers.length) - 1];if (a instanceof Error) throw a;@@ -168,6 +170,19 @@ test('a transient status (429, 5xx, 529) is retried twice with the same request,assert.equal(f.calls.length, 1);});+test('an abort that lands during a retry pause sends nothing more and ends as a timeout', async () => {+ // A forget mid-backoff: the payload must not go out a second time, and the job must drain+ // now rather than wait for the next attempt to time out.+ const ac = new AbortController();+ const f = fakeFetch([{ status: 429, body: { error: { message: 'slow down' } } }]);+ const p = openai.invoke({ cfg: {}, prompt: 'P', env, fetch: f, signal: ac.signal, retryDelayMs: 10000 });+ await new Promise(r => setTimeout(r, 20)); // the first 429 is back and the pause has begun+ ac.abort();+ const r = await p;+ assert.equal(f.calls.length, 1, 'the payload is not sent again');+ assert.equal(r.timedOut, true);+});+test('a body that is not JSON on an error still yields a readable stderr', async () => {const f = fakeFetch([{ status: 502, body: '<html>bad gateway</html>' }]);const r = await gemini.invoke({ cfg: {}, prompt: 'P', env, fetch: f });diff --git a/api/test/coach-limits.test.js b/api/test/coach-limits.test.jsnew file mode 100644index 000000000..822c833bc--- /dev/null+++ b/api/test/coach-limits.test.js@@ -0,0 +1,227 @@+/* What bounds the Coach's spend, pinned against the real queue and the fixture provider.+ *+ * Forget keeps today's per-profile count. The instance count is reserved at enqueue and is+ * not read off the capped job log. A scheduled review covers a batch of workouts once, on the+ * workout's own clock rather than the phone's local date, and an answer the model was paid+ * for counts as that review even when it was unusable. */+import test from 'node:test';+import assert from 'node:assert/strict';+import fs from 'node:fs';+import { tempData, writeState, sampleState } from './helpers.mjs';++const DIR = tempData();+const cfg = await import('../coach/config.js');+const jobs = await import('../coach/jobs.js');+const cadence = await import('../coach/cadence.js');+const { forcePrivilegeVerdict } = await import('../coach/adapters/spawn.js');++cfg.save({ enabled: true, provider: 'fixture' });+forcePrivilegeVerdict({ ok: true, dropped: false, why: 'pinned by the test suite' });++const today = new Date().toISOString().slice(0, 10);+const userFile = uid => `${DIR}/coach/${uid}.json`;++async function settle(uid, ms = 15000) {+ const until = Date.now() + ms;+ while (Date.now() < until) {+ const s = jobs.status(uid);+ if (!s.job) return s;+ await new Promise(r => setTimeout(r, 25));+ }+ throw new Error('job never finished');+}+const lastOutcome = uid => jobs.readUser(uid).history.at(-1);++/* ---------- the per-profile cap survives forget ---------- */++test('forgetting a profile does not hand it a fresh daily cap', async () => {+ const uid = 'u-forget-cap';+ writeState(DIR, uid, sampleState());+ cfg.save({ caps: { perProfileDaily: 1, instanceDaily: 0 } });+ try {+ jobs.enqueue(uid, { kind: 'review' });+ await settle(uid);+ assert.equal(jobs.capState(uid).used, 1);++ jobs.clearUser(uid);+ const s = jobs.status(uid);+ assert.equal(s.pending, null, 'the proposal is gone');+ assert.deepEqual(jobs.readUser(uid).history, [], 'the history is gone');+ assert.equal(s.cap.used, 1, 'the day\'s count is a spending record, not the profile\'s data');+ assert.throws(() => jobs.enqueue(uid, { kind: 'review' }), e => e.code === 'cap');+ } finally {+ cfg.save({ caps: { perProfileDaily: 10, instanceDaily: 0 } });+ }+});++test('with nothing spent today, forget leaves no file at all', () => {+ const uid = 'u-forget-empty';+ jobs.setShare(uid, true);+ assert.ok(fs.existsSync(userFile(uid)));+ jobs.clearUser(uid);+ assert.equal(fs.existsSync(userFile(uid)), false);++ // Yesterday's count is already worth nothing to the cap, so it does not keep the file either.+ fs.writeFileSync(userFile(uid), JSON.stringify({ daily: { date: '2000-01-01', count: 5 }, history: [] }));+ jobs.clearUser(uid);+ assert.equal(fs.existsSync(userFile(uid)), false);+});++/* ---------- the instance cap ---------- */++test('the instance cap is reserved at enqueue, so a job still running already counts', async () => {+ cfg.save({ caps: { perProfileDaily: 10, instanceDaily: 1 }, daily: null, log: [] });+ try {+ writeState(DIR, 'u-inst-1', sampleState());+ writeState(DIR, 'u-inst-2', sampleState());+ jobs.enqueue('u-inst-1', { kind: 'review' });+ assert.ok(jobs.status('u-inst-1').job, 'the first job is on its way');+ assert.throws(() => jobs.enqueue('u-inst-2', { kind: 'review' }), e => e.code === 'cap',+ 'the second profile is refused before the first job has finished');+ await settle('u-inst-1');+ assert.equal(lastOutcome('u-inst-1').outcome, 'ready');+ assert.deepEqual(cfg.load().daily, { date: today, count: 1 });+ } finally {+ cfg.save({ caps: { perProfileDaily: 10, instanceDaily: 0 } });+ }+});++test('the instance count is not bounded by the length of the job log', () => {+ const uid = 'u-inst-150';+ writeState(DIR, uid, sampleState());+ cfg.save({ caps: { perProfileDaily: 10, instanceDaily: 150 }, daily: { date: today, count: 150 }, log: [] });+ try {+ assert.throws(() => jobs.enqueue(uid, { kind: 'review' }), e => e.code === 'cap',+ 'a hundred and fifty jobs today trip a cap of a hundred and fifty, empty log or not');+ // Yesterday's count is nobody's business today.+ cfg.save({ daily: { date: '2000-01-01', count: 150 } });+ assert.doesNotThrow(() => jobs.enqueue(uid, { kind: 'review' }));+ assert.deepEqual(cfg.load().daily, { date: today, count: 1 });+ } finally {+ cfg.save({ caps: { perProfileDaily: 10, instanceDaily: 0 } });+ }+ return settle(uid);+});++/* ---------- scheduled reviews ---------- */++/** startCadence arms a setInterval; take the callback so the tests can tick it by hand. */+function captureTick(deps) {+ const real = globalThis.setInterval;+ let fn = null;+ globalThis.setInterval = f => { fn = f; return { unref() {} }; };+ try { cadence.startCadence(deps); } finally { globalThis.setInterval = real; }+ return fn;+}+// `end` lands a second past now, so the workout is after any review that has just finished.+const newWorkout = id => ({ ...sampleState().workouts[0], id, d: today, start: Date.now() - 60000, end: Date.now() + 1000 });++test('a scheduled review reads a batch of workouts once, not once per tick', async () => {+ const uid = 'u-cadence';+ const S = sampleState({ coach: { ...sampleState().coach, cadence: { everyWorkouts: 1 } } });+ writeState(DIR, uid, S);+ const tick = captureTick({ users: () => [{ id: uid }], userNow: () => ({ date: today, hhmm: '18:00', weekday: 4 }) });+ process.env.FIXTURE_MODE = 'nochange';+ try {+ tick();+ assert.ok(jobs.status(uid).job, 'the first tick queues a review');+ tick();+ await settle(uid);+ assert.equal(lastOutcome(uid).outcome, 'nochange');+ assert.equal(lastOutcome(uid).trigger, 'scheduled');++ // The phone never opened, so lastReview in the synced state is still unset — and the same+ // workout must not be reviewed again on every tick until the daily cap is gone.+ tick(); tick(); tick();+ assert.equal(jobs.status(uid).job, null);+ assert.equal(jobs.readUser(uid).history.length, 1);+ assert.equal(jobs.capState(uid).used, 1);++ // A new workout is new news.+ S.workouts.push(newWorkout('w2'));+ writeState(DIR, uid, S);+ tick();+ assert.ok(jobs.status(uid).job, 'a fresh workout is due');+ await settle(uid);+ assert.equal(jobs.readUser(uid).history.length, 2);+ } finally {+ delete process.env.FIXTURE_MODE;+ }+});++test('a workout the phone dated tomorrow is not re-read once the review has covered it', async () => {+ const uid = 'u-cadence-tz';+ // The phone stamps `d` in its own timezone: a morning session in Tokyo already carries+ // tomorrow's date by the server's UTC clock. Its `end` is on the clock the review is timed on.+ const tomorrow = new Date(Date.now() + 86400000).toISOString().slice(0, 10);+ const S = sampleState({ coach: { ...sampleState().coach, cadence: { everyWorkouts: 1 } } });+ S.workouts.push({ ...newWorkout('w-ahead'), d: tomorrow, start: Date.now() - 45 * 60000, end: Date.now() - 60000 });+ writeState(DIR, uid, S);+ const tick = captureTick({ users: () => [{ id: uid }], userNow: () => ({ date: today, hhmm: '18:00', weekday: 4 }) });+ process.env.FIXTURE_MODE = 'nochange';+ try {+ tick();+ await settle(uid);+ assert.equal(lastOutcome(uid).outcome, 'nochange');+ tick();+ assert.equal(jobs.status(uid).job, null, 'the review already read that workout, whatever date the phone gave it');+ assert.equal(jobs.readUser(uid).history.length, 1);+ } finally {+ delete process.env.FIXTURE_MODE;+ }+});++test('an answer the model was paid for counts as the review, even when it was unusable', async () => {+ const uid = 'u-cadence-unusable';+ const S = sampleState({ coach: { ...sampleState().coach, cadence: { everyWorkouts: 1 } } });+ writeState(DIR, uid, S);+ const tick = captureTick({ users: () => [{ id: uid }], userNow: () => ({ date: today, hhmm: '18:00', weekday: 4 }) });+ process.env.FIXTURE_MODE = 'invalid';+ try {+ tick();+ await settle(uid);+ assert.equal(lastOutcome(uid).outcome, 'failed');+ assert.equal(lastOutcome(uid).errorClass, 'unusable');+ tick();+ assert.equal(jobs.status(uid).job, null, 'the model read those workouts; sending them again pays twice for the same data');+ assert.equal(jobs.capState(uid).used, 1);++ // A call that never reached the model read nothing, so the same workouts are asked about again.+ process.env.FIXTURE_MODE = 'crash';+ S.workouts.push(newWorkout('w2'));+ writeState(DIR, uid, S);+ tick();+ await settle(uid);+ assert.equal(lastOutcome(uid).errorClass, 'provider');+ tick();+ assert.ok(jobs.status(uid).job, 'a provider that fell over is retried on the next tick');+ await settle(uid);+ } finally {+ delete process.env.FIXTURE_MODE;+ }+});++test('a proposal nobody has answered is not replaced by the next scheduled review', async () => {+ const uid = 'u-cadence-pending';+ const S = sampleState({ coach: { ...sampleState().coach, cadence: { everyWorkouts: 1 } } });+ writeState(DIR, uid, S);+ const tick = captureTick({ users: () => [{ id: uid }], userNow: () => ({ date: today, hhmm: '18:00', weekday: 4 }) });++ tick();+ const first = await settle(uid);+ assert.equal(lastOutcome(uid).outcome, 'ready');+ assert.ok(first.pending, 'a proposal is waiting');++ S.workouts.push(newWorkout('w2'));+ writeState(DIR, uid, S);+ tick();+ assert.equal(jobs.status(uid).job, null, 'not while the proposal is unread');+ assert.equal(jobs.status(uid).pending.id, first.pending.id, 'the unread proposal is still the same one');++ // Once it is answered, the workout logged since is due.+ jobs.resolvePending(uid, { dismissed: true });+ tick();+ assert.ok(jobs.status(uid).job, 'the workout since the last review is due');+ await settle(uid);+ assert.equal(jobs.readUser(uid).history.filter(h => h.outcome === 'ready').length, 2);+});diff --git a/api/test/cohort.test.js b/api/test/cohort.test.jsindex d09fa467a..bddaf8cd8 100644--- a/api/test/cohort.test.js+++ b/api/test/cohort.test.js@@ -101,3 +101,10 @@ test('the admin switch decides whether the prompt ever sees a cohort', () => {assert.equal(cohort.cohortForPayload('a'), null);cfg.save({ community: true });});++test('forgetting a profile takes it out of the room at once, cache or no cache', () => {+ assert.equal(cohort.computeCohort('a').people, 4);+ jobs.clearUser('b');+ assert.equal(jobs.isSharing('b'), false);+ assert.equal(cohort.computeCohort('a').people, 3);+});diff --git a/api/test/jobs.test.js b/api/test/jobs.test.jsindex fd4633acd..540c15456 100644--- a/api/test/jobs.test.js+++ b/api/test/jobs.test.js@@ -115,6 +115,165 @@ test('forgetting a profile leaves no server-side residue', async () => {assert.deepEqual(jobs.readUser(uid).history, []);});+/* ---------- forget while a job is live ----------+ A provider on localhost that parks every request until the test lets it answer, so a job+ can be caught mid-call or still waiting for a slot. */+async function holdingProvider() {+ const http = await import('node:http');+ const held = [], seen = [];+ const server = http.createServer((req, res) => {+ let body = '';+ req.on('data', c => { body += c; });+ req.on('end', () => { seen.push(JSON.parse(body || '{}')); held.push(res); });+ // A caller that hangs up mid-call takes its parked response with it.+ res.on('close', () => { const i = held.indexOf(res); if (i >= 0) held.splice(i, 1); });+ });+ await new Promise(r => server.listen(0, '127.0.0.1', r));+ /** Exactly n requests parked with the provider — 0 means every caller has gone. */+ const until = async n => {+ const t = Date.now() + 15000;+ while (held.length !== n && Date.now() < t) await new Promise(r => setTimeout(r, 25));+ assert.equal(held.length, n, `${n} request(s) with the provider`);+ };+ const answer = content => {+ for (const res of held.splice(0)) {+ res.setHeader('content-type', 'application/json');+ res.end(JSON.stringify({ choices: [{ finish_reason: 'stop', message: { content } }] }));+ }+ };+ const use = () => cfg.save({ enabled: true, provider: 'compatible', providerOptions: { compatible: { baseUrl: `http://127.0.0.1:${server.address().port}` } }, models: { compatible: 'local-model' } });+ // Parked responses hold their sockets open; a failing test must not hold node --test with them.+ const close = () => { cfg.save({ provider: 'fixture' }); server.close(); server.closeAllConnections(); };+ return { seen, held, until, answer, use, close };+}+const NOCHANGE = '{"coach_contract":1,"nochange":true,"reading":"Steady."}';+/** The job's own end, as opposed to status() going quiet: the instance log gains its line. */+async function logged(n) {+ const t = Date.now() + 15000;+ while (cfg.load().log.length < n && Date.now() < t) await new Promise(r => setTimeout(r, 25));+ assert.equal(cfg.load().log.length, n);+}++test('forgetting a profile mid-job cancels the call and frees its slot at once', async () => {+ const p = await holdingProvider();+ const notified = [];+ jobs.setProposalHook(uid => notified.push(uid));+ try {+ p.use();+ const uid = 'u-forget-live';+ writeState(DIR, uid, sampleState());+ jobs.enqueue(uid, { kind: 'review' });+ await p.until(1);+ assert.equal(jobs.status(uid).job.state, 'running');++ const before = cfg.load().log.length;+ const t0 = Date.now();+ jobs.clearUser(uid);+ assert.equal(jobs.status(uid).job, null);+ // The provider is never answered: the call goes with the record, so the job drains now+ // rather than when the provider gets round to it or the five-minute timeout does.+ await logged(before + 1);+ assert.ok(Date.now() - t0 < 5000, `drained in ${Date.now() - t0} ms`);+ await p.until(0);+ assert.equal(cfg.load().log.at(-1).outcome, 'failed', 'the job ran and is counted');+ assert.equal(cfg.load().log.at(-1).errorClass, 'forgotten', 'the log names the cancellation, not a provider timeout');+ assert.deepEqual(jobs.readUser(uid).pending, null, 'nothing is held for someone who asked to be forgotten');+ assert.deepEqual(jobs.readUser(uid).history, [], 'the record is not recreated');+ assert.deepEqual(notified, [], 'nobody is told about it');+ assert.equal(jobs.capState(uid).used, 1);++ // Single-flight went with the job: the profile can ask again straight away, not once the+ // provider hold is over.+ assert.doesNotThrow(() => jobs.enqueue(uid, { kind: 'review' }), 'the slot is free again');+ await p.until(1);+ p.answer(NOCHANGE);+ await settle(uid);+ assert.equal(lastOutcome(uid).outcome, 'nochange');+ } finally {+ jobs.setProposalHook(null);+ p.close();+ }+});++test('a runtime that cannot be cancelled still has its late answer discarded after a forget', async () => {+ // The fixture CLI is a child process, and the abort signal means nothing to one: it runs to+ // its answer, which then has nobody to belong to.+ const uid = 'u-forget-spawned';+ writeState(DIR, uid, sampleState());+ const notified = [];+ jobs.setProposalHook(u => notified.push(u));+ try {+ jobs.enqueue(uid, { kind: 'review' });+ assert.equal(jobs.status(uid).job.state, 'running');+ jobs.clearUser(uid);+ // The line this job writes to the instance log, not the next line anyone writes there.+ const mine = () => cfg.load().log.find(e => e.uid === uid);+ for (const t = Date.now() + 15000; !mine() && Date.now() < t;) await new Promise(r => setTimeout(r, 25));+ assert.equal(mine()?.outcome, 'ready', 'the job ran to its answer and is counted');+ assert.deepEqual(jobs.readUser(uid).pending, null, 'the proposal is not held for someone who asked to be forgotten');+ assert.deepEqual(jobs.readUser(uid).history, []);+ assert.deepEqual(notified, [], 'nobody is told about it');+ } finally {+ jobs.setProposalHook(null);+ }+});++test('forgetting a profile whose job is still queued drops it before anything leaves', async () => {+ const p = await holdingProvider();+ try {+ p.use();+ // Two other profiles hold both execution slots, so the third waits.+ for (const u of ['u-slot-1', 'u-slot-2']) { writeState(DIR, u, sampleState()); jobs.enqueue(u, { kind: 'review' }); }+ await p.until(2);+ const uid = 'u-forget-queued';+ writeState(DIR, uid, sampleState());+ jobs.enqueue(uid, { kind: 'review' });+ assert.equal(jobs.status(uid).job.state, 'queued');++ jobs.clearUser(uid);+ assert.equal(jobs.status(uid).job, null);+ p.answer(NOCHANGE);+ await settle('u-slot-1'); await settle('u-slot-2');+ await new Promise(r => setTimeout(r, 200)); // a job still queued would have started by now+ assert.equal(p.seen.length, 2, 'the forgotten profile\'s payload never reached the provider');+ assert.equal(jobs.status(uid).job, null);+ assert.deepEqual(jobs.readUser(uid).history, []);++ // Single-flight was released with the job, so the profile can ask again.+ jobs.enqueue(uid, { kind: 'review' });+ await p.until(1);+ p.answer(NOCHANGE);+ await settle(uid);+ assert.equal(lastOutcome(uid).outcome, 'nochange');+ } finally { p.close(); }+});++test('consent withdrawn, or the Coach switched off, while a job waits: no payload leaves', async () => {+ const p = await holdingProvider();+ try {+ p.use();+ for (const u of ['u-slot-3', 'u-slot-4']) { writeState(DIR, u, sampleState()); jobs.enqueue(u, { kind: 'review' }); }+ await p.until(2);+ writeState(DIR, 'u-revoked', sampleState());+ writeState(DIR, 'u-switched-off', sampleState());+ jobs.enqueue('u-revoked', { kind: 'review' });+ jobs.enqueue('u-switched-off', { kind: 'review' });+ assert.equal(jobs.status('u-switched-off').job.state, 'queued');++ // Consent gone from the synced state — no forget call, so the record itself stays and says+ // what happened. Then the admin switches the Coach off before a slot frees.+ writeState(DIR, 'u-revoked', sampleState({ coach: {} }));+ cfg.save({ enabled: false });+ p.answer(NOCHANGE);+ await settle('u-revoked'); await settle('u-switched-off');+ assert.equal(p.seen.length, 2, 'neither queued job reached the provider');+ assert.equal(lastOutcome('u-revoked').outcome, 'failed');+ assert.equal(lastOutcome('u-revoked').errorClass, 'consent');+ assert.equal(lastOutcome('u-switched-off').outcome, 'failed');+ assert.equal(lastOutcome('u-switched-off').errorClass, 'off');+ } finally { cfg.save({ enabled: true }); p.close(); }+});+test('a job interrupted by a restart is reported as failed, not left spinning', () => {const uid = 'u-restart';fs.mkdirSync(`${DIR}/coach`, { recursive: true });