🤯 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(agent): read the topic once per inline step (#23144)
YuTengjingb110a43d3e24
diff --git a/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.ts b/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.tsindex 2e807244be6..965e2d4557c 100644--- a/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.ts+++ b/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.ts@@ -683,12 +683,44 @@ describe('runStep inline step loop', () => {expect(res.status).toBe(200);expect(mockExecuteStep).toHaveBeenCalledTimes(1);- expect(mockScheduleContinuation).toHaveBeenCalledWith(pending);+ expect(mockScheduleContinuation).toHaveBeenCalledWith(pending, undefined);expect(getCaptures()[0].body).toMatchObject({ nextStepScheduled: true, nextStepIndex: 3 });expect(mockReleaseOperationLock).toHaveBeenCalledWith('op-1', 'op-1:owner');nowSpy.mockRestore();});+ it("carries each step's deferred message patch to whoever publishes it", async () => {+ // Step 3's entry read completes step 2's patch. Once the budget is spent,+ // the queue hand-back publishes step 3's, since no entry read here will.+ let clock = Date.now();+ const nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => clock);+ const patchOf = (stepIndex: number) => ({+ before: [],+ scopeKey: 'tpc_1',+ state: {},+ stepIndex,+ });++ mockExecuteStep+ .mockResolvedValueOnce({+ ...runningStepResult(continuationFor(3)),+ deferredMessagePatch: patchOf(2),+ })+ .mockImplementationOnce(async () => {+ clock += 600_000;+ return { ...runningStepResult(continuationFor(4)), deferredMessagePatch: patchOf(3) };+ });++ const { ctx } = buildContext({ body: validBody });+ await runStep(ctx);++ expect(mockExecuteStep).toHaveBeenCalledTimes(2);+ expect(mockExecuteStep.mock.calls[0][0].deferredMessagePatch).toBeUndefined();+ expect(mockExecuteStep.mock.calls[1][0].deferredMessagePatch).toEqual(patchOf(2));+ expect(mockScheduleContinuation).toHaveBeenCalledWith(continuationFor(4), patchOf(3));+ nowSpy.mockRestore();+ });+it('releases the lock when a step throws', async () => {// Without this the operation stays locked for the full TTL and every// redelivery bounces off it.@@ -812,7 +844,7 @@ describe('runStep inline step loop', () => {expect(res.status).toBe(200);expect(mockExecuteStep).toHaveBeenCalledTimes(1);- expect(mockScheduleContinuation).toHaveBeenCalledWith(pending);+ expect(mockScheduleContinuation).toHaveBeenCalledWith(pending, undefined);expect(getCaptures()[0].body).toMatchObject({inlinedSteps: 0,nextStepIndex: 3,diff --git a/apps/server/src/router-hono/agent/handlers/runStep.ts b/apps/server/src/router-hono/agent/handlers/runStep.tsindex fff32691cee..f6133d76390 100644--- a/apps/server/src/router-hono/agent/handlers/runStep.ts+++ b/apps/server/src/router-hono/agent/handlers/runStep.ts@@ -424,6 +424,9 @@ export async function runStep(c: Context): Promise<Response> {result = await aiAgentService.executeStep({context: next.context,+ // The previous step's message patch, which this step's entry read+ // completes. It never leaves this invocation.+ deferredMessagePatch: result.deferredMessagePatch,inlineContinuation: true,operationId,retainStepLock: true,@@ -442,7 +445,10 @@ export async function runStep(c: Context): Promise<Response> {// Whatever is still pending goes back to the queue so the operation// resumes in a fresh invocation.if (pendingContinuation) {- await aiAgentService.scheduleContinuation(pendingContinuation);+ await aiAgentService.scheduleContinuation(+ pendingContinuation,+ result.deferredMessagePatch,+ );result = { ...result, nextStepScheduled: true };pendingContinuation = undefined;}diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/executeStep.messagePatch.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/executeStep.messagePatch.test.tsnew file mode 100644index 00000000000..0a627000000--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/executeStep.messagePatch.test.ts@@ -0,0 +1,460 @@+/**+ * @vitest-environment node+ *+ * Protocol v2 message patches across an inline step loop: a step that continues+ * in the same invocation leaves its patch to the next step's entry read instead+ * of reading the conversation again when it ends.+ */+import type { UIChatMessage } from '@lobechat/types';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { AgentExecutionParams, DeferredMessagePatch } from '../../types';+import { AgentRuntimeService } from '..';+import { stepMessagesScopeKey } from '../executeStep/messagePatch';+import { stubRunningDurableOperation } from './testUtils';++vi.mock('@lobechat/model-runtime', (...args) =>+ import('./testUtils').then((m) =>+ (m.lobechatModelRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@lobechat/ssrf-safe-fetch', () => ({ ssrfSafeFetch: vi.fn() }));++vi.mock('@/libs/trusted-client', (...args) =>+ import('./testUtils').then((m) => (m.libsTrustedClientModule as (...a: any[]) => any)(...args)),+);++vi.mock('@/server/services/file', (...args) =>+ import('./testUtils').then((m) => (m.serverServicesFileModule as (...a: any[]) => any)(...args)),+);++vi.mock('@/database/models/message', (...args) =>+ import('./testUtils').then((m) =>+ (m.databaseModelsMessageModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/database/models/agent', (...args) =>+ import('./testUtils').then((m) => (m.databaseModelsAgentModule as (...a: any[]) => any)(...args)),+);++vi.mock('@/database/models/plugin', (...args) =>+ import('./testUtils').then((m) =>+ (m.databaseModelsPluginModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/server/modules/ModelRuntime', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesModelRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/server/services/search', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverServicesSearchModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/server/modules/AgentRuntime/factory', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeFactoryModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/server/modules/AgentRuntime/redis', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeRedisModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/server/modules/AgentRuntime', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@lobechat/agent-runtime', (...args) =>+ import('./testUtils').then((m) =>+ (m.lobechatAgentRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/server/services/queue', (...args) =>+ import('./testUtils').then((m) => (m.serverServicesQueueModule as (...a: any[]) => any)(...args)),+);++vi.mock('@/server/modules/Mecha', (...args) =>+ import('./testUtils').then((m) => (m.serverModulesMechaModule as (...a: any[]) => any)(...args)),+);++vi.mock('model-bank', (...args) =>+ import('./testUtils').then((m) => (m.modelBankModule as (...a: any[]) => any)(...args)),+);++const OPERATION_ID = 'op-message-patch';+const USER_ID = 'user-1';++const context = {+ payload: { isFirstMessage: false, message: { content: 'test' }, sessionId: OPERATION_ID },+ phase: 'user_input',+ session: { messageCount: 1, sessionId: OPERATION_ID, status: 'running', stepCount: 1 },+} as AgentExecutionParams['context'];++const row = (id: string, content: string, role: UIChatMessage['role'] = 'user') =>+ ({ content, createdAt: 1, id, role, updatedAt: 1 }) as UIChatMessage;++const runState = (overrides: Record<string, unknown> = {}) => ({+ events: [],+ // Protocol 2: the client reconciles through `message_patch` revisions.+ host: { clientProtocol: 2 },+ lastModified: new Date().toISOString(),+ messages: [],+ operationId: OPERATION_ID,+ origin: { agentId: 'agt_1', topicId: 'tpc_1' },+ status: 'running',+ stepCount: 1,+ ...overrides,+});++/** What step 1 leaves behind when it continues inline. */+const pendingPatch = (state = runState({ stepCount: 2 })): DeferredMessagePatch => ({+ before: [row('u1', 'question')],+ scopeKey: stepMessagesScopeKey(state as any),+ state: state as any,+ stepIndex: 1,+});++const spyAll = (target: any) => {+ for (const key of Object.getOwnPropertyNames(Object.getPrototypeOf(target))) {+ if (key !== 'constructor' && typeof target[key] === 'function') vi.spyOn(target, key);+ }+};++const buildService = (options?: ConstructorParameters<typeof AgentRuntimeService>[2]) => {+ const service = new AgentRuntimeService({} as any, USER_ID, options);+ const coordinator = (service as any).coordinator;+ const streamManager = (service as any).streamManager;+ const queueService = (service as any).queueService;+ spyAll(coordinator);+ spyAll(streamManager);+ coordinator.getOperationMetadata.mockResolvedValue({ status: 'running', userId: USER_ID });+ coordinator.saveInlineResume.mockResolvedValue(true);++ // The topic read every step starts with.+ const query = vi.fn().mockResolvedValue([]);+ (service as any).messageModel.query = query;+ vi.spyOn((service as any).messageService, 'prepareUiMessages').mockImplementation(+ async (messages: any) => messages.map((message: UIChatMessage) => ({ ...message })),+ );+ // The read a step makes when it ends.+ const queryUiMessages = vi.spyOn(service, 'queryUiMessages');++ const step = vi.fn().mockImplementation(async (input: any) => ({+ events: [],+ newState: { ...input, stepCount: input.stepCount + 1 },+ nextContext: context,+ }));+ vi.spyOn(service as any, 'createAgentRuntime').mockResolvedValue({ runtime: { step } });++ const events = () =>+ streamManager.publishStreamEvent.mock.calls.map(([, event]: any[]) => event) as any[];+ const indexOf = (type: string, stepIndex: number) =>+ events().findIndex((event) => event.type === type && event.stepIndex === stepIndex);++ return {+ coordinator,+ events,+ indexOf,+ query,+ queryUiMessages,+ queueService,+ service,+ step,+ streamManager,+ };+};++const inlineStep = (stepIndex: number, extra: Partial<AgentExecutionParams> = {}) => ({+ context,+ inlineContinuation: true,+ operationId: OPERATION_ID,+ stepIndex,+ ...extra,+});++describe('AgentRuntimeService.executeStep - message patches across inline steps', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ stubRunningDurableOperation();+ process.env.AGENT_RUNTIME_BASE_URL = 'http://localhost:3010';+ });++ afterEach(() => {+ delete process.env.AGENT_RUNTIME_BASE_URL;+ });++ it("completes a continuing step's patch from the next step's entry read", async () => {+ const { coordinator, events, indexOf, query, queryUiMessages, queueService, service, step } =+ buildService();+ coordinator.loadAgentState.mockResolvedValueOnce(runState());+ query.mockResolvedValueOnce([row('u1', 'question')]);++ const first = await service.executeStep(inlineStep(1));++ expect(first.continuation?.stepIndex).toBe(2);+ expect(first.deferredMessagePatch).toMatchObject({+ before: [row('u1', 'question')],+ stepIndex: 1,+ });+ expect(events().some((event) => event.type === 'message_patch')).toBe(false);+ expect(queueService.scheduleMessage).not.toHaveBeenCalled();++ // Written between the two steps: the user edits the question and a task+ // reports back into the topic.+ coordinator.loadAgentState.mockResolvedValueOnce(runState({ stepCount: 2 }));+ query.mockResolvedValueOnce([+ row('u1', 'edited question'),+ row('cb1', 'task finished', 'taskCallback'),+ ]);++ const second = await service.executeStep(+ inlineStep(2, { deferredMessagePatch: first.deferredMessagePatch }),+ );++ // Step 1's patch goes out ahead of step 2's `step_start`, which the client+ // checks against the last revision it applied.+ const patchAt = indexOf('message_patch', 1);+ expect(patchAt).toBeGreaterThan(-1);+ expect(patchAt).toBeLessThan(indexOf('step_start', 2));+ expect(events()[patchAt].data).toMatchObject({+ deletes: [],+ revision: 2,+ upserts: [+ { afterId: null, message: { content: 'edited question', id: 'u1' } },+ { afterId: 'u1', message: { content: 'task finished', id: 'cb1' } },+ ],+ });+ // One topic read per step, and none when either step ended.+ expect(query).toHaveBeenCalledTimes(2);+ expect(queryUiMessages).not.toHaveBeenCalled();+ // The model works from the same read the client was sent.+ expect(JSON.stringify(step.mock.calls[1][0].messages)).toContain('edited question');+ expect(second.deferredMessagePatch?.stepIndex).toBe(2);+ });++ it('reads the conversation itself when the next step reads another one', async () => {+ const { coordinator, events, indexOf, query, queryUiMessages, service } = buildService();+ const patch = pendingPatch();+ coordinator.loadAgentState.mockResolvedValueOnce(+ runState({ origin: { agentId: 'agt_1', topicId: 'tpc_other' }, stepCount: 2 }),+ );+ query.mockResolvedValueOnce([row('x1', 'another topic')]);+ queryUiMessages.mockResolvedValueOnce([+ row('u1', 'question'),+ row('a1', 'answer', 'assistant'),+ ]);++ await service.executeStep(inlineStep(2, { deferredMessagePatch: patch }));++ expect(queryUiMessages).toHaveBeenCalledWith(patch.state, { skipWorks: true });+ const patchAt = indexOf('message_patch', 1);+ expect(patchAt).toBeLessThan(indexOf('step_start', 2));+ expect(events()[patchAt].data).toMatchObject({+ deletes: [],+ upserts: [{ afterId: 'u1', message: { id: 'a1' } }],+ });+ });++ it('publishes the patch before queueing when the next step cannot stay inline', async () => {+ const {+ coordinator,+ events,+ indexOf,+ query,+ queryUiMessages,+ queueService,+ service,+ streamManager,+ } = buildService();+ coordinator.loadAgentState.mockResolvedValueOnce(runState());+ coordinator.saveInlineResume.mockResolvedValue(false);+ query.mockResolvedValueOnce([row('u1', 'question')]);+ queryUiMessages.mockResolvedValueOnce([+ row('u1', 'question'),+ row('a1', 'answer', 'assistant'),+ ]);++ const result = await service.executeStep(inlineStep(1));++ expect(result.nextStepScheduled).toBe(true);+ expect(result.deferredMessagePatch).toBeUndefined();+ expect(queryUiMessages).toHaveBeenCalledWith(expect.objectContaining({ stepCount: 2 }), {+ skipWorks: true,+ });+ const patchAt = indexOf('message_patch', 1);+ expect(events()[patchAt].data).toMatchObject({+ upserts: [{ afterId: 'u1', message: { id: 'a1' } }],+ });+ // Another invocation may start the queued step at once.+ expect(streamManager.publishStreamEvent.mock.invocationCallOrder[patchAt]).toBeLessThan(+ queueService.scheduleMessage.mock.invocationCallOrder[0],+ );+ });++ it('publishes a handed-on patch ahead of the failure when the next step throws', async () => {+ const { coordinator, events, queryUiMessages, service } = buildService();+ vi.spyOn(console, 'error').mockImplementation(() => {});+ coordinator.loadAgentState.mockRejectedValueOnce(new Error('state store unavailable'));+ queryUiMessages.mockResolvedValueOnce([+ row('u1', 'question'),+ row('a1', 'answer', 'assistant'),+ ]);++ await expect(+ service.executeStep(inlineStep(2, { deferredMessagePatch: pendingPatch() })),+ ).rejects.toThrow('state store unavailable');++ const types = events().map((event) => event.type);+ expect(types[0]).toBe('message_patch');+ expect(types).toContain('error');+ });++ it('publishes and drains a handed-on patch when another worker holds the step', async () => {+ const { coordinator, events, queryUiMessages, service, streamManager } = buildService();+ coordinator.tryClaimStep.mockResolvedValue(false);+ // This exit skips the step's `finally`, the usual drain point.+ streamManager.drainPushes = vi.fn().mockResolvedValue(undefined);+ queryUiMessages.mockResolvedValueOnce([+ row('u1', 'question'),+ row('a1', 'answer', 'assistant'),+ ]);++ await service.executeStep(inlineStep(2, { deferredMessagePatch: pendingPatch() }));++ const patchAt = events().findIndex((event) => event.type === 'message_patch');+ expect(patchAt).toBeGreaterThan(-1);+ expect(streamManager.publishStreamEvent.mock.invocationCallOrder[patchAt]).toBeLessThan(+ streamManager.drainPushes.mock.invocationCallOrder[0],+ );+ });++ it('publishes a handed-on patch before a pending init writes the turn', async () => {+ const runDeferredInit = vi.fn().mockRejectedValue(new Error('init failed'));+ const { coordinator, queryUiMessages, service } = buildService({+ delegate: { runDeferredInit } as any,+ });+ vi.spyOn(console, 'error').mockImplementation(() => {});+ coordinator.loadAgentState.mockResolvedValue(+ runState({ request: { approvedToolEntries: [], selectedToolIds: [] }, stepCount: 2 }),+ );+ queryUiMessages.mockResolvedValueOnce([row('u1', 'question')]);++ await expect(+ service.executeStep(inlineStep(2, { deferredMessagePatch: pendingPatch() })),+ ).rejects.toThrow('init failed');++ expect(runDeferredInit).toHaveBeenCalled();+ expect(queryUiMessages.mock.invocationCallOrder[0]).toBeLessThan(+ runDeferredInit.mock.invocationCallOrder[0],+ );+ });++ it.each([+ {+ name: 'a step that finishes the run',+ params: inlineStep(1),+ status: 'done',+ },+ {+ name: 'a continuing step that is not inlined',+ params: { context, operationId: OPERATION_ID, stepIndex: 1 },+ status: 'running',+ },+ ])('still reads the conversation when $name ends', async ({ params, status }) => {+ const { coordinator, events, indexOf, query, queryUiMessages, service, step } = buildService();+ coordinator.loadAgentState.mockResolvedValueOnce(runState());+ query.mockResolvedValueOnce([row('u1', 'question')]);+ queryUiMessages.mockResolvedValueOnce([+ row('u1', 'question'),+ row('a1', 'answer', 'assistant'),+ ]);+ step.mockImplementationOnce(async (input: any) => ({+ events: [],+ newState: { ...input, status, stepCount: 2 },+ nextContext: status === 'running' ? context : undefined,+ }));++ const result = await service.executeStep(params);++ expect(result.deferredMessagePatch).toBeUndefined();+ expect(queryUiMessages).toHaveBeenCalledTimes(1);+ expect(events()[indexOf('message_patch', 1)].data).toMatchObject({+ upserts: [{ afterId: 'u1', message: { id: 'a1' } }],+ });+ });++ it('leaves a client without message patches untouched', async () => {+ const { coordinator, events, query, queryUiMessages, service } = buildService();+ coordinator.loadAgentState.mockResolvedValueOnce(runState({ host: {} }));+ query.mockResolvedValueOnce([row('u1', 'question')]);++ const result = await service.executeStep(inlineStep(1));++ expect(result.continuation?.stepIndex).toBe(2);+ expect(result.deferredMessagePatch).toBeUndefined();+ expect(queryUiMessages).not.toHaveBeenCalled();+ expect(events().some((event) => event.type === 'message_patch')).toBe(false);+ });+});++describe('AgentRuntimeService.scheduleContinuation - handed-back message patch', () => {+ const continuation = {+ context,+ delay: 50,+ operationId: OPERATION_ID,+ priority: 'normal' as const,+ stepIndex: 2,+ };++ beforeEach(() => {+ vi.clearAllMocks();+ process.env.AGENT_RUNTIME_BASE_URL = 'http://localhost:3010';+ });++ afterEach(() => {+ delete process.env.AGENT_RUNTIME_BASE_URL;+ });++ it('publishes the patch before the step is queued', async () => {+ const { events, indexOf, queryUiMessages, queueService, service, streamManager } =+ buildService();+ queryUiMessages.mockResolvedValueOnce([+ row('u1', 'question'),+ row('a1', 'answer', 'assistant'),+ ]);++ await service.scheduleContinuation(continuation, pendingPatch());++ const patchAt = indexOf('message_patch', 1);+ expect(events()[patchAt].data).toMatchObject({+ revision: 2,+ upserts: [{ afterId: 'u1', message: { id: 'a1' } }],+ });+ expect(streamManager.publishStreamEvent.mock.invocationCallOrder[patchAt]).toBeLessThan(+ queueService.scheduleMessage.mock.invocationCallOrder[0],+ );+ });++ it('still queues the step when the patch cannot be read', async () => {+ const { events, queryUiMessages, queueService, service } = buildService();+ vi.spyOn(console, 'error').mockImplementation(() => {});+ queryUiMessages.mockRejectedValueOnce(new Error('database unavailable'));++ await service.scheduleContinuation(continuation, pendingPatch());++ expect(events().some((event) => event.type === 'message_patch')).toBe(false);+ expect(queueService.scheduleMessage).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/continuation.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/continuation.tsindex 42c7c0ef3d2..82d655936cf 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/continuation.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/continuation.ts@@ -26,11 +26,14 @@ export type StepContinuationDeps = Pick<export async function scheduleNextStep(deps: StepContinuationDeps,{+ beforeQueue,inlineContinuation,operationId,stepIndex,stepResult,}: {+ /** Runs before the next step is queued, which lets another invocation start it. */+ beforeQueue?: () => Promise<void>;inlineContinuation: boolean;operationId: string;stepIndex: number;@@ -104,6 +107,7 @@ export async function scheduleNextStep(// partial from the store — it has to see this step. The gateway// pushes this invocation issued have to land for the same reason:// nothing carries them once it stops running.+ await beforeQueue?.();await deps.traceRecorder.flushPartial();await deps.streamManager.drainPushes?.(operationId);await deps.queueService.scheduleMessage({ ...next, endpoint: `${deps.baseURL}/run` });diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.tsindex 70cc9bd3dbf..4ef94694975 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts@@ -7,6 +7,7 @@ import {invokeAgentSpanName,tracer as agentRuntimeTracer,} from '@lobechat/observability-otel/modules/agent-runtime';+import type { UIChatMessage } from '@lobechat/types';import debug from 'debug';import { LocalQueueServiceImpl } from '@/server/services/queue/impls';@@ -16,6 +17,7 @@ import {type AgentExecutionParams,type AgentExecutionResult,type AgentStepContinuation,+ type DeferredMessagePatch,} from '../../types';import { STEP_LOCK_TTL_SECONDS } from '../constants';import { StepOwnershipLostError } from '../executionErrors';@@ -35,6 +37,7 @@ import {skipUnrunnableStep,} from './guards';import { dispatchAfterStepHooks, dispatchBeforeStepHooks, persistStepTracking } from './hooks';+import { publishDeferredMessagePatch, stepMessagesScopeKey } from './messagePatch';import { prepareStepInput } from './prepare';import { startRunSlotLease } from './runSlotLease';import { runAndReconcileStep, saveAndPublishStep } from './runStep';@@ -133,8 +136,32 @@ export async function executeStep(stepLockOwner: providedStepLockOwner,} = params;+ // The message patch still owed to the client: the previous inline step's on+ // entry, this step's own once it defers one. Each exit that does not hand it+ // on publishes it, reading the topic for its "after" side when no entry read+ // is there to serve.+ let pendingMessagePatch: DeferredMessagePatch | undefined = params.deferredMessagePatch;+ const flushPendingMessagePatch = async (entry?: {+ scopeKey: string;+ uiMessages?: UIChatMessage[];+ }) => {+ const patch = pendingMessagePatch;+ pendingMessagePatch = undefined;+ if (patch) await publishDeferredMessagePatch(deps, operationId, patch, entry);+ };+ // For the exits ahead of the step's `finally`, which is what drains the+ // gateway pushes otherwise: an undrained push can be lost with the invocation.+ const settlePendingMessagePatch = async () => {+ if (!pendingMessagePatch) return;+ await flushPendingMessagePatch();+ await deps.streamManager.drainPushes?.(operationId);+ };+const lockFree = await runLockFreeDelivery(deps, params);- if (lockFree) return lockFree;+ if (lockFree) {+ await settlePendingMessagePatch();+ return lockFree;+ }// ===== Distributed lock: prevent duplicate execution from QStash retries =====const stepLockOwner = providedStepLockOwner ?? createStepLockOwner(operationId, stepIndex);@@ -144,7 +171,10 @@ export async function executeStep(STEP_LOCK_TTL_SECONDS,stepLockOwner,);- if (!claimed) return handleStepLockConflict(deps, params);+ if (!claimed) {+ await settlePendingMessagePatch();+ return handleStepLockConflict(deps, params);+ }await deps.agentOperationModel.touchRunning(operationId).catch((error) => {log('[%s][%d] Operation lease refresh failed: %O', operationId, stepIndex, error);@@ -206,6 +236,9 @@ export async function executeStep(// that init here, after the step claim and before anything is published.let deferredInitContext: AgentRuntimeContext | undefined;if (agentState.request) {+ // The init writes this turn's messages and may end the step; neither+ // belongs to the previous step's patch.+ await flushPendingMessagePatch();const init = await runPendingInit({abortShareRun: (state) => deps.buildShareAbortResult(operationId, state),@@ -238,6 +271,13 @@ export async function executeStep(const gatewayMessagePatchEnabled = deps.usesGatewayMessagePatch(agentState);const { uiMessages: stepStartUiMessages, messages: stepEntryMessages } =await deps.queryStepEntryMessages(agentState);+ // The previous step's patch ends at this read. It goes out first: the+ // client checks `step_start`'s `messageRevision` against the last patch+ // it applied, and a gap makes it refetch the whole topic.+ await flushPendingMessagePatch({+ scopeKey: stepMessagesScopeKey(agentState),+ uiMessages: stepStartUiMessages,+ });await deps.streamManager.publishStreamEvent(operationId, {data: {...(gatewayMessagePatchEnabled@@ -343,9 +383,10 @@ export async function executeStep(};}- const { content, shouldContinue, stepPresentationData, toolsCalling } =+ const { content, deferredMessagePatch, shouldContinue, stepPresentationData, toolsCalling } =await saveAndPublishStep(deps, {assertOwnership,+ deferMessagePatch: inlineContinuation && !!deps.queueService,gatewayMessagePatchEnabled,operationId,startAt,@@ -353,6 +394,7 @@ export async function executeStep(stepResult,stepStartUiMessages,});+ pendingMessagePatch = deferredMessagePatch;const afterStepSignalEvents = await dispatchAfterStepHooks(deps, {content,@@ -390,6 +432,8 @@ export async function executeStep(let continuation: AgentStepContinuation | undefined;if (shouldContinue && stepResult.nextContext && deps.queueService) {const scheduled = await scheduleNextStep(deps, {+ // Another invocation's `step_start` must not overtake this step's patch.+ beforeQueue: () => flushPendingMessagePatch(),inlineContinuation,operationId,stepIndex,@@ -400,6 +444,10 @@ export async function executeStep(if (scheduled.handedOffInline) handedOffInline = true;}+ // The next step runs here, so the patch goes on with it.+ const handedOnMessagePatch = continuation ? pendingMessagePatch : undefined;+ if (handedOnMessagePatch) pendingMessagePatch = undefined;+// Record final agent-level usage on the invoke_agent span. Done on every// step so partial trees (e.g. interrupted runs) still carry the// last-known token counters.@@ -417,6 +465,7 @@ export async function executeStep(return {continuation,+ ...(handedOnMessagePatch && { deferredMessagePatch: handedOnMessagePatch }),nextStepScheduled,state: stepResult.newState,stepResult,@@ -424,6 +473,8 @@ export async function executeStep(};});} catch (error) {+ // Ahead of the failure's own events, `agent_runtime_end` among them.+ await flushPendingMessagePatch();return await failStep(deps, {error,externalRetryCount,@@ -439,6 +490,9 @@ export async function executeStep(abortPoll?.stop();stopRunSlotLease?.();stopStepLockHeartbeat();+ // Any exit above that neither published nor handed the patch on, e.g. a+ // replayed intervention lifecycle.+ await flushPendingMessagePatch();// Parked runs (human input, async tools) and finished ones are read back// by a different invocation, so the partial cannot stay in memory only.// An inline hand-off keeps it: the next step runs on this recorder.diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/messagePatch.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/messagePatch.tsnew file mode 100644index 00000000000..c08d6d2b848--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/messagePatch.ts@@ -0,0 +1,88 @@+import type { AgentState } from '@lobechat/agent-runtime';+import type { UIChatMessage } from '@lobechat/types';++import { buildProjectedMessagePatch } from '../../messagePatch';+import type { DeferredMessagePatch } from '../../types';+import type { AgentRuntimeServiceContext } from '../types';++/** What this module reads off the service. */+export type StepMessagePatchDeps = Pick<+ AgentRuntimeServiceContext,+ 'queryUiMessages' | 'streamManager'+>;++/** Identifies the conversation a step reads; a patch is diffed only within one. */+export const stepMessagesScopeKey = (state: AgentState): string =>+ JSON.stringify([+ state.origin?.agentId ?? null,+ state.origin?.topicId ?? null,+ state.origin?.groupId ?? null,+ state.origin?.threadId ?? null,+ ]);++/**+ * Publish a step's protocol v2 patch: what changed in the conversation between+ * the step's entry read (`before`) and `after`. Projected, because this runs+ * only for a client that asked for protocol 2, which renders tool view models+ * and can fetch a stored payload back. The model-facing lists are read+ * elsewhere, straight off `MessageModel`, and stay whole.+ */+export async function publishStepMessagePatch(+ deps: StepMessagePatchDeps,+ {+ after,+ before,+ operationId,+ stepIndex,+ }: {+ after: UIChatMessage[];+ before: UIChatMessage[];+ operationId: string;+ stepIndex: number;+ },+): Promise<void> {+ await deps.streamManager.publishStreamEvent(operationId, {+ data: buildProjectedMessagePatch(before, after, stepIndex + 1),+ stepIndex,+ type: 'message_patch',+ });+}++/**+ * Publish a patch an inline step left for later. `entry` is the next step's+ * entry read, which serves as the "after" side when it covers the same+ * conversation; otherwise the conversation is read here, the way the step+ * would have read it when it ended.+ *+ * Best effort: a patch that never arrives costs the client one refetch, since+ * the next revision it sees (`step_start`, the next patch, `agent_runtime_end`)+ * no longer follows the last patch it applied. That must not fail the step.+ */+export async function publishDeferredMessagePatch(+ deps: StepMessagePatchDeps,+ operationId: string,+ patch: DeferredMessagePatch,+ entry?: { scopeKey: string; uiMessages?: UIChatMessage[] },+): Promise<void> {+ try {+ const after =+ entry?.uiMessages && entry.scopeKey === patch.scopeKey+ ? entry.uiMessages+ : await deps.queryUiMessages(patch.state, { skipWorks: true });+ if (!after) return;++ await publishStepMessagePatch(deps, {+ after,+ before: patch.before,+ operationId,+ stepIndex: patch.stepIndex,+ });+ } catch (error) {+ console.error(+ '[%s][%d] Failed to publish the deferred message patch: %O',+ operationId,+ patch.stepIndex,+ error,+ );+ }+}diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/runStep.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/runStep.tsindex 563ef3f0965..365082d2e52 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/runStep.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/runStep.ts@@ -7,10 +7,11 @@ import { formatErrorForState } from '@/server/modules/AgentRuntime/formatErrorFoimport { isSuccessLikeCompletionReason } from '../../CompletionLifecycle';import { stepChangedCredentials } from '../../credentialFacts';import { logToolCallPc } from '../../formalObservation';-import { buildProjectedMessagePatch } from '../../messagePatch';import { buildStepPresentation, formatTokenCount } from '../../stepPresentation';+import type { DeferredMessagePatch } from '../../types';import { INTERVENTION_LIFECYCLE_CHECKPOINT_KEY } from '../constants';import type { AgentRuntimeServiceContext, InterventionLifecycleCheckpoint } from '../types';+import { publishStepMessagePatch, stepMessagesScopeKey } from './messagePatch';import type { PreparedStepInput } from './prepare';const log = debug('lobe-server:agent-runtime-service');@@ -157,6 +158,7 @@ export async function saveAndPublishStep(deps: StepRunStepDeps,{assertOwnership,+ deferMessagePatch,gatewayMessagePatchEnabled,operationId,startAt,@@ -166,6 +168,11 @@ export async function saveAndPublishStep(}: {/** Throws once this attempt no longer owns the operation; absent when commits are not fenced. */assertOwnership?: () => Promise<void>;+ /**+ * The next step may run in this invocation, so a continuing step leaves its+ * message patch to that step's entry read instead of reading the topic.+ */+ deferMessagePatch: boolean;gatewayMessagePatchEnabled: boolean;operationId: string;startAt: number;@@ -177,6 +184,8 @@ export async function saveAndPublishStep(},): Promise<{content: StepPresentation['content'];+ /** This step's patch, left unpublished; set only when `deferMessagePatch` applied. */+ deferredMessagePatch?: DeferredMessagePatch;shouldContinue: boolean;stepPresentationData: StepPresentation;toolsCalling: StepPresentation['toolsCalling'];@@ -221,20 +230,32 @@ export async function saveAndPublishStep(// patch. Publish before saveStepResult because a terminal save emits// agent_runtime_end immediately, and the client must apply the patch// before completing the run.+ //+ // A step that continues in this invocation skips that read: the next step+ // reads the topic at its entry anyway, a moment later, and its read becomes+ // this patch's "after" side. It is the fresher of the two, so anything+ // written in between reaches the client too.+ let deferredMessagePatch: DeferredMessagePatch | undefined;if (gatewayMessagePatchEnabled && stepStartUiMessages) {- const settledUiMessages = await deps.queryUiMessages(stepResult.newState, {- skipWorks: shouldContinue,- });- if (settledUiMessages) {- // Projected: this branch runs only for a client that asked for- // protocol 2, which renders tool view models and can fetch a stored- // payload back. The model-facing lists are read elsewhere, straight- // off `MessageModel`, and stay whole.- await deps.streamManager.publishStreamEvent(operationId, {- data: buildProjectedMessagePatch(stepStartUiMessages, settledUiMessages, stepIndex + 1),+ if (shouldContinue && deferMessagePatch) {+ deferredMessagePatch = {+ before: stepStartUiMessages,+ scopeKey: stepMessagesScopeKey(stepResult.newState),+ state: stepResult.newState,stepIndex,- type: 'message_patch',+ };+ } else {+ const settledUiMessages = await deps.queryUiMessages(stepResult.newState, {+ skipWorks: shouldContinue,});+ if (settledUiMessages) {+ await publishStepMessagePatch(deps, {+ after: settledUiMessages,+ before: stepStartUiMessages,+ operationId,+ stepIndex,+ });+ }}}@@ -302,5 +323,5 @@ export async function saveAndPublishStep(const toolsCalling = stepPresentationData.toolsCalling;const content = stepPresentationData.content;- return { content, shouldContinue, stepPresentationData, toolsCalling };+ return { content, deferredMessagePatch, shouldContinue, stepPresentationData, toolsCalling };}diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/operationControl.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/operationControl.tsindex 3242a68dd6d..ecd11e95e11 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/operationControl.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/operationControl.ts@@ -14,6 +14,7 @@ import {import { steerQueueScopeOf, subAgentSteerQueueScopeOf } from '../steerQueueScope';import {type AgentStepContinuation,+ type DeferredMessagePatch,type OperationStatusResult,type StartExecutionParams,type StartExecutionResult,@@ -24,6 +25,7 @@ import {STEP_LOCK_HEARTBEAT_MS,STEP_LOCK_TTL_SECONDS,} from './constants';+import { publishDeferredMessagePatch } from './executeStep/messagePatch';import type { AgentRuntimeServiceContext } from './types';const log = debug('lobe-server:agent-runtime-service');@@ -38,6 +40,7 @@ export type OperationControlDeps = Pick<| 'delegate'| 'endExpiredClientLlmWait'| 'messageModel'+ | 'queryUiMessages'| 'queueService'| 'serverDB'| 'streamManager'@@ -416,6 +419,8 @@ export async function controlCompletedToolResult(export async function scheduleContinuation(deps: OperationControlDeps,continuation: AgentStepContinuation,+ /** The handing-back step's patch; published first, since no entry read here will. */+ deferredMessagePatch?: DeferredMessagePatch,): Promise<void> {if (!deps.queueService) {throw new Error(@@ -423,6 +428,10 @@ export async function scheduleContinuation();}+ if (deferredMessagePatch) {+ await publishDeferredMessagePatch(deps, continuation.operationId, deferredMessagePatch);+ }+// The steps this invocation inlined are still only in memory — the// invocation that picks the run up reads the partial from the store, and// the gateway pushes it issued have nothing else to carry them.diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.tsindex b111e80dc04..29ff0130811 100644--- a/apps/server/src/services/agentRuntime/types.ts+++ b/apps/server/src/services/agentRuntime/types.ts@@ -21,6 +21,7 @@ import type {EvalToolForwardingConfig,ExpertiseContextSnapshot,FrozenCredentialFacts,+ UIChatMessage,UserInterventionConfig,} from '@lobechat/types';import type { SearchDecision } from 'model-bank';@@ -143,6 +144,23 @@ export type StepCompletionReason =// ==================== Execution Params ====================+/**+ * The protocol v2 message patch of a step that continues inline, left+ * unpublished so the next step's entry read can be its "after" side. Lives+ * only in the invocation's memory; whoever ends up holding it must publish it+ * before the client hears of the next step.+ */+export interface DeferredMessagePatch {+ /** The step's entry read: the patch's "before" side. */+ before: UIChatMessage[];+ /** Conversation the step read; see `stepMessagesScopeKey`. */+ scopeKey: string;+ /** State the step ended with, to read the "after" side when no entry read takes over. */+ state: AgentState;+ /** Step the patch belongs to. */+ stepIndex: number;+}+export interface AgentExecutionParams {approvedToolCall?: any;/**@@ -158,6 +176,11 @@ export interface AgentExecutionParams {*/clientLlmWaitExpired?: string;context?: AgentRuntimeContext;+ /**+ * The previous inline step's message patch. This step publishes it from its+ * own entry read, before `step_start`. Set only by the inline step loop.+ */+ deferredMessagePatch?: DeferredMessagePatch;externalRetryCount?: number;/*** Finish (rather than resume) a `waiting_for_async_tool` supervisor op after@@ -263,6 +286,12 @@ export interface AgentExecutionResult {* inline loop can simply stop when it is missing.*/continuation?: AgentStepContinuation;+ /**+ * This step's unpublished message patch, present only alongside+ * `continuation`. The inline loop passes it to the next step, or to+ * `scheduleContinuation` when it hands the step back to the queue.+ */+ deferredMessagePatch?: DeferredMessagePatch;/*** When true, the step was already being executed by another instance (lock conflict).* Stale duplicates are handled before returning this; callers should keepdiff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex 40a322322a6..be911343caa 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -48,6 +48,7 @@ import type {AgentExecutionResult,AgentRuntimeServiceOptions,AgentStepContinuation,+ DeferredMessagePatch,SubAgentBridgeParams,} from '@/server/services/agentRuntime';import { AgentRuntimeService } from '@/server/services/agentRuntime';@@ -387,9 +388,15 @@ export class AiAgentService {return this.agentRuntimeService.createOperationLockOwner(operationId);}- /** Publish a step that an inline loop deferred instead of running. */- scheduleContinuation(continuation: AgentStepContinuation): Promise<void> {- return this.agentRuntimeService.scheduleContinuation(continuation);+ /**+ * Publish a step that an inline loop deferred instead of running, after the+ * message patch its previous step left unpublished.+ */+ scheduleContinuation(+ continuation: AgentStepContinuation,+ deferredMessagePatch?: DeferredMessagePatch,+ ): Promise<void> {+ return this.agentRuntimeService.scheduleContinuation(continuation, deferredMessagePatch);}/** Release a lock retained across an inline step loop. */diff --git a/apps/server/src/services/message/__tests__/index.integration.test.ts b/apps/server/src/services/message/__tests__/index.integration.test.tsindex de116f46638..0bab6ce3d94 100644--- a/apps/server/src/services/message/__tests__/index.integration.test.ts+++ b/apps/server/src/services/message/__tests__/index.integration.test.ts@@ -6,6 +6,7 @@ import {files,messageGroups,messages,+ messagesFiles,sessions,topics,users,@@ -23,6 +24,13 @@ import { MessageService } from '../index';vi.mock('@/server/services/file', () => ({FileService: vi.fn().mockImplementation(function () {return {+ // Carries both inputs, so a caller passing the wrong id or path shows up.+ getFileAccessUrl: vi.fn().mockImplementation(async function (file: {+ id?: string;+ url: string;+ }) {+ return `/proxy/${file.id}?path=${file.url}`;+ }),getFullFileUrl: vi.fn().mockImplementation(function (path: string) {return path ? `/files${path}` : null;}),@@ -478,4 +486,81 @@ describe('MessageService Integration Tests', () => {expect(updatedGroup[0].content).toBe('Summary content');});});++ // A protocol 2 step diffs `prepareUiMessages` over its raw topic read, and the+ // client reads the same topic through `queryMessages`. If the two resolved+ // attachments differently, a patch would rewrite them on every step.+ describe('prepareUiMessages over a raw read', () => {+ it('matches the signed read for every attachment kind', async () => {+ const messageService = new MessageService(serverDB, userId);+ await serverDB.insert(agents).values({ id: 'agent-1', userId });+ await serverDB.insert(topics).values({ id: 'topic-1', userId });+ await serverDB.insert(files).values([+ { fileType: 'video/mp4', id: 'f-video', name: 'v', size: 1, url: 'video', userId },+ { fileType: 'audio/mpeg', id: 'f-audio', name: 'a', size: 1, url: 'audio', userId },+ { fileType: 'application/pdf', id: 'f-doc', name: 'd', size: 1, url: 'doc', userId },+ // Another user's file: the viewer gets a tombstone, not its path.+ {+ fileType: 'image/png',+ id: 'f-private',+ name: 'p',+ size: 1,+ url: 'private',+ userId: otherUserId,+ },+ ]);+ await serverDB.insert(messageGroups).values({+ content: 'summary',+ createdAt: new Date('2024-01-01T10:00:30Z'),+ id: 'group-1',+ topicId: 'topic-1',+ type: MessageGroupType.Compression,+ userId,+ });+ const message = { agentId: 'agent-1', role: 'user' as const, topicId: 'topic-1', userId };+ await serverDB.insert(messages).values([+ {+ ...message,+ content: 'compressed',+ createdAt: new Date('2024-01-01T10:00:00Z'),+ id: 'msg-compressed',+ messageGroupId: 'group-1',+ },+ {+ ...message,+ content: 'latest',+ createdAt: new Date('2024-01-01T10:01:00Z'),+ id: 'msg-latest',+ },+ ]);+ await serverDB.insert(messagesFiles).values(+ [+ ['msg-compressed', 'f1'],+ ['msg-latest', 'f1'],+ ['msg-latest', 'f-video'],+ ['msg-latest', 'f-audio'],+ ['msg-latest', 'f-doc'],+ ['msg-latest', 'f-private'],+ ].map(([messageId, fileId]) => ({ fileId, messageId, userId })),+ );++ const params = { agentId: 'agent-1', skipWorks: true, topicId: 'topic-1' };+ const raw = await (messageService as any).messageModel.query(params, {+ allowShareVisitor: true,+ });+ const signed = await messageService.queryMessages(params, { allowShareVisitor: true });++ // Guards the fixture: every attachment kind, the tombstone and the+ // compressed member are really in the read.+ const serialized = JSON.stringify(signed);+ for (const url of ['f-video?path=video', 'f-audio?path=audio', 'f-doc?path=doc'])+ expect(serialized).toContain(`/proxy/${url}`);+ // Once on the latest message, once on the compressed member.+ expect(serialized.split('/proxy/f1?path=abc')).toHaveLength(3);+ expect(serialized).toContain('"inaccessible":true');+ expect(serialized).not.toContain('path=private');++ expect(await messageService.prepareUiMessages(raw)).toEqual(signed);+ });+ });});diff --git a/packages/agent-gateway-client/PROTOCOL_V2.md b/packages/agent-gateway-client/PROTOCOL_V2.mdindex 7b252f53d58..bc1e7163ccb 100644--- a/packages/agent-gateway-client/PROTOCOL_V2.md+++ b/packages/agent-gateway-client/PROTOCOL_V2.md@@ -42,6 +42,9 @@ canonical conversation at every step boundary:- After the step is durable, an `agent_event` with `event.type: 'message_patch'` carries`{ revision, deletes, upserts }`. Each upsert contains the canonical top-level`UIChatMessage` plus its immediate predecessor as `afterId` (`null` for the first row).+ When the next step runs in the same server invocation, the patch is published at that+ step's entry, after `step_complete` and before the next `step_start`. It then also+ carries what other writers changed between the two steps.- `agent_runtime_end.data` carries `{ messagePatchMode: true, messageRevision }` and omitsboth `uiMessages` and `finalState`. The client settles only after it has that revision.- A missing revision or insertion anchor falls back to the existing authorized full-message