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(chat): render direct @Agent execution and replies in the parent topic (#17510)

Arvin Xu9bb79eb3da23
diff --git a/.agents/acceptance/common-mistakes.md b/.agents/acceptance/common-mistakes.md
index aef0f435469..3f4fdae68df 100644
--- a/.agents/acceptance/common-mistakes.md
+++ b/.agents/acceptance/common-mistakes.md
@@ -376,6 +376,70 @@ the served bundle carries it — fetch the relevant `/node_modules/.vite/deps/*`
from the dev server and grep for a marker of the fix — or restart the dev server
process outright and re-verify.
+---
+
+## Cross-agent dispatch envelopes are not visible user turns
+
+**Wrong approach**: treat every persisted `role: user` row as a user-authored
+message when building the visible conversation list.
+
+**Why it's wrong**: `callAgent` persists a synthetic user envelope beneath the
+caller assistant so the target Agent has an isolated execution context. When
+that envelope is rendered, the original prompt appears twice even though the
+target Agent produced only one reply.
+
+**What it breaks**: users see a duplicate prompt bubble and cannot tell whether
+the delegation ran once or twice; acceptance screenshots become misleading.
+
+**Correct approach**: stamp synthetic envelopes with explicit dispatch metadata
+when they are persisted, keep them in the context tree, and let the presentation
+layer hide only rows declared `visibility: internal`. Continue traversal through
+the envelope so the target assistant reply remains independently visible.
+Never infer authorship from agent-id differences or a parent tool call: a real
+cross-Agent user follow-up can have the same tree shape.
+
+## A terminal Claude Code reply is not evidence of live streaming
+
+**Wrong approach**: ask a device-executed Claude Code agent for a one-token fixed
+marker, record until the process exits, and treat the eventual assistant text or
+a refreshed screenshot as proof that the reply streamed into the open Topic.
+
+**Why it's wrong**: `lh hetero exec` can run Claude Code without
+`--include-partial-messages`. In that mode the adapter receives only the final
+assistant snapshot, so the UI may show an empty target-Agent shell for the whole
+run and acquire the text only during terminal reconciliation. A short fixed
+marker also has no observable intermediate state even when partial framing works.
+
+**What it breaks**: the acceptance proves persistence and refresh recovery but
+does not prove the user sees the answer arrive live; a GIF of an empty shell is
+mistaken for streaming evidence.
+
+**Correct approach**: enable Claude Code partial messages on the device/sandbox
+CLI spawn path. Verify with a multi-part response and timestamped DOM/store
+samples before any reload, then attach a GIF whose frames visibly progress and
+whose final frame contains the complete answer. Check persistence separately by
+refreshing only after the live-stream assertion has passed.
+
+## A text-only direct mention does not prove tool-call ownership
+
+**Wrong approach**: verify a leading single-Agent mention only with a plain-text
+response, then conclude that the direct-routing message tree is correct for all
+target-Agent runs.
+
+**Why it's wrong**: tool-capable runs add assistant tool-call chunks and
+tool-result messages. Those nodes can accidentally inherit the owner Agent,
+create a synthetic target-user envelope, or resume the owner after the tool
+result even when the initial text response looked correct.
+
+**What it breaks**: the simple happy path passes while real coding Agents either
+lose their tool output, render it under the wrong Agent, or invoke Lobe AI for
+the final answer.
+
+**Correct approach**: exercise a deterministic real tool call through the same
+gateway/device route, then assert the complete persisted tree: original owner
+user, target assistant/tool call, tool result, and target final response. Also
+assert there is no owner assistant, `callAgent`, or synthetic target-user row.
+
## Historical source
Detailed incident narratives and retired pixel- or component-specific directions
diff --git a/apps/cli/src/commands/hetero.test.ts b/apps/cli/src/commands/hetero.test.ts
index d45165bea1b..c3c464b9e08 100644
--- a/apps/cli/src/commands/hetero.test.ts
+++ b/apps/cli/src/commands/hetero.test.ts
@@ -255,6 +255,15 @@ describe('hetero exec command', () => {
const call = mockSpawnAgent.mock.calls[0][0];
expect(call.operationId).toBe('op-server-allocated');
+ expect(call.includePartialMessages).toBe(true);
+ });
+
+ it('does not request Claude partial-message framing for other heterogeneous agents', async () => {
+ mockSpawnAgent.mockReturnValue(createFakeHandle());
+
+ await runCmd(['hetero', 'exec', '--type', 'codex', '--prompt', 'hi']);
+
+ expect(mockSpawnAgent.mock.calls[0][0].includePartialMessages).toBe(false);
});
it('passes Claude Code --model and --effort through as spawnAgent extraArgs', async () => {
diff --git a/apps/cli/src/commands/hetero.ts b/apps/cli/src/commands/hetero.ts
index 0810f39294d..ebf6469f3af 100644
--- a/apps/cli/src/commands/hetero.ts
+++ b/apps/cli/src/commands/hetero.ts
@@ -776,6 +776,11 @@ const exec = async (options: ExecOptions): Promise<void> => {
cwd: options.cwd || process.cwd(),
env: commandEnv,
extraArgs,
+ // Device and sandbox executions are observed through the same gateway
+ // stream as native server agents. Ask Claude Code for content-block
+ // deltas so the current conversation receives text while the process is
+ // running instead of seeing only the terminal assistant snapshot.
+ includePartialMessages: options.type === 'claude-code',
operationId,
prompt: resolved.prompt,
resumeSessionId: options.resume,
@@ -808,6 +813,7 @@ const exec = async (options: ExecOptions): Promise<void> => {
cwd: options.cwd || process.cwd(),
env: commandEnv,
extraArgs,
+ includePartialMessages: options.type === 'claude-code',
operationId,
prompt: resolved.prompt,
uploadImage,
diff --git a/apps/server/src/routers/lambda/__tests__/integration/aiAgent.createClientTaskThread.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/aiAgent.createClientTaskThread.integration.test.ts
index 156b4d2bcd6..72d77d83a14 100644
--- a/apps/server/src/routers/lambda/__tests__/integration/aiAgent.createClientTaskThread.integration.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/integration/aiAgent.createClientTaskThread.integration.test.ts
@@ -1,4 +1,5 @@
// @vitest-environment node
+import { LOADING_FLAT } from '@lobechat/const';
import { type LobeChatDatabase } from '@lobechat/database';
import {
agents,
@@ -188,6 +189,35 @@ describe('createClientTaskThread Integration', () => {
expect(thread.title).toBe('Data Analysis Task');
});
+
+ it('should seed a thread-scoped assistant placeholder for streaming transports', async () => {
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const result = await caller.createClientTaskThread({
+ agentId: testAgentId,
+ assistantMessage: { provider: 'claude-code' },
+ instruction: 'Inspect the repository',
+ parentMessageId,
+ topicId: testTopicId,
+ });
+
+ expect(result.assistantMessageId).toBeDefined();
+
+ const [assistantMessage] = await serverDB
+ .select()
+ .from(messages)
+ .where(eq(messages.id, result.assistantMessageId!));
+
+ expect(assistantMessage).toMatchObject({
+ agentId: testAgentId,
+ content: LOADING_FLAT,
+ parentId: result.userMessageId,
+ provider: 'claude-code',
+ role: 'assistant',
+ threadId: result.threadId,
+ topicId: testTopicId,
+ });
+ });
});
describe('single agent mode (without groupId)', () => {
diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.ts
index e7fad65c0e5..40df01f430e 100644
--- a/apps/server/src/routers/lambda/aiAgent.ts
+++ b/apps/server/src/routers/lambda/aiAgent.ts
@@ -1,4 +1,5 @@
import { type AgentStreamEvent } from '@lobechat/agent-gateway-client';
+import { LOADING_FLAT } from '@lobechat/const';
import { isFullAccessApiKey } from '@lobechat/const/apiKeyScope';
import { parse } from '@lobechat/conversation-flow';
import type { TaskCurrentActivity, TaskStatusResult } from '@lobechat/types';
@@ -201,6 +202,7 @@ const ExecAgentSchema = z
/** Application context for message storage */
appContext: z
.object({
+ conversationAgentId: z.string().optional(),
defaultTaskAssigneeAgentId: z.string().optional(),
documentId: z.string().nullish(),
/** The agent being edited when scope is 'agent_builder' (not the builder builtin itself). */
@@ -445,6 +447,8 @@ const ExecSubAgentTaskSchema = z.object({
const CreateClientTaskThreadSchema = z.object({
/** The Agent ID to execute the task */
agentId: z.string(),
+ /** Optional assistant placeholder for transports that stream into an existing row. */
+ assistantMessage: z.object({ provider: z.string() }).optional(),
/** The Group ID (optional, only for Group mode) */
groupId: z.string().optional(),
/** Initial user message content (task instruction) */
@@ -797,7 +801,8 @@ export const aiAgentRouter = router({
createClientTaskThread: aiAgentWriteProcedure
.input(CreateClientTaskThreadSchema)
.mutation(async ({ input, ctx }) => {
- const { agentId, groupId, instruction, parentMessageId, title, topicId } = input;
+ const { agentId, assistantMessage, groupId, instruction, parentMessageId, title, topicId } =
+ input;
log('createClientTaskThread: agentId=%s, groupId=%s', agentId, groupId);
@@ -852,6 +857,19 @@ export const aiAgentRouter = router({
log('createClientTaskThread: created user message %s', userMessage.id);
+ const assistantMessageRecord = assistantMessage
+ ? await ctx.messageModel.create({
+ agentId,
+ content: LOADING_FLAT,
+ groupId,
+ parentId: userMessage.id,
+ provider: assistantMessage.provider,
+ role: 'assistant',
+ threadId: thread.id,
+ topicId,
+ })
+ : undefined;
+
// 3. Query thread messages and main chat messages in parallel
const messageQueryOptions = {
postProcessUrl: createUiMessageFileUrlResolver(),
@@ -872,6 +890,7 @@ export const aiAgentRouter = router({
// 4. Return Thread, userMessageId, threadMessages and messages
return {
+ assistantMessageId: assistantMessageRecord?.id,
messages,
startedAt,
success: true,
diff --git a/apps/server/src/routers/lambda/aiChat.ts b/apps/server/src/routers/lambda/aiChat.ts
index eadd4f04b12..c6d52031691 100644
--- a/apps/server/src/routers/lambda/aiChat.ts
+++ b/apps/server/src/routers/lambda/aiChat.ts
@@ -416,7 +416,7 @@ export const aiChatRouter = router({
topicId,
} satisfies CreateMessageParams;
const assistantMessage = {
- agentId: input.agentId,
+ agentId: input.newAssistantMessage.agentId ?? input.agentId,
content: LOADING_FLAT,
groupId: input.groupId,
metadata: input.newAssistantMessage.metadata,
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.spineAnchor.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.spineAnchor.test.ts
index c7a5420382d..93516f3af86 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.spineAnchor.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.spineAnchor.test.ts
@@ -234,6 +234,29 @@ describe('AiAgentService.execAgent - user turn spine anchoring', () => {
});
});
+ it('keeps the user on the conversation owner while attributing a direct reply to the executing agent', async () => {
+ await service.execAgent({
+ agentId: 'agent-1',
+ appContext: {
+ conversationAgentId: 'conversation-owner',
+ scope: 'sub_agent',
+ topicId: 'topic-1',
+ },
+ prompt: '@Agent 1 hello',
+ });
+
+ expect(userMessageCall()![0]).toMatchObject({
+ agentId: 'conversation-owner',
+ metadata: { agentDispatch: { kind: 'callAgent', visibility: 'internal' } },
+ role: 'user',
+ });
+ expect(assistantMessageCall()![0]).toMatchObject({
+ agentId: 'agent-1',
+ parentId: 'user-msg-1',
+ role: 'assistant',
+ });
+ });
+
it('scopes the anchor lookup to the thread when one is active', async () => {
mockGetLatestSpineMessageId.mockResolvedValue('thread-spine-1');
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index a5cb7da09d9..c3eed1a59f9 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -1427,6 +1427,8 @@ export class AiAgentService {
// fall back to the executing agent. Tools / systemRole / skills / agent
// documents stay keyed on `resolvedAgentId`.
const persistAgentId = appContext?.agentSignal?.agentId ?? resolvedAgentId;
+ const conversationAgentId = appContext?.conversationAgentId ?? persistAgentId;
+ const assistantAgentId = appContext?.conversationAgentId ? resolvedAgentId : persistAgentId;
// Resolve the final model once, keeping per-call task / sub-agent overrides
// above the caller's personal workspace choice and the shared Agent default.
@@ -1972,10 +1974,14 @@ export class AiAgentService {
// consume the same records. Keeping it in one place is what guarantees the
// hetero path can't drift from the standard path again (the bot-image bug
// came from the hetero branch re-implementing — and skipping — this step).
- const requestTriggerMetadata =
- trigger && Object.values(RequestTrigger).includes(trigger as RequestTrigger)
+ const requestTriggerMetadata = {
+ ...(trigger && Object.values(RequestTrigger).includes(trigger as RequestTrigger)
? { trigger: trigger as RequestTrigger }
- : undefined;
+ : undefined),
+ ...(appContext?.conversationAgentId && appContext.scope === 'sub_agent'
+ ? { agentDispatch: { kind: 'callAgent' as const, visibility: 'internal' as const } }
+ : undefined),
+ };
// Attachment ingestion: raw bot/IM `files` → S3, pre-uploaded
// `attachedFileIds` → signed URLs + classification.
@@ -2023,7 +2029,7 @@ export class AiAgentService {
? undefined
: await this.messageModel.create(
{
- agentId: persistAgentId,
+ agentId: conversationAgentId,
content: prompt,
files: runAttachments.fileIds,
// Group reads filter on messages.groupId (MessageModel.query group
@@ -2064,7 +2070,7 @@ export class AiAgentService {
// run seeds model + provider as usual.
const assistantMessageRecord = await this.messageModel.create(
{
- agentId: persistAgentId,
+ 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).
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
index 92acf7644d2..3acc63d0fbf 100644
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
@@ -132,6 +132,8 @@ interface OperationState {
* after the event's XADD succeeds.
*/
publishedKeys: Set<string>;
+ /** Isolation thread that owns this heterogeneous run, when applicable. */
+ threadId: string | undefined;
/**
* Run-global DB index for every tool message in the topic, keyed by
* `tool_call_id`. Main and subagent reducers keep only their per-turn maps;
@@ -426,14 +428,15 @@ export class HeterogeneousPersistenceHandler {
throw new Error(`runningOperation on topic ${topicId} is missing assistantMessageId`);
}
+ const baseAssistantMessage = await this.deps.messageModel.findById(baseAssistantMessageId);
+
if (seedAssistantMessageId) {
- const seededMsg = await this.deps.messageModel.findById(seedAssistantMessageId);
- if (!seededMsg) {
+ if (!baseAssistantMessage) {
throw new Error(
`Seeded assistantMessageId ${seedAssistantMessageId} was not found for topic ${topicId}`,
);
}
- if (seededMsg.topicId !== topicId) {
+ if (baseAssistantMessage.topicId !== topicId) {
throw new Error(
`Seeded assistantMessageId ${seedAssistantMessageId} does not belong to topic ${topicId}`,
);
@@ -453,7 +456,13 @@ export class HeterogeneousPersistenceHandler {
: baseAssistantMessageId;
state = {
- agentId: topic?.agentId ?? null,
+ // A direct @Agent run keeps the topic under the conversation owner while
+ // the seeded assistant belongs to the executing target Agent. Every
+ // follow-up step and tool row must inherit the assistant author, not the
+ // topic owner, or the post-tool answer appears to switch back to Lobe AI.
+ // Legacy/finish-only callers may not have a readable assistant row; keep
+ // the historical topic-owner fallback for those paths.
+ agentId: baseAssistantMessage?.agentId ?? topic?.agentId ?? null,
// Left undefined until the run's own stream_start reports it (or a cold
// replica recovers it from a stamped message). NOT seeded from
// topic.metadata.heteroSessionId: that holds the id we ASKED CC to resume,
@@ -466,6 +475,7 @@ export class HeterogeneousPersistenceHandler {
processedKeys: new Set(),
publishedKeys: new Set(),
toolMsgIdByCallId: new Map(),
+ threadId: running.threadId ?? undefined,
topicId,
};
await this.refreshToolMessageIndex(state);
@@ -628,14 +638,17 @@ export class HeterogeneousPersistenceHandler {
// Recover the chain spine from the DB. The next normal
// turn parents off the run's latest main-thread message that is neither a
// tool nor a TOOLLESS signal callback (a tools-bearing signal turn is
- // main-chain — see `getLastMainThreadSpineMessageId`); reading it straight
+ // main-chain — see `getLatestSpineMessageId`); reading it straight
// from the DB (independent of
// `currentAssistantId`, which can regress to the seed placeholder on a cold
// / non-sticky replica — see the multi-replica caveat on the class) keeps
// consecutive cold-replica steps chained linearly instead of forking onto a
// stale node. Signal turns still anchor off `lastToolMsgIdEver`, which is
// maintained in-memory across the run's tool batches.
- const spineId = await this.deps.messageModel.getLastMainThreadSpineMessageId?.(state.topicId);
+ const spineId = await this.deps.messageModel.getLatestSpineMessageId({
+ threadId: state.threadId ?? null,
+ topicId: state.topicId,
+ });
if (spineId) state.main.lastSpineMessageId = spineId;
}
@@ -907,6 +920,7 @@ export class HeterogeneousPersistenceHandler {
parentId: intent.parentId,
provider: intent.provider,
role: 'assistant',
+ threadId: state.threadId,
topicId: intent.topicId ?? state.topicId,
} as any,
intent.messageId,
@@ -965,7 +979,7 @@ export class HeterogeneousPersistenceHandler {
type: tool.payload.type,
},
role: 'tool',
- threadId: null,
+ threadId: state.threadId,
tool_call_id: tool.payload.id,
topicId: state.topicId,
} as any,
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.coldReplicaChainAnchor.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.coldReplicaChainAnchor.test.ts
index 8b1eae3a9e3..3bd940d7e04 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.coldReplicaChainAnchor.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.coldReplicaChainAnchor.test.ts
@@ -19,7 +19,7 @@ import {
* would open off the seed → orphan sibling forks.
*
* The phase 2 rewrite anchors the chain to the run's latest NON-tool / NON-signal
- * main-thread message (`getLastMainThreadSpineMessageId`), read straight from the
+ * scoped message (`getLatestSpineMessageId`), read straight from the
* DB and ordered by createdAt — independent of `currentAssistantId`. So step 2
* chains off step 1's assistant even though the in-memory pointer regressed.
*
@@ -103,19 +103,21 @@ const createHarness = () => {
return [...messages.values()].filter((m) => m.threadId === params.threadId);
return [...messages.values()].filter((m) => !m.threadId && m.topicId === params?.topicId);
}),
- getLastMainThreadSpineMessageId: vi.fn(async (topicId: string) => {
- // Most recent main-thread, non-tool, non-signal message — the spine anchor.
- const match = [...messages.values()]
- .filter(
- (m) =>
- m.topicId === topicId &&
- m.role !== 'tool' &&
- !m.threadId &&
- !(m as any).metadata?.signal,
- )
- .sort((a, b) => b.seq - a.seq)[0];
- return match?.id;
- }),
+ getLatestSpineMessageId: vi.fn(
+ async ({ threadId, topicId }: { threadId?: string | null; topicId: string }) => {
+ // Most recent main-thread, non-tool, non-signal message — the spine anchor.
+ const match = [...messages.values()]
+ .filter(
+ (m) =>
+ m.topicId === topicId &&
+ m.role !== 'tool' &&
+ m.threadId === (threadId ?? null) &&
+ !(m as any).metadata?.signal,
+ )
+ .sort((a, b) => b.seq - a.seq)[0];
+ return match?.id;
+ },
+ ),
listMessagePluginsByTopic: vi.fn(async () =>
[...messages.values()]
.filter((m) => m.role === 'tool' && m.tool_call_id)
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.eventBranches.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.eventBranches.test.ts
index 79ab6eeb4c2..2b1d0aac582 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.eventBranches.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.eventBranches.test.ts
@@ -147,12 +147,18 @@ const createHarness = (
},
),
findById: vi.fn(async (id: string) => messages.get(id) ?? null),
- getLastMainThreadSpineMessageId: vi.fn(async (_topicId: string) => {
- const match = [...messages.values()].findLast(
- (m) => m.role !== 'tool' && !m.threadId && !(m as any).metadata?.signal,
- );
- return match?.id;
- }),
+ getLatestSpineMessageId: vi.fn(
+ async ({ threadId, topicId }: { threadId?: string | null; topicId: string }) => {
+ const match = [...messages.values()].findLast(
+ (m) =>
+ m.topicId === topicId &&
+ m.role !== 'tool' &&
+ m.threadId === (threadId ?? null) &&
+ !(m as any).metadata?.signal,
+ );
+ return match?.id;
+ },
+ ),
listMessagePluginsByTopic: vi.fn(async (_topicId: string) => []),
};
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.fixture.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.fixture.test.ts
index 0e1d1dc02d8..01232c1f821 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.fixture.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.fixture.test.ts
@@ -186,6 +186,18 @@ const createHarness = () => {
return { success: true };
}),
findById: vi.fn(async (id: string) => messages.get(id) ?? null),
+ getLatestSpineMessageId: vi.fn(
+ async ({ threadId, topicId }: { threadId?: string | null; topicId: string }) => {
+ const match = [...messages.values()].findLast(
+ (message) =>
+ message.topicId === topicId &&
+ message.role !== 'tool' &&
+ message.threadId === (threadId ?? null) &&
+ !(message as any).metadata?.signal,
+ );
+ return match?.id;
+ },
+ ),
listMessagePluginsByTopic: vi.fn(async (_topicId: string) => []),
};
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.mainTurnRehydration.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.mainTurnRehydration.test.ts
index b37aee637c1..12cf4f96e59 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.mainTurnRehydration.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.mainTurnRehydration.test.ts
@@ -129,12 +129,18 @@ const createHarness = () => {
return [...messages.values()].filter((m) => m.threadId === params.threadId);
return [...messages.values()].filter((m) => !m.threadId && m.topicId === params?.topicId);
}),
- getLastMainThreadSpineMessageId: vi.fn(async (_topicId: string) => {
- const match = [...messages.values()].findLast(
- (m) => m.role !== 'tool' && !m.threadId && !(m as any).metadata?.signal,
- );
- return match?.id;
- }),
+ getLatestSpineMessageId: vi.fn(
+ async ({ threadId, topicId }: { threadId?: string | null; topicId: string }) => {
+ const match = [...messages.values()].findLast(
+ (m) =>
+ m.topicId === topicId &&
+ m.role !== 'tool' &&
+ m.threadId === (threadId ?? null) &&
+ !(m as any).metadata?.signal,
+ );
+ return match?.id;
+ },
+ ),
listMessagePluginsByTopic: vi.fn(async () =>
[...messages.values()]
.filter((m) => m.role === 'tool' && m.tool_call_id)
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.subagentRehydration.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.subagentRehydration.test.ts
index fd046d30642..d3930f80d42 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.subagentRehydration.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.subagentRehydration.test.ts
@@ -123,12 +123,18 @@ const createHarness = (params: {
}
return [...messages.values()].filter((m) => !m.threadId && m.topicId === params?.topicId);
}),
- getLastMainThreadSpineMessageId: vi.fn(async (_topicId: string) => {
- const match = [...messages.values()].findLast(
- (m) => m.role !== 'tool' && !m.threadId && !(m as any).metadata?.signal,
- );
- return match?.id;
- }),
+ getLatestSpineMessageId: vi.fn(
+ async ({ threadId, topicId }: { threadId?: string | null; topicId: string }) => {
+ const match = [...messages.values()].findLast(
+ (m) =>
+ m.topicId === topicId &&
+ m.role !== 'tool' &&
+ m.threadId === (threadId ?? null) &&
+ !(m as any).metadata?.signal,
+ );
+ return match?.id;
+ },
+ ),
listMessagePluginsByTopic: vi.fn(async (_topicId: string) => {
// Mirror the real query: every persisted tool row's (toolCallId → id).
return [...messages.values()]
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts
index 1058268cd20..a4eecabc91c 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts
@@ -43,6 +43,7 @@ interface FakeTopicMetadata {
runningOperation: {
assistantMessageId: string;
operationId: string;
+ threadId?: string;
};
}
@@ -53,10 +54,12 @@ interface FakeTopic {
}
const createHarness = (params: {
+ assistantAgentId?: string | null;
assistantMessageId: string;
operationId: string;
topicAgentId?: string | null;
topicId: string;
+ threadId?: string;
}) => {
let nextMsgIdSeq = 0;
const messages = new Map<string, FakeMessage>();
@@ -65,10 +68,11 @@ const createHarness = (params: {
// Seed the initial assistant message that the orchestrator would have
// created before triggering the CLI ingest.
messages.set(params.assistantMessageId, {
- agentId: params.topicAgentId ?? null,
+ agentId: params.assistantAgentId ?? params.topicAgentId ?? null,
content: '',
id: params.assistantMessageId,
role: 'assistant',
+ threadId: params.threadId ?? null,
topicId: params.topicId,
});
@@ -117,14 +121,17 @@ const createHarness = (params: {
},
),
findById: vi.fn(async (id: string) => messages.get(id) ?? null),
- getLastMainThreadSpineMessageId: vi.fn(async (_topicId: string) => {
- // Mirror the SQL: most recent main-agent (threadId null) message that is
- // NOT a tool and NOT a signal-tagged callback. Insertion order == creation.
- const match = [...messages.values()].findLast(
- (m) => m.role !== 'tool' && !m.threadId && !(m as any).metadata?.signal,
- );
- return match?.id;
- }),
+ getLatestSpineMessageId: vi.fn(
+ async ({ threadId }: { threadId?: string | null; topicId: string }) => {
+ const match = [...messages.values()].findLast(
+ (m) =>
+ m.role !== 'tool' &&
+ (m.threadId ?? null) === (threadId ?? null) &&
+ !(m as any).metadata?.signal,
+ );
+ return match?.id;
+ },
+ ),
listMessagePluginsByTopic: vi.fn(async (_topicId: string) => []),
};
@@ -160,6 +167,7 @@ const createHarness = (params: {
runningOperation: {
assistantMessageId: params.assistantMessageId,
operationId: params.operationId,
+ threadId: params.threadId,
},
} satisfies FakeTopicMetadata,
};
@@ -544,6 +552,52 @@ describe('HeterogeneousPersistenceHandler', () => {
});
describe('3-phase tool persist (main agent)', () => {
+ it('keeps tool rows and post-tool assistants attributed to the direct target agent', async () => {
+ const h = createHarness({
+ assistantAgentId: 'agent-direct-target',
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicAgentId: 'agent-conversation-owner',
+ topicId: 'topic-1',
+ });
+
+ const tool = {
+ apiName: 'Read',
+ arguments: '{"file_path":"tool-proof.txt"}',
+ id: 'tc-1',
+ identifier: 'claude-code',
+ type: 'default' as const,
+ };
+
+ await h.handler.ingest({
+ events: [
+ buildEvent('stream_chunk', 0, { chunkType: 'tools_calling', toolsCalling: [tool] }),
+ buildEvent('tool_result', 1, {
+ content: 'TOOL_CALL_MARKER',
+ isError: false,
+ toolCallId: 'tc-1',
+ }),
+ buildEvent('stream_start', 2, { newStep: true }),
+ buildEvent('stream_chunk', 3, {
+ chunkType: 'text',
+ content: 'TOOL_CALL_MARKER',
+ }),
+ ],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const toolMessage = [...h.messages.values()].find((message) => message.role === 'tool');
+ const finalAssistant = [...h.messages.values()].find(
+ (message) => message.role === 'assistant' && message.id !== 'asst-1',
+ );
+
+ expect(toolMessage?.agentId).toBe('agent-direct-target');
+ expect(finalAssistant?.agentId).toBe('agent-direct-target');
+ expect(finalAssistant?.parentId).toBe('asst-1');
+ expect(finalAssistant?.content).toBe('TOOL_CALL_MARKER');
+ });
+
it('writes assistant.tools[] then tool message then backfilled result_msg_id in order', async () => {
const h = createHarness({
assistantMessageId: 'asst-1',
@@ -637,6 +691,41 @@ describe('HeterogeneousPersistenceHandler', () => {
});
describe('step boundaries (stream_start newStep)', () => {
+ it('recovers an isolation run from the thread spine instead of the projected topic reply', async () => {
+ const h = createHarness({
+ assistantMessageId: 'thread-asst-1',
+ operationId: 'op-1',
+ threadId: 'thread-1',
+ topicId: 'topic-1',
+ });
+ h.messages.set('projected-topic-reply', {
+ agentId: 'target-agent',
+ content: 'projected answer',
+ id: 'projected-topic-reply',
+ role: 'assistant',
+ threadId: null,
+ topicId: 'topic-1',
+ });
+
+ await h.handler.ingest({
+ events: [buildEvent('stream_start', 1, { newStep: true })],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const nextThreadAssistant = [...h.messages.values()].find(
+ (message) =>
+ message.role === 'assistant' &&
+ message.threadId === 'thread-1' &&
+ message.id !== 'thread-asst-1',
+ );
+ expect(nextThreadAssistant?.parentId).toBe('thread-asst-1');
+ expect(h.messageModel.getLatestSpineMessageId).toHaveBeenCalledWith({
+ threadId: 'thread-1',
+ topicId: 'topic-1',
+ });
+ });
+
it('flushes prior content, opens a new assistant chained off the prior assistant (spine)', async () => {
const h = createHarness({
assistantMessageId: 'asst-1',
@@ -680,7 +769,7 @@ describe('HeterogeneousPersistenceHandler', () => {
it('chains off the prior assistant (spine) across a multi-replica boundary, recovered from DB', async () => {
// Phase 2: the chain parent is the run's latest non-tool / non-signal
- // main message, recovered from the DB (`getLastMainThreadSpineMessageId`)
+ // scoped message, recovered from the DB (`getLatestSpineMessageId`)
// independent of the in-memory current-assistant pointer. So even when the
// prior step's tools_calling drained on a DIFFERENT replica (this replica's
// toolState stays empty), step 2 still chains off step 1's assistant — a
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/sessionResume.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/sessionResume.test.ts
index 7703468f704..f1912c8b0e3 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/sessionResume.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/sessionResume.test.ts
@@ -33,6 +33,7 @@ describe('HeterogeneousAgentService — phase 2c session id persistence + resume
const handler = new HeterogeneousPersistenceHandler({
messageModel: {
findById: vi.fn(async () => null),
+ getLatestSpineMessageId: vi.fn(async () => null),
listMessagePluginsByTopic: vi.fn(async () => []),
update: vi.fn(async () => ({ success: true })),
} as any,
@@ -89,6 +90,7 @@ describe('HeterogeneousAgentService — phase 2c session id persistence + resume
const handler = new HeterogeneousPersistenceHandler({
messageModel: {
findById: vi.fn(async () => null),
+ getLatestSpineMessageId: vi.fn(async () => null),
listMessagePluginsByTopic: vi.fn(async () => []),
update: vi.fn(async () => ({ success: true })),
} as any,
@@ -139,6 +141,7 @@ describe('HeterogeneousAgentService — phase 2c session id persistence + resume
const handler = new HeterogeneousPersistenceHandler({
messageModel: {
findById: vi.fn(async () => null),
+ getLatestSpineMessageId: vi.fn(async () => null),
listMessagePluginsByTopic: vi.fn(async () => []),
update: vi.fn(async () => ({ success: true })),
} as any,
@@ -195,6 +198,7 @@ describe('HeterogeneousAgentService — phase 2c session id persistence + resume
const handler = new HeterogeneousPersistenceHandler({
messageModel: {
findById: vi.fn(async () => null),
+ getLatestSpineMessageId: vi.fn(async () => null),
listMessagePluginsByTopic: vi.fn(async () => []),
update: vi.fn(async () => ({ success: true })),
} as any,
@@ -254,6 +258,7 @@ describe('HeterogeneousAgentService — phase 2c session id persistence + resume
const handler = new HeterogeneousPersistenceHandler({
messageModel: {
findById: vi.fn(async () => null),
+ getLatestSpineMessageId: vi.fn(async () => null),
listMessagePluginsByTopic: vi.fn(async () => []),
update: vi.fn(async () => ({ success: true })),
} as any,
@@ -316,6 +321,7 @@ describe('HeterogeneousAgentService — phase 2c session id persistence + resume
const handler = new HeterogeneousPersistenceHandler({
messageModel: {
findById: vi.fn(async () => null),
+ getLatestSpineMessageId: vi.fn(async () => null),
listMessagePluginsByTopic: vi.fn(async () => []),
update: vi.fn(async () => ({ success: true })),
} as any,
@@ -372,6 +378,7 @@ describe('HeterogeneousAgentService — phase 2c session id persistence + resume
const handler = new HeterogeneousPersistenceHandler({
messageModel: {
findById: vi.fn(async () => null),
+ getLatestSpineMessageId: vi.fn(async () => null),
listMessagePluginsByTopic: vi.fn(async () => []),
update: vi.fn(async () => ({ success: true })),
} as any,
@@ -413,6 +420,7 @@ describe('HeterogeneousAgentService — phase 2c session id persistence + resume
const handler = new HeterogeneousPersistenceHandler({
messageModel: {
findById: vi.fn(async () => null),
+ getLatestSpineMessageId: vi.fn(async () => null),
listMessagePluginsByTopic: vi.fn(async () => []),
update: vi.fn(async () => ({ success: true })),
} as any,
diff --git a/apps/server/src/services/heterogeneousAgent/index.ts b/apps/server/src/services/heterogeneousAgent/index.ts
index 68583922674..bbf74625bd3 100644
--- a/apps/server/src/services/heterogeneousAgent/index.ts
+++ b/apps/server/src/services/heterogeneousAgent/index.ts
@@ -6,6 +6,7 @@ import {
isHeteroStatusGuideErrorData,
type LocalHeterogeneousAgentType,
} from '@lobechat/heterogeneous-agents';
+import { ThreadStatus } from '@lobechat/types';
import debug from 'debug';
import { AgentOperationModel } from '@/database/models/agentOperation';
@@ -296,9 +297,11 @@ export class HeterogeneousAgentService {
let serializedHooks: SerializedHook[] | undefined;
let assistantMessageId: string | undefined;
+ let isolationThreadId: string | undefined;
try {
const topic = await this.topicModel.findById(topicId);
serializedHooks = topic?.metadata?.runningOperation?.hooks as SerializedHook[] | undefined;
+ isolationThreadId = topic?.metadata?.runningOperation?.threadId ?? undefined;
// Prefer heteroCurrentMsgId — the persistence handler updates this pointer
// on every step boundary, so it refers to the LAST assistant message with
// the complete final content. Fall back to the initial placeholder id
@@ -340,6 +343,40 @@ export class HeterogeneousAgentService {
}
}
+ // Heterogeneous device callbacks can finish on a different server instance
+ // from the one that registered the in-memory thread hooks. Finalize the
+ // isolation thread durably here as well, and project its terminal answer
+ // back onto the source assistant in the main conversation.
+ if (isolationThreadId) {
+ try {
+ const threadModel = new ThreadModel(this.db, this.userId, this.workspaceId);
+ const thread = await threadModel.findById(isolationThreadId);
+ if (thread) {
+ if (lastAssistantContent && thread.sourceMessageId) {
+ await this.messageModel.update(thread.sourceMessageId, {
+ content: lastAssistantContent,
+ });
+ }
+
+ const completedAt = new Date().toISOString();
+ const startedAt =
+ typeof thread.metadata?.startedAt === 'string' ? thread.metadata.startedAt : undefined;
+ await threadModel.update(isolationThreadId, {
+ metadata: {
+ ...thread.metadata,
+ completedAt,
+ ...(error ? { error } : {}),
+ ...(startedAt ? { duration: Date.now() - new Date(startedAt).getTime() } : undefined),
+ operationId,
+ },
+ status: result === 'success' ? ThreadStatus.Completed : ThreadStatus.Failed,
+ });
+ }
+ } catch (err) {
+ log('heteroFinish: failed to finalize isolation thread (non-fatal): %O', err);
+ }
+ }
+
// Finalize the trace snapshot (uploads it; the terminal op row is written by
// CompletionLifecycle.persistCompletion below). Runs on the real terminal only
// (cancelled returned above). Aggregates come from the accumulated steps;
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 13bc14944a2..fa6b72c2ed3 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -1602,6 +1602,8 @@
"turnProcess.done_other": "Ran {{count}} steps",
"turnProcess.ranFor_one": "Ran {{count}} step ({{duration}})",
"turnProcess.ranFor_other": "Ran {{count}} steps ({{duration}})",
+ "turnProcess.viewFullRecordWithSteps_one": "Executed {{count}} step · View full record",
+ "turnProcess.viewFullRecordWithSteps_other": "Executed {{count}} steps · View full record",
"untitledAgent": "Untitled Agent",
"untitledGroup": "Untitled Group",
"updateAgent": "Update Agent Information",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 66130e9a430..5b0e31724ec 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -1602,6 +1602,8 @@
"turnProcess.done_other": "共运行 {{count}} 步",
"turnProcess.ranFor_one": "共运行 {{count}} 步 ({{duration}})",
"turnProcess.ranFor_other": "共运行 {{count}} 步 ({{duration}})",
+ "turnProcess.viewFullRecordWithSteps_one": "共执行 {{count}} 步 · 点击查看完整记录",
+ "turnProcess.viewFullRecordWithSteps_other": "共执行 {{count}} 步 · 点击查看完整记录",
"untitledAgent": "未命名助理",
"untitledGroup": "未命名群组",
"updateAgent": "更新助理信息",
diff --git a/locales/zh-CN/common.json b/locales/zh-CN/common.json
index f8565b7e920..ff1276cdc7e 100644
--- a/locales/zh-CN/common.json
+++ b/locales/zh-CN/common.json
@@ -546,6 +546,7 @@
"userPanel.workspaceSetting": "工作区设置",
"userPanel.workspaceUsage": "工作区用量",
"version": "版本",
+ "viewExecutionDetails": "查看执行详情",
"visibilityConfirm.irreversible": "(不可逆)",
"visibilityConfirm.makePrivate.itemAccess": "工作区其他成员会立即失去访问权",
"visibilityConfirm.makePrivate.itemLoaded": "对方已加载过的内容无法收回",
diff --git a/packages/conversation-flow/src/transformation/FlatListBuilder.ts b/packages/conversation-flow/src/transformation/FlatListBuilder.ts
index 90a5fd7aa00..6f3c99ca141 100644
--- a/packages/conversation-flow/src/transformation/FlatListBuilder.ts
+++ b/packages/conversation-flow/src/transformation/FlatListBuilder.ts
@@ -187,6 +187,15 @@ export class FlatListBuilder {
const message = this.messageMap.get(childId);
if (!message) continue;
+ // Internal dispatch envelopes remain in the context tree so the target
+ // assistant keeps its parent chain, but they are not user-authored turns
+ // and therefore do not render as standalone bubbles.
+ if (message.metadata?.agentDispatch?.visibility === 'internal') {
+ processedIds.add(message.id);
+ this.buildFlatListRecursive(message.id, flatList, processedIds, allMessages);
+ continue;
+ }
+
// Priority 1: Compare message group
const messageGroup = message.groupId ? this.messageGroupMap.get(message.groupId) : undefined;
diff --git a/packages/conversation-flow/src/transformation/__tests__/FlatListBuilder.test.ts b/packages/conversation-flow/src/transformation/__tests__/FlatListBuilder.test.ts
index 6b9f9ef5bfb..ca3ae6f7895 100644
--- a/packages/conversation-flow/src/transformation/__tests__/FlatListBuilder.test.ts
+++ b/packages/conversation-flow/src/transformation/__tests__/FlatListBuilder.test.ts
@@ -66,6 +66,178 @@ describe('FlatListBuilder', () => {
expect(result[1].id).toBe('msg-2');
});
+ it('should hide cross-agent dispatch user envelope while preserving target reply', () => {
+ const messages: Message[] = [
+ {
+ agentId: 'parent-agent',
+ content: '@Target please handle this',
+ createdAt: 0,
+ id: 'user-parent',
+ role: 'user',
+ updatedAt: 0,
+ },
+ {
+ agentId: 'parent-agent',
+ content: '',
+ createdAt: 1,
+ id: 'assistant-parent',
+ parentId: 'user-parent',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'callAgent',
+ arguments: '{"agentId":"target-agent"}',
+ id: 'call-agent-1',
+ identifier: 'lobe-agent-management',
+ type: 'default',
+ },
+ ],
+ updatedAt: 1,
+ },
+ {
+ content: 'Called agent "target-agent" to respond.',
+ createdAt: 2,
+ id: 'tool-call-agent',
+ parentId: 'assistant-parent',
+ role: 'tool',
+ tool_call_id: 'call-agent-1',
+ updatedAt: 2,
+ },
+ {
+ agentId: 'target-agent',
+ content: '@Target please handle this',
+ createdAt: 3,
+ id: 'user-dispatch-envelope',
+ metadata: { agentDispatch: { kind: 'callAgent', visibility: 'internal' } },
+ parentId: 'assistant-parent',
+ role: 'user',
+ updatedAt: 3,
+ },
+ {
+ agentId: 'target-agent',
+ content: 'Target result',
+ createdAt: 4,
+ id: 'assistant-target',
+ parentId: 'user-dispatch-envelope',
+ role: 'assistant',
+ updatedAt: 4,
+ },
+ ];
+
+ const builder = createBuilder(messages);
+ const result = builder.flatten(messages);
+
+ expect(result.map((message) => message.id)).toEqual([
+ 'user-parent',
+ 'assistant-parent',
+ 'assistant-target',
+ ]);
+ expect(result.filter((message) => message.role === 'user')).toHaveLength(1);
+ expect(result.at(-1)).toMatchObject({
+ agentId: 'target-agent',
+ content: 'Target result',
+ role: 'assistant',
+ });
+ });
+
+ it('should not hide an unmarked cross-agent user turn', () => {
+ const messages: Message[] = [
+ {
+ agentId: 'parent-agent',
+ content: 'Parent answer',
+ createdAt: 0,
+ id: 'assistant-parent',
+ role: 'assistant',
+ updatedAt: 0,
+ },
+ {
+ agentId: 'target-agent',
+ content: 'A real user-authored turn',
+ createdAt: 1,
+ id: 'user-cross-agent',
+ parentId: 'assistant-parent',
+ role: 'user',
+ updatedAt: 1,
+ },
+ ];
+
+ const result = createBuilder(messages).flatten(messages);
+
+ expect(result.map((message) => message.id)).toEqual(['assistant-parent', 'user-cross-agent']);
+ });
+
+ it('should keep a normal same-agent follow-up user message visible', () => {
+ const messages: Message[] = [
+ {
+ agentId: 'agent-a',
+ content: 'First question',
+ createdAt: 0,
+ id: 'user-1',
+ role: 'user',
+ updatedAt: 0,
+ },
+ {
+ agentId: 'agent-a',
+ content: 'First answer',
+ createdAt: 1,
+ id: 'assistant-1',
+ parentId: 'user-1',
+ role: 'assistant',
+ updatedAt: 1,
+ },
+ {
+ agentId: 'agent-a',
+ content: 'Follow-up question',
+ createdAt: 2,
+ id: 'user-2',
+ parentId: 'assistant-1',
+ role: 'user',
+ updatedAt: 2,
+ },
+ ];
+
+ const builder = createBuilder(messages);
+ const result = builder.flatten(messages);
+
+ expect(result.map((message) => message.id)).toEqual(['user-1', 'assistant-1', 'user-2']);
+ });
+
+ it('should keep a user follow-up after a direct cross-agent reply visible', () => {
+ const messages: Message[] = [
+ {
+ agentId: 'conversation-owner',
+ content: '@Target first question',
+ createdAt: 0,
+ id: 'user-1',
+ role: 'user',
+ updatedAt: 0,
+ },
+ {
+ agentId: 'target-agent',
+ content: 'Direct answer',
+ createdAt: 1,
+ id: 'assistant-1',
+ parentId: 'user-1',
+ role: 'assistant',
+ updatedAt: 1,
+ },
+ {
+ agentId: 'conversation-owner',
+ content: 'Follow-up question',
+ createdAt: 2,
+ id: 'user-2',
+ parentId: 'assistant-1',
+ role: 'user',
+ updatedAt: 2,
+ },
+ ];
+
+ const builder = createBuilder(messages);
+ const result = builder.flatten(messages);
+
+ expect(result.map((message) => message.id)).toEqual(['user-1', 'assistant-1', 'user-2']);
+ });
+
it('should create assistant group virtual message', () => {
const messages: Message[] = [
{
diff --git a/packages/database/src/models/__tests__/messages/message.thread-query.test.ts b/packages/database/src/models/__tests__/messages/message.thread-query.test.ts
index 754a982a8cd..2c4eee9f596 100644
--- a/packages/database/src/models/__tests__/messages/message.thread-query.test.ts
+++ b/packages/database/src/models/__tests__/messages/message.thread-query.test.ts
@@ -224,7 +224,10 @@ describe('MessageModel thread query', () => {
it('should return parent messages + thread messages when querying with topicId and threadId', async () => {
await serverDB.transaction(async (trx) => {
- await trx.insert(agents).values([{ id: 'agent1', userId }]);
+ await trx.insert(agents).values([
+ { id: 'agent1', userId },
+ { id: 'agent2', userId },
+ ]);
await trx.insert(sessions).values([{ id: 'session1', userId }]);
await trx.insert(topics).values([
{ id: 'topic1', sessionId: 'session1', userId },
@@ -275,6 +278,16 @@ describe('MessageModel thread query', () => {
content: 'thread message 1',
createdAt: new Date('2023-01-02T10:00:00'),
},
+ {
+ id: 'delegated-thread-reply',
+ userId,
+ agentId: 'agent2',
+ topicId: 'topic1',
+ threadId: 'thread1',
+ role: 'assistant',
+ content: 'reply from the mentioned agent',
+ createdAt: new Date('2023-01-02T11:00:00'),
+ },
// Messages in topic2 (should not be included)
{
id: 'topic2-msg1',
@@ -296,10 +309,16 @@ describe('MessageModel thread query', () => {
threadId: 'thread1',
});
- // Should include parent messages (msg1, msg2) + thread message (thread-msg1)
+ // Should include parent messages and every reply in the topic thread, including replies
+ // persisted by an agent mentioned from the parent agent's portal.
// Should NOT include topic2-msg1
- expect(result).toHaveLength(3);
- expect(result.map((m) => m.id)).toEqual(['msg1', 'msg2', 'thread-msg1']);
+ expect(result).toHaveLength(4);
+ expect(result.map((m) => m.id)).toEqual([
+ 'msg1',
+ 'msg2',
+ 'thread-msg1',
+ 'delegated-thread-reply',
+ ]);
});
it('should return only source message + thread messages for Standalone type', async () => {
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index 7ea299f94e8..f08d7386bd8 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -448,6 +448,9 @@ export class MessageModel {
() => this.buildThreadQueryCondition(threadId),
{ hasThreadId: true },
);
+ // A topic thread may contain replies from delegated agents. When the topic is known,
+ // scope the complete thread to it instead of filtering those replies by the parent agent.
+ const threadScopeCondition = topicId ? this.matchTopic(topicId) : agentCondition;
const messageItems = await this.queryWithWhere({
current,
includeFileWorks,
@@ -455,8 +458,8 @@ export class MessageModel {
postProcessUrl: options.postProcessUrl,
skipWorks,
timing,
- // Thread queries optionally add agent/session scope if provided
- where: agentCondition ? and(agentCondition, threadCondition) : threadCondition,
+ topicId: topicId ?? undefined,
+ where: threadScopeCondition ? and(threadScopeCondition, threadCondition) : threadCondition,
});
logTiming(timing, 'db.message.query:done', {
messageCount: messageItems.length,
diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.ts
index f0a04368f17..223c5820802 100644
--- a/packages/heterogeneous-agents/src/adapters/claudeCode.ts
+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.ts
@@ -1025,10 +1025,9 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {
private stepIndex = 0;
/**
* True once any `stream_event` wrapper is seen — i.e. CC was spawned with
- * `--include-partial-messages` (desktop driver). The `lh hetero exec` CLI
- * used by device + sandbox runs spawns in BATCH mode (no partial flag), so
- * this stays false and `handleAssistant` owns per-turn usage instead of
- * `message_delta`.
+ * `--include-partial-messages` (desktop driver and current `lh hetero exec`).
+ * Older producers and explicit batch-mode callers still leave this false,
+ * so `handleAssistant` owns per-turn usage instead of `message_delta`.
*/
private sawStreamEvent = false;
/** Track current message.id to detect step boundaries */
@@ -1502,8 +1501,8 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {
}
events.push(...this.emitToolChunk(newToolCalls, messageId));
- // BATCH mode (no `--include-partial-messages`, e.g. the `lh hetero exec`
- // CLI used by device + sandbox runs): there is no `message_delta` to carry
+ // BATCH mode (no `--include-partial-messages`, e.g. older producers or
+ // explicit low-volume callers): there is no `message_delta` to carry
// per-turn usage, and the `assistant` event's usage is NOT a stale
// message_start echo — it's the real per-message total. Emit it as
// turn_metadata so usage (token counts) AND the canonical model id (the
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 2ca48d13132..80ff56e53b0 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -1825,6 +1825,8 @@ export default {
'turnProcess.done_other': 'Ran {{count}} steps',
'turnProcess.ranFor_one': 'Ran {{count}} step ({{duration}})',
'turnProcess.ranFor_other': 'Ran {{count}} steps ({{duration}})',
+ 'turnProcess.viewFullRecordWithSteps_one': 'Executed {{count}} step · View full record',
+ 'turnProcess.viewFullRecordWithSteps_other': 'Executed {{count}} steps · View full record',
'untitledAgent': 'Untitled Agent',
'untitledGroup': 'Untitled Group',
'updateAgent': 'Update Agent Information',
diff --git a/packages/locales/src/default/common.ts b/packages/locales/src/default/common.ts
index 20b44128e6e..ed8e68e7291 100644
--- a/packages/locales/src/default/common.ts
+++ b/packages/locales/src/default/common.ts
@@ -59,6 +59,7 @@ export default {
'The "Sub-topic" feature is unavailable in the current mode. To use this feature, please switch to Postgres/Pglite DB mode or use LobeHub Cloud.',
'branchingRequiresSavedTopic':
'Current topic is not saved, please save it first to use subtopic feature',
+ 'viewExecutionDetails': 'View execution details',
'cancel': 'Cancel',
'changelog': 'Changelog',
'alreadyUpToDate': 'Already Up to Date',
diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.ts
index 7728845eb23..435931fb933 100644
--- a/packages/types/src/agentExecution/index.ts
+++ b/packages/types/src/agentExecution/index.ts
@@ -68,6 +68,11 @@ export interface ExecAgentAppContext {
* Forwarded into the operation so the completion path can project receipts.
*/
agentSignal?: AgentSignalOperationMarker;
+ /**
+ * Agent that owns the conversation when it differs from the agent executing
+ * this run (for example, a single explicit @Agent direct route).
+ */
+ conversationAgentId?: string;
/** Optional default assignee candidate for task manager prompts */
defaultTaskAssigneeAgentId?: string;
/** Current document ID for page-scoped conversations */
diff --git a/packages/types/src/aiChat.ts b/packages/types/src/aiChat.ts
index 89088c58b12..f7965e1c0e4 100644
--- a/packages/types/src/aiChat.ts
+++ b/packages/types/src/aiChat.ts
@@ -63,6 +63,8 @@ export interface SendMessageServerParams {
*/
groupId?: string;
newAssistantMessage: {
+ /** Agent that authored the assistant turn when it differs from the conversation owner. */
+ agentId?: string;
/**
* Id the client already rendered this message under. Honoured verbatim by
* the server, so the optimistic row never has to be re-keyed. Omit to let
@@ -168,6 +170,7 @@ export const AiSendMessageServerSchema = z.object({
agentId: z.string().optional(),
groupId: z.string().optional(),
newAssistantMessage: z.object({
+ agentId: z.string().optional(),
id: clientEntityId('messages'),
metadata: z.record(z.string(), z.unknown()).optional(),
model: z.string().optional(),
diff --git a/packages/types/src/message/common/metadata.test.ts b/packages/types/src/message/common/metadata.test.ts
index b40411156aa..9b77a894d3a 100644
--- a/packages/types/src/message/common/metadata.test.ts
+++ b/packages/types/src/message/common/metadata.test.ts
@@ -4,6 +4,17 @@ import { RequestTrigger } from '../../agentRuntime';
import { MessageMetadataSchema } from './metadata';
describe('MessageMetadataSchema', () => {
+ it('preserves explicit internal agent-dispatch semantics', () => {
+ const parsed = MessageMetadataSchema.parse({
+ agentDispatch: { kind: 'callAgent', visibility: 'internal' },
+ unknown: 'stripped',
+ });
+
+ expect(parsed).toEqual({
+ agentDispatch: { kind: 'callAgent', visibility: 'internal' },
+ });
+ });
+
it('preserves request trigger metadata during runtime parsing', () => {
const parsed = MessageMetadataSchema.parse({
trigger: RequestTrigger.Onboarding,
diff --git a/packages/types/src/message/common/metadata.ts b/packages/types/src/message/common/metadata.ts
index b792f95e35f..7c475a909e6 100644
--- a/packages/types/src/message/common/metadata.ts
+++ b/packages/types/src/message/common/metadata.ts
@@ -185,7 +185,18 @@ export const MessageWorkMetadataSchema = z.object({
userMessageId: z.string().optional(),
});
+export const AgentDispatchMetadataSchema = z.object({
+ kind: z.enum(['callAgent']),
+ visibility: z.literal('internal'),
+});
+
+export interface AgentDispatchMetadata {
+ kind: 'callAgent';
+ visibility: 'internal';
+}
+
export const MessageMetadataSchema = ModelUsageSchema.merge(ModelPerformanceSchema).extend({
+ agentDispatch: AgentDispatchMetadataSchema.optional(),
collapsed: z.boolean().optional(),
contextSelections: z.array(ContextSelectionSchema).optional(),
// Hetero-agent (Claude Code) per-message provenance. Listed here so zod does
@@ -273,6 +284,11 @@ export interface MessageMetadata {
* AgentCouncil: its member responses render as one parallel-streaming block.
*/
agentCouncil?: boolean;
+ /**
+ * Explicit transport semantics for an internal cross-agent dispatch turn.
+ * Renderers consume this marker instead of inferring intent from the message tree.
+ */
+ agentDispatch?: AgentDispatchMetadata;
/**
* Message collapse state
* true: collapsed, false/undefined: expanded
diff --git a/src/features/Conversation/ChatList/index.tsx b/src/features/Conversation/ChatList/index.tsx
index 50b699e2aaf..5988faaed5c 100644
--- a/src/features/Conversation/ChatList/index.tsx
+++ b/src/features/Conversation/ChatList/index.tsx
@@ -2,7 +2,7 @@
import { Flexbox } from '@lobehub/ui';
import type { ReactNode } from 'react';
-import { memo, useCallback } from 'react';
+import { memo, useCallback, useMemo } from 'react';
import AsyncError from '@/components/AsyncError';
import { useFetchTopicMemories } from '@/hooks/useFetchMemoryForTopic';
@@ -28,6 +28,16 @@ import { useAgentSignalReceipts } from './hooks/useAgentSignalReceipts';
import { useMessageRefreshError } from './hooks/useMessageRefreshError';
import { resolveMessageListFeedback } from './resolveMessageListFeedback';
+const MessageAuthorConfigLoader = memo<{ agentId: string; isLogin: boolean | undefined }>(
+ ({ agentId, isLogin }) => {
+ const useFetchAgentConfig = useAgentStore((s) => s.useFetchAgentConfig);
+ useFetchAgentConfig(isLogin, agentId);
+ return null;
+ },
+);
+
+MessageAuthorConfigLoader.displayName = 'MessageAuthorConfigLoader';
+
export interface ChatListProps {
/**
* Default expand level for assistant workflow (tool-call) groups. When set,
@@ -143,6 +153,13 @@ const ChatList = memo<ChatListProps>(
const isLogin = useUserStore(authSelectors.isLogin);
const useFetchAgentConfig = useAgentStore((s) => s.useFetchAgentConfig);
useFetchAgentConfig(isLogin, context.agentId);
+ const messageAuthorAgentIds = useMemo(
+ () =>
+ [...new Set(displayMessages.map((message) => message.agentId).filter(Boolean))].filter(
+ (agentId) => agentId !== context.agentId,
+ ) as string[],
+ [context.agentId, displayMessages],
+ );
// Fetch conversation context data when a conversation is visible (skip for share pages).
// NOTE: the agent-document list is intentionally NOT pre-warmed here — this
@@ -234,6 +251,9 @@ const ChatList = memo<ChatListProps>(
return (
<Flexbox style={{ height: '100%', minHeight: 0 }}>
+ {messageAuthorAgentIds.map((agentId) => (
+ <MessageAuthorConfigLoader agentId={agentId} isLogin={isLogin} key={agentId} />
+ ))}
<Flexbox flex={1} style={{ minHeight: 0 }}>
{content}
</Flexbox>
diff --git a/src/features/Conversation/Messages/Assistant/components/ThreadExecutionSummary.test.ts b/src/features/Conversation/Messages/Assistant/components/ThreadExecutionSummary.test.ts
new file mode 100644
index 00000000000..1b1686e830a
--- /dev/null
+++ b/src/features/Conversation/Messages/Assistant/components/ThreadExecutionSummary.test.ts
@@ -0,0 +1,13 @@
+import { describe, expect, it } from 'vitest';
+
+import { getThreadExecutionStepCount } from './ThreadExecutionSummary';
+
+describe('getThreadExecutionStepCount', () => {
+ it('shows one execution step before tool-call totals settle', () => {
+ expect(getThreadExecutionStepCount()).toBe(1);
+ });
+
+ it('counts each tool call plus the final response step', () => {
+ expect(getThreadExecutionStepCount(2)).toBe(3);
+ });
+});
diff --git a/src/features/Conversation/Messages/Assistant/components/ThreadExecutionSummary.tsx b/src/features/Conversation/Messages/Assistant/components/ThreadExecutionSummary.tsx
new file mode 100644
index 00000000000..52626ac15d4
--- /dev/null
+++ b/src/features/Conversation/Messages/Assistant/components/ThreadExecutionSummary.tsx
@@ -0,0 +1,53 @@
+import { Accordion, AccordionItem, Text } from '@lobehub/ui';
+import { type Key, memo, useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useChatStore } from '@/store/chat';
+import { threadSelectors } from '@/store/chat/selectors';
+
+interface ThreadExecutionSummaryProps {
+ messageId: string;
+}
+
+export const getThreadExecutionStepCount = (toolCalls?: number): number =>
+ Math.max(1, (toolCalls ?? 0) + 1);
+
+/**
+ * Persistent content-level affordance for a projected Agent reply.
+ * Reuses the same borderless Accordion chrome as AssistantGroup's ProcessFold,
+ * but opening this projection navigates to the associated Isolation Thread.
+ */
+const ThreadExecutionSummary = memo<ThreadExecutionSummaryProps>(({ messageId }) => {
+ const { t } = useTranslation('chat');
+ const thread = useChatStore(threadSelectors.getIsolationThreadBySourceMsgId(messageId));
+ const openThreadInPortal = useChatStore((s) => s.openThreadInPortal);
+
+ const handleExpandedChange = useCallback(
+ (_keys: Key[]) => {
+ if (!thread) return;
+ openThreadInPortal(thread.id, messageId);
+ },
+ [messageId, openThreadInPortal, thread],
+ );
+
+ if (!thread) return null;
+
+ const label = t('turnProcess.viewFullRecordWithSteps', {
+ count: getThreadExecutionStepCount(thread.metadata?.totalToolCalls),
+ });
+
+ return (
+ <Accordion expandedKeys={[]} variant={'borderless'} onExpandedChange={handleExpandedChange}>
+ <AccordionItem
+ itemKey={'execution-record'}
+ paddingBlock={4}
+ paddingInline={4}
+ title={<Text type={'secondary'}>{label}</Text>}
+ />
+ </Accordion>
+ );
+});
+
+ThreadExecutionSummary.displayName = 'ThreadExecutionSummary';
+
+export default ThreadExecutionSummary;
diff --git a/src/features/Conversation/Messages/Assistant/index.tsx b/src/features/Conversation/Messages/Assistant/index.tsx
index 92c764eb636..186fa6f8b09 100644
--- a/src/features/Conversation/Messages/Assistant/index.tsx
+++ b/src/features/Conversation/Messages/Assistant/index.tsx
@@ -26,6 +26,7 @@ import {
import MessageWorks from '../MessageWorks';
import InterruptedHint from './components/InterruptedHint';
import MessageContent from './components/MessageContent';
+import ThreadExecutionSummary from './components/ThreadExecutionSummary';
import { AssistantMessageExtra } from './Extra';
const actionBarHolder = (
@@ -126,12 +127,12 @@ const AssistantMessage = memo<AssistantMessageProps>(
return (
<ChatItem
showTitle
- aboveMessage={null}
- avatar={avatar}
- belowMessage={hasEmptyErrorMessage ? footerRender : undefined}
+ aboveMessage={<ThreadExecutionSummary messageId={id} />}
// ChatItem renders this as the primary block when the message is empty,
// or inside messageExtra (below the content) when the turn streamed
// content before erroring — so don't gate it on empty content.
+ avatar={avatar}
+ belowMessage={hasEmptyErrorMessage ? footerRender : undefined}
customErrorRender={(error) => <ErrorMessageExtra data={item} error={error} />}
editing={editing}
error={errorContent && error ? errorContent : undefined}
diff --git a/src/features/Portal/Thread/Chat/index.tsx b/src/features/Portal/Thread/Chat/index.tsx
index 417d2bb9a37..65b7babb63a 100644
--- a/src/features/Portal/Thread/Chat/index.tsx
+++ b/src/features/Portal/Thread/Chat/index.tsx
@@ -17,13 +17,15 @@ import { useChatFollowUp } from '@/features/Conversation/hooks/useChatFollowUp';
import { type ComposerTarget, resolveThreadComposerTarget } from '@/features/Conversation/types';
import { mergeConversationHooks } from '@/features/Conversation/utils/mergeConversationHooks';
import { useOperationState } from '@/hooks/useOperationState';
+import HeterogeneousChatInput from '@/routes/(main)/agent/features/Conversation/HeterogeneousChatInput';
import { useAgentStore } from '@/store/agent';
-import { chatConfigByIdSelectors } from '@/store/agent/selectors';
+import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
import { portalThreadSelectors, threadSelectors } from '@/store/chat/selectors';
import { type MessageMapKeyInput } from '@/store/chat/utils/messageMapKey';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+import { getThreadInputMode } from './inputMode';
import ThreadDivider from './ThreadDivider';
import { useThreadActionsBarConfig } from './useThreadActionsBarConfig';
@@ -33,80 +35,75 @@ import { useThreadActionsBarConfig } from './useThreadActionsBarConfig';
*/
interface ThreadChatContentProps {
composerWritable: boolean;
+ isHeterogeneousAgent: boolean;
readOnly: boolean;
}
-const ThreadChatContent = memo<ThreadChatContentProps>(({ composerWritable, readOnly }) => {
- // Get display messages from ConversationStore to determine thread divider position
- // With the new backend API, parent messages have threadId === null
- // and thread messages have threadId === context.threadId
- const displayMessages = useConversationStore(conversationSelectors.displayMessages);
+const ThreadChatContent = memo<ThreadChatContentProps>(
+ ({ composerWritable, isHeterogeneousAgent, readOnly }) => {
+ const inputMode = getThreadInputMode({
+ isExternallyOwnedThread: readOnly,
+ isHeterogeneousAgent,
+ });
+ const displayMessages = useConversationStore(conversationSelectors.displayMessages);
- // Find the last parent message (source message) - it's the last message with threadId === null
- const threadSourceInfo = useMemo(() => {
- // Find the index of the last parent message (threadId is null or undefined)
- let sourceMessageIndex = -1;
- let sourceMessageId: string | undefined;
+ const threadSourceInfo = useMemo(() => {
+ let sourceMessageIndex = -1;
+ let sourceMessageId: string | undefined;
- for (const [i, msg] of displayMessages.entries()) {
- // Parent messages don't have threadId
- if (!msg.threadId) {
- sourceMessageIndex = i;
- sourceMessageId = msg.id;
+ for (const [i, msg] of displayMessages.entries()) {
+ if (!msg.threadId) {
+ sourceMessageIndex = i;
+ sourceMessageId = msg.id;
+ }
}
- }
-
- return { sourceMessageId, sourceMessageIndex };
- }, [displayMessages]);
- // Custom item content renderer for thread-specific features
- const itemContent = useCallback(
- (index: number, id: string) => {
- // Check if this message needs ThreadDivider (after thread source message)
- const enableThreadDivider = threadSourceInfo.sourceMessageId === id;
+ return { sourceMessageId, sourceMessageIndex };
+ }, [displayMessages]);
- // Check if this is a parent message (should be read-only)
- // Parent messages are those with index <= sourceMessageIndex
- const isParentMessage = index <= threadSourceInfo.sourceMessageIndex;
+ const itemContent = useCallback(
+ (index: number, id: string) => {
+ const enableThreadDivider = threadSourceInfo.sourceMessageId === id;
+ const isParentMessage = index <= threadSourceInfo.sourceMessageIndex;
- return (
- <MessageItem
- inPortalThread
- disableEditing={readOnly || isParentMessage}
- endRender={enableThreadDivider ? <ThreadDivider /> : undefined}
- id={id}
- index={index}
- />
- );
- },
- [threadSourceInfo.sourceMessageId, threadSourceInfo.sourceMessageIndex, readOnly],
- );
+ return (
+ <MessageItem
+ inPortalThread
+ disableEditing={readOnly || isParentMessage}
+ endRender={enableThreadDivider ? <ThreadDivider /> : undefined}
+ id={id}
+ index={index}
+ />
+ );
+ },
+ [threadSourceInfo.sourceMessageId, threadSourceInfo.sourceMessageIndex, readOnly],
+ );
- return (
- <>
- <Suspense
- fallback={
- <Flexbox flex={1} height={'100%'}>
- <SkeletonList />
- </Flexbox>
- }
- >
- <Flexbox
- flex={1}
- width={'100%'}
- style={{
- overflowX: 'hidden',
- overflowY: 'auto',
- position: 'relative',
- }}
+ return (
+ <>
+ <Suspense
+ fallback={
+ <Flexbox flex={1} height={'100%'}>
+ <SkeletonList />
+ </Flexbox>
+ }
>
- <ChatList itemContent={itemContent} />
- </Flexbox>
- </Suspense>
- {composerWritable && <ChatInput leftActions={['typo']} rightActions={['contextWindow']} />}
- </>
- );
-});
+ <Flexbox
+ flex={1}
+ style={{ overflowX: 'hidden', overflowY: 'auto', position: 'relative' }}
+ width={'100%'}
+ >
+ <ChatList itemContent={itemContent} />
+ </Flexbox>
+ </Suspense>
+ {composerWritable && inputMode === 'heterogeneous' && <HeterogeneousChatInput />}
+ {composerWritable && inputMode === 'default' && (
+ <ChatInput leftActions={['typo']} rightActions={['contextWindow']} />
+ )}
+ </>
+ );
+ },
+);
ThreadChatContent.displayName = 'ThreadChatContent';
@@ -137,6 +134,10 @@ const ThreadChat = memo(() => {
const portalThread = useChatStore(portalThreadSelectors.portalCurrentThread);
const threadMetadataResolved = !portalThreadId || !!portalThread;
const isSubagentThread = !!portalThread?.metadata?.sourceToolCallId;
+ const threadAgentId = portalThread?.agentId || activeAgentId;
+ const isHeterogeneousAgent = useAgentStore(
+ agentByIdSelectors.isAgentHeterogeneousById(threadAgentId || ''),
+ );
// Get thread-specific actionsBar config
const actionsBarConfig = useThreadActionsBarConfig({
@@ -150,7 +151,7 @@ const ThreadChat = memo(() => {
// Context for ConversationProvider (includes sourceMessageId/threadType for new thread creation)
const context: ConversationContext = useMemo(
() => ({
- agentId: activeAgentId,
+ agentId: threadAgentId,
// Use isNew + scope for new thread creation
isNew: isCreatingNewThread,
scope: 'thread',
@@ -161,7 +162,7 @@ const ThreadChat = memo(() => {
topicId: activeTopicId,
}),
[
- activeAgentId,
+ threadAgentId,
activeTopicId,
portalThreadId,
threadStartMessageId,
@@ -173,13 +174,13 @@ const ThreadChat = memo(() => {
// Context for messageMapKey (only needs fields used in key generation)
const keyContext = useMemo<MessageMapKeyInput>(
() => ({
- agentId: activeAgentId,
+ agentId: threadAgentId,
isNew: isCreatingNewThread,
scope: 'thread',
threadId: portalThreadId,
topicId: activeTopicId,
}),
- [activeAgentId, activeTopicId, portalThreadId, isCreatingNewThread],
+ [threadAgentId, activeTopicId, portalThreadId, isCreatingNewThread],
);
// Generate messageMapKey for direct subscription to dbMessagesMap
@@ -203,7 +204,7 @@ const ThreadChat = memo(() => {
const operationState = useOperationState(context);
const agentChatConfig = useAgentStore(
- chatConfigByIdSelectors.getChatConfigById(activeAgentId || ''),
+ chatConfigByIdSelectors.getChatConfigById(threadAgentId || ''),
);
const chatFollowUpHooks = useChatFollowUp({
agentChatConfig,
@@ -258,6 +259,7 @@ const ThreadChat = memo(() => {
>
<ThreadChatContent
composerWritable={composerTarget.writable}
+ isHeterogeneousAgent={isHeterogeneousAgent}
readOnly={!composerTarget.writable}
/>
</ConversationProvider>
diff --git a/src/features/Portal/Thread/Chat/inputMode.test.ts b/src/features/Portal/Thread/Chat/inputMode.test.ts
new file mode 100644
index 00000000000..9ed440eaba4
--- /dev/null
+++ b/src/features/Portal/Thread/Chat/inputMode.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from 'vitest';
+
+import { getThreadInputMode } from './inputMode';
+
+describe('getThreadInputMode', () => {
+ it('uses the heterogeneous Agent composer for a continuable heterogeneous thread', () => {
+ expect(getThreadInputMode({ isExternallyOwnedThread: false, isHeterogeneousAgent: true })).toBe(
+ 'heterogeneous',
+ );
+ });
+
+ it('uses the default composer for an ordinary continuable thread', () => {
+ expect(
+ getThreadInputMode({ isExternallyOwnedThread: false, isHeterogeneousAgent: false }),
+ ).toBe('default');
+ });
+
+ it('keeps tool-owned subagent records read-only regardless of Agent type', () => {
+ expect(getThreadInputMode({ isExternallyOwnedThread: true, isHeterogeneousAgent: true })).toBe(
+ 'hidden',
+ );
+ });
+});
diff --git a/src/features/Portal/Thread/Chat/inputMode.ts b/src/features/Portal/Thread/Chat/inputMode.ts
new file mode 100644
index 00000000000..3e5b5f8a212
--- /dev/null
+++ b/src/features/Portal/Thread/Chat/inputMode.ts
@@ -0,0 +1,13 @@
+export type ThreadInputMode = 'default' | 'heterogeneous' | 'hidden';
+
+export const getThreadInputMode = ({
+ isExternallyOwnedThread,
+ isHeterogeneousAgent,
+}: {
+ isExternallyOwnedThread: boolean;
+ isHeterogeneousAgent: boolean;
+}): ThreadInputMode => {
+ if (isExternallyOwnedThread) return 'hidden';
+
+ return isHeterogeneousAgent ? 'heterogeneous' : 'default';
+};
diff --git a/src/features/Portal/Thread/Header/Active.tsx b/src/features/Portal/Thread/Header/Active.tsx
index cc2e291afe2..475a779b4ec 100644
--- a/src/features/Portal/Thread/Header/Active.tsx
+++ b/src/features/Portal/Thread/Header/Active.tsx
@@ -1,18 +1,20 @@
import { resolveCCSubagentType } from '@lobechat/builtin-tool-claude-code/client';
-import { Flexbox, Icon, Tag, Text } from '@lobehub/ui';
+import { Avatar, Flexbox, Icon, Tag, Text } from '@lobehub/ui';
import { cssVar } from 'antd-style';
import isEqual from 'fast-deep-equal';
-import { ListTree } from 'lucide-react';
import { memo } from 'react';
import BubblesLoading from '@/components/BubblesLoading';
import { LOADING_FLAT } from '@/const/message';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
import { portalThreadSelectors } from '@/store/chat/selectors';
import { oneLineEllipsis } from '@/styles';
const Active = memo(() => {
const currentThread = useChatStore(portalThreadSelectors.portalCurrentThread, isEqual);
+ const agentMeta = useAgentStore(agentSelectors.getAgentMetaById(currentThread?.agentId || ''));
if (!currentThread) return null;
@@ -23,7 +25,7 @@ const Active = memo(() => {
return (
<Flexbox horizontal align={'center'} gap={8} style={{ marginInlineStart: 4 }}>
- <Icon color={cssVar.colorTextSecondary} icon={ListTree} size={18} />
+ <Avatar {...agentMeta} size={24} />
<Text
className={oneLineEllipsis}
ellipsis={true}
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx
index c03e89d6607..8b77e304604 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx
@@ -6,8 +6,6 @@ import { Alert, Flexbox } from '@lobehub/ui';
import { Button } from '@lobehub/ui/base-ui';
import { memo, type ReactNode, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useParams } from 'react-router';
-import urlJoin from 'url-join';
import { useHeteroAgentCloudConfig } from '@/business/client/hooks/useHeteroAgentCloudConfig';
import { isDesktop } from '@/const/version';
@@ -86,7 +84,6 @@ const HeterogeneousChatInput = memo(() => {
// the global (hijack-prone) active agent.
const agentId = useConversationStore(contextSelectors.agentId);
const { isConfigured, goToConfig } = useHeteroAgentCloudConfig(agentId);
- const params = useParams<{ aid: string }>();
const navigate = useWorkspaceAwareNavigate();
// Effective config = shared row + this member's per-agent device override
@@ -152,7 +149,7 @@ const HeterogeneousChatInput = memo(() => {
const { status, refresh } = useRemoteAgentDeviceGuard({ agentId, enabled: isDeviceExecution });
const goToAgentProfile = () => {
- if (params.aid) navigate(urlJoin('/agent', params.aid, 'profile'));
+ if (agentId) navigate(`/agent/${agentId}/profile`);
};
const deviceBlocked =
diff --git a/src/services/aiAgent.ts b/src/services/aiAgent.ts
index 4cfdd810fcb..3b751298795 100644
--- a/src/services/aiAgent.ts
+++ b/src/services/aiAgent.ts
@@ -134,6 +134,11 @@ export interface InterruptTaskParams {
*/
export interface CreateClientTaskThreadParams {
agentId: string;
+ /**
+ * Seed an assistant placeholder for transports that stream into an existing
+ * message (for example a local heterogeneous CLI).
+ */
+ assistantMessage?: { provider: string };
groupId?: string;
/** Initial user message content (task instruction) */
instruction: string;
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
index 54cbe42d548..d09b3164a9f 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
@@ -4,6 +4,7 @@ import { TRPCClientError } from '@trpc/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { agentService } from '@/services/agent';
+import { aiAgentService } from '@/services/aiAgent';
import { aiChatService } from '@/services/aiChat';
import { chatService } from '@/services/chat';
import * as skillPreload from '@/services/chat/mecha/skillPreload';
@@ -2766,9 +2767,9 @@ describe('ConversationLifecycle actions', () => {
it('should directly call a single leading @agent in non-group chat', async () => {
const { result } = renderHook(() => useChatStore());
const targetAgentId = 'agent-direct-target';
- const toolMessageId = 'tool-call-agent-result';
+ const toolMessageId = 'unused-tool-call-agent-result';
const message = '@Agent B hello';
- const createdThreadId = 'thread-created-by-send';
+ const createdThreadId = 'thread-direct-mention';
const userMessage = createMockMessage({
id: TEST_IDS.USER_MESSAGE_ID,
@@ -2783,12 +2784,26 @@ describe('ConversationLifecycle actions', () => {
});
vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({
- createdThreadId,
messages: [userMessage, assistantMessage],
- topics: [],
+ topicId: TEST_IDS.TOPIC_ID,
assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
userMessageId: TEST_IDS.USER_MESSAGE_ID,
} as any);
+ vi.spyOn(aiAgentService, 'createClientTaskThread').mockResolvedValue({
+ messages: [userMessage, assistantMessage],
+ startedAt: new Date().toISOString(),
+ success: true,
+ threadId: createdThreadId,
+ threadMessages: [
+ createMockMessage({ id: 'thread-user', role: 'user', threadId: createdThreadId }),
+ ],
+ userMessageId: 'thread-user',
+ } as any);
+ vi.spyOn(aiAgentService, 'updateClientTaskThreadStatus').mockResolvedValue({
+ status: 'completed',
+ success: true,
+ threadId: createdThreadId,
+ } as any);
(messageService.updateMessage as any).mockImplementation(
async (_id: string, value: any) => {
@@ -2830,71 +2845,161 @@ describe('ConversationLifecycle actions', () => {
type: 'root',
},
} as any,
- context: createTestContext(),
+ context: { ...createTestContext(), topicId: TEST_IDS.TOPIC_ID },
});
});
- expect(agentService.getAgentConfigById).toHaveBeenCalledWith(targetAgentId);
- expect(messageService.updateMessage).toHaveBeenCalledWith(
- TEST_IDS.ASSISTANT_MESSAGE_ID,
- expect.objectContaining({
- content: '',
- tools: [
- expect.objectContaining({
- apiName: 'callAgent',
- identifier: 'lobe-agent-management',
- }),
- ],
- }),
- expect.objectContaining({ agentId: TEST_IDS.SESSION_ID }),
- );
- expect(messageService.createMessage).toHaveBeenCalledWith(
+ expect(messageService.createMessage).not.toHaveBeenCalled();
+ expect(aiChatService.sendMessageInServer).toHaveBeenCalledWith(
expect.objectContaining({
agentId: TEST_IDS.SESSION_ID,
- content: `Called agent "${targetAgentId}" to respond.`,
- parentId: TEST_IDS.ASSISTANT_MESSAGE_ID,
- plugin: expect.objectContaining({
- apiName: 'callAgent',
- identifier: 'lobe-agent-management',
- }),
- pluginState: {
- agentId: targetAgentId,
- instruction: message,
- mode: 'speak',
- },
- role: 'tool',
+ newAssistantMessage: expect.objectContaining({ agentId: targetAgentId }),
}),
+ expect.any(AbortController),
);
const execCall = (result.current.executeClientAgent as any).mock.calls[0]?.[0];
expect(execCall).toEqual(
expect.objectContaining({
context: expect.objectContaining({
- agentId: TEST_IDS.SESSION_ID,
+ agentId: targetAgentId,
scope: 'sub_agent',
subAgentId: targetAgentId,
+ threadId: createdThreadId,
}),
inPortalThread: true,
- parentMessageId: toolMessageId,
- parentMessageType: 'tool',
+ isSubAgent: true,
+ parentMessageId: 'thread-user',
+ parentMessageType: 'user',
}),
);
expect(execCall.initialContext).toBeUndefined();
- expect(execCall.messages).toEqual(
- expect.arrayContaining([
- expect.objectContaining({ id: toolMessageId, role: 'tool' }),
- expect.objectContaining({
- content: expect.stringContaining(message),
- role: 'user',
+ expect(execCall.messages).toEqual(expect.any(Array));
+ });
+
+ it('should isolate a direct mention executed by a local heterogeneous agent', async () => {
+ mockConstEnv.isDesktop = true;
+ setupMockSelectors({
+ agentConfig: {
+ agencyConfig: {
+ heterogeneousProvider: { command: 'codex', type: 'codex' },
+ },
+ },
+ });
+
+ const targetAgentId = 'agent-direct-codex';
+ const threadId = 'thread-direct-codex';
+ const threadAssistantId = 'thread-assistant-codex';
+ const message = '@Codex inspect this';
+ const userMessage = createMockMessage({
+ content: message,
+ id: TEST_IDS.USER_MESSAGE_ID,
+ role: 'user',
+ });
+ const sourceAssistant = createMockMessage({
+ agentId: targetAgentId,
+ content: '',
+ id: TEST_IDS.ASSISTANT_MESSAGE_ID,
+ role: 'assistant',
+ });
+
+ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({
+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
+ messages: [userMessage, sourceAssistant],
+ topicId: TEST_IDS.TOPIC_ID,
+ userMessageId: TEST_IDS.USER_MESSAGE_ID,
+ } as any);
+ const createTaskSpy = vi.spyOn(aiAgentService, 'createClientTaskThread').mockResolvedValue({
+ assistantMessageId: threadAssistantId,
+ messages: [userMessage, sourceAssistant],
+ startedAt: new Date().toISOString(),
+ success: true,
+ threadId,
+ threadMessages: [
+ createMockMessage({ id: 'thread-user-codex', role: 'user', threadId }),
+ createMockMessage({ id: threadAssistantId, role: 'assistant', threadId }),
+ ],
+ userMessageId: 'thread-user-codex',
+ } as any);
+ const updateTaskSpy = vi
+ .spyOn(aiAgentService, 'updateClientTaskThreadStatus')
+ .mockResolvedValue({
+ status: 'completed',
+ success: true,
+ threadId,
+ } as any);
+ executeHeterogeneousAgentMock.mockResolvedValue(undefined);
+
+ const { result } = renderHook(() => useChatStore());
+ const dispatchSpy = vi.spyOn(useChatStore.getState(), 'internal_dispatchMessage');
+ await act(async () => {
+ await result.current.sendMessage({
+ context: { ...createTestContext(), topicId: TEST_IDS.TOPIC_ID },
+ editorData: {
+ root: {
+ children: [
+ {
+ children: [
+ {
+ label: 'Codex',
+ metadata: { id: targetAgentId, type: 'agent' },
+ type: 'mention',
+ },
+ { text: ' inspect this', type: 'text' },
+ ],
+ type: 'paragraph',
+ },
+ ],
+ type: 'root',
+ },
+ } as any,
+ message,
+ });
+ });
+
+ expect(createTaskSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentId: targetAgentId,
+ assistantMessage: { provider: 'codex' },
+ parentMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
+ topicId: TEST_IDS.TOPIC_ID,
+ }),
+ );
+ expect(executeHeterogeneousAgentMock).toHaveBeenCalledWith(
+ expect.any(Function),
+ expect.objectContaining({
+ assistantMessageId: threadAssistantId,
+ context: expect.objectContaining({
+ agentId: targetAgentId,
+ scope: 'sub_agent',
+ subAgentId: targetAgentId,
+ threadId,
}),
- ]),
+ }),
+ );
+ expect(updateTaskSpy).toHaveBeenCalledWith(
+ expect.objectContaining({ completionReason: 'done', threadId }),
+ );
+ expect(dispatchSpy).toHaveBeenCalledWith(
+ {
+ id: TEST_IDS.ASSISTANT_MESSAGE_ID,
+ type: 'updateMessage',
+ value: { content: TEST_CONTENT.USER_MESSAGE },
+ },
+ {
+ context: expect.objectContaining({
+ agentId: TEST_IDS.SESSION_ID,
+ isNew: false,
+ topicId: TEST_IDS.TOPIC_ID,
+ }),
+ },
);
});
it('should route a single leading @agent through the gateway when gateway mode is enabled', async () => {
const { result } = renderHook(() => useChatStore());
const targetAgentId = 'agent-direct-target';
- const toolMessageId = 'tool-call-agent-result';
+ const toolMessageId = 'unused-tool-call-agent-result';
const message = '@Agent B hello';
const userMessage = createMockMessage({
@@ -2909,17 +3014,26 @@ describe('ConversationLifecycle actions', () => {
tools: [],
});
- // sendMessageInServer must still run: directMention deliberately uses the
- // client message-persistence path even under gateway mode (the supervisor
- // is a pure router and never executes an LLM turn on the gateway).
+ // A direct mention runs the target on the gateway, which owns persistence.
const sendMessageInServerSpy = vi
.spyOn(aiChatService, 'sendMessageInServer')
.mockResolvedValue({
messages: [userMessage, assistantMessage],
- topics: [],
+ topicId: TEST_IDS.TOPIC_ID,
assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
userMessageId: TEST_IDS.USER_MESSAGE_ID,
} as any);
+ vi.spyOn(aiAgentService, 'execSubAgentTask').mockResolvedValue({
+ assistantMessageId: 'thread-assistant',
+ operationId: 'op-gw-sub',
+ success: true,
+ threadId: 'thread-gateway',
+ });
+ vi.spyOn(aiAgentService, 'getSubAgentTaskStatus').mockResolvedValue({
+ result: 'Gateway result',
+ status: 'completed',
+ taskDetail: undefined,
+ } as any);
(messageService.updateMessage as any).mockImplementation(
async (_id: string, value: any) => {
@@ -2966,36 +3080,20 @@ describe('ConversationLifecycle actions', () => {
type: 'root',
},
} as any,
- context: createTestContext(),
+ context: { ...createTestContext(), topicId: TEST_IDS.TOPIC_ID },
});
});
- // Messages were persisted client-side (we did NOT take the supervisor
- // gateway early-return, which skips sendMessageInServer entirely).
expect(sendMessageInServerSpy).toHaveBeenCalled();
- // The callAgent tool call was still emitted on the supervisor message.
- expect(messageService.updateMessage).toHaveBeenCalledWith(
- TEST_IDS.ASSISTANT_MESSAGE_ID,
- expect.objectContaining({
- tools: [
- expect.objectContaining({
- apiName: 'callAgent',
- identifier: 'lobe-agent-management',
- }),
- ],
- }),
- expect.objectContaining({ agentId: TEST_IDS.SESSION_ID }),
- );
+ expect(messageService.createMessage).not.toHaveBeenCalled();
// The TARGET agent runs on the gateway, not the client.
expect(result.current.executeClientAgent).not.toHaveBeenCalled();
- expect(executeGatewayAgentSpy).toHaveBeenCalledWith(
+ expect(executeGatewayAgentSpy).not.toHaveBeenCalled();
+ expect(aiAgentService.execSubAgentTask).toHaveBeenCalledWith(
expect.objectContaining({
- context: expect.objectContaining({
- agentId: targetAgentId,
- scope: 'sub_agent',
- subAgentId: targetAgentId,
- }),
- message,
+ agentId: targetAgentId,
+ parentMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
+ topicId: TEST_IDS.TOPIC_ID,
}),
);
});
@@ -3118,8 +3216,8 @@ describe('ConversationLifecycle actions', () => {
});
});
- // Multi-mention keeps the supervisor on the gateway (unlike single-mention,
- // which falls through to the client path). The mentioned agents are
+ // Multi-mention keeps the supervisor on the gateway; single-mention runs
+ // the target directly. The mentioned agents are
// forwarded so the server enables callAgent + injects the delegation context.
expect(result.current.executeClientAgent).not.toHaveBeenCalled();
expect(executeGatewayAgentSpy).toHaveBeenCalledWith(
diff --git a/src/store/chat/slices/agentRun/actions/dispatch/directMentionExecutor.test.ts b/src/store/chat/slices/agentRun/actions/dispatch/directMentionExecutor.test.ts
new file mode 100644
index 00000000000..c772bf69500
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/dispatch/directMentionExecutor.test.ts
@@ -0,0 +1,22 @@
+import { AgentRuntimeErrorType, ChatErrorType } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { toDirectMentionMessageError } from './directMentionExecutor';
+
+describe('toDirectMentionMessageError', () => {
+ it('maps an offline execution device to the actionable device-gateway error', () => {
+ const error = toDirectMentionMessageError(
+ new Error('{"error":"DEVICE_OFFLINE","success":false}'),
+ );
+
+ expect(error).toEqual({ type: ChatErrorType.DeviceGatewayNotConfigured });
+ });
+
+ it('keeps unexpected failures on the generic agent-runtime error path', () => {
+ expect(toDirectMentionMessageError(new Error('gateway exploded'))).toEqual({
+ body: { message: 'gateway exploded' },
+ message: 'gateway exploded',
+ type: AgentRuntimeErrorType.AgentRuntimeError,
+ });
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/dispatch/directMentionExecutor.ts b/src/store/chat/slices/agentRun/actions/dispatch/directMentionExecutor.ts
new file mode 100644
index 00000000000..500edf6bbbb
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/dispatch/directMentionExecutor.ts
@@ -0,0 +1,160 @@
+import {
+ AgentRuntimeErrorType,
+ ChatErrorType,
+ type ChatMessageError,
+ type ConversationContext,
+} from '@lobechat/types';
+
+import { aiAgentService } from '@/services/aiAgent';
+import { ClientSubAgentTransport } from '@/store/chat/agents/transports/ClientSubAgentTransport';
+import type { ChatStore } from '@/store/chat/store';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+import { aggregateSubagentMetrics } from '@/utils/subagentMetrics';
+
+import type { AgentRuntimeType } from './agentDispatcher';
+
+interface DirectMentionExecutionParams {
+ context: ConversationContext;
+ instruction: string;
+ parentOperationId: string;
+ runtimeType: Extract<AgentRuntimeType, 'client' | 'gateway'>;
+ sourceMessageId: string;
+ targetAgentId: string;
+}
+
+const getErrorMessage = (error: unknown): string =>
+ error instanceof Error ? error.message : String(error);
+
+export const toDirectMentionMessageError = (error: unknown): ChatMessageError => {
+ const message = getErrorMessage(error);
+ const isDeviceOffline = message.includes('DEVICE_OFFLINE');
+
+ if (isDeviceOffline) {
+ return { type: ChatErrorType.DeviceGatewayNotConfigured };
+ }
+
+ return {
+ body: { message },
+ message,
+ type: AgentRuntimeErrorType.AgentRuntimeError,
+ };
+};
+
+/**
+ * Executes a direct @Agent route as an isolated task and projects its final
+ * answer onto the source assistant message in the parent conversation.
+ *
+ * The server owns durable Thread completion and projection. The client mirrors
+ * the result into the active store so the visible conversation updates without
+ * waiting for a refetch.
+ */
+export const executeDirectMention = async (
+ params: DirectMentionExecutionParams,
+ get: () => ChatStore,
+): Promise<void> => {
+ const { context, instruction, parentOperationId, runtimeType, sourceMessageId, targetAgentId } =
+ params;
+
+ if (!context.topicId) throw new Error('Direct mention requires a persisted topic');
+
+ const { operationId } = get().startOperation({
+ context: { ...context, messageId: sourceMessageId },
+ parentOperationId,
+ type: 'execClientSubAgent',
+ });
+ get().associateMessageWithOperation(sourceMessageId, operationId);
+
+ let clientThreadId: string | undefined;
+
+ try {
+ let resultContent = '';
+
+ if (runtimeType === 'gateway') {
+ const result = await new ClientSubAgentTransport(get, operationId).execSubAgent({
+ agentId: targetAgentId,
+ instruction,
+ parentMessageId: sourceMessageId,
+ parentOperationId: operationId,
+ title: instruction.slice(0, 50),
+ topicId: context.topicId,
+ });
+
+ if (!result.success) throw new Error(result.error || 'Mentioned agent execution failed');
+ resultContent = result.result || '';
+ } else {
+ const task = await aiAgentService.createClientTaskThread({
+ agentId: targetAgentId,
+ instruction,
+ parentMessageId: sourceMessageId,
+ title: instruction.slice(0, 50),
+ topicId: context.topicId,
+ });
+ clientThreadId = task.threadId;
+
+ const threadContext: ConversationContext = {
+ ...context,
+ agentId: targetAgentId,
+ scope: 'sub_agent',
+ subAgentId: targetAgentId,
+ threadId: task.threadId,
+ };
+ get().replaceMessages(task.threadMessages, { context: threadContext });
+ void get().refreshThreads();
+
+ const runtimeResult = await get().executeClientAgent({
+ context: threadContext,
+ inPortalThread: true,
+ isSubAgent: true,
+ messages: task.threadMessages,
+ parentMessageId: task.userMessageId,
+ parentMessageType: 'user',
+ parentOperationId: operationId,
+ });
+ const threadMessages = get().dbMessagesMap[messageMapKey(threadContext)] || [];
+ const metrics = aggregateSubagentMetrics(threadMessages);
+ resultContent =
+ threadMessages.findLast((message) => message.role === 'assistant')?.content || '';
+
+ await aiAgentService.updateClientTaskThreadStatus({
+ completionReason: 'done',
+ metadata: {
+ totalCost: runtimeResult?.cost?.total,
+ totalMessages: threadMessages.length,
+ totalTokens: metrics.totalTokens,
+ totalToolCalls: metrics.toolCalls,
+ },
+ resultContent,
+ threadId: task.threadId,
+ });
+ }
+
+ await get().optimisticUpdateMessageContent(sourceMessageId, resultContent, undefined, {
+ operationId,
+ });
+ void get().refreshThreads();
+ get().completeOperation(operationId);
+ } catch (error) {
+ if (clientThreadId) {
+ await aiAgentService
+ .updateClientTaskThreadStatus({
+ completionReason: 'error',
+ error: getErrorMessage(error),
+ threadId: clientThreadId,
+ })
+ .catch(console.error);
+ void get().refreshThreads();
+ }
+
+ await get()
+ .optimisticUpdateMessageError(sourceMessageId, toDirectMentionMessageError(error), {
+ operationId,
+ })
+ .catch(console.error);
+
+ get().failOperation(operationId, {
+ message: getErrorMessage(error),
+ type: 'DirectMentionExecutionError',
+ });
+ throw error;
+ }
+};
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
index 22717a28de2..e358b248b62 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
@@ -1,10 +1,5 @@
// Disable the auto sort key eslint rule to make the code more logic and readable
-import type { CallAgentParams, CallAgentState } from '@lobechat/builtin-tool-agent-management';
-import {
- AgentManagementApiName,
- AgentManagementIdentifier,
- createCallAgentManifest,
-} from '@lobechat/builtin-tool-agent-management';
+import { createCallAgentManifest } from '@lobechat/builtin-tool-agent-management';
import { isDesktop, isHeterogeneousAgentModelId, LOADING_FLAT } from '@lobechat/const';
import { formatSelectedSkillsContext, formatSelectedToolsContext } from '@lobechat/context-engine';
import { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';
@@ -12,7 +7,6 @@ import { chainCompressContext } from '@lobechat/prompts';
import type {
ChatImageItem,
ChatThreadType,
- ChatToolPayload,
ChatTopicMetadata,
ChatVideoItem,
ConversationContext,
@@ -39,13 +33,14 @@ import {
import { resolveExecutionTarget, resolveWorkspaceScoped } from '@/helpers/executionTarget';
import { globalAgentContextManager } from '@/helpers/GlobalAgentContextManager';
import { agentService } from '@/services/agent';
+import { aiAgentService } from '@/services/aiAgent';
import { aiChatService } from '@/services/aiChat';
import { chatService } from '@/services/chat';
import { resolveSelectedSkillsWithContent } from '@/services/chat/mecha/skillPreload';
import { resolveSelectedToolsWithContent } from '@/services/chat/mecha/toolPreload';
import { messageService } from '@/services/message';
import { topicService } from '@/services/topic';
-import { getAgentStoreState, useAgentStore } from '@/store/agent';
+import { getAgentStoreState } from '@/store/agent';
import {
agentByIdSelectors,
agentSelectors,
@@ -59,7 +54,7 @@ import {
topicSelectors,
} from '@/store/chat/selectors';
import { selectRuntimeType } from '@/store/chat/slices/agentRun/actions/dispatch/agentDispatcher';
-import { dispatchNonHeteroSubAgent } from '@/store/chat/slices/agentRun/actions/dispatch/nonHeteroSubAgentDispatcher';
+import { executeDirectMention } from '@/store/chat/slices/agentRun/actions/dispatch/directMentionExecutor';
import { buildRunLifecycle } from '@/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle';
import type { RunScope } from '@/store/chat/slices/agentRun/actions/lifecycle/types';
import { resolveHeteroResume } from '@/store/chat/slices/agentRun/actions/transports/hetero/heteroResume';
@@ -90,9 +85,10 @@ import { getUserStoreState } from '@/store/user';
import { userProfileSelectors } from '@/store/user/selectors';
import { useUserMemoryStore } from '@/store/userMemory';
import { markdownToTxt } from '@/utils/markdownToTxt';
+import { aggregateSubagentMetrics } from '@/utils/subagentMetrics';
import { materializeLocalSystemToolSnapshots } from '../transports/client/localSystemToolSnapshots';
-import type { CommandSendOverrides, SingleAgentMentionDirectRoute } from './commandBus';
+import type { CommandSendOverrides } from './commandBus';
import {
hasNonActionContent,
injectReferTopicNode,
@@ -274,7 +270,7 @@ export class ConversationLifecycleActionImpl {
let editorData = inputEditorData;
const { executeClientAgent, mainInputEditor } = this.#get();
const targetInputEditor = inputEditor ?? mainInputEditor;
- const { agentId } = context;
+ const ownerAgentId = context.agentId;
const selectedSkills = parseSelectedSkillsFromEditorData(editorData);
const selectedTools = parseSelectedToolsFromEditorData(editorData);
const mentionedAgents = parseMentionedAgentsFromEditorData(editorData);
@@ -296,13 +292,29 @@ export class ConversationLifecycleActionImpl {
}
: undefined;
- if (!agentId) {
+ if (!ownerAgentId) {
onPreflightFailure?.();
return;
}
- const agentState = getAgentStoreState();
- const agentConfig = agentSelectors.getAgentConfigById(agentId)(agentState);
+ // A single explicit @Agent is an execution route, not a supervisor turn.
+ // Keep the current conversation as the owner, but resolve runtime/config
+ // from the mentioned agent so Lobe AI is never invoked for this message.
+ const directMentionRoute = !context.groupId
+ ? parseSingleAgentMentionDirectRoute(editorData)
+ : undefined;
+ const agentId = directMentionRoute?.agent.id ?? ownerAgentId;
+
+ let agentState = getAgentStoreState();
+ let agentConfig = agentSelectors.getAgentConfigById(agentId)(agentState);
+ if (directMentionRoute && !agentConfig) {
+ const targetAgentConfig = await agentService.getAgentConfigById(agentId);
+ if (!targetAgentConfig) throw new Error(`Mentioned agent not found: ${agentId}`);
+
+ agentState.internal_dispatchAgentMap(agentId, targetAgentConfig);
+ agentState = getAgentStoreState();
+ agentConfig = agentSelectors.getAgentConfigById(agentId)(agentState);
+ }
const agent = agentByIdSelectors.getAgentById(agentId)(agentState);
const currentUserId = userProfileSelectors.userId(getUserStoreState());
const isAuthor = !!currentUserId && agent?.userId === currentUserId;
@@ -398,9 +410,6 @@ export class ConversationLifecycleActionImpl {
isGroupSupervisor = group?.supervisorAgentId === agentId;
}
// In non-group context, @agent mentions make the current agent act as supervisor
- const directMentionRoute = !context.groupId
- ? parseSingleAgentMentionDirectRoute(editorData)
- : undefined;
const hasMentionedAgents =
!context.groupId && !directMentionRoute && mentionedAgents.length > 0;
@@ -447,6 +456,7 @@ export class ConversationLifecycleActionImpl {
const operationContext = {
...context,
+ agentId: ownerAgentId,
...(isCreatingNewThread && { threadId: undefined }),
// Only set the supervisor markers for actual group supervisors — NOT for
// @agent mentions. These drive group-specific UI rendering (SupervisorMessage
@@ -686,7 +696,7 @@ export class ConversationLifecycleActionImpl {
{
content: LOADING_FLAT,
role: 'assistant',
- agentId: operationContext.agentId,
+ agentId,
// if there is topicId, then add topicId to message
topicId: operationContext.topicId ?? undefined,
threadId: operationContext.threadId ?? undefined,
@@ -996,6 +1006,7 @@ export class ConversationLifecycleActionImpl {
// provider up front; the adapter backfills the actual model later
// if the CLI reports it.
newAssistantMessage: {
+ agentId: directMentionRoute ? agentId : undefined,
id: tempAssistantId,
provider: heterogeneousProvider.type,
},
@@ -1112,6 +1123,38 @@ export class ConversationLifecycleActionImpl {
});
}
+ let directMentionThreadId: string | undefined;
+ let heteroExecutionAssistantId = heteroData.assistantMessageId;
+ let heteroExecutionContext = heteroContext;
+
+ if (directMentionRoute) {
+ if (!heteroTopicId) throw new Error('Direct mention requires a persisted topic');
+
+ const task = await aiAgentService.createClientTaskThread({
+ agentId,
+ assistantMessage: { provider: heterogeneousProvider.type },
+ instruction: message,
+ parentMessageId: heteroData.assistantMessageId,
+ title: message.slice(0, 50),
+ topicId: heteroTopicId,
+ });
+ if (!task.assistantMessageId) {
+ throw new Error('Direct mention thread is missing an assistant placeholder');
+ }
+
+ directMentionThreadId = task.threadId;
+ heteroExecutionAssistantId = task.assistantMessageId;
+ heteroExecutionContext = {
+ ...heteroContext,
+ agentId,
+ scope: 'sub_agent',
+ subAgentId: agentId,
+ threadId: task.threadId,
+ };
+ this.#get().replaceMessages(task.threadMessages, { context: heteroExecutionContext });
+ void this.#get().refreshThreads();
+ }
+
// No temp-message cleanup: the optimistic rows were created under the very
// ids the server just persisted, so `replaceMessages` above already
// reconciled them in place. Deleting them here would delete the real ones.
@@ -1149,7 +1192,7 @@ export class ConversationLifecycleActionImpl {
// Start heterogeneous agent execution
const { operationId: heteroOpId } = this.#get().startOperation({
- context: heteroContext,
+ context: heteroExecutionContext,
label: 'Heterogeneous Agent Execution',
metadata: { heterogeneousType: heterogeneousProvider.type },
parentOperationId: operationId,
@@ -1157,6 +1200,7 @@ export class ConversationLifecycleActionImpl {
});
this.#get().associateMessageWithOperation(heteroData.assistantMessageId, heteroOpId);
+ this.#get().associateMessageWithOperation(heteroExecutionAssistantId, heteroOpId);
try {
const { executeHeterogeneousAgent } =
@@ -1194,8 +1238,8 @@ export class ConversationLifecycleActionImpl {
}
await executeHeterogeneousAgent(() => this.#get(), {
- assistantMessageId: heteroData.assistantMessageId,
- context: heteroContext,
+ assistantMessageId: heteroExecutionAssistantId,
+ context: heteroExecutionContext,
contextSelections: effectiveContextSelections,
heterogeneousProvider,
imageList: persistedImageList?.length ? persistedImageList : undefined,
@@ -1206,6 +1250,37 @@ export class ConversationLifecycleActionImpl {
workingDirectory,
workingDirectoryConfig,
});
+
+ if (directMentionThreadId) {
+ const threadMessages =
+ this.#get().dbMessagesMap[messageMapKey(heteroExecutionContext)] || [];
+ const metrics = aggregateSubagentMetrics(threadMessages);
+ const resultContent =
+ threadMessages.findLast((item) => item.role === 'assistant')?.content || '';
+ await aiAgentService.updateClientTaskThreadStatus({
+ completionReason: 'done',
+ metadata: {
+ totalMessages: threadMessages.length,
+ totalTokens: metrics.totalTokens,
+ totalToolCalls: metrics.toolCalls,
+ },
+ resultContent,
+ threadId: directMentionThreadId,
+ });
+ // updateClientTaskThreadStatus owns the durable source-message
+ // projection. Mirror that result into the persisted Topic bucket
+ // without issuing a second write whose returned message list can race
+ // and restore the original loading placeholder.
+ this.#get().internal_dispatchMessage(
+ {
+ id: heteroData.assistantMessageId,
+ type: 'updateMessage',
+ value: { content: resultContent },
+ },
+ { context: heteroContext },
+ );
+ void this.#get().refreshThreads();
+ }
} catch (e) {
console.error('[HeterogeneousAgent] Execution failed:', e);
this.#get().failOperation(heteroOpId, {
@@ -1221,14 +1296,6 @@ export class ConversationLifecycleActionImpl {
}
// ── Gateway mode: skip sendMessageInServer, let execAgentTask handle everything ──
- // A single-agent @mention (`directMentionRoute`) is the exception: the current
- // agent acts as a pure deterministic router and never runs an LLM turn itself, so
- // there is nothing to execute on the gateway. We let it fall through to the client
- // message-persistence path below, where `#executeDirectMentionRoute` emits the
- // callAgent tool call and dispatches the *target* agent via
- // `dispatchNonHeteroSubAgent` — which re-selects the runtime and runs the target on
- // the gateway when gateway mode is enabled. Routing the supervisor through the
- // gateway here would drop the mention entirely (execAgentTask carries no mention data).
if (runtimeType === 'gateway' && !directMentionRoute) {
try {
// Pass `sendMessage` as `parentOperationId` so executeGatewayAgent
@@ -1268,8 +1335,8 @@ export class ConversationLifecycleActionImpl {
// them (multi-mention). Mirrors the client runtime's `initialContext`
// injection: the server enables the callAgent tool and injects the
// mentioned-agents delegation context so the supervisor calls them.
- // Omit when empty (single-mention takes the client path above and never
- // reaches here). Non-group only — group @member mentions are handled by
+ // Omit when empty (single-mention executes the target directly and does
+ // not need supervisor delegation context). Non-group only — group @member mentions are handled by
// the group orchestration path, not agent-management delegation.
mentionedAgents: hasMentionedAgents ? mentionedAgents : undefined,
// Pass temp message IDs so the UI doesn't show a blank loading
@@ -1409,6 +1476,7 @@ export class ConversationLifecycleActionImpl {
// Pass groupId for group chat scenarios
groupId: operationContext.groupId ?? undefined,
newAssistantMessage: {
+ agentId: directMentionRoute ? agentId : undefined,
id: tempAssistantId,
// Pass isSupervisor metadata for group orchestration
metadata: operationContext.isSupervisor
@@ -1665,14 +1733,17 @@ export class ConversationLifecycleActionImpl {
{
try {
if (directMentionRoute) {
- await this.#executeDirectMentionRoute({
- assistantMessageId: data.assistantMessageId,
- context: execContext,
- directMentionRoute,
- inPortalThread: !!data.createdThreadId,
- instruction: message,
- parentOperationId: operationId,
- });
+ await executeDirectMention(
+ {
+ context: execContext,
+ instruction: message,
+ parentOperationId: operationId,
+ runtimeType: runtimeType === 'gateway' ? 'gateway' : 'client',
+ sourceMessageId: data.assistantMessageId,
+ targetAgentId: agentId,
+ },
+ this.#get,
+ );
} else {
const displayMessages = displayMessageSelectors.getDisplayMessagesByKey(
messageMapKey(execContext),
@@ -1741,169 +1812,6 @@ export class ConversationLifecycleActionImpl {
};
};
- async #executeDirectMentionRoute({
- assistantMessageId,
- context,
- inPortalThread,
- directMentionRoute,
- instruction,
- parentOperationId,
- }: {
- assistantMessageId: string;
- context: ConversationContext;
- inPortalThread?: boolean;
- directMentionRoute: SingleAgentMentionDirectRoute;
- instruction: string;
- parentOperationId: string;
- }): Promise<void> {
- const targetAgentId = directMentionRoute.agent.id;
- const callAgentParams: CallAgentParams = {
- agentId: targetAgentId,
- instruction,
- };
- const toolPayload: ChatToolPayload = {
- apiName: AgentManagementApiName.callAgent,
- arguments: JSON.stringify(callAgentParams),
- id: `call_agent_${nanoid()}`,
- identifier: AgentManagementIdentifier,
- source: 'builtin',
- type: 'builtin',
- };
- const callAgentState: CallAgentState = {
- agentId: targetAgentId,
- instruction,
- mode: 'speak',
- };
- const toolResultContent = `Called agent "${targetAgentId}" to respond.`;
-
- const { operationId } = this.#get().startOperation({
- context: { ...context, messageId: assistantMessageId },
- label: 'Direct Agent Mention',
- metadata: {
- apiName: AgentManagementApiName.callAgent,
- targetAgentId,
- tool_call_id: toolPayload.id,
- },
- parentOperationId,
- type: 'toolCalling',
- });
-
- try {
- this.#get().internal_dispatchMessage(
- {
- id: assistantMessageId,
- type: 'updateMessage',
- value: { content: '' },
- },
- { operationId },
- );
- await this.#get().optimisticUpdateMessageContent(
- assistantMessageId,
- '',
- { tools: [toolPayload] },
- { operationId },
- );
-
- const toolMessage = await this.#get().optimisticCreateMessage(
- {
- agentId: context.agentId!,
- content: toolResultContent,
- groupId: context.groupId,
- parentId: assistantMessageId,
- plugin: toolPayload,
- pluginState: callAgentState,
- role: 'tool',
- threadId: context.threadId,
- tool_call_id: toolPayload.id,
- topicId: context.topicId ?? undefined,
- },
- { operationId },
- );
-
- if (!toolMessage) {
- throw new Error(
- `[directMentionRoute] Failed to create callAgent tool message for agentId: ${targetAgentId}`,
- );
- }
-
- const preloadError = await this.#preloadDirectMentionAgentConfig(targetAgentId);
- if (preloadError) {
- await this.#get().optimisticUpdateMessageContent(toolMessage.id, preloadError, undefined, {
- operationId,
- });
- this.#get().completeOperation(operationId);
- return;
- }
-
- const currentMessages = dbMessageSelectors.getDbMessagesByKey(messageMapKey(context))(
- this.#get(),
- );
- const trimmedInstruction = instruction.trim();
- const now = Date.now();
- const messagesWithInstruction = trimmedInstruction
- ? [
- ...currentMessages,
- {
- content: `<speaker name="Supervisor" />\n${instruction}`,
- createdAt: now,
- id: `virtual_speak_instruction_${now}`,
- role: 'user' as const,
- updatedAt: now,
- },
- ]
- : currentMessages;
-
- // Sub-agent dispatch inherits the parent's runtime selection — a
- // gateway/hetero parent must keep its sub-agents on the same path.
- // Runtime routing is fully delegated to dispatchNonHeteroSubAgent ().
- const parentAgentConfig = context.agentId
- ? agentSelectors.getAgentConfigById(context.agentId)(getAgentStoreState())
- : undefined;
-
- await dispatchNonHeteroSubAgent(
- { kind: 'mention', targetAgentId, instruction, parentMessageId: toolMessage.id },
- {
- conversationContext: context,
- boundDeviceId: parentAgentConfig?.agencyConfig?.boundDeviceId,
- heterogeneousProvider: parentAgentConfig?.agencyConfig?.heterogeneousProvider,
- inPortalThread,
- isGatewayMode: this.#get().isGatewayModeEnabled(context.agentId),
- isWorkspaceAgent: context.agentId
- ? agentByIdSelectors.isWorkspaceAgentById(context.agentId)(getAgentStoreState())
- : false,
- messages: messagesWithInstruction,
- parentOperationId: operationId,
- },
- this.#get(),
- );
-
- this.#get().completeOperation(operationId);
- } catch (error) {
- this.#get().failOperation(operationId, {
- type: 'DirectMentionRouteError',
- message: error instanceof Error ? error.message : String(error),
- });
- throw error;
- }
- }
-
- async #preloadDirectMentionAgentConfig(agentId: string): Promise<string | undefined> {
- const targetAgentExists = useAgentStore.getState().agentMap[agentId];
- if (targetAgentExists) return;
-
- try {
- const config = await agentService.getAgentConfigById(agentId);
- if (!config) {
- return `Agent "${agentId}" not found in your workspace. Please check the agent ID and try again.`;
- }
-
- useAgentStore.getState().internal_dispatchAgentMap(agentId, config);
- } catch (error) {
- console.error('[directMentionRoute] Failed to load agent config:', error);
- return `Failed to load agent "${agentId}": ${(error as Error).message}`;
- }
- }
-
/**
* Execute context compression for /compact command.
* Reuses the same service methods as the agent runtime's compress_context executor.
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
index 7d65c982a19..71f7e491439 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -572,6 +572,9 @@ export class GatewayActionImpl {
clientIds,
appContext: {
agentDocumentId: executionContext.agentDocumentId,
+ ...(messageContext.agentId !== executionContext.agentId && {
+ conversationAgentId: messageContext.agentId,
+ }),
defaultTaskAssigneeAgentId: executionContext.defaultTaskAssigneeAgentId,
documentId: executionContext.documentId,
// When AgentBuilder runs, context.agentId is the builtin builder agent.
diff --git a/src/store/chat/slices/message/actions/internals.ts b/src/store/chat/slices/message/actions/internals.ts
index 753e12f9307..89d908722d6 100644
--- a/src/store/chat/slices/message/actions/internals.ts
+++ b/src/store/chat/slices/message/actions/internals.ts
@@ -35,7 +35,7 @@ export class MessageInternalsActionImpl {
internal_dispatchMessage = (
payload: MessageDispatch,
- context?: { operationId?: string },
+ context?: Parameters<ChatStore['internal_getConversationContext']>[0],
): void => {
// Get full conversation context (including scope) from operation or global state
const ctx = this.#get().internal_getConversationContext(context);
diff --git a/src/store/chat/slices/message/actions/optimisticUpdate.ts b/src/store/chat/slices/message/actions/optimisticUpdate.ts
index de7683d9878..8eda146af8e 100644
--- a/src/store/chat/slices/message/actions/optimisticUpdate.ts
+++ b/src/store/chat/slices/message/actions/optimisticUpdate.ts
@@ -16,6 +16,7 @@ import { nanoid } from '@lobechat/utils';
import { messageService } from '@/services/message';
import { type ChatStore } from '@/store/chat/store';
+import type { MessageMapKeyInput } from '@/store/chat/utils/messageMapKey';
import { type StoreSetter } from '@/store/types';
import { dbMessageSelectors } from '../selectors';
@@ -24,6 +25,8 @@ import { dbMessageSelectors } from '../selectors';
* Context for optimistic updates to specify session/topic isolation
*/
export interface OptimisticUpdateContext {
+ /** Explicit message bucket for writes that cross operation scopes. */
+ context?: MessageMapKeyInput;
operationId?: string;
/** Pre-generated temp message ID (used when ID needs to be known before creation) */
tempMessageId?: string;
diff --git a/src/store/chat/slices/message/actions/query.ts b/src/store/chat/slices/message/actions/query.ts
index 15d3ab40063..6a4a1a2ea92 100644
--- a/src/store/chat/slices/message/actions/query.ts
+++ b/src/store/chat/slices/message/actions/query.ts
@@ -164,7 +164,7 @@ export class MessageQueryActionImpl {
}
// Priority 2: Get full context from operation if operationId is provided (deprecated)
else if (params?.operationId) {
- ctx = this.#get().internal_getConversationContext(params);
+ ctx = this.#get().internal_getConversationContext({ operationId: params.operationId });
}
// Priority 3: Fallback to global state
else {
diff --git a/src/store/chat/slices/operation/__tests__/actions.test.ts b/src/store/chat/slices/operation/__tests__/actions.test.ts
index 62a9f44e232..c6aa9cae6f8 100644
--- a/src/store/chat/slices/operation/__tests__/actions.test.ts
+++ b/src/store/chat/slices/operation/__tests__/actions.test.ts
@@ -258,8 +258,6 @@ describe('Operation Actions', () => {
}).operationId;
});
- const startTime = result.current.operations[operationId!].metadata.startTime;
-
act(() => {
result.current.completeOperation(operationId!);
});
@@ -1053,7 +1051,7 @@ describe('Operation Actions', () => {
const { result } = renderHook(() => useChatStore());
let operationId: string;
- const asyncHandler = vi.fn(async ({ type }) => {
+ const asyncHandler = vi.fn(async () => {
// Simulate async cleanup
await new Promise((resolve) => setTimeout(resolve, 10));
// Don't return anything (void)
@@ -1142,6 +1140,36 @@ describe('Operation Actions', () => {
});
describe('internal_getConversationContext', () => {
+ it('should prefer an explicit message context over the operation context', () => {
+ const { result } = renderHook(() => useChatStore());
+ const { operationId } = result.current.startOperation({
+ context: {
+ agentId: 'operation-agent',
+ isNew: true,
+ scope: 'main',
+ topicId: 'operation-topic',
+ },
+ type: 'execAgentRuntime',
+ });
+
+ const context = result.current.internal_getConversationContext({
+ context: {
+ agentId: 'projection-agent',
+ isNew: false,
+ scope: 'main',
+ topicId: 'persisted-topic',
+ },
+ operationId,
+ });
+
+ expect(context).toEqual({
+ agentId: 'projection-agent',
+ isNew: false,
+ scope: 'main',
+ topicId: 'persisted-topic',
+ });
+ });
+
it('should return context from operationId when provided', () => {
const { result } = renderHook(() => useChatStore());
diff --git a/src/store/chat/slices/operation/actions.ts b/src/store/chat/slices/operation/actions.ts
index 013ed6b5a3d..71f8e03b61a 100644
--- a/src/store/chat/slices/operation/actions.ts
+++ b/src/store/chat/slices/operation/actions.ts
@@ -47,9 +47,14 @@ export class OperationActionsImpl {
this.#get = get;
}
- internal_getConversationContext = (context?: { operationId?: string }): MessageMapKeyInput => {
- if (context?.operationId) {
- const operation = this.#get().operations[context.operationId];
+ internal_getConversationContext = (reference?: {
+ context?: MessageMapKeyInput;
+ operationId?: string;
+ }): MessageMapKeyInput => {
+ if (reference?.context) return reference.context;
+
+ if (reference?.operationId) {
+ const operation = this.#get().operations[reference.operationId];
if (!operation) {
// The op was already cleaned up (e.g. completed CC turn whose
// runtime_end fired and was GC'd 30s later), but a late caller
@@ -59,17 +64,17 @@ export class OperationActionsImpl {
// degrade to the global-state fallback and log loudly.
log(
'[internal_getConversationContext] WARNING: Operation not found, falling back to global state: %s',
- context.operationId,
+ reference.operationId,
);
console.warn(
'[internal_getConversationContext] operation not found, using global state:',
- context.operationId,
+ reference.operationId,
);
} else {
const { agentId, topicId, threadId, scope, groupId, documentId } = operation.context;
log(
'[internal_getConversationContext] get from operation %s: agentId=%s, topicId=%s, threadId=%s, scope=%s, groupId=%s, documentId=%s',
- context.operationId,
+ reference.operationId,
agentId,
topicId,
threadId,
diff --git a/src/store/chat/slices/thread/selectors/index.test.ts b/src/store/chat/slices/thread/selectors/index.test.ts
new file mode 100644
index 00000000000..9c14976edcd
--- /dev/null
+++ b/src/store/chat/slices/thread/selectors/index.test.ts
@@ -0,0 +1,119 @@
+import { ThreadStatus, ThreadType } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import type { ChatStoreState } from '@/store/chat';
+
+import { threadSelectors } from '.';
+
+describe('threadSelectors', () => {
+ it('returns only an isolation thread for an execution source message', () => {
+ const state = {
+ activeTopicId: 'topic-1',
+ threadMaps: {
+ 'topic-1': [
+ {
+ createdAt: new Date(),
+ id: 'continuation-thread',
+ lastActiveAt: new Date(),
+ sourceMessageId: 'message-1',
+ status: ThreadStatus.Active,
+ title: 'Discussion',
+ topicId: 'topic-1',
+ type: ThreadType.Continuation,
+ updatedAt: new Date(),
+ userId: 'user-1',
+ },
+ {
+ createdAt: new Date(),
+ id: 'isolation-thread',
+ lastActiveAt: new Date(),
+ sourceMessageId: 'message-1',
+ status: ThreadStatus.Completed,
+ title: 'Execution',
+ topicId: 'topic-1',
+ type: ThreadType.Isolation,
+ updatedAt: new Date(),
+ userId: 'user-1',
+ },
+ ],
+ },
+ } as unknown as ChatStoreState;
+
+ expect(threadSelectors.getIsolationThreadBySourceMsgId('message-1')(state)?.id).toBe(
+ 'isolation-thread',
+ );
+ });
+
+ it('does not treat a continuation thread as execution details', () => {
+ const state = {
+ activeTopicId: 'topic-1',
+ threadMaps: {
+ 'topic-1': [
+ {
+ createdAt: new Date(),
+ id: 'continuation-thread',
+ lastActiveAt: new Date(),
+ sourceMessageId: 'message-1',
+ status: ThreadStatus.Active,
+ title: 'Discussion',
+ topicId: 'topic-1',
+ type: ThreadType.Continuation,
+ updatedAt: new Date(),
+ userId: 'user-1',
+ },
+ ],
+ },
+ } as unknown as ChatStoreState;
+
+ expect(threadSelectors.getIsolationThreadBySourceMsgId('message-1')(state)).toBeUndefined();
+ });
+
+ it('keeps direct-mention isolation threads conversational', () => {
+ const state = {
+ activeThreadId: 'direct-thread',
+ activeTopicId: 'topic-1',
+ threadMaps: {
+ 'topic-1': [
+ {
+ createdAt: new Date(),
+ id: 'direct-thread',
+ lastActiveAt: new Date(),
+ status: ThreadStatus.Completed,
+ title: 'Direct Agent run',
+ topicId: 'topic-1',
+ type: ThreadType.Isolation,
+ updatedAt: new Date(),
+ userId: 'user-1',
+ },
+ ],
+ },
+ } as unknown as ChatStoreState;
+
+ expect(threadSelectors.isActiveThreadSubagent(state)).toBe(false);
+ });
+
+ it('keeps tool-spawned isolation threads read-only', () => {
+ const state = {
+ activeThreadId: 'spawned-thread',
+ activeTopicId: 'topic-1',
+ threadMaps: {
+ 'topic-1': [
+ {
+ createdAt: new Date(),
+ id: 'spawned-thread',
+ lastActiveAt: new Date(),
+ metadata: { sourceToolCallId: 'tool-call-1' },
+ status: ThreadStatus.Completed,
+ title: 'Spawned subagent',
+ topicId: 'topic-1',
+ type: ThreadType.Isolation,
+ updatedAt: new Date(),
+ userId: 'user-1',
+ },
+ ],
+ },
+ } as unknown as ChatStoreState;
+
+ expect(threadSelectors.isActiveThreadSubagent(state)).toBe(true);
+ });
+});
diff --git a/src/store/chat/slices/thread/selectors/index.ts b/src/store/chat/slices/thread/selectors/index.ts
index 4f9f7c565d6..e27ed930782 100644
--- a/src/store/chat/slices/thread/selectors/index.ts
+++ b/src/store/chat/slices/thread/selectors/index.ts
@@ -34,9 +34,10 @@ const currentActiveThread = (s: ChatStoreState): ThreadItem | undefined => {
const isActiveThreadSubagent = (s: ChatStoreState): boolean => {
const thread = currentActiveThread(s);
- // Isolation threads (CC subagents + lobe-agent sub-agents) are driven by the
- // parent agent, so the thread view is read-only regardless of origin.
- return thread?.type === ThreadType.Isolation;
+ // Only tool-spawned subagent threads are externally owned and read-only.
+ // Direct @Agent isolation threads are ordinary target-Agent conversations
+ // after the delegated run completes, so users can continue chatting there.
+ return !!thread?.metadata?.sourceToolCallId;
};
const getThreadsByTopic = (topicId?: string) => (s: ChatStoreState) => {
@@ -51,6 +52,14 @@ const getThreadsBySourceMsgId = (id: string) => (s: ChatStoreState) => {
return threads.filter((t) => t.sourceMessageId === id);
};
+const getIsolationThreadBySourceMsgId = (id: string) => (s: ChatStoreState) => {
+ const threads = currentTopicThreads(s);
+
+ return threads.find(
+ (thread) => thread.sourceMessageId === id && thread.type === ThreadType.Isolation,
+ );
+};
+
const hasThreadBySourceMsgId = (id: string) => (s: ChatStoreState) => {
const threads = currentTopicThreads(s);
@@ -167,6 +176,7 @@ export const threadSelectors = {
currentTopicThreads,
getThreadChildMessages,
getThreadDbMessages,
+ getIsolationThreadBySourceMsgId,
getThreadsBySourceMsgId,
getThreadsByTopic,
hasThreadBySourceMsgId,