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(model-runtime): classify mid-stream socket drops as ProviderStreamInterrupted (#22827)

Arvin Xu976b02dff59e
diff --git a/packages/model-runtime/src/core/protocols/anthropicMessages/stream.interruption.test.ts b/packages/model-runtime/src/core/protocols/anthropicMessages/stream.interruption.test.ts
index 761eb98265f..27bf22ece37 100644
--- a/packages/model-runtime/src/core/protocols/anthropicMessages/stream.interruption.test.ts
+++ b/packages/model-runtime/src/core/protocols/anthropicMessages/stream.interruption.test.ts
@@ -89,7 +89,7 @@ describe('AnthropicStream interruptions', () => {
expect(chunks).toContain('event: error\n');
expect(onErrorMock).toHaveBeenCalledWith(
- expect.objectContaining({ message: 'terminated', type: 'ProviderBizError' }),
+ expect.objectContaining({ message: 'terminated', type: 'ProviderStreamInterrupted' }),
);
expect(onFinalMock).toHaveBeenCalledWith(
expect.objectContaining({ error: expect.objectContaining({ message: 'terminated' }) }),
diff --git a/packages/model-runtime/src/core/streams/protocol.disconnect.test.ts b/packages/model-runtime/src/core/streams/protocol.disconnect.test.ts
new file mode 100644
index 00000000000..507396a403f
--- /dev/null
+++ b/packages/model-runtime/src/core/streams/protocol.disconnect.test.ts
@@ -0,0 +1,63 @@
+import { AgentRuntimeErrorType } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { convertIterableToStream, createFirstErrorHandleTransformer } from './protocol';
+
+const drain = async (readable: ReadableStream<any>) => {
+ const reader = readable.getReader();
+ const chunks: any[] = [];
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ chunks.push(value);
+ }
+ return chunks;
+};
+
+describe('createFirstErrorHandleTransformer upstream disconnects', () => {
+ it('should classify an upstream socket drop as ProviderStreamInterrupted', async () => {
+ // undici's shape when the provider resets the connection mid-body
+ // (op_1794405705354).
+ async function* erroringStream() {
+ yield 'first';
+ throw new TypeError('terminated', { cause: new Error('read ECONNRESET') });
+ }
+
+ const chunks = await drain(
+ convertIterableToStream(erroringStream()).pipeThrough(
+ createFirstErrorHandleTransformer(undefined, 'lobehub'),
+ ),
+ );
+
+ expect(chunks[1].causeMessage).toBe('read ECONNRESET');
+ expect(chunks[1].errorType).toBe(AgentRuntimeErrorType.ProviderStreamInterrupted);
+ });
+
+ it('should keep ProviderBizError for other iterator failures', async () => {
+ async function* erroringStream() {
+ yield 'first';
+ throw new Error('rate limit');
+ }
+
+ const chunks = await drain(
+ convertIterableToStream(erroringStream()).pipeThrough(createFirstErrorHandleTransformer()),
+ );
+
+ expect(chunks[1].errorType).toBe(AgentRuntimeErrorType.ProviderBizError);
+ });
+
+ it('should let the provider error handler win over disconnect detection', async () => {
+ async function* erroringStream() {
+ yield 'first';
+ throw new TypeError('terminated');
+ }
+
+ const chunks = await drain(
+ convertIterableToStream(erroringStream()).pipeThrough(
+ createFirstErrorHandleTransformer(() => AgentRuntimeErrorType.InvalidProviderAPIKey),
+ ),
+ );
+
+ expect(chunks[1].errorType).toBe(AgentRuntimeErrorType.InvalidProviderAPIKey);
+ });
+});
diff --git a/packages/model-runtime/src/core/streams/protocol.ts b/packages/model-runtime/src/core/streams/protocol.ts
index d098f18d356..698a5836acd 100644
--- a/packages/model-runtime/src/core/streams/protocol.ts
+++ b/packages/model-runtime/src/core/streams/protocol.ts
@@ -408,6 +408,20 @@ export function createCallbacksTransformer(
export const FIRST_CHUNK_ERROR_KEY = '_isFirstChunkError';
+const SOCKET_DISCONNECT_PATTERN = /ECONNRESET|EPIPE|socket hang up|other side closed/i;
+
+/**
+ * The upstream connection dropped while the SDK iterator was reading the body: undici throws
+ * `TypeError: terminated` with the socket error as `cause` (e.g. `read ECONNRESET`). Nothing
+ * failed to parse, so it is a provider stream interruption, not a `ProviderBizError` that the
+ * router later rewraps as a harness `StreamChunkError`.
+ */
+const isUpstreamDisconnect = (errorData: { causeMessage?: unknown; message?: unknown }) =>
+ (typeof errorData.message === 'string' &&
+ (errorData.message === 'terminated' || SOCKET_DISCONNECT_PATTERN.test(errorData.message))) ||
+ (typeof errorData.causeMessage === 'string' &&
+ SOCKET_DISCONNECT_PATTERN.test(errorData.causeMessage));
+
export const createFirstErrorHandleTransformer = (
errorHandler?: (errorJson: any) => any,
provider?: string,
@@ -425,7 +439,11 @@ export const createFirstErrorHandleTransformer = (
controller.enqueue({
...errorData,
[FIRST_CHUNK_ERROR_KEY]: true,
- errorType: errorHandler?.(errorData) || AgentRuntimeErrorType.ProviderBizError,
+ errorType:
+ errorHandler?.(errorData) ||
+ (isUpstreamDisconnect(errorData)
+ ? AgentRuntimeErrorType.ProviderStreamInterrupted
+ : AgentRuntimeErrorType.ProviderBizError),
provider,
});
} else {