{"record":{"id":"fbd49cba268080d7","repo":"JuliusBrussee/caveman","slug":"device-login-polling-failed-error-instanceof-er-fbd49c","errorCode":null,"errorMessage":"device login polling failed: ${error instanceof Error ? error.message : String(error)}","messagePattern":"device login polling failed: (.+?)","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"packages/device-auth/src/index.ts","lineNumber":134,"sourceCode":"    let retryAfterMs = 0;\n    try {\n      const response = await fetcher(`${baseURL}/api/v1/auth/device/token`, {\n        method: \"POST\",\n        headers: { \"content-type\": \"application/json\", \"x-cave-client\": options.client },\n        body: JSON.stringify({ device_code: code.device_code }),\n        signal: requestSignal(options.signal, 5000),\n      });\n      status = response.status;\n      const retryAfter = response.headers.get(\"retry-after\");\n      if (retryAfter !== null) {\n        const seconds = Number(retryAfter);\n        if (Number.isFinite(seconds) && seconds >= 0) retryAfterMs = seconds * 1000;\n      }\n      payload = await response.json() as Record<string, unknown>;\n    } catch (error) {\n      if (options.signal?.aborted) throw options.signal.reason;\n      if (Date.now() >= deadline) {\n        throw new Error(`device login polling failed: ${error instanceof Error ? error.message : String(error)}`);\n      }\n      await wait(Math.max(intervalMs, retryAfterMs, 200));\n      continue;\n    }\n    if (status === 429) {\n      await wait(Math.max(intervalMs, retryAfterMs, 200));\n      continue;\n    }\n    const accessToken = typeof payload.access_token === \"string\" ? payload.access_token : \"\";\n    if (accessToken !== \"\") {\n      const credentials = { ...payload, access_token: accessToken } as DeviceCredentials;\n      let acknowledged = false;\n      return {\n        code: structuredClone(code),\n        credentials: structuredClone(credentials),\n        async acknowledge() {\n          if (acknowledged) return;\n          await acknowledge({","sourceCodeStart":116,"sourceCodeEnd":152,"githubUrl":"https://github.com/JuliusBrussee/caveman/blob/3ee70a102609e550bd2e68004bf5990a9341c851/packages/device-auth/src/index.ts#L116-L152","documentation":"Thrown by runCavemanDeviceFlow when a token-polling request throws (network error, invalid JSON, etc.) and the polling deadline has already passed. The original error's message is wrapped in 'device login polling failed: ...'. If the signal aborted, the signal's reason is rethrown instead; if time remains, the loop retries after a backoff wait.","triggerScenarios":"Inside the polling loop's catch block: a fetch or response.json() error occurs AND Date.now() >= deadline (the expires_in window from the device code has elapsed).","commonSituations":"User takes longer than expires_in to approve, network drops out mid-poll, server returns malformed JSON on the last poll after the window closed, or laptop sleeps past the deadline.","solutions":["Restart the device flow (call runCavemanDeviceFlow again) to obtain a fresh device code with a new expiry window.","Fix the underlying network issue named in the wrapped message (DNS, TLS, proxy).","Complete approval in the browser before expires_in elapses; the wrapped message shows the last poll error after the deadline.","If timeouts are frequent, check system clock skew — Date.now() vs server time affects the deadline."],"exampleFix":"// before: user approves too late\nawait runCavemanDeviceFlow({ ..., onCode: c => console.log(c.user_code) }); // expired after 15 min\n// after: detect and retry with a fresh code\ntry { await runCavemanDeviceFlow(opts); } catch (e) {\n  if (String(e.message).startsWith('device login polling failed')) await runCavemanDeviceFlow(opts);\n}","handlingStrategy":"retry","validationCode":null,"typeGuard":null,"tryCatchPattern":"try {\n  await runCavemanDeviceFlow(opts);\n} catch (e) {\n  if (e instanceof Error && e.message.startsWith('device login polling failed')) {\n    // deadline passed with a transport error: restart the flow with a fresh device code\n    await runCavemanDeviceFlow(opts);\n  } else throw e;\n}","preventionTips":["Prompt users to approve promptly within expires_in","Restart the whole flow on polling failure rather than resuming","Ensure network stability (avoid sleeping/suspending mid-flow)","Check AbortSignal wiring — pass a signal only when cancellation is intended"],"tags":["network","timeout","device-auth","polling"],"backgroundTag":"request-timeout","analyzedSha":"3ee70a102609e550bd2e68004bf5990a9341c851","analyzedAt":"2026-09-20T15:53:39.229Z","contentChangedAt":"2026-09-20T15:53:39.229Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}