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.

⚑️ perf: make step completion state snapshots opt-in (#19682)

Arvin Xuc8666105863a
diff --git a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
index 905d7c32c39..684ed8b0ffa 100644
--- a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
+++ b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
@@ -395,7 +395,8 @@ export class GatewayStreamNotifier implements IStreamEventManager {
// payload too. The gateway forwards events verbatim to clients, and
// downstream consumers don't read these fields, so carrying them
// would re-introduce the same multi-megabyte serialization that
- // crashed the xadd path. Additionally, for a shared-agent visitor run,
+ // crashed the xadd path. step_complete state snapshots require the run
+ // to opt into includeFinalState. Additionally, for a shared-agent visitor run,
// drop `finalState` wholesale and scrub the rest β€” see
// `sanitizeGatewayEventData`.
const sanitizedEvent =
diff --git a/apps/server/src/modules/AgentRuntime/InMemoryStreamEventManager.ts b/apps/server/src/modules/AgentRuntime/InMemoryStreamEventManager.ts
index 9378d931c7c..fdbdc817e2f 100644
--- a/apps/server/src/modules/AgentRuntime/InMemoryStreamEventManager.ts
+++ b/apps/server/src/modules/AgentRuntime/InMemoryStreamEventManager.ts
@@ -49,7 +49,7 @@ export class InMemoryStreamEventManager implements IStreamEventManager {
// event shape stays identical to the production wire format β€”
// tests run against this manager and would otherwise mask
// regressions in the strip behaviour.
- data: stripFinalStateInEventData(event.data),
+ data: stripFinalStateInEventData(event.data, event.type),
id: eventId,
operationId,
timestamp: Date.now(),
diff --git a/apps/server/src/modules/AgentRuntime/StreamEventManager.ts b/apps/server/src/modules/AgentRuntime/StreamEventManager.ts
index 329eeff12da..27beecb9adb 100644
--- a/apps/server/src/modules/AgentRuntime/StreamEventManager.ts
+++ b/apps/server/src/modules/AgentRuntime/StreamEventManager.ts
@@ -1,5 +1,6 @@
import { type AgentStreamEventType } from '@lobechat/agent-gateway-client';
import { type ChatToolPayload } from '@lobechat/types';
+import { isRecord } from '@lobechat/utils/object';
import debug from 'debug';
import { type Redis } from 'ioredis';
@@ -78,7 +79,8 @@ const stripStateForStream = <T extends Record<string, any>>(
/**
* Chokepoint helper applied inside every stream-event publish site.
- * If the event `data` carries a `finalState`, strip `expertise`, `messages`,
+ * Step completion events omit finalState unless the persisted run host opts in.
+ * For other events carrying a `finalState`, strip `expertise`, `messages`,
* and the tool-set group off it (see `stripStateForStream` for the rationale).
*
* Centralizing the strip here means new callers β€” including direct
@@ -89,9 +91,16 @@ const stripStateForStream = <T extends Record<string, any>>(
* Returns the original reference when no stripping is needed so the
* common path stays allocation-free.
*/
-export const stripFinalStateInEventData = (data: unknown): unknown => {
+export const stripFinalStateInEventData = (data: unknown, eventType?: unknown): unknown => {
if (!data || typeof data !== 'object') return data;
const record = data as Record<string, unknown>;
+ const state = record.finalState;
+ const includeFinalState =
+ isRecord(state) && isRecord(state.host) && state.host.includeFinalState === true;
+ if (eventType === 'step_complete' && !includeFinalState) {
+ const { finalState: _finalState, ...rest } = record;
+ return rest;
+ }
const finalState = record.finalState;
if (!finalState || typeof finalState !== 'object') return data;
return { ...record, finalState: stripStateForStream(finalState as Record<string, any>) };
@@ -185,10 +194,10 @@ export class StreamEventManager {
const eventData: StreamEvent = {
...event,
// Chokepoint strip β€” every event passing through here gets its
- // `data.finalState` trimmed (messages + tool-set fields) before
+ // `data.finalState` removed for step_complete, otherwise trimmed, before
// serialization so a single xadd can't blow past Upstash's 10 MB
// request limit on long topics.
- data: stripFinalStateInEventData(event.data),
+ data: stripFinalStateInEventData(event.data, event.type),
operationId,
timestamp: Date.now(),
};
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts
index 15df657764e..2d58bd5cc19 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts
@@ -1,6 +1,7 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { GatewayStreamNotifier } from '../GatewayStreamNotifier';
+import { FULL_STRIP_REDACTION, sanitizeGatewayEventData } from '../gatewayVisitorRedaction';
import type { StreamChunkData } from '../StreamEventManager';
import type { IStreamEventManager } from '../types';
@@ -80,6 +81,59 @@ describe('GatewayStreamNotifier', () => {
);
});
+ it.each([undefined, 'execution_complete'])(
+ 'omits unused step_complete state from gateway payloads (phase=%s)',
+ async (phase) => {
+ const finalState = {
+ initialContext: { systemRole: 'system context' },
+ plan: { tools: ['tool'] },
+ status: 'done',
+ world: { agent: { name: 'agent' } },
+ };
+ const data = {
+ finalState,
+ nextStepScheduled: false,
+ ...(phase && { phase, reason: 'done', reasonDetail: 'Finished' }),
+ stepIndex: 2,
+ };
+
+ await notifier.publishStreamEvent('op-1', {
+ data,
+ stepIndex: 2,
+ type: 'step_complete',
+ });
+
+ const body = JSON.parse(mockFetch.mock.calls[0][1].body);
+ const { finalState: _finalState, ...expected } = data;
+ expect(body.event.data).toEqual(expected);
+ expect(body.event.data).not.toHaveProperty('finalState');
+ // The notifier must not mutate the runtime state passed by its caller.
+ expect(inner.calls.publishStreamEvent[0][1].data.finalState).toBe(finalState);
+ expect(data.finalState).toBe(finalState);
+ },
+ );
+
+ it('forwards opted-in step state without bypassing visitor redaction', async () => {
+ const finalState = {
+ host: { includeFinalState: true },
+ initialContext: { prompt: 'context' },
+ messages: [{ content: 'history' }],
+ status: 'done',
+ };
+ const data = { finalState, phase: 'execution_complete', reason: 'done' };
+ await notifier.publishStreamEvent('op-1', { data, stepIndex: 2, type: 'step_complete' });
+ const body = JSON.parse(mockFetch.mock.calls[0][1].body);
+ expect(body.event.data.finalState).toEqual({
+ host: { includeFinalState: true },
+ initialContext: { prompt: 'context' },
+ status: 'done',
+ });
+ expect(sanitizeGatewayEventData(data, FULL_STRIP_REDACTION, 'step_complete')).toEqual({
+ phase: 'execution_complete',
+ reason: 'done',
+ });
+ });
+
it('awaits stream_end gateway push before resolving', async () => {
let resolveFetch!: () => void;
mockFetch.mockImplementationOnce(
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/StreamEventManager.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/StreamEventManager.test.ts
index 83324e72392..40a45f4ad35 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/StreamEventManager.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/StreamEventManager.test.ts
@@ -317,6 +317,49 @@ describe('StreamEventManager', () => {
});
});
+ it.each([undefined, 'execution_complete'])(
+ 'omits finalState from persisted step_complete events (phase=%s)',
+ async (phase) => {
+ const finalState = { initialContext: { prompt: 'context' }, status: 'done' };
+ const data = { finalState, ...(phase && { phase, reason: 'done' }) };
+ mockRedis.xadd.mockResolvedValue('event-1');
+
+ await streamManager.publishStreamEvent('op-1', {
+ data,
+ stepIndex: 1,
+ type: 'step_complete',
+ });
+
+ const args = mockRedis.xadd.mock.calls[0];
+ const stored = JSON.parse(args[args.indexOf('data') + 1]);
+ expect(stored).toEqual(phase ? { phase, reason: 'done' } : {});
+ expect(data.finalState).toBe(finalState);
+ },
+ );
+
+ it('persists an opted-in state snapshot while omitting reconstructible message bodies', async () => {
+ const finalState = {
+ host: { includeFinalState: true },
+ initialContext: { prompt: 'context' },
+ messages: [{ content: 'large history' }],
+ status: 'done',
+ };
+ mockRedis.xadd.mockResolvedValue('event-1');
+ await streamManager.publishStreamEvent('op-1', {
+ data: { finalState, phase: 'execution_complete', reason: 'done' },
+ stepIndex: 1,
+ type: 'step_complete',
+ });
+ const args = mockRedis.xadd.mock.calls[0];
+ const stored = JSON.parse(args[args.indexOf('data') + 1]);
+ expect(stored.finalState).toEqual({
+ host: { includeFinalState: true },
+ initialContext: { prompt: 'context' },
+ status: 'done',
+ });
+ expect(finalState.messages).toHaveLength(1);
+ });
+
describe('readEventsOnce', () => {
it("resolves '$' to the current tail and returns it (not '$') on timeout", async () => {
// Stream has a tail entry; xread then times out (no newer events).
diff --git a/apps/server/src/modules/AgentRuntime/gatewayVisitorRedaction.ts b/apps/server/src/modules/AgentRuntime/gatewayVisitorRedaction.ts
index 63aa5edd03a..da658180ad7 100644
--- a/apps/server/src/modules/AgentRuntime/gatewayVisitorRedaction.ts
+++ b/apps/server/src/modules/AgentRuntime/gatewayVisitorRedaction.ts
@@ -185,7 +185,9 @@ const sanitizeErrorEventDataForVisitor = (
* 4. `uiMessages` additionally goes through {@link toVisitorMessage}'s full
* field allowlist, which the private-blob key strip alone does not cover.
*
- * For a normal run this falls back to the generic
+ * Normal step_complete events omit finalState unless the run opts in. Clients reconcile
+ * messages through message_patch/uiMessages and do not consume runtime state.
+ * Other events in a normal run fall back to the generic
* {@link stripFinalStateInEventData} (messages / tool-set fields only),
* matching the Redis xadd chokepoint.
*/
@@ -197,7 +199,7 @@ export const sanitizeGatewayEventData = (
if (!data || typeof data !== 'object') return data;
const record = data as Record<string, unknown>;
- if (!redaction) return stripFinalStateInEventData(data);
+ if (!redaction) return stripFinalStateInEventData(data, eventType);
const withoutFinalState: Record<string, unknown> =
'finalState' in record
diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.ts
index 2064fa0e771..b978cd8091c 100644
--- a/apps/server/src/routers/lambda/aiAgent.ts
+++ b/apps/server/src/routers/lambda/aiAgent.ts
@@ -936,6 +936,7 @@ const StartExecutionSchema = z.object({
*/
const ExecAgentSchema = z
.object({
+ includeFinalState: z.boolean().optional(),
/** The agent ID to run (either agentId or slug is required) */
agentId: z.string().optional(),
/** Application context for message storage */
@@ -2324,6 +2325,7 @@ export const aiAgentRouter = router({
appContext,
autoStart,
clientIds: input.clientIds,
+ includeFinalState: input.includeFinalState,
// This procedure serves the composer (`aiAgentService.execAgentTask`).
// The client already queues follow-ups behind a live run and shows the
// user a tray; refusing here would only make the message disappear.
@@ -2478,6 +2480,7 @@ export const aiAgentRouter = router({
workspaceId: ctx.workspaceId,
});
const result = await ctx.aiAgentService.execAgent({
+ includeFinalState: task.includeFinalState,
agentId,
appContext,
autoStart,
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
index b2878b24e99..acc148aafc0 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
@@ -441,6 +441,15 @@ describe('AgentRuntimeService', () => {
initialMessages: [],
};
+ it.each([undefined, false, true])(
+ 'persists the snapshot opt-in for resumed steps (%s)',
+ async (includeFinalState) => {
+ await service.createOperation({ ...mockParams, autoStart: false, includeFinalState });
+ const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];
+ expect(savedState.host.includeFinalState === true).toBe(includeFinalState === true);
+ },
+ );
+
it('should create operation successfully with autoStart=true', async () => {
mockQueueService.scheduleMessage.mockResolvedValueOnce('message-123');
@@ -952,7 +961,6 @@ describe('AgentRuntimeService', () => {
stepIndex: 1,
data: {
stepIndex: 1,
- finalState: mockStepResult.newState,
nextStepScheduled: false, // Published before nextStepScheduled is updated
},
});
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
index 4fe62b14c08..78b26be1cc6 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
@@ -1064,7 +1064,10 @@ export class AgentRuntimeService {
}),
// What the host needs to deliver and retry the run. Hooks are stamped
// right after creation once the dispatcher has serialized them.
- host: { queue: { retries: queueRetries, retryDelay: queueRetryDelay } },
+ host: {
+ ...(params.includeFinalState === true && { includeFinalState: true }),
+ queue: { retries: queueRetries, retryDelay: queueRetryDelay },
+ },
// Run ledger β€” everything fixed at creation lives in the typed slots.
metadata: {},
// Where the run came from β€” frozen from here on. Mirrors the
@@ -2197,7 +2200,9 @@ export class AgentRuntimeService {
// Publish step complete event
await this.streamManager.publishStreamEvent(operationId, {
data: {
- finalState: stepResult.newState,
+ ...(stepResult.newState.host?.includeFinalState === true && {
+ finalState: stepResult.newState,
+ }),
nextStepScheduled,
stepIndex,
},
diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.ts
index 41245b8a0d4..2a4ec6c2459 100644
--- a/apps/server/src/services/agentRuntime/types.ts
+++ b/apps/server/src/services/agentRuntime/types.ts
@@ -511,6 +511,8 @@ export interface OperationCreationParams {
* Registered once, auto-adapt to local (in-memory) or production (webhook) mode
*/
hooks?: AgentHook[];
+ /** Opt into runtime state snapshots on step_complete events. Defaults to false. */
+ includeFinalState?: boolean;
initialContext: AgentRuntimeContext;
initialMessages?: any[];
/** Initial step count offset for resumed operations (accumulated from previous runs) */
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index cbb3a9073d5..407533a99fa 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -1352,6 +1352,7 @@ export class AiAgentService {
queueRetryDelay,
signal,
stream,
+ includeFinalState: params.includeFinalState,
topicStartOwnerOperationId: params.topicStartOwnerOperationId,
updateAbortedAssistantMessage,
userAgent,
diff --git a/apps/server/src/services/aiAgent/pipeline/startOperation.ts b/apps/server/src/services/aiAgent/pipeline/startOperation.ts
index 44c5b6f4275..53b1496990d 100644
--- a/apps/server/src/services/aiAgent/pipeline/startOperation.ts
+++ b/apps/server/src/services/aiAgent/pipeline/startOperation.ts
@@ -40,6 +40,7 @@ export interface StartOperationInput {
evalContext?: InternalExecAgentParams['evalContext'];
evalRuntime?: InternalExecAgentParams['evalRuntime'];
hooks?: InternalExecAgentParams['hooks'];
+ includeFinalState?: boolean;
/** Final runtime context β€” base prep context with 16b/16c overrides applied. */
initialContext: OperationPrepResult['initialContext'];
initialStepCount?: number;
@@ -137,6 +138,7 @@ export const startOperation = async (
// If createOperation fails, we still have valid messages that need error info
try {
const result = await deps.agentRuntimeService.createOperation({
+ includeFinalState: input.includeFinalState,
activeDeviceId: discovery.activeDeviceId,
activeDeviceScope: discovery.activeDeviceScope,
agentConfig,
diff --git a/packages/agent-gateway-client/PROTOCOL_V2.md b/packages/agent-gateway-client/PROTOCOL_V2.md
index 98a9efb8d46..afd06946e03 100644
--- a/packages/agent-gateway-client/PROTOCOL_V2.md
+++ b/packages/agent-gateway-client/PROTOCOL_V2.md
@@ -24,6 +24,15 @@ clients (web without the Labs flag, CLI, desktop).
Non-goals for this iteration: SharedWorker cross-tab sharing; removing `mirrorToOperationId`
/ `subagent_progress`; migrating CLI; removing v1.
+### Optional step state snapshots
+
+`aiAgent.execAgent({ includeFinalState: true, ... })` opts a run into
+`step_complete.data.finalState`. The default is false. The option is persisted in
+`AgentState.host`, so queued and inline steps use the same policy. Snapshots still
+omit reconstructible message history and tool-set fields; share-visitor redaction
+always takes precedence. Internal state persistence and local done events are
+unaffected. This option does not change terminal message-patch reconciliation.
+
### 0.1 Native runtime message reconciliation
For the server-owned native agent harness, protocol v2 avoids repeating the complete
diff --git a/packages/agent-gateway-client/src/types.ts b/packages/agent-gateway-client/src/types.ts
index 153bfe034a5..81751070cc3 100644
--- a/packages/agent-gateway-client/src/types.ts
+++ b/packages/agent-gateway-client/src/types.ts
@@ -175,6 +175,7 @@ export interface ToolEndData {
}
export interface StepCompleteData {
+ /** Present only when the run opts into includeFinalState. */
finalState?: unknown;
phase: string;
reason?: string;
diff --git a/packages/agent-runtime/src/executors/finish.ts b/packages/agent-runtime/src/executors/finish.ts
index e36c0dcac96..f6718513fda 100644
--- a/packages/agent-runtime/src/executors/finish.ts
+++ b/packages/agent-runtime/src/executors/finish.ts
@@ -20,12 +20,10 @@ export const finish =
// re-trigger after completion. Best-effort β€” the adapter swallows failures.
await transports.operationStore?.clearRunningMark();
- // Publish the execution-complete stream event. `finalState.messages` +
- // tool-set fields are stripped centrally inside the sink adapter, so this
- // call site stays unaware.
+ // State snapshots are opt-in; internal done events always retain the state.
await transports.stream.publishEvent({
data: {
- finalState: { ...state, status: 'done' },
+ ...(state.host?.includeFinalState === true && { finalState: { ...state, status: 'done' } }),
phase: 'execution_complete',
reason,
reasonDetail,
diff --git a/packages/agent-runtime/src/executors/resolveTools.test.ts b/packages/agent-runtime/src/executors/resolveTools.test.ts
index a36ba674fd8..4c7969c8733 100644
--- a/packages/agent-runtime/src/executors/resolveTools.test.ts
+++ b/packages/agent-runtime/src/executors/resolveTools.test.ts
@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { AgentRuntimeHost } from '../transport';
import type { AgentInstruction, AgentState } from '../types';
+import { finish } from './finish';
import { resolveAbortedTools, resolveBlockedTools } from './resolveTools';
const createState = (overrides?: Partial<AgentState>): AgentState => ({
@@ -98,6 +99,21 @@ describe('resolveTools executors', () => {
} as unknown as AgentRuntimeHost;
});
+ it.each([undefined, false, true])(
+ 'includes finish state only when the run opts in (%s)',
+ async (includeFinalState) => {
+ const state = createState({ host: { includeFinalState } });
+ const result = await finish(host)({ type: 'finish', reason: 'completed' }, state);
+ const event = publishEvent.mock.calls[0][0];
+ expect(event.data.finalState !== undefined).toBe(includeFinalState === true);
+ if (includeFinalState) expect(event.data.finalState.status).toBe('done');
+ expect(result.newState.status).toBe('done');
+ expect(result.events).toContainEqual(
+ expect.objectContaining({ type: 'done', finalState: result.newState }),
+ );
+ },
+ );
+
it('persists blocked tools as rejected tool messages and continues', async () => {
const instruction: Extract<AgentInstruction, { type: 'resolve_blocked_tools' }> = {
payload: {
diff --git a/packages/agent-runtime/src/executors/resolveTools.ts b/packages/agent-runtime/src/executors/resolveTools.ts
index a755763d423..fb05ad02962 100644
--- a/packages/agent-runtime/src/executors/resolveTools.ts
+++ b/packages/agent-runtime/src/executors/resolveTools.ts
@@ -192,7 +192,7 @@ export const resolveAbortedTools =
await transports.stream.publishEvent({
data: {
- finalState: newState,
+ ...(newState.host?.includeFinalState === true && { finalState: newState }),
phase: 'execution_complete',
reason: USER_ABORTED_REASON,
reasonDetail: USER_ABORTED_REASON_DETAIL,
diff --git a/packages/agent-runtime/src/types/state.ts b/packages/agent-runtime/src/types/state.ts
index 995ce3e3e60..79936983036 100644
--- a/packages/agent-runtime/src/types/state.ts
+++ b/packages/agent-runtime/src/types/state.ts
@@ -159,6 +159,8 @@ export interface AgentRunPlan {
export interface AgentRunHostEnvelope {
/** Serialized lifecycle hook configs (webhook mode), so a queue worker can rebuild the dispatcher. */
hooks?: SerializedAgentHook[];
+ /** Opt into runtime state snapshots on step_complete events. Defaults to false. */
+ includeFinalState?: boolean;
/** Queue retry policy for step scheduling. */
queue?: { retries?: number; retryDelay?: string };
}
diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.ts
index 8e219855871..7f5ba73efa5 100644
--- a/packages/types/src/agentExecution/index.ts
+++ b/packages/types/src/agentExecution/index.ts
@@ -234,6 +234,8 @@ export interface ExecAgentParams {
* use the internal `files` param instead.
*/
fileIds?: string[];
+ /** Opt into runtime state snapshots on step_complete events. Defaults to false. */
+ includeFinalState?: boolean;
/** Additional system instructions appended after the agent's own system role */
instructions?: string;
/** Current desktop's device ID; used only when the effective target is `local`. */