{"record":{"id":"313b9920ddd2fe50","repo":"different-ai/openwork","slug":"failed-to-apply-github-discovery-response-statu","errorCode":null,"errorMessage":"Failed to apply GitHub discovery (${response.status}).","messagePattern":"Failed to apply GitHub discovery \\((.+?)\\)\\.","errorType":"http","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"ee/apps/den-web/app/(den)/dashboard/_components/integration-data.tsx","lineNumber":810,"sourceCode":"export function useApplyGithubDiscovery() {\n  const queryClient = useQueryClient();\n  const { runReauthableAction } = useOrgDashboard();\n\n  return useMutation({\n    mutationFn: async (input: { autoImportNewPlugins: boolean; connectorInstanceId: string; selectedKeys: string[] }): Promise<GithubDiscoveryApplyResult> => {\n      let result: GithubDiscoveryApplyResult | null = null;\n      await runReauthableAction(\"apply-github-discovery\", async () => {\n      const { response, payload } = await requestJson(\n        `/v1/connector-instances/${encodeURIComponent(input.connectorInstanceId)}/discovery/apply`,\n        {\n          method: \"POST\",\n          body: JSON.stringify({ autoImportNewPlugins: input.autoImportNewPlugins, selectedKeys: input.selectedKeys }),\n        },\n        20000,\n      );\n\n      if (!response.ok) {\n        throw getRequestError(payload, response, `Failed to apply GitHub discovery (${response.status}).`);\n      }\n\n      const item = isRecord(payload) && isRecord(payload.item) ? payload.item : null;\n      const createdPlugins = item && Array.isArray(item.createdPlugins)\n        ? item.createdPlugins.flatMap((entry) => {\n            if (!isRecord(entry)) return [];\n            const name = asString(entry.name);\n            return name ? [name] : [];\n          })\n        : [];\n      const createdMappingCount = item && Array.isArray(item.createdMappings) ? item.createdMappings.length : 0;\n      const materializedConfigObjectCount = item && Array.isArray(item.materializedConfigObjects) ? item.materializedConfigObjects.length : 0;\n\n        result = {\n        autoImportNewPlugins: item ? Boolean(item.autoImportNewPlugins) : input.autoImportNewPlugins,\n        createdMappingCount,\n        materializedConfigObjectCount,\n        createdPluginNames: createdPlugins,","sourceCodeStart":792,"sourceCodeEnd":828,"githubUrl":"https://github.com/different-ai/openwork/blob/2b7df46e8ae1517d64c896c7793d2d52ec845669/ee/apps/den-web/app/(den)/dashboard/_components/integration-data.tsx#L792-L828","documentation":"Thrown when applying a GitHub discovery result (auto-importing selected repositories as plugins) fails with a non-2xx response. Like all call sites, the error is produced by getRequestError (den-flow.ts:527), which surfaces the server's `error` message or the fallback \"Failed to apply GitHub discovery (<status>).\"; a 403 {error:'reauth'} payload becomes a ReauthRequiredError.","triggerScenarios":"POST of {autoImportNewPlugins, selectedKeys} with a 20s timeout throws when response.ok is false: 401/403 (expired session or missing permission), 404 (the discovery session or connector instance expired server-side), 409 (selected keys already imported), 422 (selectedKeys no longer valid or malformed), 5xx (server error importing from GitHub).","commonSituations":"User leaves the discovery screen open, the connector's discovery session expires, then submits; selected repos were deleted or renamed on GitHub; user lacks admin rights on the org; concurrent import by another admin creates duplicate keys.","solutions":["Inspect the status in the message; for 401/403 force a re-login before retrying.","If 404, refresh the discovery results (re-run discovery) and resubmit with fresh selectedKeys.","If 409, reload existing plugins and deselect already-imported keys.","If 422, validate selectedKeys against the latest discovery payload before submitting."],"exampleFix":"// before\nif (!response.ok) {\n  throw getRequestError(payload, response, `Failed to apply GitHub discovery (${response.status}).`);\n}\n// after\nif (!response.ok) {\n  if (response.status === 404 || response.status === 422) {\n    await refetchDiscovery();\n    throw new Error(\"Discovery results are stale — please review and resubmit.\");\n  }\n  throw getRequestError(payload, response, `Failed to apply GitHub discovery (${response.status}).`);\n}","handlingStrategy":"try-catch","validationCode":"// before applying discovery\nconst validKeys = new Set(discoveryResults.map((r) => r.key));\nconst unknown = selectedKeys.filter((k) => !validKeys.has(k));\nif (unknown.length > 0) throw new Error(`Stale selection: ${unknown.join(\", \")}`);","typeGuard":"function isReauthError(e: unknown): e is ReauthRequiredError {\n  return e instanceof ReauthRequiredError;\n}","tryCatchPattern":"try {\n  await applyDiscoveryMutation.mutateAsync({ selectedKeys, autoImportNewPlugins });\n} catch (error) {\n  if (isReauthError(error)) { startReauth(); return; }\n  if (/\\((404|422)\\)/.test(error.message)) { await refetchDiscovery(); }\n  showToast(error.message);\n}","preventionTips":["Refresh discovery results before submit if the page has been idle (stale selectedKeys 404/422).","Diff selectedKeys against the latest discovery payload client-side.","Handle conflict (already imported) by refreshing the plugin list instead of retrying blindly.","Ensure the user has admin rights before enabling the apply button."],"tags":["http","github-integration","den-api","react-query"],"backgroundTag":"http-non-ok-response","analyzedSha":"2b7df46e8ae1517d64c896c7793d2d52ec845669","analyzedAt":"2026-09-01T07:59:23.713Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-08T10:18:20.063Z"}