Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ“ˆ perf(agent): trace every stage of the send path, not just tool discovery (#20464)

Arvin Xu6951ebc5a200
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
index de2ca19e61b..dddeb82afed 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
@@ -87,6 +87,7 @@ import {
import { type IStreamEventManager } from '@/server/modules/AgentRuntime/types';
import { emitAgentSignalSourceEvent } from '@/server/services/agentSignal';
import { toAgentSignalTraceEvents } from '@/server/services/agentSignal/observability/traceEvents';
+import { traceStartStage } from '@/server/services/aiAgent/pipeline/sendTracing';
import { FileService } from '@/server/services/file';
import { mcpService } from '@/server/services/mcp';
import { MessageService } from '@/server/services/message';
@@ -1207,43 +1208,45 @@ export class AgentRuntimeService {
// stop can still reach the member's supervisor (`loadGroupMemberBridge`).
const groupMemberBridge = hooks?.find((hook) => hook.id === 'group-member-bridge')?.webhook
?.body as Omit<GroupActionMemberBridgeParams, 'operationId' | 'reason'> | undefined;
- const operationStartPersisted = await this.completionLifecycle.recordStart({
- agentId: appContext?.agentId ?? null,
- appContext: {
- defaultTaskAssigneeAgentId: appContext?.defaultTaskAssigneeAgentId,
- documentId: appContext?.documentId,
- editingAgentId: appContext?.editingAgentId,
- groupId: appContext?.groupId,
- scope: appContext?.scope,
- sessionId: appContext?.sessionId,
- sourceMessageId: appContext?.sourceMessageId,
- },
- chatGroupId: appContext?.groupId ?? null,
- maxSteps,
- // Persist the Agent Signal run marker on the operation row so server-side
- // self-iteration tools can read it back (operation.metadata.agentSignal) at tool-call
- // time β€” the trimmed appContext above intentionally drops it.
- ...(appContext?.agentSignal || interventionResolution || groupMemberBridge
- ? {
- metadata: {
- ...(appContext?.agentSignal ? { agentSignal: appContext.agentSignal } : {}),
- ...(interventionResolution
- ? { agentInterventionContinuation: interventionResolution }
- : {}),
- ...(groupMemberBridge ? { groupMemberBridge } : {}),
- },
- }
- : {}),
- model: modelRuntimeConfig?.model,
- modelRuntimeConfig: withoutFrozenModelFacts(modelRuntimeConfig),
- operationId,
- parentOperationId: parentOperationId ?? null,
- provider: modelRuntimeConfig?.provider,
- taskId: appContext?.taskId ?? null,
- threadId: appContext?.threadId ?? null,
- topicId: appContext?.topicId ?? null,
- trigger: appContext?.trigger,
- });
+ const operationStartPersisted = await traceStartStage('record_start', () =>
+ this.completionLifecycle.recordStart({
+ agentId: appContext?.agentId ?? null,
+ appContext: {
+ defaultTaskAssigneeAgentId: appContext?.defaultTaskAssigneeAgentId,
+ documentId: appContext?.documentId,
+ editingAgentId: appContext?.editingAgentId,
+ groupId: appContext?.groupId,
+ scope: appContext?.scope,
+ sessionId: appContext?.sessionId,
+ sourceMessageId: appContext?.sourceMessageId,
+ },
+ chatGroupId: appContext?.groupId ?? null,
+ maxSteps,
+ // Persist the Agent Signal run marker on the operation row so server-side
+ // self-iteration tools can read it back (operation.metadata.agentSignal) at tool-call
+ // time β€” the trimmed appContext above intentionally drops it.
+ ...(appContext?.agentSignal || interventionResolution || groupMemberBridge
+ ? {
+ metadata: {
+ ...(appContext?.agentSignal ? { agentSignal: appContext.agentSignal } : {}),
+ ...(interventionResolution
+ ? { agentInterventionContinuation: interventionResolution }
+ : {}),
+ ...(groupMemberBridge ? { groupMemberBridge } : {}),
+ },
+ }
+ : {}),
+ model: modelRuntimeConfig?.model,
+ modelRuntimeConfig: withoutFrozenModelFacts(modelRuntimeConfig),
+ operationId,
+ parentOperationId: parentOperationId ?? null,
+ provider: modelRuntimeConfig?.provider,
+ taskId: appContext?.taskId ?? null,
+ threadId: appContext?.threadId ?? null,
+ topicId: appContext?.topicId ?? null,
+ trigger: appContext?.trigger,
+ }),
+ );
if (interventionResolution && !operationStartPersisted) {
throw new Error(
`Failed to durably persist intervention continuation ${operationId} before dispatch`,
@@ -1438,30 +1441,34 @@ export class AgentRuntimeService {
// not one per member (single-connection multiplexing).
const mirrorToOperationId =
appContext?.orchestrationRole === 'member' ? (parentOperationId ?? undefined) : undefined;
- await this.coordinator.createAgentOperation(operationId, {
- acceptsMemberRuntimeEnd,
- agentConfig,
- // Persisted so a queue worker that never ran this op's init still
- // applies the owner-configured visitor redaction policy instead of the
- // fail-closed full strip. See `gatewayVisitorRedaction.ts`.
- visitorRedaction: agentShareVisitor
- ? {
- showErrorDetails: agentShareVisitor.showErrorDetails,
- showModelInfo: agentShareVisitor.showModelInfo,
- }
- : undefined,
- mirrorToOperationId,
- modelRuntimeConfig: withoutFrozenModelFacts(modelRuntimeConfig),
- // Share-visitor runs execute as the creator (`userId`) but stream only
- // to the visitor β€” the gateway registers the WS channel under this id.
- streamOwnerUserId: agentShareVisitor?.visitorUserId,
- userId,
- workspaceId: this.workspaceId,
- });
+ await traceStartStage('runtime_meta', () =>
+ this.coordinator.createAgentOperation(operationId, {
+ acceptsMemberRuntimeEnd,
+ agentConfig,
+ // Persisted so a queue worker that never ran this op's init still
+ // applies the owner-configured visitor redaction policy instead of the
+ // fail-closed full strip. See `gatewayVisitorRedaction.ts`.
+ visitorRedaction: agentShareVisitor
+ ? {
+ showErrorDetails: agentShareVisitor.showErrorDetails,
+ showModelInfo: agentShareVisitor.showModelInfo,
+ }
+ : undefined,
+ mirrorToOperationId,
+ modelRuntimeConfig: withoutFrozenModelFacts(modelRuntimeConfig),
+ // Share-visitor runs execute as the creator (`userId`) but stream only
+ // to the visitor β€” the gateway registers the WS channel under this id.
+ streamOwnerUserId: agentShareVisitor?.visitorUserId,
+ userId,
+ workspaceId: this.workspaceId,
+ }),
+ );
operationCreated = true;
// Save initial state
- await this.coordinator.saveAgentState(operationId, initialState as any);
+ await traceStartStage('save_state', () =>
+ this.coordinator.saveAgentState(operationId, initialState as any),
+ );
// Register external hooks
hookDispatcher.register(operationId, hooks ?? []);
@@ -1528,17 +1535,20 @@ export class AgentRuntimeService {
// Both local and queue modes use scheduleMessage
// LocalQueueServiceImpl uses setTimeout + callback mechanism
// QStashQueueServiceImpl schedules HTTP requests
- messageId = await this.queueService.scheduleMessage({
- context: initialContext,
- deduplicationId,
- delay: 50, // Short delay for startup
- endpoint: `${this.baseURL}/run`,
- operationId,
- priority: 'high',
- retryDelay: queueRetryDelay,
- retries: queueRetries,
- stepIndex: initialStepCount,
- });
+ const queueService = this.queueService;
+ messageId = await traceStartStage('schedule_step', () =>
+ queueService.scheduleMessage({
+ context: initialContext,
+ deduplicationId,
+ delay: 50, // Short delay for startup
+ endpoint: `${this.baseURL}/run`,
+ operationId,
+ priority: 'high',
+ retryDelay: queueRetryDelay,
+ retries: queueRetries,
+ stepIndex: initialStepCount,
+ }),
+ );
if (interventionResolution && deduplicationId) {
await this.persistInterventionDispatchAck({
deduplicationId,
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index 9b6124f7eea..2142b98bdc4 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -77,6 +77,7 @@ import { dispatchHeteroAgent } from './pipeline/heteroDispatch';
import { buildOperationInitRequest, runOperationInit } from './pipeline/operationInit';
import { createHistoryMessagesLoader } from './pipeline/operationPrep';
import { resolveRunAgentConfig } from './pipeline/resolveRunAgentConfig';
+import { traceSendStage } from './pipeline/sendTracing';
import { startOperation } from './pipeline/startOperation';
import { resolveNewTopicSnapshot, setupTurn } from './pipeline/turnSetup';
import { createRunFacts, type RunFacts } from './runFacts';
@@ -1066,24 +1067,26 @@ export class AiAgentService {
memberDeviceOverride,
persistAgentId,
resolvedAgentId,
- } = await resolveRunAgentConfig(
- {
- db: this.db,
- resolveAgentConfigOrThrow: (id) => this.resolveAgentConfigOrThrow(id),
- userId: this.userId,
- workspaceId: this.workspaceId,
- },
- {
- appContext,
- chatConfigOverride,
- identifier,
- instructions,
- modelOverride,
- providerOverride,
- shareVisitorUserId: shareGate?.visitorUserId,
- throwIfExecutionAborted,
- toolModeOverride,
- },
+ } = await traceSendStage('agent_config', () =>
+ resolveRunAgentConfig(
+ {
+ db: this.db,
+ resolveAgentConfigOrThrow: (id) => this.resolveAgentConfigOrThrow(id),
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ },
+ {
+ appContext,
+ chatConfigOverride,
+ identifier,
+ instructions,
+ modelOverride,
+ providerOverride,
+ shareVisitorUserId: shareGate?.visitorUserId,
+ throwIfExecutionAborted,
+ toolModeOverride,
+ },
+ ),
);
// Share-visitor runs must never see the creator's files/knowledge bases.
@@ -1159,19 +1162,21 @@ export class AiAgentService {
approvedToolEntries,
batchApprovalAnchorId,
resumeApprovalPlugin,
- } = await claimApprovalResume(
- { messageModel: this.messageModel },
- {
- appContext,
- approvalClaim,
- approvalDecisions,
- parentMessageId,
- providedApprovalResolutionRequestId,
- providedApprovalSourceOperationId,
- resumeApprovals,
- resumeParentMessage,
- resumeToolResult,
- },
+ } = await traceSendStage('approval_claim', () =>
+ claimApprovalResume(
+ { messageModel: this.messageModel },
+ {
+ appContext,
+ approvalClaim,
+ approvalDecisions,
+ parentMessageId,
+ providedApprovalResolutionRequestId,
+ providedApprovalSourceOperationId,
+ resumeApprovals,
+ resumeParentMessage,
+ resumeToolResult,
+ },
+ ),
);
// Deterministic continuation identity for a generic (v2) approval claim.
@@ -1217,45 +1222,47 @@ export class AiAgentService {
// Stage 3 + shared turn setup β€” topic creation/reuse (with the pinned
// model), device-access policy, hetero detection, attachment ingestion, and
// the persisted user/assistant rows (see `pipeline/turnSetup`).
- const turn = await setupTurn(
- {
- db: this.db,
- messageModel: this.messageModel,
- topicModel: this.topicModel,
- userId: this.userId,
- workspaceId: this.workspaceId,
- },
- {
- agentConfig,
- agentSlug,
- appContext,
- assistantAgentId,
- attachedFileIds,
- batchApprovalAnchorId,
- botContext,
- botSender,
- clientIds,
- continuationAssistantId,
- conversationAgentId,
- createdThreadId,
- externalOrigin,
- cronJobId,
- files,
- modelOverride,
- operationTaskId,
- parentMessageId,
- prompt,
- providerOverride,
- requestedDeviceId,
- resolvedAgentId,
- resume,
- runFromHistory,
- shareGate,
- steer,
- throwIfExecutionAborted,
- title,
- trigger,
- },
+ const turn = await traceSendStage('turn_setup', () =>
+ setupTurn(
+ {
+ db: this.db,
+ messageModel: this.messageModel,
+ topicModel: this.topicModel,
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ },
+ {
+ agentConfig,
+ agentSlug,
+ appContext,
+ assistantAgentId,
+ attachedFileIds,
+ batchApprovalAnchorId,
+ botContext,
+ botSender,
+ clientIds,
+ continuationAssistantId,
+ conversationAgentId,
+ createdThreadId,
+ externalOrigin,
+ cronJobId,
+ files,
+ modelOverride,
+ operationTaskId,
+ parentMessageId,
+ prompt,
+ providerOverride,
+ requestedDeviceId,
+ resolvedAgentId,
+ resume,
+ runFromHistory,
+ shareGate,
+ steer,
+ throwIfExecutionAborted,
+ title,
+ trigger,
+ },
+ ),
);
assistantMessageRef.current = turn.assistantMessageId;
const {
@@ -1348,43 +1355,45 @@ export class AiAgentService {
let globalMemoryEnabled = agentMemoryEnabled ?? false;
let enableExpertise = false;
let userTimezone: string | undefined;
- try {
- const settings = await runFacts.userSettings();
- const memorySettings = settings?.memory as { enabled?: boolean } | undefined;
-
- globalMemoryEnabled = agentMemoryEnabled ?? memorySettings?.enabled !== false;
-
- // Timezone drives the session-date placeholder rendered back to whoever
- // is actually conversing. In a share-visitor run that is the VISITOR,
- // not the creator whose settings this block otherwise reads β€” memory /
- // expertise intentionally stay creator-scoped below (gated by
- // `allowReadMemory`), but the timezone has no such gate and must not
- // leak the creator's own setting into a visitor's turn.
- if (shareGate) {
- const visitorSettings = await runFacts.userSettings(shareGate.visitorUserId);
- const visitorGeneralSettings = visitorSettings?.general as
- { timezone?: string } | undefined;
- userTimezone = visitorGeneralSettings?.timezone;
- } else {
- const generalSettings = settings?.general as { timezone?: string } | undefined;
- userTimezone = generalSettings?.timezone;
+ await traceSendStage('run_settings', async () => {
+ try {
+ const settings = await runFacts.userSettings();
+ const memorySettings = settings?.memory as { enabled?: boolean } | undefined;
+
+ globalMemoryEnabled = agentMemoryEnabled ?? memorySettings?.enabled !== false;
+
+ // Timezone drives the session-date placeholder rendered back to whoever
+ // is actually conversing. In a share-visitor run that is the VISITOR,
+ // not the creator whose settings this block otherwise reads β€” memory /
+ // expertise intentionally stay creator-scoped below (gated by
+ // `allowReadMemory`), but the timezone has no such gate and must not
+ // leak the creator's own setting into a visitor's turn.
+ if (shareGate) {
+ const visitorSettings = await runFacts.userSettings(shareGate.visitorUserId);
+ const visitorGeneralSettings = visitorSettings?.general as
+ { timezone?: string } | undefined;
+ userTimezone = visitorGeneralSettings?.timezone;
+ } else {
+ const generalSettings = settings?.general as { timezone?: string } | undefined;
+ userTimezone = generalSettings?.timezone;
+ }
+ } catch (error) {
+ log('execAgent: failed to fetch user settings: %O', error);
}
- } catch (error) {
- log('execAgent: failed to fetch user settings: %O', error);
- }
- try {
- const preference = await new UserModel(this.db, this.userId).getUserPreference();
- enableExpertise = preference?.lab?.enableSelfLearning === true;
- } catch (error) {
- console.error('Failed to resolve expertise injection Lab preference:', error);
- }
- // Share visitors only get the creator's memory (persona + learned
- // expertise) when the share explicitly allows it β€” both surfaces would
- // otherwise leak the creator's personal context into visitor turns.
- if (shareGate && !shareGate.shareConfig.allowReadMemory) {
- globalMemoryEnabled = false;
- enableExpertise = false;
- }
+ try {
+ const preference = await new UserModel(this.db, this.userId).getUserPreference();
+ enableExpertise = preference?.lab?.enableSelfLearning === true;
+ } catch (error) {
+ console.error('Failed to resolve expertise injection Lab preference:', error);
+ }
+ // Share visitors only get the creator's memory (persona + learned
+ // expertise) when the share explicitly allows it β€” both surfaces would
+ // otherwise leak the creator's personal context into visitor turns.
+ if (shareGate && !shareGate.shareConfig.allowReadMemory) {
+ globalMemoryEnabled = false;
+ enableExpertise = false;
+ }
+ });
log(
'execAgent: globalMemoryEnabled=%s, timezone=%s',
globalMemoryEnabled,
@@ -1463,26 +1472,28 @@ export class AiAgentService {
topicBoundDeviceId: turn.topicBoundDeviceId,
});
- const { discovery, initialContext, prep } = await runOperationInit(
- {
- agentDocumentsService: this.agentDocumentsService,
- agentModel: this.agentModel,
- bindTopicWorkingDirectory: (p) => this.bindTopicWorkingDirectory(p),
- composioService: this.composioService,
- connectorModel: this.connectorModel,
- connectorToolModel: this.connectorToolModel,
- db: this.db,
- getMarketService: () => this.getMarketService(runFacts),
- loadHistoryMessages,
- messageModel: this.messageModel,
- pluginModel: this.pluginModel,
- throwIfExecutionAborted,
- topicModel: this.topicModel,
- userId: this.userId,
- workspaceId: this.workspaceId,
- },
- runContext,
- initRequest,
+ const { discovery, initialContext, prep } = await traceSendStage('operation_init', () =>
+ runOperationInit(
+ {
+ agentDocumentsService: this.agentDocumentsService,
+ agentModel: this.agentModel,
+ bindTopicWorkingDirectory: (p) => this.bindTopicWorkingDirectory(p),
+ composioService: this.composioService,
+ connectorModel: this.connectorModel,
+ connectorToolModel: this.connectorToolModel,
+ db: this.db,
+ getMarketService: () => this.getMarketService(runFacts),
+ loadHistoryMessages,
+ messageModel: this.messageModel,
+ pluginModel: this.pluginModel,
+ throwIfExecutionAborted,
+ topicModel: this.topicModel,
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ },
+ runContext,
+ initRequest,
+ ),
);
// 17. Log final operation parameters summary
@@ -1537,55 +1548,57 @@ export class AiAgentService {
// 19. Create the operation via AgentRuntimeService, persist the reconnect
// marker, and mint the gateway token (see `pipeline/startOperation`).
- return startOperation(
- {
- agentRuntimeService: this.agentRuntimeService,
- messageModel: this.messageModel,
- retirePendingApprovalOperation: (opId) => this.retirePendingApprovalOperation(opId),
- topicModel: this.topicModel,
- userId: this.userId,
- withholdGatewayToken: this.withholdGatewayToken,
- workspaceId: this.workspaceId,
- },
- runContext,
- {
- acceptsMemberRuntimeEnd: params.acceptsMemberRuntimeEnd,
- approvalClaim,
- approvalSourceOperationId,
- approvalSourceToolMessageIds,
- autoStart,
- onOperationCreated: params.onOperationCreated,
- botContext,
- botPlatformContext,
- clientIp,
- disabledPluginIds,
- discordContext,
- discovery,
- enableExpertise,
- evalContext,
- evalRuntime,
- hooks,
- initialContext,
- initialStepCount,
- maxSteps,
- operationId,
- operationTaskId,
- parentOperationId,
- prep,
- providedApprovalResolutionRequestId,
- queueRetries,
- queueRetryDelay,
- signal,
- stream,
- clientProtocol: params.clientProtocol,
- includeFinalState: params.includeFinalState,
- llmExecutor: params.llmExecutor,
- topicStartOwnerOperationId: params.topicStartOwnerOperationId,
- updateAbortedAssistantMessage,
- userAgent,
- userInterventionConfig,
- userTimezone,
- },
+ return traceSendStage('start_operation', () =>
+ startOperation(
+ {
+ agentRuntimeService: this.agentRuntimeService,
+ messageModel: this.messageModel,
+ retirePendingApprovalOperation: (opId) => this.retirePendingApprovalOperation(opId),
+ topicModel: this.topicModel,
+ userId: this.userId,
+ withholdGatewayToken: this.withholdGatewayToken,
+ workspaceId: this.workspaceId,
+ },
+ runContext,
+ {
+ acceptsMemberRuntimeEnd: params.acceptsMemberRuntimeEnd,
+ approvalClaim,
+ approvalSourceOperationId,
+ approvalSourceToolMessageIds,
+ autoStart,
+ onOperationCreated: params.onOperationCreated,
+ botContext,
+ botPlatformContext,
+ clientIp,
+ disabledPluginIds,
+ discordContext,
+ discovery,
+ enableExpertise,
+ evalContext,
+ evalRuntime,
+ hooks,
+ initialContext,
+ initialStepCount,
+ maxSteps,
+ operationId,
+ operationTaskId,
+ parentOperationId,
+ prep,
+ providedApprovalResolutionRequestId,
+ queueRetries,
+ queueRetryDelay,
+ signal,
+ stream,
+ clientProtocol: params.clientProtocol,
+ includeFinalState: params.includeFinalState,
+ llmExecutor: params.llmExecutor,
+ topicStartOwnerOperationId: params.topicStartOwnerOperationId,
+ updateAbortedAssistantMessage,
+ userAgent,
+ userInterventionConfig,
+ userTimezone,
+ },
+ ),
);
}
diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/sendTracing.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/sendTracing.test.ts
new file mode 100644
index 00000000000..fe948faad6d
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/sendTracing.test.ts
@@ -0,0 +1,80 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createStageTracer, openStageMark } from '../sendTracing';
+
+const { span, startActiveSpan, startSpan } = vi.hoisted(() => {
+ const span = { end: vi.fn(), setAttribute: vi.fn(), setStatus: vi.fn() };
+ return {
+ span,
+ startActiveSpan: vi.fn((_name: string, fn: (span: unknown) => unknown) => fn(span)),
+ startSpan: vi.fn(() => span),
+ };
+});
+
+vi.mock('@lobechat/observability-otel/modules/agent-runtime', () => ({
+ tracer: { startActiveSpan, startSpan },
+}));
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('createStageTracer', () => {
+ it('names the span after the family and stage and ends it on success', async () => {
+ const trace = createStageTracer('execAgent');
+
+ await expect(trace('turn_setup', async () => 'ok')).resolves.toBe('ok');
+
+ expect(startActiveSpan).toHaveBeenCalledWith('execAgent turn_setup', expect.any(Function));
+ expect(span.end).toHaveBeenCalledTimes(1);
+ expect(span.setStatus).not.toHaveBeenCalled();
+ });
+
+ it('marks the span errored, still ends it, and rethrows when the stage throws', async () => {
+ const trace = createStageTracer('execAgent');
+
+ await expect(
+ trace('agent_config', async () => {
+ throw new Error('boom');
+ }),
+ ).rejects.toThrow('boom');
+
+ expect(span.setStatus).toHaveBeenCalledWith(expect.objectContaining({ message: 'boom' }));
+ expect(span.end).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('openStageMark', () => {
+ it('opens a plain span and closes it from finally on the success path', () => {
+ const mark = openStageMark('turn_setup')('topic');
+ try {
+ expect(startSpan).toHaveBeenCalledWith('turn_setup topic');
+ expect(span.end).not.toHaveBeenCalled();
+ } finally {
+ mark.end();
+ }
+
+ expect(span.end).toHaveBeenCalledTimes(1);
+ expect(span.setStatus).not.toHaveBeenCalled();
+ });
+
+ it('records the error and still closes the span when the block throws', () => {
+ const mark = openStageMark('turn_setup')('topic');
+
+ expect(() => {
+ try {
+ throw new Error('topic missing');
+ } catch (error) {
+ mark.fail(error);
+ throw error;
+ } finally {
+ mark.end();
+ }
+ }).toThrow('topic missing');
+
+ expect(span.setStatus).toHaveBeenCalledWith(
+ expect.objectContaining({ message: 'topic missing' }),
+ );
+ expect(span.end).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.parallelReads.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.parallelReads.test.ts
index e9bdc05bebe..a5d0a4c72ad 100644
--- a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.parallelReads.test.ts
+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.parallelReads.test.ts
@@ -82,6 +82,8 @@ vi.mock('@/database/models/file', () => ({
vi.mock('@lobechat/observability-otel/modules/agent-runtime', () => ({
tracer: {
startActiveSpan: (_name: string, fn: (span: unknown) => unknown) => fn(discoverySpan),
+ // Marked blocks (`openStageMark`) open a plain span.
+ startSpan: () => discoverySpan,
},
}));
diff --git a/apps/server/src/services/aiAgent/pipeline/discoveryTracing.ts b/apps/server/src/services/aiAgent/pipeline/discoveryTracing.ts
index 20df6b2e236..fa48f40e56f 100644
--- a/apps/server/src/services/aiAgent/pipeline/discoveryTracing.ts
+++ b/apps/server/src/services/aiAgent/pipeline/discoveryTracing.ts
@@ -1,23 +1,14 @@
import type { Span } from '@lobechat/observability-otel/api';
import { SpanStatusCode } from '@lobechat/observability-otel/api';
-import { tracer as agentRuntimeTracer } from '@lobechat/observability-otel/modules/agent-runtime';
+
+import { createStageTracer } from './sendTracing';
/**
* Wrap an IO-bound discovery stage in a span. Discovery runs on the send path
* before the operation exists, so these spans are the only breakdown of how
* long a user waits between "message saved" and "operation started".
*/
-export const traceDiscoveryStage = <T>(stage: string, fn: (span: Span) => Promise<T>): Promise<T> =>
- agentRuntimeTracer.startActiveSpan(`tool_discovery ${stage}`, async (span) => {
- try {
- return await fn(span);
- } catch (error) {
- span.setStatus({ code: SpanStatusCode.ERROR, message: (error as Error)?.message });
- throw error;
- } finally {
- span.end();
- }
- });
+export const traceDiscoveryStage = createStageTracer('tool_discovery');
/**
* Surface failures a stage absorbed instead of throwing (settled promises,
diff --git a/apps/server/src/services/aiAgent/pipeline/operationInit.ts b/apps/server/src/services/aiAgent/pipeline/operationInit.ts
index 3c9551e9e9d..f81a3861f8d 100644
--- a/apps/server/src/services/aiAgent/pipeline/operationInit.ts
+++ b/apps/server/src/services/aiAgent/pipeline/operationInit.ts
@@ -22,6 +22,7 @@ import {
type OperationPrepResult,
prepareOperation,
} from './operationPrep';
+import { traceSendStage } from './sendTracing';
import { discoverTools, type ToolDiscoveryResult } from './toolDiscovery';
import type { RunAttachments } from './turnSetup';
@@ -142,75 +143,79 @@ export const runOperationInit = async (
request: OperationInitRequest,
): Promise<OperationInitResult> => {
// Stage 5 (5a–5f) β€” tool discovery (see `pipeline/toolDiscovery`).
- const discovery = await discoverTools(
- {
- agentDocumentsService: deps.agentDocumentsService,
- composioService: deps.composioService,
- connectorModel: deps.connectorModel,
- connectorToolModel: deps.connectorToolModel,
- db: deps.db,
- getMarketService: deps.getMarketService,
- messageModel: deps.messageModel,
- pluginModel: deps.pluginModel,
- userId: deps.userId,
- workspaceId: deps.workspaceId,
- },
- ctx,
- {
- additionalPluginIds: request.additionalPluginIds,
- agentSlug: request.agentSlug,
- attachedFileIds: request.attachedFileIds,
- botContext: request.botContext,
- disableLocalSystem: request.disableLocalSystem,
- disableSelfFeedbackIntentTool: request.disableSelfFeedbackIntentTool,
- disableTools: request.disableTools,
- disabledPluginIds: request.disabledPluginIds,
- discordContext: request.discordContext,
- exclusivePluginIds: request.exclusivePluginIds,
- externalFileTypes: request.externalFileTypes,
- functionTools: request.functionTools,
- globalMemoryEnabled: request.globalMemoryEnabled,
- hasMentionedAgents: request.hasMentionedAgents,
- isFixedDeviceTarget: request.isFixedDeviceTarget,
- loadHistoryMessages: deps.loadHistoryMessages,
- localDeviceId: request.localDeviceId,
- requestTrigger: request.requestTrigger,
- requestedDeviceId: request.requestedDeviceId,
- selectedToolIds: request.selectedToolIds,
- throwIfExecutionAborted: deps.throwIfExecutionAborted,
- topicBoundDeviceId: request.topicBoundDeviceId,
- },
+ const discovery = await traceSendStage('tool_discovery', () =>
+ discoverTools(
+ {
+ agentDocumentsService: deps.agentDocumentsService,
+ composioService: deps.composioService,
+ connectorModel: deps.connectorModel,
+ connectorToolModel: deps.connectorToolModel,
+ db: deps.db,
+ getMarketService: deps.getMarketService,
+ messageModel: deps.messageModel,
+ pluginModel: deps.pluginModel,
+ userId: deps.userId,
+ workspaceId: deps.workspaceId,
+ },
+ ctx,
+ {
+ additionalPluginIds: request.additionalPluginIds,
+ agentSlug: request.agentSlug,
+ attachedFileIds: request.attachedFileIds,
+ botContext: request.botContext,
+ disableLocalSystem: request.disableLocalSystem,
+ disableSelfFeedbackIntentTool: request.disableSelfFeedbackIntentTool,
+ disableTools: request.disableTools,
+ disabledPluginIds: request.disabledPluginIds,
+ discordContext: request.discordContext,
+ exclusivePluginIds: request.exclusivePluginIds,
+ externalFileTypes: request.externalFileTypes,
+ functionTools: request.functionTools,
+ globalMemoryEnabled: request.globalMemoryEnabled,
+ hasMentionedAgents: request.hasMentionedAgents,
+ isFixedDeviceTarget: request.isFixedDeviceTarget,
+ loadHistoryMessages: deps.loadHistoryMessages,
+ localDeviceId: request.localDeviceId,
+ requestTrigger: request.requestTrigger,
+ requestedDeviceId: request.requestedDeviceId,
+ selectedToolIds: request.selectedToolIds,
+ throwIfExecutionAborted: deps.throwIfExecutionAborted,
+ topicBoundDeviceId: request.topicBoundDeviceId,
+ },
+ ),
);
// Stages 9.4–18 β€” device system info, agent-management context, persona
// memory, history + message assembly, the base initial runtime context,
// workspace init, the OperationSkillSet, and the expertise snapshot
// (see `pipeline/operationPrep`).
- const prep = await prepareOperation(
- {
- agentDocumentsService: deps.agentDocumentsService,
- agentModel: deps.agentModel,
- bindTopicWorkingDirectory: deps.bindTopicWorkingDirectory,
- db: deps.db,
- topicModel: deps.topicModel,
- userId: deps.userId,
- workspaceId: deps.workspaceId,
- },
- ctx,
- {
- botPlatformContext: request.botPlatformContext,
- disabledPluginIds: request.disabledPluginIds,
- discovery,
- ephemeralUserMessage: request.ephemeralUserMessage,
- globalMemoryEnabled: request.globalMemoryEnabled,
- hasMentionedAgents: request.hasMentionedAgents,
- loadHistoryMessages: deps.loadHistoryMessages,
- mentionedAgents: request.mentionedAgents,
- operationId: request.operationId,
- runAttachments: request.runAttachments,
- runFromHistory: request.resumeFromHistory,
- throwIfExecutionAborted: deps.throwIfExecutionAborted,
- },
+ const prep = await traceSendStage('operation_prep', () =>
+ prepareOperation(
+ {
+ agentDocumentsService: deps.agentDocumentsService,
+ agentModel: deps.agentModel,
+ bindTopicWorkingDirectory: deps.bindTopicWorkingDirectory,
+ db: deps.db,
+ topicModel: deps.topicModel,
+ userId: deps.userId,
+ workspaceId: deps.workspaceId,
+ },
+ ctx,
+ {
+ botPlatformContext: request.botPlatformContext,
+ disabledPluginIds: request.disabledPluginIds,
+ discovery,
+ ephemeralUserMessage: request.ephemeralUserMessage,
+ globalMemoryEnabled: request.globalMemoryEnabled,
+ hasMentionedAgents: request.hasMentionedAgents,
+ loadHistoryMessages: deps.loadHistoryMessages,
+ mentionedAgents: request.mentionedAgents,
+ operationId: request.operationId,
+ runAttachments: request.runAttachments,
+ runFromHistory: request.resumeFromHistory,
+ throwIfExecutionAborted: deps.throwIfExecutionAborted,
+ },
+ ),
);
// 16b/16c β€” override the initial context with the human decision
diff --git a/apps/server/src/services/aiAgent/pipeline/sendTracing.ts b/apps/server/src/services/aiAgent/pipeline/sendTracing.ts
new file mode 100644
index 00000000000..d3d86707886
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/sendTracing.ts
@@ -0,0 +1,74 @@
+import type { Span } from '@lobechat/observability-otel/api';
+import { SpanStatusCode } from '@lobechat/observability-otel/api';
+import { tracer as agentRuntimeTracer } from '@lobechat/observability-otel/modules/agent-runtime';
+
+export type StageTracer = <T>(stage: string, fn: (span: Span) => Promise<T>) => Promise<T>;
+
+/**
+ * Build a span wrapper for one family of send-path stages. Every stage of the
+ * family shares a name prefix (`tool_discovery connectors`,
+ * `execAgent turn_setup`, …) so a trace reads as a timeline of where the
+ * user waited between pressing send and the operation starting.
+ *
+ * The wrapper only records a failure when the callback throws: a stage that
+ * absorbs its own errors must mark the span itself (see `markDegradedStage`).
+ */
+export const createStageTracer =
+ (family: string): StageTracer =>
+ (stage, fn) =>
+ agentRuntimeTracer.startActiveSpan(`${family} ${stage}`, async (span) => {
+ try {
+ return await fn(span);
+ } catch (error) {
+ span.setStatus({ code: SpanStatusCode.ERROR, message: (error as Error)?.message });
+ throw error;
+ } finally {
+ span.end();
+ }
+ });
+
+export interface StageMark {
+ /** Close the span. Call from `finally` so every exit path reaches it. */
+ end: () => void;
+ /** Record the error that is about to propagate; call from `catch` before rethrowing. */
+ fail: (error: unknown) => void;
+}
+
+/**
+ * A span over a block that cannot be wrapped in a callback: one that assigns
+ * the enclosing function's narrowed bindings (TypeScript drops a `let`'s
+ * narrowing for every later read once a closure assigns it). The caller
+ * owns the lifecycle and must shape it as
+ * `try { … } catch (e) { mark.fail(e); throw e; } finally { mark.end(); }`,
+ * so a throw on any path still records the error and closes the span. The
+ * span is not made active; nested stages attach to the enclosing one.
+ */
+export const openStageMark =
+ (family: string) =>
+ (stage: string): StageMark => {
+ const span = agentRuntimeTracer.startSpan(`${family} ${stage}`);
+ return {
+ end: () => span.end(),
+ fail: (error) =>
+ span.setStatus({ code: SpanStatusCode.ERROR, message: (error as Error)?.message }),
+ };
+ };
+
+/**
+ * The top-level stages of `execAgent`: agent config, the approval claim, turn
+ * setup (rows + attachments), the init stage (discovery + prep) and operation
+ * start. Postgres and Redis carry no spans of their own, so these are the
+ * only breakdown of the untraced stretches before discovery and after it.
+ *
+ * Stages are wrapped where they are a call, and marked (`openStageMark`,
+ * inside try/catch/finally) where they are a block that assigns the
+ * function's narrowed bindings; either way every exit records the error
+ * and closes the span.
+ */
+export const traceSendStage = createStageTracer('execAgent');
+
+/** The serial reads of `prepareOperation` (persona, history, workspace scan, skills, …). */
+export const tracePrepStage = createStageTracer('operation_prep');
+
+/** The persistence steps of `createOperation` (row, runtime meta + gateway init, state, queue). */
+export const traceStartStage = createStageTracer('operation_start');
diff --git a/apps/server/src/services/aiAgent/pipeline/startOperation.ts b/apps/server/src/services/aiAgent/pipeline/startOperation.ts
index 337cebb8ed7..6150e5f7d2a 100644
--- a/apps/server/src/services/aiAgent/pipeline/startOperation.ts
+++ b/apps/server/src/services/aiAgent/pipeline/startOperation.ts
@@ -10,6 +10,7 @@ import { isAbortError } from '@/server/services/agentRuntime/abort';
import type { ExecRunContext, InternalExecAgentParams } from '../types';
import type { ApprovalClaimState } from './approvalResume';
import type { OperationPrepResult } from './operationPrep';
+import { traceStartStage } from './sendTracing';
import type { ToolDiscoveryResult } from './toolDiscovery';
const log = debug('lobe-server:ai-agent-service');
@@ -395,7 +396,9 @@ export const startOperation = async (
let gatewayToken: string | undefined;
if (!deps.withholdGatewayToken) {
try {
- gatewayToken = await signUserJWT(shareGate?.visitorUserId ?? deps.userId);
+ gatewayToken = await traceStartStage('sign_gateway_token', () =>
+ signUserJWT(shareGate?.visitorUserId ?? deps.userId),
+ );
} catch {
log('execAgent: failed to sign gateway JWT, gateway auth will be unavailable');
}
diff --git a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
index bfed214ac8b..9d79b8e4858 100644
--- a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
+++ b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
@@ -38,9 +38,13 @@ import { ingestAttachment } from '../ingestAttachment';
import type { AgentShareGate } from '../shareGate';
import { reserveShareVisitorTopic, reserveShareVisitorTurn } from '../shareVisitorAbuseGuards';
import type { InternalExecAgentParams } from '../types';
+import { createStageTracer, openStageMark } from './sendTracing';
const log = debug('lobe-server:ai-agent-service');
+const traceTurnStage = createStageTracer('turn_setup');
+const openTurnStage = openStageMark('turn_setup');
+
export interface TurnSetupDeps {
db: LobeChatDatabase;
messageModel: MessageModel;
@@ -480,202 +484,215 @@ export const setupTurn = async (
});
}
- if (!topicId) {
- if (resume) {
- throw new Error('Resume mode requires the parent message to belong to a topic');
- }
-
- // Prepare metadata with cronJobId, taskId, botContext, bound device, and any
- // client-supplied initial metadata (e.g. repos selected before first message).
- const initialTopicMeta = appContext?.initialTopicMetadata;
- // Builder conversations are owned by a builtin builder agent and get no
- // `groupId` / `sessionId` (those columns mark the target's own chat), so
- // without this the row keeps no trace of what it was configuring. The
- // association exists only at run time: a topic written without it can
- // never be attributed afterwards, which is why it is stamped even though
- // nothing filters on it yet.
- const { editingGroupId } = appContext ?? {};
- const metadata =
- cronJobId ||
- operationTaskId ||
- botContext ||
- topicBoundDeviceId ||
- initialTopicMeta ||
- editingGroupId ||
- editingAgentId
- ? {
- bot: botContext,
- boundDeviceId: topicBoundDeviceId,
- cronJobId: cronJobId || undefined,
- ...(editingAgentId && { editingAgentId }),
- ...(editingGroupId && { editingGroupId }),
- taskId: operationTaskId,
- ...(initialTopicMeta?.repos && { repos: initialTopicMeta.repos }),
- ...(initialTopicMeta?.sandboxInstanceId && {
- sandboxInstanceId: initialTopicMeta.sandboxInstanceId,
- }),
- ...(initialTopicMeta?.sandboxMode && { sandboxMode: initialTopicMeta.sandboxMode }),
- ...(initialTopicMeta?.workingDirectory && {
- workingDirectory: initialTopicMeta.workingDirectory,
- }),
- ...(initialTopicMeta?.workingDirectoryConfig && {
- workingDirectoryConfig: initialTopicMeta.workingDirectoryConfig,
- }),
- }
- : undefined;
-
- const fallbackTitleSource = markdownToTxt(prompt);
- const snapshot = await resolveNewTopicSnapshot(deps, agentConfig);
- const metadataWithSnapshot: ChatTopicMetadata | undefined =
- metadata || snapshot.metadata ? { ...metadata, ...snapshot.metadata } : undefined;
- // Second argument: the id the client already rendered this topic under
- // (sidebar row, message bucket). Absent β†’ the model mints one as before.
- const newTopicParams = {
- agentId: resolvedAgentId,
- // Persist the group association when running inside a group conversation.
- // Without it the topic is created group-less and only shows under the
- // member agent's topic list β€” never in the group sidebar (which queries
- // `topics.groupId`), so the conversation silently "disappears" from the
- // group. execGroupAgent normally pre-creates the topic, but any path
- // that reaches execAgent without a topicId (e.g. the async/queue run)
- // must carry the groupId through too (group topic sidebar + ownership fix).
- groupId: appContext?.groupId,
- metadata: metadataWithSnapshot,
- // Snapshot the effective model as the topic's pinned model (config).
- model: snapshot.model,
- provider: snapshot.provider,
- // Share-visitor runs: the topic row belongs to the creator
- // (`deps.userId`), but stamping the visitor's id here is what
- // `TopicModel`'s creator-facing reads (`query`, `count`, `queryTopics`,
- // `queryRecent`, `rank`) filter out via `notShareVisitorTopic()`, and
- // what lets shareChat scope reads per visitor (`queryBySender` /
- // `countBySender`).
- senderId: shareGate?.visitorUserId,
- title:
- title !== undefined
- ? title
- : fallbackTitleSource.slice(0, 50) + (fallbackTitleSource.length > 50 ? '...' : ''),
- trigger,
- };
- // Share-visitor runs must reserve the `maxTopicsPerVisitor` slot and
- // insert the topic in ONE locked transaction β€” see
- // `reserveShareVisitorTopic`'s JSDoc for the race this closes. Non-share
- // runs (no per-visitor cap to enforce) keep the plain unlocked insert.
- const newTopic = shareGate
- ? await reserveShareVisitorTopic(
- {
- agentId: resolvedAgentId,
- db: deps.db,
- expectedShareId: shareGate.shareId,
- ownerId: deps.userId,
- visitorUserId: shareGate.visitorUserId,
- workspaceId: deps.workspaceId,
- },
- newTopicParams,
- clientIds?.topicId,
- )
- : await deps.topicModel.create(newTopicParams, clientIds?.topicId);
- topicId = newTopic.id;
- log(
- 'execAgent: created new topic %s with trigger %s, groupId %s, cronJobId %s',
- topicId,
- trigger || 'default',
- appContext?.groupId || 'none',
- cronJobId || 'none',
- );
- } else {
- log('execAgent: reusing existing topic %s', topicId);
-
- // Honor a topic-pinned model (snapshotted on creation, updated when the
- // user switched model while the topic was active) over the agent default.
- // Explicit per-run values (such as callSubAgent) override their own field.
- // The pinned model lives in the top-level `topics.model`/`provider` columns
- // (config source of truth), NOT in metadata.
- const existingTopic = await deps.topicModel.findById(topicId);
- topicEditingGroupId = existingTopic?.metadata?.editingGroupId ?? undefined;
-
- // Fail-closed guard: a non-share run must never operate on a share-visitor
- // topic. `findById` is ownership-scoped but deliberately does NOT exclude
- // visitor topics (see its JSDoc) β€” they carry the CREATOR's own userId for
- // billing attribution, so `deps.userId`'s ownership check alone lets a
- // creator-authenticated but non-share call (e.g. hitting `aiAgent.execAgent`
- // directly with a leaked/guessed visitor topicId) load a visitor
- // conversation as if it were their own. A share visitor's own run is
- // authorized separately via `shareGate` β€” already re-validated upstream by
- // `findVisitorTopicOrThrow` in `shareChat.ts` β€” and must keep working.
- if (!shareGate && existingTopic?.senderId) {
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Topic not found' });
- }
+ // Topic resolution assigns the turn's narrowed bindings (topic id, pinned
+ // model, device targets), so it is a marked block rather than a callback:
+ // every exit, including a throw, records the error and closes the span.
+ const topicStage = openTurnStage('topic');
+ try {
+ if (!topicId) {
+ if (resume) {
+ throw new Error('Resume mode requires the parent message to belong to a topic');
+ }
- /** A group topic pins its owning agent; member runs keep their own model and effort. */
- const canUseTopicPin = !existingTopic?.groupId || existingTopic.agentId === resolvedAgentId;
- // The model pin belongs to the topic's own agent. A `callAgent` child runs
- // in an isolation thread on the CALLER's topic; inheriting that pin would
- // run the callee on the caller's model (#19542). Legacy topics without an
- // owner keep the pin.
- const canUseTopicModelPin =
- canUseTopicPin && (!existingTopic?.agentId || existingTopic.agentId === resolvedAgentId);
- const pinnedModel = canUseTopicModelPin ? existingTopic?.model : undefined;
- if (pinnedModel) {
- model = modelOverride || pinnedModel;
- provider = providerOverride || existingTopic?.provider || provider;
- pinnedHeterogeneousTopicModel = { model, provider };
+ // Prepare metadata with cronJobId, taskId, botContext, bound device, and any
+ // client-supplied initial metadata (e.g. repos selected before first message).
+ const initialTopicMeta = appContext?.initialTopicMetadata;
+ // Builder conversations are owned by a builtin builder agent and get no
+ // `groupId` / `sessionId` (those columns mark the target's own chat), so
+ // without this the row keeps no trace of what it was configuring. The
+ // association exists only at run time: a topic written without it can
+ // never be attributed afterwards, which is why it is stamped even though
+ // nothing filters on it yet.
+ const { editingGroupId } = appContext ?? {};
+ const metadata =
+ cronJobId ||
+ operationTaskId ||
+ botContext ||
+ topicBoundDeviceId ||
+ initialTopicMeta ||
+ editingGroupId ||
+ editingAgentId
+ ? {
+ bot: botContext,
+ boundDeviceId: topicBoundDeviceId,
+ cronJobId: cronJobId || undefined,
+ ...(editingAgentId && { editingAgentId }),
+ ...(editingGroupId && { editingGroupId }),
+ taskId: operationTaskId,
+ ...(initialTopicMeta?.repos && { repos: initialTopicMeta.repos }),
+ ...(initialTopicMeta?.sandboxInstanceId && {
+ sandboxInstanceId: initialTopicMeta.sandboxInstanceId,
+ }),
+ ...(initialTopicMeta?.sandboxMode && { sandboxMode: initialTopicMeta.sandboxMode }),
+ ...(initialTopicMeta?.workingDirectory && {
+ workingDirectory: initialTopicMeta.workingDirectory,
+ }),
+ ...(initialTopicMeta?.workingDirectoryConfig && {
+ workingDirectoryConfig: initialTopicMeta.workingDirectoryConfig,
+ }),
+ }
+ : undefined;
+
+ const fallbackTitleSource = markdownToTxt(prompt);
+ const snapshot = await resolveNewTopicSnapshot(deps, agentConfig);
+ const metadataWithSnapshot: ChatTopicMetadata | undefined =
+ metadata || snapshot.metadata ? { ...metadata, ...snapshot.metadata } : undefined;
+ // Second argument: the id the client already rendered this topic under
+ // (sidebar row, message bucket). Absent β†’ the model mints one as before.
+ const newTopicParams = {
+ agentId: resolvedAgentId,
+ // Persist the group association when running inside a group conversation.
+ // Without it the topic is created group-less and only shows under the
+ // member agent's topic list β€” never in the group sidebar (which queries
+ // `topics.groupId`), so the conversation silently "disappears" from the
+ // group. execGroupAgent normally pre-creates the topic, but any path
+ // that reaches execAgent without a topicId (e.g. the async/queue run)
+ // must carry the groupId through too (group topic sidebar + ownership fix).
+ groupId: appContext?.groupId,
+ metadata: metadataWithSnapshot,
+ // Snapshot the effective model as the topic's pinned model (config).
+ model: snapshot.model,
+ provider: snapshot.provider,
+ // Share-visitor runs: the topic row belongs to the creator
+ // (`deps.userId`), but stamping the visitor's id here is what
+ // `TopicModel`'s creator-facing reads (`query`, `count`, `queryTopics`,
+ // `queryRecent`, `rank`) filter out via `notShareVisitorTopic()`, and
+ // what lets shareChat scope reads per visitor (`queryBySender` /
+ // `countBySender`).
+ senderId: shareGate?.visitorUserId,
+ title:
+ title !== undefined
+ ? title
+ : fallbackTitleSource.slice(0, 50) + (fallbackTitleSource.length > 50 ? '...' : ''),
+ trigger,
+ };
+ // Share-visitor runs must reserve the `maxTopicsPerVisitor` slot and
+ // insert the topic in ONE locked transaction β€” see
+ // `reserveShareVisitorTopic`'s JSDoc for the race this closes. Non-share
+ // runs (no per-visitor cap to enforce) keep the plain unlocked insert.
+ const newTopic = shareGate
+ ? await reserveShareVisitorTopic(
+ {
+ agentId: resolvedAgentId,
+ db: deps.db,
+ expectedShareId: shareGate.shareId,
+ ownerId: deps.userId,
+ visitorUserId: shareGate.visitorUserId,
+ workspaceId: deps.workspaceId,
+ },
+ newTopicParams,
+ clientIds?.topicId,
+ )
+ : await deps.topicModel.create(newTopicParams, clientIds?.topicId);
+ topicId = newTopic.id;
log(
- 'execAgent: using topic-pinned model=%s provider=%s for topic %s',
- model,
- provider,
+ 'execAgent: created new topic %s with trigger %s, groupId %s, cronJobId %s',
topicId,
+ trigger || 'default',
+ appContext?.groupId || 'none',
+ cronJobId || 'none',
);
- }
- // The heterogeneous effort pin lives in metadata and is independent of the
- // model pin (a runtime without a model selector can still pin an effort).
- const pinnedHeteroEffort = canUseTopicModelPin
- ? existingTopic?.metadata?.heteroEffort
- : undefined;
- if (pinnedHeteroEffort !== undefined) {
- pinnedHeterogeneousTopicModel = {
- ...pinnedHeterogeneousTopicModel,
- effort: pinnedHeteroEffort,
- };
- }
+ } else {
+ log('execAgent: reusing existing topic %s', topicId);
+
+ // Honor a topic-pinned model (snapshotted on creation, updated when the
+ // user switched model while the topic was active) over the agent default.
+ // Explicit per-run values (such as callSubAgent) override their own field.
+ // The pinned model lives in the top-level `topics.model`/`provider` columns
+ // (config source of truth), NOT in metadata.
+ const existingTopic = await deps.topicModel.findById(topicId);
+ topicEditingGroupId = existingTopic?.metadata?.editingGroupId ?? undefined;
+
+ // Fail-closed guard: a non-share run must never operate on a share-visitor
+ // topic. `findById` is ownership-scoped but deliberately does NOT exclude
+ // visitor topics (see its JSDoc) β€” they carry the CREATOR's own userId for
+ // billing attribution, so `deps.userId`'s ownership check alone lets a
+ // creator-authenticated but non-share call (e.g. hitting `aiAgent.execAgent`
+ // directly with a leaked/guessed visitor topicId) load a visitor
+ // conversation as if it were their own. A share visitor's own run is
+ // authorized separately via `shareGate` β€” already re-validated upstream by
+ // `findVisitorTopicOrThrow` in `shareChat.ts` β€” and must keep working.
+ if (!shareGate && existingTopic?.senderId) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Topic not found' });
+ }
- // A conversation stays on the machine it already ran on: its cwd and CLI
- // session live there, so the agent-level target (the default for NEW
- // topics) must not move a later turn elsewhere. An explicit request device
- // (the picker's in-process preset, a task/sub-agent override) and a fixed
- // workspace target still win. `auto` opted into picking a fresh online
- // device every run, so an earlier pick never pins it.
- const topicPinnedDeviceId = canUseTopicPin ? existingTopic?.metadata?.boundDeviceId : undefined;
- if (
- !requestedDeviceId &&
- topicPinnedDeviceId &&
- !isFixedExecutionTargetSelection &&
- agentConfig.agencyConfig?.executionTarget !== 'auto'
- ) {
- resolvedRequestedDeviceId = topicPinnedDeviceId;
- effectiveRequestedDeviceId = topicPinnedDeviceId;
- topicBoundDeviceId = topicPinnedDeviceId;
- log('execAgent: routing topic %s to its bound device %s', topicId, topicPinnedDeviceId);
- }
+ /** A group topic pins its owning agent; member runs keep their own model and effort. */
+ const canUseTopicPin = !existingTopic?.groupId || existingTopic.agentId === resolvedAgentId;
+ // The model pin belongs to the topic's own agent. A `callAgent` child runs
+ // in an isolation thread on the CALLER's topic; inheriting that pin would
+ // run the callee on the caller's model (#19542). Legacy topics without an
+ // owner keep the pin.
+ const canUseTopicModelPin =
+ canUseTopicPin && (!existingTopic?.agentId || existingTopic.agentId === resolvedAgentId);
+ const pinnedModel = canUseTopicModelPin ? existingTopic?.model : undefined;
+ if (pinnedModel) {
+ model = modelOverride || pinnedModel;
+ provider = providerOverride || existingTopic?.provider || provider;
+ pinnedHeterogeneousTopicModel = { model, provider };
+ log(
+ 'execAgent: using topic-pinned model=%s provider=%s for topic %s',
+ model,
+ provider,
+ topicId,
+ );
+ }
+ // The heterogeneous effort pin lives in metadata and is independent of the
+ // model pin (a runtime without a model selector can still pin an effort).
+ const pinnedHeteroEffort = canUseTopicModelPin
+ ? existingTopic?.metadata?.heteroEffort
+ : undefined;
+ if (pinnedHeteroEffort !== undefined) {
+ pinnedHeterogeneousTopicModel = {
+ ...pinnedHeterogeneousTopicModel,
+ effort: pinnedHeteroEffort,
+ };
+ }
- // Re-assert the share restriction after topic overrides are applied.
- // Heterogeneous agents are not available for shared visitor runs.
- if (shareGate && isHeterogeneousAgentModelId(model)) {
- throw new TRPCError({
- code: 'FORBIDDEN',
- message: ChatErrorType.ShareHeterogeneousAgentUnsupported,
- });
- }
+ // A conversation stays on the machine it already ran on: its cwd and CLI
+ // session live there, so the agent-level target (the default for NEW
+ // topics) must not move a later turn elsewhere. An explicit request device
+ // (the picker's in-process preset, a task/sub-agent override) and a fixed
+ // workspace target still win. `auto` opted into picking a fresh online
+ // device every run, so an earlier pick never pins it.
+ const topicPinnedDeviceId = canUseTopicPin
+ ? existingTopic?.metadata?.boundDeviceId
+ : undefined;
+ if (
+ !requestedDeviceId &&
+ topicPinnedDeviceId &&
+ !isFixedExecutionTargetSelection &&
+ agentConfig.agencyConfig?.executionTarget !== 'auto'
+ ) {
+ resolvedRequestedDeviceId = topicPinnedDeviceId;
+ effectiveRequestedDeviceId = topicPinnedDeviceId;
+ topicBoundDeviceId = topicPinnedDeviceId;
+ log('execAgent: routing topic %s to its bound device %s', topicId, topicPinnedDeviceId);
+ }
- // A builder conversation edits exactly one agent, stamped on the topic when
- // it was created. Continuations rebuilt from the durable operation (approval
- // or askUserQuestion resumes) arrive without `editingAgentId`; recover it
- // here so the run origin still carries the target instead of leaving the
- // builder tools with nothing to write to.
- if (appContext?.scope === 'agent_builder' && !editingAgentId) {
- editingAgentId = existingTopic?.metadata?.editingAgentId ?? undefined;
- log('execAgent: recovered editingAgentId=%s from topic %s', editingAgentId, topicId);
+ // Re-assert the share restriction after topic overrides are applied.
+ // Heterogeneous agents are not available for shared visitor runs.
+ if (shareGate && isHeterogeneousAgentModelId(model)) {
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: ChatErrorType.ShareHeterogeneousAgentUnsupported,
+ });
+ }
+
+ // A builder conversation edits exactly one agent, stamped on the topic when
+ // it was created. Continuations rebuilt from the durable operation (approval
+ // or askUserQuestion resumes) arrive without `editingAgentId`; recover it
+ // here so the run origin still carries the target instead of leaving the
+ // builder tools with nothing to write to.
+ if (appContext?.scope === 'agent_builder' && !editingAgentId) {
+ editingAgentId = existingTopic?.metadata?.editingAgentId ?? undefined;
+ log('execAgent: recovered editingAgentId=%s from topic %s', editingAgentId, topicId);
+ }
}
+ } catch (error) {
+ topicStage.fail(error);
+ throw error;
+ } finally {
+ topicStage.end();
}
await throwIfExecutionAborted('topic setup');
@@ -725,11 +742,18 @@ export const setupTurn = async (
// Attachment ingestion: raw bot/IM `files` β†’ S3, pre-uploaded
// `attachedFileIds` β†’ signed URLs + classification.
- const runAttachments = await resolveRunAttachments(deps, {
- attachedFileIds,
- fileAccessScope: shareGate ? agentShareFileAccessScope(shareGate) : ordinaryFileAccessScope,
- files,
- throwIfAborted: throwIfExecutionAborted,
+ // Raw bot/IM uploads are parsed here, on the send path β€” a PDF can hold
+ // this stage for seconds, which is why it gets its own span.
+ const runAttachments = await traceTurnStage('attachments', async (span) => {
+ const resolved = await resolveRunAttachments(deps, {
+ attachedFileIds,
+ fileAccessScope: shareGate ? agentShareFileAccessScope(shareGate) : ordinaryFileAccessScope,
+ files,
+ throwIfAborted: throwIfExecutionAborted,
+ });
+ span.setAttribute('lobehub.turn_setup.raw_file_count', files?.length ?? 0);
+ span.setAttribute('lobehub.turn_setup.attached_file_count', attachedFileIds?.length ?? 0);
+ return resolved;
});
await throwIfExecutionAborted('message creation');
@@ -737,153 +761,159 @@ export const setupTurn = async (
// Persist the user turn. `selfMessageIds` lets the normal-path history loader
// exclude this freshly-created turn β€” history must be the PRIOR turns only,
// otherwise the new prompt is double-counted in the LLM context.
- const selfMessageIds = new Set<string>();
- // Anchor the new user turn on the conversation tail. Never leave it
- // undefined for a topic that already has messages: `parentId: undefined`
- // persists a second ROOT, and the renderer walks the parentId forest
- // depth-first β€” an earlier root's still-growing subtree is emitted before a
- // later root, so the newest reply lands ABOVE older messages.
- //
- // `getLatestSpineMessageId` skips tool rows and toolless signal turns, so it
- // can come back empty on a topic built entirely from signal callbacks; fall
- // back to the latest non-tool row rather than orphaning the turn.
- const resolveUserMessageParentId = async () => {
- if (runFromHistory) return undefined;
- if (parentMessageId) return parentMessageId;
- // A thread created for THIS turn is empty, so there is no spine head to
- // anchor on. Its branch point is the source message β€” the same anchor the
- // non-gateway path keeps for a brand-new thread. Without it the first turn
- // persists as a second root and the renderer's parentId walk emits it out
- // of order.
- if (createdThreadId) return appContext?.newThread?.sourceMessageId;
-
- const threadId = appContext?.threadId ?? null;
- const spineId = await deps.messageModel.getLatestSpineMessageId({ threadId, topicId });
- if (spineId) return spineId;
-
- const fallbackId = await deps.messageModel.getLatestNonToolMessageId({ threadId, topicId });
- if (fallbackId) {
- log(
- 'execAgent: no spine head for topic %s, anchoring user turn on latest non-tool message %s',
- topicId,
- fallbackId,
- );
- }
- return fallbackId;
- };
- const userMessageParentId = await resolveUserMessageParentId();
- const userMessageParams = {
- agentId: conversationAgentId,
- content: prompt,
- files: runAttachments.fileIds,
- // Group reads filter on messages.groupId (MessageModel.query group
- // branch), so a group turn must stamp groupId or the message never
- // shows when the topic is reopened (group topic sidebar + ownership fix).
- groupId: appContext?.groupId ?? undefined,
- metadata: requestTriggerMetadata,
- parentId: userMessageParentId,
- role: 'user' as const,
- threadId: appContext?.threadId ?? undefined,
- topicId,
- };
- // Share-visitor runs must reserve the `maxTurnsPerTopic` slot and insert
- // the user message in ONE locked transaction β€” see
- // `reserveShareVisitorTurn`'s JSDoc for the race this closes (same class of
- // count-then-act bug as the topic cap above). Harmless no-op on a topic
- // this same call just created (count is 0). Non-share runs (no per-turn
- // cap) keep the plain unlocked insert.
- const userMessageRecord = runFromHistory
- ? undefined
- : shareGate
- ? await reserveShareVisitorTurn(
- {
- agentId: shareGate.agentId,
- db: deps.db,
- expectedShareId: shareGate.shareId,
- ownerId: deps.userId,
+ const { assistantMessageRecord, selfMessageIds, userMessageRecord } = await traceTurnStage(
+ 'messages',
+ async () => {
+ const selfMessageIds = new Set<string>();
+ // Anchor the new user turn on the conversation tail. Never leave it
+ // undefined for a topic that already has messages: `parentId: undefined`
+ // persists a second ROOT, and the renderer walks the parentId forest
+ // depth-first β€” an earlier root's still-growing subtree is emitted before a
+ // later root, so the newest reply lands ABOVE older messages.
+ //
+ // `getLatestSpineMessageId` skips tool rows and toolless signal turns, so it
+ // can come back empty on a topic built entirely from signal callbacks; fall
+ // back to the latest non-tool row rather than orphaning the turn.
+ const resolveUserMessageParentId = async () => {
+ if (runFromHistory) return undefined;
+ if (parentMessageId) return parentMessageId;
+ // A thread created for THIS turn is empty, so there is no spine head to
+ // anchor on. Its branch point is the source message β€” the same anchor the
+ // non-gateway path keeps for a brand-new thread. Without it the first turn
+ // persists as a second root and the renderer's parentId walk emits it out
+ // of order.
+ if (createdThreadId) return appContext?.newThread?.sourceMessageId;
+
+ const threadId = appContext?.threadId ?? null;
+ const spineId = await deps.messageModel.getLatestSpineMessageId({ threadId, topicId });
+ if (spineId) return spineId;
+
+ const fallbackId = await deps.messageModel.getLatestNonToolMessageId({ threadId, topicId });
+ if (fallbackId) {
+ log(
+ 'execAgent: no spine head for topic %s, anchoring user turn on latest non-tool message %s',
topicId,
- workspaceId: deps.workspaceId,
- },
- userMessageParams,
- // The id the client's optimistic user row already renders under.
- clientIds?.userMessageId,
- )
- : await deps.messageModel.create(
- userMessageParams,
- // The id the client's optimistic user row already renders under.
- clientIds?.userMessageId,
- );
- if (userMessageRecord) {
- selfMessageIds.add(userMessageRecord.id);
- log('execAgent: created user message %s', userMessageRecord.id);
- }
-
- // Snapshot the author's group orchestration role onto the assistant message
- // so the role survives the server round-trip (gateway step_start snapshot /
- // message.getMessages). Without this the client's optimistic isSupervisor flag
- // is lost on refetch and the supervisor renders as a generic assistant.
- // The persisted message `role` stays 'assistant' β€” only metadata carries the
- // orchestration role, keeping the data training-friendly.
- const orchestrationMetadata = appContext?.orchestrationRole
- ? {
- ...(appContext.orchestrationRole === 'supervisor' ? { isSupervisor: true } : {}),
- orchestrationRole: appContext.orchestrationRole,
+ fallbackId,
+ );
+ }
+ return fallbackId;
+ };
+ const userMessageParentId = await resolveUserMessageParentId();
+ const userMessageParams = {
+ agentId: conversationAgentId,
+ content: prompt,
+ files: runAttachments.fileIds,
+ // Group reads filter on messages.groupId (MessageModel.query group
+ // branch), so a group turn must stamp groupId or the message never
+ // shows when the topic is reopened (group topic sidebar + ownership fix).
+ groupId: appContext?.groupId ?? undefined,
+ metadata: requestTriggerMetadata,
+ parentId: userMessageParentId,
+ role: 'user' as const,
+ threadId: appContext?.threadId ?? undefined,
+ topicId,
+ };
+ // Share-visitor runs must reserve the `maxTurnsPerTopic` slot and insert
+ // the user message in ONE locked transaction β€” see
+ // `reserveShareVisitorTurn`'s JSDoc for the race this closes (same class of
+ // count-then-act bug as the topic cap above). Harmless no-op on a topic
+ // this same call just created (count is 0). Non-share runs (no per-turn
+ // cap) keep the plain unlocked insert.
+ const userMessageRecord = runFromHistory
+ ? undefined
+ : shareGate
+ ? await reserveShareVisitorTurn(
+ {
+ agentId: shareGate.agentId,
+ db: deps.db,
+ expectedShareId: shareGate.shareId,
+ ownerId: deps.userId,
+ topicId,
+ workspaceId: deps.workspaceId,
+ },
+ userMessageParams,
+ // The id the client's optimistic user row already renders under.
+ clientIds?.userMessageId,
+ )
+ : await deps.messageModel.create(
+ userMessageParams,
+ // The id the client's optimistic user row already renders under.
+ clientIds?.userMessageId,
+ );
+ if (userMessageRecord) {
+ selfMessageIds.add(userMessageRecord.id);
+ log('execAgent: created user message %s', userMessageRecord.id);
}
- : undefined;
- // Assistant placeholder (shows the spinner in the UI). A hetero run seeds
- // ONLY the provider β€” the CLI reports the real model later via `stream_start`
- // / `turn_metadata` (backfilled by HeterogeneousPersistenceHandler), and
- // seeding the agent's chat model would leak it into the model tag. A normal
- // run seeds model + provider as usual.
- const assistantParentId = userMessageRecord?.id ?? batchApprovalAnchorId ?? parentMessageId;
- const existingContinuationAssistant = continuationAssistantId
- ? await deps.messageModel.findById(continuationAssistantId)
- : undefined;
+ // Snapshot the author's group orchestration role onto the assistant message
+ // so the role survives the server round-trip (gateway step_start snapshot /
+ // message.getMessages). Without this the client's optimistic isSupervisor flag
+ // is lost on refetch and the supervisor renders as a generic assistant.
+ // The persisted message `role` stays 'assistant' β€” only metadata carries the
+ // orchestration role, keeping the data training-friendly.
+ const orchestrationMetadata = appContext?.orchestrationRole
+ ? {
+ ...(appContext.orchestrationRole === 'supervisor' ? { isSupervisor: true } : {}),
+ orchestrationRole: appContext.orchestrationRole,
+ }
+ : undefined;
- if (
- existingContinuationAssistant &&
- (existingContinuationAssistant.role !== 'assistant' ||
- existingContinuationAssistant.topicId !== topicId ||
- (existingContinuationAssistant.threadId ?? undefined) !==
- (appContext?.threadId ?? undefined) ||
- (existingContinuationAssistant.parentId ?? undefined) !== assistantParentId ||
- existingContinuationAssistant.agentId !== assistantAgentId)
- ) {
- throw new Error(
- `Intervention continuation assistant identity conflict: ${continuationAssistantId}`,
- );
- }
+ // Assistant placeholder (shows the spinner in the UI). A hetero run seeds
+ // ONLY the provider β€” the CLI reports the real model later via `stream_start`
+ // / `turn_metadata` (backfilled by HeterogeneousPersistenceHandler), and
+ // seeding the agent's chat model would leak it into the model tag. A normal
+ // run seeds model + provider as usual.
+ const assistantParentId = userMessageRecord?.id ?? batchApprovalAnchorId ?? parentMessageId;
+ const existingContinuationAssistant = continuationAssistantId
+ ? await deps.messageModel.findById(continuationAssistantId)
+ : undefined;
- const assistantMessageRecord =
- existingContinuationAssistant ??
- (await deps.messageModel.create(
- {
- agentId: assistantAgentId,
- content: LOADING_FLAT,
- // Stamp groupId so the assistant turn is visible in the group read path
- // (MessageModel.query filters group chats by messages.groupId).
- groupId: appContext?.groupId ?? undefined,
- metadata: orchestrationMetadata,
- model: isHeteroAgent ? undefined : model,
- // Chain onto the user turn we just persisted; `parentMessageId` is the
- // anchor only on a resume, where no user message is created. A batch
- // approval overrides it with the assistant that emitted the batch β€” the
- // previous LLM call β€” so the spine stays one node per call and never
- // depends on which of the batch's tool rows the client sent as anchor.
- parentId: assistantParentId,
- provider: isHeteroAgent ? heteroType : provider,
- role: 'assistant',
- threadId: appContext?.threadId ?? undefined,
- topicId,
- },
- // Generic intervention continuations use a stable placeholder so a
- // crash after this insert but before operation-state creation can
- // safely re-enter without creating a second assistant turn.
- continuationAssistantId ?? clientIds?.assistantMessageId,
- ));
- selfMessageIds.add(assistantMessageRecord.id);
- log('execAgent: created assistant message %s', assistantMessageRecord.id);
+ if (
+ existingContinuationAssistant &&
+ (existingContinuationAssistant.role !== 'assistant' ||
+ existingContinuationAssistant.topicId !== topicId ||
+ (existingContinuationAssistant.threadId ?? undefined) !==
+ (appContext?.threadId ?? undefined) ||
+ (existingContinuationAssistant.parentId ?? undefined) !== assistantParentId ||
+ existingContinuationAssistant.agentId !== assistantAgentId)
+ ) {
+ throw new Error(
+ `Intervention continuation assistant identity conflict: ${continuationAssistantId}`,
+ );
+ }
+
+ const assistantMessageRecord =
+ existingContinuationAssistant ??
+ (await deps.messageModel.create(
+ {
+ agentId: assistantAgentId,
+ content: LOADING_FLAT,
+ // Stamp groupId so the assistant turn is visible in the group read path
+ // (MessageModel.query filters group chats by messages.groupId).
+ groupId: appContext?.groupId ?? undefined,
+ metadata: orchestrationMetadata,
+ model: isHeteroAgent ? undefined : model,
+ // Chain onto the user turn we just persisted; `parentMessageId` is the
+ // anchor only on a resume, where no user message is created. A batch
+ // approval overrides it with the assistant that emitted the batch β€” the
+ // previous LLM call β€” so the spine stays one node per call and never
+ // depends on which of the batch's tool rows the client sent as anchor.
+ parentId: assistantParentId,
+ provider: isHeteroAgent ? heteroType : provider,
+ role: 'assistant',
+ threadId: appContext?.threadId ?? undefined,
+ topicId,
+ },
+ // Generic intervention continuations use a stable placeholder so a
+ // crash after this insert but before operation-state creation can
+ // safely re-enter without creating a second assistant turn.
+ continuationAssistantId ?? clientIds?.assistantMessageId,
+ ));
+ selfMessageIds.add(assistantMessageRecord.id);
+ log('execAgent: created assistant message %s', assistantMessageRecord.id);
+ return { assistantMessageRecord, selfMessageIds, userMessageRecord };
+ },
+ );
// Agent Signal is a governance side-channel (feedback / self-iteration). It
// only applies to the server-side LLM pipeline, so it is intentionally NOT