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.

✨ feat(agent): return from a plain chat send before its init (behind agent_deferred_init) (#22607)

Arvin Xu183ccf2b02d6
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/createOperation.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/createOperation.test.ts
index 26d719df657..551528d8a81 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/createOperation.test.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/createOperation.test.ts
@@ -175,6 +175,28 @@ describe('AgentRuntimeService', () => {
},
);
+ it('leaves the init owed on the state and queues step 0 with the placeholder', async () => {
+ const pendingInitRequest = { prompt: 'hi', runAttachments: {} } as any;
+ const scheduleMessage = vi.fn().mockResolvedValue('msg-1');
+ (service as any).queueService = { scheduleMessage };
+
+ await service.createOperation({
+ ...mockParams,
+ initialMessages: [{ content: 'must not land', role: 'user' }],
+ pendingInitRequest,
+ });
+
+ const saved = mockCoordinator.saveAgentState.mock.calls[0][1];
+ expect(saved.request).toEqual(pendingInitRequest);
+ expect(saved.messages).toEqual([]);
+ expect(saved.operationToolSet).toBeUndefined();
+ // The stale-run reaper redrives step 0 from this saved context.
+ expect(saved.initialContext).toEqual(mockParams.initialContext);
+ expect(scheduleMessage).toHaveBeenCalledWith(
+ expect.objectContaining({ context: mockParams.initialContext, stepIndex: 0 }),
+ );
+ });
+
it('mirrors a resumed LLM-call baseline into the usage counter old workers report', async () => {
await service.createOperation({ ...mockParams, autoStart: false, initialLlmCalls: 7 });
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.ts
index 5f28bf2b84d..f5f3234d39f 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.ts
@@ -192,7 +192,12 @@ export async function createOperation(
: undefined);
const preInitState = buildPreInitState(params, { fileWorksAccepted, llmExecutor });
- const initialState = applyOperationInitSlots(preInitState, pickOperationInitSlots(params));
+ // A deferred init leaves the turn's request on the state: its presence is
+ // what tells the step-0 worker the init is still owed. The placeholder
+ // context is saved too, so the stale-run reaper can redrive step 0.
+ const initialState = params.pendingInitRequest
+ ? { ...preInitState, initialContext, messages: [], request: params.pendingInitRequest }
+ : applyOperationInitSlots(preInitState, pickOperationInitSlots(params));
// Use coordinator to create operation, automatically sends initialization event.
// For an in-group broadcast/speak member, mirror its Gateway stream events
diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.ts
index eadc76e676a..26cab64bbc7 100644
--- a/apps/server/src/services/agentRuntime/types.ts
+++ b/apps/server/src/services/agentRuntime/types.ts
@@ -13,6 +13,7 @@ import type {
ToolSource,
} from '@lobechat/context-engine';
import type {
+ AgentRunInitRequest,
AgentShareVisitorContext,
ChatTopicBotContext,
EvalToolForwardingConfig,
@@ -613,6 +614,12 @@ export interface OperationCreationParams {
* sub-tree back to its root.
*/
parentOperationId?: string;
+ /**
+ * Create the operation without its init: the step-0 worker runs it from this
+ * request. The init's own fields (`toolSet`, `initialMessages`, …) are then
+ * ignored and `initialContext` is only the placeholder step 0 is queued with.
+ */
+ pendingInitRequest?: AgentRunInitRequest;
/**
* A project's root instruction files, collected once during operation prep.
* Run context for the context engine to inject — see `expertise`.
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.deferredInit.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.deferredInit.test.ts
index bfdc8c6b39d..749ee8dcb34 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.deferredInit.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.deferredInit.test.ts
@@ -1,3 +1,4 @@
+import { RequestTrigger } from '@lobechat/types';
import type * as ModelBankModule from 'model-bank';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -19,8 +20,12 @@ const {
mockCreateOperation,
mockFindShareById,
mockQueryTree,
+ mockAppEnv,
+ mockFeatureFlags,
mockTopicFindById,
} = vi.hoisted(() => ({
+ mockAppEnv: {} as Record<string, unknown>,
+ mockFeatureFlags: vi.fn(),
mockCreateOperation: vi.fn(),
mockFindShareById: vi.fn(),
mockQueryTree: vi.fn(),
@@ -30,6 +35,20 @@ const {
mockTopicFindById: vi.fn(),
}));
+vi.mock('@/envs/app', async (importOriginal) => {
+ const actual = await importOriginal<{ appEnv: Record<string, unknown> }>();
+ return {
+ ...actual,
+ appEnv: new Proxy(actual.appEnv, {
+ get: (target, key: string) => (key in mockAppEnv ? mockAppEnv[key] : target[key]),
+ }),
+ };
+});
+
+vi.mock('@/server/featureFlags', () => ({
+ getServerFeatureFlagsStateFromRuntimeConfig: mockFeatureFlags,
+}));
+
vi.mock('@/database/models/agentShare', () => ({
AgentShareModel: {
findByShareId: mockFindShareById,
@@ -231,6 +250,7 @@ describe('AiAgentService.runDeferredInit - parity with the send path', () => {
beforeEach(() => {
vi.clearAllMocks();
rows.clear();
+ mockFeatureFlags.mockResolvedValue({});
let nextId = 0;
mockMessageCreate.mockImplementation(async (params: any, id?: string) => {
const row = { ...params, id: id ?? `msg-${++nextId}` };
@@ -342,6 +362,64 @@ describe('AiAgentService.runDeferredInit - parity with the send path', () => {
expect(run.deferred.state.messages).toEqual(throughRedis(run.created.initialMessages));
});
+ describe('a send inside the rollout', () => {
+ beforeEach(() => {
+ mockFeatureFlags.mockResolvedValue({ enableDeferredInit: true });
+ mockAppEnv.enableQueueAgentRuntime = true;
+ });
+
+ afterEach(() => {
+ delete mockAppEnv.enableQueueAgentRuntime;
+ });
+
+ const plainSend = {
+ agentId: 'agent-1',
+ appContext: { topicId: 'topic-1' },
+ prompt: 'Hello',
+ trigger: RequestTrigger.Chat,
+ };
+
+ it('creates the operation without running the init, and the worker can run it', async () => {
+ const result = await service.execAgent(plainSend);
+
+ expect(result.success).toBe(true);
+ expect(runOperationInit).not.toHaveBeenCalled();
+ const created = mockCreateOperation.mock.calls[0][0];
+ expect(created.pendingInitRequest.prompt).toBe('Hello');
+ expect(created.initialContext.phase).toBe('user_input');
+
+ const { pendingInitRequest: request, operationId } = created;
+ const deferred = await service.runDeferredInit({
+ operationId,
+ request: throughRedis(request),
+ state: throughRedis({ ...buildPreInitState(created, {}), request }) as any,
+ });
+
+ expect(runOperationInit).toHaveBeenCalledTimes(1);
+ expect(deferred.state.operationToolSet).toBeDefined();
+ expect(deferred.context.payload).toMatchObject({
+ assistantMessageId: created.appContext.assistantMessageId,
+ });
+ });
+
+ it('keeps the init synchronous for a regenerate', async () => {
+ rows.set('msg-prev-1', {
+ content: 'earlier',
+ id: 'msg-prev-1',
+ role: 'user',
+ topicId: 'topic-1',
+ });
+ await service.execAgent({
+ ...plainSend,
+ parentMessageId: 'msg-prev-1',
+ resume: true,
+ });
+
+ expect(runOperationInit).toHaveBeenCalledTimes(1);
+ expect(mockCreateOperation.mock.calls[0][0].pendingInitRequest).toBeUndefined();
+ });
+ });
+
describe('a share visitor run', () => {
const shareGate = {
agentId: 'agent-1',
diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/deferInitGate.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/deferInitGate.test.ts
new file mode 100644
index 00000000000..5ecb695f6f3
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/deferInitGate.test.ts
@@ -0,0 +1,61 @@
+import { RequestTrigger } from '@lobechat/types';
+import { describe, expect, it, vi } from 'vitest';
+
+import { type DeferInitInput, shouldDeferOperationInit } from '../deferInitGate';
+
+describe('shouldDeferOperationInit', () => {
+ const plainSend: DeferInitInput = {
+ autoStart: true,
+ hasOrchestration: false,
+ queueRuntimeEnabled: true,
+ request: { runAttachments: {} } as DeferInitInput['request'],
+ trigger: RequestTrigger.Chat,
+ };
+
+ const flagOn = async () => true;
+
+ it('defers a plain chat send once the flag is on', async () => {
+ await expect(shouldDeferOperationInit(plainSend, flagOn)).resolves.toBe(true);
+ });
+
+ it('keeps the init synchronous while the flag is off', async () => {
+ await expect(shouldDeferOperationInit(plainSend, async () => false)).resolves.toBe(false);
+ });
+
+ it('does not read the flag for a run that could never defer', async () => {
+ const isEnabled = vi.fn(flagOn);
+ await shouldDeferOperationInit({ ...plainSend, autoStart: false }, isEnabled);
+ expect(isEnabled).not.toHaveBeenCalled();
+ });
+
+ it.each<[string, Partial<DeferInitInput>]>([
+ ['no queue runtime', { queueRuntimeEnabled: false }],
+ ['no auto-start', { autoStart: false }],
+ ['an orchestrated run', { hasOrchestration: true }],
+ ['a non-chat trigger', { trigger: 'cron' }],
+ ])('keeps the init synchronous for %s', async (_, override) => {
+ await expect(shouldDeferOperationInit({ ...plainSend, ...override }, flagOn)).resolves.toBe(
+ false,
+ );
+ });
+
+ it.each([
+ ['a resume', { resume: true }],
+ ['an approval', { resumeApproval: {} }],
+ ['a batch approval', { resumeApprovals: [{}] }],
+ ['a run from history', { resumeFromHistory: true }],
+ ['a tool result', { resumeToolResult: {} }],
+ ['a fixed device', { isFixedDeviceTarget: true }],
+ ['a required device', { requireDevice: true }],
+ ])('keeps the init synchronous for %s', async (_, request) => {
+ await expect(
+ shouldDeferOperationInit(
+ {
+ ...plainSend,
+ request: { ...plainSend.request, ...request } as DeferInitInput['request'],
+ },
+ flagOn,
+ ),
+ ).resolves.toBe(false);
+ });
+});
diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.editingGroupId.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.editingGroupId.test.ts
index 085774b0de7..74338afb019 100644
--- a/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.editingGroupId.test.ts
+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.editingGroupId.test.ts
@@ -48,14 +48,16 @@ describe('startOperation › group builder editing target inheritance', () => {
approvalClaim: {},
approvalSourceToolMessageIds: [],
autoStart: true,
- discovery: {
- credentialFactsPromise: Promise.resolve(undefined),
- modelMediaCapabilities: {},
- toolsResult: { enabledToolIds: [] },
+ init: {
+ discovery: {
+ credentialFactsPromise: Promise.resolve(undefined),
+ modelMediaCapabilities: {},
+ toolsResult: { enabledToolIds: [] },
+ },
+ initialContext: {},
+ prep: { allMessages: [], deviceSystemInfo: {} },
},
- initialContext: {},
operationId: 'op-new',
- prep: { allMessages: [], deviceSystemInfo: {} },
updateAbortedAssistantMessage: vi.fn(),
userInterventionConfig: { approvalMode: 'manual' },
...extra,
@@ -71,7 +73,6 @@ describe('startOperation › group builder editing target inheritance', () => {
ctx,
input({
approvalSourceOperationId: 'op-parked',
- initialContext: { appContext: { topicId: 'tpc-1' } },
}),
);
@@ -108,7 +109,6 @@ describe('startOperation › group builder editing target inheritance', () => {
ctx,
input({
approvalSourceOperationId: 'op-parked',
- initialContext: { appContext: { topicId: 'tpc-1' } },
}),
);
diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.memberRuntimeEnd.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.memberRuntimeEnd.test.ts
index fedad37fc49..15b22cc1ff1 100644
--- a/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.memberRuntimeEnd.test.ts
+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.memberRuntimeEnd.test.ts
@@ -47,14 +47,16 @@ const setup = (sourceAccepts: boolean) => {
approvalClaim: {},
approvalSourceToolMessageIds: [],
autoStart: true,
- discovery: {
- credentialFactsPromise: Promise.resolve(undefined),
- modelMediaCapabilities: {},
- toolsResult: { enabledToolIds: [] },
+ init: {
+ discovery: {
+ credentialFactsPromise: Promise.resolve(undefined),
+ modelMediaCapabilities: {},
+ toolsResult: { enabledToolIds: [] },
+ },
+ initialContext: {},
+ prep: { allMessages: [], deviceSystemInfo: {} },
},
- initialContext: {},
operationId: 'op-new',
- prep: { allMessages: [], deviceSystemInfo: {} },
updateAbortedAssistantMessage: vi.fn(),
userInterventionConfig: { approvalMode: 'manual' },
...extra,
diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.onScheduled.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.onScheduled.test.ts
index 7cc7d884760..9bae1650498 100644
--- a/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.onScheduled.test.ts
+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.onScheduled.test.ts
@@ -39,15 +39,17 @@ const setup = (autoStarted: boolean) => {
approvalClaim: {},
approvalSourceToolMessageIds: [],
autoStart: true,
- discovery: {
- credentialFactsPromise: Promise.resolve(undefined),
- modelMediaCapabilities: {},
- toolsResult: { enabledToolIds: [] },
+ init: {
+ discovery: {
+ credentialFactsPromise: Promise.resolve(undefined),
+ modelMediaCapabilities: {},
+ toolsResult: { enabledToolIds: [] },
+ },
+ initialContext: {},
+ prep: { allMessages: [], deviceSystemInfo: {} },
},
- initialContext: {},
onScheduled,
operationId: 'op-new',
- prep: { allMessages: [], deviceSystemInfo: {} },
updateAbortedAssistantMessage: vi.fn(),
userInterventionConfig: { approvalMode: 'manual' },
} as any;
diff --git a/apps/server/src/services/aiAgent/pipeline/deferInitGate.ts b/apps/server/src/services/aiAgent/pipeline/deferInitGate.ts
new file mode 100644
index 00000000000..59679953f11
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/deferInitGate.ts
@@ -0,0 +1,47 @@
+import type { AgentRunInitRequest } from '@lobechat/types';
+import { RequestTrigger } from '@lobechat/types';
+
+import { getServerFeatureFlagsStateFromRuntimeConfig } from '@/server/featureFlags';
+
+/** A flag that cannot be read keeps the send on the synchronous init. */
+export const isDeferredInitEnabled = async (userId: string): Promise<boolean> => {
+ const flags = await getServerFeatureFlagsStateFromRuntimeConfig(userId).catch(() => undefined);
+ return flags?.enableDeferredInit === true;
+};
+
+export interface DeferInitInput {
+ /** Runs started without auto-start are stepped by their caller, not the queue. */
+ autoStart: boolean;
+ /** Set for every caller that is not the plain composer (bots, group members, sub-agents, ...). */
+ hasOrchestration: boolean;
+ queueRuntimeEnabled: boolean;
+ request: AgentRunInitRequest;
+ trigger?: string;
+}
+
+/**
+ * Only a plain chat send may skip the init on the send path.
+ *
+ * Everything else needs what the init produces before it returns: an approval
+ * resume dispatches against a prepared state, a fixed or required device has to
+ * fail synchronously rather than after the caller was told the message was
+ * sent, and an inline runtime has no step-0 worker to hand the init to.
+ *
+ * The flag is read last, so runs that could never defer pay no read for it.
+ */
+export const shouldDeferOperationInit = async (
+ { autoStart, hasOrchestration, queueRuntimeEnabled, request, trigger }: DeferInitInput,
+ isEnabled: () => Promise<boolean>,
+): Promise<boolean> =>
+ queueRuntimeEnabled &&
+ autoStart &&
+ !hasOrchestration &&
+ trigger === RequestTrigger.Chat &&
+ !request.resume &&
+ !request.resumeApproval &&
+ !request.resumeApprovals?.length &&
+ !request.resumeFromHistory &&
+ !request.resumeToolResult &&
+ !request.isFixedDeviceTarget &&
+ !request.requireDevice &&
+ (await isEnabled());
diff --git a/apps/server/src/services/aiAgent/pipeline/deferredInit.ts b/apps/server/src/services/aiAgent/pipeline/deferredInit.ts
index d30a41c3554..a1ba3d0564d 100644
--- a/apps/server/src/services/aiAgent/pipeline/deferredInit.ts
+++ b/apps/server/src/services/aiAgent/pipeline/deferredInit.ts
@@ -13,6 +13,7 @@ import type { ExecRunContext } from '../types';
import { type OperationInitDeps, runOperationInit } from './operationInit';
import { resolveOperationInitSlots } from './operationInitSlots';
import { createHistoryMessagesLoader } from './operationPrep';
+import { traceSendStage } from './sendTracing';
const log = debug('lobe-server:ai-agent-service');
@@ -182,19 +183,21 @@ export const runDeferredOperationInit = async (
},
);
- const { discovery, initialContext, prep } = await runOperationInit(
- {
- ...deps,
- getMarketService: () => deps.getMarketService(ctx.runFacts),
- loadHistoryMessages,
- readFileContent: (fileId) => deps.readFileContent(fileId, ctx.shareGate),
- // A Stop during the init is settled by the step once the init returns
- // (`runPendingInit`), so the stages need no abort probe of their own.
- throwIfExecutionAborted: async () => {},
- },
- ctx,
- request,
- operationId,
+ const { discovery, initialContext, prep } = await traceSendStage('operation_init', () =>
+ runOperationInit(
+ {
+ ...deps,
+ getMarketService: () => deps.getMarketService(ctx.runFacts),
+ loadHistoryMessages,
+ readFileContent: (fileId) => deps.readFileContent(fileId, ctx.shareGate),
+ // A Stop during the init is settled by the step once the init returns
+ // (`runPendingInit`), so the stages need no abort probe of their own.
+ throwIfExecutionAborted: async () => {},
+ },
+ ctx,
+ request,
+ operationId,
+ ),
);
const slots = await resolveOperationInitSlots({ discovery, initialContext, prep });
diff --git a/apps/server/src/services/aiAgent/pipeline/execTurn.ts b/apps/server/src/services/aiAgent/pipeline/execTurn.ts
index 935b37ba261..33e1f652a54 100644
--- a/apps/server/src/services/aiAgent/pipeline/execTurn.ts
+++ b/apps/server/src/services/aiAgent/pipeline/execTurn.ts
@@ -16,6 +16,7 @@ import type { ConnectorToolModel } from '@/database/models/connectorTool';
import type { MessageModel } from '@/database/models/message';
import type { PluginModel } from '@/database/models/plugin';
import type { TopicModel } from '@/database/models/topic';
+import { appEnv } from '@/envs/app';
import type { AgentConfigWithId } from '@/server/services/agent';
import type { AgentDocumentsService } from '@/server/services/agentDocuments';
import type { AgentRuntimeService } from '@/server/services/agentRuntime';
@@ -30,8 +31,13 @@ import { assertAgentRelayHop } from '../sourceAttribution';
import type { ExecRunContext, InternalExecAgentParams } from '../types';
import type { ApprovalClaimState } from './approvalResume';
import { claimApprovalResume, tryReuseInterventionContinuation } from './approvalResume';
+import { isDeferredInitEnabled, shouldDeferOperationInit } from './deferInitGate';
import { dispatchHeteroAgent } from './heteroDispatch';
-import { buildOperationInitRequest, runOperationInit } from './operationInit';
+import {
+ buildOperationInitRequest,
+ runOperationInit,
+ toPersistedInitRequest,
+} from './operationInit';
import { createHistoryMessagesLoader } from './operationPrep';
import { resolveRunAgentConfig } from './resolveRunAgentConfig';
import { loadResumeParentMessage } from './resumeParent';
@@ -39,7 +45,7 @@ import { bindRunFee, claimRunFee, type RunFeeClaim, shouldHoldRunFee } from './r
import { resolveRunSettings } from './runSettings';
import { bindRunSlot, claimRunSlot, resolveRunSlotPolicy, type RunSlotClaim } from './runSlot';
import { traceSendStage } from './sendTracing';
-import { startOperation } from './startOperation';
+import { startOperation, type StartOperationInit } from './startOperation';
import { bindTopicWorkingDirectory } from './topicWorkingDirectory';
import { setupTurn } from './turnSetup';
@@ -650,49 +656,66 @@ export const execAgentTurn = async (
viewedGoal: appContext?.viewedGoal,
});
- const { discovery, initialContext, prep } = await traceSendStage('operation_init', () =>
- runOperationInit(
- {
- agentDocumentsService: deps.agentDocumentsService,
- agentModel: deps.agentModel,
- bindTopicWorkingDirectory: (p) =>
- bindTopicWorkingDirectory({ topicModel: deps.topicModel }, p),
- composioService: deps.composioService,
- connectorModel: deps.connectorModel,
- connectorToolModel: deps.connectorToolModel,
- db: deps.db,
- getMarketService: () => deps.getMarketService(runFacts),
- loadHistoryMessages,
- messageModel: deps.messageModel,
- pluginModel: deps.pluginModel,
- readFileContent: async (fileId) =>
- (
- await new DocumentService(deps.db, deps.userId, deps.workspaceId).parseFile(
- fileId,
- shareGate ? agentShareFileAccessScope(shareGate) : ordinaryFileAccessScope,
- )
- ).content ?? undefined,
- throwIfExecutionAborted,
- topicModel: deps.topicModel,
- userId: deps.userId,
- workspaceId: deps.workspaceId,
- },
- runContext,
- initRequest,
- operationId,
- ),
- );
-
- // 17. Log final operation parameters summary
- log(
- 'execAgent: creating operation %s with params: model=%s, provider=%s, tools=%d, messages=%d, manifests=%d',
- operationId,
- model,
- provider,
- discovery.tools?.length ?? 0,
- prep.allMessages.length,
- Object.keys(discovery.toolManifestMap).length,
+ // A plain chat send returns here and leaves the init to the step-0 worker.
+ const deferInit = await shouldDeferOperationInit(
+ {
+ autoStart,
+ hasOrchestration: !!(
+ appContext?.agentSignal ||
+ appContext?.groupId ||
+ appContext?.isSubAgent ||
+ botContext ||
+ botPlatformContext ||
+ continuationOperationId ||
+ discordContext ||
+ evalContext ||
+ evalRuntime ||
+ params.llmExecutor ||
+ params.reservedOperationId ||
+ params.topicStartOwnerOperationId ||
+ parentOperationId ||
+ shareGate
+ ),
+ queueRuntimeEnabled: appEnv.enableQueueAgentRuntime === true,
+ request: initRequest,
+ trigger,
+ },
+ () => isDeferredInitEnabled(deps.userId),
);
+ const init: StartOperationInit = deferInit
+ ? { pendingRequest: toPersistedInitRequest(initRequest) }
+ : await traceSendStage('operation_init', () =>
+ runOperationInit(
+ {
+ agentDocumentsService: deps.agentDocumentsService,
+ agentModel: deps.agentModel,
+ bindTopicWorkingDirectory: (p) =>
+ bindTopicWorkingDirectory({ topicModel: deps.topicModel }, p),
+ composioService: deps.composioService,
+ connectorModel: deps.connectorModel,
+ connectorToolModel: deps.connectorToolModel,
+ db: deps.db,
+ getMarketService: () => deps.getMarketService(runFacts),
+ loadHistoryMessages,
+ messageModel: deps.messageModel,
+ pluginModel: deps.pluginModel,
+ readFileContent: async (fileId) =>
+ (
+ await new DocumentService(deps.db, deps.userId, deps.workspaceId).parseFile(
+ fileId,
+ shareGate ? agentShareFileAccessScope(shareGate) : ordinaryFileAccessScope,
+ )
+ ).content ?? undefined,
+ throwIfExecutionAborted,
+ topicModel: deps.topicModel,
+ userId: deps.userId,
+ workspaceId: deps.workspaceId,
+ },
+ runContext,
+ initRequest,
+ operationId,
+ ),
+ );
// Claim the child slot on the supervisor's runningOperation marker LAST,
// immediately before startup. The marker vanishes when the supervisor is
@@ -767,19 +790,17 @@ export const execAgentTurn = async (
clientIp,
disabledPluginIds,
discordContext,
- discovery,
enableExpertise,
evalContext,
evalRuntime,
hooks,
- initialContext,
+ init,
initialLlmCalls,
initialStepCount,
maxSteps,
operationId,
operationTaskId,
parentOperationId,
- prep,
providedApprovalResolutionRequestId,
queueRetries,
queueRetryDelay,
diff --git a/apps/server/src/services/aiAgent/pipeline/operationInitSlots.ts b/apps/server/src/services/aiAgent/pipeline/operationInitSlots.ts
index 3245a1fffad..4192fd98322 100644
--- a/apps/server/src/services/aiAgent/pipeline/operationInitSlots.ts
+++ b/apps/server/src/services/aiAgent/pipeline/operationInitSlots.ts
@@ -70,3 +70,27 @@ export const resolveOperationInitSlots = async ({
userMemory: prep.userMemory,
};
};
+
+/**
+ * The slots of an operation created without its init: nothing the init
+ * produces, and the context step 0 is queued with until the worker has
+ * assembled the real one.
+ */
+export const buildPendingInitSlots = ({
+ assistantMessageId,
+ operationId,
+ parentMessageId,
+}: {
+ assistantMessageId: string;
+ operationId: string;
+ parentMessageId: string;
+}): OperationInitSlots =>
+ ({
+ initialContext: {
+ payload: { assistantMessageId, isFirstMessage: true, message: [], parentMessageId },
+ phase: 'user_input',
+ session: { messageCount: 0, sessionId: operationId, status: 'idle', stepCount: 0 },
+ },
+ modelCapabilities: {},
+ toolSet: { enabledToolIds: [], manifestMap: {}, sourceMap: {}, tools: [] },
+ }) as OperationInitSlots;
diff --git a/apps/server/src/services/aiAgent/pipeline/startOperation.ts b/apps/server/src/services/aiAgent/pipeline/startOperation.ts
index 784006a1de0..1083d5e9fac 100644
--- a/apps/server/src/services/aiAgent/pipeline/startOperation.ts
+++ b/apps/server/src/services/aiAgent/pipeline/startOperation.ts
@@ -9,7 +9,8 @@ import { isAbortError } from '@/server/services/agentRuntime/abort';
import type { ExecRunContext, InternalExecAgentParams } from '../types';
import type { ApprovalClaimState } from './approvalResume';
-import { resolveOperationInitSlots } from './operationInitSlots';
+import type { OperationInitRequest } from './operationInit';
+import { buildPendingInitSlots, resolveOperationInitSlots } from './operationInitSlots';
import type { OperationPrepResult } from './operationPrep';
import { traceStartStage } from './sendTracing';
import type { ToolDiscoveryResult } from './toolDiscovery';
@@ -26,6 +27,16 @@ export interface StartOperationDeps {
workspaceId?: string;
}
+/** What the init produced, or the request the step-0 worker will run it from. */
+export type StartOperationInit =
+ | {
+ discovery: ToolDiscoveryResult;
+ /** Final runtime context — base prep context with 16b/16c overrides applied. */
+ initialContext: OperationPrepResult['initialContext'];
+ prep: OperationPrepResult;
+ }
+ | { pendingRequest: OperationInitRequest };
+
export interface StartOperationInput {
/** See {@link InternalExecAgentParams.acceptsFileWorks}. */
acceptsFileWorks?: boolean;
@@ -43,14 +54,12 @@ export interface StartOperationInput {
/** Tri-state disabled plugin identifiers, kept on the world slot for the context rules. */
disabledPluginIds?: string[];
discordContext?: any;
- discovery: ToolDiscoveryResult;
enableExpertise: boolean;
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'];
+ init: StartOperationInit;
initialLlmCalls?: number;
initialStepCount?: number;
/** Relay executor the calling client declared; lands on `state.host.llmExecutor`. */
@@ -66,7 +75,6 @@ export interface StartOperationInput {
operationId: string;
operationTaskId?: string;
parentOperationId?: string;
- prep: OperationPrepResult;
providedApprovalResolutionRequestId?: string;
queueRetries?: number;
queueRetryDelay?: string;
@@ -123,19 +131,17 @@ export const startOperation = async (
clientIp,
disabledPluginIds,
discordContext,
- discovery,
enableExpertise,
evalContext,
evalRuntime,
hooks,
- initialContext,
+ init,
initialLlmCalls,
initialStepCount,
maxSteps,
operationId,
operationTaskId,
parentOperationId,
- prep,
providedApprovalResolutionRequestId,
queueRetries,
queueRetryDelay,
@@ -155,14 +161,8 @@ export const startOperation = async (
(appContext?.scope === 'group_agent_builder' ? appContext.editingGroupId : undefined) ||
topicEditingGroupId;
- log(
- 'execAgent: creating operation %s — agentDocuments=%d, knowledgeBases=%s, tools=%d, skills=%d',
- operationId,
- discovery.hasAgentDocuments ? 'yes' : 0,
- discovery.hasEnabledKnowledgeBases,
- discovery.tools?.length ?? 0,
- prep.operationSkillSet?.skills?.length ?? 0,
- );
+ const pendingInitRequest = 'pendingRequest' in init ? init.pendingRequest : undefined;
+ log('execAgent: creating operation %s (deferred init: %s)', operationId, !!pendingInitRequest);
// Wrap in try-catch to handle operation startup failures (e.g., QStash unavailable)
// If createOperation fails, we still have valid messages that need error info
@@ -199,13 +199,17 @@ export const startOperation = async (
const inheritedEditingGroupId = approvalSourceOperationId
? await deps.agentRuntimeService.getOperationEditingGroupId(approvalSourceOperationId)
: undefined;
- const { modelCapabilities, ...initSlots } = await resolveOperationInitSlots({
- discovery,
- initialContext,
- prep,
- });
+ const { modelCapabilities, ...initSlots } =
+ 'pendingRequest' in init
+ ? buildPendingInitSlots({
+ assistantMessageId,
+ operationId,
+ parentMessageId: userMessageId ?? parentMessageId ?? '',
+ })
+ : await resolveOperationInitSlots(init);
const result = await deps.agentRuntimeService.createOperation({
...initSlots,
+ pendingInitRequest,
acceptsFileWorks: fileWorksAccepted,
acceptsMemberRuntimeEnd: memberRuntimeEndAccepted,
clientProtocol: input.clientProtocol,
diff --git a/docs/self-hosting/advanced/feature-flags.mdx b/docs/self-hosting/advanced/feature-flags.mdx
index b29b581d2d6..1fcb5ee8192 100644
--- a/docs/self-hosting/advanced/feature-flags.mdx
+++ b/docs/self-hosting/advanced/feature-flags.mdx
@@ -44,6 +44,7 @@ You can achieve various feature combinations using the above configuration synta
| `agent_share` | Gates new or re-enabled interactive Agent shares. Requires deployment support; see the boundary below. | Disabled |
| `agent_gateway_mux_mobile` | LobeHub Mobile rollout switch for the multiplexed gateway socket and protocol-v2 payloads; Web needs no flag and follows `AGENT_GATEWAY_PROTOCOL`. Requires a gateway that serves `/v2/ws`. | Disabled |
| `agent_llm_relay` | Runs LLM calls for model providers only the user's device can reach (local Ollama / LM Studio, private-network endpoints) on the client that started the run, while the agent loop stays on the server. Requires an open LobeHub client for such runs. | Disabled |
+| `agent_deferred_init` | Returns a plain chat send as soon as its messages are saved and runs tool discovery and context assembly in the first agent step, so sending feels instant. Requires the queue agent runtime. | Disabled |
| `dashboard` | Dashboards: the home and project dashboard pages, the widget Portal, in-chat widget previews and the `builtin-dashboard` agent tool that builds monitoring widgets. When off, these are hidden and the widget / dashboard APIs return FORBIDDEN; widgets already published keep refreshing on their schedule. | Disabled |
| `mcp_apps` | MCP Apps: a tool result whose MCP server declares an interactive `ui://` view renders that view (the server's HTML, in a sandboxed iframe) in the conversation. When off, such results render as plain tool results and the server does not announce MCP Apps support to MCP servers. | Disabled |
| `edit_agent` | Allows users to edit assistants. | Enabled |
diff --git a/docs/self-hosting/advanced/feature-flags.zh-CN.mdx b/docs/self-hosting/advanced/feature-flags.zh-CN.mdx
index 92d27a99524..0ade6b9a709 100644
--- a/docs/self-hosting/advanced/feature-flags.zh-CN.mdx
+++ b/docs/self-hosting/advanced/feature-flags.zh-CN.mdx
@@ -42,6 +42,7 @@ tags:
| `agent_share` | 控制新建或重新启用交互式助理分享;还需部署支持,详见下文边界。 | 关闭 |
| `agent_gateway_mux_mobile` | LobeHub Mobile 使用多路复用网关连接与 v2 协议载荷的灰度开关;Web 无需开关,跟随 `AGENT_GATEWAY_PROTOCOL`;需要网关提供 `/v2/ws`。 | 关闭 |
| `agent_llm_relay` | 对只有用户设备能访问的模型服务商(本地 Ollama / LM Studio、私网地址),由发起运行的客户端执行单次模型调用,助理循环仍在服务端运行;这类运行需要有打开的 LobeHub 客户端。 | 关闭 |
+| `agent_deferred_init` | 普通聊天发送在消息落库后立即返回,工具发现和上下文组装放到第一个助理步骤中执行,发送不再等待。需要队列模式的助理运行时。 | 关闭 |
| `dashboard` | 看板:首页与项目看板页面、监控组件侧边栏、对话内的组件预览,以及用于搭建监控组件的 `builtin-dashboard` 助理工具。关闭时以上入口均隐藏,组件与看板相关接口返回 FORBIDDEN;已发布的组件仍按计划刷新。 | 关闭 |
| `mcp_apps` | MCP Apps:MCP 服务器为工具结果声明了交互页面(`ui://`)时,在对话中渲染该页面(服务器提供的 HTML,运行在沙箱 iframe 中)。关闭时按普通工具结果显示,服务端也不再向 MCP 服务器声明支持 MCP Apps。 | 关闭 |
| `edit_agent` | 允许用户编辑助手。 | 开启 |
diff --git a/packages/app-config/src/featureFlags/schema.ts b/packages/app-config/src/featureFlags/schema.ts
index 8cc2931ff60..0c346f2cfee 100644
--- a/packages/app-config/src/featureFlags/schema.ts
+++ b/packages/app-config/src/featureFlags/schema.ts
@@ -55,6 +55,14 @@ export const FeatureFlagsSchema = z.object({
*/
agent_llm_relay: FeatureFlagValue.optional(),
+ /**
+ * Rollout gate for deferring an operation's init: a plain chat send returns
+ * once its messages are durable and the step-0 worker runs tool discovery and
+ * context assembly. Off: the send path runs them before returning. Array
+ * values are user ids.
+ */
+ agent_deferred_init: FeatureFlagValue.optional(),
+
/**
* Dashboards: monitoring widgets built by the `builtin-dashboard` agent tool,
* the home / project dashboard pages, the widget Portal and in-chat widget
@@ -205,6 +213,7 @@ export const DEFAULT_FEATURE_FLAGS: IFeatureFlags = {
// Off until the client executor ships everywhere; allowlist first.
agent_llm_relay: false,
+ agent_deferred_init: false,
// Off until an admin publishes a user allowlist or flips it to true.
dashboard: false,
@@ -266,6 +275,11 @@ export const mapFeatureFlagsEnvToState = (
'agent_gateway_mux_mobile',
),
enableLlmRelay: evaluateFeatureFlag(config.agent_llm_relay, userId, 'agent_llm_relay'),
+ enableDeferredInit: evaluateFeatureFlag(
+ config.agent_deferred_init,
+ userId,
+ 'agent_deferred_init',
+ ),
enableDashboard: evaluateFeatureFlag(config.dashboard, userId, 'dashboard'),
enableMcpApps: evaluateFeatureFlag(config.mcp_apps, userId, 'mcp_apps'),
enableAgentKnowledgeSpace: evaluateFeatureFlag(
diff --git a/packages/types/src/serverConfig.ts b/packages/types/src/serverConfig.ts
index 03339d5375a..463f0029afd 100644
--- a/packages/types/src/serverConfig.ts
+++ b/packages/types/src/serverConfig.ts
@@ -67,6 +67,8 @@ export type IFeatureFlagsState = {
* as an executor only when this is on; the server checks it again.
*/
enableLlmRelay: boolean | undefined;
+ /** A plain chat send leaves its init to the step-0 worker (`agent_deferred_init`). */
+ enableDeferredInit: boolean | undefined;
/**
* Creating managed cloud devices (`managed_cloud_device`). Off by default: the "Create in
* cloud" entry is hidden and the creation APIs answer FORBIDDEN. Existing managed devices keep