🤯 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
⚡️ perf(chat): skip redundant full-topic refetches in gateway runs (#23160)
YuTengjing2fcf22262556
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/index.toolEvents.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/index.toolEvents.test.tsindex 6f1cdeb90d5..d0d6ffd6204 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/index.toolEvents.test.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/index.toolEvents.test.ts@@ -1,6 +1,7 @@import { createAdapter } from '@lobechat/heterogeneous-agents';import { beforeEach, describe, expect, it, vi } from 'vitest';+import { messageService } from '@/services/message';import type * as WorkServiceModule from '@/services/work';import { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNotification';@@ -162,6 +163,26 @@ describe('createGatewayEventHandler — tool and step events', () => {expect(store.replaceMessages).toHaveBeenCalled();});+ it('should read the topic once more, not once per tool, when parallel tools end together', async () => {+ let releaseFirstRead: (() => void) | undefined;+ vi.mocked(messageService.getMessages).mockImplementationOnce(+ () => new Promise((resolve) => (releaseFirstRead = () => resolve([]))),+ );+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('tool_end', { isSuccess: true, toolCallId: 'call-1' }));+ await flush();+ handler(makeEvent('tool_end', { isSuccess: true, toolCallId: 'call-2' }));+ handler(makeEvent('tool_end', { isSuccess: true, toolCallId: 'call-3' }));+ handler(makeEvent('tool_end', { isSuccess: true, toolCallId: 'call-4' }));+ releaseFirstRead?.();+ await flush();++ // The in-flight read, then one read for the three that queued behind it.+ expect(messageService.getMessages).toHaveBeenCalledTimes(2);+ });+it('should dispatch onAfterCall when payload is wrapped as { parentMessageId, toolCalling } (real gateway shape)', async () => {const store = createMockStore();const handler = createHandler(store);@@ -318,6 +339,36 @@ describe('createGatewayEventHandler — tool and step events', () => {expect(store.replaceMessages).toHaveBeenCalled();});+ it('should leave execution_complete to message patches once the run sends revisions', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('step_start', { messageRevision: 0 }));+ handler(makeEvent('step_complete', { phase: 'execution_complete', reason: 'completed' }));+ await flush();++ expect(messageService.getMessages).not.toHaveBeenCalled();+ });++ it('should still read the final messages on agent_runtime_end after skipping execution_complete', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('step_start', { messageRevision: 0 }));+ handler(makeEvent('step_complete', { phase: 'execution_complete', reason: 'completed' }));+ handler(+ makeEvent('agent_runtime_end', {+ messagePatchMode: true,+ messageRevision: 1,+ reason: 'completed',+ }),+ );+ await flush();++ // Only the terminal read: the revision the run ended on is ahead of the last applied patch.+ expect(messageService.getMessages).toHaveBeenCalledTimes(1);+ });+it('should not refresh on other phases', async () => {const store = createMockStore();const handler = createHandler(store);diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/index.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/index.tsindex 8dc3e1df773..8693bf81790 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/index.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/index.ts@@ -47,6 +47,7 @@ import { resolveStepSideEvent } from '../stepSideEvent';import { insertStreamStartSeeds, streamStartOperationMetadata } from '../streamStartSeed';import type { RuntimeEndData } from './runtimeEndMessages';import { reconcileRuntimeEndMessages } from './runtimeEndMessages';+import { createTopicRefreshGate } from './topicRefreshGate';// Lazy-loaded to break the import cycle:// gateway.ts → gatewayEventHandler/index.ts → executors/index.ts (which pulls in@@ -100,11 +101,6 @@ const fetchAndReplaceMessages = async (return messages;};-const shouldSkipMessageFetch = (- event: AgentStreamEvent,- runtimeType: 'gateway' | 'hetero',-): boolean => runtimeType === 'hetero' && event.data?.skipMessageFetch === true;-const getToolId = (tool: unknown): string | undefined =>isRecord(tool) ? pickNonEmptyString(tool.id) : undefined;@@ -366,6 +362,7 @@ export const createGatewayEventHandler = (let lastMessagePatchRevision = 0;// Set even when the step_start read fails, so Stop can tell which step it landed in.let lastStepStartRevision = 0;+ const refreshGate = createTopicRefreshGate(runtimeType);const latestToolStateByCallId = new Map<string, ToolStateChunkData & { operationId: string }>();const toolStateBootstrapPromiseByCallId = new Map<string, Promise<void>>();const lastAppliedToolStateSeqByCallId = new Map<string, number>();@@ -1031,6 +1028,7 @@ export const createGatewayEventHandler = (};if (typeof data?.messageRevision === 'number') lastStepStartRevision = data.messageRevision;+ if (typeof data?.messageRevision === 'number') refreshGate.markRevisionSeen();if (typeof data?.messageRevision === 'number' &&data.messageRevision !== lastMessagePatchRevision@@ -1074,6 +1072,7 @@ export const createGatewayEventHandler = (case 'message_patch': {const patch = event.data as MessagePatchData;+ refreshGate.markRevisionSeen();if (patch.revision <= lastMessagePatchRevision) break;const current = get().dbMessagesMap[messageMapKey(context)] ?? [];@@ -1148,10 +1147,11 @@ export const createGatewayEventHandler = (completedToolStateCallIds.add(completedToolCallId);latestToolStateByCallId.delete(completedToolCallId);}+ const toolEndNeedsRefresh = refreshGate.toolEnd(event);enqueue(async () => {- const maybeRefresh = shouldSkipMessageFetch(event, runtimeType)- ? Promise.resolve()- : refreshMessagesFromDb({ skipWorks: true }).catch(console.error);+ const maybeRefresh = toolEndNeedsRefresh()+ ? refreshMessagesFromDb({ skipWorks: true }).catch(console.error)+ : Promise.resolve();const payload = unwrapToolPayload(data?.payload);const result = data?.result as{ state?: unknown; workRegistration?: unknown } | undefined;@@ -1189,7 +1189,7 @@ export const createGatewayEventHandler = (applyStepMetrics(get().updateOperationMetadata, operationId, undefined, data?.llmCalls);- // Refresh on execution_complete to ensure final step state is consistent+ // Refresh on execution_complete unless message revisions settle the runif (data?.phase === 'execution_complete') {enqueue(async () => {void emitAgentSignal({@@ -1202,7 +1202,7 @@ export const createGatewayEventHandler = (sourceId: `${operationId}:gateway:step_complete:${event.stepIndex}`,sourceType: 'client.gateway.step_complete',});- if (!shouldSkipMessageFetch(event, runtimeType)) {+ if (refreshGate.completionNeedsRefresh(event)) {await refreshMessagesFromDb({ skipWorks: true }).catch(console.error);}});diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/topicRefreshGate.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/topicRefreshGate.test.tsnew file mode 100644index 00000000000..d4f22f105ac--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/topicRefreshGate.test.ts@@ -0,0 +1,36 @@+import { describe, expect, it } from 'vitest';++import { makeEvent } from '../testUtils';+import { createTopicRefreshGate } from './topicRefreshGate';++const toolEnd = makeEvent('tool_end', { isSuccess: true });+const skippedToolEnd = makeEvent('tool_end', { isSuccess: true, skipMessageFetch: true });+const completion = makeEvent('step_complete', { phase: 'execution_complete' });++describe('createTopicRefreshGate', () => {+ it('keeps only the newest queued tool_end read', () => {+ const gate = createTopicRefreshGate('gateway');+ const first = gate.toolEnd(toolEnd);+ const second = gate.toolEnd(toolEnd);++ expect(first()).toBe(false);+ expect(second()).toBe(true);+ });++ it('does not let a hetero tool_end that skips its fetch supersede an earlier read', () => {+ const gate = createTopicRefreshGate('hetero');+ const read = gate.toolEnd(toolEnd);+ const skipped = gate.toolEnd(skippedToolEnd);++ expect(skipped()).toBe(false);+ expect(read()).toBe(true);+ });++ it('needs the execution_complete read until a message revision arrives', () => {+ const gate = createTopicRefreshGate('gateway');+ expect(gate.completionNeedsRefresh(completion)).toBe(true);++ gate.markRevisionSeen();+ expect(gate.completionNeedsRefresh(completion)).toBe(false);+ });+});diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/topicRefreshGate.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/topicRefreshGate.tsnew file mode 100644index 00000000000..7e10842bd0f--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/topicRefreshGate.ts@@ -0,0 +1,42 @@+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';++type RuntimeType = 'gateway' | 'hetero';++/** A hetero event that already carries its result and asks for no refetch. */+const shouldSkipMessageFetch = (event: AgentStreamEvent, runtimeType: RuntimeType): boolean =>+ runtimeType === 'hetero' && event.data?.skipMessageFetch === true;++/**+ * Decides which gateway events still need a full-topic read (`getMessages`).+ * Every read returns the whole topic, so a read that a later event already+ * covers is skipped.+ */+export const createTopicRefreshGate = (runtimeType: RuntimeType) => {+ let revisionSeen = false;+ let latestToolEnd = 0;++ return {+ /**+ * A run whose server sends message revisions (`step_start.messageRevision`,+ * `message_patch`) settles without this read: the terminal step's patch+ * follows `execution_complete`, and `agent_runtime_end` refetches when its+ * revision is ahead of the last applied patch.+ */+ completionNeedsRefresh: (event: AgentStreamEvent) =>+ !revisionSeen && !shouldSkipMessageFetch(event, runtimeType),+ markRevisionSeen: () => {+ revisionSeen = true;+ },+ /**+ * Register a `tool_end` and return whether its queued read should still run+ * when its turn comes. Parallel tools of one step end in a burst: a read a+ * later `tool_end` supersedes is skipped, because that later read runs right+ * after it and returns a list at least as new.+ */+ toolEnd: (event: AgentStreamEvent): (() => boolean) => {+ if (shouldSkipMessageFetch(event, runtimeType)) return () => false;+ const ticket = ++latestToolEnd;+ return () => ticket === latestToolEnd;+ },+ };+};