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.

πŸ› fix(hetero): derive trace agentId from operationId instead of the assistant message (#16354)

Arvin Xudccdbc5aec64
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
index a77c9ce1cc6..0c0d81ea972 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
@@ -2050,7 +2050,30 @@ describe('RuntimeExecutors', () => {
expect(engineSpy).toHaveBeenCalledWith(expect.objectContaining({ evalContext }));
});
- it('should inject current agent identity for bot-originated runs', async () => {
+ it('forwards the bot-originated agent identity snapshot to serverMessagesEngine', async () => {
+ // The bot/group member roster is resolved once at op creation
+ // (AiAgentService.execAgent β†’ buildBotConversationGroupContext) and
+ // snapshotted into op metadata as `agentGroup`. The per-step executor no
+ // longer rebuilds it β€” it just forwards the snapshot to the engine.
+ const agentGroup = {
+ agentMap: {
+ 'agent-support': {
+ name: 'Support Bot',
+ role: 'participant',
+ },
+ },
+ currentAgentId: 'agent-support',
+ currentAgentName: 'Support Bot',
+ currentAgentRole: 'participant',
+ members: [
+ {
+ id: 'agent-support',
+ name: 'Support Bot',
+ role: 'participant',
+ },
+ ],
+ systemPrompt: 'Answers customer support questions.',
+ };
const ctxWithConfig: RuntimeExecutorContext = {
...ctx,
agentConfig: {
@@ -2070,6 +2093,7 @@ describe('RuntimeExecutors', () => {
const executors = createRuntimeExecutors(ctxWithConfig);
const state = createMockState({
metadata: {
+ agentGroup,
agentId: 'agent-support',
botContext: ctxWithConfig.botContext,
topicId: 'topic-123',
@@ -2087,29 +2111,7 @@ describe('RuntimeExecutors', () => {
await executors.call_llm!(instruction, state);
- expect(engineSpy).toHaveBeenCalledWith(
- expect.objectContaining({
- agentGroup: {
- agentMap: {
- 'agent-support': {
- name: 'Support Bot',
- role: 'participant',
- },
- },
- currentAgentId: 'agent-support',
- currentAgentName: 'Support Bot',
- currentAgentRole: 'participant',
- members: [
- {
- id: 'agent-support',
- name: 'Support Bot',
- role: 'participant',
- },
- ],
- systemPrompt: 'Answers customer support questions.',
- },
- }),
- );
+ expect(engineSpy).toHaveBeenCalledWith(expect.objectContaining({ agentGroup }));
});
it('should build capabilities from LOBE_DEFAULT_MODEL_LIST', async () => {
diff --git a/apps/server/src/modules/AgentTracing/S3SnapshotStore.test.ts b/apps/server/src/modules/AgentTracing/S3SnapshotStore.test.ts
index 52ca2fed38e..e84c0e3ff72 100644
--- a/apps/server/src/modules/AgentTracing/S3SnapshotStore.test.ts
+++ b/apps/server/src/modules/AgentTracing/S3SnapshotStore.test.ts
@@ -67,15 +67,31 @@ describe('S3SnapshotStore.save', () => {
expect(roundtripped).toEqual(snap);
});
- it('falls back to "unknown" when agentId or topicId is missing', async () => {
+ it('recovers agentId/topicId from the operationId when the snapshot omits them', async () => {
const store = new S3SnapshotStore();
+ // agentId/topicId missing on the snapshot, but encoded in the operationId β€”
+ // the key must match what readers rebuild from the operationId, not "unknown".
await store.save(sampleSnapshot({ agentId: undefined, topicId: undefined }));
const [key] = uploadBuffer.mock.calls[0];
expect(key).toBe(
- 'agent-traces/unknown/unknown/op_1777000000000_agt_abc_tpc_xyz_QwErTy.json.zst',
+ 'agent-traces/agt_abc/tpc_xyz/op_1777000000000_agt_abc_tpc_xyz_QwErTy.json.zst',
);
});
+
+ it('falls back to "unknown" only when the operationId carries no agt_/tpc_ segments', async () => {
+ const store = new S3SnapshotStore();
+ await store.save(
+ sampleSnapshot({
+ agentId: undefined,
+ operationId: 'op_legacy_no_segments',
+ topicId: undefined,
+ }),
+ );
+
+ const [key] = uploadBuffer.mock.calls[0];
+ expect(key).toBe('agent-traces/unknown/unknown/op_legacy_no_segments.json.zst');
+ });
});
describe('S3SnapshotStore.savePartial', () => {
diff --git a/apps/server/src/modules/AgentTracing/S3SnapshotStore.ts b/apps/server/src/modules/AgentTracing/S3SnapshotStore.ts
index 60bc4f63e24..38b1b8d239a 100644
--- a/apps/server/src/modules/AgentTracing/S3SnapshotStore.ts
+++ b/apps/server/src/modules/AgentTracing/S3SnapshotStore.ts
@@ -1,7 +1,12 @@
import { promisify } from 'node:util';
import { zstdCompress, zstdDecompress } from 'node:zlib';
-import type { ExecutionSnapshot, ISnapshotStore, SnapshotSummary } from '@lobechat/agent-tracing';
+import {
+ type ExecutionSnapshot,
+ type ISnapshotStore,
+ parseOperationId,
+ type SnapshotSummary,
+} from '@lobechat/agent-tracing';
import debug from 'debug';
import { FileS3 } from '@/server/modules/S3';
@@ -72,8 +77,12 @@ export class S3SnapshotStore implements ISnapshotStore {
}
async save(snapshot: ExecutionSnapshot): Promise<void> {
- const agentId = snapshot.agentId ?? 'unknown';
- const topicId = snapshot.topicId ?? 'unknown';
+ // Recover agentId/topicId from the operationId when the snapshot lacks them,
+ // so the key matches what readers reconstruct from the operationId. Only an
+ // operationId that doesn't carry the segments falls through to "unknown".
+ const parsedOp = parseOperationId(snapshot.operationId);
+ const agentId = snapshot.agentId ?? parsedOp?.agentId ?? 'unknown';
+ const topicId = snapshot.topicId ?? parsedOp?.topicId ?? 'unknown';
const key = buildFinalSnapshotKey(agentId, topicId, snapshot.operationId);
log('Saving snapshot to S3: %s', key);
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.threadId.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.threadId.test.ts
index eb557a9dec2..3ebd89334c4 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.threadId.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.threadId.test.ts
@@ -81,6 +81,16 @@ vi.mock('@/database/models/thread', () => ({
})),
}));
+// Mock ChatGroupModel β€” execAgent resolves the operation's group context when
+// appContext.groupId is set (SubAgent task scenario). An empty roster makes
+// buildGroupAgentContext return undefined, so the run proceeds without a group.
+vi.mock('@/database/models/chatGroup', () => ({
+ ChatGroupModel: vi.fn().mockImplementation(() => ({
+ findById: vi.fn().mockResolvedValue(undefined),
+ getGroupAgentsWithMeta: vi.fn().mockResolvedValue([]),
+ })),
+}));
+
// Mock AgentRuntimeService
vi.mock('@/server/services/agentRuntime', () => ({
AgentRuntimeService: vi.fn().mockImplementation(() => ({
diff --git a/apps/server/src/services/heterogeneousAgent/HeteroTraceRecorder.ts b/apps/server/src/services/heterogeneousAgent/HeteroTraceRecorder.ts
index 08402d1e4a0..4af924c8ce5 100644
--- a/apps/server/src/services/heterogeneousAgent/HeteroTraceRecorder.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeteroTraceRecorder.ts
@@ -1,5 +1,10 @@
import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
-import type { ExecutionSnapshot, ISnapshotStore, StepSnapshot } from '@lobechat/agent-tracing';
+import {
+ type ExecutionSnapshot,
+ type ISnapshotStore,
+ parseOperationId,
+ type StepSnapshot,
+} from '@lobechat/agent-tracing';
import debug from 'debug';
import { buildFinalSnapshotKey } from '@/server/modules/AgentTracing';
@@ -112,8 +117,13 @@ export class HeteroTraceRecorder {
session?.totalOutputTokens ?? steps.reduce((sum, s) => sum + (s.outputTokens || 0), 0);
const totalCost = session?.totalCost ?? steps.reduce((sum, s) => sum + (s.totalCost || 0), 0);
- const agentId = params.agentId ?? undefined;
- const topicId = params.topicId ?? undefined;
+ // Fall back to the agentId/topicId encoded in the operationId when the
+ // caller didn't supply them, so the snapshot body and its S3 key never
+ // degrade to the literal "unknown" (which also breaks the reader, since
+ // it rebuilds the key from the operationId's agt_/tpc_ segments).
+ const parsedOp = parseOperationId(operationId);
+ const agentId = params.agentId ?? parsedOp?.agentId ?? undefined;
+ const topicId = params.topicId ?? parsedOp?.topicId ?? undefined;
const snapshot: ExecutionSnapshot = {
agentId,
diff --git a/apps/server/src/services/heterogeneousAgent/index.ts b/apps/server/src/services/heterogeneousAgent/index.ts
index 229e7981851..2ba06a5a861 100644
--- a/apps/server/src/services/heterogeneousAgent/index.ts
+++ b/apps/server/src/services/heterogeneousAgent/index.ts
@@ -1,5 +1,5 @@
import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
-import type { ISnapshotStore } from '@lobechat/agent-tracing';
+import { type ISnapshotStore, parseOperationId } from '@lobechat/agent-tracing';
import type { LobeChatDatabase } from '@lobechat/database';
import debug from 'debug';
@@ -237,15 +237,22 @@ export class HeterogeneousAgentService {
log('heteroFinish: failed to clear runningOperation (non-fatal): %O', err);
}
- // Read the final assistant content + owning agent so the bot-callback
- // handler has lastAssistantContent to render and the event carries agentId.
+ // The owning agentId is authoritatively encoded in the operationId
+ // (op_<ts>_agt_<id>_tpc_<id>_<suffix>, built at dispatch from the resolved
+ // agent), so derive it from there. Reading it back off the final assistant
+ // message is unreliable: the message pointer (heteroCurrentMsgId /
+ // runningOperation.assistantMessageId) is absent on single-step desktop
+ // runs, which dropped agentId and landed the trace snapshot under
+ // agent-traces/unknown/... and left terminal hooks without an agentId.
+ const agentId = parseOperationId(operationId)?.agentId;
+
+ // Still read the assistant message for its content so the bot-callback
+ // handler has lastAssistantContent to render.
let lastAssistantContent: string | undefined;
- let agentId: string | undefined;
if (assistantMessageId) {
try {
const msg = await this.messageModel.findById(assistantMessageId);
lastAssistantContent = msg?.content as string | undefined;
- agentId = msg?.agentId ?? undefined;
} catch (err) {
log('heteroFinish: failed to read final assistant message (non-fatal): %O', err);
}
diff --git a/packages/agent-tracing/src/index.ts b/packages/agent-tracing/src/index.ts
index ce6d4577f3f..58e42a75a2a 100644
--- a/packages/agent-tracing/src/index.ts
+++ b/packages/agent-tracing/src/index.ts
@@ -1,5 +1,6 @@
export { appendStepToPartial, finalizeSnapshot } from './recorder';
export { FileSnapshotStore } from './store/file-store';
+export { isOperationId, parseOperationId } from './store/remote-store';
export type { ISnapshotStore } from './store/types';
export type { ExecutionSnapshot, SnapshotSummary, StepSnapshot } from './types';
export {