sync-outcome.ts

6.1 KB · raw

1// Why a sync run ended, in a form both the service worker and the popup can2// name. Before this existed, "no eligible host", "runner not wired" and3// "synced fine, nothing to do" were all a bare `return` — indistinguishable4// to the user and to us. A failed sync and a successful no-op must never5// look the same again.67export type SyncOutcome =8  | "completed_changes"9  | "completed_no_changes"10  | "no_paired_devices"11  | "no_eligible_host"12  | "runner_unavailable"13  | "sync_disabled"14  | "private_relay_unset"15  | "vault_locked"16  | "relay_unreachable"17  | "handshake_failed"18  | "vault_id_mismatch"19  | "sync_timeout"20  | "connection_lost"21  | "run_failed";2223/**24 * Outcomes where sync did not do what the user asked, so the UI shows red.25 *26 * Network-class failures (relay/handshake/timeout) are NOT in this set —27 * with a 10-minute background alarm the normal state for most minutes is28 * "the relay didn't answer this time". That is the network, not the app,29 * and the next alarm tick will retry. They live in `WARNINGS` so the30 * indicator goes yellow instead of red.31 */32const FAILURES: ReadonlySet<SyncOutcome> = new Set<SyncOutcome>([33  "no_eligible_host",34  "runner_unavailable",35  "private_relay_unset",36  "vault_id_mismatch",37  "run_failed",38]);3940/**41 * Network-class outcomes — the dial did not reach the peer this attempt.42 * The alarm keeps trying, so this is warn (yellow), not error (red).43 */44const WARNINGS: ReadonlySet<SyncOutcome> = new Set<SyncOutcome>([45  "relay_unreachable",46  "handshake_failed",47  "sync_timeout",48  "connection_lost",49  // vault_locked is the reader's vault being closed — not a misconfiguration,50  // not a broken sync. The user is in another app or hasn't unlocked yet; the51  // next unlock + retry will succeed. Same alarm-keeps-trying semantics as a52  // missed dial, so it lives here rather than in FAILURES.53  "vault_locked",54]);5556/**57 * A transport that hung up, as opposed to a protocol or vault problem.58 *59 * Lives here because two callers need the same judgement and must not drift:60 * the coordinator (a close while waiting for the peer's final SYNC_DONE echo61 * is a completed sync) and the trigger's error classifier (a close anywhere62 * else is network-class, so yellow rather than red).63 *64 * Deliberately does not match SyncFrameTooLargeError's "WebSocket close 1009"65 * — an oversized frame is a misbehaving peer and must keep failing.66 */67export function isConnectionClosedError(err: unknown): boolean {68  const message = err instanceof Error ? err.message : String(err);69  return /websocket closed|connection closed/i.test(message);70}7172export function isSyncFailure(outcome: SyncOutcome): boolean {73  return FAILURES.has(outcome);74}7576export function isSyncWarning(outcome: SyncOutcome): boolean {77  return WARNINGS.has(outcome);78}7980export interface SyncOutcomeSummary {81  status?: "idle" | "syncing" | "error";82  outcome?: SyncOutcome;83  entriesSent?: number;84  entriesReceived?: number;85  detail?: string;86  /** When the last attempt ended, success or not. */87  finishedAt?: number;88}8990/**91 * The one indicator light. `busy` pulses green, `ok` is solid green, `warn`92 * is yellow (a transient network miss — the next alarm tick retries),93 * `error` is red (the app is actually broken), `idle` is unlit. Nothing94 * that is actually broken may resolve to `ok` — a paired-but-unsyncable95 * device is red, not green. A dial that didn't reach the peer is yellow,96 * because the alarm will try again.97 */98export type SyncIndicator = "busy" | "ok" | "warn" | "error" | "idle";99100export function syncIndicator(s: SyncOutcomeSummary, pairedCount: number): SyncIndicator {101  if (s.status === "syncing") return "busy";102  if (s.outcome && isSyncFailure(s.outcome)) return "error";103  if (s.outcome && isSyncWarning(s.outcome)) return "warn";104  if (s.outcome === "completed_changes" || s.outcome === "completed_no_changes") {105    return "ok";106  }107  // Paired with a healthy history but no attempt since this SW woke: still a108  // successful pair, which is what the light is claiming.109  if (pairedCount > 0 && s.outcome === undefined) return "ok";110  return "idle";111}112113const INDICATOR_LABEL: Record<SyncIndicator, string> = {114  busy: "Syncing",115  ok: "Sync healthy",116  warn: "Last sync attempt missed — will retry",117  error: "Sync problem",118  idle: "Not syncing",119};120121/** Colour alone is never the signal — this is the same claim in words. */122export function syncIndicatorLabel(123  indicator: SyncIndicator,124  s: SyncOutcomeSummary,125): string {126  return `${INDICATOR_LABEL[indicator]} — ${describeSyncOutcome(s)}`;127}128129const COPY: Record<SyncOutcome, string> = {130  completed_changes: "Synced",131  completed_no_changes: "Up to date — nothing to send or receive",132  no_paired_devices: "No devices paired yet",133  no_eligible_host: "Paired, but no device here can accept a sync",134  runner_unavailable: "Sync isn't running in the background — reload Peach",135  sync_disabled: "Sync is switched off",136  private_relay_unset: "Private relay chosen but no address set",137  vault_locked: "Vault was locked — unlock and sync again",138  relay_unreachable: "Couldn't reach the relay",139  handshake_failed: "Reached the relay, but the device didn't answer",140  vault_id_mismatch: "That device holds a different vault",141  sync_timeout: "The device stopped responding mid-sync",142  connection_lost: "The connection dropped mid-sync — will retry",143  run_failed: "Sync failed",144};145146/**147 * One plain-English line for a sync outcome. `detail` — the raw internal code148 * or the device inventory behind `no_eligible_host` — is appended rather than149 * hidden: it is the whole diagnostic on a real device, where devtools is not150 * an option.151 */152export function describeSyncOutcome(s: SyncOutcomeSummary): string {153  if (!s.outcome) return "Not synced yet";154  const base = COPY[s.outcome] ?? "Sync failed";155  if (s.outcome === "completed_changes") {156    const moved = [157      (s.entriesSent ?? 0) > 0 ? `${s.entriesSent} sent` : null,158      (s.entriesReceived ?? 0) > 0 ? `${s.entriesReceived} received` : null,159    ].filter(Boolean);160    return moved.length > 0 ? `${base} — ${moved.join(", ")}` : base;161  }162  return s.detail ? `${base} (${s.detail})` : base;163}