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(agent-runtime): deliver background sub-agent results again (#22530)

Lobehub Coder8b6594a5d189
diff --git a/packages/agent-runtime/src/executors/tool.batch.test.ts b/packages/agent-runtime/src/executors/tool.batch.test.ts
index 0b0390a5351..94366b4a879 100644
--- a/packages/agent-runtime/src/executors/tool.batch.test.ts
+++ b/packages/agent-runtime/src/executors/tool.batch.test.ts
@@ -166,6 +166,29 @@ describe('batch tool executors', () => {
expect(result.nextContext?.payload).toMatchObject({ parentMessageId: 'assistant-msg-1' });
});
+ it('merges a batch result into a row the tool created, keeping the state it wrote', async () => {
+ runTool.mockResolvedValueOnce({
+ attempts: 1,
+ result: { content: 'Started in the background.', executionTime: 5, success: true },
+ toolMessageId: 'background-placeholder',
+ });
+ const instruction: Extract<AgentInstruction, { type: 'call_tools_batch' }> = {
+ payload: {
+ parentMessageId: 'assistant-msg-1',
+ toolsCalling: [createToolCall('background-call', 'lobe-agent')],
+ },
+ type: 'call_tools_batch',
+ };
+
+ await callToolsBatch(host)(instruction, createState());
+
+ expect(createToolMessage).not.toHaveBeenCalled();
+ expect(host.transports.messages.updateToolMessage).toHaveBeenCalledWith(
+ 'background-placeholder',
+ expect.objectContaining({ pluginState: {}, replacePluginState: false }),
+ );
+ });
+
it('publishes and rethrows tool-message persist errors', async () => {
const error = new Error('database failed');
createToolMessage.mockRejectedValueOnce(error);
diff --git a/packages/agent-runtime/src/executors/tool.replay.test.ts b/packages/agent-runtime/src/executors/tool.replay.test.ts
index 13ee669ebc7..938b220ad99 100644
--- a/packages/agent-runtime/src/executors/tool.replay.test.ts
+++ b/packages/agent-runtime/src/executors/tool.replay.test.ts
@@ -256,6 +256,22 @@ describe.each(['single', 'batch'] as const)('%s tool step redelivery', (mode) =>
expect(f.stored).toHaveLength(1);
});
+ it('reuses a written result whose state stays pending while its work continues', async () => {
+ // A background sub-agent's start receipt: the call returned, but the row
+ // keeps `status: pending` until the sub-agent reports back.
+ const f = fixture([
+ {
+ content: 'Started in the background.',
+ metadata: { toolExecutionTimeMs: 5, toolResultSuccess: true },
+ pluginState: { background: true, status: 'pending' },
+ },
+ ]);
+ await execute(f);
+ expect(f.tools.run).not.toHaveBeenCalled();
+ expect(f.messages.updateToolMessage).not.toHaveBeenCalled();
+ expect(f.stored[0].pluginState).toEqual({ background: true, status: 'pending' });
+ });
+
it('does not reuse a provider call id from another assistant', async () => {
const f = fixture([{ content: 'unrelated result', parentId: 'other-assistant' }]);
await execute(f);
diff --git a/packages/agent-runtime/src/executors/tool.test.ts b/packages/agent-runtime/src/executors/tool.test.ts
index cfb5c7c4667..7c2840e14f0 100644
--- a/packages/agent-runtime/src/executors/tool.test.ts
+++ b/packages/agent-runtime/src/executors/tool.test.ts
@@ -190,6 +190,53 @@ describe('single tool executors', () => {
expect(result.nextContext?.payload).toMatchObject({ parentMessageId: 'client-tool-msg' });
});
+ it('merges a result into a row the tool created, keeping the state it wrote', async () => {
+ // A background sub-agent writes its placeholder with `state.background`
+ // and returns only the start receipt; replacing the state dropped the flag,
+ // so the completion bridge never delivered the sub-agent's answer.
+ runTool.mockResolvedValueOnce({
+ attempts: 1,
+ result: { content: 'Started in the background.', executionTime: 5, success: true },
+ toolMessageId: 'background-placeholder',
+ });
+ const instruction: Extract<AgentInstruction, { type: 'call_tool' }> = {
+ payload: { parentMessageId: 'assistant-msg-1', toolCalling: createToolCall() },
+ type: 'call_tool',
+ };
+
+ await callTool(host)(instruction, createState());
+
+ expect(createToolMessage).not.toHaveBeenCalled();
+ expect(updateToolMessage).toHaveBeenCalledWith(
+ 'background-placeholder',
+ expect.objectContaining({
+ content: 'Started in the background.',
+ pluginState: {},
+ replacePluginState: false,
+ }),
+ );
+ });
+
+ it('replaces the state of a row the tool created when its result is withheld', async () => {
+ runTool.mockResolvedValueOnce({
+ attempts: 1,
+ result: { content: 'Withheld by policy.', success: false, state: { reason: 'denied' } },
+ resultBlocked: true,
+ toolMessageId: 'background-placeholder',
+ });
+ const instruction: Extract<AgentInstruction, { type: 'call_tool' }> = {
+ payload: { parentMessageId: 'assistant-msg-1', toolCalling: createToolCall() },
+ type: 'call_tool',
+ };
+
+ await callTool(host)(instruction, createState());
+
+ expect(updateToolMessage).toHaveBeenCalledWith(
+ 'background-placeholder',
+ expect.objectContaining({ pluginState: { reason: 'denied' }, replacePluginState: true }),
+ );
+ });
+
it('settles the existing row when the transport reports cancellation', async () => {
runTool.mockResolvedValueOnce({
attempts: 0,
diff --git a/packages/agent-runtime/src/executors/tool.ts b/packages/agent-runtime/src/executors/tool.ts
index 8e576e0d90d..7364b02ec8e 100644
--- a/packages/agent-runtime/src/executors/tool.ts
+++ b/packages/agent-runtime/src/executors/tool.ts
@@ -568,6 +568,7 @@ export const callTool =
if (!execution.resultPersisted) {
await updateExistingToolMessage({
host,
+ ownedByTransport: true,
result: executionResult,
toolMessageId,
resultBlocked: execution.resultBlocked,
@@ -924,6 +925,7 @@ export const callToolsBatch =
if (!execution.resultPersisted) {
await updateExistingToolMessage({
host,
+ ownedByTransport: true,
result: executionResult,
toolMessageId,
resultBlocked: execution.resultBlocked,
diff --git a/packages/agent-runtime/src/executors/toolPersistence.ts b/packages/agent-runtime/src/executors/toolPersistence.ts
index 1eb8802ea99..74d132b374a 100644
--- a/packages/agent-runtime/src/executors/toolPersistence.ts
+++ b/packages/agent-runtime/src/executors/toolPersistence.ts
@@ -131,24 +131,37 @@ export const createToolMessage = async ({
export const updateExistingToolMessage = async ({
host,
+ ownedByTransport,
result,
resultBlocked,
toolMessageId,
}: {
host: AgentRuntimeHost;
+ /**
+ * The transport handed this row back (`ToolRunExecution.toolMessageId`): it
+ * or the tool wrote the row's state during this call, and the result does not
+ * repeat it — a background sub-agent's placeholder holds the `background`
+ * flag its completion bridge and delivery look up. Merge into it instead of
+ * replacing. Rows the executor fills on its own (replayed or approval-resumed
+ * placeholders the transport did not return) keep the replace so their stale
+ * pending state does not survive.
+ */
+ ownedByTransport?: boolean;
result: ToolRunResult;
resultBlocked?: boolean;
toolMessageId: string;
}) => {
+ const blocked = isBlockedBeforeExecution(result) || resultBlocked === true;
try {
await host.transports.messages.updateToolMessage(toolMessageId, {
content: result.content,
metadata: toolResultMetadata(result),
pluginError: result.error ?? null,
pluginState: result.state ?? {},
- replacePluginState: true,
+ // A withheld result must not leave the original output in the state.
+ replacePluginState: !ownedByTransport || blocked,
});
- if (isBlockedBeforeExecution(result) || resultBlocked) {
+ if (blocked) {
await host.transports.messages.updateToolIntervention(toolMessageId, {
rejectedReason: result.state?.reason,
status: 'rejected',
diff --git a/packages/agent-runtime/src/executors/toolReplay.ts b/packages/agent-runtime/src/executors/toolReplay.ts
index 6bd591ccbc1..76c985d5a57 100644
--- a/packages/agent-runtime/src/executors/toolReplay.ts
+++ b/packages/agent-runtime/src/executors/toolReplay.ts
@@ -26,9 +26,15 @@ export const resolveToolReplay = async ({
throw new Error(`Cannot read tool result for ${toolMessageId}`);
}
- const pending =
- message.pluginState?.status === 'pending' || message.pluginIntervention?.status === 'pending';
const placeholder = !message.content || message.content === '...';
+ // A written result outranks a pending state: a tool that keeps working after
+ // it returns (a background sub-agent's start receipt) leaves `status: pending`
+ // on its row until it reports back, and running the call again would start
+ // that work a second time.
+ const resultWritten = !placeholder && typeof message.metadata?.toolExecutionTimeMs === 'number';
+ const pending =
+ (message.pluginState?.status === 'pending' && !resultWritten) ||
+ message.pluginIntervention?.status === 'pending';
if (
pending ||
(placeholder &&