{"record":{"id":"2ba8cbee9abc9685","repo":"yikart/AiToEarn","slug":"agenttasknotfound","errorCode":"AgentTaskNotFound","errorMessage":"AgentTaskNotFound","messagePattern":"AgentTaskNotFound","errorType":"error_code","errorClass":"AppException","httpStatus":null,"severity":"error","filePath":"project/aitoearn-backend/apps/aitoearn-ai/src/core/agent/services/agent-runtime.service.ts","lineNumber":726,"sourceCode":"    sessionId: string | undefined\n    historicalMessages: Array<Record<string, unknown>>\n    abortController: AbortController\n    mcpServers: Record<string, McpServerConfig>\n  }> {\n    let task\n    let originalTask\n    let sessionId: string | undefined\n    let historicalMessages: Array<Record<string, unknown>> = []\n\n    if (dto.taskId) {\n      const originalTaskId = dto.taskId\n      this.logger.debug({ taskId: originalTaskId }, `Resuming conversation for task ${originalTaskId}`)\n\n      originalTask = await this.contentGenerateRepository.getByUserIdAndId(userId, originalTaskId)\n      if (!originalTask) {\n        this.logger.warn({ taskId: originalTaskId }, `Task ${originalTaskId} not found for user ${userId}`)\n        throw new AppException(ResponseCode.AgentTaskNotFound)\n      }\n\n      sessionId = originalTask.sessionId\n      if (!sessionId) {\n        this.logger.warn({ taskId: originalTaskId }, `Task ${originalTaskId} has no sessionId, cannot resume`)\n        throw new AppException(ResponseCode.AgentTaskNotFound)\n      }\n\n      this.logger.debug({ taskId: originalTaskId, sessionId }, `Task ${originalTaskId} resuming with sessionId: ${sessionId}`)\n      task = originalTask\n      historicalMessages = originalTask.messages || []\n\n      await this.downloadAgentSession(originalTask)\n    }\n    else {\n      task = await this.contentGenerateRepository.create({\n        userId,\n      })\n      this.logger.debug({ taskId: task.id }, `Created new task ${task.id} for user ${userId}`)","sourceCodeStart":708,"sourceCodeEnd":744,"githubUrl":"https://github.com/yikart/AiToEarn/blob/d3aa8bea5b146a8675607cf0144d891aad3e9683/project/aitoearn-backend/apps/aitoearn-ai/src/core/agent/services/agent-runtime.service.ts#L708-L744","documentation":"initializeTask in agent-runtime.service.ts resumes an existing agent conversation: it loads the original task by id AND userId via contentGenerateRepository.getByUserIdAndId. If no task is found, it throws AppException(ResponseCode.AgentTaskNotFound). This means the given originalTaskId does not exist or does not belong to the requesting user.","triggerScenarios":"createContentGenerationTask is called with a continuation/originalTaskId that (a) was never created, (b) was deleted, (c) has a different userId (wrong user's token), or (d) contains a malformed/foreign-namespace id.","commonSituations":"Client cached a taskId from a cleared database/environment (dev vs prod); calling resume with a task id from another account after switching users; id truncation or wrong field passed by the frontend.","solutions":["Verify the originalTaskId exists in the content-generate collection for that exact userId; re-query with the same credentials","If the task was deleted or from another environment, start a fresh task instead of resuming","Check the client is not sending a stale/cached taskId after re-login or DB reset","Confirm the userId resolved from the auth token matches the task owner"],"exampleFix":"// before\noriginalTask = await this.contentGenerateRepository.getByUserIdAndId(userId, originalTaskId)\nif (!originalTask) throw new AppException(ResponseCode.AgentTaskNotFound)\n// after\nif (!ObjectId.isValid(originalTaskId)) throw new AppException(ResponseCode.AgentTaskNotFound)\noriginalTask = await this.contentGenerateRepository.getByUserIdAndId(userId, originalTaskId)\nif (!originalTask) throw new AppException(ResponseCode.AgentTaskNotFound)","handlingStrategy":"validation","validationCode":"// client-side pre-check before resuming\nif (!originalTaskId || !originalTaskId.trim()) throw new Error('originalTaskId is required to resume');\n// server-side: validate id shape before the DB query\nif (!ObjectId.isValid(originalTaskId)) throw new AppException(ResponseCode.AgentTaskNotFound);","typeGuard":"function isOwnTask(task: { userId: string } | null, userId: string): task is { userId: string } {\n  return task !== null && task.userId === userId;\n}","tryCatchPattern":"try {\n  await aiService.createContentGenerationTask({ originalTaskId });\n} catch (e) {\n  if (e instanceof AppException && e.code === ResponseCode.AgentTaskNotFound) {\n    // fall back to starting a new task instead of resuming\n  } else throw e;\n}","preventionTips":["Never cache taskId across logins or environment switches","Validate id format (ObjectId) before sending resume requests","Confirm the auth token belongs to the task owner","Clean stale task references in client storage after DB resets"],"tags":["agent","task-lookup","resume","user-scope"],"backgroundTag":"agent-task-not-found","analyzedSha":"d3aa8bea5b146a8675607cf0144d891aad3e9683","analyzedAt":"2026-08-31T14:19:24.185Z","schemaVersion":2},"datasetVersion":"2026-08-31T19:17:28.585Z"}