/** * EACH APP'S OWN REPORT ON A SHARED DEVICE ROW (coordinator, 25 Nov 2026: DEVICE ROWS). The iPhone apps share one * keychain group, so Words, Comms, Cinemas, Books… on one phone sign in with ONE credential and are filed under ONE * `device` row (src/sync_status.ts `ownDevice`). Each writes its whole `reported_state` on that row after a pass * (cotton-client transport/object.rs), so the row said only whichever app synced last, and an older report could * land over a newer one. * * Additive, on the object: a report that names its `bundleId` is also kept under `reported_state.apps[bundleId]` * (build, sha, schema, last_exchange_at, last_answer, unsent, held, and when the object took it; since UNSENT SEEN, 26 Nov * 2026, also unsent_ops, waiting_by_table and waiting_by_code as names and counts only, and the oldest waits). An app's entry is * never replaced by a report older than it (by `last_exchange_at`), and the top level stays the newest report any app * gave. A report without a `bundleId` (the Mac, an older core) is written as it always was. The apps map is the * object's: whatever a write says of `apps` is ignored. */ import { DEVICE_TABLE } from "./sync_status.ts"; type Data = Record; /** At most this many apps are kept on one row: the newest by when they reported. */ export const MAX_APPS = 40; /** The fields an app's entry keeps. */ const KEPT = ["build", "sha", "schema", "last_exchange_at", "last_answer", "unsent", "held", "unsent_ops", "oldest_waiting_at", "oldest_seal_waiting_at"] as const; /** The first pull under way (FIRST SYNC FAST, 26 Nov 2026): whole counts only, said every few pages. */ const PASS_COUNTS = ["pass_done", "pass_total", "parked"] as const; /** The count maps an app's entry keeps (UNSENT SEEN, 26 Nov 2026): table names and refusal codes to counts, never a value. */ const COUNTED = ["waiting_by_table", "waiting_by_code"] as const; /** At most this many names in one count map. */ export const MAX_NAMES = 40; /** A map of names a table or a code can be to whole counts; anything else in it is dropped. */ export function counts(v: unknown): Record | undefined { const map = objectOf(v); if (!map) return undefined; const kept = Object.entries(map) .filter(([name, n]) => /^[a-z0-9_]{1,64}$/.test(name) && typeof n === "number" && Number.isInteger(n) && n >= 0) .slice(0, MAX_NAMES); return kept.length ? (Object.fromEntries(kept) as Record) : undefined; } function objectOf(v: unknown): Data | null { if (typeof v === "string") { try { return objectOf(JSON.parse(v)); } catch { return null; } } return v && typeof v === "object" && !Array.isArray(v) ? (v as Data) : null; } /** An ISO instant's milliseconds, or null. */ function when(v: unknown): number | null { if (typeof v !== "string") return null; const ms = Date.parse(v); return Number.isFinite(ms) ? ms : null; } /** Whether `incoming` is older than `held`: both name a time and the incoming one is before it. */ function older(incoming: Data, held: Data | null): boolean { const a = when(incoming.last_exchange_at); const b = held ? when(held.last_exchange_at) : null; return a !== null && b !== null && a < b; } /** * The patch a write to a `device` row becomes: its `reported_state` merged with what the row holds, as above. * Any other table, or a write without `reported_state`, is untouched. */ export function withAppReports(table: string, patch: Data, held: Data, now: Date): Data { if (table !== DEVICE_TABLE || !("reported_state" in patch)) return patch; const incoming = objectOf(patch.reported_state); const before = objectOf(held.reported_state); const apps: Data = { ...(objectOf(before?.apps) ?? {}) }; if (!incoming) { // Cleared: the apps the object kept stay. return Object.keys(apps).length ? { ...patch, reported_state: { apps } } : patch; } const { apps: _ignored, ...report } = incoming; const bundle = typeof report.bundleId === "string" && /^[A-Za-z0-9.\-_]{1,200}$/.test(report.bundleId) ? report.bundleId : null; if (bundle === null && !Object.keys(apps).length) return { ...patch, reported_state: report }; if (bundle !== null) { const was = objectOf(apps[bundle]); if (!older(report, was)) { const entry: Data = { reported_at: now.toISOString() }; for (const k of KEPT) if (report[k] !== undefined) entry[k] = report[k]; for (const k of PASS_COUNTS) if (Number.isSafeInteger(report[k]) && (report[k] as number) >= 0) entry[k] = report[k]; for (const k of COUNTED) { const kept = counts(report[k]); if (kept) entry[k] = kept; } apps[bundle] = entry; } } const kept = Object.fromEntries( Object.entries(apps) .sort(([, a], [, b]) => String(objectOf(b)?.reported_at ?? "").localeCompare(String(objectOf(a)?.reported_at ?? ""))) .slice(0, MAX_APPS), ); // The top level is the newest report: an older one keeps what the row said there. const { apps: _heldApps, ...heldTop } = before ?? {}; const top = before && older(report, heldTop) ? heldTop : report; return { ...patch, reported_state: { ...top, apps: kept } }; } /** Minutes since an ISO instant, or null. */ function minutesSince(v: unknown, now: number): number | null { const ms = when(v); return ms === null ? null : Math.max(0, Math.floor((now - ms) / 60_000)); } /** Each app's report on a device row, newest first, as list_devices answers it. */ export function appReports(reported: Data | null, now: number = Date.now()): Data[] { const apps = objectOf(reported?.apps); if (!apps) return []; return Object.entries(apps) .map(([bundleId, v]) => { const e = objectOf(v) ?? {}; return { bundleId, build: e.build ?? null, sha: e.sha ?? null, schema: e.schema ?? null, lastExchangeAt: e.last_exchange_at ?? null, lastAnswer: e.last_answer ?? null, unsent: e.unsent ?? null, unsentOps: e.unsent_ops ?? null, held: e.held ?? null, waitingByTable: counts(e.waiting_by_table) ?? null, waitingByCode: counts(e.waiting_by_code) ?? null, oldestWaitingAt: e.oldest_waiting_at ?? null, oldestWaitingMinutes: minutesSince(e.oldest_waiting_at, now), oldestSealWaitingMinutes: minutesSince(e.oldest_seal_waiting_at, now), // FIRST SYNC FAST: the pass under way, said every few pages, so slow and stuck differ (counts only). passDone: e.pass_done ?? null, passTotal: e.pass_total ?? null, parked: e.parked ?? null, reportedAt: e.reported_at ?? null, }; }) .sort((a, b) => String(b.reportedAt ?? "").localeCompare(String(a.reportedAt ?? ""))); }