🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(expertise): skip history topics when the provider account refuses (#19539)
Arvin Xu08704326a3fb
diff --git a/apps/server/src/services/expertise/ingestion.test.ts b/apps/server/src/services/expertise/ingestion.test.tsindex 955fb9e8241..88f9fceb53a 100644--- a/apps/server/src/services/expertise/ingestion.test.ts+++ b/apps/server/src/services/expertise/ingestion.test.ts@@ -113,6 +113,54 @@ describe('ExpertiseIngestionService historical ingestion', () => {['agent_1', 'topic_2'],]);});++ it('finishes a topic as a skip when the provider account refuses', async () => {+ const service = new ExpertiseIngestionService({} as never, 'user_1');+ // The raw OpenAI SDK error xAI throws when the account has no credits: no runtime errorType.+ const outOfCredits = Object.assign(+ new Error('403 "You have run out of credits or need a Grok subscription."'),+ { status: 403 },+ );+ vi.spyOn(service, 'ingestCompletion').mockRejectedValue(outOfCredits);++ await expect(service.ingestHistoricalTopic('agent_1', 'topic_1')).resolves.toEqual({+ ingested: 0,+ reason: 'provider-account-error',+ });+ });++ it('treats a wrapped runtime quota error as a provider account refusal', async () => {+ const service = new ExpertiseIngestionService({} as never, 'user_1');+ vi.spyOn(service, 'ingestCompletion').mockRejectedValue({ errorType: 'InsufficientQuota' });++ await expect(service.ingestHistoricalTopic('agent_1', 'topic_1')).resolves.toEqual({+ ingested: 0,+ reason: 'provider-account-error',+ });+ });++ it('still throws transient provider failures so the workflow retries them', async () => {+ const service = new ExpertiseIngestionService({} as never, 'user_1');+ const overloaded = Object.assign(new Error('503 overloaded'), { status: 503 });+ vi.spyOn(service, 'ingestCompletion').mockRejectedValue(overloaded);++ await expect(service.ingestHistoricalTopic('agent_1', 'topic_1')).rejects.toBe(overloaded);+ });++ it('stops the local backfill once the provider account refuses', async () => {+ const service = new ExpertiseIngestionService({} as never, 'user_1');+ vi.spyOn(service, 'listHistoricalTopics').mockResolvedValue([+ { topicId: 'topic_1' },+ { topicId: 'topic_2' },+ { topicId: 'topic_3' },+ ] as never);+ const ingest = vi+ .spyOn(service, 'ingestHistoricalTopic')+ .mockResolvedValue({ ingested: 0, reason: 'provider-account-error' });++ await expect(service.ingestHistory('agent_1')).resolves.toEqual({ ingested: 0, scanned: 1 });+ expect(ingest).toHaveBeenCalledTimes(1);+ });});describe('ExpertiseIngestionService.ingestCompletion', () => {diff --git a/apps/server/src/services/expertise/ingestion.ts b/apps/server/src/services/expertise/ingestion.tsindex bf991eacee1..433bf181133 100644--- a/apps/server/src/services/expertise/ingestion.ts+++ b/apps/server/src/services/expertise/ingestion.ts@@ -26,6 +26,7 @@ import type { CompletionCallbackParams } from '@/server/services/agentSignal/polimport { AiGenerationService } from '@/server/services/aiGeneration';import { resolveExpertiseModelConfig } from './modelConfig';+import { isProviderAccountError } from './providerAccountError';const MAX_CONTEXT_MESSAGES = 24;const MAX_CONTEXT_CHARS = 24_000;@@ -231,13 +232,26 @@ export class ExpertiseIngestionService {return row?.count ?? 0;};- /** Imports one old topic with a stable key, so retrying the workflow cannot duplicate runs. */- ingestHistoricalTopic = async (agentId: string, topicId: string) =>- this.ingestCompletion({- agentId,- ingestionKey: `historical-v1:${topicId}`,- topicId,- });+ /**+ * Imports one old topic with a stable key, so retrying the workflow cannot duplicate runs.+ *+ * A provider account refusal is the user's to fix, not a server fault: it finishes as a skip so+ * the durable workflow neither reports a 500 nor retries every topic against a dead account.+ */+ ingestHistoricalTopic = async (agentId: string, topicId: string) => {+ try {+ return await this.ingestCompletion({+ agentId,+ ingestionKey: `historical-v1:${topicId}`,+ topicId,+ });+ } catch (error) {+ if (isProviderAccountError(error)) {+ return { ingested: 0, reason: 'provider-account-error' } as const;+ }+ throw error;+ }+ };/** Local-runtime fallback for the durable workflow used in queue deployments. */ingestHistory = async (agentId: string) => {@@ -250,6 +264,8 @@ export class ExpertiseIngestionService {const result = await this.ingestHistoricalTopic(agentId, topic.topicId);ingested += result.ingested;scanned += 1;+ // Every remaining topic would hit the same refusal until the user fixes their account.+ if (result.reason === 'provider-account-error') return { ingested, scanned };}const last = topicRows.at(-1);if (!last || topicRows.length < 50 || !last.lastActivityAt) break;diff --git a/apps/server/src/services/expertise/providerAccountError.ts b/apps/server/src/services/expertise/providerAccountError.tsnew file mode 100644index 00000000000..12023d0f8a8--- /dev/null+++ b/apps/server/src/services/expertise/providerAccountError.ts@@ -0,0 +1,27 @@+import { AgentRuntimeErrorType } from '@lobechat/types';++const ACCOUNT_ERROR_TYPES = new Set<string>([+ AgentRuntimeErrorType.AccountDeactivated,+ AgentRuntimeErrorType.InsufficientQuota,+ AgentRuntimeErrorType.InvalidProviderAPIKey,+ AgentRuntimeErrorType.NoAvailableProvider,+ AgentRuntimeErrorType.PermissionDenied,+]);+const ACCOUNT_ERROR_STATUSES = new Set([401, 402, 403]);++/**+ * Whether the provider refused the call because of the account behind it, not the request.+ *+ * Out of credits, a revoked key or a missing provider stays broken until the user acts, so a retry+ * only repeats the same refusal. Provider SDKs surface these either as a runtime `errorType` or,+ * when the body is not recognized (xAI's "run out of credits" 403), as a raw HTTP `status`.+ */+export const isProviderAccountError = (error: unknown) => {+ if (!error || typeof error !== 'object') return false;+ const { errorType, status } = error as { errorType?: unknown; status?: unknown };++ return (+ (typeof errorType === 'string' && ACCOUNT_ERROR_TYPES.has(errorType)) ||+ (typeof status === 'number' && ACCOUNT_ERROR_STATUSES.has(status))+ );+};