π€― 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): keep the group-builder editing target across intervention continuations (#20626)
Arvin Xu2ce186d6df56
diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIntervention.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIntervention.test.tsindex c7a04e2a420..336f3a5e61b 100644--- a/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIntervention.test.ts+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIntervention.test.ts@@ -1148,6 +1148,113 @@ describe('aiAgentRouter β remote Human-in-the-loop', () => {});});+ // The router's contract is pass-through: it forwards the claimed runtime+ // action's appContext verbatim plus the parked operation id+ // (`approvalSourceOperationId`). The Group Agent Builder target inheritance+ // itself lives in the service pipeline β see+ // `startOperation.editingGroupId.test.ts` (Codex P1 on #20626: a bare+ // execAgent mock never reaches that enrichment, so asserting an inherited+ // value here was both failing and vacuous).+ describe('group builder editing target forwarding', () => {+ const execution = {+ autoStarted: true,+ messageId: 'assistant-continuation-group',+ operationId: 'operation-continuation-group',+ success: true,+ };++ const resolveGroupContinuation = async (params: {+ appContext?: Record<string, unknown>;+ resolutionRequestId: string;+ sourceOperationId: string;+ }) => {+ await insertPendingTool({+ batchId: `batch-${params.sourceOperationId}`,+ messageId: 'assistant-runtime',+ operationId: params.sourceOperationId,+ toolCallId: 'tool-runtime',+ });+ businessV2.resolveAgentIntervention.mockResolvedValueOnce({+ claimId: `claim-${params.sourceOperationId}`,+ contractVersion: 2,+ handled: true,+ ownerUserId: userId,+ resolutionRequestId: params.resolutionRequestId,+ runtimeAction: {+ agentId: 'agt_group_builder',+ appContext: params.appContext ?? { topicId: 'topic-runtime' },+ content: '{"answer":"A"}',+ operationId: params.sourceOperationId,+ outcome: 'submitted',+ parentMessageId: 'assistant-runtime',+ toolCallId: 'tool-runtime',+ type: 'resume_tool_result',+ },+ state: 'claimed',+ });+ aiAgentService.execAgent.mockResolvedValueOnce(execution);++ await userCaller().resolveAgentIntervention({+ action: { itemId: 'item-runtime', type: 'skip_interaction' },+ expectedBatchVersion: 1,+ expectedRequestRevisions: {+ 'item-runtime': { hash: 'c'.repeat(64), version: 1 },+ },+ resolutionRequestId: params.resolutionRequestId,+ reviewToken: 'h'.repeat(43),+ });+ };++ const execCallFor = () =>+ aiAgentService.execAgent.mock.calls.find(+ ([input]) => input?.appContext?.topicId === 'topic-runtime',+ );++ it('forwards the appContext verbatim and names the parked operation for the service to enrich', async () => {+ const sourceOperationId = 'operation-group-source';+ await insertOperation(sourceOperationId, userId);++ await resolveGroupContinuation({+ resolutionRequestId: '018fbd8e-7baf-7c6d-8000-000000000051',+ sourceOperationId,+ });++ const call = execCallFor();+ expect(call?.[0]?.appContext).toEqual({ topicId: 'topic-runtime' });+ expect(call?.[0]?.approvalSourceOperationId).toBe(sourceOperationId);+ });++ it('never injects an editing group at the router boundary (ordinary topic)', async () => {+ const sourceOperationId = 'operation-plain-source';+ await insertOperation(sourceOperationId, userId);++ await resolveGroupContinuation({+ resolutionRequestId: '018fbd8e-7baf-7c6d-8000-000000000052',+ sourceOperationId,+ });++ expect(execCallFor()?.[0]?.appContext).not.toHaveProperty('editingGroupId');+ });++ it('passes a request-named editing group through without rewriting it', async () => {+ const sourceOperationId = 'operation-group-explicit';+ await insertOperation(sourceOperationId, userId);++ await resolveGroupContinuation({+ appContext: { editingGroupId: 'cg_panel', topicId: 'topic-runtime' },+ resolutionRequestId: '018fbd8e-7baf-7c6d-8000-000000000053',+ sourceOperationId,+ });++ const call = execCallFor();+ expect(call?.[0]?.appContext).toEqual({+ editingGroupId: 'cg_panel',+ topicId: 'topic-runtime',+ });+ expect(call?.[0]?.approvalSourceOperationId).toBe(sourceOperationId);+ });+ });+it('retries only the published transition after runtime dispatch already settled the source', async () => {const reviewToken = 'f'.repeat(43);const messageId = 'message-published-retry';diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.tsindex 9c7aad543f2..318f66ebe91 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.ts@@ -117,6 +117,11 @@ export async function createOperation(defaultTaskAssigneeAgentId: appContext?.defaultTaskAssigneeAgentId,documentId: appContext?.documentId,editingAgentId: appContext?.editingAgentId,+ // The Group Agent Builder target must survive on the durable row: an+ // intervention continuation rebuilds its app context from this row+ // (never from client input), and a topic whose metadata predates the+ // `editingGroupId` stamp has nothing else to recover it from.+ editingGroupId: appContext?.editingGroupId,groupId: appContext?.groupId,scope: appContext?.scope,sessionId: appContext?.sessionId,diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/index.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/index.tsindex 9b8588ab160..f319178600a 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/index.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/index.ts@@ -69,6 +69,7 @@ import {acceptsFileWorks,acceptsMemberRuntimeEnd,controlCompletedToolResult,+ getOperationEditingGroupId,getOperationStatus,injectQueuedFollowUp,interruptOperation,@@ -381,6 +382,10 @@ export class AgentRuntimeService {return acceptsMemberRuntimeEnd(this.context, ...args);}+ getOperationEditingGroupId(...args: MethodArgs<typeof getOperationEditingGroupId>) {+ return getOperationEditingGroupId(this.context, ...args);+ }+setQueuedMessages(...args: MethodArgs<typeof setQueuedMessages>) {return setQueuedMessages(this.context, ...args);}diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/operationControl.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/operationControl.tsindex d2b4cbb023d..1a3bf6ce503 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/operationControl.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/operationControl.ts@@ -223,6 +223,29 @@ export async function acceptsMemberRuntimeEnd(return metadata?.acceptsMemberRuntimeEnd === true;}+/**+ * The Group Agent Builder target frozen on the durable operation row.+ *+ * An intervention continuation rebuilds its app context from server-side+ * evidence (never client input), and `state.origin` expires with the runtime+ * snapshot. The row is the only durable copy β older topics may lack+ * `topics.metadata.editingGroupId`, so without it the resumed member tools+ * answer `NoGroupContext`.+ */+export async function getOperationEditingGroupId(+ deps: OperationControlDeps,+ operationId: string,+): Promise<string | undefined> {+ try {+ const row = await deps.agentOperationModel.findById(operationId);+ const value = row?.appContext?.editingGroupId;+ return typeof value === 'string' && value ? value : undefined;+ } catch (error) {+ log('[%s] Failed to read the editing group target: %O', operationId, error);+ return undefined;+ }+}+/*** Record whether the client still holds user messages queued behind a run.* Only the run's owner may flag it; an unknown or foreign operation is adiff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.tsindex 0333b013f02..21fcd4fcc32 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts@@ -155,6 +155,7 @@ vi.mock('@/server/services/agentRuntime', () => ({acceptsFileWorks: vi.fn().mockResolvedValue(false),acceptsMemberRuntimeEnd: vi.fn().mockResolvedValue(false),getLlmExecutor: vi.fn().mockResolvedValue(undefined),+ getOperationEditingGroupId: vi.fn().mockResolvedValue(undefined),completeGroupActionMember: mockCompleteGroupActionMember,createOperation: mockCreateOperation,ensureInterventionContinuationStarted: mockEnsureInterventionContinuationStarted,diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.editingGroupId.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.editingGroupId.test.tsnew file mode 100644index 00000000000..085774b0de7--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.editingGroupId.test.ts@@ -0,0 +1,142 @@+import { describe, expect, it, vi } from 'vitest';++import { startOperation } from '../startOperation';++vi.mock('@/libs/trpc/utils/internalJwt', () => ({+ signUserJWT: vi.fn().mockResolvedValue('jwt'),+}));++// Codex P1 on #20626: the router-level test mocked `AiAgentService.execAgent`+// as a bare object, so the enrichment in this pipeline stage never ran and the+// assertions there were vacuous. These cases exercise the real inheritance+// implementation: the Group Agent Builder target is read back from the parked+// operation's durable row and merged into the continuation's appContext.+describe('startOperation βΊ group builder editing target inheritance', () => {+ const setup = (durableEditingGroupId?: string) => {+ const calls: string[] = [];+ const agentRuntimeService = {+ acceptsFileWorks: vi.fn(async () => true),+ acceptsMemberRuntimeEnd: vi.fn(async () => true),+ createOperation: vi.fn(async () => ({ autoStarted: true, messageId: 'msg-assistant' })),+ getLlmExecutor: vi.fn(async () => undefined),+ getOperationEditingGroupId: vi.fn(async () => {+ calls.push('read-group-target');+ return durableEditingGroupId;+ }),+ };+ const deps = {+ agentRuntimeService,+ messageModel: {},+ retirePendingApprovalOperation: vi.fn(async () => {+ calls.push('retire-source');+ }),+ topicModel: { updateMetadata: vi.fn() },+ userId: 'user-1',+ withholdGatewayToken: true,+ } as any;+ const ctx = {+ agentConfig: {},+ assistantMessageId: 'msg-assistant',+ model: 'gpt',+ provider: 'openai',+ resolvedAgentId: 'agt-supervisor',+ topicId: 'tpc-1',+ userMessageId: 'msg-user',+ } as any;+ const input = (extra: Record<string, unknown>) =>+ ({+ approvalClaim: {},+ approvalSourceToolMessageIds: [],+ autoStart: true,+ discovery: {+ credentialFactsPromise: Promise.resolve(undefined),+ modelMediaCapabilities: {},+ toolsResult: { enabledToolIds: [] },+ },+ initialContext: {},+ operationId: 'op-new',+ prep: { allMessages: [], deviceSystemInfo: {} },+ updateAbortedAssistantMessage: vi.fn(),+ userInterventionConfig: { approvalMode: 'manual' },+ ...extra,+ }) as any;+ return { agentRuntimeService, calls, ctx, deps, input };+ };++ it('recovers the parked run editing group when the request names none', async () => {+ const { agentRuntimeService, ctx, deps, input } = setup('cg_edited');++ await startOperation(+ deps,+ ctx,+ input({+ approvalSourceOperationId: 'op-parked',+ initialContext: { appContext: { topicId: 'tpc-1' } },+ }),+ );++ expect(agentRuntimeService.getOperationEditingGroupId).toHaveBeenCalledWith('op-parked');+ expect(agentRuntimeService.createOperation).toHaveBeenCalledWith(+ expect.objectContaining({+ appContext: expect.objectContaining({ editingGroupId: 'cg_edited' }),+ }),+ );+ // Read before the parked operation is retired.+ });++ it('lets the parked target win without overwriting a request-named group', async () => {+ const { agentRuntimeService, ctx, deps, input } = setup('cg_edited');+ const groupCtx = {+ ...ctx,+ appContext: { editingGroupId: 'cg_panel', scope: 'group_agent_builder' },+ };++ await startOperation(deps, groupCtx, input({ approvalSourceOperationId: 'op-parked' }));++ expect(agentRuntimeService.createOperation).toHaveBeenCalledWith(+ expect.objectContaining({+ appContext: expect.objectContaining({ editingGroupId: 'cg_panel' }),+ }),+ );+ });++ it('keeps a continuation without a durable group target unchanged (ordinary topic)', async () => {+ const { agentRuntimeService, ctx, deps, input } = setup(undefined);++ await startOperation(+ deps,+ ctx,+ input({+ approvalSourceOperationId: 'op-parked',+ initialContext: { appContext: { topicId: 'tpc-1' } },+ }),+ );++ expect(agentRuntimeService.createOperation).toHaveBeenCalledWith(+ expect.objectContaining({+ appContext: expect.not.objectContaining({ editingGroupId: expect.anything() }),+ }),+ );+ });++ it('does not consult the durable row when there is no approval source', async () => {+ const { agentRuntimeService, ctx, deps, input } = setup('cg_edited');++ await startOperation(deps, ctx, input({}));++ expect(agentRuntimeService.getOperationEditingGroupId).not.toHaveBeenCalled();+ expect(agentRuntimeService.createOperation).toHaveBeenCalledWith(+ expect.objectContaining({+ appContext: expect.not.objectContaining({ editingGroupId: expect.anything() }),+ }),+ );+ });++ it('reads the durable target before retiring the parked operation', async () => {+ const { calls, ctx, deps, input } = setup('cg_edited');++ await startOperation(deps, ctx, input({ approvalSourceOperationId: 'op-parked' }));++ expect(calls.indexOf('read-group-target')).toBeLessThan(calls.indexOf('retire-source'));+ });+});diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.memberRuntimeEnd.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.memberRuntimeEnd.test.tsindex 71eb14a2f14..850811b0d67 100644--- a/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.memberRuntimeEnd.test.ts+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.memberRuntimeEnd.test.ts@@ -21,6 +21,7 @@ const setup = (sourceAccepts: boolean) => {calls.push('read-executor');return sourceExecutor;}),+ getOperationEditingGroupId: vi.fn(async () => undefined),};const deps = {agentRuntimeService,diff --git a/apps/server/src/services/aiAgent/pipeline/startOperation.ts b/apps/server/src/services/aiAgent/pipeline/startOperation.tsindex a1a3878047f..fffee15424a 100644--- a/apps/server/src/services/aiAgent/pipeline/startOperation.ts+++ b/apps/server/src/services/aiAgent/pipeline/startOperation.ts@@ -179,6 +179,15 @@ export const startOperation = async ((approvalSourceOperationId? await deps.agentRuntimeService.acceptsFileWorks(approvalSourceOperationId): undefined);+ // The Group Agent Builder target is server state captured on the parked+ // operation row. A continuation is the SAME builder conversation: it must+ // re-bind to the edited group instead of relying on the resumed topic's+ // `metadata.editingGroupId`, which older topics never received β the member+ // tools would then answer `No active group found`. Never trusted from the+ // resolving client; read back from the durable row.+ const inheritedEditingGroupId = approvalSourceOperationId+ ? await deps.agentRuntimeService.getOperationEditingGroupId(approvalSourceOperationId)+ : undefined;const result = await deps.agentRuntimeService.createOperation({acceptsFileWorks: fileWorksAccepted,acceptsMemberRuntimeEnd: memberRuntimeEndAccepted,@@ -260,7 +269,14 @@ export const startOperation = async (// owned by the builtin builder agent, so the edited group only rides// here. Read by the group-agent-builder server runtime and by the// `<current_group_context>` injector.- ...(editingGroupId ? { editingGroupId } : {}),+ //+ // An intervention continuation arrives without the group (the parked+ // run's client is gone), so the parked operation's durable target+ // stands in β the same inheritance `fileWorks` / `memberRuntimeEnd`+ // already use. An explicit request value always wins.+ ...(editingGroupId || inheritedEditingGroupId+ ? { editingGroupId: editingGroupId ?? inheritedEditingGroupId }+ : {}),// Run-scoped Agent Signal marker for background self-iteration / memory// runs β lands in state.origin.signal so the completion path can// project receipts/briefs. Undefined for ordinary chat runs.diff --git a/packages/business-server/src/agent-run/agentInterventionReview.ts b/packages/business-server/src/agent-run/agentInterventionReview.tsindex 4ef28663a88..9ae9850dfa2 100644--- a/packages/business-server/src/agent-run/agentInterventionReview.ts+++ b/packages/business-server/src/agent-run/agentInterventionReview.ts@@ -320,6 +320,13 @@ export interface AgentInterventionRuntimeAppContext {* resumes with no target (the run is owned by the builder itself).*/editingAgentId?: string;+ /**+ * The group a Group Agent Builder run edits. Without it a `group_agent_builder`+ * continuation falls back to `topics.metadata.editingGroupId`, which older+ * topics never received β the member tools then answer `NoGroupContext`.+ * Cloud rebuilds it from the parked operation's durable row.+ */+ editingGroupId?: string;groupId?: string | null;scope?: MessageMapScope;sessionId?: string;diff --git a/packages/database/src/schemas/agentOperations.ts b/packages/database/src/schemas/agentOperations.tsindex dc42eb00f06..7d1fdcd1a49 100644--- a/packages/database/src/schemas/agentOperations.ts+++ b/packages/database/src/schemas/agentOperations.ts@@ -31,6 +31,8 @@ export interface AgentOperationAppContext {documentId?: string | null;/** The agent a builder run edits (scope `agent_builder`); the run itself is owned by the builder. */editingAgentId?: string;+ /** The group a Group Agent Builder run edits; recovered by intervention continuations. */+ editingGroupId?: string;groupId?: string | null;scope?: string | null;sessionId?: string;