🤯 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(topic): stop re-dispatching topics whose summary model rejected user settings (#23114)
Arvin Xu1160d07ffc83
diff --git a/apps/server/src/services/topicAutoSummary/index.test.ts b/apps/server/src/services/topicAutoSummary/index.test.tsindex 76dd461ba98..393cf0d20bd 100644--- a/apps/server/src/services/topicAutoSummary/index.test.ts+++ b/apps/server/src/services/topicAutoSummary/index.test.ts@@ -12,6 +12,7 @@ const mocks = vi.hoisted(() => ({snapshotTopicUsage: vi.fn(),getUserSettings: vi.fn(),resolveSystemAgentModelConfig: vi.fn(),+ markSummaryFailed: vi.fn(),updateSummaryIfCurrent: vi.fn(),}));@@ -27,6 +28,7 @@ vi.mock('@/database/models/topicAnalysis', () => ({}));vi.mock('@/database/models/topicSummary', () => ({TopicSummaryModel: class {+ markSummaryFailed = mocks.markSummaryFailed;updateSummaryIfCurrent = mocks.updateSummaryIfCurrent;},topicSummaryEligibleMessage: undefined,@@ -171,6 +173,44 @@ describe('TopicAutoSummaryService', () => {expect(mocks.updateSummaryIfCurrent).not.toHaveBeenCalled();});+ it.each([+ 'InvalidProviderAPIKey',+ 'InsufficientQuota',+ 'ModelNotFound',+ 'InsufficientBudgetForModel',+ ])(+ 'records a %s rejection so the topic is not re-dispatched until a new message',+ async (errorType) => {+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ mocks.generateObject.mockRejectedValue({ errorType, provider: 'deepseek' });+ const service = new TopicAutoSummaryService(createDb(), 'user-1');++ const result = await service.summarize('topic-1');++ expect(result).toEqual({ reason: 'provider-rejected', summarized: false });+ expect(mocks.markSummaryFailed).toHaveBeenCalledWith({+ lastMessageId: 'message-1',+ lastMessageUpdatedAt: new Date('2026-07-31T10:00:00Z'),+ reason: errorType,+ topicId: 'topic-1',+ });+ expect(mocks.updateSummaryIfCurrent).not.toHaveBeenCalled();+ },+ );++ it.each([+ 'ProviderNetworkError',+ 'RateLimitExceeded',+ 'ProviderBizError',+ 'InvalidRequestFormat',+ ])('rethrows a retryable or unclassified %s without recording a failure', async (errorType) => {+ mocks.generateObject.mockRejectedValue({ errorType });+ const service = new TopicAutoSummaryService(createDb(), 'user-1');++ await expect(service.summarize('topic-1')).rejects.toMatchObject({ errorType });+ expect(mocks.markSummaryFailed).not.toHaveBeenCalled();+ });+it('still fails the step on any other generation error', async () => {mocks.generateObject.mockRejectedValue(new Error('provider down'));const service = new TopicAutoSummaryService(createDb(), 'user-1');@@ -278,6 +318,13 @@ describe('TopicAutoSummaryService', () => {reason: 'no-executor',});+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ mocks.analyzeTopic.mockRejectedValueOnce({ errorType: 'InvalidProviderAPIKey' });+ expect(await new TopicAutoSummaryService(createDb(), 'user-1').analyze('topic-1')).toEqual({+ analyzed: false,+ reason: 'provider-rejected',+ });+mocks.analyzeTopic.mockRejectedValueOnce(new Error('provider down'));await expect(new TopicAutoSummaryService(createDb(), 'user-1').analyze('topic-1'),diff --git a/apps/server/src/services/topicAutoSummary/index.ts b/apps/server/src/services/topicAutoSummary/index.tsindex 8f7c0b6dfb0..e5599d9064c 100644--- a/apps/server/src/services/topicAutoSummary/index.ts+++ b/apps/server/src/services/topicAutoSummary/index.ts@@ -1,12 +1,13 @@import { TRACING_SCENARIOS } from '@lobechat/const';import type { TracingOptions } from '@lobechat/llm-generation-tracing';+import { getErrorCodeSpec } from '@lobechat/model-runtime';import {chainTopicAutoSummary,TOPIC_AUTO_SUMMARY_JSON_SCHEMA,TOPIC_AUTO_SUMMARY_PROMPT_VERSION,} from '@lobechat/prompts';import type { SystemAgentItem, UserSystemAgentConfig } from '@lobechat/types';-import { AgentRuntimeErrorType, RequestTrigger } from '@lobechat/types';+import { AgentRuntimeErrorType, ChatErrorType, RequestTrigger } from '@lobechat/types';import debug from 'debug';import { and, desc, eq } from 'drizzle-orm';@@ -30,13 +31,13 @@ const MAX_TRANSCRIPT_CHARS = 60_000;type SkipReason = 'disabled' | 'empty' | 'stale';export interface TopicAutoSummaryResult {- reason?: SkipReason | 'invalid-output' | 'no-executor';+ reason?: SkipReason | 'invalid-output' | 'no-executor' | 'provider-rejected';summarized: boolean;}export interface TopicAnalysisOutcome {analyzed: boolean;- reason?: SkipReason | 'invalid-output' | 'no-executor';+ reason?: SkipReason | 'invalid-output' | 'no-executor' | 'provider-rejected';}interface TopicContext {@@ -46,9 +47,39 @@ interface TopicContext {transcript: string;}+const errorTypeOf = (error: unknown) => (error as { errorType?: unknown })?.errorType;+const isClientOnlyModelError = (error: unknown) =>- (error as { errorType?: unknown })?.errorType ===- AgentRuntimeErrorType.ClientLlmExecutorUnavailable;+ errorTypeOf(error) === AgentRuntimeErrorType.ClientLlmExecutorUnavailable;++/**+ * Codes outside the auth / quota / config categories that a retry cannot fix+ * either: the chosen model is gone, the local runtime is down, or the topic no+ * longer fits the model's context.+ */+const SETTLED_REQUEST_ERRORS = new Set<string>([+ AgentRuntimeErrorType.ExceededContextWindow,+ AgentRuntimeErrorType.ModelNotFound,+ AgentRuntimeErrorType.OllamaServiceUnavailable,+ ChatErrorType.LobeHubModelDeprecated,+]);+const SETTLED_CATEGORIES = new Set(['auth', 'config', 'quota']);++/**+ * The user's own model setup rejected the call (invalid key, no balance or+ * budget, unknown or retired model). Retrying cannot succeed until the user+ * changes their settings. Request-shape errors stay out on purpose: they may+ * come from our own prompt or schema and must keep failing visibly.+ */+const userSettingsRejected = (error: unknown): string | undefined => {+ const errorType = errorTypeOf(error);+ if (typeof errorType !== 'string') return;+ const spec = getErrorCodeSpec(errorType);+ if (!spec || spec.attribution !== 'user' || spec.retryable) return;+ return SETTLED_CATEGORIES.has(spec.category) || SETTLED_REQUEST_ERRORS.has(errorType)+ ? errorType+ : undefined;+};export class TopicAutoSummaryService {constructor(@@ -102,6 +133,22 @@ export class TopicAutoSummaryService {log('skip topic %s: %s has no executor outside a browser tab', topicId, provider);return { reason: 'no-executor', summarized: false };}+ // Without a summary the watermark never moves, so every dispatch run would+ // call the user's misconfigured model again for the same topic. Record the+ // failure instead; a new message makes the topic a candidate again.+ const rejected = userSettingsRejected(error);+ if (rejected) {+ console.warn(+ `[topic-auto-summary] summary rejected by user settings: topicId=${topicId} provider=${provider} model=${model} errorType=${rejected}`,+ );+ await new TopicSummaryModel(this.db).markSummaryFailed({+ lastMessageId: latest.id,+ lastMessageUpdatedAt: latest.updatedAt,+ reason: rejected,+ topicId,+ });+ return { reason: 'provider-rejected', summarized: false };+ }throw error;}@@ -153,6 +200,13 @@ export class TopicAutoSummaryService {});} catch (error) {if (isClientOnlyModelError(error)) return { analyzed: false, reason: 'no-executor' };+ const rejected = userSettingsRejected(error);+ if (rejected) {+ console.warn(+ `[topic-auto-summary] analysis rejected by user settings: topicId=${topicId} provider=${provider} model=${model} errorType=${rejected}`,+ );+ return { analyzed: false, reason: 'provider-rejected' };+ }throw error;}if (!result) {diff --git a/packages/database/src/models/__tests__/topicSummary.test.ts b/packages/database/src/models/__tests__/topicSummary.test.tsindex b2cfb47f80f..44dc98a9d19 100644--- a/packages/database/src/models/__tests__/topicSummary.test.ts+++ b/packages/database/src/models/__tests__/topicSummary.test.ts@@ -467,4 +467,159 @@ describe('TopicSummaryModel', () => {});expect(forced.map(({ id }) => id)).toEqual(['cursor-b', 'cursor-c']);});++ describe('markSummaryFailed', () => {+ const at = new Date('2026-07-31T10:00:00Z');+ const window = {+ idleBefore: new Date('2026-07-31T11:00:00Z'),+ limit: 20,+ topicCreatedAfter: new Date('2026-07-30T12:00:00Z'),+ };++ beforeEach(async () => {+ await db+ .insert(topics)+ .values({ createdAt: new Date('2026-07-31T00:00:00Z'), id: 'rejected', userId });+ await db.insert(messages).values({+ content: 'a',+ id: 'm-1',+ role: 'user',+ topicId: 'rejected',+ updatedAt: at,+ userId,+ });+ });++ it('keeps the topic out of dispatch until a new message arrives', async () => {+ expect(+ await model.markSummaryFailed({+ lastMessageId: 'm-1',+ lastMessageUpdatedAt: at,+ reason: 'InvalidProviderAPIKey',+ topicId: 'rejected',+ }),+ ).toBe(true);++ expect((await model.listCandidates(window)).map((c) => c.id)).not.toContain('rejected');++ await db.insert(messages).values({+ content: 'b',+ id: 'm-2',+ role: 'user',+ topicId: 'rejected',+ updatedAt: new Date('2026-07-31T10:30:00Z'),+ userId,+ });+ expect((await model.listCandidates(window)).map((c) => c.id)).toContain('rejected');+ });++ it('records the failure without dropping an earlier summary marker', async () => {+ expect(+ await model.updateSummaryIfCurrent({+ description: 'd',+ lastMessageId: 'm-1',+ lastMessageUpdatedAt: at,+ summary: 's',+ topicId: 'rejected',+ }),+ ).toBe(true);+ const [before] = await db+ .select({ metadata: topics.metadata, summary: topics.historySummary })+ .from(topics)+ .where(eq(topics.id, 'rejected'));+ await db.insert(messages).values({+ content: 'b',+ id: 'm-2',+ role: 'user',+ topicId: 'rejected',+ updatedAt: new Date('2026-07-31T10:30:00Z'),+ userId,+ });++ await model.markSummaryFailed({+ lastMessageId: 'm-2',+ lastMessageUpdatedAt: new Date('2026-07-31T10:30:00Z'),+ reason: 'InsufficientQuota',+ topicId: 'rejected',+ });++ const [after] = await db+ .select({ metadata: topics.metadata, summary: topics.historySummary })+ .from(topics)+ .where(eq(topics.id, 'rejected'));+ expect(after.summary).toBe('s');+ expect(after.metadata?.autoSummary).toMatchObject({+ failureReason: 'InsufficientQuota',+ lastMessageId: 'm-2',+ lastMessageUpdatedAt: '2026-07-31T10:30:00.000Z',+ summarizedAt: before.metadata?.autoSummary?.summarizedAt,+ });+ expect(after.metadata?.autoSummary?.failedAt).toEqual(expect.any(String));+ });++ it('clears the failure once a summary is written', async () => {+ await model.markSummaryFailed({+ lastMessageId: 'm-1',+ lastMessageUpdatedAt: at,+ reason: 'ModelNotFound',+ topicId: 'rejected',+ });+ await model.updateSummaryIfCurrent({+ description: 'd',+ lastMessageId: 'm-1',+ lastMessageUpdatedAt: at,+ summary: 's',+ topicId: 'rejected',+ });++ const [row] = await db+ .select({ metadata: topics.metadata })+ .from(topics)+ .where(eq(topics.id, 'rejected'));+ expect(row.metadata?.autoSummary?.failedAt).toBeUndefined();+ expect(row.metadata?.autoSummary?.summarizedAt).toEqual(expect.any(String));+ });++ it('never rewinds the watermark when a newer message already exists', async () => {+ await db.insert(messages).values({+ content: 'b',+ id: 'm-2',+ role: 'user',+ topicId: 'rejected',+ updatedAt: new Date('2026-07-31T10:30:00Z'),+ userId,+ });++ expect(+ await model.markSummaryFailed({+ lastMessageId: 'm-1',+ lastMessageUpdatedAt: at,+ reason: 'InvalidProviderAPIKey',+ topicId: 'rejected',+ }),+ ).toBe(false);++ const [row] = await db+ .select({ metadata: topics.metadata })+ .from(topics)+ .where(eq(topics.id, 'rejected'));+ expect(row.metadata?.autoSummary).toBeUndefined();+ });++ it('leaves trashed topics alone', async () => {+ await db+ .update(topics)+ .set({ isDeleted: true, deletedAt: new Date() })+ .where(eq(topics.id, 'rejected'));++ expect(+ await model.markSummaryFailed({+ lastMessageId: 'm-1',+ lastMessageUpdatedAt: at,+ reason: 'InvalidProviderAPIKey',+ topicId: 'rejected',+ }),+ ).toBe(false);+ });+ });});diff --git a/packages/database/src/models/topicSummary.ts b/packages/database/src/models/topicSummary.tsindex ffab8c0fc80..ac7fde63b37 100644--- a/packages/database/src/models/topicSummary.ts+++ b/packages/database/src/models/topicSummary.ts@@ -77,6 +77,29 @@ const mergeAutoSummaryMetadata = (marker: NonNullable<ChatTopicMetadata['autoSumexport class TopicSummaryModel {constructor(private readonly db: LobeChatDatabase) {}+ /** An eligible message that arrived after the given snapshot. */+ private newerEligibleMessage = (input: {+ lastMessageId: string;+ lastMessageUpdatedAt: Date;+ topicId: string;+ }) =>+ this.db+ .select({ id: messages.id })+ .from(messages)+ .where(+ and(+ eq(messages.topicId, input.topicId),+ topicSummaryEligibleMessage,+ or(+ gt(messages.updatedAt, input.lastMessageUpdatedAt),+ and(+ eq(messages.updatedAt, input.lastMessageUpdatedAt),+ gt(messages.id, input.lastMessageId),+ ),+ ),+ ),+ );+listCandidates = async ({cursor,force = false,@@ -156,22 +179,7 @@ export class TopicSummaryModel {eq(messages.updatedAt, input.lastMessageUpdatedAt),),);- const newerMessage = this.db- .select({ id: messages.id })- .from(messages)- .where(- and(- eq(messages.topicId, input.topicId),- topicSummaryEligibleMessage,- or(- gt(messages.updatedAt, input.lastMessageUpdatedAt),- and(- eq(messages.updatedAt, input.lastMessageUpdatedAt),- gt(messages.id, input.lastMessageId),- ),- ),- ),- );+ const newerMessage = this.newerEligibleMessage(input);const rows = await this.db.update(topics)@@ -199,4 +207,43 @@ export class TopicSummaryModel {return rows.length > 0;};++ /**+ * Advance the watermark without a summary when the model failed for a reason+ * only the user can fix, so the dispatch stops re-queueing the topic every run+ * until a new message arrives. A summary written earlier is kept.+ */+ markSummaryFailed = async (input: {+ lastMessageId: string;+ lastMessageUpdatedAt: Date;+ reason: string;+ topicId: string;+ }): Promise<boolean> => {+ const failure = {+ failedAt: new Date().toISOString(),+ failureReason: input.reason,+ lastMessageId: input.lastMessageId,+ lastMessageUpdatedAt: input.lastMessageUpdatedAt.toISOString(),+ version: 1,+ };++ const rows = await this.db+ .update(topics)+ .set({+ // Merge into the existing marker: `summarizedAt` from an earlier summary survives.+ metadata: sql`jsonb_set(COALESCE(${topics.metadata}, '{}'::jsonb), '{autoSummary}', COALESCE(${topics.metadata}->'autoSummary', '{}'::jsonb) || ${JSON.stringify(failure)}::jsonb)`,+ })+ .where(+ and(+ eq(topics.id, input.topicId),+ notShareVisitorTopic(),+ notTrashed(topics.isDeleted),+ // A newer message means a later run owns the watermark; never rewind it.+ notExists(this.newerEligibleMessage(input)),+ ),+ )+ .returning({ id: topics.id });++ return rows.length > 0;+ };}diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.tsindex 0b93f6d7e77..84faa942345 100644--- a/packages/types/src/topic/topic.ts+++ b/packages/types/src/topic/topic.ts@@ -130,9 +130,17 @@ export interface OnboardingSessionSnapshot {export interface ChatTopicMetadata {/** Watermark written by the background topic-summary workflow. */autoSummary?: {+ /**+ * Set when the summary model rejected the request for a reason only the user+ * can fix (invalid key, no balance, missing model). The watermark still moves,+ * so the topic is retried only after a new message.+ */+ failedAt?: string;+ failureReason?: string;lastMessageId: string;lastMessageUpdatedAt: string;- summarizedAt: string;+ /** Absent until a summary has been written for this topic. */+ summarizedAt?: string;version: number;};