|
| 1 | +// src/utils/kai_cadence.ts |
| 2 | +// Kai-native cadence scheduler: beat/pulse intervals with Fibonacci backoff. |
| 3 | +// - NO Date.now |
| 4 | +// - NO setInterval backlog (uses recursive setTimeout) |
| 5 | +// - Mobile reality: resync on foreground, optional pause when hidden |
| 6 | +// - Deterministic cadence in Kai units (as constants), not hours |
| 7 | + |
| 8 | +import { PULSE_MS, PULSES_BEAT } from "./kai_pulse"; |
| 9 | + |
| 10 | +export type KaiCadenceUnit = "pulse" | "beat"; |
| 11 | + |
| 12 | +export type KaiCadenceOptions = { |
| 13 | + unit: KaiCadenceUnit; |
| 14 | + // Every N units. For SW updates you’ll likely use unit="beat", every=1. |
| 15 | + every: number; |
| 16 | + |
| 17 | + // If true, no timers run while hidden; resumes cleanly on visible. |
| 18 | + pauseWhenHidden?: boolean; |
| 19 | + |
| 20 | + // Called each tick. Throwing/rejecting can be used by wrappers to backoff. |
| 21 | + onTick: () => void | Promise<void>; |
| 22 | +}; |
| 23 | + |
| 24 | +export type KaiCadenceHandle = { |
| 25 | + stop: () => void; |
| 26 | +}; |
| 27 | + |
| 28 | +const clampInt = (n: number, min: number, max: number): number => { |
| 29 | + const x = Math.floor(n); |
| 30 | + if (x < min) return min; |
| 31 | + if (x > max) return max; |
| 32 | + return x; |
| 33 | +}; |
| 34 | + |
| 35 | +const MIN_DELAY_MS = 250; |
| 36 | +const MAX_DELAY_MS = 2 ** 31 - 1; // browser clamp for setTimeout |
| 37 | + |
| 38 | +function unitMs(unit: KaiCadenceUnit): number { |
| 39 | + if (unit === "pulse") return PULSE_MS; |
| 40 | + // beat = pulses/beat * pulse_ms |
| 41 | + return PULSE_MS * PULSES_BEAT; |
| 42 | +} |
| 43 | + |
| 44 | +export function startKaiCadence(opts: KaiCadenceOptions): KaiCadenceHandle { |
| 45 | + const pauseWhenHidden = opts.pauseWhenHidden !== false; // default true |
| 46 | + const every = clampInt(opts.every, 1, 1_000_000); |
| 47 | + |
| 48 | + const baseMs = unitMs(opts.unit); |
| 49 | + const steadyDelay = clampInt(every * baseMs, MIN_DELAY_MS, MAX_DELAY_MS); |
| 50 | + |
| 51 | + let disposed = false; |
| 52 | + let timer: number | null = null; |
| 53 | + |
| 54 | + const clear = (): void => { |
| 55 | + if (timer !== null) window.clearTimeout(timer); |
| 56 | + timer = null; |
| 57 | + }; |
| 58 | + |
| 59 | + const schedule = (delayMs: number): void => { |
| 60 | + if (disposed) return; |
| 61 | + const d = clampInt(delayMs, MIN_DELAY_MS, MAX_DELAY_MS); |
| 62 | + timer = window.setTimeout(() => void tick(), d); |
| 63 | + }; |
| 64 | + |
| 65 | + const tick = async (): Promise<void> => { |
| 66 | + if (disposed) return; |
| 67 | + |
| 68 | + if (pauseWhenHidden && document.visibilityState !== "visible") { |
| 69 | + // Don’t spin in background; re-armed on visibilitychange. |
| 70 | + schedule(steadyDelay); |
| 71 | + return; |
| 72 | + } |
| 73 | + |
| 74 | + try { |
| 75 | + await opts.onTick(); |
| 76 | + } finally { |
| 77 | + // Always continue cadence; caller can implement backoff externally. |
| 78 | + schedule(steadyDelay); |
| 79 | + } |
| 80 | + }; |
| 81 | + |
| 82 | + // Start cadence immediately (first tick after steadyDelay) |
| 83 | + schedule(steadyDelay); |
| 84 | + |
| 85 | + const onVis = (): void => { |
| 86 | + if (document.visibilityState !== "visible") return; |
| 87 | + clear(); |
| 88 | + // Foreground: tick soon (but not immediately) then resume steady cadence |
| 89 | + schedule(Math.min(steadyDelay, 1000)); |
| 90 | + }; |
| 91 | + |
| 92 | + document.addEventListener("visibilitychange", onVis, { passive: true }); |
| 93 | + |
| 94 | + return { |
| 95 | + stop: () => { |
| 96 | + disposed = true; |
| 97 | + clear(); |
| 98 | + document.removeEventListener("visibilitychange", onVis); |
| 99 | + }, |
| 100 | + }; |
| 101 | +} |
| 102 | + |
| 103 | +// Fibonacci helper for backoff schedules (1,2,3,5,8,13,...) |
| 104 | +export const KAI_FIB: readonly number[] = [ |
| 105 | + 1, 2, 3, 5, 8, 13, 21, 34, |
| 106 | +] as const; |
| 107 | + |
| 108 | +export type KaiFibBackoffOptions = { |
| 109 | + unit: KaiCadenceUnit; |
| 110 | + // Fibonacci list index cap (default last index) |
| 111 | + maxIndex?: number; |
| 112 | + pauseWhenHidden?: boolean; |
| 113 | + |
| 114 | + // On success: reset to fib[0] |
| 115 | + onSuccess?: () => void; |
| 116 | + // On failure: step to next fib index |
| 117 | + onFailure?: () => void; |
| 118 | + |
| 119 | + // Actual work (e.g., reg.update) |
| 120 | + work: () => Promise<void>; |
| 121 | +}; |
| 122 | + |
| 123 | +export function startKaiFibBackoff(opts: KaiFibBackoffOptions): KaiCadenceHandle { |
| 124 | + const pauseWhenHidden = opts.pauseWhenHidden !== false; // default true |
| 125 | + const maxIdx = clampInt( |
| 126 | + typeof opts.maxIndex === "number" ? opts.maxIndex : KAI_FIB.length - 1, |
| 127 | + 0, |
| 128 | + KAI_FIB.length - 1 |
| 129 | + ); |
| 130 | + |
| 131 | + const baseMs = unitMs(opts.unit); |
| 132 | + |
| 133 | + let disposed = false; |
| 134 | + let timer: number | null = null; |
| 135 | + let idx = 0; |
| 136 | + |
| 137 | + const clear = (): void => { |
| 138 | + if (timer !== null) window.clearTimeout(timer); |
| 139 | + timer = null; |
| 140 | + }; |
| 141 | + |
| 142 | + const scheduleNext = (): void => { |
| 143 | + if (disposed) return; |
| 144 | + |
| 145 | + const beats = KAI_FIB[idx] ?? 1; |
| 146 | + const delay = clampInt(beats * baseMs, MIN_DELAY_MS, MAX_DELAY_MS); |
| 147 | + |
| 148 | + timer = window.setTimeout(() => { |
| 149 | + void tick(); |
| 150 | + }, delay); |
| 151 | + }; |
| 152 | + |
| 153 | + const tick = async (): Promise<void> => { |
| 154 | + if (disposed) return; |
| 155 | + |
| 156 | + if (pauseWhenHidden && document.visibilityState !== "visible") { |
| 157 | + scheduleNext(); |
| 158 | + return; |
| 159 | + } |
| 160 | + |
| 161 | + try { |
| 162 | + await opts.work(); |
| 163 | + idx = 0; |
| 164 | + opts.onSuccess?.(); |
| 165 | + } catch { |
| 166 | + idx = Math.min(idx + 1, maxIdx); |
| 167 | + opts.onFailure?.(); |
| 168 | + } |
| 169 | + |
| 170 | + scheduleNext(); |
| 171 | + }; |
| 172 | + |
| 173 | + scheduleNext(); |
| 174 | + |
| 175 | + const onVis = (): void => { |
| 176 | + if (document.visibilityState !== "visible") return; |
| 177 | + clear(); |
| 178 | + // Foreground: poke once, then resume schedule |
| 179 | + void opts.work().catch(() => {}); |
| 180 | + scheduleNext(); |
| 181 | + }; |
| 182 | + |
| 183 | + document.addEventListener("visibilitychange", onVis, { passive: true }); |
| 184 | + |
| 185 | + return { |
| 186 | + stop: () => { |
| 187 | + disposed = true; |
| 188 | + clear(); |
| 189 | + document.removeEventListener("visibilitychange", onVis); |
| 190 | + }, |
| 191 | + }; |
| 192 | +} |
0 commit comments