[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6HY8YBXKT2G799BAGWFERXQ":3,"skill-same:01M6HY8YBXKT2G799BAGWFERXQ":59},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":26,"linkOnly":27,"markdownContent":28,"markdownBody":29,"frontMatter":30,"refName":31,"commitSha":32,"skillDirectory":33,"forksCount":34,"repositoryHtmlUrl":35,"repositoryHomepageUrl":6,"ownerHtmlUrl":36,"ownerBlogUrl":37,"ownerDescription":6,"updatedAt":38,"install":39,"resources":52},"01M6HY8YBXKT2G799BAGWFERXQ","smart-poll-loop",null,"Adaptive polling pattern with exponential backoff on failure, automatic recovery on success, and visibility-aware scheduling","HKUDS\u002FAgentPilot","HKUDS","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F118165258?v=4","01M6HW8VRNZP64G0P4MVJW2KKQ","✨Data Intelligence Lab@HKU✨","01M6HW8VWZVHBRHYH3T330PFWV",8029,"MIT","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Flegacy\u002Fv1\u002Fshowcase\u002Fskills\u002Fsmart-poll-loop\u002FSKILL.md",[],[19,20,21,22,23,24,25],"loop","smart poll loop","recovery","scheduling","pattern","with","backoff","2026-11-10 10:12:30",false,"---\nname: smart-poll-loop\ndescription: Adaptive polling pattern with exponential backoff on failure, automatic recovery on success, and visibility-aware scheduling\n---\n\n# Smart Poll Loop Pattern\n\n## Overview\n\nThe Smart Poll Loop pattern implements resilient, adaptive polling for periodic data refresh operations. It combines exponential backoff on consecutive failures with automatic recovery on success, ensuring system resources are protected during outages while maintaining responsiveness when services are healthy.\n\nThis pattern is essential for production applications that need to poll external services or APIs continuously but must gracefully handle intermittent failures, rate limits, or temporary service disruptions without overwhelming the system or degrading user experience.\n\n## Key Patterns Identified\n\n### Pattern 1: Exponential Backoff on Failure\n\n**Purpose**: Prevent overwhelming failing services with repeated requests while giving them time to recover.\n\n**Implementation**: Each consecutive failure doubles the polling interval up to a configurable maximum multiplier. This creates exponentially increasing delays: 1x → 2x → 4x → 8x (default max).\n\n**Key Elements**:\n- `consecutiveFailures`: Counter tracking sequential failures\n- `currentBackoffMultiplier`: Current delay multiplier (starts at 1)\n- `maxBackoffMultiplier`: Upper bound to prevent infinite delays (typically 4-8x)\n- Boolean return from callbacks (`true` = success, `false` = failure)\n\n**Code Pattern**:\n```typescript\n\u002F\u002F Track failure state per runner\ninterface RunnerEntry {\n  consecutiveFailures: number;\n  currentBackoffMultiplier: number;\n  intervalMs: number; \u002F\u002F base interval\n  \u002F\u002F ... other fields\n}\n\n\u002F\u002F On failure, increase backoff\nif (!success) {\n  entry.consecutiveFailures++;\n  const newMultiplier = Math.min(\n    Math.pow(2, entry.consecutiveFailures),\n    maxBackoffMultiplier\n  );\n  entry.currentBackoffMultiplier = newMultiplier;\n  \n  \u002F\u002F Reschedule with new interval\n  const effectiveInterval = entry.intervalMs * entry.currentBackoffMultiplier;\n  scheduleNextRun(effectiveInterval);\n}\n```\n\n### Pattern 2: Automatic Recovery on Success\n\n**Purpose**: Immediately restore normal polling frequency when a service recovers, ensuring fresh data flows without unnecessary delay.\n\n**Implementation**: On any successful callback execution, reset both the failure counter and backoff multiplier to their initial states (0 and 1), then reschedule at the base interval.\n\n**Key Elements**:\n- Reset logic triggered by `success === true` or no error thrown\n- Immediate rescheduling at base interval (no waiting for current timer)\n- Logging state transitions for observability\n\n**Code Pattern**:\n```typescript\nif (success) {\n  \u002F\u002F Auto-recovery: reset backoff and failure count\n  if (entry.consecutiveFailures > 0 || entry.currentBackoffMultiplier > 1) {\n    entry.consecutiveFailures = 0;\n    entry.currentBackoffMultiplier = 1;\n    \n    \u002F\u002F Immediately reschedule at normal interval\n    if (!paused && entry.timer) {\n      scheduleNextRun(name, entry); \u002F\u002F uses base intervalMs\n    }\n  }\n}\n```\n\n### Pattern 3: Failure Detection via Boolean Return or Exception\n\n**Purpose**: Provide flexible signaling for success\u002Ffailure states, supporting both explicit boolean returns and exception-based error handling.\n\n**Implementation**: Callbacks can return `boolean` (explicit success\u002Ffailure), `void` (success assumed), or throw exceptions (failure). All three mechanisms trigger the same backoff\u002Frecovery logic.\n\n**Key Elements**:\n- Type signature: `() => Promise\u003Cboolean | void>`\n- `true` = explicit success, triggers recovery\n- `false` = explicit failure, triggers backoff\n- `void`\u002F`undefined` = implicit success (no news is good news)\n- Exception thrown = failure, triggers backoff\n\n**Code Pattern**:\n```typescript\nlet success = true;\ntry {\n  const result = await entry.fn();\n  \n  \u002F\u002F Boolean return indicates explicit success\u002Ffailure\n  if (typeof result === 'boolean') {\n    success = result;\n  }\n  \u002F\u002F void\u002Fundefined is treated as success\n  \n  if (success) {\n    \u002F\u002F trigger recovery...\n  } else {\n    \u002F\u002F trigger backoff...\n  }\n} catch (err) {\n  \u002F\u002F Exception is also treated as failure\n  success = false;\n  \u002F\u002F trigger backoff...\n}\n```\n\n### Pattern 4: Visibility-Aware Scheduling\n\n**Purpose**: Pause or slow down polling when the page is hidden to conserve resources, then resume or refresh immediately when visible.\n\n**Implementation**: Listen to `visibilitychange` events. On hide, clear all timers. On show, either flush stale data (if enough time passed) or resume normal polling.\n\n**Key Elements**:\n- `document.hidden` state check\n- `pauseWhenHidden` flag (full stop vs slower polling)\n- `hiddenSince` timestamp for staleness detection\n- Staggered flush on resume (prevent request bursts)\n\n**Code Pattern**:\n```typescript\nprivate onVisibilityChange(): void {\n  if (document.hidden) {\n    this.hiddenSince = Date.now();\n    \u002F\u002F Pause all runners\n    for (const entry of this.runners.values()) {\n      if (entry.timer) {\n        clearInterval(entry.timer);\n        entry.timer = null;\n      }\n    }\n  } else {\n    \u002F\u002F Resume: flush stale refreshes first\n    this.flushStaleRefreshes();\n    \u002F\u002F Then restart timers\n    for (const [name, entry] of this.runners) {\n      if (!entry.timer) {\n        this.scheduleNextRun(name, entry);\n      }\n    }\n  }\n}\n\nprivate flushStaleRefreshes(): void {\n  if (!this.hiddenSince) return;\n  const hiddenMs = Date.now() - this.hiddenSince;\n  this.hiddenSince = 0;\n\n  let stagger = 0;\n  for (const [name, entry] of this.runners) {\n    const effectiveInterval = entry.intervalMs * entry.currentBackoffMultiplier;\n    if (hiddenMs \u003C effectiveInterval) continue; \u002F\u002F not stale yet\n    \n    \u002F\u002F Stagger refreshes to avoid thundering herd\n    setTimeout(() => this.runRefresh(name), stagger);\n    stagger += 150; \u002F\u002F 150ms between each\n  }\n}\n```\n\n### Pattern 5: Per-Runner State Management\n\n**Purpose**: Allow multiple independent polling loops with isolated failure tracking and backoff state.\n\n**Implementation**: Use a map keyed by runner name, storing all state (timer, interval, backoff, failures) per entry. Each runner progresses through its own backoff cycle independently.\n\n**Key Elements**:\n- `Map\u003Cstring, RunnerEntry>` for isolated state\n- Unique names prevent conflicts\n- Per-runner failure counters\n- Per-runner backoff multipliers\n- In-flight tracking prevents overlapping executions\n\n**Code Pattern**:\n```typescript\nprivate runners = new Map\u003Cstring, RunnerEntry>();\nprivate inFlight = new Set\u003Cstring>();\n\nscheduleRefresh(\n  name: string,\n  fn: () => Promise\u003Cboolean | void>,\n  intervalMs: number,\n): void {\n  \u002F\u002F Each runner gets isolated state\n  const entry: RunnerEntry = {\n    timer: null,\n    intervalMs,\n    fn,\n    lastRun: 0,\n    consecutiveFailures: 0,\n    currentBackoffMultiplier: 1,\n  };\n  \n  this.runners.set(name, entry);\n  this.scheduleNextRun(name, entry);\n}\n\nprivate async runRefresh(name: string): Promise\u003Cvoid> {\n  const entry = this.runners.get(name);\n  if (!entry) return;\n  \n  \u002F\u002F Prevent overlapping executions of the same runner\n  if (this.inFlight.has(name)) return;\n  this.inFlight.add(name);\n  \n  try {\n    \u002F\u002F ... execute and handle backoff\u002Frecovery\n  } finally {\n    this.inFlight.delete(name);\n  }\n}\n```\n\n## Complete Code Template\n\nBelow is a minimal but complete implementation of the adaptive polling pattern:\n\n```typescript\ninterface RefreshRegistration {\n  name: string;\n  fn: () => Promise\u003Cboolean | void>;\n  intervalMs: number;\n  condition?: () => boolean; \u002F\u002F optional: skip if returns false\n}\n\ninterface RunnerEntry {\n  timer: ReturnType\u003Ctypeof setInterval> | null;\n  intervalMs: number;\n  fn: () => Promise\u003Cboolean | void>;\n  condition?: () => boolean;\n  lastRun: number;\n  consecutiveFailures: number;\n  currentBackoffMultiplier: number;\n}\n\nclass AdaptiveScheduler {\n  private runners = new Map\u003Cstring, RunnerEntry>();\n  private inFlight = new Set\u003Cstring>();\n  private hiddenSince = 0;\n  private readonly maxBackoffMultiplier = 8;\n\n  constructor() {\n    document.addEventListener('visibilitychange', () => this.onVisibilityChange());\n  }\n\n  private onVisibilityChange(): void {\n    if (document.hidden) {\n      this.hiddenSince = Date.now();\n      for (const entry of this.runners.values()) {\n        if (entry.timer) {\n          clearInterval(entry.timer);\n          entry.timer = null;\n        }\n      }\n    } else {\n      this.flushStaleRefreshes();\n      for (const [name, entry] of this.runners) {\n        if (!entry.timer) {\n          this.scheduleNextRun(name, entry);\n        }\n      }\n    }\n  }\n\n  private scheduleNextRun(name: string, entry: RunnerEntry): void {\n    if (entry.timer) clearInterval(entry.timer);\n    \n    const effectiveInterval = entry.intervalMs * entry.currentBackoffMultiplier;\n    entry.timer = setInterval(() => this.runRefresh(name), effectiveInterval);\n  }\n\n  private async runRefresh(name: string): Promise\u003Cvoid> {\n    const entry = this.runners.get(name);\n    if (!entry) return;\n    if (this.inFlight.has(name)) return;\n    if (entry.condition && !entry.condition()) return;\n\n    this.inFlight.add(name);\n    let success = true;\n\n    try {\n      const result = await entry.fn();\n      \n      if (typeof result === 'boolean') {\n        success = result;\n      }\n      \n      entry.lastRun = Date.now();\n\n      if (success) {\n        \u002F\u002F Auto-recovery\n        if (entry.consecutiveFailures > 0 || entry.currentBackoffMultiplier > 1) {\n          entry.consecutiveFailures = 0;\n          entry.currentBackoffMultiplier = 1;\n          if (!document.hidden && entry.timer) {\n            this.scheduleNextRun(name, entry);\n          }\n        }\n      } else {\n        \u002F\u002F Exponential backoff\n        entry.consecutiveFailures++;\n        const newMultiplier = Math.min(\n          Math.pow(2, entry.consecutiveFailures),\n          this.maxBackoffMultiplier\n        );\n        \n        if (newMultiplier !== entry.currentBackoffMultiplier) {\n          entry.currentBackoffMultiplier = newMultiplier;\n          if (!document.hidden && entry.timer) {\n            this.scheduleNextRun(name, entry);\n          }\n        }\n      }\n    } catch (err) {\n      success = false;\n      entry.consecutiveFailures++;\n      const newMultiplier = Math.min(\n        Math.pow(2, entry.consecutiveFailures),\n        this.maxBackoffMultiplier\n      );\n      \n      if (newMultiplier !== entry.currentBackoffMultiplier) {\n        entry.currentBackoffMultiplier = newMultiplier;\n        if (!document.hidden && entry.timer) {\n          this.scheduleNextRun(name, entry);\n        }\n      }\n      console.error(`Refresh ${name} failed:`, err);\n    } finally {\n      this.inFlight.delete(name);\n    }\n  }\n\n  private flushStaleRefreshes(): void {\n    if (!this.hiddenSince) return;\n    const hiddenMs = Date.now() - this.hiddenSince;\n    this.hiddenSince = 0;\n\n    let stagger = 0;\n    for (const [name, entry] of this.runners) {\n      const effectiveInterval = entry.intervalMs * entry.currentBackoffMultiplier;\n      if (hiddenMs \u003C effectiveInterval) continue;\n      \n      setTimeout(() => this.runRefresh(name), stagger);\n      stagger += 150;\n    }\n  }\n\n  scheduleRefresh(\n    name: string,\n    fn: () => Promise\u003Cboolean | void>,\n    intervalMs: number,\n    condition?: () => boolean,\n  ): void {\n    const existing = this.runners.get(name);\n    if (existing?.timer) clearInterval(existing.timer);\n\n    const entry: RunnerEntry = {\n      timer: null,\n      intervalMs,\n      fn,\n      condition,\n      lastRun: 0,\n      consecutiveFailures: 0,\n      currentBackoffMultiplier: 1,\n    };\n\n    if (!document.hidden) {\n      this.scheduleNextRun(name, entry);\n    }\n\n    this.runners.set(name, entry);\n  }\n\n  trigger(name: string): void {\n    this.runRefresh(name);\n  }\n\n  destroy(): void {\n    for (const entry of this.runners.values()) {\n      if (entry.timer) clearInterval(entry.timer);\n    }\n    this.runners.clear();\n    this.inFlight.clear();\n  }\n}\n```\n\n## Usage Examples\n\n### Example 1: Basic Polling with Explicit Success\u002FFailure\n\n```typescript\nconst scheduler = new AdaptiveScheduler();\n\n\u002F\u002F API endpoint that may fail intermittently\nscheduler.scheduleRefresh(\n  'fetch-stock-prices',\n  async () => {\n    try {\n      const response = await fetch('\u002Fapi\u002Fstocks');\n      if (!response.ok) return false; \u002F\u002F explicit failure\n      \n      const data = await response.json();\n      updateStockPrices(data);\n      return true; \u002F\u002F explicit success\n    } catch (err) {\n      console.error('Stock fetch failed:', err);\n      return false; \u002F\u002F explicit failure\n    }\n  },\n  30_000 \u002F\u002F 30 seconds base interval\n);\n```\n\n**Behavior**:\n- On success: polls every 30s\n- After 1 failure: polls every 60s (2x)\n- After 2 failures: polls every 120s (4x)\n- After 3+ failures: polls every 240s (8x, max)\n- On any success: immediately returns to 30s interval\n\n### Example 2: Multiple Independent Runners\n\n```typescript\nconst scheduler = new AdaptiveScheduler();\n\n\u002F\u002F Weather updates - critical, frequent\nscheduler.scheduleRefresh(\n  'weather',\n  async () => {\n    const res = await fetch('\u002Fapi\u002Fweather');\n    return res.ok; \u002F\u002F boolean indicates success\u002Ffailure\n  },\n  60_000 \u002F\u002F 1 minute\n);\n\n\u002F\u002F News feed - less critical, slower\nscheduler.scheduleRefresh(\n  'news',\n  async () => {\n    const res = await fetch('\u002Fapi\u002Fnews');\n    if (!res.ok) return false;\n    const articles = await res.json();\n    updateNewsFeed(articles);\n    return true;\n  },\n  300_000 \u002F\u002F 5 minutes\n);\n\n\u002F\u002F Each runner has independent backoff state\n\u002F\u002F Weather failures don't affect news polling, and vice versa\n```\n\n### Example 3: Conditional Execution\n\n```typescript\nscheduler.scheduleRefresh(\n  'user-notifications',\n  async () => {\n    const res = await fetch('\u002Fapi\u002Fnotifications');\n    if (!res.ok) return false;\n    \n    const notifications = await res.json();\n    displayNotifications(notifications);\n    return true;\n  },\n  60_000,\n  \u002F\u002F Only poll if user is logged in\n  () => isUserLoggedIn()\n);\n```\n\n### Example 4: Void Return (Implicit Success)\n\n```typescript\nscheduler.scheduleRefresh(\n  'analytics-heartbeat',\n  async () => {\n    \u002F\u002F No explicit return = void = success assumed\n    await fetch('\u002Fapi\u002Fanalytics\u002Fheartbeat', { method: 'POST' });\n    \u002F\u002F If this throws, it's treated as failure\n    \u002F\u002F If it completes, it's success\n  },\n  120_000 \u002F\u002F 2 minutes\n);\n```\n\n### Example 5: Manual Trigger\n\n```typescript\n\u002F\u002F Schedule background refresh\nscheduler.scheduleRefresh('dashboard-data', fetchDashboard, 60_000);\n\n\u002F\u002F User clicks refresh button - trigger immediate run\ndocument.getElementById('refresh-btn')?.addEventListener('click', () => {\n  scheduler.trigger('dashboard-data');\n});\n```\n\n## Best Practices\n\n### Choose Appropriate Base Intervals\n\n- **High-frequency data** (stock prices, live scores): 10-30 seconds\n- **Medium-frequency data** (weather, news): 1-5 minutes\n- **Low-frequency data** (configuration, settings): 10-30 minutes\n\n### Set Reasonable Backoff Limits\n\n- **Max multiplier 4-8x**: Prevents indefinite delays while allowing sufficient recovery time\n- **Too low** (2x): May overwhelm failing services\n- **Too high** (16x+): Data may become too stale during recovery\n\n### Use Explicit Boolean Returns When Possible\n\n```typescript\n\u002F\u002F Good: Explicit failure signaling\nasync () => {\n  const res = await fetch('\u002Fapi\u002Fdata');\n  if (res.status === 429) return false; \u002F\u002F rate limited - back off\n  if (res.status === 503) return false; \u002F\u002F service unavailable - back off\n  if (res.status === 404) return true;  \u002F\u002F not found - but don't back off\n  return res.ok;\n}\n\n\u002F\u002F Less ideal: Relying on exceptions\nasync () => {\n  const res = await fetch('\u002Fapi\u002Fdata');\n  res.json(); \u002F\u002F throws on error, but less explicit\n}\n```\n\n### Handle Stale Data on Resume\n\nWhen the page becomes visible after being hidden, stale refreshes are flushed with staggering. Ensure your data handlers can cope with rapid updates:\n\n```typescript\n\u002F\u002F Debounce or batch UI updates\nlet updateTimer: number | null = null;\nfunction updateUI(data: any) {\n  if (updateTimer) clearTimeout(updateTimer);\n  updateTimer = setTimeout(() => {\n    renderData(data); \u002F\u002F actual DOM update\n  }, 100);\n}\n```\n\n### Monitor Backoff State\n\nExpose backoff state for debugging and monitoring:\n\n```typescript\n\u002F\u002F Check current backoff status\nconst state = scheduler.getBackoffState('api-poller');\nconsole.log(`Failures: ${state.failures}, Multiplier: ${state.multiplier}x`);\n\n\u002F\u002F Manual reset if needed (e.g., after user fixes credentials)\nscheduler.resetBackoff('api-poller');\n```\n\n### Clean Up on Component Unmount\n\n```typescript\n\u002F\u002F React example\nuseEffect(() => {\n  const scheduler = new AdaptiveScheduler();\n  scheduler.scheduleRefresh('data', fetchData, 30_000);\n  \n  return () => scheduler.destroy(); \u002F\u002F clear all timers\n}, []);\n```\n\n## When to Use This Pattern\n\n### Ideal For:\n\n- **Polling external APIs** that may experience intermittent failures or rate limits\n- **Dashboard\u002Fmonitoring UIs** that need to stay fresh but must handle service outages gracefully\n- **Real-time-ish data** where strict real-time isn't required (use WebSockets for true real-time)\n- **Multiple data sources** with different refresh rates and reliability profiles\n\n### Not Ideal For:\n\n- **True real-time requirements**: Use WebSockets, Server-Sent Events, or long polling instead\n- **One-time operations**: Use direct async calls, not scheduled polling\n- **Critical, must-not-miss updates**: Add push notifications or webhooks as a complement\n- **High-frequency sub-second polling**: Consider WebSocket or EventSource\n\n## Common Pitfalls to Avoid\n\n### Thundering Herd on Resume\n\n**Problem**: All runners trigger simultaneously when page becomes visible.\n\n**Solution**: Use staggered flush (already implemented in the pattern):\n```typescript\nlet stagger = 0;\nfor (const [name, entry] of this.runners) {\n  setTimeout(() => this.runRefresh(name), stagger);\n  stagger += 150; \u002F\u002F stagger by 150ms\n}\n```\n\n### Backoff Not Resetting\n\n**Problem**: Forgetting to reset backoff on success keeps the service in slow-poll mode forever.\n\n**Solution**: Always check and reset state on success:\n```typescript\nif (success && entry.currentBackoffMultiplier > 1) {\n  entry.currentBackoffMultiplier = 1;\n  entry.consecutiveFailures = 0;\n  reschedule(); \u002F\u002F immediate effect\n}\n```\n\n### Overlapping Executions\n\n**Problem**: Long-running callbacks overlap with the next scheduled run.\n\n**Solution**: Use in-flight tracking (already implemented):\n```typescript\nif (this.inFlight.has(name)) return; \u002F\u002F skip if already running\nthis.inFlight.add(name);\ntry {\n  await callback();\n} finally {\n  this.inFlight.delete(name);\n}\n```\n\n### Ignoring Visibility State\n\n**Problem**: Polling continues in hidden tabs, wasting resources and battery.\n\n**Solution**: Always implement visibility-aware pausing (already implemented):\n```typescript\nif (document.hidden) {\n  clearAllTimers();\n} else {\n  restartTimers();\n}\n```\n\n## Related Patterns\n\n- **Circuit Breaker**: After N consecutive failures, stop polling entirely until manual reset or timeout\n- **Jittered Backoff**: Add randomization to backoff delays to prevent synchronized retries across clients\n- **Adaptive Intervals**: Adjust base interval based on data change frequency (not just failures)\n- **WebSocket with Fallback**: Use WebSocket for real-time, fall back to smart polling on connection loss\n\n## Performance Considerations\n\n### Memory Usage\n\nEach runner entry stores:\n- Timer reference: ~8 bytes\n- Function reference: ~8 bytes\n- State integers: ~16 bytes\n- Total: ~32-64 bytes per runner\n\nFor 100 concurrent runners: ~6 KB overhead (negligible).\n\n### CPU Usage\n\n- **Idle state** (no failures): Minimal - just timer callbacks\n- **During backoff**: Reduced CPU usage due to longer intervals\n- **On resume**: Brief spike from staggered flush, then normal\n\n### Network Usage\n\n- **Normal operation**: Consistent request rate\n- **During failures**: Exponentially reduced request rate (desired behavior)\n- **On recovery**: Immediate return to normal rate\n\n## Testing Strategies\n\n### Unit Tests\n\n```typescript\ndescribe('AdaptiveScheduler', () => {\n  it('should double interval on consecutive failures', async () => {\n    const scheduler = new AdaptiveScheduler();\n    let callCount = 0;\n    \n    scheduler.scheduleRefresh('test', async () => {\n      callCount++;\n      return false; \u002F\u002F always fail\n    }, 1000);\n    \n    await sleep(1000);\n    expect(callCount).toBe(1);\n    \n    await sleep(2000); \u002F\u002F doubled interval\n    expect(callCount).toBe(2);\n    \n    await sleep(4000); \u002F\u002F doubled again\n    expect(callCount).toBe(3);\n  });\n  \n  it('should reset backoff on success', async () => {\n    const scheduler = new AdaptiveScheduler();\n    let shouldFail = true;\n    \n    scheduler.scheduleRefresh('test', async () => {\n      return !shouldFail;\n    }, 1000);\n    \n    \u002F\u002F ... cause failures ...\n    shouldFail = false;\n    scheduler.trigger('test'); \u002F\u002F manual trigger\n    \n    const state = scheduler.getBackoffState('test');\n    expect(state.multiplier).toBe(1);\n    expect(state.failures).toBe(0);\n  });\n});\n```\n\n### Integration Tests\n\nMock `fetch` to simulate service failures and recoveries, verify backoff timing and state transitions.\n\n### Manual Testing\n\nUse browser DevTools to throttle network, simulate hidden\u002Fvisible transitions, and observe polling behavior in the Network tab.\n\n## References\n\n- **Source**: worldmonitor\u002Fsrc\u002Fservices\u002Fruntime.ts - `startSmartPollLoop` function\n- **Implementation**: my-daily-monitor\u002Fsrc\u002Fservices\u002Frefresh-scheduler.ts\n- **AWS Architecture Blog**: [Exponential Backoff and Jitter](https:\u002F\u002Faws.amazon.com\u002Fblogs\u002Farchitecture\u002Fexponential-backoff-and-jitter\u002F)\n- **Google SRE Book**: [Handling Overload](https:\u002F\u002Fsre.google\u002Fsre-book\u002Fhandling-overload\u002F)\n","# Smart Poll Loop Pattern\n\n## Overview\n\nThe Smart Poll Loop pattern implements resilient, adaptive polling for periodic data refresh operations. It combines exponential backoff on consecutive failures with automatic recovery on success, ensuring system resources are protected during outages while maintaining responsiveness when services are healthy.\n\nThis pattern is essential for production applications that need to poll external services or APIs continuously but must gracefully handle intermittent failures, rate limits, or temporary service disruptions without overwhelming the system or degrading user experience.\n\n## Key Patterns Identified\n\n### Pattern 1: Exponential Backoff on Failure\n\n**Purpose**: Prevent overwhelming failing services with repeated requests while giving them time to recover.\n\n**Implementation**: Each consecutive failure doubles the polling interval up to a configurable maximum multiplier. This creates exponentially increasing delays: 1x → 2x → 4x → 8x (default max).\n\n**Key Elements**:\n- `consecutiveFailures`: Counter tracking sequential failures\n- `currentBackoffMultiplier`: Current delay multiplier (starts at 1)\n- `maxBackoffMultiplier`: Upper bound to prevent infinite delays (typically 4-8x)\n- Boolean return from callbacks (`true` = success, `false` = failure)\n\n**Code Pattern**:\n```typescript\n\u002F\u002F Track failure state per runner\ninterface RunnerEntry {\n  consecutiveFailures: number;\n  currentBackoffMultiplier: number;\n  intervalMs: number; \u002F\u002F base interval\n  \u002F\u002F ... other fields\n}\n\n\u002F\u002F On failure, increase backoff\nif (!success) {\n  entry.consecutiveFailures++;\n  const newMultiplier = Math.min(\n    Math.pow(2, entry.consecutiveFailures),\n    maxBackoffMultiplier\n  );\n  entry.currentBackoffMultiplier = newMultiplier;\n  \n  \u002F\u002F Reschedule with new interval\n  const effectiveInterval = entry.intervalMs * entry.currentBackoffMultiplier;\n  scheduleNextRun(effectiveInterval);\n}\n```\n\n### Pattern 2: Automatic Recovery on Success\n\n**Purpose**: Immediately restore normal polling frequency when a service recovers, ensuring fresh data flows without unnecessary delay.\n\n**Implementation**: On any successful callback execution, reset both the failure counter and backoff multiplier to their initial states (0 and 1), then reschedule at the base interval.\n\n**Key Elements**:\n- Reset logic triggered by `success === true` or no error thrown\n- Immediate rescheduling at base interval (no waiting for current timer)\n- Logging state transitions for observability\n\n**Code Pattern**:\n```typescript\nif (success) {\n  \u002F\u002F Auto-recovery: reset backoff and failure count\n  if (entry.consecutiveFailures > 0 || entry.currentBackoffMultiplier > 1) {\n    entry.consecutiveFailures = 0;\n    entry.currentBackoffMultiplier = 1;\n    \n    \u002F\u002F Immediately reschedule at normal interval\n    if (!paused && entry.timer) {\n      scheduleNextRun(name, entry); \u002F\u002F uses base intervalMs\n    }\n  }\n}\n```\n\n### Pattern 3: Failure Detection via Boolean Return or Exception\n\n**Purpose**: Provide flexible signaling for success\u002Ffailure states, supporting both explicit boolean returns and exception-based error handling.\n\n**Implementation**: Callbacks can return `boolean` (explicit success\u002Ffailure), `void` (success assumed), or throw exceptions (failure). All three mechanisms trigger the same backoff\u002Frecovery logic.\n\n**Key Elements**:\n- Type signature: `() => Promise\u003Cboolean | void>`\n- `true` = explicit success, triggers recovery\n- `false` = explicit failure, triggers backoff\n- `void`\u002F`undefined` = implicit success (no news is good news)\n- Exception thrown = failure, triggers backoff\n\n**Code Pattern**:\n```typescript\nlet success = true;\ntry {\n  const result = await entry.fn();\n  \n  \u002F\u002F Boolean return indicates explicit success\u002Ffailure\n  if (typeof result === 'boolean') {\n    success = result;\n  }\n  \u002F\u002F void\u002Fundefined is treated as success\n  \n  if (success) {\n    \u002F\u002F trigger recovery...\n  } else {\n    \u002F\u002F trigger backoff...\n  }\n} catch (err) {\n  \u002F\u002F Exception is also treated as failure\n  success = false;\n  \u002F\u002F trigger backoff...\n}\n```\n\n### Pattern 4: Visibility-Aware Scheduling\n\n**Purpose**: Pause or slow down polling when the page is hidden to conserve resources, then resume or refresh immediately when visible.\n\n**Implementation**: Listen to `visibilitychange` events. On hide, clear all timers. On show, either flush stale data (if enough time passed) or resume normal polling.\n\n**Key Elements**:\n- `document.hidden` state check\n- `pauseWhenHidden` flag (full stop vs slower polling)\n- `hiddenSince` timestamp for staleness detection\n- Staggered flush on resume (prevent request bursts)\n\n**Code Pattern**:\n```typescript\nprivate onVisibilityChange(): void {\n  if (document.hidden) {\n    this.hiddenSince = Date.now();\n    \u002F\u002F Pause all runners\n    for (const entry of this.runners.values()) {\n      if (entry.timer) {\n        clearInterval(entry.timer);\n        entry.timer = null;\n      }\n    }\n  } else {\n    \u002F\u002F Resume: flush stale refreshes first\n    this.flushStaleRefreshes();\n    \u002F\u002F Then restart timers\n    for (const [name, entry] of this.runners) {\n      if (!entry.timer) {\n        this.scheduleNextRun(name, entry);\n      }\n    }\n  }\n}\n\nprivate flushStaleRefreshes(): void {\n  if (!this.hiddenSince) return;\n  const hiddenMs = Date.now() - this.hiddenSince;\n  this.hiddenSince = 0;\n\n  let stagger = 0;\n  for (const [name, entry] of this.runners) {\n    const effectiveInterval = entry.intervalMs * entry.currentBackoffMultiplier;\n    if (hiddenMs \u003C effectiveInterval) continue; \u002F\u002F not stale yet\n    \n    \u002F\u002F Stagger refreshes to avoid thundering herd\n    setTimeout(() => this.runRefresh(name), stagger);\n    stagger += 150; \u002F\u002F 150ms between each\n  }\n}\n```\n\n### Pattern 5: Per-Runner State Management\n\n**Purpose**: Allow multiple independent polling loops with isolated failure tracking and backoff state.\n\n**Implementation**: Use a map keyed by runner name, storing all state (timer, interval, backoff, failures) per entry. Each runner progresses through its own backoff cycle independently.\n\n**Key Elements**:\n- `Map\u003Cstring, RunnerEntry>` for isolated state\n- Unique names prevent conflicts\n- Per-runner failure counters\n- Per-runner backoff multipliers\n- In-flight tracking prevents overlapping executions\n\n**Code Pattern**:\n```typescript\nprivate runners = new Map\u003Cstring, RunnerEntry>();\nprivate inFlight = new Set\u003Cstring>();\n\nscheduleRefresh(\n  name: string,\n  fn: () => Promise\u003Cboolean | void>,\n  intervalMs: number,\n): void {\n  \u002F\u002F Each runner gets isolated state\n  const entry: RunnerEntry = {\n    timer: null,\n    intervalMs,\n    fn,\n    lastRun: 0,\n    consecutiveFailures: 0,\n    currentBackoffMultiplier: 1,\n  };\n  \n  this.runners.set(name, entry);\n  this.scheduleNextRun(name, entry);\n}\n\nprivate async runRefresh(name: string): Promise\u003Cvoid> {\n  const entry = this.runners.get(name);\n  if (!entry) return;\n  \n  \u002F\u002F Prevent overlapping executions of the same runner\n  if (this.inFlight.has(name)) return;\n  this.inFlight.add(name);\n  \n  try {\n    \u002F\u002F ... execute and handle backoff\u002Frecovery\n  } finally {\n    this.inFlight.delete(name);\n  }\n}\n```\n\n## Complete Code Template\n\nBelow is a minimal but complete implementation of the adaptive polling pattern:\n\n```typescript\ninterface RefreshRegistration {\n  name: string;\n  fn: () => Promise\u003Cboolean | void>;\n  intervalMs: number;\n  condition?: () => boolean; \u002F\u002F optional: skip if returns false\n}\n\ninterface RunnerEntry {\n  timer: ReturnType\u003Ctypeof setInterval> | null;\n  intervalMs: number;\n  fn: () => Promise\u003Cboolean | void>;\n  condition?: () => boolean;\n  lastRun: number;\n  consecutiveFailures: number;\n  currentBackoffMultiplier: number;\n}\n\nclass AdaptiveScheduler {\n  private runners = new Map\u003Cstring, RunnerEntry>();\n  private inFlight = new Set\u003Cstring>();\n  private hiddenSince = 0;\n  private readonly maxBackoffMultiplier = 8;\n\n  constructor() {\n    document.addEventListener('visibilitychange', () => this.onVisibilityChange());\n  }\n\n  private onVisibilityChange(): void {\n    if (document.hidden) {\n      this.hiddenSince = Date.now();\n      for (const entry of this.runners.values()) {\n        if (entry.timer) {\n          clearInterval(entry.timer);\n          entry.timer = null;\n        }\n      }\n    } else {\n      this.flushStaleRefreshes();\n      for (const [name, entry] of this.runners) {\n        if (!entry.timer) {\n          this.scheduleNextRun(name, entry);\n        }\n      }\n    }\n  }\n\n  private scheduleNextRun(name: string, entry: RunnerEntry): void {\n    if (entry.timer) clearInterval(entry.timer);\n    \n    const effectiveInterval = entry.intervalMs * entry.currentBackoffMultiplier;\n    entry.timer = setInterval(() => this.runRefresh(name), effectiveInterval);\n  }\n\n  private async runRefresh(name: string): Promise\u003Cvoid> {\n    const entry = this.runners.get(name);\n    if (!entry) return;\n    if (this.inFlight.has(name)) return;\n    if (entry.condition && !entry.condition()) return;\n\n    this.inFlight.add(name);\n    let success = true;\n\n    try {\n      const result = await entry.fn();\n      \n      if (typeof result === 'boolean') {\n        success = result;\n      }\n      \n      entry.lastRun = Date.now();\n\n      if (success) {\n        \u002F\u002F Auto-recovery\n        if (entry.consecutiveFailures > 0 || entry.currentBackoffMultiplier > 1) {\n          entry.consecutiveFailures = 0;\n          entry.currentBackoffMultiplier = 1;\n          if (!document.hidden && entry.timer) {\n            this.scheduleNextRun(name, entry);\n          }\n        }\n      } else {\n        \u002F\u002F Exponential backoff\n        entry.consecutiveFailures++;\n        const newMultiplier = Math.min(\n          Math.pow(2, entry.consecutiveFailures),\n          this.maxBackoffMultiplier\n        );\n        \n        if (newMultiplier !== entry.currentBackoffMultiplier) {\n          entry.currentBackoffMultiplier = newMultiplier;\n          if (!document.hidden && entry.timer) {\n            this.scheduleNextRun(name, entry);\n          }\n        }\n      }\n    } catch (err) {\n      success = false;\n      entry.consecutiveFailures++;\n      const newMultiplier = Math.min(\n        Math.pow(2, entry.consecutiveFailures),\n        this.maxBackoffMultiplier\n      );\n      \n      if (newMultiplier !== entry.currentBackoffMultiplier) {\n        entry.currentBackoffMultiplier = newMultiplier;\n        if (!document.hidden && entry.timer) {\n          this.scheduleNextRun(name, entry);\n        }\n      }\n      console.error(`Refresh ${name} failed:`, err);\n    } finally {\n      this.inFlight.delete(name);\n    }\n  }\n\n  private flushStaleRefreshes(): void {\n    if (!this.hiddenSince) return;\n    const hiddenMs = Date.now() - this.hiddenSince;\n    this.hiddenSince = 0;\n\n    let stagger = 0;\n    for (const [name, entry] of this.runners) {\n      const effectiveInterval = entry.intervalMs * entry.currentBackoffMultiplier;\n      if (hiddenMs \u003C effectiveInterval) continue;\n      \n      setTimeout(() => this.runRefresh(name), stagger);\n      stagger += 150;\n    }\n  }\n\n  scheduleRefresh(\n    name: string,\n    fn: () => Promise\u003Cboolean | void>,\n    intervalMs: number,\n    condition?: () => boolean,\n  ): void {\n    const existing = this.runners.get(name);\n    if (existing?.timer) clearInterval(existing.timer);\n\n    const entry: RunnerEntry = {\n      timer: null,\n      intervalMs,\n      fn,\n      condition,\n      lastRun: 0,\n      consecutiveFailures: 0,\n      currentBackoffMultiplier: 1,\n    };\n\n    if (!document.hidden) {\n      this.scheduleNextRun(name, entry);\n    }\n\n    this.runners.set(name, entry);\n  }\n\n  trigger(name: string): void {\n    this.runRefresh(name);\n  }\n\n  destroy(): void {\n    for (const entry of this.runners.values()) {\n      if (entry.timer) clearInterval(entry.timer);\n    }\n    this.runners.clear();\n    this.inFlight.clear();\n  }\n}\n```\n\n## Usage Examples\n\n### Example 1: Basic Polling with Explicit Success\u002FFailure\n\n```typescript\nconst scheduler = new AdaptiveScheduler();\n\n\u002F\u002F API endpoint that may fail intermittently\nscheduler.scheduleRefresh(\n  'fetch-stock-prices',\n  async () => {\n    try {\n      const response = await fetch('\u002Fapi\u002Fstocks');\n      if (!response.ok) return false; \u002F\u002F explicit failure\n      \n      const data = await response.json();\n      updateStockPrices(data);\n      return true; \u002F\u002F explicit success\n    } catch (err) {\n      console.error('Stock fetch failed:', err);\n      return false; \u002F\u002F explicit failure\n    }\n  },\n  30_000 \u002F\u002F 30 seconds base interval\n);\n```\n\n**Behavior**:\n- On success: polls every 30s\n- After 1 failure: polls every 60s (2x)\n- After 2 failures: polls every 120s (4x)\n- After 3+ failures: polls every 240s (8x, max)\n- On any success: immediately returns to 30s interval\n\n### Example 2: Multiple Independent Runners\n\n```typescript\nconst scheduler = new AdaptiveScheduler();\n\n\u002F\u002F Weather updates - critical, frequent\nscheduler.scheduleRefresh(\n  'weather',\n  async () => {\n    const res = await fetch('\u002Fapi\u002Fweather');\n    return res.ok; \u002F\u002F boolean indicates success\u002Ffailure\n  },\n  60_000 \u002F\u002F 1 minute\n);\n\n\u002F\u002F News feed - less critical, slower\nscheduler.scheduleRefresh(\n  'news',\n  async () => {\n    const res = await fetch('\u002Fapi\u002Fnews');\n    if (!res.ok) return false;\n    const articles = await res.json();\n    updateNewsFeed(articles);\n    return true;\n  },\n  300_000 \u002F\u002F 5 minutes\n);\n\n\u002F\u002F Each runner has independent backoff state\n\u002F\u002F Weather failures don't affect news polling, and vice versa\n```\n\n### Example 3: Conditional Execution\n\n```typescript\nscheduler.scheduleRefresh(\n  'user-notifications',\n  async () => {\n    const res = await fetch('\u002Fapi\u002Fnotifications');\n    if (!res.ok) return false;\n    \n    const notifications = await res.json();\n    displayNotifications(notifications);\n    return true;\n  },\n  60_000,\n  \u002F\u002F Only poll if user is logged in\n  () => isUserLoggedIn()\n);\n```\n\n### Example 4: Void Return (Implicit Success)\n\n```typescript\nscheduler.scheduleRefresh(\n  'analytics-heartbeat',\n  async () => {\n    \u002F\u002F No explicit return = void = success assumed\n    await fetch('\u002Fapi\u002Fanalytics\u002Fheartbeat', { method: 'POST' });\n    \u002F\u002F If this throws, it's treated as failure\n    \u002F\u002F If it completes, it's success\n  },\n  120_000 \u002F\u002F 2 minutes\n);\n```\n\n### Example 5: Manual Trigger\n\n```typescript\n\u002F\u002F Schedule background refresh\nscheduler.scheduleRefresh('dashboard-data', fetchDashboard, 60_000);\n\n\u002F\u002F User clicks refresh button - trigger immediate run\ndocument.getElementById('refresh-btn')?.addEventListener('click', () => {\n  scheduler.trigger('dashboard-data');\n});\n```\n\n## Best Practices\n\n### Choose Appropriate Base Intervals\n\n- **High-frequency data** (stock prices, live scores): 10-30 seconds\n- **Medium-frequency data** (weather, news): 1-5 minutes\n- **Low-frequency data** (configuration, settings): 10-30 minutes\n\n### Set Reasonable Backoff Limits\n\n- **Max multiplier 4-8x**: Prevents indefinite delays while allowing sufficient recovery time\n- **Too low** (2x): May overwhelm failing services\n- **Too high** (16x+): Data may become too stale during recovery\n\n### Use Explicit Boolean Returns When Possible\n\n```typescript\n\u002F\u002F Good: Explicit failure signaling\nasync () => {\n  const res = await fetch('\u002Fapi\u002Fdata');\n  if (res.status === 429) return false; \u002F\u002F rate limited - back off\n  if (res.status === 503) return false; \u002F\u002F service unavailable - back off\n  if (res.status === 404) return true;  \u002F\u002F not found - but don't back off\n  return res.ok;\n}\n\n\u002F\u002F Less ideal: Relying on exceptions\nasync () => {\n  const res = await fetch('\u002Fapi\u002Fdata');\n  res.json(); \u002F\u002F throws on error, but less explicit\n}\n```\n\n### Handle Stale Data on Resume\n\nWhen the page becomes visible after being hidden, stale refreshes are flushed with staggering. Ensure your data handlers can cope with rapid updates:\n\n```typescript\n\u002F\u002F Debounce or batch UI updates\nlet updateTimer: number | null = null;\nfunction updateUI(data: any) {\n  if (updateTimer) clearTimeout(updateTimer);\n  updateTimer = setTimeout(() => {\n    renderData(data); \u002F\u002F actual DOM update\n  }, 100);\n}\n```\n\n### Monitor Backoff State\n\nExpose backoff state for debugging and monitoring:\n\n```typescript\n\u002F\u002F Check current backoff status\nconst state = scheduler.getBackoffState('api-poller');\nconsole.log(`Failures: ${state.failures}, Multiplier: ${state.multiplier}x`);\n\n\u002F\u002F Manual reset if needed (e.g., after user fixes credentials)\nscheduler.resetBackoff('api-poller');\n```\n\n### Clean Up on Component Unmount\n\n```typescript\n\u002F\u002F React example\nuseEffect(() => {\n  const scheduler = new AdaptiveScheduler();\n  scheduler.scheduleRefresh('data', fetchData, 30_000);\n  \n  return () => scheduler.destroy(); \u002F\u002F clear all timers\n}, []);\n```\n\n## When to Use This Pattern\n\n### Ideal For:\n\n- **Polling external APIs** that may experience intermittent failures or rate limits\n- **Dashboard\u002Fmonitoring UIs** that need to stay fresh but must handle service outages gracefully\n- **Real-time-ish data** where strict real-time isn't required (use WebSockets for true real-time)\n- **Multiple data sources** with different refresh rates and reliability profiles\n\n### Not Ideal For:\n\n- **True real-time requirements**: Use WebSockets, Server-Sent Events, or long polling instead\n- **One-time operations**: Use direct async calls, not scheduled polling\n- **Critical, must-not-miss updates**: Add push notifications or webhooks as a complement\n- **High-frequency sub-second polling**: Consider WebSocket or EventSource\n\n## Common Pitfalls to Avoid\n\n### Thundering Herd on Resume\n\n**Problem**: All runners trigger simultaneously when page becomes visible.\n\n**Solution**: Use staggered flush (already implemented in the pattern):\n```typescript\nlet stagger = 0;\nfor (const [name, entry] of this.runners) {\n  setTimeout(() => this.runRefresh(name), stagger);\n  stagger += 150; \u002F\u002F stagger by 150ms\n}\n```\n\n### Backoff Not Resetting\n\n**Problem**: Forgetting to reset backoff on success keeps the service in slow-poll mode forever.\n\n**Solution**: Always check and reset state on success:\n```typescript\nif (success && entry.currentBackoffMultiplier > 1) {\n  entry.currentBackoffMultiplier = 1;\n  entry.consecutiveFailures = 0;\n  reschedule(); \u002F\u002F immediate effect\n}\n```\n\n### Overlapping Executions\n\n**Problem**: Long-running callbacks overlap with the next scheduled run.\n\n**Solution**: Use in-flight tracking (already implemented):\n```typescript\nif (this.inFlight.has(name)) return; \u002F\u002F skip if already running\nthis.inFlight.add(name);\ntry {\n  await callback();\n} finally {\n  this.inFlight.delete(name);\n}\n```\n\n### Ignoring Visibility State\n\n**Problem**: Polling continues in hidden tabs, wasting resources and battery.\n\n**Solution**: Always implement visibility-aware pausing (already implemented):\n```typescript\nif (document.hidden) {\n  clearAllTimers();\n} else {\n  restartTimers();\n}\n```\n\n## Related Patterns\n\n- **Circuit Breaker**: After N consecutive failures, stop polling entirely until manual reset or timeout\n- **Jittered Backoff**: Add randomization to backoff delays to prevent synchronized retries across clients\n- **Adaptive Intervals**: Adjust base interval based on data change frequency (not just failures)\n- **WebSocket with Fallback**: Use WebSocket for real-time, fall back to smart polling on connection loss\n\n## Performance Considerations\n\n### Memory Usage\n\nEach runner entry stores:\n- Timer reference: ~8 bytes\n- Function reference: ~8 bytes\n- State integers: ~16 bytes\n- Total: ~32-64 bytes per runner\n\nFor 100 concurrent runners: ~6 KB overhead (negligible).\n\n### CPU Usage\n\n- **Idle state** (no failures): Minimal - just timer callbacks\n- **During backoff**: Reduced CPU usage due to longer intervals\n- **On resume**: Brief spike from staggered flush, then normal\n\n### Network Usage\n\n- **Normal operation**: Consistent request rate\n- **During failures**: Exponentially reduced request rate (desired behavior)\n- **On recovery**: Immediate return to normal rate\n\n## Testing Strategies\n\n### Unit Tests\n\n```typescript\ndescribe('AdaptiveScheduler', () => {\n  it('should double interval on consecutive failures', async () => {\n    const scheduler = new AdaptiveScheduler();\n    let callCount = 0;\n    \n    scheduler.scheduleRefresh('test', async () => {\n      callCount++;\n      return false; \u002F\u002F always fail\n    }, 1000);\n    \n    await sleep(1000);\n    expect(callCount).toBe(1);\n    \n    await sleep(2000); \u002F\u002F doubled interval\n    expect(callCount).toBe(2);\n    \n    await sleep(4000); \u002F\u002F doubled again\n    expect(callCount).toBe(3);\n  });\n  \n  it('should reset backoff on success', async () => {\n    const scheduler = new AdaptiveScheduler();\n    let shouldFail = true;\n    \n    scheduler.scheduleRefresh('test', async () => {\n      return !shouldFail;\n    }, 1000);\n    \n    \u002F\u002F ... cause failures ...\n    shouldFail = false;\n    scheduler.trigger('test'); \u002F\u002F manual trigger\n    \n    const state = scheduler.getBackoffState('test');\n    expect(state.multiplier).toBe(1);\n    expect(state.failures).toBe(0);\n  });\n});\n```\n\n### Integration Tests\n\nMock `fetch` to simulate service failures and recoveries, verify backoff timing and state transitions.\n\n### Manual Testing\n\nUse browser DevTools to throttle network, simulate hidden\u002Fvisible transitions, and observe polling behavior in the Network tab.\n\n## References\n\n- **Source**: worldmonitor\u002Fsrc\u002Fservices\u002Fruntime.ts - `startSmartPollLoop` function\n- **Implementation**: my-daily-monitor\u002Fsrc\u002Fservices\u002Frefresh-scheduler.ts\n- **AWS Architecture Blog**: [Exponential Backoff and Jitter](https:\u002F\u002Faws.amazon.com\u002Fblogs\u002Farchitecture\u002Fexponential-backoff-and-jitter\u002F)\n- **Google SRE Book**: [Handling Overload](https:\u002F\u002Fsre.google\u002Fsre-book\u002Fhandling-overload\u002F)\n",{"name":5,"description":7},"main","6b84b0689ca0d9e7b1e4061188ff6b60758e0f8a","openspace\u002Flegacy\u002Fv1\u002Fshowcase\u002Fskills\u002Fsmart-poll-loop",944,"https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot","https:\u002F\u002Fgithub.com\u002FHKUDS","https:\u002F\u002Fsites.google.com\u002Fview\u002Fchaoh","2026-11-12 22:26:39",{"source":8,"skillName":5,"commands":40,"prompt":50,"zipAvailable":51},[41,44,47],{"tool":42,"command":43},"npx","npx skills add HKUDS\u002FAgentPilot --skill smart-poll-loop",{"tool":45,"command":46},"bunx","bunx skills add HKUDS\u002FAgentPilot --skill smart-poll-loop",{"tool":48,"command":49},"pnpm","pnpm dlx skills add HKUDS\u002FAgentPilot --skill smart-poll-loop","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Flegacy\u002Fv1\u002Fshowcase\u002Fskills\u002Fsmart-poll-loop\u002FSKILL.md",true,[53],{"path":54,"resourceType":55,"resourceTypeDesc":56,"sizeBytes":57,"sourceHtmlUrl":58},".skill_id","OTHER","其他",30,"https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Flegacy\u002Fv1\u002Fshowcase\u002Fskills\u002Fsmart-poll-loop\u002F.skill_id",[60,79,98,123,147,170],{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":26},"01M6HYB297NDABRERJRVG0K8R0","agentpilot","Set up AgentPilot and use its single entry to prepare missing inputs and run configured RSI experiments. Use when the user requests AgentPilot installation or work with AgentPilot.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fplugins\u002Fagentpilot\u002Fskills\u002Fagentpilot\u002FSKILL.md",[],[62,67,68,24,69,70,71,72,73,74,75,76,77,78],"prepare","requests","missing","installation","rsi","up","use","user","work","SET","run","experiments",{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":26},"01M6HYAYWXTTE1J7DJM0MFNQ4H","remember","Review auto-memory entries and propose promotions to OPENSPACE.md, OPENSPACE.local.md, or retained auto-memory topics; detect duplicates, stale facts, conflicts, and ambiguous entries before making changes.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fopenspace\u002Fskills\u002Fremember\u002FSKILL.md",[],[81,86,87,88,89,90,91,92,93,94,95,96,97],"memory","review","auto","openspace","changes","facts","detect","entries","local","conflicts","stale","duplicates",{"skillNo":99,"name":100,"nameZh":6,"description":101,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":102,"categories":103,"keywords":109,"publishedAt":26},"01M6HYAVMPM4SBDV60R2B5HPV8","skill-discovery","Search reusable OpenSpace skills locally, and browse cloud packages step by step when a cloud skill may help. Reusing proven skills saves tokens, improves reliability, and extends your capabilities beyond built-in tools.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fopenspace\u002Fhost_skills\u002Fskill-discovery\u002FSKILL.md",[104],{"categoryNo":105,"categoryName":106,"taxonomyType":107,"taxonomyTypeDesc":108},"01JBSEEDCAT000000000000023","Skill与智能体开发","SCENARIO","使用场景",[110,111,112,89,113,114,115,116,117,118,119,120,121,122],"skill discovery","discovery","reusable","step by step","tokens","packages","help","cloud","reliability","capabilities","browse","search","Tools",{"skillNo":124,"name":125,"nameZh":6,"description":126,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":127,"categories":128,"keywords":130,"publishedAt":26},"01M6HYAR811B3RB0M50RBEDGN6","delegate-task","Delegate tasks to OpenSpace — a full-stack autonomous worker for coding, DevOps, web research, and desktop automation, backed by an extensive MCP tool and skill library. Skills auto-improve through use, reducing token consumption over time. A cloud community lets agents share and collectively evolve reusable skills.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fopenspace\u002Fhost_skills\u002Fdelegate-task\u002FSKILL.md",[129],{"categoryNo":105,"categoryName":106,"taxonomyType":107,"taxonomyTypeDesc":108},[131,132,133,89,134,135,136,137,138,112,88,73,139,140,141,142,143,144,145,146],"delegate","task","delegate task","time","improve","desktop automation","worker","community","autonomous","tool","stack","for","share","tasks","automation","MCP",{"skillNo":148,"name":149,"nameZh":6,"description":150,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":151,"categories":152,"keywords":153,"publishedAt":26},"01M6HYAM9FSGV6E52AYENDQXYH","write-special-chars-ts-check","Workaround for write_file failures caused by special characters (apostrophes, backticks, template literals) using a Python heredoc script, plus a reliable TypeScript type-checking step that filters output to only the newly-written files to avoid being misled by pre-existing errors.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Flegacy\u002Fv1\u002Fshowcase\u002Fskills\u002Fwrite-special-chars-ts-check\u002FSKILL.md",[],[154,155,156,157,158,159,160,161,162,163,164,165,166,167,142,168,169],"write special chars ts check","write","check","type","files","filters","only","template","file","python","typescript","output","Existing","type-checking","errors","script",{"skillNo":171,"name":172,"nameZh":6,"description":173,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":174,"categories":175,"keywords":176,"publishedAt":26},"01M6HYAH05HGV7SVWSVR8PJRQD","write-special-chars-readback","Workaround for write_file failures caused by special characters (apostrophes, backticks, template literals) using a Python heredoc script, with mandatory post-write verification via read_file and cleanup of \u002Ftmp helper scripts.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Flegacy\u002Fv1\u002Fshowcase\u002Fskills\u002Fwrite-special-chars-readback\u002FSKILL.md",[],[177,178,155,24,142,169,179,180,181,182,183,161,162,184,185,163],"write special chars readback","readback","helper","post","via","scripts","read","verification","cleanup"]