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(chat): end client runs cleanly when stopped during retry backoff (#20799)

YuTengjing55ed3885d172
diff --git a/src/store/chat/agents/transports/ClientLLMTransport.ts b/src/store/chat/agents/transports/ClientLLMTransport.ts
index 7eb9ee3901f..67b1494f485 100644
--- a/src/store/chat/agents/transports/ClientLLMTransport.ts
+++ b/src/store/chat/agents/transports/ClientLLMTransport.ts
@@ -183,9 +183,32 @@ class ClientLLMRetryPolicy implements LLMRetryPolicy {
return resolveLLMRetryBudget(provider, CLIENT_LLM_RETRY_POLICY);
}
- async waitForRetry(delayMs: number): Promise<void> {
- await sleep(delayMs);
- }
+ /**
+ * Wakes early when the operation is aborted. `callLlm` re-checks for an
+ * interrupt right after this resolves, so Stop during a backoff (up to 30s
+ * between attempts) ends the run at once instead of keeping the spinner
+ * until the delay elapses.
+ *
+ * An arrow field because `callLlm` invokes it unbound.
+ */
+ waitForRetry = async (delayMs: number): Promise<void> => {
+ const signal = this.get().operations[this.operationId]?.abortController?.signal;
+ if (!signal) {
+ await sleep(delayMs);
+ return;
+ }
+ if (signal.aborted) return;
+
+ await new Promise<void>((resolve) => {
+ const wake = () => {
+ clearTimeout(timer);
+ signal.removeEventListener('abort', wake);
+ resolve();
+ };
+ const timer = setTimeout(wake, delayMs);
+ signal.addEventListener('abort', wake, { once: true });
+ });
+ };
}
interface ClientLLMTransportOptions {
diff --git a/src/store/chat/agents/transports/ClientRuntimeStreamSink.ts b/src/store/chat/agents/transports/ClientRuntimeStreamSink.ts
index 603aeca1b40..a3064534a75 100644
--- a/src/store/chat/agents/transports/ClientRuntimeStreamSink.ts
+++ b/src/store/chat/agents/transports/ClientRuntimeStreamSink.ts
@@ -38,6 +38,10 @@ export class ClientRuntimeStreamSink implements StreamSink {
async publishError({ error }: StreamErrorInput): Promise<void> {
if (!this.session.assistantMessageId) return;
+ // `callLlm` rethrows the last attempt's provider error when Stop lands
+ // during a retry backoff. The user ended the run, so the reply must not
+ // render that error.
+ if (this.get().operations[this.operationId]?.status === 'cancelled') return;
this.get().internal_dispatchMessage(
{
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts
index 5a4fec993d9..9b92d8253ce 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts
@@ -707,6 +707,77 @@ describe('StreamingExecutor actions', () => {
streamSpy.mockRestore();
});
+ // https://github.com/lobehub/lobehub/issues/17723 — Stop during a retry
+ // backoff kept the spinner until the delay elapsed, then saved the last
+ // provider error on the reply as if the run had failed.
+ it('ends at once without a provider error when stopped during a retry backoff', async () => {
+ act(() => {
+ useChatStore.setState({ executeClientAgent: realExecAgentRuntime });
+ });
+
+ // The branded provider is excluded from client retries; use one that retries.
+ vi.spyOn(agentConfigResolver, 'resolveAgentConfig').mockReturnValue({
+ agentConfig: createMockAgentConfig({ model: 'gpt-4o-mini', provider: 'openai' }),
+ chatConfig: createMockChatConfig(),
+ isBuiltinAgent: false,
+ plugins: [],
+ });
+
+ const { result } = renderHook(() => useChatStore());
+ const userMessage = {
+ id: TEST_IDS.USER_MESSAGE_ID,
+ role: 'user',
+ content: TEST_CONTENT.USER_MESSAGE,
+ sessionId: TEST_IDS.SESSION_ID,
+ topicId: TEST_IDS.TOPIC_ID,
+ } as UIChatMessage;
+
+ seedDbMessages({ agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID }, [userMessage]);
+ const updateMessageErrorSpy = vi.spyOn(messageService, 'updateMessageError');
+ const streamSpy = spyOnClientLLMStream();
+ let streamCallCount = 0;
+ streamSpy.mockImplementation(async (_params, options) => {
+ streamCallCount++;
+ options?.onErrorHandle?.({
+ message: 'tokens per minute exceeded',
+ type: 'RateLimitExceeded',
+ } as any);
+ // The first backoff is 1s; Stop lands while it is still waiting.
+ setTimeout(() => {
+ const execOperation = Object.values(result.current.operations).find(
+ (op) => op.type === 'execAgentRuntime',
+ );
+ if (execOperation) result.current.cancelOperation(execOperation.id, 'user_cancelled');
+ }, 20);
+ return new Response();
+ });
+
+ const startedAt = Date.now();
+ await act(async () => {
+ await result.current.executeClientAgent({
+ context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },
+ messages: [userMessage],
+ parentMessageId: userMessage.id,
+ parentMessageType: 'user',
+ });
+ });
+
+ expect(Date.now() - startedAt).toBeLessThan(800);
+ expect(streamCallCount).toBe(1);
+ expect(
+ Object.values(result.current.operations).find((op) => op.type === 'execAgentRuntime')
+ ?.status,
+ ).toBe('cancelled');
+ expect(updateMessageErrorSpy).not.toHaveBeenCalled();
+ const assistantMessages = Object.values(result.current.messagesMap)
+ .flat()
+ .filter((message) => message.role === 'assistant');
+ expect(assistantMessages.length).toBeGreaterThan(0);
+ for (const message of assistantMessages) expect(message.error).toBeFalsy();
+
+ streamSpy.mockRestore();
+ });
+
it('should resolve aborted tools when cancelled after LLM returns tool calls', async () => {
act(() => {
useChatStore.setState({ executeClientAgent: realExecAgentRuntime });
diff --git a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
index 05bede6be3e..fb0604683de 100644
--- a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
@@ -903,7 +903,11 @@ export class StreamingExecutorActionImpl {
// Find the assistant message to update error
const currentMessages = this.#get().messagesMap[messageKey] || [];
const assistantMessage = currentMessages.findLast((m) => m.role === 'assistant');
- if (assistantMessage) {
+ // A Stop during a retry backoff surfaces as the last attempt's
+ // provider error. The user ended the run, so the reply must read
+ // as stopped, not as failed.
+ const isCancelled = this.#get().operations[operationId]?.status === 'cancelled';
+ if (assistantMessage && !isCancelled) {
await messageService.updateMessageError(assistantMessage.id, event.error, {
agentId,
groupId,