sync-outcome.ts

6.4 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  | "peer_protocol_outdated"21  | "sync_timeout"22  | "connection_lost"23  | "run_failed";2425/**26 * Outcomes where sync did not do what the user asked, so the UI shows red.27 *28 * Network-class failures (relay/handshake/timeout) are NOT in this set —29 * with a 10-minute background alarm the normal state for most minutes is30 * "the relay didn't answer this time". That is the network, not the app,31 * and the next alarm tick will retry. They live in `WARNINGS` so the32 * indicator goes yellow instead of red.33 */34const FAILURES: ReadonlySet<SyncOutcome> = new Set<SyncOutcome>([35  "no_eligible_host",36  "runner_unavailable",37  "private_relay_unset",38  "vault_id_mismatch",39  "peer_protocol_outdated",40  "run_failed",41]);4243/**44 * Network-class outcomes — the dial did not reach the peer this attempt.45 * The alarm keeps trying, so this is warn (yellow), not error (red).46 */47const WARNINGS: ReadonlySet<SyncOutcome> = new Set<SyncOutcome>([48  "relay_unreachable",49  "handshake_failed",50  "sync_timeout",51  "connection_lost",52  // vault_locked is the reader's vault being closed — not a misconfiguration,53  // not a broken sync. The user is in another app or hasn't unlocked yet; the54  // next unlock + retry will succeed. Same alarm-keeps-trying semantics as a55  // missed dial, so it lives here rather than in FAILURES.56  "vault_locked",57]);5859/**60 * A transport that hung up, as opposed to a protocol or vault problem.61 *62 * Lives here because two callers need the same judgement and must not drift:63 * the coordinator (a close while waiting for the peer's final SYNC_DONE echo64 * is a completed sync) and the trigger's error classifier (a close anywhere65 * else is network-class, so yellow rather than red).66 *67 * Deliberately does not match SyncFrameTooLargeError's "WebSocket close 1009"68 * — an oversized frame is a misbehaving peer and must keep failing.69 */70export function isConnectionClosedError(err: unknown): boolean {71  const message = err instanceof Error ? err.message : String(err);72  return /websocket closed|connection closed/i.test(message);73}7475export function isSyncFailure(outcome: SyncOutcome): boolean {76  return FAILURES.has(outcome);77}7879export function isSyncWarning(outcome: SyncOutcome): boolean {80  return WARNINGS.has(outcome);81}8283export interface SyncOutcomeSummary {84  status?: "idle" | "syncing" | "error";85  outcome?: SyncOutcome;86  entriesSent?: number;87  entriesReceived?: number;88  detail?: string;89  /** When the last attempt ended, success or not. */90  finishedAt?: number;91}9293/**94 * The one indicator light. `busy` pulses green, `ok` is solid green, `warn`95 * is yellow (a transient network miss — the next alarm tick retries),96 * `error` is red (the app is actually broken), `idle` is unlit. Nothing97 * that is actually broken may resolve to `ok` — a paired-but-unsyncable98 * device is red, not green. A dial that didn't reach the peer is yellow,99 * because the alarm will try again.100 */101export type SyncIndicator = "busy" | "ok" | "warn" | "error" | "idle";102103export function syncIndicator(s: SyncOutcomeSummary, pairedCount: number): SyncIndicator {104  if (s.status === "syncing") return "busy";105  if (s.outcome && isSyncFailure(s.outcome)) return "error";106  if (s.outcome && isSyncWarning(s.outcome)) return "warn";107  if (s.outcome === "completed_changes" || s.outcome === "completed_no_changes") {108    return "ok";109  }110  if (s.outcome === "waiting_for_peer") return "ok";111  // Paired with a healthy history but no attempt since this SW woke: still a112  // successful pair, which is what the light is claiming.113  if (pairedCount > 0 && s.outcome === undefined) return "ok";114  return "idle";115}116117const INDICATOR_LABEL: Record<SyncIndicator, string> = {118  busy: "Syncing",119  ok: "Sync healthy",120  warn: "Last sync attempt missed — will retry",121  error: "Sync problem",122  idle: "Not syncing",123};124125/** Colour alone is never the signal — this is the same claim in words. */126export function syncIndicatorLabel(127  indicator: SyncIndicator,128  s: SyncOutcomeSummary,129): string {130  return `${INDICATOR_LABEL[indicator]} — ${describeSyncOutcome(s)}`;131}132133const COPY: Record<SyncOutcome, string> = {134  completed_changes: "Synced",135  completed_no_changes: "Up to date — nothing to send or receive",136  no_paired_devices: "No devices paired yet",137  no_eligible_host: "Paired, but no device here can accept a sync",138  waiting_for_peer: "Waiting for the paired device to connect",139  runner_unavailable: "Sync isn't running in the background — reload Peach",140  sync_disabled: "Sync is switched off",141  private_relay_unset: "Private relay chosen but no address set",142  vault_locked: "Vault was locked — unlock and sync again",143  relay_unreachable: "Couldn't reach the relay",144  handshake_failed: "Reached the relay, but the device didn't answer",145  vault_id_mismatch: "That device holds a different vault",146  peer_protocol_outdated: "Your other device needs to update before it can sync",147  sync_timeout: "The device stopped responding mid-sync",148  connection_lost: "The connection dropped mid-sync — will retry",149  run_failed: "Sync failed",150};151152/**153 * One plain-English line for a sync outcome. `detail` — the raw internal code154 * or the device inventory behind `no_eligible_host` — is appended rather than155 * hidden: it is the whole diagnostic on a real device, where devtools is not156 * an option.157 */158export function describeSyncOutcome(s: SyncOutcomeSummary): string {159  if (!s.outcome) return "Not synced yet";160  const base = COPY[s.outcome] ?? "Sync failed";161  if (s.outcome === "completed_changes") {162    const moved = [163      (s.entriesSent ?? 0) > 0 ? `${s.entriesSent} sent` : null,164      (s.entriesReceived ?? 0) > 0 ? `${s.entriesReceived} received` : null,165    ].filter(Boolean);166    return moved.length > 0 ? `${base} — ${moved.join(", ")}` : base;167  }168  return s.detail ? `${base} (${s.detail})` : base;169}