🤯 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): trace and overlap the hetero send path (#22898)
Arvin Xu05883669ca95
diff --git a/apps/server/src/services/aiAgent/pipeline/execTurn.ts b/apps/server/src/services/aiAgent/pipeline/execTurn.tsindex f284c0987e0..82863023aa6 100644--- a/apps/server/src/services/aiAgent/pipeline/execTurn.ts+++ b/apps/server/src/services/aiAgent/pipeline/execTurn.ts@@ -526,48 +526,71 @@ export const execAgentTurn = async (userMessageMetadata: turn.userMessageId ? turn.requestTriggerMetadata : undefined,};+ // Every caller that is not the plain composer (bots, group members,+ // sub-agents, evals, share visitors, …): only a plain send may answer before+ // its init (`agent_deferred_init`) or device dispatch+ // (`agent_deferred_hetero_dispatch`) has run.+ const hasOrchestration = !!(+ appContext?.agentSignal ||+ appContext?.groupId ||+ appContext?.isSubAgent ||+ botContext ||+ botPlatformContext ||+ continuationOperationId ||+ discordContext ||+ evalContext ||+ evalRuntime ||+ params.reservedOperationId ||+ params.topicStartOwnerOperationId ||+ parentOperationId ||+ shareGate+ );+if (isHeteroAgent) {- const heteroResult = await dispatchHeteroAgent(- {- bindTopicWorkingDirectory: (p) =>- bindTopicWorkingDirectory({ topicModel: deps.topicModel }, p),- db: deps.db,- getMarketService: (options) => deps.getMarketService(runFacts, options),- messageModel: deps.messageModel,- resolveDeviceWorkspaceId: deps.resolveDeviceWorkspaceId,- topicModel: deps.topicModel,- userId: deps.userId,- withholdGatewayToken: deps.withholdGatewayToken,- workspaceId: deps.workspaceId,- },- runContext,- {- canManageAgent,- effectiveRequestedDeviceId: turn.effectiveRequestedDeviceId,- heteroType: turn.heteroType,- heterogeneousProvider: turn.heterogeneousProvider,- hooks,- isPublicWorkspaceAgent,- localDeviceId,- maxSteps,- memberDeviceOverride,- operationTaskId,- // The hetero run settles its fee on `heteroFinish` under this id, so the- // fee moves to it as soon as the durable operation row exists.- onOperationCreated: async (operationId) => {- await bindRunFee(runFee, deps.userId, operationId);- await params.onOperationCreated?.(operationId);+ const heteroResult = await traceSendStage('hetero_dispatch', () =>+ dispatchHeteroAgent(+ {+ bindTopicWorkingDirectory: (p) =>+ bindTopicWorkingDirectory({ topicModel: deps.topicModel }, p),+ db: deps.db,+ getMarketService: (options) => deps.getMarketService(runFacts, options),+ messageModel: deps.messageModel,+ resolveDeviceWorkspaceId: deps.resolveDeviceWorkspaceId,+ topicModel: deps.topicModel,+ userId: deps.userId,+ withholdGatewayToken: deps.withholdGatewayToken,+ workspaceId: deps.workspaceId,},- reservedOperationId: params.reservedOperationId,- parentOperationId,- pinnedHeterogeneousTopicModel: turn.pinnedHeterogeneousTopicModel,- pinnedHeterogeneousTopicSources: turn.pinnedHeterogeneousTopicSources,- requestTrigger: requestTriggerMetadata.trigger,- requestedDeviceId: turn.requestedDeviceId,- runAttachments,- selfMessageIds,- topicStartOwnerOperationId: params.topicStartOwnerOperationId,- },+ runContext,+ {+ canManageAgent,+ effectiveRequestedDeviceId: turn.effectiveRequestedDeviceId,+ hasOrchestration,+ heteroType: turn.heteroType,+ heterogeneousProvider: turn.heterogeneousProvider,+ hooks,+ isPublicWorkspaceAgent,+ localDeviceId,+ maxSteps,+ memberDeviceOverride,+ operationTaskId,+ // The hetero run settles its fee on `heteroFinish` under this id, so the+ // fee moves to it as soon as the durable operation row exists.+ onOperationCreated: async (operationId) => {+ await bindRunFee(runFee, deps.userId, operationId);+ await params.onOperationCreated?.(operationId);+ },+ reservedOperationId: params.reservedOperationId,+ parentOperationId,+ pinnedHeterogeneousTopicModel: turn.pinnedHeterogeneousTopicModel,+ pinnedHeterogeneousTopicSources: turn.pinnedHeterogeneousTopicSources,+ requestTrigger: requestTriggerMetadata.trigger,+ requestedDeviceId: turn.requestedDeviceId,+ runAttachments,+ selfMessageIds,+ topicStartOwnerOperationId: params.topicStartOwnerOperationId,+ },+ ),);// A returned dispatch is the run's from here: `heteroFinish` settles a// started run and a refused dispatch settles its error through the same@@ -674,21 +697,7 @@ export const execAgentTurn = async (const deferInit = await shouldDeferOperationInit({autoStart,- hasOrchestration: !!(- appContext?.agentSignal ||- appContext?.groupId ||- appContext?.isSubAgent ||- botContext ||- botPlatformContext ||- continuationOperationId ||- discordContext ||- evalContext ||- evalRuntime ||- params.reservedOperationId ||- params.topicStartOwnerOperationId ||- parentOperationId ||- shareGate- ),+ hasOrchestration,queueRuntimeEnabled: appEnv.enableQueueAgentRuntime === true,request: initRequest,trigger,diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/deferDispatchGate.test.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/deferDispatchGate.test.tsnew file mode 100644index 00000000000..6878d3a9edf--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/deferDispatchGate.test.ts@@ -0,0 +1,37 @@+import { RequestTrigger } from '@lobechat/types';+import { describe, expect, it, vi } from 'vitest';++import { shouldDeferHeteroDispatch } from './deferDispatchGate';++describe('shouldDeferHeteroDispatch', () => {+ const plainSend = { hasOrchestration: false, trigger: RequestTrigger.Chat };+ const flagOn = async () => true;++ it('defers a plain chat send once the flag is on', async () => {+ await expect(shouldDeferHeteroDispatch(plainSend, flagOn)).resolves.toBe(true);+ });++ it('keeps the dispatch synchronous while the flag is off', async () => {+ await expect(shouldDeferHeteroDispatch(plainSend, async () => false)).resolves.toBe(false);+ });++ it('keeps the dispatch synchronous when the flag cannot be read', async () => {+ await expect(+ shouldDeferHeteroDispatch(plainSend, () => Promise.reject(new Error('config down'))),+ ).resolves.toBe(false);+ });++ it.each([+ ['an orchestrated run', { hasOrchestration: true }],+ ['a bot message', { trigger: 'bot' }],+ ['a scheduled run', { trigger: RequestTrigger.Scheduled }],+ ['a run without a trigger', { trigger: undefined }],+ ])('does not read the flag for %s', async (_, override) => {+ const isEnabled = vi.fn(flagOn);++ await expect(shouldDeferHeteroDispatch({ ...plainSend, ...override }, isEnabled)).resolves.toBe(+ false,+ );+ expect(isEnabled).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/deferDispatchGate.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/deferDispatchGate.tsnew file mode 100644index 00000000000..4affbb88958--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/deferDispatchGate.ts@@ -0,0 +1,37 @@+import { RequestTrigger } from '@lobechat/types';++import { getServerFeatureFlagsStateFromRuntimeConfig } from '@/server/featureFlags';++/** A flag that cannot be read keeps the send on the synchronous dispatch. */+export const isDeferredHeteroDispatchEnabled = async (userId: string): Promise<boolean> => {+ const flags = await getServerFeatureFlagsStateFromRuntimeConfig(userId).catch(() => undefined);+ return flags?.enableDeferredHeteroDispatch === true;+};++export interface DeferHeteroDispatchInput {+ /**+ * Set for every caller that is not the plain composer: a group member, an+ * isolation-thread child, a Task run, a reserved (Channel) operation. Those+ * callers act on the dispatch result itself, so it has to be final.+ */+ hasOrchestration: boolean;+ trigger?: string;+}++/**+ * Only a plain chat send may return before its device dispatch completes.+ *+ * The composer already handles a dispatch that fails after the response (the+ * timed-out ack and the woken managed device both settle that way): the error+ * is written onto the assistant message and the run's stream closes. Every+ * other caller reads `success` / `terminalReported` from the result, so it+ * keeps the synchronous dispatch.+ *+ * The flag is read last, so runs that could never defer pay no read for it.+ * Never rejects.+ */+export const shouldDeferHeteroDispatch = async (+ { hasOrchestration, trigger }: DeferHeteroDispatchInput,+ isEnabled: () => Promise<boolean>,+): Promise<boolean> =>+ !hasOrchestration && trigger === RequestTrigger.Chat && (await isEnabled().catch(() => false));diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.tsindex 88923790926..91fe0f90f6e 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.ts@@ -26,10 +26,11 @@ import {import { resolveDeviceWorkingDirectoryConfig } from '../../resolveDeviceWorkingDirectory';import type { ExecRunContext } from '../../types';import { selectCodexDeviceDispatch } from '../codexDeviceRuntime';+import { traceHeteroStage } from '../sendTracing';import type { PreparedHeteroRun } from './prepare';import { scheduleTimedOutDispatchConfirmation } from './timeoutConfirmation';import type { HeteroDispatchDeps, HeteroDispatchInput, HeteroRun } from './types';-import { failHeteroDispatch } from './utils';+import { failHeteroDispatch, settleInOrder } from './utils';const log = debug('lobe-server:ai-agent-service');@@ -92,6 +93,14 @@ export const dispatchToCliDevice = async (heteroPlan: CliDispatchPlan;heteroType: HeteroDispatchInput['heteroType'];heterogeneousProvider: HeteroDispatchInput['heterogeneousProvider'];+ /**+ * For a dispatch that runs after the response, when a Stop can land while+ * it prepares: checked right before the gateway hop (a stopped run is not+ * sent) and right after it (a run stopped mid-hop is cancelled on the+ * device). The synchronous send leaves it out: the client cannot stop a+ * run it has not been told about yet.+ */+ isStopped?: () => Promise<boolean>;prepared: PreparedHeteroRun;},): Promise<ExecAgentResult | undefined> => {@@ -102,6 +111,7 @@ export const dispatchToCliDevice = async (heteroPlan,heteroType,heterogeneousProvider,+ isStopped,prepared,} = params;const {@@ -131,17 +141,43 @@ export const dispatchToCliDevice = async ({ error: 'No bound device', message: 'Hetero agent requires a bound device' },);}- const codexRuntime = await selectCodexDeviceDispatch({- db: deps.db,- heterogeneousProvider,- heteroType,- readSystemInfo: (clientKinds) =>- deviceGateway.readDeviceSystemInfo(deps.userId, dispatchDeviceId, cliDeviceWorkspaceId, {- clientKinds,+ // The Codex runtime, the device row and the Claude Code account are three+ // independent reads keyed only by the device, so they run together. All of+ // them are reads: a rejected Codex runtime below still leaves nothing written.+ // The device row lives in the DB (the gateway only knows live connections),+ // so read it directly rather than via deviceGateway. The bound device may be+ // personal (userId-scoped) or a workspace device (workspace-scoped) — look+ // up both so its defaultCwd resolves.+ const deviceModelForCwd = new DeviceModel(deps.db, deps.userId, deps.workspaceId);+ const [codexRuntime, boundDevice, claudeAccountRouting] = await settleInOrder([+ traceHeteroStage('device codex_runtime', () =>+ selectCodexDeviceDispatch({+ db: deps.db,+ heterogeneousProvider,+ heteroType,+ readSystemInfo: (clientKinds) =>+ deviceGateway.readDeviceSystemInfo(deps.userId, dispatchDeviceId, cliDeviceWorkspaceId, {+ clientKinds,+ }),+ resume: Boolean(resumeSessionId),+ userId: deps.userId,}),- resume: Boolean(resumeSessionId),- userId: deps.userId,- });+ ),+ traceHeteroStage(+ 'device bound_device',+ async () =>+ (await deviceModelForCwd.findByDeviceId(dispatchDeviceId)) ??+ (await deviceModelForCwd.findWorkspaceDeviceById(dispatchDeviceId)),+ ),+ traceHeteroStage('device account_routing', () =>+ resolveClaudeAccountRouting(deps, {+ agentId: resolvedAgentId,+ deviceId: dispatchDeviceId,+ heteroType,+ heterogeneousProvider,+ }),+ ),+ ]);if (codexRuntime.kind === 'error') {return failHeteroDispatch(deps,@@ -153,15 +189,7 @@ export const dispatchToCliDevice = async (const nativeCodex = codexRuntime.kind === 'native' ? codexRuntime : undefined;// Resolve the working directory for the run: a topic-level override- // wins, else the device's user-configured defaultCwd. The device row- // lives in the DB (the gateway only knows live connections), so read- // it directly rather than via deviceGateway.- // The bound device may be personal (userId-scoped) or a workspace- // device (workspace-scoped) — look up both so its defaultCwd resolves.- const deviceModelForCwd = new DeviceModel(deps.db, deps.userId, deps.workspaceId);- const boundDevice =- (await deviceModelForCwd.findByDeviceId(dispatchDeviceId)) ??- (await deviceModelForCwd.findWorkspaceDeviceById(dispatchDeviceId));+ // wins, else the device's user-configured defaultCwd.const dispatchWorkspaceId = cliDeviceWorkspaceId;// Resolve via the shared precedence helper so dispatch, workspace-init,// and the new-topic backfill below all agree on the cwd.@@ -194,13 +222,29 @@ export const dispatchToCliDevice = async (// recorded at agent level (`workingDirByDevice`) when no topic existed.// Persist the resolved cwd onto the topic so the sidebar groups it// under the right project and the next turn reuses the same directory.- await deps.bindTopicWorkingDirectory({- config: deviceCwdConfig,- currentDeviceId: topic?.metadata?.boundDeviceId,- currentWorkingDirectory: topic?.metadata?.workingDirectory,- deviceId: dispatchDeviceId,- topicId,- });+ //+ // The registry recheck is a read the topic write cannot change, so it runs+ // alongside it and still lands right before the dispatch. It fails closed:+ // a missing device refuses the dispatch, and a failed read throws before it.+ const [, authorizationError] = await settleInOrder([+ traceHeteroStage('device bind_working_directory', () =>+ deps.bindTopicWorkingDirectory({+ config: deviceCwdConfig,+ currentDeviceId: topic?.metadata?.boundDeviceId,+ currentWorkingDirectory: topic?.metadata?.workingDirectory,+ deviceId: dispatchDeviceId,+ topicId,+ }),+ ),+ traceHeteroStage('device authorization', () =>+ resolveDeviceDispatchAuthorizationFailure(+ deps.db,+ deps.userId,+ dispatchDeviceId,+ dispatchWorkspaceId,+ ),+ ),+ ]);// Build only device-relevant context instead of reusing the cloud-sandbox one// (which describes an ephemeral /workspace + pre-cloned repos and would mislead@@ -220,42 +264,39 @@ export const dispatchToCliDevice = async (}): undefined;- const claudeAccountRouting = await resolveClaudeAccountRouting(deps, {- agentId: resolvedAgentId,- deviceId: dispatchDeviceId,- heteroType,- heterogeneousProvider,- });+ // A Stop that settled the run while it prepared found no process to cancel;+ // sending it now would start a CLI nobody can see. The stop path already+ // settled the operation and its marker, so there is nothing left to write.+ if (!authorizationError && (await isStopped?.())) {+ log('execAgent: op=%s stopped while its dispatch prepared, not dispatching', operationId);+ return undefined;+ }- const authorizationError = await resolveDeviceDispatchAuthorizationFailure(- deps.db,- deps.userId,- dispatchDeviceId,- dispatchWorkspaceId,- );// Anything that touches the run after this instant proves it started.const dispatchedAt = new Date();const result = authorizationError? { error: 'DEVICE_NOT_FOUND', errorData: authorizationError, success: false }- : await deviceGateway.dispatchAgentRun({- ...heteroParams,- agentId: resolvedAgentId,- // Only a live client advertising the native protocol receives these wrapper flags.- args: nativeCodex ? [...(heteroExecArgs ?? []), ...nativeCodex.args] : heteroExecArgs,- ...(claudeAccountRouting && { claudeAccountRouting }),- clientKinds: nativeCodex?.clientKinds,- cwd: deviceCwd,- deviceId: dispatchDeviceId,- resumeFallbackSystemContext: deviceResumeFallbackSystemContext,- systemContext: deviceSystemContext,- // Route to the workspace pool when this is a workspace device; the- // operation JWT stays member-scoped (the run belongs to the member).- workspaceId: dispatchWorkspaceId,- // Topic scope for device-side heteroIngest/heteroFinish. Distinct- // from the routing workspace above: a workspace topic on a personal- // device still has to write back under `deps.workspaceId`.- ingestWorkspaceId: deps.workspaceId,- });+ : await traceHeteroStage('device gateway_dispatch', () =>+ deviceGateway.dispatchAgentRun({+ ...heteroParams,+ agentId: resolvedAgentId,+ // Only a live client advertising the native protocol receives these wrapper flags.+ args: nativeCodex ? [...(heteroExecArgs ?? []), ...nativeCodex.args] : heteroExecArgs,+ ...(claudeAccountRouting && { claudeAccountRouting }),+ clientKinds: nativeCodex?.clientKinds,+ cwd: deviceCwd,+ deviceId: dispatchDeviceId,+ resumeFallbackSystemContext: deviceResumeFallbackSystemContext,+ systemContext: deviceSystemContext,+ // Route to the workspace pool when this is a workspace device; the+ // operation JWT stays member-scoped (the run belongs to the member).+ workspaceId: dispatchWorkspaceId,+ // Topic scope for device-side heteroIngest/heteroFinish. Distinct+ // from the routing workspace above: a workspace topic on a personal+ // device still has to write back under `deps.workspaceId`.+ ingestWorkspaceId: deps.workspaceId,+ }),+ );if (!result.success) {const finalize = {detail: result.error ?? 'Device dispatch failed',@@ -285,16 +326,37 @@ export const dispatchToCliDevice = async (scheduleTimedOutDispatchConfirmation(deps, run, { dispatchedAt, finalize, result: failure });}+ // A Stop that landed during the gateway hop may have found no process yet.+ // The device registers the process before it acks, so cancel it now; the+ // stop path already settled the operation, so the route is not recorded.+ if (result.success && (await isStopped?.())) {+ log('execAgent: op=%s stopped during its dispatch, cancelling on the device', operationId);+ await traceHeteroStage('device cancel_stopped_dispatch', () =>+ deviceGateway.executeToolCall(+ { deviceId: dispatchDeviceId, userId: deps.userId, workspaceId: dispatchWorkspaceId },+ {+ apiName: 'cancelHeteroTask',+ arguments: JSON.stringify({ signal: 'SIGINT', taskId: operationId }),+ identifier: 'cancelHeteroTask',+ },+ 10_000,+ ),+ ).catch((err) => log('execAgent: cancelling a stopped dispatch failed: %O', err));+ return undefined;+ }+// Local CLI hetero agents dispatch to a device just like remote platform// agents, so persist the device route once the dispatch is accepted (or may// have been, after a timeout).// interruptTask uses these fields to find and stop the native process.try {- const patched = await deps.topicModel.patchRunningOperation(topicId, operationId, {- deviceId: dispatchDeviceId,- deviceWorkspaceId: dispatchWorkspaceId,- heteroType,- });+ const patched = await traceHeteroStage('device patch_running_operation', () =>+ deps.topicModel.patchRunningOperation(topicId, operationId, {+ deviceId: dispatchDeviceId,+ deviceWorkspaceId: dispatchWorkspaceId,+ heteroType,+ }),+ );log('execAgent: patch runningOperation device info=%s deviceId=%s heteroType=%s op=%s',patched,@@ -309,6 +371,77 @@ export const dispatchToCliDevice = async (return undefined;};+/** Whether the run settled (stopped, failed) before a dispatch run after the response. */+const isRunStopped = async (deps: HeteroDispatchDeps, run: HeteroRun) =>+ !(await new AgentOperationModel(deps.db, deps.userId, deps.workspaceId).isRunningOnTopic(+ run.operationId,+ run.topicId,+ ));++/** Off the request path nothing else would settle the run, so a throw is its error. */+const failDispatchAfterResponse = async (+ deps: HeteroDispatchDeps,+ run: HeteroRun,+ deviceId: string,+ error: unknown,+ label: string,+) => {+ const message = error instanceof Error ? error.message : String(error);+ console.error(`[HeteroDispatch] ${label}`, {+ deviceId,+ error: message,+ operationId: run.operationId,+ });+ await failHeteroDispatch(+ deps,+ run,+ { detail: message, message: 'Hetero agent device dispatch failed' },+ { error: message, message: 'Hetero agent device dispatch failed' },+ );+};++/**+ * Dispatch to an online device after the response (`agent_deferred_hetero_dispatch`).+ *+ * The run is already durable and its marker names the device, so the client can+ * stop it and render it as soon as `execAgent` returns; only the device steps+ * (Codex runtime, working directory, account routing, the registry recheck and+ * the gateway hop) move off the send. A refused dispatch settles through+ * `failHeteroDispatch` exactly like an immediate one: the error lands on the+ * assistant message and the run's stream closes. A run stopped before the+ * gateway hop is not dispatched, and one stopped during it is cancelled on+ * the device (see `isStopped` on `dispatchToCliDevice`).+ */+export const deferCliDeviceDispatch = (+ deps: HeteroDispatchDeps,+ run: HeteroRun,+ params: CliDispatchParams & { heteroPlan: Extract<CliDispatchPlan, { kind: 'device' }> },+): void => {+ const { deviceId } = params.heteroPlan;+ afterUnscoped(() =>+ traceHeteroStage('deferred_device_dispatch', async () => {+ try {+ if (await isRunStopped(deps, run)) {+ log('execAgent: op=%s settled before its deferred dispatch, skipping', run.operationId);+ return;+ }+ await dispatchToCliDevice(deps, run, {+ ...params,+ isStopped: () => isRunStopped(deps, run),+ });+ } catch (error) {+ await failDispatchAfterResponse(+ deps,+ run,+ deviceId,+ error,+ 'Deferred device dispatch failed',+ );+ }+ }),+ );+};+/*** Wake a managed cloud device, then dispatch to it once it is online.*@@ -343,7 +476,7 @@ export const dispatchToWakingCliDevice = async (target: heteroPlan.target,};- if (!(await wakeManagedDevice(deps.userId, device))) {+ if (!(await traceHeteroStage('wake_device', () => wakeManagedDevice(deps.userId, device)))) {log('execAgent: wake refused for managed device %s, dispatching op=%s now',heteroPlan.deviceId,@@ -352,9 +485,7 @@ export const dispatchToWakingCliDevice = async (return dispatchToCliDevice(deps, run, { ...dispatchParams, heteroPlan: devicePlan });}- const operationModel = new AgentOperationModel(deps.db, deps.userId, deps.workspaceId);- const isStopped = async () =>- !(await operationModel.isRunningOnTopic(run.operationId, run.topicId));+ const isStopped = () => isRunStopped(deps, run);const dispatchWhenOnline = async () => {try {@@ -374,20 +505,18 @@ export const dispatchToWakingCliDevice = async (online,run.operationId,);- await dispatchToCliDevice(deps, run, { ...dispatchParams, heteroPlan: devicePlan });- } catch (error) {- // Off the request path nothing else would settle the run.- const message = error instanceof Error ? error.message : String(error);- console.error('[HeteroDispatch] Dispatch to a woken managed device failed', {- deviceId: heteroPlan.deviceId,- error: message,- operationId: run.operationId,+ await dispatchToCliDevice(deps, run, {+ ...dispatchParams,+ heteroPlan: devicePlan,+ isStopped,});- await failHeteroDispatch(+ } catch (error) {+ await failDispatchAfterResponse(deps,run,- { detail: message, message: 'Hetero agent device dispatch failed' },- { error: message, message: 'Hetero agent device dispatch failed' },+ heteroPlan.deviceId,+ error,+ 'Dispatch to a woken managed device failed',);}};diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.deferredDispatch.test.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.deferredDispatch.test.tsnew file mode 100644index 00000000000..9b89b75d0d3--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.deferredDispatch.test.ts@@ -0,0 +1,449 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { ExecRunContext } from '../../types';+import type { HeteroDispatchDeps, HeteroDispatchInput } from '.';+import { dispatchHeteroAgent } from '.';++const mocks = vi.hoisted(() => {+ const spans = { ended: [] as string[], failed: [] as string[] };+ return {+ afterWork: [] as (() => Promise<unknown> | unknown)[],+ completeOperation: vi.fn(),+ createOperationMetadata: vi.fn(),+ dispatchAgentRun: vi.fn(),+ executeToolCall: vi.fn(),+ featureFlags: vi.fn(),+ finalizeHeteroDispatchError: vi.fn(),+ findByDeviceId: vi.fn(),+ isRunningOnTopic: vi.fn(),+ planDeviceRouting: vi.fn(),+ publishAgentRuntimeInit: vi.fn(),+ recordStart: vi.fn(),+ resolveDeviceDispatchAuthorizationFailure: vi.fn(),+ resolveSandboxSessionConfig: vi.fn(),+ selectCodexDeviceDispatch: vi.fn(),+ signHeteroOperationJWT: vi.fn(),+ signUserJWT: vi.fn(),+ span: (name: string) => ({+ end: vi.fn(() => spans.ended.push(name)),+ setAttribute: vi.fn(),+ setStatus: vi.fn(() => spans.failed.push(name)),+ }),+ spans,+ waitForVerifyPlan: vi.fn(),+ };+});++vi.mock('@lobechat/observability-otel/modules/agent-runtime', () => ({+ tracer: {+ startActiveSpan: (name: string, fn: (span: unknown) => unknown) => fn(mocks.span(name)),+ },+}));++vi.mock('@/server/featureFlags', () => ({+ getServerFeatureFlagsStateFromRuntimeConfig: mocks.featureFlags,+}));++vi.mock('@/server/utils/scheduleAfterResponse', () => ({+ afterUnscoped: (work: () => Promise<unknown> | unknown) => {+ mocks.afterWork.push(work);+ },+}));++vi.mock('@/database/models/agentOperation', () => ({+ AgentOperationModel: vi.fn().mockImplementation(function () {+ return { isRunningOnTopic: mocks.isRunningOnTopic };+ }),+}));++vi.mock('@/server/services/deviceGateway/managedDeviceWake', () => ({+ findWakeableManagedDevices: vi.fn().mockResolvedValue([]),+ waitForManagedDeviceOnline: vi.fn(),+ wakeManagedDevice: vi.fn(),+}));++vi.mock('@/server/services/agentRuntime/CompletionLifecycle', () => ({+ CompletionLifecycle: vi.fn().mockImplementation(function () {+ return {+ completeOperation: mocks.completeOperation,+ recordStart: mocks.recordStart,+ waitForVerifyPlan: mocks.waitForVerifyPlan,+ };+ }),+}));++vi.mock('@/server/services/agentRuntime/hooks', () => ({+ hookDispatcher: {+ canDeliver: vi.fn().mockReturnValue(false),+ getSerializedHooks: vi.fn().mockReturnValue([]),+ register: vi.fn(),+ unregister: vi.fn(),+ },+}));++vi.mock('@/server/services/heterogeneousAgent', () => ({+ HeterogeneousAgentService: vi.fn().mockImplementation(function () {+ return { getHeterogeneousResumeSessionId: vi.fn().mockResolvedValue(undefined) };+ }),+}));++vi.mock('@/libs/trpc/utils/internalJwt', () => ({+ signHeteroOperationJWT: mocks.signHeteroOperationJWT,+ signUserJWT: mocks.signUserJWT,+}));++vi.mock('@/server/modules/AgentRuntime/factory', () => ({+ createAgentStateManager: () => ({ createOperationMetadata: mocks.createOperationMetadata }),+ createStreamEventManager: () => ({ publishAgentRuntimeInit: mocks.publishAgentRuntimeInit }),+}));++vi.mock('@/server/services/agentQuota', () => ({+ AgentQuotaService: vi.fn(function () {+ return {+ planDeviceRouting: mocks.planDeviceRouting,+ resolveDeviceRowId: async (id?: string) => (id ? `row-${id}` : undefined),+ };+ }),+}));++vi.mock('@/server/services/deviceGateway', () => ({+ deviceGateway: {+ dispatchAgentRun: mocks.dispatchAgentRun,+ executeToolCall: mocks.executeToolCall,+ readDeviceSystemInfo: vi.fn(),+ },+}));++vi.mock('@/server/services/deviceGateway/dispatchAuthorization', () => ({+ resolveDeviceDispatchAuthorizationFailure: mocks.resolveDeviceDispatchAuthorizationFailure,+}));++vi.mock('@/database/models/device', () => ({+ DeviceModel: vi.fn().mockImplementation(function () {+ return {+ findByDeviceId: mocks.findByDeviceId,+ findWorkspaceDeviceById: vi.fn().mockResolvedValue(undefined),+ };+ }),+}));++vi.mock('@/server/services/sandbox/session', () => ({+ resolveSandboxSessionConfig: mocks.resolveSandboxSessionConfig,+}));++vi.mock('../finalizeHeteroDispatchError', () => ({+ finalizeHeteroDispatchError: mocks.finalizeHeteroDispatchError,+}));++vi.mock('./timeoutConfirmation', () => ({ scheduleTimedOutDispatchConfirmation: vi.fn() }));++vi.mock('../codexDeviceRuntime', () => ({+ selectCodexDeviceDispatch: mocks.selectCodexDeviceDispatch,+}));++/** Resolves only once `count` callers wait on it: sequential callers deadlock. */+const createBarrier = (count: number) => {+ const started: string[] = [];+ let open: () => void = () => {};+ const opened = new Promise<void>((resolve) => {+ open = resolve;+ });+ return {+ gate:+ <T>(stage: string, value: T) =>+ async () => {+ started.push(stage);+ if (started.length >= count) open();+ await opened;+ return value;+ },+ started,+ };+};++const createDeps = (overrides: Partial<HeteroDispatchDeps> = {}) => {+ const topicModel = {+ appendRunningOperationChild: vi.fn().mockResolvedValue(true),+ findById: vi.fn().mockResolvedValue({ metadata: {} }),+ patchRunningOperation: vi.fn().mockResolvedValue(true),+ updateMetadata: vi.fn().mockResolvedValue(undefined),+ };+ const deps = {+ bindTopicWorkingDirectory: vi.fn().mockResolvedValue(undefined),+ db: {} as any,+ getMarketService: vi.fn().mockRejectedValue(new Error('market unavailable')),+ messageModel: { query: vi.fn().mockResolvedValue([]) } as any,+ resolveDeviceWorkspaceId: vi.fn().mockResolvedValue(undefined),+ topicModel: topicModel as any,+ userId: 'user-1',+ withholdGatewayToken: false,+ ...overrides,+ } satisfies HeteroDispatchDeps;+ return { deps, topicModel };+};++const deviceCtx = (overrides: Partial<ExecRunContext> = {}): ExecRunContext =>+ ({+ agentConfig: {+ agencyConfig: {+ boundDeviceId: 'dev-1',+ executionTarget: 'device',+ heterogeneousProvider: { type: 'claude-code' },+ },+ id: 'agent-1',+ userId: 'user-1',+ },+ assistantMessageId: 'asst-1',+ canUseDevice: true,+ deviceAccessReason: 'owner',+ parentMessageId: 'parent-1',+ persistAgentId: 'agent-1',+ prompt: 'hello',+ resolvedAgentId: 'agent-1',+ runFacts: {} as any,+ topicId: 'topic-1',+ trigger: 'chat',+ userMessageId: 'user-msg-1',+ ...overrides,+ }) as ExecRunContext;++const plainInput = (overrides: Partial<HeteroDispatchInput> = {}): HeteroDispatchInput => ({+ canManageAgent: true,+ hasOrchestration: false,+ heteroType: 'claude-code',+ isPublicWorkspaceAgent: false,+ runAttachments: { audioList: [], fileList: [], imageList: [], videoList: [] },+ selfMessageIds: new Set(),+ ...overrides,+});++const runAfterResponse = async () => {+ const work = mocks.afterWork.splice(0);+ for (const fn of work) await fn();+};++beforeEach(() => {+ vi.clearAllMocks();+ mocks.afterWork.length = 0;+ mocks.spans.ended.length = 0;+ mocks.spans.failed.length = 0;+ mocks.featureFlags.mockResolvedValue({ enableDeferredHeteroDispatch: false });+ mocks.isRunningOnTopic.mockResolvedValue(true);+ mocks.recordStart.mockResolvedValue(true);+ mocks.waitForVerifyPlan.mockResolvedValue(undefined);+ mocks.signHeteroOperationJWT.mockResolvedValue('op-jwt');+ mocks.signUserJWT.mockResolvedValue('user-jwt');+ mocks.finalizeHeteroDispatchError.mockResolvedValue(true);+ mocks.findByDeviceId.mockResolvedValue(undefined);+ mocks.resolveDeviceDispatchAuthorizationFailure.mockResolvedValue(undefined);+ mocks.resolveSandboxSessionConfig.mockResolvedValue(undefined);+ mocks.selectCodexDeviceDispatch.mockResolvedValue({ kind: 'exec' });+ mocks.dispatchAgentRun.mockResolvedValue({ success: true });+ mocks.planDeviceRouting.mockResolvedValue(null);+ mocks.publishAgentRuntimeInit.mockResolvedValue('init');+ mocks.createOperationMetadata.mockResolvedValue(undefined);+});++describe('dispatchHeteroAgent — overlapping waits', () => {+ it('prepares and routes the run while it waits for the verify plan', async () => {+ const barrier = createBarrier(3);+ mocks.waitForVerifyPlan.mockImplementation(barrier.gate('verify', undefined));+ mocks.signHeteroOperationJWT.mockImplementation(barrier.gate('jwt', 'op-jwt'));+ const { deps } = createDeps({+ resolveDeviceWorkspaceId: vi.fn(barrier.gate('routing', undefined)),+ });++ const result = await dispatchHeteroAgent(deps, deviceCtx(), plainInput());++ expect(barrier.started.toSorted()).toEqual(['jwt', 'routing', 'verify']);+ expect(result.success).toBe(true);+ expect(mocks.dispatchAgentRun).toHaveBeenCalledTimes(1);+ });++ it('reads the Codex runtime, the device row and the account routing together', async () => {+ const barrier = createBarrier(3);+ mocks.selectCodexDeviceDispatch.mockImplementation(barrier.gate('codex', { kind: 'exec' }));+ mocks.findByDeviceId.mockImplementation(barrier.gate('device', undefined));+ mocks.planDeviceRouting.mockImplementation(barrier.gate('account', null));+ const { deps } = createDeps();++ await dispatchHeteroAgent(deps, deviceCtx(), plainInput());++ expect(barrier.started.toSorted()).toEqual(['account', 'codex', 'device']);+ expect(mocks.dispatchAgentRun).toHaveBeenCalledTimes(1);+ });++ it('writes nothing when the Codex runtime refuses the run', async () => {+ mocks.selectCodexDeviceDispatch.mockResolvedValue({ kind: 'error', message: 'too old' });+ const { deps } = createDeps();++ const result = await dispatchHeteroAgent(deps, deviceCtx(), plainInput());++ expect(result.success).toBe(false);+ expect(deps.bindTopicWorkingDirectory).not.toHaveBeenCalled();+ expect(mocks.dispatchAgentRun).not.toHaveBeenCalled();+ });++ it('fails closed when the registry recheck throws', async () => {+ mocks.resolveDeviceDispatchAuthorizationFailure.mockRejectedValue(new Error('db down'));+ const { deps } = createDeps();++ await expect(dispatchHeteroAgent(deps, deviceCtx(), plainInput())).rejects.toThrow('db down');+ expect(mocks.dispatchAgentRun).not.toHaveBeenCalled();+ expect(mocks.spans.failed).toContain('hetero_dispatch device authorization');+ expect(mocks.spans.ended).toContain('hetero_dispatch device authorization');+ });++ it('closes the span of a stage that throws and records its error', async () => {+ mocks.recordStart.mockRejectedValue(new Error('insert failed'));+ const { deps } = createDeps();++ await expect(dispatchHeteroAgent(deps, deviceCtx(), plainInput())).rejects.toThrow(+ 'insert failed',+ );+ expect(mocks.spans.failed).toEqual(['hetero_dispatch record_start']);+ expect(mocks.spans.ended).toEqual(['hetero_dispatch record_start']);+ });+});++describe('dispatchHeteroAgent — agent_deferred_hetero_dispatch', () => {+ beforeEach(() => {+ mocks.featureFlags.mockResolvedValue({ enableDeferredHeteroDispatch: true });+ });++ it('answers a plain chat send before the device dispatch, then dispatches', async () => {+ const { deps, topicModel } = createDeps();++ const result = await dispatchHeteroAgent(deps, deviceCtx(), plainInput());++ expect(result).toMatchObject({ status: 'created', success: true, token: 'user-jwt' });+ // The marker naming the device is written before the response, so a stop+ // request can reach the run as soon as the client has it.+ expect(topicModel.updateMetadata).toHaveBeenCalledWith(+ 'topic-1',+ expect.objectContaining({+ runningOperation: expect.objectContaining({ deviceId: 'dev-1' }),+ }),+ );+ expect(mocks.publishAgentRuntimeInit).toHaveBeenCalledTimes(1);+ expect(mocks.dispatchAgentRun).not.toHaveBeenCalled();++ await runAfterResponse();++ expect(mocks.dispatchAgentRun).toHaveBeenCalledWith(+ expect.objectContaining({ deviceId: 'dev-1', operationId: result.operationId }),+ );+ expect(topicModel.patchRunningOperation).toHaveBeenCalledTimes(1);+ expect(mocks.spans.ended).toContain('hetero_dispatch deferred_device_dispatch');+ });++ it('puts a refused deferred dispatch on the assistant message', async () => {+ mocks.dispatchAgentRun.mockResolvedValue({ error: 'DEVICE_OFFLINE', success: false });+ const { deps } = createDeps();++ const result = await dispatchHeteroAgent(deps, deviceCtx(), plainInput());+ expect(result.success).toBe(true);++ await runAfterResponse();++ expect(mocks.finalizeHeteroDispatchError).toHaveBeenCalledWith(+ deps,+ expect.objectContaining({+ assistantMessageId: 'asst-1',+ detail: 'DEVICE_OFFLINE',+ operationId: result.operationId,+ }),+ );+ });++ it('settles a deferred dispatch that throws as the run error', async () => {+ mocks.resolveDeviceDispatchAuthorizationFailure.mockRejectedValue(new Error('db down'));+ const { deps } = createDeps();++ await dispatchHeteroAgent(deps, deviceCtx(), plainInput());+ await runAfterResponse();++ expect(mocks.dispatchAgentRun).not.toHaveBeenCalled();+ expect(mocks.finalizeHeteroDispatchError).toHaveBeenCalledWith(+ deps,+ expect.objectContaining({+ detail: 'db down',+ message: 'Hetero agent device dispatch failed',+ }),+ );+ });++ it('does not dispatch a run stopped while its dispatch prepared', async () => {+ // Live when the deferred work starts, stopped by the time the device steps finish.+ mocks.isRunningOnTopic.mockResolvedValueOnce(true).mockResolvedValue(false);+ const { deps, topicModel } = createDeps();++ await dispatchHeteroAgent(deps, deviceCtx(), plainInput());+ await runAfterResponse();++ expect(mocks.dispatchAgentRun).not.toHaveBeenCalled();+ expect(mocks.executeToolCall).not.toHaveBeenCalled();+ expect(topicModel.patchRunningOperation).not.toHaveBeenCalled();+ expect(mocks.finalizeHeteroDispatchError).not.toHaveBeenCalled();+ });++ it('cancels on the device a run stopped during the gateway hop', async () => {+ mocks.isRunningOnTopic+ .mockResolvedValueOnce(true)+ .mockResolvedValueOnce(true)+ .mockResolvedValue(false);+ mocks.executeToolCall.mockResolvedValue({ success: true });+ const { deps, topicModel } = createDeps();++ const result = await dispatchHeteroAgent(deps, deviceCtx(), plainInput());+ await runAfterResponse();++ expect(mocks.dispatchAgentRun).toHaveBeenCalledTimes(1);+ expect(mocks.executeToolCall).toHaveBeenCalledWith(+ expect.objectContaining({ deviceId: 'dev-1' }),+ expect.objectContaining({+ apiName: 'cancelHeteroTask',+ arguments: JSON.stringify({ signal: 'SIGINT', taskId: result.operationId }),+ }),+ 10_000,+ );+ expect(topicModel.patchRunningOperation).not.toHaveBeenCalled();+ expect(mocks.finalizeHeteroDispatchError).not.toHaveBeenCalled();+ });++ it('does not dispatch a run stopped before the deferred dispatch started', async () => {+ mocks.isRunningOnTopic.mockResolvedValue(false);+ const { deps } = createDeps();++ await dispatchHeteroAgent(deps, deviceCtx(), plainInput());+ await runAfterResponse();++ expect(mocks.dispatchAgentRun).not.toHaveBeenCalled();+ expect(mocks.finalizeHeteroDispatchError).not.toHaveBeenCalled();+ });++ it.each<[string, Partial<ExecRunContext>, Partial<HeteroDispatchInput>]>([+ ['an orchestrated caller', {}, { hasOrchestration: true }],+ ['a caller that does not say', {}, { hasOrchestration: undefined }],+ ['a Task run', {}, { operationTaskId: 'task-1' }],+ ['a bot message', { trigger: 'bot' }, {}],+ ])('dispatches synchronously for %s without reading the flag', async (_, ctx, input) => {+ const { deps } = createDeps();++ await dispatchHeteroAgent(deps, deviceCtx(ctx), plainInput(input));++ expect(mocks.dispatchAgentRun).toHaveBeenCalledTimes(1);+ expect(mocks.afterWork).toHaveLength(0);+ expect(mocks.featureFlags).not.toHaveBeenCalled();+ });++ it('dispatches synchronously while the flag is off', async () => {+ mocks.featureFlags.mockResolvedValue({ enableDeferredHeteroDispatch: false });+ const { deps } = createDeps();++ await dispatchHeteroAgent(deps, deviceCtx(), plainInput());++ expect(mocks.dispatchAgentRun).toHaveBeenCalledTimes(1);+ expect(mocks.afterWork).toHaveLength(0);+ });+});diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.tsindex 0e28e691a60..cd84a6c2836 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.ts@@ -7,7 +7,6 @@ import { resolveHeterogeneousRuntimeConfig } from '@lobechat/types';import { nanoid } from '@lobechat/utils';import debug from 'debug';-import { resolveExecutionPlan, resolveWorkspaceScoped } from '@/helpers/executionTarget';import { signUserJWT } from '@/libs/trpc/utils/internalJwt';import {createAgentStateManager,@@ -15,16 +14,17 @@ import {} from '@/server/modules/AgentRuntime/factory';import { CompletionLifecycle } from '@/server/services/agentRuntime/CompletionLifecycle';import { hookDispatcher } from '@/server/services/agentRuntime/hooks';-import { findWakeableManagedDevices } from '@/server/services/deviceGateway/managedDeviceWake';-import { supportsCloudHeterogeneousSandbox } from '../../helpers/heteroErrors';import type { ExecRunContext } from '../../types';-import { dispatchToCliDevice, dispatchToWakingCliDevice } from './device';+import { traceHeteroStage } from '../sendTracing';+import { isDeferredHeteroDispatchEnabled, shouldDeferHeteroDispatch } from './deferDispatchGate';+import { deferCliDeviceDispatch, dispatchToCliDevice, dispatchToWakingCliDevice } from './device';import { prepareHeteroRun } from './prepare';import { dispatchToPlatformDevice } from './remote';+import { resolveHeteroRouting } from './routing';import { spawnInCloudSandbox } from './sandbox';import type { HeteroDispatchDeps, HeteroDispatchInput, HeteroRun } from './types';-import { failHeteroDispatch, heteroErrorResult } from './utils';+import { failHeteroDispatch, heteroErrorResult, settleInOrder } from './utils';export type { HeteroDispatchDeps, HeteroDispatchInput } from './types';@@ -62,20 +62,13 @@ export const dispatchHeteroAgent = async (userMessageId,} = ctx;const {- canManageAgent,- effectiveRequestedDeviceId,heteroType,heterogeneousProvider,hooks,- isPublicWorkspaceAgent,- localDeviceId,maxSteps,- memberDeviceOverride,operationTaskId,parentOperationId,pinnedHeterogeneousTopicModel,- requestTrigger,- requestedDeviceId,topicStartOwnerOperationId,} = input;@@ -112,36 +105,78 @@ export const dispatchHeteroAgent = async (// re-authorizes its operation token against this exact principal. Do not// mint a token or dispatch/spawn when persistence fails.const completionLifecycle = new CompletionLifecycle(deps.db, deps.userId, deps.workspaceId);- const operationPersisted = await completionLifecycle.recordStart({- requireReservation: !!input.reservedOperationId,- agentId: persistAgentId,- appContext: { ...appContext, sourceMessageId: userMessageId },- chatGroupId: appContext?.groupId ?? null,- maxSteps,- metadata: {- _hooks: serializedHooks,- assistantMessageId,- heterogeneousRuntimeConfig: runtimeConfig,- },- operationId,- parentOperationId,- provider: heteroType,- taskId: operationTaskId ?? null,- threadId: appContext?.threadId ?? null,- topicId,- trigger,- });+ const operationPersisted = await traceHeteroStage('record_start', () =>+ completionLifecycle.recordStart({+ requireReservation: !!input.reservedOperationId,+ agentId: persistAgentId,+ appContext: { ...appContext, sourceMessageId: userMessageId },+ chatGroupId: appContext?.groupId ?? null,+ maxSteps,+ metadata: {+ _hooks: serializedHooks,+ assistantMessageId,+ heterogeneousRuntimeConfig: runtimeConfig,+ },+ operationId,+ parentOperationId,+ provider: heteroType,+ taskId: operationTaskId ?? null,+ threadId: appContext?.threadId ?? null,+ topicId,+ trigger,+ }),+ );if (!operationPersisted) {hookDispatcher.unregister(operationId);throw new Error('Failed to persist heterogeneous agent operation');}- await input.onOperationCreated?.(operationId);+ await traceHeteroStage('operation_created', async () => input.onOperationCreated?.(operationId));++ // Only a plain composer send may answer before its device dispatch; the flag+ // read overlaps the reads below and never rejects.+ const deferDispatchPromise = shouldDeferHeteroDispatch(+ {+ // A Task run and an isolation-thread child are settled by callers that+ // read the result, on top of what `execAgent` counts as orchestration.+ hasOrchestration: Boolean(+ input.hasOrchestration !== false ||+ parentOperationId ||+ topicStartOwnerOperationId ||+ appContext?.isolationThread ||+ operationTaskId ||+ input.reservedOperationId,+ ),+ trigger,+ },+ () => isDeferredHeteroDispatchEnabled(deps.userId),+ );- // The builder runs elsewhere and this request ends once it is dispatched, so- // the plan has to be in place first or the builder finds no criteria to file- // evidence against.- await completionLifecycle.waitForVerifyPlan(operationId);+ // Three independent waits, overlapped:+ // - the verify plan: the builder runs elsewhere and this request ends once+ // it is dispatched, so the plan has to be in place before the dispatch or+ // the builder finds no criteria to file evidence against. It never throws,+ // and neither the preparation nor the routing reads the plan;+ // - the run preparation: resume session, operation JWT, topic repos, GitHub+ // token, recovery history, sandbox placement, system contexts and the CLI+ // request (the JWT is still minted only after the row above persisted);+ // - the routing: execution plans and device workspaces, reads only.+ // A failure rethrows in this order, the order they used to run in.+ const [, prepared, routing] = await settleInOrder([+ traceHeteroStage('wait_verify_plan', () => completionLifecycle.waitForVerifyPlan(operationId)),+ traceHeteroStage('prepare', () => prepareHeteroRun(deps, ctx, input, operationId)),+ traceHeteroStage('resolve_routing', () => resolveHeteroRouting(deps, ctx, input)),+ ]);+ const {+ cliDeviceId,+ cliDeviceWorkspaceId,+ deviceAccessDenied,+ deviceHeteroPlan,+ remoteDeviceId,+ remoteDeviceUserId,+ remoteDeviceWorkspaceId,+ wakeableCliDevices,+ } = routing;const run: HeteroRun = {agentId: resolvedAgentId,@@ -151,82 +186,6 @@ export const dispatchHeteroAgent = async (userMessageId: userMessageId ?? parentMessageId ?? '',};- // Resume session, operation JWT, topic repos, GitHub token, recovery- // history, sandbox placement, system contexts and the CLI request.- const prepared = await prepareHeteroRun(deps, ctx, input, operationId);-- const platformPlan = isRemoteHetero- ? resolveExecutionPlan({- agencyConfig: agentConfig.agencyConfig,- canUseDevice,- clientExecutionAvailable: Boolean(localDeviceId),- isHetero: true,- localDeviceId,- requestedDeviceId: effectiveRequestedDeviceId,- sandboxExecutionAvailable: false,- trigger: requestTrigger,- workspaceScoped: resolveWorkspaceScoped(- isPublicWorkspaceAgent && !canManageAgent,- memberDeviceOverride,- ),- })- : undefined;- const remoteDeviceId = platformPlan?.kind === 'device' ? platformPlan.deviceId : undefined;- const remoteDeviceWorkspaceId = remoteDeviceId- ? await deps.resolveDeviceWorkspaceId(remoteDeviceId)- : undefined;- const usesCallersPersonalDevice =- platformPlan?.kind === 'device' &&- !remoteDeviceWorkspaceId &&- (effectiveRequestedDeviceId === remoteDeviceId ||- (platformPlan.target === 'local' &&- agentConfig.agencyConfig?.executionTargetSelectionPolicy !== 'fixed') ||- (!canManageAgent && memberDeviceOverride?.boundDeviceId === remoteDeviceId));- const remoteDeviceUserId = usesCallersPersonalDevice- ? deps.userId- : (agentConfig.userId ?? deps.userId);-- // Resolve CLI-device routing before persisting the marker. Cancellation- // must address the same device even though local CLI agents use a different- // dispatch transport from notify-based platform agents.- // A bound managed cloud device that is offline resolves to- // `device-wakeable`: it is woken and the dispatch waits for it.- const wakeableCliDevices =- !isRemoteHetero && canUseDevice- ? await findWakeableManagedDevices(- { db: deps.db, userId: deps.userId, workspaceId: deps.workspaceId },- [requestedDeviceId, agentConfig.agencyConfig?.boundDeviceId],- )- : [];- const cliPlanParams = {- agencyConfig: agentConfig.agencyConfig,- clientExecutionAvailable: false,- isHetero: true,- requestedDeviceId,- sandboxExecutionAvailable: supportsCloudHeterogeneousSandbox(heteroType),- trigger: requestTrigger,- wakeableDeviceIds: wakeableCliDevices.map((device) => device.deviceId),- };- const deviceHeteroPlan = !isRemoteHetero- ? resolveExecutionPlan({ ...cliPlanParams, canUseDevice })- : undefined;- const cliDeviceId =- deviceHeteroPlan?.kind === 'device' || deviceHeteroPlan?.kind === 'device-wakeable'- ? deviceHeteroPlan.deviceId- : undefined;- // Whether the sandbox is a fallback for a sender denied the agent's device:- // with access the same request would have routed to a device. Lets a failed- // sandbox run tell the sender why it ran there instead.- const deviceAccessDenied =- deviceHeteroPlan?.kind === 'sandbox' &&- !canUseDevice &&- ['device', 'device-wakeable'].includes(- resolveExecutionPlan({ ...cliPlanParams, canUseDevice: true }).kind,- );- const cliDeviceWorkspaceId = cliDeviceId- ? await deps.resolveDeviceWorkspaceId(cliDeviceId)- : undefined;-// Register the run's lifecycle hooks so the hetero terminal path fires// onComplete/onError through the same `hookDispatcher` the normal LLM// runtime uses — driving the task lifecycle (onTopicComplete) and IM bot@@ -262,10 +221,12 @@ export const dispatchHeteroAgent = async (threadId: appContext?.threadId ?? undefined,};if (topicStartOwnerOperationId) {- const attached = await deps.topicModel.appendRunningOperationChild(- topicId,- topicStartOwnerOperationId,- childOperation,+ const attached = await traceHeteroStage('running_marker', () =>+ deps.topicModel.appendRunningOperationChild(+ topicId,+ topicStartOwnerOperationId,+ childOperation,+ ),);if (!attached) {const message = 'Group supervisor finished before this member could start.';@@ -298,10 +259,8 @@ export const dispatchHeteroAgent = async (// callAgent resume bridge) never fire. Nest under the parent's own// marker instead of claiming the topic-level root outright, so the// parent's marker survives for the rest of its still-running turn.- const attachedToParent = await deps.topicModel.appendRunningOperationChild(- topicId,- parentOperationId,- childOperation,+ const attachedToParent = await traceHeteroStage('running_marker', () =>+ deps.topicModel.appendRunningOperationChild(topicId, parentOperationId, childOperation),);if (!attachedToParent) {// Parent isn't (or is no longer) the topic's current root marker —@@ -309,7 +268,9 @@ export const dispatchHeteroAgent = async (// Fall back to claiming the marker directly so this child is still// discoverable by its own operationId, rather than permanently// unrecognized by heteroIngest/heteroFinish.- await deps.topicModel.updateMetadata(topicId, { runningOperation: childOperation });+ await traceHeteroStage('running_marker', () =>+ deps.topicModel.updateMetadata(topicId, { runningOperation: childOperation }),+ );}} else if (!appContext?.isolationThread) {// The receipt previously had a separate projection write after this marker.@@ -317,10 +278,12 @@ export const dispatchHeteroAgent = async (// while retaining the previous operation's displayed configuration.// Task drawer follow-ups can omit taskId; receipt ownership is independent// of Task lifecycle association, while isolated children keep the root receipt.- await deps.topicModel.updateMetadata(topicId, {- heteroRuntimeConfig: runtimeConfig,- runningOperation: childOperation,- });+ await traceHeteroStage('running_marker', () =>+ deps.topicModel.updateMetadata(topicId, {+ heteroRuntimeConfig: runtimeConfig,+ runningOperation: childOperation,+ }),+ );}// Always persist operation metadata (userId/workspaceId) to the state@@ -333,13 +296,15 @@ export const dispatchHeteroAgent = async (// watchdog abandons it).const persistOperationMetadata = async () => {try {- await createAgentStateManager().createOperationMetadata(operationId, {- ...(topicStartOwnerOperationId && {- mirrorToOperationId: topicStartOwnerOperationId,+ await traceHeteroStage('operation_metadata', () =>+ createAgentStateManager().createOperationMetadata(operationId, {+ ...(topicStartOwnerOperationId && {+ mirrorToOperationId: topicStartOwnerOperationId,+ }),+ userId: deps.userId,+ workspaceId: deps.workspaceId,}),- userId: deps.userId,- workspaceId: deps.workspaceId,- });+ );} catch (err) {log('execAgent: failed to persist hetero operation metadata: %O', err);}@@ -361,18 +326,20 @@ export const dispatchHeteroAgent = async (}if (isRemoteHetero) {- const failure = await dispatchToPlatformDevice(deps, run, {- agentConfig,- canUseDevice,- deviceAccessReason,- heteroType,- persistOperationMetadata,- prompt,- remoteDeviceId,- remoteDeviceUserId,- remoteDeviceWorkspaceId,- topicStartOwnerOperationId,- });+ const failure = await traceHeteroStage('platform_dispatch', () =>+ dispatchToPlatformDevice(deps, run, {+ agentConfig,+ canUseDevice,+ deviceAccessReason,+ heteroType,+ persistOperationMetadata,+ prompt,+ remoteDeviceId,+ remoteDeviceUserId,+ remoteDeviceWorkspaceId,+ topicStartOwnerOperationId,+ }),+ );if (failure) return failure;} else {// Local CLI hetero (Amp / Claude Code / Codex / Kimi Code / OpenCode /@@ -409,14 +376,16 @@ export const dispatchHeteroAgent = async (// probes Redis synchronously, so guard construction too, not just publish.try {await persistOperationMetadata();- await createStreamEventManager().publishAgentRuntimeInit(operationId, {- agentId: resolvedAgentId,- assistantMessageId,- heteroType,- mirrorToOperationId: topicStartOwnerOperationId,- topicId,- userId: deps.userId,- });+ await traceHeteroStage('stream_init', () =>+ createStreamEventManager().publishAgentRuntimeInit(operationId, {+ agentId: resolvedAgentId,+ assistantMessageId,+ heteroType,+ mirrorToOperationId: topicStartOwnerOperationId,+ topicId,+ userId: deps.userId,+ }),+ );} catch (err) {log('execAgent: failed to init stream for local hetero: %O', err);}@@ -433,25 +402,39 @@ export const dispatchHeteroAgent = async (let failure: ExecAgentResult | undefined;switch (heteroPlan.kind) {case 'sandbox': {- failure = await spawnInCloudSandbox(deps, run, {- deviceAccessDenied,- heteroType,- prepared,- });+ failure = await traceHeteroStage('sandbox_spawn', () =>+ spawnInCloudSandbox(deps, run, { deviceAccessDenied, heteroType, prepared }),+ );break;}case 'device-wakeable': {// Wakes the device and dispatches after the response, once it is// online (or when the wait times out, through the offline handling).- failure = await dispatchToWakingCliDevice(deps, run, {- ...cliDispatchParams,- device: wakeableCliDevices.find((device) => device.deviceId === heteroPlan.deviceId)!,- heteroPlan,- });+ failure = await traceHeteroStage('waking_device_dispatch', () =>+ dispatchToWakingCliDevice(deps, run, {+ ...cliDispatchParams,+ device: wakeableCliDevices.find((device) => device.deviceId === heteroPlan.deviceId)!,+ heteroPlan,+ }),+ );+ break;+ }+ case 'device': {+ // Behind `agent_deferred_hetero_dispatch` a plain chat send answers+ // now and the device steps run after the response.+ if (await deferDispatchPromise) {+ deferCliDeviceDispatch(deps, run, { ...cliDispatchParams, heteroPlan });+ break;+ }+ failure = await traceHeteroStage('device_dispatch', () =>+ dispatchToCliDevice(deps, run, { ...cliDispatchParams, heteroPlan }),+ );break;}default: {- failure = await dispatchToCliDevice(deps, run, { ...cliDispatchParams, heteroPlan });+ failure = await traceHeteroStage('device_dispatch', () =>+ dispatchToCliDevice(deps, run, { ...cliDispatchParams, heteroPlan }),+ );}}if (failure) return failure;@@ -460,7 +443,7 @@ export const dispatchHeteroAgent = async (let gatewayToken: string | undefined;if (!deps.withholdGatewayToken) {try {- gatewayToken = await signUserJWT(deps.userId);+ gatewayToken = await traceHeteroStage('sign_gateway_token', () => signUserJWT(deps.userId));} catch {// non-critical}diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.parallelReads.test.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.parallelReads.test.tsnew file mode 100644index 00000000000..29163ef409d--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.parallelReads.test.ts@@ -0,0 +1,253 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type * as ViewedTaskContextModule from '../viewedTaskContext';+import { prepareHeteroRun } from './prepare';+import type { HeteroDispatchDeps } from './types';++const mocks = vi.hoisted(() => {+ /**+ * The required reads and the two best-effort reads all wait on one barrier+ * that opens only once every one of them has started. Run one after another,+ * the first waits for a barrier the rest never reach and the test times out.+ */+ const STAGE_COUNT = 5;+ const started: string[] = [];+ let openBarrier: () => void = () => {};+ let barrier = new Promise<void>((resolve) => {+ openBarrier = resolve;+ });+ const gated =+ <T>(stage: string, value: () => T) =>+ async () => {+ started.push(stage);+ if (started.length >= STAGE_COUNT) openBarrier();+ await barrier;+ return value();+ };++ const span = (name: string) => ({+ end: vi.fn(() => spans.ended.push(name)),+ setAttribute: vi.fn(),+ setStatus: vi.fn(() => spans.failed.push(name)),+ });+ const spans = { ended: [] as string[], failed: [] as string[] };++ return {+ gated,+ getFullFileUrl: vi.fn(),+ getResumeSessionId: vi.fn(),+ reset: () => {+ started.length = 0;+ spans.ended.length = 0;+ spans.failed.length = 0;+ barrier = new Promise<void>((resolve) => {+ openBarrier = resolve;+ });+ },+ resolveSandboxSessionConfig: vi.fn(),+ signHeteroOperationJWT: vi.fn(),+ span,+ spans,+ started,+ };+});++vi.mock('@lobechat/observability-otel/modules/agent-runtime', () => ({+ tracer: {+ startActiveSpan: (name: string, fn: (span: unknown) => unknown) => fn(mocks.span(name)),+ },+}));++vi.mock('@/server/services/heterogeneousAgent', () => ({+ HeterogeneousAgentService: vi.fn().mockImplementation(function () {+ return { getHeterogeneousResumeSessionId: mocks.getResumeSessionId };+ }),+}));++vi.mock('@/server/services/file', () => ({+ FileService: vi.fn().mockImplementation(function () {+ return { getFullFileUrl: mocks.getFullFileUrl };+ }),+}));++vi.mock('@/libs/trpc/utils/internalJwt', () => ({+ signHeteroOperationJWT: mocks.signHeteroOperationJWT,+}));++vi.mock('@/server/services/sandbox/session', () => ({+ resolveSandboxSessionConfig: mocks.resolveSandboxSessionConfig,+}));++vi.mock('../viewedTaskContext', async (importOriginal) => ({+ ...(await importOriginal<typeof ViewedTaskContextModule>()),+ buildViewedTaskContextPrompt: vi.fn().mockResolvedValue(undefined),+}));++vi.mock('../projectContext', () => ({+ buildHeteroProjectContext: vi.fn().mockResolvedValue(undefined),+}));++vi.mock('../finalizeHeteroDispatchError', () => ({ finalizeHeteroDispatchError: vi.fn() }));++const createDeps = () => {+ const credsGet = vi.fn().mockResolvedValue({ plaintext: { access_token: 'gh-token' } });+ const marketService = {+ market: {+ creds: {+ get: credsGet,+ list: mocks.gated('github_token', () => ({ data: [{ id: 'cred-1', key: 'github' }] })),+ },+ },+ };+ const topicModel = {+ findById: vi.fn(mocks.gated('topic', () => ({ metadata: { repos: ['lobehub/lobehub'] } }))),+ };+ const messageModel = {+ query: vi.fn(+ mocks.gated('history', () => [+ { content: 'earlier question', id: 'm-1', role: 'user' },+ { content: 'earlier answer', id: 'm-2', role: 'assistant' },+ ]),+ ),+ };+ const deps = {+ bindTopicWorkingDirectory: vi.fn(),+ db: {} as any,+ getMarketService: vi.fn().mockResolvedValue(marketService),+ messageModel: messageModel as any,+ resolveDeviceWorkspaceId: vi.fn(),+ topicModel: topicModel as any,+ userId: 'user-1',+ withholdGatewayToken: false,+ } satisfies HeteroDispatchDeps;+ return { credsGet, deps, messageModel, topicModel };+};++const ctx = {+ agentConfig: { agencyConfig: {}, id: 'agent-1' },+ assistantMessageId: 'asst-1',+ prompt: 'hello',+ topicId: 'topic-1',+ trigger: 'chat',+ userMessageId: 'user-msg-1',+} as any;++const input = {+ heteroType: 'claude-code' as const,+ runAttachments: { audioList: [], fileList: [], imageList: [], videoList: [] },+ selfMessageIds: new Set<string>(),+};++beforeEach(() => {+ vi.clearAllMocks();+ mocks.reset();+ mocks.getResumeSessionId.mockImplementation(mocks.gated('resume_session', () => undefined));+ mocks.signHeteroOperationJWT.mockImplementation(mocks.gated('sign_operation_jwt', () => 'jwt'));+ mocks.resolveSandboxSessionConfig.mockResolvedValue(undefined);+});++describe('prepareHeteroRun — overlapping reads', () => {+ it('starts the resume, JWT, topic, GitHub and history reads together', async () => {+ const { credsGet, deps } = createDeps();++ const prepared = await prepareHeteroRun(deps, ctx, input, 'op-1');++ expect(mocks.started.toSorted()).toEqual(+ ['github_token', 'history', 'resume_session', 'sign_operation_jwt', 'topic'].toSorted(),+ );+ expect(credsGet).toHaveBeenCalledWith('cred-1', { decrypt: true });+ expect(prepared.heteroParams).toMatchObject({+ githubToken: 'gh-token',+ jwt: 'jwt',+ repos: ['lobehub/lobehub'],+ });+ expect(prepared.conversationHistory).toEqual([+ { content: 'earlier question', role: 'user' },+ { content: 'earlier answer', role: 'assistant' },+ ]);+ expect(mocks.resolveSandboxSessionConfig).toHaveBeenCalledTimes(1);+ // Every stage span closed, none marked failed.+ expect(mocks.spans.ended).toEqual(+ expect.arrayContaining([+ 'hetero_dispatch github_token',+ 'hetero_dispatch history',+ 'hetero_dispatch resume_session',+ 'hetero_dispatch sandbox_session',+ 'hetero_dispatch sign_operation_jwt',+ 'hetero_dispatch system_context',+ 'hetero_dispatch topic',+ ]),+ );+ expect(mocks.spans.failed).toEqual([]);+ });++ it('keeps the best-effort reads best-effort when they fail', async () => {+ const { deps, messageModel, topicModel } = createDeps();+ deps.getMarketService.mockRejectedValue(new Error('market down'));+ messageModel.query.mockRejectedValue(new Error('db down'));+ topicModel.findById.mockResolvedValue({ metadata: {} });+ mocks.getResumeSessionId.mockResolvedValue(undefined);+ mocks.signHeteroOperationJWT.mockResolvedValue('jwt');++ const prepared = await prepareHeteroRun(deps, ctx, input, 'op-1');++ expect(prepared.heteroParams.githubToken).toBeUndefined();+ expect(prepared.conversationHistory).toBeUndefined();+ expect(prepared.heteroParams.jwt).toBe('jwt');+ });++ it('surfaces the JWT failure before a later topic failure and never places the sandbox', async () => {+ const { deps, topicModel } = createDeps();+ mocks.signHeteroOperationJWT.mockImplementation(async () => {+ // Fails last in time, but came first in the old sequence.+ await new Promise((resolve) => setTimeout(resolve, 10));+ throw new Error('kms unavailable');+ });+ topicModel.findById.mockRejectedValue(new Error('topic read failed'));+ mocks.getResumeSessionId.mockResolvedValue(undefined);++ await expect(prepareHeteroRun(deps, ctx, input, 'op-1')).rejects.toThrow(+ 'Failed to sign operation JWT for hetero agent',+ );+ // The placement may create a drive folder: it waits for the required reads.+ expect(mocks.resolveSandboxSessionConfig).not.toHaveBeenCalled();+ // The failed stages still closed their spans and recorded the error.+ expect(mocks.spans.failed).toEqual(+ expect.arrayContaining(['hetero_dispatch sign_operation_jwt', 'hetero_dispatch topic']),+ );+ expect(mocks.spans.ended).toEqual(+ expect.arrayContaining(['hetero_dispatch sign_operation_jwt', 'hetero_dispatch topic']),+ );+ });++ it('keeps the text history when signing an unanswered attachment fails', async () => {+ const { deps, messageModel, topicModel } = createDeps();+ topicModel.findById.mockResolvedValue({ metadata: {} });+ deps.getMarketService.mockRejectedValue(new Error('market down'));+ mocks.getResumeSessionId.mockResolvedValue('session-1');+ mocks.signHeteroOperationJWT.mockResolvedValue('jwt');+ mocks.getFullFileUrl.mockRejectedValue(new Error('signing failed'));+ messageModel.query.mockResolvedValue([+ { content: 'earlier question', id: 'm-1', role: 'user' },+ { content: 'earlier answer', id: 'm-2', role: 'assistant' },+ {+ content: 'stopped before the CLI saw it',+ fileList: [{ name: 'spec.pdf', url: 'files/spec.pdf' }],+ id: 'm-3',+ role: 'user',+ },+ ]);++ const prepared = await prepareHeteroRun(deps, ctx, input, 'op-1');++ expect(mocks.getFullFileUrl).toHaveBeenCalledWith('files/spec.pdf');+ expect(prepared.conversationHistory).toEqual([+ { content: 'earlier question', role: 'user' },+ { content: 'earlier answer', role: 'assistant' },+ { content: 'stopped before the CLI saw it', role: 'user' },+ ]);+ expect(prepared.unansweredUserTurns).toBeUndefined();+ // A resumed run still gets its fallback context built from that history.+ expect(prepared.heteroParams.resumeFallbackSystemContext).toBeDefined();+ });+});diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.tsindex 16481488675..193725b4ccc 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts@@ -17,6 +17,7 @@ import {RequestTrigger,} from '@lobechat/types';import debug from 'debug';+import pMap from 'p-map';import { signHeteroOperationJWT } from '@/libs/trpc/utils/internalJwt';import { FileService } from '@/server/services/file';@@ -31,8 +32,13 @@ import { supportsCloudHeterogeneousSandbox } from '../../helpers/heteroErrors';import type { ExecRunContext } from '../../types';import { heteroOperationCapabilities } from '../heteroOperationCapabilities';import { buildHeteroProjectContext } from '../projectContext';+import { traceHeteroStage } from '../sendTracing';import { buildViewedTaskContextPrompt, joinSystemContext } from '../viewedTaskContext';import type { HeteroDispatchDeps, HeteroDispatchInput } from './types';+import { settleInOrder } from './utils';++/** How many stored attachment keys are signed at once, per level. */+const SIGN_URL_CONCURRENCY = 5;const log = debug('lobe-server:ai-agent-service');@@ -83,81 +89,107 @@ export const prepareHeteroRun = async (workspaceId: deps.workspaceId,});const isChannelOperation = ctx.trigger === 'channel' && input.reservedOperationId === operationId;- const resumeSessionId = await heteroService.getHeterogeneousResumeSessionId(topicId);+// Sign an operation-scoped JWT so the CLI can authenticate against// heteroIngest / heteroFinish without full user credentials.- let operationJwt: string;- try {- operationJwt = await signHeteroOperationJWT({- // A run the user sent also gets `goal:manage` so it can create- // the goal the agent supervises; the server still derives the agent and- // topic from this operation, never from the CLI. A Task run also gets- // `acceptance:evidence` for its own verification round.- capabilities: heteroOperationCapabilities(prompt, {- channel: isChannelOperation,- taskId: operationTaskId,- // A scheduled run replays the user's own message off history, so it has- // no fresh user row; server-started `chat` deliveries have none either.- userTurn:- (ctx.trigger === RequestTrigger.Chat && !!ctx.userMessageId) ||- ctx.trigger === RequestTrigger.Scheduled,- }),- operationId,- userId: deps.userId,- workspaceId: deps.workspaceId,- });- } catch (err) {- log('execAgent: failed to sign operation JWT for hetero run: %O', err);- throw new Error('Failed to sign operation JWT for hetero agent', { cause: err });- }-- // Read repos from topic metadata for sandbox setup (web/cloud only).- const topic = await deps.topicModel.findById(topicId);- const topicRepos: string[] = topic?.metadata?.repos ?? [];+ const signOperationJwt = async () => {+ try {+ return await signHeteroOperationJWT({+ // A run the user sent also gets `goal:manage` so it can create+ // the goal the agent supervises; the server still derives the agent and+ // topic from this operation, never from the CLI. A Task run also gets+ // `acceptance:evidence` for its own verification round.+ capabilities: heteroOperationCapabilities(prompt, {+ channel: isChannelOperation,+ taskId: operationTaskId,+ // A scheduled run replays the user's own message off history, so it has+ // no fresh user row; server-started `chat` deliveries have none either.+ userTurn:+ (ctx.trigger === RequestTrigger.Chat && !!ctx.userMessageId) ||+ ctx.trigger === RequestTrigger.Scheduled,+ }),+ operationId,+ userId: deps.userId,+ workspaceId: deps.workspaceId,+ });+ } catch (err) {+ log('execAgent: failed to sign operation JWT for hetero run: %O', err);+ throw new Error('Failed to sign operation JWT for hetero agent', { cause: err });+ }+ };// Resolve GitHub OAuth token for the sandbox. Always attempt so CC can use// git / gh CLI even when no repos are pre-selected. Falls back to the// standard 'github' key (LobeHub OAuth connector default); agent config can- // override via GITHUB_CRED_KEY.- let githubToken: string | undefined;+ // override via GITHUB_CRED_KEY. Never rejects: a missing token is no token.const githubCredKey =agentConfig.agencyConfig?.heterogeneousProvider?.env?.GITHUB_CRED_KEY ?? 'github';- try {- const marketService = await deps.getMarketService();- // Inside a workspace, the GitHub cred must come from the workspace's shared- // organization credentials, not the operator's personal creds.- const credsAccessor = deps.workspaceId- ? marketService.market.organizations.creds({ workspaceId: deps.workspaceId })- : marketService.market.creds;- const list = await credsAccessor.list();- const cred = list.data?.find((c: { key: string }) => c.key === githubCredKey);- if (cred) {+ const resolveGithubToken = async (): Promise<string | undefined> => {+ try {+ const marketService = await deps.getMarketService();+ // Inside a workspace, the GitHub cred must come from the workspace's shared+ // organization credentials, not the operator's personal creds.+ const credsAccessor = deps.workspaceId+ ? marketService.market.organizations.creds({ workspaceId: deps.workspaceId })+ : marketService.market.creds;+ const list = await credsAccessor.list();+ const cred = list.data?.find((c: { key: string }) => c.key === githubCredKey);+ if (!cred) return;const full = await credsAccessor.get(cred.id, { decrypt: true });const vals = (full as any).plaintext ?? (full as any).values ?? {};- githubToken = vals.access_token ?? vals.token;+ return vals.access_token ?? vals.token;+ } catch (err) {+ log('execAgent: failed to resolve GitHub token: %O', err);}- } catch (err) {- log('execAgent: failed to resolve GitHub token: %O', err);- }+ };// Recovery history is reserved for the CLI's retry without native resume.- // The primary resumed attempt already has native history and must not get- // a serialized duplicate. Amp threads are server-backed, so they rely on- // native continuation exclusively and never need this local-file fallback.- let conversationHistory: ConversationHistoryEntry[] | undefined;- // A resumed session still needs the prompts of runs stopped before the CLI- // recorded them; the history above is withheld from it.- let unansweredUserTurns: UnansweredUserTurn[] | undefined;- if (heteroType !== 'amp') {+ // Amp threads are server-backed, so they rely on native continuation+ // exclusively and never need this local-file fallback. Never rejects.+ const loadRecentMessages = async () => {+ if (heteroType === 'amp') return;try {// `allowShareVisitor`: this is the RUN's own topic, already resolved// and authorized upstream. An agent-share visitor run executes under// the creator's identity, so without the opt-in `query()`'s// creator-facing default would hand the agent an empty history.- const recentMsgs = await deps.messageModel.query(- { topicId, pageSize: 200 },- { allowShareVisitor: true },- );+ return await deps.messageModel.query({ topicId, pageSize: 200 }, { allowShareVisitor: true });+ } catch (err) {+ log('execAgent: failed to load conversation history for hetero context: %O', err);+ }+ };++ // Every read below depends only on the request, so they start together+ // instead of one after another. The two best-effort reads (GitHub token,+ // history) never reject; the required ones are settled in their old order+ // so a failure surfaces the same error the sequential code threw. Nothing+ // here writes: the sandbox placement, which may create a drive folder,+ // waits until these required reads have succeeded, as before.+ const githubTokenPromise = traceHeteroStage('github_token', resolveGithubToken);+ const recentMessagesPromise = traceHeteroStage('history', loadRecentMessages);+ const [resumeSessionId, operationJwt, topic] = await settleInOrder([+ traceHeteroStage('resume_session', () =>+ heteroService.getHeterogeneousResumeSessionId(topicId),+ ),+ traceHeteroStage('sign_operation_jwt', signOperationJwt),+ // Read repos from topic metadata for sandbox setup (web/cloud only).+ traceHeteroStage('topic', () => deps.topicModel.findById(topicId)),+ ]);+ const topicRepos: string[] = topic?.metadata?.repos ?? [];++ // The primary resumed attempt already has native history and must not get+ // a serialized duplicate. A resumed session still needs the prompts of runs+ // stopped before the CLI recorded them; the history is withheld from it.+ const buildRecoveryHistory = async (): Promise<{+ conversationHistory?: ConversationHistoryEntry[];+ unansweredUserTurns?: UnansweredUserTurn[];+ }> => {+ const recentMsgs = await recentMessagesPromise;+ if (!recentMsgs) return {};+ // Assigned before the attachments are signed: a signing failure drops only+ // the unanswered turns, never the text history the resume fallback needs.+ let conversationHistory: ConversationHistoryEntry[] | undefined;+ try {const topicMsgs = recentMsgs.filter((m) => !m.threadId && !selfMessageIds.has(m.id));const turns = topicMsgs.filter(@@ -171,57 +203,77 @@ export const prepareHeteroRun = async (content: m.content ?? '',role: m.role as 'assistant' | 'user',}));- if (turns.length > 0) conversationHistory = turns;- if (resumeSessionId) {- const unanswered = collectUnansweredUserTurns(topicMsgs, prompt);- if (unanswered.length > 0) {- // The query returns stored file keys; sign them like the current turn's attachments.- const fileService = unanswered.some((turn) => turn.files.length > 0)- ? new FileService(deps.db, deps.userId, deps.workspaceId)- : undefined;- unansweredUserTurns = await Promise.all(- unanswered.map(async (turn) => ({- ...turn,- files: await Promise.all(- turn.files.map(async (file) => ({- ...file,- url: (await fileService?.getFullFileUrl(file.url)) || file.url,- })),- ),- })),- );- }- }+ conversationHistory = turns.length > 0 ? turns : undefined;+ if (!resumeSessionId) return { conversationHistory };+ const unanswered = collectUnansweredUserTurns(topicMsgs, prompt);+ if (unanswered.length === 0) return { conversationHistory };+ // The query returns stored file keys; sign them like the current turn's attachments.+ const fileService = unanswered.some((turn) => turn.files.length > 0)+ ? new FileService(deps.db, deps.userId, deps.workspaceId)+ : undefined;+ // Both lists come from stored rows, so cap the URL signing they fan out into.+ const unansweredUserTurns = await pMap(+ unanswered,+ async (turn) => ({+ ...turn,+ files: await pMap(+ turn.files,+ async (file) => ({+ ...file,+ url: (await fileService?.getFullFileUrl(file.url)) || file.url,+ }),+ { concurrency: SIGN_URL_CONCURRENCY },+ ),+ }),+ { concurrency: SIGN_URL_CONCURRENCY },+ );+ return { conversationHistory, unansweredUserTurns };} catch (err) {log('execAgent: failed to load conversation history for hetero context: %O', err);+ return { conversationHistory };}- }+ };// Where a cloud-sandbox run keeps its files: the same resolution the plain// cloud-sandbox runtime does, so a hetero topic bound to an environment// instance runs in that instance rather than in a throwaway box. Only for// providers the cloud sandbox can host at all; device-only providers never// read it. Never throws — a failed lookup is the ephemeral sandbox.- const sandbox = supportsCloudHeterogeneousSandbox(heteroType)- ? await resolveSandboxSessionConfig({- isShareVisitorRun: !!ctx.shareGate,- serverDB: deps.db,- topicId,- userId: deps.userId,- workspaceId: deps.workspaceId,- })- : undefined;- const sandboxPlacement = sandbox && { cwd: sandbox.cwd, mode: sandbox.mode };-+ //// Primary context omits history (a failed native resume retries with the full// fallback). `/goal`, the task viewed in a Tasks side chat and the content the// user attached to this message ride along — the same selection context the- // desktop's in-process run hands its CLI.- const providerContext = agentConfig.agencyConfig?.heterogeneousProvider?.systemContext;- const [viewedTaskContext, projectContext] = await Promise.all([- buildViewedTaskContextPrompt(deps, appContext, operationTaskId),- buildHeteroProjectContext(deps, appContext?.projectId, agentConfig.id),+ // desktop's in-process run hands its CLI. These reads are independent of+ // each other and of the history, so they overlap too.+ const [+ githubToken,+ { conversationHistory, unansweredUserTurns },+ sandbox,+ [viewedTaskContext, projectContext],+ ] = await settleInOrder([+ githubTokenPromise,+ buildRecoveryHistory(),+ supportsCloudHeterogeneousSandbox(heteroType)+ ? traceHeteroStage('sandbox_session', () =>+ resolveSandboxSessionConfig({+ isShareVisitorRun: !!ctx.shareGate,+ serverDB: deps.db,+ topicId,+ userId: deps.userId,+ workspaceId: deps.workspaceId,+ }),+ )+ : Promise.resolve(undefined),+ traceHeteroStage('system_context', () =>+ Promise.all([+ buildViewedTaskContextPrompt(deps, appContext, operationTaskId),+ buildHeteroProjectContext(deps, appContext?.projectId, agentConfig.id),+ ]),+ ),]);+ const sandboxPlacement = sandbox && { cwd: sandbox.cwd, mode: sandbox.mode };++ const providerContext = agentConfig.agencyConfig?.heterogeneousProvider?.systemContext;const contextSelections = userMessageMetadata?.contextSelections;const pageSelections = userMessageMetadata?.pageSelections;const selectionContext = contextSelections?.lengthdiff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/routing.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/routing.tsnew file mode 100644index 00000000000..7afd98d3520--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/routing.ts@@ -0,0 +1,126 @@+import { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';++import { resolveExecutionPlan, resolveWorkspaceScoped } from '@/helpers/executionTarget';+import { findWakeableManagedDevices } from '@/server/services/deviceGateway/managedDeviceWake';++import { supportsCloudHeterogeneousSandbox } from '../../helpers/heteroErrors';+import type { ExecRunContext } from '../../types';+import type { HeteroDispatchDeps, HeteroDispatchInput } from './types';++/**+ * Where a hetero run goes: the platform device of a remote agent, or the+ * execution plan of a local CLI agent with the device it names. Reads only+ * the request and the device registry — never the prepared run — so it runs+ * alongside `prepareHeteroRun`.+ */+export const resolveHeteroRouting = async (+ deps: HeteroDispatchDeps,+ ctx: Pick<ExecRunContext, 'agentConfig' | 'canUseDevice'>,+ input: Pick<+ HeteroDispatchInput,+ | 'canManageAgent'+ | 'effectiveRequestedDeviceId'+ | 'heteroType'+ | 'isPublicWorkspaceAgent'+ | 'localDeviceId'+ | 'memberDeviceOverride'+ | 'requestTrigger'+ | 'requestedDeviceId'+ >,+) => {+ const { agentConfig, canUseDevice } = ctx;+ const {+ canManageAgent,+ effectiveRequestedDeviceId,+ heteroType,+ isPublicWorkspaceAgent,+ localDeviceId,+ memberDeviceOverride,+ requestTrigger,+ requestedDeviceId,+ } = input;+ const isRemoteHetero = isRemoteHeterogeneousType(heteroType);++ const platformPlan = isRemoteHetero+ ? resolveExecutionPlan({+ agencyConfig: agentConfig.agencyConfig,+ canUseDevice,+ clientExecutionAvailable: Boolean(localDeviceId),+ isHetero: true,+ localDeviceId,+ requestedDeviceId: effectiveRequestedDeviceId,+ sandboxExecutionAvailable: false,+ trigger: requestTrigger,+ workspaceScoped: resolveWorkspaceScoped(+ isPublicWorkspaceAgent && !canManageAgent,+ memberDeviceOverride,+ ),+ })+ : undefined;+ const remoteDeviceId = platformPlan?.kind === 'device' ? platformPlan.deviceId : undefined;+ const remoteDeviceWorkspaceId = remoteDeviceId+ ? await deps.resolveDeviceWorkspaceId(remoteDeviceId)+ : undefined;+ const usesCallersPersonalDevice =+ platformPlan?.kind === 'device' &&+ !remoteDeviceWorkspaceId &&+ (effectiveRequestedDeviceId === remoteDeviceId ||+ (platformPlan.target === 'local' &&+ agentConfig.agencyConfig?.executionTargetSelectionPolicy !== 'fixed') ||+ (!canManageAgent && memberDeviceOverride?.boundDeviceId === remoteDeviceId));+ const remoteDeviceUserId = usesCallersPersonalDevice+ ? deps.userId+ : (agentConfig.userId ?? deps.userId);++ // Resolve CLI-device routing before persisting the marker. Cancellation+ // must address the same device even though local CLI agents use a different+ // dispatch transport from notify-based platform agents.+ // A bound managed cloud device that is offline resolves to+ // `device-wakeable`: it is woken and the dispatch waits for it.+ const wakeableCliDevices =+ !isRemoteHetero && canUseDevice+ ? await findWakeableManagedDevices(+ { db: deps.db, userId: deps.userId, workspaceId: deps.workspaceId },+ [requestedDeviceId, agentConfig.agencyConfig?.boundDeviceId],+ )+ : [];+ const cliPlanParams = {+ agencyConfig: agentConfig.agencyConfig,+ clientExecutionAvailable: false,+ isHetero: true,+ requestedDeviceId,+ sandboxExecutionAvailable: supportsCloudHeterogeneousSandbox(heteroType),+ trigger: requestTrigger,+ wakeableDeviceIds: wakeableCliDevices.map((device) => device.deviceId),+ };+ const deviceHeteroPlan = !isRemoteHetero+ ? resolveExecutionPlan({ ...cliPlanParams, canUseDevice })+ : undefined;+ const cliDeviceId =+ deviceHeteroPlan?.kind === 'device' || deviceHeteroPlan?.kind === 'device-wakeable'+ ? deviceHeteroPlan.deviceId+ : undefined;+ // Whether the sandbox is a fallback for a sender denied the agent's device:+ // with access the same request would have routed to a device. Lets a failed+ // sandbox run tell the sender why it ran there instead.+ const deviceAccessDenied =+ deviceHeteroPlan?.kind === 'sandbox' &&+ !canUseDevice &&+ ['device', 'device-wakeable'].includes(+ resolveExecutionPlan({ ...cliPlanParams, canUseDevice: true }).kind,+ );+ const cliDeviceWorkspaceId = cliDeviceId+ ? await deps.resolveDeviceWorkspaceId(cliDeviceId)+ : undefined;++ return {+ cliDeviceId,+ cliDeviceWorkspaceId,+ deviceAccessDenied,+ deviceHeteroPlan,+ remoteDeviceId,+ remoteDeviceUserId,+ remoteDeviceWorkspaceId,+ wakeableCliDevices,+ };+};diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/types.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/types.tsindex 97d1e8f1064..16841ff45be 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/types.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/types.ts@@ -38,6 +38,8 @@ export interface HeteroDispatchDeps {export interface HeteroDispatchInput {canManageAgent: boolean;effectiveRequestedDeviceId?: string;+ /** Not a plain composer send; see `shouldDeferHeteroDispatch`. */+ hasOrchestration?: boolean;heterogeneousProvider?: LobeAgentAgencyConfig['heterogeneousProvider'];heteroType: HeterogeneousAgentType;hooks?: AgentHook[];diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/utils.test.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/utils.test.tsnew file mode 100644index 00000000000..60759ab93e7--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/utils.test.ts@@ -0,0 +1,37 @@+import { describe, expect, it, vi } from 'vitest';++import { settleInOrder } from './utils';++vi.mock('../finalizeHeteroDispatchError', () => ({ finalizeHeteroDispatchError: vi.fn() }));++const later = <T>(ms: number, value: T) =>+ new Promise<T>((resolve) => setTimeout(() => resolve(value), ms));+const failLater = (ms: number, message: string) =>+ new Promise<never>((_, reject) => setTimeout(() => reject(new Error(message)), ms));++describe('settleInOrder', () => {+ it('returns every value in argument order, however they finish', async () => {+ await expect(settleInOrder([later(20, 'a'), later(0, 1), later(10, true)])).resolves.toEqual([+ 'a',+ 1,+ true,+ ]);+ });++ it('rethrows the first failure in argument order, not the first to happen', async () => {+ await expect(+ settleInOrder([later(0, 'ok'), failLater(20, 'first'), failLater(0, 'second')]),+ ).rejects.toThrow('first');+ });++ it('waits for every read to settle before rethrowing', async () => {+ let slowSettled = false;+ const slow = later(20, 'slow').then((value) => {+ slowSettled = true;+ return value;+ });++ await expect(settleInOrder([failLater(0, 'boom'), slow])).rejects.toThrow('boom');+ expect(slowSettled).toBe(true);+ });+});diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/utils.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/utils.tsindex da4cd0580c4..2cf35660ff4 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/utils.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/utils.ts@@ -52,3 +52,21 @@ export const failHeteroDispatch = async (});return heteroErrorResult(run, { ...result, terminalReported });};++/**+ * `Promise.all` for reads that used to run one after another: waits for every+ * one to settle, then rethrows the first failure in ARGUMENT order, so the+ * error a caller sees is the one the sequential code would have hit first.+ * Nothing is left running unobserved when one of them fails.+ */+export const settleInOrder = async <T extends readonly unknown[] | []>(+ promises: T,+): Promise<{ -readonly [K in keyof T]: Awaited<T[K]> }> => {+ const settled = await Promise.allSettled(promises as readonly Promise<unknown>[]);+ const values: unknown[] = [];+ for (const result of settled) {+ if (result.status === 'rejected') throw result.reason;+ values.push(result.value);+ }+ return values as { -readonly [K in keyof T]: Awaited<T[K]> };+};diff --git a/apps/server/src/services/aiAgent/pipeline/sendTracing.ts b/apps/server/src/services/aiAgent/pipeline/sendTracing.tsindex d3d86707886..6e815b50b08 100644--- a/apps/server/src/services/aiAgent/pipeline/sendTracing.ts+++ b/apps/server/src/services/aiAgent/pipeline/sendTracing.ts@@ -72,3 +72,12 @@ export const tracePrepStage = createStageTracer('operation_prep');/** The persistence steps of `createOperation` (row, runtime meta + gateway init, state, queue). */export const traceStartStage = createStageTracer('operation_start');++/**+ * The stages of a heterogeneous-agent send (`dispatchHeteroAgent`): the+ * operation row, the verify-plan wait, the run preparation reads, device+ * routing, every device-dispatch step and the gateway hop. `execAgent` waits+ * on all of them before it answers, so these are what the "sending" state+ * of a Claude Code / Codex send is spent on.+ */+export const traceHeteroStage = createStageTracer('hetero_dispatch');diff --git a/docs/self-hosting/advanced/feature-flags.mdx b/docs/self-hosting/advanced/feature-flags.mdxindex c8f54ec75c3..ae0ed2285a3 100644--- a/docs/self-hosting/advanced/feature-flags.mdx+++ b/docs/self-hosting/advanced/feature-flags.mdx@@ -34,30 +34,31 @@ You can achieve various feature combinations using the above configuration syntatheir default values).</Callout>-| Configuration Item | Description | Default Value |-| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- |-| `check_updates` | Allows checking for updates. | Enabled |-| `provider_settings` | Controls model provider settings display. | Enabled |-| `openai_api_key` | Allows users to customize the OpenAI API Key. | Enabled |-| `openai_proxy_url` | Allows users to customize the OpenAI proxy URL. | Enabled |-| `api_key_manage` | Controls access to API key management page (/profile/apikey). | Disabled |-| `agent_share` | Gates new or re-enabled interactive Agent shares. Requires deployment support; see the boundary below. | 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 |-| `ai_image` | Controls AI image generation feature and page (/image). | Enabled |-| `speech_to_text` | Enables speech-to-text functionality. | Enabled |-| `token_counter` | Reserved for token counter display. | Enabled |-| `welcome_suggest` | Displays welcome suggestions. | Enabled |-| `changelog` | Controls changelog modal/page display. | Enabled |-| `market` | Enables the assistant market functionality. | Enabled |-| `knowledge_base` | Enables the knowledge base functionality. | Enabled |-| `rag_eval` | Controls RAG evaluation feature (/repos/\[id]/evals). | Disabled |-| `cloud_promotion` | Controls cloud service promotion link display in user menu. | Disabled |-| `commercial_hide_github` | Hides GitHub-related links in settings footer (requires commercial license). | Disabled |-| `commercial_hide_docs` | Hides documentation and help menu including changelog, docs, and feedback (requires commercial license). | Disabled |+| Configuration Item | Description | Default Value |+| --- | --- | --- |+| `check_updates` | Allows checking for updates. | Enabled |+| `provider_settings` | Controls model provider settings display. | Enabled |+| `openai_api_key` | Allows users to customize the OpenAI API Key. | Enabled |+| `openai_proxy_url` | Allows users to customize the OpenAI proxy URL. | Enabled |+| `api_key_manage` | Controls access to API key management page (/profile/apikey). | Disabled |+| `agent_share` | Gates new or re-enabled interactive Agent shares. Requires deployment support; see the boundary below. | 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 |+| `agent_deferred_hetero_dispatch` | Returns a plain chat send to a heterogeneous agent (Claude Code, Codex, …) on an online device before the device accepts the run; the dispatch runs after the response, and a failure is shown on the assistant message. | 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 |+| `ai_image` | Controls AI image generation feature and page (/image). | Enabled |+| `speech_to_text` | Enables speech-to-text functionality. | Enabled |+| `token_counter` | Reserved for token counter display. | Enabled |+| `welcome_suggest` | Displays welcome suggestions. | Enabled |+| `changelog` | Controls changelog modal/page display. | Enabled |+| `market` | Enables the assistant market functionality. | Enabled |+| `knowledge_base` | Enables the knowledge base functionality. | Enabled |+| `rag_eval` | Controls RAG evaluation feature (/repos/\[id]/evals). | Disabled |+| `cloud_promotion` | Controls cloud service promotion link display in user menu. | Disabled |+| `commercial_hide_github` | Hides GitHub-related links in settings footer (requires commercial license). | Disabled |+| `commercial_hide_docs` | Hides documentation and help menu including changelog, docs, and feedback (requires commercial license). | Disabled |## Interactive Agent Sharing: Deployment and Rollout Boundariesdiff --git a/docs/self-hosting/advanced/feature-flags.zh-CN.mdx b/docs/self-hosting/advanced/feature-flags.zh-CN.mdxindex 14568932894..f70a813d2c1 100644--- a/docs/self-hosting/advanced/feature-flags.zh-CN.mdx+++ b/docs/self-hosting/advanced/feature-flags.zh-CN.mdx@@ -32,30 +32,31 @@ tags:关键字,你需要手动控制所有的功能标志(否则它们会采用对应的默认值)。</Callout>-| 配置项 | 解释 | 默认值 |-| ------------------------ | ----------------------------------------------------------------------------------------------------------------------- | --- |-| `check_updates` | 允许检查更新。 | 开启 |-| `provider_settings` | 控制模型供应商设置的显示。 | 开启 |-| `openai_api_key` | 允许用户自定义 OpenAI API Key。 | 开启 |-| `openai_proxy_url` | 允许用户自定义 OpenAI 代理 URL。 | 开启 |-| `api_key_manage` | 控制 API 密钥管理页面 (/profile/apikey) 的访问。 | 关闭 |-| `agent_share` | 控制新建或重新启用交互式助理分享;还需部署支持,详见下文边界。 | 关闭 |-| `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` | 允许用户编辑助手。 | 开启 |-| `ai_image` | 控制 AI 图像生成功能和页面 (/image)。 | 开启 |-| `speech_to_text` | 启用语音转文本功能。 | 开启 |-| `token_counter` | 保留用于令牌计数器显示。 | 开启 |-| `welcome_suggest` | 显示欢迎建议。 | 开启 |-| `changelog` | 控制更新日志弹窗 / 页面的显示。 | 开启 |-| `market` | 启用助手市场功能。 | 开启 |-| `knowledge_base` | 启用知识库功能。 | 开启 |-| `rag_eval` | 控制 RAG 评估功能 (/repos/\[id]/evals)。 | 关闭 |-| `cloud_promotion` | 控制用户菜单中云服务推广链接的显示。 | 关闭 |-| `commercial_hide_github` | 隐藏设置页面底部的 GitHub 相关链接(需要商业授权)。 | 关闭 |-| `commercial_hide_docs` | 隐藏文档和帮助菜单,包括更新日志、文档和反馈(需要商业授权)。 | 关闭 |+| 配置项 | 解释 | 默认值 |+| --- | --- | --- |+| `check_updates` | 允许检查更新。 | 开启 |+| `provider_settings` | 控制模型供应商设置的显示。 | 开启 |+| `openai_api_key` | 允许用户自定义 OpenAI API Key。 | 开启 |+| `openai_proxy_url` | 允许用户自定义 OpenAI 代理 URL。 | 开启 |+| `api_key_manage` | 控制 API 密钥管理页面 (/profile/apikey) 的访问。 | 关闭 |+| `agent_share` | 控制新建或重新启用交互式助理分享;还需部署支持,详见下文边界。 | 关闭 |+| `agent_llm_relay` | 对只有用户设备能访问的模型服务商(本地 Ollama / LM Studio、私网地址),由发起运行的客户端执行单次模型调用,助理循环仍在服务端运行;这类运行需要有打开的 LobeHub 客户端。 | 关闭 |+| `agent_deferred_init` | 普通聊天发送在消息落库后立即返回,工具发现和上下文组装放到第一个助理步骤中执行,发送不再等待。需要队列模式的助理运行时。 | 关闭 |+| `agent_deferred_hetero_dispatch` | 普通聊天发给在线设备上的异构助理(Claude Code、Codex 等)时,不等设备接收任务就立即返回;派发在响应后执行,失败会显示在助理消息上。 | 关闭 |+| `dashboard` | 看板:首页与项目看板页面、监控组件侧边栏、对话内的组件预览,以及用于搭建监控组件的 `builtin-dashboard` 助理工具。关闭时以上入口均隐藏,组件与看板相关接口返回 FORBIDDEN;已发布的组件仍按计划刷新。 | 关闭 |+| `mcp_apps` | MCP Apps:MCP 服务器为工具结果声明了交互页面(`ui://`)时,在对话中渲染该页面(服务器提供的 HTML,运行在沙箱 iframe 中)。关闭时按普通工具结果显示,服务端也不再向 MCP 服务器声明支持 MCP Apps。 | 关闭 |+| `edit_agent` | 允许用户编辑助手。 | 开启 |+| `ai_image` | 控制 AI 图像生成功能和页面 (/image)。 | 开启 |+| `speech_to_text` | 启用语音转文本功能。 | 开启 |+| `token_counter` | 保留用于令牌计数器显示。 | 开启 |+| `welcome_suggest` | 显示欢迎建议。 | 开启 |+| `changelog` | 控制更新日志弹窗 / 页面的显示。 | 开启 |+| `market` | 启用助手市场功能。 | 开启 |+| `knowledge_base` | 启用知识库功能。 | 开启 |+| `rag_eval` | 控制 RAG 评估功能 (/repos/\[id]/evals)。 | 关闭 |+| `cloud_promotion` | 控制用户菜单中云服务推广链接的显示。 | 关闭 |+| `commercial_hide_github` | 隐藏设置页面底部的 GitHub 相关链接(需要商业授权)。 | 关闭 |+| `commercial_hide_docs` | 隐藏文档和帮助菜单,包括更新日志、文档和反馈(需要商业授权)。 | 关闭 |## 交互式助理分享:部署与灰度边界diff --git a/packages/app-config/src/featureFlags/schema.ts b/packages/app-config/src/featureFlags/schema.tsindex d448285367b..bb887c4b6cb 100644--- a/packages/app-config/src/featureFlags/schema.ts+++ b/packages/app-config/src/featureFlags/schema.ts@@ -56,6 +56,15 @@ export const FeatureFlagsSchema = z.object({*/agent_deferred_init: FeatureFlagValue.optional(),+ /**+ * Rollout gate for answering a plain chat send to a heterogeneous agent+ * (Claude Code, Codex, …) on an online device before the device dispatch+ * completes; the dispatch runs after the response and a failure lands on the+ * assistant message. Off: the send waits for the device to accept the run.+ * Array values are user ids.+ */+ agent_deferred_hetero_dispatch: FeatureFlagValue.optional(),+/*** Keep the immutable per-operation tool set out of the agent state blob that* is rewritten at every step; it is written once to its own Redis key and@@ -210,6 +219,7 @@ export const DEFAULT_FEATURE_FLAGS: IFeatureFlags = {// Off until the client executor ships everywhere; allowlist first.agent_llm_relay: false,agent_deferred_init: false,+ agent_deferred_hetero_dispatch: false,agent_runtime_strip_operation_toolset: false,// Off until an admin publishes a user allowlist or flips it to true.@@ -273,6 +283,11 @@ export const mapFeatureFlagsEnvToState = (userId,'agent_deferred_init',),+ enableDeferredHeteroDispatch: evaluateFeatureFlag(+ config.agent_deferred_hetero_dispatch,+ userId,+ 'agent_deferred_hetero_dispatch',+ ),enableStripOperationToolset: evaluateFeatureFlag(config.agent_runtime_strip_operation_toolset,userId,diff --git a/packages/types/src/serverConfig.ts b/packages/types/src/serverConfig.tsindex da8aa53daa3..a1b0db5e2cf 100644--- a/packages/types/src/serverConfig.ts+++ b/packages/types/src/serverConfig.ts@@ -72,6 +72,11 @@ export type IFeatureFlagsState = {enableLlmRelay: boolean | undefined;/** A plain chat send leaves its init to the step-0 worker (`agent_deferred_init`). */enableDeferredInit: boolean | undefined;+ /**+ * A plain chat send to a heterogeneous agent on an online device returns+ * before the device dispatch completes (`agent_deferred_hetero_dispatch`).+ */+ enableDeferredHeteroDispatch: 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