sync-outcome.ts

6.2 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  | "waiting_for_peer"13  | "runner_unavailable"14  | "sync_disabled"15  | "private_relay_unset"16  | "vault_locked"17  | "relay_unreachable"18  | "handshake_failed"19  | "vault_id_mismatch"20  | "sync_timeout"21  | "connection_lost"22  | "run_failed";2324/**25 * Outcomes where sync did not do what the user asked, so the UI shows red.26 *27 * Network-class failures (relay/handshake/timeout) are NOT in this set —28 * with a 10-minute background alarm the normal state for most minutes is29 * "the relay didn't answer this time". That is the network, not the app,30 * and the next alarm tick will retry. They live in `WARNINGS` so the31 * indicator goes yellow instead of red.32 */33const FAILURES: ReadonlySet<SyncOutcome> = new Set<SyncOutcome>([34  "no_eligible_host",35  "runner_unavailable",36  "private_relay_unset",37  "vault_id_mismatch",38  "run_failed",39]);4041/**42 * Network-class outcomes — the dial did not reach the peer this attempt.43 * The alarm keeps trying, so this is warn (yellow), not error (red).44 */45const WARNINGS: ReadonlySet<SyncOutcome> = new Set<SyncOutcome>([46  "relay_unreachable",47  "handshake_failed",48  "sync_timeout",49  "connection_lost",50  // vault_locked is the reader's vault being closed — not a misconfiguration,51  // not a broken sync. The user is in another app or hasn't unlocked yet; the52  // next unlock + retry will succeed. Same alarm-keeps-trying semantics as a53  // missed dial, so it lives here rather than in FAILURES.54  "vault_locked",55]);5657/**58 * A transport that hung up, as opposed to a protocol or vault problem.59 *60 * Lives here because two callers need the same judgement and must not drift:61 * the coordinator (a close while waiting for the peer's final SYNC_DONE echo62 * is a completed sync) and the trigger's error classifier (a close anywhere63 * else is network-class, so yellow rather than red).64 *65 * Deliberately does not match SyncFrameTooLargeError's "WebSocket close 1009"66 * — an oversized frame is a misbehaving peer and must keep failing.67 */68export function isConnectionClosedError(err: unknown): boolean {69  const message = err instanceof Error ? err.message : String(err);70  return /websocket closed|connection closed/i.test(message);71}7273export function isSyncFailure(outcome: SyncOutcome): boolean {74  return FAILURES.has(outcome);75}7677export function isSyncWarning(outcome: SyncOutcome): boolean {78  return WARNINGS.has(outcome);79}8081export interface SyncOutcomeSummary {82  status?: "idle" | "syncing" | "error";83  outcome?: SyncOutcome;84  entriesSent?: number;85  entriesReceived?: number;86  detail?: string;87  /** When the last attempt ended, success or not. */88  finishedAt?: number;89}9091/**92 * The one indicator light. `busy` pulses green, `ok` is solid green, `warn`93 * is yellow (a transient network miss — the next alarm tick retries),94 * `error` is red (the app is actually broken), `idle` is unlit. Nothing95 * that is actually broken may resolve to `ok` — a paired-but-unsyncable96 * device is red, not green. A dial that didn't reach the peer is yellow,97 * because the alarm will try again.98 */99export type SyncIndicator = "busy" | "ok" | "warn" | "error" | "idle";100101export function syncIndicator(s: SyncOutcomeSummary, pairedCount: number): SyncIndicator {102  if (s.status === "syncing") return "busy";103  if (s.outcome && isSyncFailure(s.outcome)) return "error";104  if (s.outcome && isSyncWarning(s.outcome)) return "warn";105  if (s.outcome === "completed_changes" || s.outcome === "completed_no_changes") {106    return "ok";107  }108  if (s.outcome === "waiting_for_peer") return "ok";109  // Paired with a healthy history but no attempt since this SW woke: still a110  // successful pair, which is what the light is claiming.111  if (pairedCount > 0 && s.outcome === undefined) return "ok";112  return "idle";113}114115const INDICATOR_LABEL: Record<SyncIndicator, string> = {116  busy: "Syncing",117  ok: "Sync healthy",118  warn: "Last sync attempt missed — will retry",119  error: "Sync problem",120  idle: "Not syncing",121};122123/** Colour alone is never the signal — this is the same claim in words. */124export function syncIndicatorLabel(125  indicator: SyncIndicator,126  s: SyncOutcomeSummary,127): string {128  return `${INDICATOR_LABEL[indicator]} — ${describeSyncOutcome(s)}`;129}130131const COPY: Record<SyncOutcome, string> = {132  completed_changes: "Synced",133  completed_no_changes: "Up to date — nothing to send or receive",134  no_paired_devices: "No devices paired yet",135  no_eligible_host: "Paired, but no device here can accept a sync",136  waiting_for_peer: "Waiting for the paired device to connect",137  runner_unavailable: "Sync isn't running in the background — reload Peach",138  sync_disabled: "Sync is switched off",139  private_relay_unset: "Private relay chosen but no address set",140  vault_locked: "Vault was locked — unlock and sync again",141  relay_unreachable: "Couldn't reach the relay",142  handshake_failed: "Reached the relay, but the device didn't answer",143  vault_id_mismatch: "That device holds a different vault",144  sync_timeout: "The device stopped responding mid-sync",145  connection_lost: "The connection dropped mid-sync — will retry",146  run_failed: "Sync failed",147};148149/**150 * One plain-English line for a sync outcome. `detail` — the raw internal code151 * or the device inventory behind `no_eligible_host` — is appended rather than152 * hidden: it is the whole diagnostic on a real device, where devtools is not153 * an option.154 */155export function describeSyncOutcome(s: SyncOutcomeSummary): string {156  if (!s.outcome) return "Not synced yet";157  const base = COPY[s.outcome] ?? "Sync failed";158  if (s.outcome === "completed_changes") {159    const moved = [160      (s.entriesSent ?? 0) > 0 ? `${s.entriesSent} sent` : null,161      (s.entriesReceived ?? 0) > 0 ? `${s.entriesReceived} received` : null,162    ].filter(Boolean);163    return moved.length > 0 ? `${base} — ${moved.join(", ")}` : base;164  }165  return s.detail ? `${base} (${s.detail})` : base;166}