π€― 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
π fix(agent): recover sub-agent bridge answer from isolation thread for hetero children (#18781)
LiJian3e7024f9c271
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.tsindex b2a38d9115d..80984b9f014 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts@@ -2454,6 +2454,73 @@ describe('AgentRuntimeService', () => {);});+ // Regression: same as completeSubAgentBridge's hetero case β a+ // heterogeneous isolated member never populates the coordinator's+ // runtime state at all, so `loadAgentState` genuinely resolves `null`.+ // Recover the real answer from the member's own isolation thread instead+ // of falling through to the "no textual answer" stub.+ it('single isolated member: recovers the answer from the isolation thread when the coordinator has no state at all (hetero)', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue(null);+ (service as any).messageModel.query.mockResolvedValue(+ buildPersistedToolChain('hello from the CLI'),+ );++ await service.completeGroupActionMember({+ anchorMessageId: 'grp-tool-1',+ expectedMembers: 1,+ groupToolMessageId: 'grp-tool-1',+ mode: 'isolated',+ onComplete: 'resume',+ operationId: 'child-1',+ parentOperationId: 'parent-1',+ reason: 'done',+ threadId: 'thread-1',+ });++ expect((service as any).messageModel.query).toHaveBeenCalledWith({ threadId: 'thread-1' });+ expect(updateToolMessage).toHaveBeenCalledWith(+ 'grp-tool-1',+ expect.objectContaining({ content: 'hello from the CLI' }),+ );+ });++ // Mirrors completeSubAgentBridge's identical Codex-flagged regression:+ // the thread fallback must be gated on `!finalState`, not merely an+ // empty `lastAssistantContent` β a real finalState whose last turn is+ // legitimately textless must keep the stub, not risk a stale earlier+ // reply from the thread's own history.+ it('single isolated member: does not query the thread when a real finalState already says the final turn is textless', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ ...memberState,+ messages: undefined,+ });+ (service as any).messageModel.query.mockResolvedValue(+ buildPersistedToolChain(+ JSON.stringify([{ image: 'https://example.com/image.png', type: 'image' }]),+ { isMultimodal: true },+ ),+ );+ const threadFallbackSpy = vi.spyOn(service as any, 'resolveLastAssistantContentFromThread');++ await service.completeGroupActionMember({+ anchorMessageId: 'grp-tool-1',+ expectedMembers: 1,+ groupToolMessageId: 'grp-tool-1',+ mode: 'isolated',+ onComplete: 'resume',+ operationId: 'child-1',+ parentOperationId: 'parent-1',+ reason: 'done',+ threadId: 'thread-1',+ });++ expect(threadFallbackSpy).not.toHaveBeenCalled();+ expect(updateToolMessage).toHaveBeenCalledWith(+ 'grp-tool-1',+ expect.objectContaining({ content: 'Agent member completed without a textual answer.' }),+ );+ });+it('multi-member: holds (no group-tool backfill, no resume) until the barrier is met', async () => {(service as any).serverDB.query = {messagePlugins: { findFirst: vi.fn() },@@ -2605,6 +2672,30 @@ describe('AgentRuntimeService', () => {);});+ // Regression: a heterogeneous (CLI-driven) child never populates the+ // coordinator's Redis-backed runtime state at all β `loadAgentState`+ // genuinely resolves `null` for it, unlike the standard-runtime case+ // above where it resolves a real (if message-stripped) state object.+ // Without a thread-scoped fallback this always fell through to "Sub-agent+ // completed without a textual answer.", even though the CLI produced a+ // real reply β because the webhook's `eventFields` deliberately excludes+ // `lastAssistantContent` (see `createSubAgentBridgeHook`) and hetero never+ // writes into the coordinator, so nothing else could ever supply it.+ it('recovers the answer from the isolation thread when the coordinator has no state at all (hetero)', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue(null);+ (service as any).messageModel.query.mockResolvedValue(+ buildPersistedToolChain('hello from the CLI'),+ );++ await service.completeSubAgentBridge(bridgeParams);++ expect((service as any).messageModel.query).toHaveBeenCalledWith({ threadId: 'thread-1' });+ expect(updateToolMessage).toHaveBeenCalledWith(+ 'tool-msg-1',+ expect.objectContaining({ content: 'hello from the CLI' }),+ );+ });+it('extracts a grouped final answer after webhook state is rehydrated from the DB', async () => {mockCoordinator.loadAgentState.mockResolvedValue({...childState,@@ -2665,6 +2756,36 @@ describe('AgentRuntimeService', () => {);});+ // Regression for a Codex review finding on the thread-fallback above: it+ // must be gated on `!finalState` (no authoritative state at all β the+ // heterogeneous case), not merely an empty `lastAssistantContent`.+ // Otherwise a REAL, authoritative finalState whose last turn is+ // legitimately textless would still trigger the thread re-query, and a+ // lagging read that surfaces an EARLIER real reply from the same thread+ // would silently show stale text instead of the correct empty-answer+ // stub.+ it('does not query the thread when a real finalState already says the final turn is textless', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ ...childState,+ messages: undefined,+ });+ (service as any).messageModel.query.mockResolvedValue(+ buildPersistedToolChain(+ JSON.stringify([{ image: 'https://example.com/image.png', type: 'image' }]),+ { isMultimodal: true },+ ),+ );+ const threadFallbackSpy = vi.spyOn(service as any, 'resolveLastAssistantContentFromThread');++ await service.completeSubAgentBridge(bridgeParams);++ expect(threadFallbackSpy).not.toHaveBeenCalled();+ expect(updateToolMessage).toHaveBeenCalledWith(+ 'tool-msg-1',+ expect.objectContaining({ content: 'Sub-agent completed without a textual answer.' }),+ );+ });+it('extracts text parts from the grouped final assistant content', async () => {await service.completeSubAgentBridge({...bridgeParams,diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.tsindex 3d12892a3b5..9f49538b2a8 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts@@ -2902,7 +2902,31 @@ export class AgentRuntimeService {}const messages = Array.isArray(finalState?.messages) ? finalState.messages : [];lastAssistant ??= findLastAssistantMessage(normalizeCompletionMessages(messages));- const lastAssistantContent = extractTextFromMessage(lastAssistant);+ let lastAssistantContent = extractTextFromMessage(lastAssistant);++ // Gated on `!finalState`, not merely an empty `lastAssistantContent`: a+ // real (authoritative) final state whose last turn is legitimately+ // textless (image-only, or the "preserve an empty leaf" case in+ // `normalizeCompletionMessages`) must keep the stub below, not go dig+ // through the thread's own message history β a lagging read could+ // surface an EARLIER real reply from the same thread and silently show+ // stale text instead of the correct empty-answer signal. `!finalState`+ // is exactly the case this fallback exists for: heterogeneous (CLI-driven)+ // children never populate it at all (see+ // `resolveLastAssistantContentFromThread`'s doc comment), so there is no+ // authoritative signal here to override.+ if (!failed && !finalState && threadId) {+ try {+ lastAssistantContent = await this.resolveLastAssistantContentFromThread(threadId);+ } catch (error) {+ console.error(+ '[%s] sub-agent bridge: failed to resolve content from thread %s: %O',+ operationId,+ threadId,+ error,+ );+ }+ }const errorReason = failed ? formatSubAgentErrorReason(finalState?.error) : undefined;const content = failed? errorReason@@ -3096,7 +3120,27 @@ export class AgentRuntimeService {}const messages = Array.isArray(finalState?.messages) ? finalState.messages : [];lastAssistant ??= findLastAssistantMessage(normalizeCompletionMessages(messages));- const lastAssistantContent = extractTextFromMessage(lastAssistant);+ let lastAssistantContent = extractTextFromMessage(lastAssistant);++ // Gated on `!finalState`, not merely an empty `lastAssistantContent` β+ // see the identical guard (and its full rationale) in+ // `completeSubAgentBridge`. A real final state whose last turn is+ // legitimately textless must keep the stub below, not risk surfacing a+ // stale earlier reply from the thread's own history. `!finalState` is+ // exactly the heterogeneous-isolated-member case this fallback exists+ // for: it never populates `finalState` at all.+ if (!failed && mode !== 'in_group' && !finalState && threadId) {+ try {+ lastAssistantContent = await this.resolveLastAssistantContentFromThread(threadId);+ } catch (error) {+ console.error(+ '[%s] group-member bridge: failed to resolve content from thread %s: %O',+ operationId,+ threadId,+ error,+ );+ }+ }const agentLabel = (finalState?.metadata?.agentId as string | undefined) ?? 'member';const memberErrorReason = failed ? formatSubAgentErrorReason(finalState?.error) : undefined;const anchorContent = failed@@ -3307,6 +3351,31 @@ export class AgentRuntimeService {);}+ /**+ * Fallback content resolution for a heterogeneous (CLI-driven) sub-agent+ * child in queue mode. `coordinator.loadAgentState`/`finalState` is always+ * empty here: a hetero run never writes into the Redis-backed runtime state+ * this class's step loop maintains (only `saveAgentState` calls under the+ * homogeneous step loop populate it), and the completion webhook's+ * `eventFields` deliberately excludes `lastAssistantContent` to keep the+ * QStash payload lean (see `createSubAgentBridgeHook`'s doc comment) β+ * `heteroFinish` already resolves the real answer server-side before+ * dispatching, but that resolution never reaches this callback.+ *+ * The child's own conversation is queryable directly by its isolation+ * `threadId` regardless β the same source `heteroFinish` itself reads via+ * `heteroCurrentMsgId` before completion. Scoping by `threadId` alone is+ * sufficient: thread ids are unique, so no `agentId`/`topicId` is needed to+ * disambiguate.+ */+ private async resolveLastAssistantContentFromThread(+ threadId: string,+ ): Promise<string | undefined> {+ const messages = await this.messageModel.query({ threadId });+ const lastAssistant = findLastAssistantMessage(normalizeCompletionMessages(messages));+ return extractTextFromMessage(lastAssistant) || undefined;+ }+/*** Overwrite `state.messages` in place with the canonical DB conversation at* step entry, making the DB the single source of truth for messages.