{"record":{"id":"b2b5e6fe9b07eebe","repo":"paperclipai/paperclip","slug":"agent-not-found-agentchat","errorCode":null,"errorMessage":"Agent not found","messagePattern":"Agent not found","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"ui/src/pages/AgentChat.tsx","lineNumber":49,"sourceCode":"  const agent = agents.data?.find(\n    (item) => item.id === agentRef || agentRouteRef(item) === agentRef,\n  );\n  const chatKey = queryKeys.agentChats.detail(selectedCompanyId, userId, agent?.id);\n  const chat = useQuery({\n    queryKey: chatKey,\n    queryFn: () => agentChatsApi.get(selectedCompanyId!, agent!.id),\n    enabled: enabled && !!agent && session.isFetched,\n  });\n  const creating = useRef<Promise<Issue> | null>(null);\n  useEffect(() => {\n    creating.current = null;\n  }, [selectedCompanyId, userId, agent?.id]);\n  useEffect(() => {\n    if (enabled && agent && session.isFetched)\n      recordAgentChatVisit(agent.companyId, userId, agent.id);\n  }, [enabled, agent?.id, agent?.companyId, userId, session.isFetched]);\n  const ensureIssue = useCallback(async () => {\n    if (!agent || !selectedCompanyId) throw new Error(\"Agent not found\");\n    if (chat.data) return chat.data;\n    const promise = (creating.current ??= agentChatsApi.ensure(\n      selectedCompanyId,\n      agent.id,\n    ));\n    try {\n      const issue = await promise;\n      client.setQueryData(queryKeys.issues.detail(issue.id), issue);\n      client.setQueryData(chatKey, issue);\n      return issue;\n    } catch (error) {\n      creating.current = null;\n      throw error;\n    }\n  }, [agent, selectedCompanyId, chat.data, client, userId]);\n  if (!loaded || agents.isPending || session.isPending)\n    return (\n      <p className=\"text-sm text-muted-foreground\">Loading conversation…</p>","sourceCodeStart":31,"sourceCodeEnd":67,"githubUrl":"https://github.com/paperclipai/paperclip/blob/3f1d897a7c018d76563a21c6e39c3c9b03933622/ui/src/pages/AgentChat.tsx#L31-L67","documentation":"AgentChat throws 'Agent not found' when the ensureIssue callback is invoked before an agent has been resolved for the current chat context. The page fetches the agent asynchronously; if the user action (or query) runs while `agent` is still undefined, or after it fails to load for the selected company, the guard `if (!agent || !selectedCompanyId)` throws. It is a local client-side guard, not a server 404 — it means the UI's agent data has not been resolved yet.","triggerScenarios":"Calling `ensureIssue()` (directly or via chat creation/recordAgentChatVisit flows) while the agent query is still loading; navigating to an agent chat URL whose agent id does not exist or belongs to another company so the query resolves with no agent; selectedCompanyId is unset when the effect fires.","commonSituations":"Developer opens AgentChat with a stale or bookmarked agent id; company switcher changes selectedCompanyId before the agent refetch completes; a component callback (attachment, message send) fires during initial render when agent is undefined; deleted agent referenced by an old URL.","solutions":["Wait for the agent query before enabling actions: gate the calling code on `agent && selectedCompanyId` (e.g. disable buttons until loaded).","Return an early result or skip the call instead of throwing when `agent` is undefined, e.g. `if (!agent || !selectedCompanyId) return;` where a thrown value is unnecessary.","Check that the agent id in the route is valid and that the agent query key includes the correct selectedCompanyId/company scoping.","If the agent truly does not exist, show a not-found state and redirect the user instead of surfacing the raw Error."],"exampleFix":"// before\nconst ensureIssue = useCallback(async () => {\n  if (!agent || !selectedCompanyId) throw new Error(\"Agent not found\");\n  ...\n}, []);\n\n// after\nconst ensureIssue = useCallback(async () => {\n  if (!agent || !selectedCompanyId) return null; // caller handles null\n  ...\n}, [agent?.id, selectedCompanyId]);","handlingStrategy":"validation","validationCode":"if (!agent || !selectedCompanyId) return; // skip the call until data resolves","typeGuard":"const isAgentReady = (a: Agent | null | undefined, c: string | null | undefined): a is Agent => Boolean(a?.id && c);","tryCatchPattern":"try {\n  await ensureIssue();\n} catch (err) {\n  if (err instanceof Error && err.message === \"Agent not found\") {\n    showError(\"Chat is still initializing — try again in a moment.\");\n  } else { throw err; }\n}","preventionTips":["Gate all agent-dependent actions on the agent query's isSuccess state","Include agent id validity in the route's loader so the page never renders actions without it","Disable or hide chat actions while agent is undefined","Redirect to a not-found page when the agent query returns nothing"],"tags":["react","client-side-guard","loading-state","ui"],"backgroundTag":"entity-not-found","analyzedSha":"3f1d897a7c018d76563a21c6e39c3c9b03933622","analyzedAt":"2026-09-18T08:03:59.046Z","contentChangedAt":"2026-09-18T08:03:59.046Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}