🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat: let agents continue earlier sub-agents on preserved history (#19763)
YuTengjing0c6ad7a9250c
diff --git a/.agents/skills/builtin-tool/SKILL.md b/.agents/skills/builtin-tool/SKILL.mdindex b9d2180d992..b06fe315460 100644--- a/.agents/skills/builtin-tool/SKILL.md+++ b/.agents/skills/builtin-tool/SKILL.md@@ -51,6 +51,7 @@ A builtin tool is a package the agent runtime can call. It ships **five faces**:5. **UI defaults to "do nothing".** Inspector is required (the header strip). Render/Placeholder/Streaming/Intervention/Portal are added **only when there's something specific to show** — empty registries are fine.6. **Style with `createStaticStyles + cssVar.*`** (zero-runtime). Fall back to `createStyles + token` only when you genuinely need runtime values. Use `@lobehub/ui` components, not raw antd.7. **i18n keys live in `packages/locales/src/default/plugin.ts`.** Inspector titles must come from `t('builtins.<identifier>.apiName.<api>')` so something renders while args stream.+8. **A failed long-running call should be continuable, not just inspectable.** Example: when `callSubAgent` stops halfway, the user says "keep going". So the fix was an optional `subAgentId` on `callSubAgent` that appends a new instruction to the same sub-agent thread — not a new "look up that run" API the model has to remember to call before retrying from scratch. Add a new API only when a user would ask for it on its own.---diff --git a/AGENTS.md b/AGENTS.mdindex 4795c5181f4..4633de259f3 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -87,6 +87,7 @@ Use the `acceptance` skill to decide whether the delivery needs product verifica- Documentation/instruction-only changes, pure refactors or tooling changes with no product behavior change, and gitlink-only syncs do not require a new acceptance run. State the reason in the PR; for a gitlink sync, link the upstream change and its existing acceptance when available.- Reuse a completed acceptance that covers the delivered behavior. If its report and evidence exist only locally, inspect and upload them with `lh acceptance run ingest`; if already published, reuse the link. Do not rerun the product merely to open a PR or obtain a report URL.- For new or changed product behavior not covered by valid evidence, verify the affected outcomes on the real product, capture the required evidence, and publish the result. The skill owns reuse criteria and the execution workflow.+- Agent tool results shown in chat are Web UI outcomes even when the implementation is server-side. Verify the rendered tool card and parent reply, including the failure state when recovery is the goal.When acceptance is required, put its published `https://app.lobehub.com/acceptance/<id>` link in the PR body. Tests, lint, and type-check remain separate quality gates; they do not replace product acceptance.diff --git a/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentModel.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentModel.test.tsindex bccc879ae34..9c297e191e7 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentModel.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentModel.test.ts@@ -83,6 +83,52 @@ describe('buildServerVirtualSubAgentRunner sub-agent model resolution', () => {// Fail-close regression for share-visitor runs: the child run spawned by// either runner does not inherit the parent's shareGate, so for a run with// `ctx.agentShareVisitor` set, no runner may be built at all.+describe('buildServerVirtualSubAgentRunner continuing an earlier sub-agent', () => {+ it('reuses the sub-agent thread and links the new placeholder to it', async () => {+ const execVirtualSubAgent = vi+ .fn()+ .mockResolvedValue({ operationId: 'child-op-2', success: true, threadId: 'thread-1' });+ const create = vi.fn().mockResolvedValue({ id: 'placeholder-2' });+ const runner = buildServerVirtualSubAgentRunner(+ {+ execVirtualSubAgent,+ messageModel: { create },+ operationId: 'parent-op',+ topicId: 'topic-1',+ } as unknown as RuntimeExecutorContext,+ {+ operationId: 'parent-op',+ origin: { agentId: 'agent-1', topicId: 'topic-1' },+ } as AgentState,+ { id: 'tool-call-2' } as ChatToolPayload,+ 'parent-message-2',+ );++ const result = await runner!.run({+ description: 'Hand over',+ instruction: 'Summarize your findings',+ subAgentId: 'thread-1',+ });++ expect(create).toHaveBeenCalledWith(+ expect.objectContaining({ pluginState: { status: 'pending', threadId: 'thread-1' } }),+ );+ expect(execVirtualSubAgent).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: 'agent-1',+ parentMessageId: 'placeholder-2',+ parentOperationId: 'parent-op',+ threadId: 'thread-1',+ }),+ );+ expect(result).toMatchObject({+ started: true,+ threadId: 'thread-1',+ toolMessageId: 'placeholder-2',+ });+ });+});+describe('runner builders fail closed for share-visitor runs', () => {const shareCtx = {agentShareVisitor: {diff --git a/apps/server/src/modules/AgentRuntime/executorHelpers.ts b/apps/server/src/modules/AgentRuntime/executorHelpers.tsindex 2016062b05e..f3b3be4369a 100644--- a/apps/server/src/modules/AgentRuntime/executorHelpers.ts+++ b/apps/server/src/modules/AgentRuntime/executorHelpers.ts@@ -248,7 +248,7 @@ export const buildServerVirtualSubAgentRunner = (const parentDeviceId = resolveRunActiveDeviceId(state);return {- run: async ({ agentId: targetAgentId, description, instruction, timeout }) => {+ run: async ({ agentId: targetAgentId, description, instruction, subAgentId, timeout }) => {// This runner serves two tools, and only one of them may swap the model:// - `callSubAgent` names no agent, so the child is an anonymous clone of// the parent — it takes the parent's `agencyConfig.subagent` override,@@ -277,7 +277,11 @@ export const buildServerVirtualSubAgentRunner = (groupId: state.origin?.groupId ?? undefined,parentId: parentMessageId,plugin: chatToolPayload as any,- pluginState: { status: 'pending' },+ // A continued sub-agent already has its thread, so the card can link to+ // it while the new turn is still running.+ pluginState: subAgentId+ ? { status: 'pending', threadId: subAgentId }+ : { status: 'pending' },role: 'tool',threadId: state.origin?.threadId,tool_call_id: chatToolPayload.id,@@ -298,6 +302,7 @@ export const buildServerVirtualSubAgentRunner = (parentMessageId: placeholder.id,parentOperationId: ctx.operationId,provider: subAgentModel?.provider,+ threadId: subAgentId,timeout,title: description,topicId,diff --git a/apps/server/src/routers/lambda/__tests__/integration/aiAgent/serverSubAgent.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/aiAgent/serverSubAgent.integration.test.tsindex ecb02129d9a..772e0b8973b 100644--- a/apps/server/src/routers/lambda/__tests__/integration/aiAgent/serverSubAgent.integration.test.ts+++ b/apps/server/src/routers/lambda/__tests__/integration/aiAgent/serverSubAgent.integration.test.ts@@ -11,6 +11,7 @@* sub-agent's answer and resumes the parent.* 5. The parent op runs one more LLM step and reaches `done`.*/+import { stripSubAgentReference } from '@lobechat/builtin-tool-lobe-agent';import { type LobeChatDatabase } from '@lobechat/database';import { agentOperations, agents, messages } from '@lobechat/database/schemas';import { getTestDB } from '@lobechat/database/test-utils';@@ -247,11 +248,14 @@ describe('Server callSubAgent suspend/resume', () => {.where(eq(agentOperations.parentOperationId, createResult.operationId));expect(childOps.length).toBeGreaterThanOrEqual(1);- // The placeholder tool message was backfilled with the sub-agent's answer+ // The placeholder tool message was backfilled with the sub-agent's answer,+ // followed by the hidden reference the parent uses to continue that sub-agentconst allMessages = await serverDB.select().from(messages).where(eq(messages.userId, userId));const subAgentToolMessage = allMessages.find(- (m) => m.role === 'tool' && m.content === SUB_AGENT_ANSWER,+ (m) =>+ m.role === 'tool' && !!m.content && stripSubAgentReference(m.content) === SUB_AGENT_ANSWER,);expect(subAgentToolMessage).toBeDefined();+ expect(subAgentToolMessage!.content).toMatch(/<sub_agent id="[^"]+" \/>$/);});});diff --git a/apps/server/src/services/agentRuntime/AbandonOperationService.ts b/apps/server/src/services/agentRuntime/AbandonOperationService.tsindex f460cd3c1b1..704574c6032 100644--- a/apps/server/src/services/agentRuntime/AbandonOperationService.ts+++ b/apps/server/src/services/agentRuntime/AbandonOperationService.ts@@ -44,7 +44,7 @@ export interface AbandonedSubAgentResume {*/streamOwnerUserId?: string;threadId: string;- /** The parent's placeholder `role: 'tool'` message to backfill (= thread.sourceMessageId). */+ /** The parent's placeholder `role: 'tool'` message this run reports to. */toolMessageId: string;userId: string;workspaceId?: string;@@ -207,8 +207,11 @@ export class AbandonOperationService {// otherwise wait on this slot forever. We surface the ids the caller needs// to backfill the placeholder tool message and CAS-resume the parent.// parentOperationId + threadId live on the (persistent) operation row;- // toolMessageId is the thread's sourceMessageId (the parent's placeholder),- // set when the sub-agent was dispatched. When this is set, the coordinator+ // toolMessageId is this run's own placeholder (`lineage.progressAnchor`),+ // falling back to the thread's sourceMessageId. The fallback alone is not+ // enough: a continued sub-agent (`callSubAgent({ subAgentId })`) reuses its+ // thread, whose sourceMessageId is the FIRST run's placeholder, while the+ // parent now waits on a new one. When this is set, the coordinator// cleanup below is SKIPPED so the durable resume can still resolve userId.//// Isolated group members ALSO run with `isSubAgent: true` and an isolation@@ -231,10 +234,15 @@ export class AbandonOperationService {const parentOperationId = opRow?.parentOperationId ?? undefined;const threadId = opRow?.threadId ?? origin.threadId ?? undefined;if (parentOperationId && threadId) {- const thread = await new ThreadModel(this.db, origin.userId, origin.workspaceId).findById(- threadId,- );- const toolMessageId = thread?.sourceMessageId ?? undefined;+ const anchoredToolMessageId =+ origin.lineage?.progressAnchor?.parentOperationId === parentOperationId+ ? origin.lineage.progressAnchor.toolMessageId+ : undefined;+ const toolMessageId =+ anchoredToolMessageId ??+ (await new ThreadModel(this.db, origin.userId, origin.workspaceId).findById(threadId))+ ?.sourceMessageId ??+ undefined;if (toolMessageId) {result.subAgentResume = {parentOperationId,diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.tsindex 13567e6a2f6..b94185b3791 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts@@ -3275,6 +3275,47 @@ describe('AgentRuntimeService', () => {);});+ it('ends a callSubAgent result with the sub-agent id so the parent can continue it', async () => {+ (service as any).messageModel.findMessagePlugin = vi+ .fn()+ .mockResolvedValue({ apiName: 'callSubAgent', identifier: 'lobe-agent' });++ await service.completeSubAgentBridge({ ...bridgeParams, finalState: childState as any });+ await service.completeSubAgentBridge({+ ...bridgeParams,+ finalState: { ...childState, error: { message: 'Budget exceeded' } } as any,+ reason: 'error',+ });++ expect(updateToolMessage).toHaveBeenNthCalledWith(+ 1,+ 'tool-msg-1',+ expect.objectContaining({ content: 'final answer\n\n<sub_agent id="thread-1" />' }),+ );+ expect(updateToolMessage).toHaveBeenNthCalledWith(+ 2,+ 'tool-msg-1',+ expect.objectContaining({+ content: expect.stringMatching(+ /^Sub-agent did not complete \(error\): .*\n\n<sub_agent id="thread-1" \/>$/,+ ),+ }),+ );+ });++ it('leaves callAgent results without a sub-agent id', async () => {+ (service as any).messageModel.findMessagePlugin = vi+ .fn()+ .mockResolvedValue({ apiName: 'callAgent', identifier: 'lobe-agent-management' });++ await service.completeSubAgentBridge({ ...bridgeParams, finalState: childState as any });++ expect(updateToolMessage).toHaveBeenCalledWith(+ 'tool-msg-1',+ expect.objectContaining({ content: 'final answer' }),+ );+ });+it('loads the child state from the coordinator when finalState is not passed (webhook path)', async () => {mockCoordinator.loadAgentState.mockResolvedValue(childState);diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.tsindex 6393f30ca7b..8d348768c4a 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts@@ -17,6 +17,7 @@ import {isParkedStatus,} from '@lobechat/agent-runtime';import type { ISnapshotStore } from '@lobechat/agent-tracing';+import { appendSubAgentReference, isCallSubAgentCall } from '@lobechat/builtin-tool-lobe-agent';import { dynamicInterventionAudits } from '@lobechat/builtin-tools/dynamicInterventionAudits';import { parse } from '@lobechat/conversation-flow';import { getModelPropertyWithFallback } from '@lobechat/model-runtime';@@ -3468,11 +3469,17 @@ export class AgentRuntimeService {}}const errorReason = failed ? formatSubAgentErrorReason(finalState?.error) : undefined;- const content = failed+ const resultContent = failed? errorReason? `Sub-agent did not complete (${reason}): ${errorReason}`: `Sub-agent did not complete (${reason}).`: lastAssistantContent || 'Sub-agent completed without a textual answer.';+ // callSubAgent results carry the sub-agent id so the parent can later send+ // this same sub-agent a follow-up (`callSubAgent({ subAgentId })`) — e.g.+ // to hand over what it gathered before failing — instead of redoing it.+ const content = (await this.isCallSubAgentToolMessage(toolMessageId, threadId))+ ? appendSubAgentReference(resultContent, threadId)+ : resultContent;const backfill = await this.messageModel.updateToolMessage(toolMessageId, {content,@@ -3508,6 +3515,24 @@ export class AgentRuntimeService {);}+ /**+ * Whether the bridged placeholder belongs to `lobe-agent.callSubAgent` (the+ * same bridge also serves `callAgent`, whose children cannot be continued).+ * Best-effort: a failed lookup only drops the id trailer, never the bridge.+ */+ private async isCallSubAgentToolMessage(+ toolMessageId: string,+ threadId: string | undefined,+ ): Promise<boolean> {+ if (!threadId) return false;+ try {+ return isCallSubAgentCall(await this.messageModel.findMessagePlugin(toolMessageId));+ } catch (error) {+ log('[%s] sub-agent bridge: failed to read tool plugin: %O', toolMessageId, error);+ return false;+ }+ }+/*** Whether every pending tool call has a fulfilled tool_result message — i.e.* a tool message exists for its `tool_call_id` with non-empty content or adiff --git a/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts b/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.tsindex e6a13257cca..f76a5e13215 100644--- a/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts@@ -600,6 +600,46 @@ describe('AbandonOperationService', () => {expect(coord.deleteAgentOperation).not.toHaveBeenCalled();});+ it("backfills a continued sub-agent's own placeholder, not the thread's first one", async () => {+ findOperationMock.mockResolvedValue({+ parentOperationId: 'op_parent',+ threadId: 'thread_1',+ });+ // The reused thread still points at the placeholder of its FIRST run.+ findThreadMock.mockResolvedValue({ sourceMessageId: 'msg_first_placeholder' });++ const coord = buildCoordinator({+ loadAgentState: vi.fn().mockResolvedValue(+ stateWith({+ metadata: { assistantMessageId: 'msg_assist_2' },+ origin: {+ threadId: 'thread_1',+ userId: 'user_x',+ workspaceId: 'ws_1',+ lineage: {+ isSubAgent: true,+ progressAnchor: {+ parentOperationId: 'op_parent',+ toolMessageId: 'msg_followup_placeholder',+ },+ },+ },+ }),+ ),+ });+ const store = buildStore();+ store.loadPartial.mockResolvedValue(null);++ const svc = new AbandonOperationService({} as any, {+ coordinator: coord as any,+ snapshotStore: store as any,+ });++ const result = await svc.finalizeAbandoned('op_child', 'inactivity_watchdog');++ expect(result.subAgentResume?.toolMessageId).toBe('msg_followup_placeholder');+ });+it('omits subAgentResume for an isolated group member (orchestrationRole=member)', async () => {findOperationMock.mockResolvedValue({parentOperationId: 'op_supervisor',diff --git a/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts b/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.tsindex 5b9058261e0..b702d4555dc 100644--- a/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts@@ -12,11 +12,15 @@ vi.mock('@/libs/trusted-client', () => ({// Mock ThreadModelconst mockThreadModel = {+ claimForRun: vi.fn(),create: vi.fn(),findById: vi.fn(),update: vi.fn(),};+const mockOperationFindById = vi.fn();+const mockFindMessagePlugin = vi.fn();+vi.mock('@/database/models/thread', () => ({ThreadModel: vi.fn().mockImplementation(function () {return mockThreadModel;@@ -26,7 +30,7 @@ vi.mock('@/database/models/thread', () => ({vi.mock('@/database/models/agentOperation', () => ({AgentOperationModel: vi.fn().mockImplementation(function () {return {- findById: vi.fn().mockResolvedValue({ trigger: 'cli' }),+ findById: mockOperationFindById,};}),}));@@ -45,6 +49,7 @@ vi.mock('@/database/models/message', () => ({MessageModel: vi.fn().mockImplementation(function () {return {create: vi.fn().mockResolvedValue({ id: 'msg-1' }),+ findMessagePlugin: mockFindMessagePlugin,getLatestNonToolMessageId: vi.fn().mockResolvedValue(undefined),getLatestSpineMessageId: vi.fn().mockResolvedValue(undefined),query: vi.fn().mockResolvedValue([]),@@ -142,6 +147,7 @@ describe('AiAgentService.execSubAgent', () => {sourceMessageId: 'parent-msg-1',});mockThreadModel.update.mockResolvedValue({});+ mockOperationFindById.mockResolvedValue({ trigger: 'cli' });service = new AiAgentService(mockDb, userId);});@@ -565,4 +571,219 @@ describe('AiAgentService.execSubAgent', () => {expect(onCompleteHook!.handler).toBeInstanceOf(Function);});});++ describe('continuing an earlier callSubAgent thread', () => {+ const execAgentResult = {+ agentId: 'agent-1',+ assistantMessageId: 'assistant-msg-2',+ autoStarted: true,+ createdAt: new Date().toISOString(),+ message: 'Agent operation created successfully',+ messageId: 'queue-msg-2',+ operationId: 'op-new',+ status: 'created',+ success: true,+ timestamp: new Date().toISOString(),+ topicId: 'topic-1',+ userMessageId: 'user-msg-2',+ };++ const followUp = {+ agentId: 'agent-1',+ instruction: 'Hand over what you found so far',+ parentMessageId: 'tool-msg-2',+ parentOperationId: 'parent-op-2',+ threadId: 'thread-old',+ topicId: 'topic-1',+ };++ beforeEach(() => {+ mockThreadModel.findById.mockResolvedValue({+ agentId: 'agent-1',+ id: 'thread-old',+ metadata: { operationId: 'op-old' },+ sourceMessageId: 'tool-msg-1',+ status: ThreadStatus.Failed,+ topicId: 'topic-1',+ type: ThreadType.Isolation,+ });+ mockThreadModel.claimForRun.mockResolvedValue(true);+ mockFindMessagePlugin.mockResolvedValue({+ apiName: 'callSubAgent',+ identifier: 'lobe-agent',+ });+ mockOperationFindById.mockImplementation(async (id: string) =>+ id === 'op-old' ? { status: 'error' } : { trigger: 'cli' },+ );+ });++ it('runs the new instruction on the same thread and reports to the new placeholder', async () => {+ const execAgentSpy = vi.spyOn(service, 'execAgent').mockResolvedValue(execAgentResult);++ const result = await service.execVirtualSubAgent(followUp);++ expect(mockThreadModel.create).not.toHaveBeenCalled();+ expect(mockThreadModel.claimForRun).toHaveBeenCalledWith(+ 'thread-old',+ { operationId: 'op-old', status: ThreadStatus.Failed },+ { startedAt: expect.any(String) },+ );+ expect(execAgentSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ appContext: expect.objectContaining({+ isSubAgent: true,+ subAgentProgress: { parentOperationId: 'parent-op-2', toolMessageId: 'tool-msg-2' },+ threadId: 'thread-old',+ }),+ hooks: expect.arrayContaining([+ expect.objectContaining({+ id: 'sub-agent-bridge',+ webhook: expect.objectContaining({+ body: {+ parentOperationId: 'parent-op-2',+ threadId: 'thread-old',+ toolMessageId: 'tool-msg-2',+ },+ }),+ }),+ ]),+ parentOperationId: 'parent-op-2',+ prompt: 'Hand over what you found so far',+ }),+ );+ expect(result).toMatchObject({+ operationId: 'op-new',+ success: true,+ threadId: 'thread-old',+ });+ });++ it('allows a stale processing thread whose run was abandoned', async () => {+ mockThreadModel.findById.mockResolvedValue({+ agentId: 'agent-1',+ id: 'thread-old',+ metadata: { operationId: 'op-old' },+ sourceMessageId: 'tool-msg-1',+ status: ThreadStatus.Processing,+ topicId: 'topic-1',+ type: ThreadType.Isolation,+ });+ mockOperationFindById.mockImplementation(async (id: string) =>+ id === 'op-old' ? { status: 'abandoned' } : { trigger: 'cli' },+ );+ vi.spyOn(service, 'execAgent').mockResolvedValue(execAgentResult);++ await expect(service.execVirtualSubAgent(followUp)).resolves.toMatchObject({+ success: true,+ });+ });++ it.each([+ [+ 'its previous run is still going',+ () => mockOperationFindById.mockResolvedValue({ status: 'running' }),+ 'still running',+ ],+ [+ 'another follow-up claimed it first',+ () => mockThreadModel.claimForRun.mockResolvedValue(false),+ 'still running',+ ],+ [+ 'it belongs to another topic',+ () =>+ mockThreadModel.findById.mockResolvedValue({+ agentId: 'agent-1',+ id: 'thread-old',+ sourceMessageId: 'tool-msg-1',+ status: ThreadStatus.Failed,+ topicId: 'topic-other',+ type: ThreadType.Isolation,+ }),+ 'not found',+ ],+ [+ 'it was not started by callSubAgent',+ () =>+ mockFindMessagePlugin.mockResolvedValue({+ apiName: 'callAgent',+ identifier: 'lobe-agent-management',+ }),+ 'not a sub-agent',+ ],+ ])('refuses to start when %s', async (_case, arrange, error) => {+ arrange();+ const execAgentSpy = vi.spyOn(service, 'execAgent');++ const result = await service.execVirtualSubAgent(followUp);++ expect(execAgentSpy).not.toHaveBeenCalled();+ expect(result.success).toBe(false);+ expect(result.error).toContain(error);+ });++ it('adds the new run usage to the totals of earlier runs', async () => {+ mockThreadModel.findById.mockResolvedValue({+ agentId: 'agent-1',+ id: 'thread-old',+ metadata: {+ operationId: 'op-old',+ totalCost: 0.5,+ totalMessages: 6,+ totalTokens: 1000,+ totalToolCalls: 3,+ },+ sourceMessageId: 'tool-msg-1',+ status: ThreadStatus.Failed,+ topicId: 'topic-1',+ type: ThreadType.Isolation,+ });+ const execAgentSpy = vi.spyOn(service, 'execAgent').mockResolvedValue(execAgentResult);++ await service.execVirtualSubAgent(followUp);++ const carried = { totalCost: 0.5, totalMessages: 6, totalTokens: 1000, totalToolCalls: 3 };+ expect(mockThreadModel.claimForRun).toHaveBeenCalledWith(+ 'thread-old',+ expect.anything(),+ expect.objectContaining(carried),+ );+ expect(mockThreadModel.update).toHaveBeenCalledWith('thread-old', {+ metadata: expect.objectContaining({ ...carried, operationId: 'op-new' }),+ });++ const completion = execAgentSpy.mock.calls[0][0].hooks?.find(+ (h) => h.id === 'thread-completion',+ );+ await completion!.handler({+ finalState: {+ cost: { total: 0.25 },+ messages: [{ content: 'part 4', role: 'assistant' }],+ operationId: 'op-new',+ usage: { llm: { tokens: { total: 400 } }, tools: { totalCalls: 2 } },+ },+ operationId: 'op-new',+ reason: 'done',+ } as any);++ expect(mockThreadModel.update).toHaveBeenLastCalledWith('thread-old', {+ metadata: expect.objectContaining({+ totalCost: 0.75,+ totalTokens: 1400,+ totalToolCalls: 5,+ }),+ status: ThreadStatus.Completed,+ });+ });++ it('marks the claimed thread failed when the run cannot be created', async () => {+ vi.spyOn(service, 'execAgent').mockRejectedValue(new Error('db down'));++ await expect(service.execVirtualSubAgent(followUp)).rejects.toThrow('db down');+ expect(mockThreadModel.update).toHaveBeenCalledWith(+ 'thread-old',+ expect.objectContaining({ status: ThreadStatus.Failed }),+ );+ });+ });});diff --git a/apps/server/src/services/aiAgent/hooks/threadRunHooks.ts b/apps/server/src/services/aiAgent/hooks/threadRunHooks.tsindex ce1d8997817..38eefb319cc 100644--- a/apps/server/src/services/aiAgent/hooks/threadRunHooks.ts+++ b/apps/server/src/services/aiAgent/hooks/threadRunHooks.ts@@ -1,4 +1,5 @@import type { AgentHookEvent, AgentState } from '@lobechat/agent-runtime';+import type { ThreadMetadata } from '@lobechat/types';import { ThreadStatus } from '@lobechat/types';import debug from 'debug';@@ -22,6 +23,26 @@ export function calculateTotalTokens(usage?: AgentState['usage']): number | undereturn usage.llm?.tokens?.total;}+/**+ * Usage a continued sub-agent thread accumulated in its earlier runs. Every+ * run starts fresh counters and each thread write replaces `metadata`, so a+ * follow-up run carries these forward and adds its own usage on top.+ */+export type ThreadUsageBaseline = Pick<+ ThreadMetadata,+ 'totalCost' | 'totalMessages' | 'totalTokens' | 'totalToolCalls'+>;++export const pickThreadUsageBaseline = (metadata?: ThreadMetadata | null): ThreadUsageBaseline => ({+ totalCost: metadata?.totalCost,+ totalMessages: metadata?.totalMessages,+ totalTokens: metadata?.totalTokens,+ totalToolCalls: metadata?.totalToolCalls,+});++const addUsage = (baseline?: number, run?: number): number | undefined =>+ baseline === undefined ? run : baseline + (run ?? 0);+/*** Create step lifecycle callbacks for updating Thread metadata* These callbacks accumulate metrics during execution and update Thread on completion@@ -163,29 +184,26 @@ export function createThreadHooks(startedAt: string,sourceMessageId: string,logScope: 'execSubAgent' | 'execVirtualSubAgent',+ usageBaseline: ThreadUsageBaseline = {},): AgentHook[] {- let accumulatedToolCalls = 0;-return [{handler: async (event: AgentHookEvent) => {const state = event.finalState;if (!state) return;- // Count tool calls from step result- const stepToolCalls = state.session?.toolCalls || 0;- if (stepToolCalls > accumulatedToolCalls) {- accumulatedToolCalls = stepToolCalls;- }-try {await threadModel.update(threadId, {metadata: {operationId: event.operationId,startedAt,+ totalCost: usageBaseline.totalCost,totalMessages: state.messages?.length ?? 0,- totalTokens: calculateTotalTokens(state.usage),- totalToolCalls: accumulatedToolCalls,+ totalTokens: addUsage(usageBaseline.totalTokens, calculateTotalTokens(state.usage)),+ totalToolCalls: addUsage(+ usageBaseline.totalToolCalls,+ state.usage?.tools?.totalCalls,+ ),},});} catch (error) {@@ -258,10 +276,16 @@ export function createThreadHooks(error: formattedError,operationId: finalState.operationId,startedAt,- totalCost: finalState.cost?.total,+ totalCost: addUsage(usageBaseline.totalCost, finalState.cost?.total),totalMessages: finalState.messages?.length ?? 0,- totalTokens: calculateTotalTokens(finalState.usage),- totalToolCalls: accumulatedToolCalls,+ totalTokens: addUsage(+ usageBaseline.totalTokens,+ calculateTotalTokens(finalState.usage),+ ),+ totalToolCalls: addUsage(+ usageBaseline.totalToolCalls,+ finalState.usage?.tools?.totalCalls,+ ),},status,});diff --git a/apps/server/src/services/aiAgent/subAgentRuns.ts b/apps/server/src/services/aiAgent/subAgentRuns.tsindex cca8bc770d3..182128c862a 100644--- a/apps/server/src/services/aiAgent/subAgentRuns.ts+++ b/apps/server/src/services/aiAgent/subAgentRuns.ts@@ -1,11 +1,13 @@+import { isCallSubAgentCall } from '@lobechat/builtin-tool-lobe-agent';import type {ExecAgentResult,ExecSubAgentParams,ExecSubAgentResult,ExecVirtualSubAgentParams,LobeAgentChatConfig,+ ThreadMetadata,} from '@lobechat/types';-import { ThreadStatus, ThreadType } from '@lobechat/types';+import { isAgentOperationInFlight, ThreadStatus, ThreadType } from '@lobechat/types';import debug from 'debug';import type { AgentOperationModel } from '@/database/models/agentOperation';@@ -23,6 +25,8 @@ import {createGroupActionMemberBridgeHook,createSubAgentBridgeHook,createThreadHooks,+ pickThreadUsageBaseline,+ type ThreadUsageBaseline,} from './hooks/threadRunHooks';import type { InternalExecAgentParams } from './types';@@ -81,6 +85,67 @@ export interface ExecAgentThreadRunOptions {resumeParentOnComplete?: boolean;}+type ThreadRow = NonNullable<Awaited<ReturnType<ThreadModel['findById']>>>;++/**+ * Take over an earlier `callSubAgent` isolation thread for a new turn, so the+ * same sub-agent continues on its preserved history.+ *+ * Refuses threads outside the parent's topic/agent, threads not created by+ * `callSubAgent` (group members, `callAgent` children, …), and threads whose+ * previous run is still going. The final compare-and-set claim makes+ * concurrent follow-ups to one sub-agent race-safe.+ *+ * Returns the usage the thread accumulated so far; the claim and every later+ * write of this run carry it forward instead of resetting the totals.+ */+const claimSubAgentThread = async (+ deps: SubAgentRunDeps,+ params: { agentId: string; startedAt: string; threadId: string; topicId: string },+): Promise<{ error: string } | { thread: ThreadRow; usageBaseline: ThreadUsageBaseline }> => {+ const { agentId, startedAt, threadId, topicId } = params;+ const thread = await deps.threadModel.findById(threadId);++ if (+ !thread ||+ thread.type !== ThreadType.Isolation ||+ thread.topicId !== topicId ||+ thread.agentId !== agentId+ ) {+ return { error: `Sub-agent "${threadId}" was not found in this conversation.` };+ }++ const sourcePlugin = thread.sourceMessageId+ ? await deps.messageModel.findMessagePlugin(thread.sourceMessageId)+ : undefined;+ if (!isCallSubAgentCall(sourcePlugin)) {+ return { error: `"${threadId}" is not a sub-agent started by callSubAgent.` };+ }++ const previousMetadata = thread.metadata as ThreadMetadata | null;+ const previousOperationId = previousMetadata?.operationId;+ const previousOperation = previousOperationId+ ? await deps.agentOperationModel.findById(previousOperationId)+ : null;+ // The operation, not the thread row's own `status`, is authoritative: the+ // inactivity watchdog abandons a stuck operation without touching its thread.+ const stillRunning = previousOperation+ ? isAgentOperationInFlight(previousOperation.status)+ : thread.status === ThreadStatus.Processing;+ const busyError = `Sub-agent "${threadId}" is still running. Wait for its result before sending it another instruction.`;++ if (stillRunning) return { error: busyError };++ const usageBaseline = pickThreadUsageBaseline(previousMetadata);+ const claimed = await deps.threadModel.claimForRun(+ thread.id,+ { operationId: previousOperationId ?? null, status: thread.status },+ { ...usageBaseline, startedAt },+ );++ return claimed ? { thread, usageBaseline } : { error: busyError };+};+/*** Execute an agent in an isolated Thread context: create the isolation thread,* register thread-lifecycle (and optionally completion-bridge) hooks, delegate@@ -116,28 +181,72 @@ export const execAgentThreadRun = async (.catch(() => {});}- // 1. Create Thread for isolated agent execution- const thread = await deps.threadModel.create({- agentId,- groupId,- sourceMessageId: parentMessageId,- title,- topicId,- type: ThreadType.Isolation,- });+ const startedAt = new Date().toISOString();+ const continueThreadId = 'threadId' in params ? params.threadId : undefined;+ let thread: ThreadRow;+ let usageBaseline: ThreadUsageBaseline = {};- if (!thread) {- throw new Error('Failed to create thread for agent execution');- }+ if (continueThreadId) {+ // 1-2. Continue an earlier callSubAgent thread: claim it (→ processing).+ // The new instruction lands as the next user turn on that thread, so the+ // sub-agent keeps its full history. Its original source message stays the+ // thread anchor; this run reports to the new placeholder (`parentMessageId`).+ const claim = await claimSubAgentThread(deps, {+ agentId,+ startedAt,+ threadId: continueThreadId,+ topicId,+ });- log('%s: created thread %s', options.logScope, thread.id);+ if ('error' in claim) {+ log('%s: cannot continue thread %s: %s', options.logScope, continueThreadId, claim.error);+ if (parentOperationId) {+ hookDispatcher+ .dispatch(parentOperationId, 'onCallAgentError', {+ agentId,+ error: claim.error,+ operationId: parentOperationId,+ userId: deps.userId,+ })+ .catch(() => {});+ }- // 2. Update Thread status to processing with startedAt timestamp- const startedAt = new Date().toISOString();- await deps.threadModel.update(thread.id, {- metadata: { startedAt },- status: ThreadStatus.Processing,- });+ return {+ assistantMessageId: '',+ error: claim.error,+ operationId: '',+ success: false,+ threadId: continueThreadId,+ };+ }++ thread = claim.thread;+ usageBaseline = claim.usageBaseline;+ log('%s: continuing thread %s', options.logScope, thread.id);+ } else {+ // 1. Create Thread for isolated agent execution+ const created = await deps.threadModel.create({+ agentId,+ groupId,+ sourceMessageId: parentMessageId,+ title,+ topicId,+ type: ThreadType.Isolation,+ });++ if (!created) {+ throw new Error('Failed to create thread for agent execution');+ }++ thread = created;+ log('%s: created thread %s', options.logScope, thread.id);++ // 2. Update Thread status to processing with startedAt timestamp+ await deps.threadModel.update(thread.id, {+ metadata: { startedAt },+ status: ThreadStatus.Processing,+ });+ }// 3. Create hooks for updating Thread metadata and source messageconst threadHooks = createThreadHooks(@@ -148,6 +257,7 @@ export const execAgentThreadRun = async (startedAt,parentMessageId,options.logScope,+ usageBaseline,);// For the virtual sub-agent path, also register the completion bridge that// backfills the parent's placeholder tool message and resumes the parked@@ -206,22 +316,47 @@ export const execAgentThreadRun = async (// 4. Delegate to execAgent with threadId in appContext and hooks// The instruction will be created as user message in the Thread// Use headless mode to skip human approval in async agent execution- const result = await deps.execAgent({- agentId,- appContext,- autoStart: true,- chatConfigOverride: options.chatConfig,- deviceId: options.deviceId,- hooks,- localDeviceId: options.localDeviceId,- // Explicit sub-agent model override resolved at the spawn site.- model: options.model,- parentOperationId,- prompt: instruction,- provider: options.provider,- trigger: inheritedTrigger,- userInterventionConfig: { approvalMode: 'headless' },- });+ let result: ExecAgentResult;+ try {+ result = await deps.execAgent({+ agentId,+ appContext,+ autoStart: true,+ chatConfigOverride: options.chatConfig,+ deviceId: options.deviceId,+ hooks,+ localDeviceId: options.localDeviceId,+ // Explicit sub-agent model override resolved at the spawn site.+ model: options.model,+ parentOperationId,+ prompt: instruction,+ provider: options.provider,+ trigger: inheritedTrigger,+ userInterventionConfig: { approvalMode: 'headless' },+ });+ } catch (error) {+ // Without an operation id a `processing` thread reads as "still running"+ // forever, which would lock the sub-agent against any later follow-up.+ await deps.threadModel+ .update(thread.id, {+ metadata: {+ ...usageBaseline,+ completedAt: new Date().toISOString(),+ error: String(error),+ startedAt,+ },+ status: ThreadStatus.Failed,+ })+ .catch((updateError) =>+ log(+ '%s: failed to mark thread %s failed after execAgent threw: %O',+ options.logScope,+ thread.id,+ updateError,+ ),+ );+ throw error;+ }log('%s: delegated to execAgent, operationId=%s, success=%s',@@ -232,7 +367,7 @@ export const execAgentThreadRun = async (// 5. Store operationId in Thread metadataawait deps.threadModel.update(thread.id, {- metadata: { operationId: result.operationId, startedAt },+ metadata: { ...usageBaseline, operationId: result.operationId, startedAt },});// 6. If operation failed to start, update thread status@@ -240,6 +375,7 @@ export const execAgentThreadRun = async (const completedAt = new Date().toISOString();await deps.threadModel.update(thread.id, {metadata: {+ ...usageBaseline,completedAt,duration: Date.now() - new Date(startedAt).getTime(),error: result.error,diff --git a/apps/server/src/services/goal/supervisor/policy.ts b/apps/server/src/services/goal/supervisor/policy.tsindex 0dc29d32797..a57dd8a7276 100644--- a/apps/server/src/services/goal/supervisor/policy.ts+++ b/apps/server/src/services/goal/supervisor/policy.ts@@ -1,10 +1,10 @@import type {AgentOperationCompletionReason,- AgentOperationStatus,GoalGraphSnapshot,GoalItem,TaskItem,} from '@lobechat/types';+import { isAgentOperationInFlight } from '@lobechat/types';import type { AgentOperationItem } from '@/database/schemas/agentOperations';import { HETERO_DISPATCH_ERROR_HEADLINES } from '@/server/services/aiAgent/helpers/heteroErrors';@@ -58,14 +58,6 @@ export const statusAuthoredByActor = (return Boolean(latest.actorUserId || latest.actorAgentId);};-/** The run has not settled yet; the lease reclaim owns it, not recovery. */-const IN_FLIGHT_STATUSES = new Set<AgentOperationStatus>([- 'idle',- 'running',- 'waiting_for_async_tool',- 'waiting_for_human',-]);-/*** Gateway codes whose own message states the run never started, so a retry cannot* duplicate committed work. `DEVICE_GATEWAY_UNAUTHORIZED` and `GATEWAY_NOT_CONFIGURED`@@ -107,7 +99,8 @@ export const recoveryEligibility = (if (graph.goal.status !== 'running' || graph.decisions.some((d) => d.status === 'pending')) {return { eligible: false, reason: 'Goal is stopped or has a pending decision' };}- if (operation && IN_FLIGHT_STATUSES.has(operation.status)) {+ // The run has not settled yet; the lease reclaim owns it, not recovery.+ if (operation && isAgentOperationInFlight(operation.status)) {return { eligible: false, reason: 'The operation has not settled yet' };}if (diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.tsindex 1fbcd213db4..7cc9b62d118 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.ts@@ -930,6 +930,57 @@ describe('lobeAgentRuntime', () => {expect(result).toMatchObject({ error: { code: 'SUB_AGENT_START_FAILED' } });});+ it('passes subAgentId to the runner to continue an earlier sub-agent', async () => {+ const runtime = lobeAgentRuntime.factory(baseContext);+ const run = vi+ .fn()+ .mockResolvedValue({ started: true, subOperationId: 'sub-op-2', threadId: 'thread-1' });++ const result = await runtime.callSubAgent(+ {+ description: 'Hand over',+ instruction: 'Summarize your findings',+ subAgentId: ' thread-1 ',+ },+ { ...baseContext, subAgent: { run } } as ToolExecutionContext,+ );++ expect(run).toHaveBeenCalledWith(expect.objectContaining({ subAgentId: 'thread-1' }));+ expect(result).toMatchObject({ deferred: true, state: { threadId: 'thread-1' } });+ });++ it('explains why an earlier sub-agent could not be continued', async () => {+ const runtime = lobeAgentRuntime.factory(baseContext);+ const run = vi.fn().mockResolvedValue({+ error: 'Sub-agent "thread-1" is still running.',+ started: false,+ threadId: 'thread-1',+ });++ const result = await runtime.callSubAgent(+ { description: 'Hand over', instruction: 'Summarize', subAgentId: 'thread-1' },+ { ...baseContext, subAgent: { run } } as ToolExecutionContext,+ );++ expect(result.deferred).toBeUndefined();+ expect(result.content).toBe(+ 'Sub-agent could not be continued: Sub-agent "thread-1" is still running.',+ );+ });++ it('rejects an empty subAgentId instead of silently starting a new sub-agent', async () => {+ const runtime = lobeAgentRuntime.factory(baseContext);+ const run = vi.fn();++ const result = await runtime.callSubAgent(+ { description: 'Hand over', instruction: 'Summarize', subAgentId: ' ' },+ { ...baseContext, subAgent: { run } } as ToolExecutionContext,+ );++ expect(result).toMatchObject({ error: { code: 'INVALID_ARGUMENTS' }, success: false });+ expect(run).not.toHaveBeenCalled();+ });+it('fails (not deferred) when no sub-agent runner is available', async () => {const runtime = lobeAgentRuntime.factory(baseContext);diff --git a/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts b/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.tsindex dfa856cea76..68ed90e497b 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts@@ -249,14 +249,18 @@ class LobeAgentExecutionRuntime {);}- const { description, instruction, timeout } = params;+ const { description, instruction, subAgentId, timeout } = params;if (!instruction || typeof instruction !== 'string') {return buildError('instruction is required.', 'INVALID_ARGUMENTS');}+ if (subAgentId !== undefined && (typeof subAgentId !== 'string' || !subAgentId.trim())) {+ return buildError('subAgentId must be a non-empty string.', 'INVALID_ARGUMENTS');+ }const { started, error, threadId, subOperationId, toolMessageId } = await ctx.subAgent.run({description,instruction,+ subAgentId: subAgentId?.trim(),timeout,});@@ -265,8 +269,9 @@ class LobeAgentExecutionRuntime {// (non-deferred) tool error so the parent's LLM sees the failure and the// batch continues instead of hanging in `waiting_for_async_tool`.if (!started) {+ const action = subAgentId ? 'could not be continued' : 'failed to start';return buildError(- error ? `Sub-agent failed to start: ${error}` : 'Sub-agent failed to start.',+ error ? `Sub-agent ${action}: ${error}` : `Sub-agent ${action}.`,'SUB_AGENT_START_FAILED',);}diff --git a/apps/server/src/services/toolExecution/types.ts b/apps/server/src/services/toolExecution/types.tsindex 86a90bf2bbf..c0fbf5bedd0 100644--- a/apps/server/src/services/toolExecution/types.ts+++ b/apps/server/src/services/toolExecution/types.ts@@ -27,6 +27,11 @@ export interface ServerSubAgentRunParams {description: string;/** Detailed instruction/prompt for the sub-agent run. */instruction: string;+ /**+ * Continue this earlier `callSubAgent` sub-agent (its isolation thread id)+ * instead of starting a new one. Only set by `callSubAgent`.+ */+ subAgentId?: string;/** Optional per-run timeout in milliseconds. */timeout?: number;}diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.jsonindex 8991f3f698b..abf54fd158d 100644--- a/locales/en-US/plugin.json+++ b/locales/en-US/plugin.json@@ -174,6 +174,7 @@"builtins.lobe-agent.apiName.vent.rejected": "Not recorded","builtins.lobe-agent.subAgent.stats.tokens": "{{count}} tokens","builtins.lobe-agent.subAgent.stats.tools": "{{count}} tools",+ "builtins.lobe-agent.subAgent.stopped": "Stopped before finishing","builtins.lobe-agent.title": "Lobe Agent","builtins.lobe-agent.todos.allDone": "All tasks completed","builtins.lobe-agent.todos.completedStep": "Completed",diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.jsonindex 9bead01ba70..ed1e9626fd3 100644--- a/locales/zh-CN/plugin.json+++ b/locales/zh-CN/plugin.json@@ -174,6 +174,7 @@"builtins.lobe-agent.apiName.vent.rejected": "未记录","builtins.lobe-agent.subAgent.stats.tokens": "{{count}} tokens","builtins.lobe-agent.subAgent.stats.tools": "{{count}} 个工具",+ "builtins.lobe-agent.subAgent.stopped": "未完成即中止","builtins.lobe-agent.title": "Lobe Agent","builtins.lobe-agent.todos.allDone": "全部任务已完成","builtins.lobe-agent.todos.completedStep": "已完成",diff --git a/packages/builtin-tool-lobe-agent/src/client/Render/CallSubAgent/index.tsx b/packages/builtin-tool-lobe-agent/src/client/Render/CallSubAgent/index.tsxindex e83301ef5af..a6ba683ce3c 100644--- a/packages/builtin-tool-lobe-agent/src/client/Render/CallSubAgent/index.tsx+++ b/packages/builtin-tool-lobe-agent/src/client/Render/CallSubAgent/index.tsx@@ -1,16 +1,17 @@'use client';import type { BuiltinRenderProps } from '@lobechat/types';-import { Flexbox, Markdown } from '@lobehub/ui';+import { Flexbox, Icon, Markdown } from '@lobehub/ui';import { Button, Text } from '@lobehub/ui/base-ui';-import { createStaticStyles } from 'antd-style';-import { ListTree } from 'lucide-react';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import { AlertTriangle, ListTree } from 'lucide-react';import { memo, useCallback } from 'react';import { useTranslation } from 'react-i18next';import { useChatStore } from '@/store/chat';import { portalThreadSelectors, threadSelectors } from '@/store/chat/selectors';+import { stripSubAgentReference } from '../../../subAgentReference';import type { CallSubAgentParams, CallSubAgentState } from '../../../types';const styles = createStaticStyles(({ css, cssVar }) => ({@@ -42,6 +43,14 @@ const styles = createStaticStyles(({ css, cssVar }) => ({border-radius: ${cssVar.borderRadiusLG};background: ${cssVar.colorBgContainer};`,+ stoppedLabel: css`+ font-size: 12px;+ color: ${cssVar.colorWarning};+ `,+ stoppedResultBox: css`+ border: 1px solid ${cssVar.colorWarningBorder};+ background: ${cssVar.colorWarningBg};+ `,}));/**@@ -53,6 +62,9 @@ const styles = createStaticStyles(({ css, cssVar }) => ({* is located by the `threadId` persisted in tool state; while the run is still* starting the lookup can return `undefined`, so the button is hidden rather* than rendered as a dead no-op.+ *+ * A run that stopped before finishing is marked with a warning, so its partial+ * summary is not mistaken for a finished result.*/export const CallSubAgentRender = memo<BuiltinRenderProps<CallSubAgentParams, CallSubAgentState, string>@@ -60,8 +72,9 @@ export const CallSubAgentRender = memo<const { t } = useTranslation('plugin');const { t: tChat } = useTranslation('chat');const prompt = args?.instruction?.trim();- const result = typeof content === 'string' ? content.trim() : '';+ const result = typeof content === 'string' ? stripSubAgentReference(content).trim() : '';const threadId = pluginState?.threadId;+ const stopped = pluginState?.status === 'error';const subagentThread = useChatStore((s) =>threadId@@ -109,7 +122,16 @@ export const CallSubAgentRender = memo<className={styles.labelRow}justify={'space-between'}>- <Text className={styles.label}>{t('builtins.lobe-claude-code.agent.result')}</Text>+ {stopped ? (+ <Flexbox horizontal align={'center'} gap={4}>+ <Icon color={cssVar.colorWarning} icon={AlertTriangle} size={14} />+ <Text className={styles.stoppedLabel}>+ {t('builtins.lobe-agent.subAgent.stopped')}+ </Text>+ </Flexbox>+ ) : (+ <Text className={styles.label}>{t('builtins.lobe-claude-code.agent.result')}</Text>+ )}{subagentThread && (<ButtonclassName={styles.openThread}@@ -125,7 +147,7 @@ export const CallSubAgentRender = memo<)}</Flexbox>{result && (- <Flexbox className={styles.resultBox}>+ <Flexbox className={cx(styles.resultBox, stopped && styles.stoppedResultBox)}><Markdown style={{ maxHeight: 320, overflow: 'auto' }} variant={'chat'}>{result}</Markdown>diff --git a/packages/builtin-tool-lobe-agent/src/client/executor/callSubAgent.test.ts b/packages/builtin-tool-lobe-agent/src/client/executor/callSubAgent.test.tsindex 48e06f8af4b..974607946a8 100644--- a/packages/builtin-tool-lobe-agent/src/client/executor/callSubAgent.test.ts+++ b/packages/builtin-tool-lobe-agent/src/client/executor/callSubAgent.test.ts@@ -47,6 +47,19 @@ describe('lobeAgentExecutor.callSubAgent', () => {});});+ it('refuses to continue an earlier sub-agent instead of starting a fresh one', async () => {+ const run = vi.fn();++ const result = await lobeAgentExecutor.callSubAgent(+ { ...params, subAgentId: 'thd_1' },+ createContext(run),+ );++ expect(result.success).toBe(false);+ expect(result.content).toContain('not supported in this runtime');+ expect(run).not.toHaveBeenCalled();+ });+it('surfaces a failed run as a tool error without state', async () => {const run = vi.fn().mockResolvedValue({error: 'boom',diff --git a/packages/builtin-tool-lobe-agent/src/client/executor/index.ts b/packages/builtin-tool-lobe-agent/src/client/executor/index.tsindex c4476755a99..4f88d5ba4d8 100644--- a/packages/builtin-tool-lobe-agent/src/client/executor/index.ts+++ b/packages/builtin-tool-lobe-agent/src/client/executor/index.ts@@ -437,12 +437,23 @@ class LobeAgentExecutor extends BaseExecutor<typeof LobeAgentApiName> {return nestedSubAgentDisabledResult();}- const { description, instruction, inheritMessages, timeout } = params;+ const { description, instruction, inheritMessages, subAgentId, timeout } = params;if (!description || !instruction) {return { content: 'Sub-agent description and instruction are required.', success: false };}+ // Continuing an earlier sub-agent is implemented by the server runtime only.+ // Fail loudly instead of silently starting a fresh sub-agent that has none+ // of the earlier sub-agent's history.+ if (subAgentId) {+ return {+ content:+ 'Continuing an earlier sub-agent (subAgentId) is not supported in this runtime. Omit subAgentId to start a new sub-agent.',+ success: false,+ };+ }+if (!ctx.subAgent) {return { content: 'Sub-agent execution is not available in this runtime.', success: false };}diff --git a/packages/builtin-tool-lobe-agent/src/index.ts b/packages/builtin-tool-lobe-agent/src/index.tsindex 589afeb5fc8..4c1566244be 100644--- a/packages/builtin-tool-lobe-agent/src/index.ts+++ b/packages/builtin-tool-lobe-agent/src/index.ts@@ -1,11 +1,8 @@-// Plan execution runtime — pure logic, safe to consume server-side-export {- type PlanDocument,- type PlanRuntimeContext,- type PlanRuntimeService,-} from './PlanRuntime';export * from './manifest';export * from './media';+// Plan execution runtime — pure logic, safe to consume server-side+export { type PlanDocument, type PlanRuntimeContext, type PlanRuntimeService } from './PlanRuntime';export * from './resolveManifest';+export * from './subAgentReference';export * from './systemRole';export * from './types';diff --git a/packages/builtin-tool-lobe-agent/src/manifest.ts b/packages/builtin-tool-lobe-agent/src/manifest.tsindex ebfe7215142..d2a130e3fcd 100644--- a/packages/builtin-tool-lobe-agent/src/manifest.ts+++ b/packages/builtin-tool-lobe-agent/src/manifest.ts@@ -234,7 +234,7 @@ export const LobeAgentManifest: BuiltinToolManifest = {// ==================== Sub-Agent ===================={description:- 'Dispatch a single sub-agent that runs in an isolated context to handle a long-running, multi-step request. Use this when the request requires extended processing (web research, multi-source synthesis, deep investigation) that benefits from running independently of the main conversation.',+ 'Dispatch a single sub-agent that runs in an isolated context to handle a long-running, multi-step request. Use this when the request requires extended processing (web research, multi-source synthesis, deep investigation) that benefits from running independently of the main conversation. Pass `subAgentId` to send a follow-up message to an earlier sub-agent instead of starting a new one.',name: LobeAgentApiName.callSubAgent,parameters: {properties: {@@ -251,6 +251,11 @@ export const LobeAgentManifest: BuiltinToolManifest = {'Whether to inherit context messages from the parent conversation. Default is false.',type: 'boolean',},+ subAgentId: {+ description:+ 'Optional. The id from the `<sub_agent id="..." />` tag at the end of an earlier callSubAgent result. Sends `instruction` as a new message to that same sub-agent, which keeps all of its previous work and history — use it to continue a sub-agent that stopped or failed, ask it to hand over what it has found so far, or follow up on its answer. Omit to start a new sub-agent.',+ type: 'string',+ },...(isDesktop && {runInClient: {description:diff --git a/packages/builtin-tool-lobe-agent/src/subAgentReference.test.ts b/packages/builtin-tool-lobe-agent/src/subAgentReference.test.tsnew file mode 100644index 00000000000..3cc8b68b324--- /dev/null+++ b/packages/builtin-tool-lobe-agent/src/subAgentReference.test.ts@@ -0,0 +1,36 @@+import { describe, expect, it } from 'vitest';++import { appendSubAgentReference, stripSubAgentReference } from './subAgentReference';++describe('subAgentReference', () => {+ it('appends the sub-agent id after the result', () => {+ expect(appendSubAgentReference('Findings', 'thd_1')).toBe(+ 'Findings\n\n<sub_agent id="thd_1" />',+ );+ });++ it('replaces an existing trailer instead of stacking another one', () => {+ const once = appendSubAgentReference('Findings', 'thd_1');++ expect(appendSubAgentReference(once, 'thd_1')).toBe(once);+ });++ it('keeps an empty result addressable', () => {+ expect(appendSubAgentReference('', 'thd_1')).toBe('<sub_agent id="thd_1" />');+ });++ it('strips only the trailing reference', () => {+ const content = 'See <sub_agent id="thd_0" /> inline\n\n<sub_agent id="thd_1" />';++ expect(stripSubAgentReference(content)).toBe('See <sub_agent id="thd_0" /> inline');+ expect(stripSubAgentReference('Plain result')).toBe('Plain result');+ });++ it('stays linear on long whitespace runs', () => {+ const content = `a${' '.repeat(50_000)}b`;+ const start = performance.now();++ expect(stripSubAgentReference(content)).toBe(content);+ expect(performance.now() - start).toBeLessThan(100);+ });+});diff --git a/packages/builtin-tool-lobe-agent/src/subAgentReference.ts b/packages/builtin-tool-lobe-agent/src/subAgentReference.tsnew file mode 100644index 00000000000..429e5698f31--- /dev/null+++ b/packages/builtin-tool-lobe-agent/src/subAgentReference.ts@@ -0,0 +1,41 @@+import { LobeAgentApiName, LobeAgentIdentifier } from './types';++/**+ * Whether a tool call is `lobe-agent.callSubAgent` — the only call whose+ * result carries the sub-agent reference and whose sub-agent can be continued+ * (`callAgent` children and group members cannot).+ */+export const isCallSubAgentCall = (+ plugin?: { apiName?: string | null; identifier?: string | null } | null,+): boolean =>+ plugin?.identifier === LobeAgentIdentifier && plugin.apiName === LobeAgentApiName.callSubAgent;++/**+ * Trailer appended to every server `callSubAgent` tool result. It is the+ * parent model's only handle on the sub-agent it just ran: passing the id back+ * as `callSubAgent({ subAgentId })` sends that same sub-agent a new turn on its+ * preserved history (continue after a failure, hand over partial findings,+ * follow-up questions). The id is the sub-agent's isolation thread id.+ *+ * The chat UI strips the trailer before rendering the result.+ */+/**+ * Starts at the literal tag instead of a leading `\s*`: an unanchored leading+ * `\s*` backtracks quadratically on long whitespace runs (CodeQL+ * js/polynomial-redos). Whitespace before the tag is trimmed in code instead.+ */+const SUB_AGENT_REFERENCE_PATTERN = /<sub_agent id="[^"]*" \/>\s*$/;++export const stripSubAgentReference = (content: string): string => {+ const match = SUB_AGENT_REFERENCE_PATTERN.exec(content);+ if (!match) return content;++ return content.slice(0, match.index).trimEnd();+};++export const appendSubAgentReference = (content: string, subAgentId: string): string => {+ const body = stripSubAgentReference(content);+ const reference = `<sub_agent id="${subAgentId}" />`;++ return body ? `${body}\n\n${reference}` : reference;+};diff --git a/packages/builtin-tool-lobe-agent/src/systemRole.ts b/packages/builtin-tool-lobe-agent/src/systemRole.tsindex b3dbc8da482..69cbbfea80b 100644--- a/packages/builtin-tool-lobe-agent/src/systemRole.ts+++ b/packages/builtin-tool-lobe-agent/src/systemRole.ts@@ -38,6 +38,12 @@ You can dispatch **sub-agents** to handle long-running, multi-step work in isola- \`callSubAgent\`: Dispatch a single sub-agent. **Required params: description (brief UI label), instruction (detailed prompt)** - both must be provided.- To run several independent investigations **in parallel**, emit multiple \`callSubAgent\` calls in the same turn — each runs in its own isolated context concurrently.+**Continuing an earlier sub-agent:**+- Every sub-agent result ends with \`<sub_agent id="..." />\`. Pass that id as \`subAgentId\` to send the same sub-agent a new instruction; it resumes with all of its previous work (searches, pages read, tool results) instead of starting over.+- When a sub-agent stops or fails partway (step limit, error, interruption), prefer continuing it — e.g. ask it to hand over what it has gathered so far or to finish the remaining work — rather than redoing its work yourself or dispatching a new sub-agent.+- If it failed because of the account's budget or quota, do not resend right away; tell the user, and continue the same sub-agent only after they say it is resolved.+- A sub-agent can only take one instruction at a time; do not send it a new instruction while it is still running.+**Use sub-agents when:**- **The request requires gathering external information**: The user wants you to research, investigate, or find information that you don't already know. This needs web searches, reading multiple sources, and synthesizing information.- **The task involves multiple steps**: The request cannot be answered in one simple response - it requires searching, reading, analyzing, and summarizing.diff --git a/packages/builtin-tool-lobe-agent/src/types.ts b/packages/builtin-tool-lobe-agent/src/types.tsindex 03e2fd686fc..fe158d6dfd7 100644--- a/packages/builtin-tool-lobe-agent/src/types.ts+++ b/packages/builtin-tool-lobe-agent/src/types.ts@@ -142,6 +142,12 @@ export interface CallSubAgentParams {inheritMessages?: boolean;instruction: string;runInClient?: boolean;+ /**+ * Id of an earlier sub-agent (from its result's `<sub_agent id>` trailer).+ * When set, `instruction` is sent as a new turn to that same sub-agent, which+ * keeps its previous history, instead of starting a fresh one.+ */+ subAgentId?: string;timeout?: number;}diff --git a/packages/database/src/models/__tests__/thread.test.ts b/packages/database/src/models/__tests__/thread.test.tsindex f5c8919a37a..f3520676ff9 100644--- a/packages/database/src/models/__tests__/thread.test.ts+++ b/packages/database/src/models/__tests__/thread.test.ts@@ -392,6 +392,92 @@ describe('ThreadModel', () => {});});+ describe('claimForRun', () => {+ const insertThread = (values: Partial<typeof threads.$inferInsert> = {}) =>+ serverDB.insert(threads).values({+ id: 'thread-claim',+ metadata: { operationId: 'op-old' },+ status: ThreadStatus.Failed,+ topicId,+ type: ThreadType.Isolation,+ userId,+ ...values,+ });++ it('moves the thread to processing when it still matches the validated run', async () => {+ await insertThread();++ const claimed = await threadModel.claimForRun(+ 'thread-claim',+ { operationId: 'op-old', status: ThreadStatus.Failed },+ { startedAt: '2026-09-25T00:00:00.000Z' },+ );++ const row = await serverDB.query.threads.findFirst({ where: eq(threads.id, 'thread-claim') });+ expect(claimed).toBe(true);+ expect(row?.status).toBe(ThreadStatus.Processing);+ expect(row?.metadata).toEqual({ startedAt: '2026-09-25T00:00:00.000Z' });+ });++ it('lets only one of two concurrent claims win', async () => {+ await insertThread();+ const expected = { operationId: 'op-old', status: ThreadStatus.Failed };++ const results = await Promise.all([+ threadModel.claimForRun('thread-claim', expected, { startedAt: 'a' }),+ threadModel.claimForRun('thread-claim', expected, { startedAt: 'b' }),+ ]);++ expect(results.filter(Boolean)).toHaveLength(1);+ });++ it('refuses when the thread moved on since it was read', async () => {+ await insertThread({ metadata: { operationId: 'op-new' } });++ await expect(+ threadModel.claimForRun(+ 'thread-claim',+ { operationId: 'op-old', status: ThreadStatus.Failed },+ { startedAt: 'a' },+ ),+ ).resolves.toBe(false);+ });++ it('matches a thread that never recorded a run id', async () => {+ await insertThread({ metadata: null, status: ThreadStatus.Active });++ await expect(+ threadModel.claimForRun(+ 'thread-claim',+ { status: ThreadStatus.Active },+ { startedAt: 'a' },+ ),+ ).resolves.toBe(true);+ });++ it('does not claim a thread owned by another user', async () => {+ await serverDB.transaction(async (tx) => {+ await tx.insert(topics).values({ id: 'other-topic', userId: otherUserId });+ await tx.insert(threads).values({+ id: 'thread-other',+ metadata: { operationId: 'op-old' },+ status: ThreadStatus.Failed,+ topicId: 'other-topic',+ type: ThreadType.Isolation,+ userId: otherUserId,+ });+ });++ await expect(+ threadModel.claimForRun(+ 'thread-other',+ { operationId: 'op-old', status: ThreadStatus.Failed },+ { startedAt: 'a' },+ ),+ ).resolves.toBe(false);+ });+ });+describe('delete', () => {it('should delete a thread', async () => {await serverDB.insert(threads).values({diff --git a/packages/database/src/models/thread.ts b/packages/database/src/models/thread.tsindex de4ec12bc34..b7e8987dad6 100644--- a/packages/database/src/models/thread.ts+++ b/packages/database/src/models/thread.ts@@ -1,6 +1,6 @@-import type { CreateThreadParams } from '@lobechat/types';+import type { CreateThreadParams, ThreadMetadata } from '@lobechat/types';import { RequestTrigger, ThreadStatus } from '@lobechat/types';-import { and, desc, eq, notExists, sql } from 'drizzle-orm';+import { and, desc, eq, isNull, notExists, sql } from 'drizzle-orm';import type { ThreadItem } from '../schemas';import { agentOperations, messages, threads } from '../schemas';@@ -163,6 +163,41 @@ export class ThreadModel {});};+ /**+ * Compare-and-set an existing thread into `processing` for a new run.+ *+ * Succeeds only while the row still carries the `status` and+ * `metadata.operationId` the caller validated, so two concurrent follow-ups+ * to the same sub-agent thread cannot both start a run on it.+ *+ * @returns whether this caller won the claim+ */+ claimForRun = async (+ id: string,+ expected: { operationId?: string | null; status?: ThreadItem['status'] },+ metadata: ThreadMetadata,+ ): Promise<boolean> => {+ const rows = await this.db+ .update(threads)+ .set({ metadata, status: ThreadStatus.Processing, updatedAt: new Date() })+ .where(+ and(+ eq(threads.id, id),+ this.ownership(),+ expected.status ? eq(threads.status, expected.status) : isNull(threads.status),+ // COALESCE instead of `IS NULL` on the extracted path: a bare jsonb null+ // test breaks the planner once the table carries a pg_search index (see+ // `__tests__/jsonbNullTest.test.ts`).+ expected.operationId+ ? sql`${threads.metadata} ->> 'operationId' = ${expected.operationId}`+ : sql`COALESCE(${threads.metadata} ->> 'operationId', '') = ''`,+ ),+ )+ .returning({ id: threads.id });++ return rows.length > 0;+ };+update = async (id: string, value: Partial<ThreadItem>) => {return this.db.update(threads)diff --git a/packages/locales/src/default/plugin.ts b/packages/locales/src/default/plugin.tsindex 3a3c4282a78..724ff6741e2 100644--- a/packages/locales/src/default/plugin.ts+++ b/packages/locales/src/default/plugin.ts@@ -89,6 +89,7 @@ export default {'builtins.lobe-agent.apiName.callSubAgent': 'Call sub-agent','builtins.lobe-agent.subAgent.stats.tokens': '{{count}} tokens','builtins.lobe-agent.subAgent.stats.tools': '{{count}} tools',+ 'builtins.lobe-agent.subAgent.stopped': 'Stopped before finishing','builtins.lobe-agent.title': 'Lobe Agent','builtins.lobe-claude-code.agent.instruction': 'Instruction','builtins.lobe-claude-code.agent.result': 'Result',diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.tsindex 097b6c521f9..2eb27844c60 100644--- a/packages/types/src/agentExecution/index.ts+++ b/packages/types/src/agentExecution/index.ts@@ -516,6 +516,12 @@ export interface ExecVirtualSubAgentParams {parentOperationId: string;/** Provider for {@link model}. */provider?: string;+ /**+ * Existing isolation thread of an earlier `callSubAgent` run to continue.+ * When set, the instruction becomes a new turn on that thread (the sub-agent+ * keeps its history) instead of a new thread being created.+ */+ threadId?: string;/** Timeout in milliseconds (optional) */timeout?: number;/** Thread title shown in UI */diff --git a/packages/types/src/agentOperation.ts b/packages/types/src/agentOperation.tsindex b62f8dc3c59..cc612e798ea 100644--- a/packages/types/src/agentOperation.ts+++ b/packages/types/src/agentOperation.ts@@ -8,6 +8,20 @@ export type AgentOperationStatus =| 'waiting_for_async_tool'| 'waiting_for_human';+const IN_FLIGHT_OPERATION_STATUSES = new Set<AgentOperationStatus>([+ 'idle',+ 'running',+ 'waiting_for_async_tool',+ 'waiting_for_human',+]);++/**+ * Whether the operation has not settled yet and may still write to its topic or+ * thread. `idle` counts: the run exists but has not started.+ */+export const isAgentOperationInFlight = (status: AgentOperationStatus): boolean =>+ IN_FLIGHT_OPERATION_STATUSES.has(status);+export type AgentOperationCompletionReason =| 'cost_limit'| 'done'diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/index.tsxindex 82a252e30d9..8ea2d130c94 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/index.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/index.tsx@@ -9,6 +9,7 @@ import AbortResponse from './AbortResponse';import LoadingPlaceholder from './LoadingPlaceholder';import RejectedResponse from './RejectedResponse';import ToolRender from './Render';+import { shouldShowCustomToolRender } from './shouldShowCustomToolRender';interface RenderProps {apiName: string;@@ -125,7 +126,6 @@ const Render = memo<RenderProps>(content={result.content || ''}messageId={toolMessageId}pluginState={result.state}- showCustomToolRender={result.error ? false : showCustomToolRender}toolCallId={toolCallId}plugin={{apiName,@@ -133,6 +133,12 @@ const Render = memo<RenderProps>(identifier,type: type as any,}}+ showCustomToolRender={shouldShowCustomToolRender({+ apiName,+ identifier,+ result,+ showCustomToolRender,+ })}/></Flexbox></Suspense>diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/shouldShowCustomToolRender.test.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/shouldShowCustomToolRender.test.tsnew file mode 100644index 00000000000..b306d7e764a--- /dev/null+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/shouldShowCustomToolRender.test.ts@@ -0,0 +1,48 @@+import { LobeAgentApiName, LobeAgentIdentifier } from '@lobechat/builtin-tool-lobe-agent';+import { describe, expect, it } from 'vitest';++import { shouldShowCustomToolRender } from './shouldShowCustomToolRender';++describe('shouldShowCustomToolRender', () => {+ const subAgent = {+ apiName: LobeAgentApiName.callSubAgent,+ identifier: LobeAgentIdentifier,+ showCustomToolRender: true,+ };++ it('keeps the custom renderer for a failed sub-agent with a preserved thread', () => {+ expect(+ shouldShowCustomToolRender({+ ...subAgent,+ result: { error: { message: 'Child failed' }, state: { threadId: 'thd_saved' } },+ }),+ ).toBe(true);+ });++ it('uses the generic error renderer when there is no child thread to open', () => {+ expect(shouldShowCustomToolRender({ ...subAgent, result: { error: 'Child failed' } })).toBe(+ false,+ );+ });++ it('keeps generic error rendering for other tools', () => {+ expect(+ shouldShowCustomToolRender({+ ...subAgent,+ apiName: LobeAgentApiName.createTodos,+ result: { error: 'Todo update failed', state: { threadId: 'thd_saved' } },+ }),+ ).toBe(false);+ });++ it('respects the caller setting and ordinary success results', () => {+ expect(shouldShowCustomToolRender({ ...subAgent, result: {} })).toBe(true);+ expect(+ shouldShowCustomToolRender({+ ...subAgent,+ result: { error: 'Child failed', state: { threadId: 'thd_saved' } },+ showCustomToolRender: false,+ }),+ ).toBe(false);+ });+});diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/shouldShowCustomToolRender.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/shouldShowCustomToolRender.tsnew file mode 100644index 00000000000..48b87f3d760--- /dev/null+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/shouldShowCustomToolRender.ts@@ -0,0 +1,36 @@+import { isCallSubAgentCall } from '@lobechat/builtin-tool-lobe-agent';+import type { ChatToolResult } from '@lobechat/types';++interface CustomToolRenderInput {+ apiName: string;+ identifier: string;+ result: Pick<ChatToolResult, 'error' | 'state'>;+ showCustomToolRender?: boolean;+}++/**+ * A failed `callSubAgent` whose child thread was preserved keeps its custom+ * render: that card is the only entry to the sub-agent's work.+ */+const isFailedSubAgentWithThread = ({+ apiName,+ identifier,+ result,+}: Omit<CustomToolRenderInput, 'showCustomToolRender'>): boolean =>+ isCallSubAgentCall({ apiName, identifier }) && typeof result.state?.threadId === 'string';++/**+ * Errored results fall back to the generic error view, except+ * {@link isFailedSubAgentWithThread}.+ */+export const shouldShowCustomToolRender = ({+ apiName,+ identifier,+ result,+ showCustomToolRender,+}: CustomToolRenderInput): boolean => {+ if (!showCustomToolRender) return false;+ if (!result.error) return true;++ return isFailedSubAgentWithThread({ apiName, identifier, result });+};diff --git a/src/features/ShareModal/ShareText/template.test.ts b/src/features/ShareModal/ShareText/template.test.tsindex 7e041f23ace..cbe303f0848 100644--- a/src/features/ShareModal/ShareText/template.test.ts+++ b/src/features/ShareModal/ShareText/template.test.ts@@ -113,6 +113,25 @@ describe('generateMarkdown', () => {expect(result).toContain('```json\n{"result": "tool data"}\n```');});+ it('should drop the hidden sub-agent reference from callSubAgent results', () => {+ const result = generateMarkdown({+ ...defaultParams,+ includeTool: true,+ messages: [+ {+ content: 'Found parts 1-3\n\n<sub_agent id="thd_1" />',+ createdAt: Date.now(),+ id: 'sub-agent-tool',+ plugin: { apiName: 'callSubAgent', arguments: '{}', identifier: 'lobe-agent' },+ role: 'tool',+ },+ ] as UIChatMessage[],+ });++ expect(result).toContain('```json\nFound parts 1-3\n```');+ expect(result).not.toContain('<sub_agent');+ });+it('should exclude tool messages when includeTool is false', () => {const result = generateMarkdown({...defaultParams,diff --git a/src/features/ShareModal/ShareText/template.ts b/src/features/ShareModal/ShareText/template.tsindex 1a4c806db2f..bfecb7681d2 100644--- a/src/features/ShareModal/ShareText/template.ts+++ b/src/features/ShareModal/ShareText/template.ts@@ -1,3 +1,4 @@+import { isCallSubAgentCall, stripSubAgentReference } from '@lobechat/builtin-tool-lobe-agent';import { type UIChatMessage } from '@lobechat/types';import { LOADING_FLAT } from '@/const/message';@@ -48,7 +49,13 @@ export const generateMarkdown = ({}if (chat.role === 'tool') {- parts.push('```json', String(chat.content), '```');+ // The sub-agent reference is a hidden address for the parent agent, not+ // part of the readable result. JSON export keeps it so an imported+ // conversation can still continue that sub-agent.+ const content = isCallSubAgentCall(chat.plugin)+ ? stripSubAgentReference(String(chat.content))+ : String(chat.content);+ parts.push('```json', content, '```');} else {parts.push(String(chat.content));