Skip to content

🀯 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.

πŸ› fix(agent-runtime): persist empty completion retry diagnostics (#16876)

Arvin Xu8cc61ed187f4
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
index ce3e6f50cec..6bdb643c905 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
@@ -915,13 +915,27 @@ describe('RuntimeExecutors', () => {
state,
);
// Drive the retry backoff sleeps to completion.
- const settled = expect(promise).rejects.toBeInstanceOf(ModelEmptyError);
+ const rejection = promise.catch((error) => error);
await vi.runAllTimersAsync();
// Must throw (so the harness records a readable error state) instead of
// silently finalizing to a completion with a blank assistant message.
- await settled;
+ const error = await rejection;
+ expect(error).toBeInstanceOf(ModelEmptyError);
// EMPTY_COMPLETION_MAX_RETRIES (2) retries β†’ 3 total attempts.
expect(mockChat).toHaveBeenCalledTimes(3);
+ expect(error.diagnostics).toMatchObject({
+ attempt: 3,
+ maxAttempts: 3,
+ model: 'deepseek-v4-pro',
+ outputTokens: 1,
+ provider: 'lobehub',
+ retryBudget: 2,
+ retryEvents: [
+ expect.objectContaining({ attempt: 2, delayMs: 1000, maxAttempts: 3 }),
+ expect.objectContaining({ attempt: 3, delayMs: 2000, maxAttempts: 3 }),
+ ],
+ toolCallCount: 0,
+ });
} finally {
vi.useRealTimers();
}
@@ -4738,7 +4752,7 @@ describe('RuntimeExecutors', () => {
'op-123',
expect.objectContaining({
type: 'stream_retry',
- data: { attempt: 2, delayMs: 1000, maxAttempts: 6 },
+ data: expect.objectContaining({ attempt: 2, delayMs: 1000, maxAttempts: 6 }),
}),
);
} finally {
@@ -4869,21 +4883,21 @@ describe('RuntimeExecutors', () => {
'op-123',
expect.objectContaining({
type: 'stream_retry',
- data: { attempt: 2, delayMs: 1000, maxAttempts: 6 },
+ data: expect.objectContaining({ attempt: 2, delayMs: 1000, maxAttempts: 6 }),
}),
);
expect(mockStreamManager.publishStreamEvent).toHaveBeenCalledWith(
'op-123',
expect.objectContaining({
type: 'stream_retry',
- data: { attempt: 3, delayMs: 2000, maxAttempts: 6 },
+ data: expect.objectContaining({ attempt: 3, delayMs: 2000, maxAttempts: 6 }),
}),
);
expect(mockStreamManager.publishStreamEvent).toHaveBeenCalledWith(
'op-123',
expect.objectContaining({
type: 'stream_retry',
- data: { attempt: 4, delayMs: 4000, maxAttempts: 6 },
+ data: expect.objectContaining({ attempt: 4, delayMs: 4000, maxAttempts: 6 }),
}),
);
} finally {
diff --git a/apps/server/src/modules/AgentRuntime/executors/callLlm.ts b/apps/server/src/modules/AgentRuntime/executors/callLlm.ts
index 58c44c9af7d..be934e98b02 100644
--- a/apps/server/src/modules/AgentRuntime/executors/callLlm.ts
+++ b/apps/server/src/modules/AgentRuntime/executors/callLlm.ts
@@ -1420,7 +1420,19 @@ export const callLlm =
attempt,
maxAttempts,
);
- throw new ModelEmptyError();
+ throw new ModelEmptyError(undefined, {
+ attempt,
+ contentLength: content.length,
+ finishReason: currentStepFinishReason,
+ imageCount: imageList.length,
+ maxAttempts,
+ model,
+ outputTokens:
+ typeof reportedOutputTokens === 'number' ? reportedOutputTokens : undefined,
+ provider,
+ reasoningLength: thinkingContent.length,
+ toolCallCount: toolsCalling.length + tool_calls.length,
+ });
}
// Answer-in-thinking salvage: some thinking-mode models β€” notably
@@ -1714,8 +1726,20 @@ export const callLlm =
delayMs,
);
+ const retryEvent: AgentEvent = {
+ data: {
+ attempt: attempt + 1,
+ delayMs,
+ errorType: classified.code,
+ kind: classified.kind,
+ maxAttempts,
+ },
+ type: 'stream_retry',
+ };
+ events.push(retryEvent);
+
await streamManager.publishStreamEvent(operationId, {
- data: { attempt: attempt + 1, delayMs, maxAttempts },
+ data: retryEvent.data,
stepIndex,
type: 'stream_retry',
});
@@ -1729,6 +1753,13 @@ export const callLlm =
continue;
}
+ if (error instanceof ModelEmptyError && error.diagnostics) {
+ error.diagnostics.retryBudget = retryBudget;
+ error.diagnostics.retryEvents = events
+ .filter((event) => event.type === 'stream_retry')
+ .map((event) => event.data);
+ }
+
// Cancel/interrupt path: when the user stops mid-stream, the model-runtime
// stream is aborted before reaching the post-stream finalize (line ~1078),
// so the DB row remains a LOADING_FLAT placeholder. Without this fix,
diff --git a/apps/server/src/modules/AgentRuntime/formatErrorForState.test.ts b/apps/server/src/modules/AgentRuntime/formatErrorForState.test.ts
index c1ba4c2321a..68e2946ed57 100644
--- a/apps/server/src/modules/AgentRuntime/formatErrorForState.test.ts
+++ b/apps/server/src/modules/AgentRuntime/formatErrorForState.test.ts
@@ -83,7 +83,14 @@ describe('formatErrorForState', () => {
});
it('enriches a thrown ModelEmptyError into a readable retryable terminal error', () => {
- const result = formatErrorForState(new ModelEmptyError());
+ const result = formatErrorForState(
+ new ModelEmptyError(undefined, {
+ attempt: 3,
+ maxAttempts: 3,
+ outputTokens: 1,
+ retryEvents: [{ attempt: 2, delayMs: 1000, maxAttempts: 3 }],
+ }),
+ );
// The `errorType` field must win over the generic Error β†’ InternalServerError
// path so the terminal state is classified and dashboard-visible instead of
@@ -95,6 +102,14 @@ describe('formatErrorForState', () => {
expect(result.countAsFailure).toBe(true);
expect(result.numericId).toBe(8014);
expect(result.message).toContain('empty completion');
+ expect(result.body).toMatchObject({
+ diagnostics: {
+ attempt: 3,
+ maxAttempts: 3,
+ outputTokens: 1,
+ retryEvents: [expect.objectContaining({ attempt: 2 })],
+ },
+ });
});
it('marks provider-side rate limits as retryable with provider attribution', () => {
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
index 37605d06bd5..c31a9294f28 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
@@ -1331,6 +1331,7 @@ export class AgentRuntimeService {
error: newStateError
? {
attribution: newStateError.attribution,
+ body: newStateError.body,
category: newStateError.category,
countAsFailure: newStateError.countAsFailure,
httpStatus: newStateError.httpStatus,
@@ -1441,6 +1442,7 @@ export class AgentRuntimeService {
completionReason: 'error',
error: {
attribution: formattedError.attribution,
+ body: formattedError.body,
category: formattedError.category,
countAsFailure: formattedError.countAsFailure,
httpStatus: formattedError.httpStatus,
@@ -1450,7 +1452,11 @@ export class AgentRuntimeService {
severity: formattedError.severity,
type: String(formattedError.type),
},
- failedStep: { startedAt: stepStartAt, stepIndex },
+ failedStep: {
+ startedAt: stepStartAt,
+ stepIndex,
+ stepType: formattedError.category === 'provider' ? 'call_llm' : 'call_tool',
+ },
state: finalStateWithError,
});
diff --git a/apps/server/src/services/agentRuntime/OperationTraceRecorder.ts b/apps/server/src/services/agentRuntime/OperationTraceRecorder.ts
index c0913e19645..3074d347e9b 100644
--- a/apps/server/src/services/agentRuntime/OperationTraceRecorder.ts
+++ b/apps/server/src/services/agentRuntime/OperationTraceRecorder.ts
@@ -55,6 +55,7 @@ export interface FinalizeParams {
*/
error?: {
attribution?: ChatMessageErrorAttribution;
+ body?: unknown;
category?: string;
countAsFailure?: boolean;
httpStatus?: number;
@@ -70,7 +71,7 @@ export interface FinalizeParams {
* so the catch caller passes this to keep step counts aligned with the
* assistant message that triggered the call. See .
*/
- failedStep?: { startedAt: number; stepIndex: number };
+ failedStep?: { startedAt: number; stepIndex: number; stepType?: 'call_llm' | 'call_tool' };
state: any;
}
@@ -151,12 +152,7 @@ export class OperationTraceRecorder {
executionTimeMs: now - params.failedStep.startedAt,
startedAt: params.failedStep.startedAt,
stepIndex: params.failedStep.stepIndex,
- // StepSnapshot.stepType is strictly 'call_llm' | 'call_tool';
- // persist-fatal originates in the tool path so 'call_tool' is the
- // truthful label. LLM-side failures still map here β€” the
- // surrounding `events: [{type: 'error'}]` is the discriminant
- // consumers read.
- stepType: 'call_tool',
+ stepType: params.failedStep.stepType ?? 'call_tool',
totalCost: params.state?.cost?.total ?? 0,
totalTokens: params.state?.usage?.llm?.tokens?.total ?? 0,
});
diff --git a/apps/server/src/services/agentRuntime/__tests__/OperationTraceRecorder.test.ts b/apps/server/src/services/agentRuntime/__tests__/OperationTraceRecorder.test.ts
index e2692aa61a8..f6d8abffbd2 100644
--- a/apps/server/src/services/agentRuntime/__tests__/OperationTraceRecorder.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/OperationTraceRecorder.test.ts
@@ -296,6 +296,55 @@ describe('OperationTraceRecorder', () => {
expect(saved.completionReason).toBe('error');
});
+ it('preserves failed LLM step type and structured error body diagnostics', async () => {
+ store.loadPartial.mockResolvedValue({
+ startedAt: 1000,
+ steps: [{ stepIndex: 0, stepType: 'call_tool' }],
+ });
+
+ await recorder.finalize('op-empty-completion', {
+ completionReason: 'error',
+ error: {
+ body: {
+ diagnostics: {
+ attempt: 3,
+ maxAttempts: 3,
+ outputTokens: 1,
+ retryEvents: [
+ { attempt: 2, delayMs: 1000, maxAttempts: 3, type: 'stream_retry' },
+ { attempt: 3, delayMs: 2000, maxAttempts: 3, type: 'stream_retry' },
+ ],
+ },
+ },
+ message: 'Model returned an empty completion',
+ retryable: true,
+ type: 'ModelEmptyCompletion',
+ },
+ failedStep: { startedAt: 5000, stepIndex: 1, stepType: 'call_llm' },
+ state: { metadata: {}, stepCount: 1 },
+ });
+
+ const saved = store.save.mock.calls[0][0];
+ const failed = saved.steps.find((s: any) => s.stepIndex === 1);
+ expect(failed.stepType).toBe('call_llm');
+ expect(failed.events?.[0]).toMatchObject({
+ error: {
+ body: {
+ diagnostics: {
+ attempt: 3,
+ retryEvents: [
+ expect.objectContaining({ attempt: 2 }),
+ expect.objectContaining({ attempt: 3 }),
+ ],
+ },
+ },
+ type: 'ModelEmptyCompletion',
+ },
+ type: 'error',
+ });
+ expect(saved.error.body.diagnostics).toMatchObject({ attempt: 3, maxAttempts: 3 });
+ });
+
it('merges the error event into an existing step when stepIndex collides (success-path append landed before later failure)', async () => {
// The success path may have already pushed step 1 to the partial before
// a later failure (e.g. saveAgentState throws post-append). The recorder
diff --git a/packages/agent-runtime/src/types/event.ts b/packages/agent-runtime/src/types/event.ts
index eb82a6860ee..c66c39e87fe 100644
--- a/packages/agent-runtime/src/types/event.ts
+++ b/packages/agent-runtime/src/types/event.ts
@@ -21,6 +21,17 @@ export interface AgentEventLlmResult {
type: 'llm_result';
}
+export interface AgentEventStreamRetry {
+ data: {
+ attempt: number;
+ delayMs: number;
+ errorType?: string;
+ kind?: string;
+ maxAttempts: number;
+ };
+ type: 'stream_retry';
+}
+
export interface AgentEventToolPending {
toolCalls: ToolsCalling[];
type: 'tool_pending';
@@ -120,6 +131,7 @@ export type AgentEvent =
| AgentEventLlmStart
| AgentEventLlmStream
| AgentEventLlmResult
+ | AgentEventStreamRetry
// Tool invocation
| AgentEventToolPending
| AgentEventToolResult
diff --git a/packages/model-runtime/src/errors/modelEmptyCompletion.ts b/packages/model-runtime/src/errors/modelEmptyCompletion.ts
index bb25937a712..0b2044f7519 100644
--- a/packages/model-runtime/src/errors/modelEmptyCompletion.ts
+++ b/packages/model-runtime/src/errors/modelEmptyCompletion.ts
@@ -1,5 +1,20 @@
import { AgentRuntimeErrorType } from '@lobechat/types';
+export interface ModelEmptyCompletionDiagnostics {
+ attempt?: number;
+ contentLength?: number;
+ finishReason?: string;
+ imageCount?: number;
+ maxAttempts?: number;
+ model?: string;
+ outputTokens?: number;
+ provider?: string;
+ reasoningLength?: number;
+ retryBudget?: number;
+ retryEvents?: Array<Record<string, unknown>>;
+ toolCallCount?: number;
+}
+
/**
* Thrown when the model returns an empty completion β€” no text content, no
* reasoning, no tool calls, no images, and ~0 output tokens. This is the "empty
@@ -19,12 +34,15 @@ import { AgentRuntimeErrorType } from '@lobechat/types';
*/
export class ModelEmptyError extends Error {
readonly errorType = AgentRuntimeErrorType.ModelEmptyCompletion;
+ readonly diagnostics?: ModelEmptyCompletionDiagnostics;
constructor(
message = 'Model returned an empty completion (no content, no tool calls, no output tokens).',
+ diagnostics?: ModelEmptyCompletionDiagnostics,
) {
super(message);
this.name = 'ModelEmptyError';
+ this.diagnostics = diagnostics;
}
}