π€― 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(group): enforce builder config access and member tool approval in gateway mode (stack L1: G-01, G-05) (#20093)
Arvin Xufc7e08a6146e
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.groupMember.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.groupMember.test.tsindex 40e30350f48..ea1b7d1c685 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.groupMember.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.groupMember.test.ts@@ -1,6 +1,8 @@-import { describe, expect, it } from 'vitest';+import type { AgentState } from '@lobechat/agent-runtime';+import { describe, expect, it, vi } from 'vitest';-import { resolveGroupMemberId } from '../executorHelpers';+import type { RuntimeExecutorContext } from '../context';+import { buildServerAgentMemberRunner, resolveGroupMemberId } from '../executorHelpers';describe('resolveGroupMemberId', () => {const agentMap = {@@ -25,3 +27,100 @@ describe('resolveGroupMemberId', () => {).toBe('Assistant');});});++// G-05: the member runner hands the supervisor run's approval policy to every+// forked member instead of letting them fall back to headless.+describe('buildServerAgentMemberRunner', () => {+ it('forwards the supervisor approval policy to each member', async () => {+ const execGroupMember = vi.fn().mockResolvedValue({ operationId: 'op-m', started: true });+ const ctx = {+ execGroupMember,+ messageModel: {+ create: vi.fn().mockResolvedValue({ id: 'group-tool-1' }),+ updateToolMessage: vi.fn(),+ },+ operationId: 'op-sup',+ topicId: 'topic-1',+ } as unknown as RuntimeExecutorContext;+ const state = {+ origin: { agentId: 'agt_sup', groupId: 'group-1', topicId: 'topic-1' },+ principal: { policy: { userIntervention: { approvalMode: 'manual' } } },+ } as unknown as AgentState;++ const runner = buildServerAgentMemberRunner(+ ctx,+ state,+ { apiName: 'speak', arguments: '{}', id: 'call_1', identifier: 'x', type: 'builtin' },+ 'sup-msg-1',+ );+ await runner!.run({+ members: [{ agentId: 'agt_carol', instruction: 'go' }],+ mode: 'in_group',+ onComplete: 'resume',+ });++ expect(execGroupMember).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: 'agt_carol',+ parentOperationId: 'op-sup',+ userInterventionConfig: { approvalMode: 'manual' },+ }),+ );+ });++ // An approved group tool resumes on its own pending row (`call_tool` with+ // `skipCreateToolMessage`). Writing a second row with the same tool_call_id+ // under it rendered as an orphan skill call with a delete button.+ it('reuses the approved pending tool row instead of writing a duplicate', async () => {+ const execGroupMember = vi.fn().mockResolvedValue({ operationId: 'op-m', started: true });+ const messageModel = {+ create: vi.fn().mockResolvedValue({ id: 'new-row' }),+ findById: vi.fn().mockResolvedValue({ id: 'approved-tool', parentId: 'sup-msg-1' }),+ updateMetadata: vi.fn(),+ updatePluginState: vi.fn(),+ updateToolMessage: vi.fn(),+ };+ const ctx = {+ execGroupMember,+ messageModel,+ operationId: 'op-sup',+ topicId: 'topic-1',+ } as unknown as RuntimeExecutorContext;+ const state = {+ origin: { agentId: 'agt_sup', groupId: 'group-1', topicId: 'topic-1' },+ } as unknown as AgentState;++ const runner = buildServerAgentMemberRunner(+ ctx,+ state,+ {+ apiName: 'executeAgentTask',+ arguments: '{}',+ id: 'call_1',+ identifier: 'lobe-group-management',+ type: 'builtin',+ },+ 'approved-tool',+ 'approved-tool',+ );+ await runner!.run({+ members: [{ agentId: 'agt_carol', instruction: 'go' }],+ mode: 'isolated',+ onComplete: 'resume',+ });++ expect(messageModel.create).not.toHaveBeenCalled();+ expect(messageModel.updatePluginState).toHaveBeenCalledWith('approved-tool', {+ expectedMembers: 1,+ onComplete: 'resume',+ status: 'pending',+ });+ expect(execGroupMember).toHaveBeenCalledWith(+ expect.objectContaining({+ anchorMessageId: 'approved-tool',+ groupToolMessageId: 'approved-tool',+ supervisorMessageId: 'sup-msg-1',+ }),+ );+ });+});diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.tsindex 9b62fd646ab..15bf4930593 100644--- a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts@@ -225,6 +225,7 @@ export class ServerToolTransport implements ToolTransport {context.state,chatToolPayload,context.parentMessageId,+ context.reuseExistingMessage ? context.toolMessageId : undefined,),// Share-visitor marker: lets `BuiltinToolsExecutor.execute`// re-apply the share data-tool gate at the actual dispatch site.diff --git a/apps/server/src/modules/AgentRuntime/executorHelpers.ts b/apps/server/src/modules/AgentRuntime/executorHelpers.tsindex 1d6bb5f3d29..3101fcaa174 100644--- a/apps/server/src/modules/AgentRuntime/executorHelpers.ts+++ b/apps/server/src/modules/AgentRuntime/executorHelpers.ts@@ -1,4 +1,4 @@-import { type AgentState } from '@lobechat/agent-runtime';+import { type AgentState, selectUserInterventionConfig } from '@lobechat/agent-runtime';import { LobeActivatorIdentifier } from '@lobechat/builtin-tool-activator';import { dispatchWorkRegistrationIntent } from '@lobechat/builtin-tools/workRegistration';import { getSubAgentChatConfigOverride, resolveSubAgentModel } from '@lobechat/const';@@ -392,6 +392,13 @@ export const buildServerAgentMemberRunner = (state: AgentState,chatToolPayload: ChatToolPayload,parentMessageId: string,+ /**+ * The call's own pending tool row when it resumes after a human approval+ * (`call_tool` with `skipCreateToolMessage`, where `parentMessageId` is that+ * row). Reused as the group tool message instead of writing a second row+ * with the same `tool_call_id` under it.+ */+ existingToolMessageId?: string,): ServerAgentMemberRunner | undefined => {// Same share-visitor fail-close as `buildServerVirtualSubAgentRunner`:// member runs would not inherit the parent's shareGate.@@ -427,19 +434,35 @@ export const buildServerAgentMemberRunner = (// 1. Group tool placeholder β the parked tool call the supervisor op waits// on. Stamped with the barrier target + finish disposition so the resume// path (and verify watchdog) resolve resume-vs-finish on their own.- const groupTool = await ctx.messageModel.create({- agentId,- content: '',- groupId,- ...(isCouncil ? { metadata: { agentCouncil: true } } : {}),- parentId: parentMessageId,- plugin: chatToolPayload as any,- pluginState: { expectedMembers, onComplete, status: 'pending' },- role: 'tool',- threadId: state.origin?.threadId,- tool_call_id: chatToolPayload.id,- topicId,- });+ const existingToolMessage = existingToolMessageId+ ? await ctx.messageModel.findById(existingToolMessageId)+ : undefined;+ // The supervisor assistant message owning this tool call. An approved+ // call resumes with its own tool row as the parent, so step up from it.+ const supervisorMessageId = existingToolMessage?.parentId ?? parentMessageId;+ const groupTool = existingToolMessage+ ? { id: existingToolMessage.id }+ : await ctx.messageModel.create({+ agentId,+ content: '',+ groupId,+ ...(isCouncil ? { metadata: { agentCouncil: true } } : {}),+ parentId: parentMessageId,+ plugin: chatToolPayload as any,+ pluginState: { expectedMembers, onComplete, status: 'pending' },+ role: 'tool',+ threadId: state.origin?.threadId,+ tool_call_id: chatToolPayload.id,+ topicId,+ });+ if (existingToolMessage) {+ await ctx.messageModel.updatePluginState(groupTool.id, {+ expectedMembers,+ onComplete,+ status: 'pending',+ });+ if (isCouncil) await ctx.messageModel.updateMetadata(groupTool.id, { agentCouncil: true });+ }// 2. Per-member anchors. A single member collapses onto the group tool// message; multiple members each get a child anchor under it. These@@ -488,9 +511,10 @@ export const buildServerAgentMemberRunner = (parentOperationId: ctx.operationId,// The supervisor assistant message owning this tool call β council// members parent their response here (siblings of the council tool).- supervisorMessageId: parentMessageId,+ supervisorMessageId,timeout,topicId,+ userInterventionConfig: selectUserInterventionConfig(state),});if (result?.started) {startedCount += 1;@@ -523,7 +547,10 @@ export const buildServerAgentMemberRunner = (// None started β no bridge will ever fire, so tear down the placeholders// and let the caller surface an inline tool error instead of parking.if (startedCount === 0) {+ // A reused approved row is the call's own record β the caller writes+ // the inline error into it, so only drop what this run created.for (const id of new Set([...anchorIds, groupTool.id])) {+ if (id === existingToolMessage?.id) continue;try {// Runtime placeholder cleanup β see the sub-agent runner above.await ctx.messageModel.deleteMessage(id, { includeShareVisitor: true });diff --git a/apps/server/src/routers/lambda/_helpers/groupMemberContinuationResult.test.ts b/apps/server/src/routers/lambda/_helpers/groupMemberContinuationResult.test.tsnew file mode 100644index 00000000000..2e15442a470--- /dev/null+++ b/apps/server/src/routers/lambda/_helpers/groupMemberContinuationResult.test.ts@@ -0,0 +1,41 @@+import type { ExecAgentResult } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { toClientExecAgentResult } from './groupMemberContinuationResult';++const base = {+ agentId: 'agt_carol',+ assistantMessageId: 'msg-1',+ autoStarted: true,+ createdAt: '2026-09-28T00:00:00.000Z',+ message: 'ok',+ operationId: 'op-member-continuation',+ status: 'created',+ success: true,+ timestamp: '2026-09-28T00:00:00.000Z',+ topicId: 'tpc-1',+ userMessageId: 'msg-user-1',+} satisfies ExecAgentResult;++// Codex P1 on #20093: a client released before member continuations took the+// returned operationId as the topic's new run, dropping the supervisor's stream.+describe('toClientExecAgentResult', () => {+ it("names the supervisor's run for a member continuation and keeps the member op aside", () => {+ expect(+ toClientExecAgentResult({+ ...base,+ groupMemberContinuation: true,+ supervisorOperationId: 'op-supervisor',+ }),+ ).toEqual({+ ...base,+ groupMemberContinuation: true,+ memberOperationId: 'op-member-continuation',+ operationId: 'op-supervisor',+ });+ });++ it('passes every other result through unchanged', () => {+ expect(toClientExecAgentResult(base)).toEqual(base);+ });+});diff --git a/apps/server/src/routers/lambda/_helpers/groupMemberContinuationResult.ts b/apps/server/src/routers/lambda/_helpers/groupMemberContinuationResult.tsnew file mode 100644index 00000000000..f265050d8a6--- /dev/null+++ b/apps/server/src/routers/lambda/_helpers/groupMemberContinuationResult.ts@@ -0,0 +1,24 @@+import type { ExecAgentResult } from '@lobechat/types';++/**+ * Client-facing shape of an `execAgent` result.+ *+ * A group member's approval continuation runs under the supervisor's run, and+ * the supervisor keeps the topic and its stream. Clients released before that+ * existed take any returned `operationId` as the topic's new run: they replace+ * the topic marker and drop the supervisor's socket, losing the supervisor's+ * closing. So the response names the supervisor's run as `operationId` (safe+ * for those clients: they keep following it) and carries the member's+ * continuation as `memberOperationId` for clients that understand+ * `groupMemberContinuation`. Every other result passes through unchanged.+ */+export const toClientExecAgentResult = <T extends ExecAgentResult>(result: T): T => {+ const { supervisorOperationId, ...rest } = result;+ if (!result.groupMemberContinuation || !supervisorOperationId) return rest as T;++ return {+ ...rest,+ memberOperationId: result.operationId,+ operationId: supervisorOperationId,+ } as T;+};diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.tsindex ffc96d53262..e1b5204dac6 100644--- a/apps/server/src/routers/lambda/aiAgent.ts+++ b/apps/server/src/routers/lambda/aiAgent.ts@@ -81,6 +81,7 @@ import {assertCanUseTopicTargets,assertCanViewMessageTargets,} from '@/server/routers/lambda/_helpers/conversationResourceGuard';+import { toClientExecAgentResult } from '@/server/routers/lambda/_helpers/groupMemberContinuationResult';import { assertCanUseWorkspaceAgent } from '@/server/routers/lambda/_helpers/workspaceAgentGuard';import {GetAgentInterventionReviewBySourceSchema,@@ -2388,12 +2389,12 @@ export const aiAgentRouter = router({if (!dispatch.execution) {throw new Error('Durable intervention resume did not create an operation');}- return dispatch.execution;+ return toClientExecAgentResult(dispatch.execution);}}}- return await ctx.aiAgentService.execAgent({+ const result = await ctx.aiAgentService.execAgent({agentId,appContext,autoStart,@@ -2428,6 +2429,7 @@ export const aiAgentRouter = router({userAgent: ctx.userAgent ?? undefined,userInterventionConfig,});+ return toClientExecAgentResult(result);} catch (error: any) {console.error('execAgent failed: %O', error);@@ -3484,7 +3486,7 @@ export const aiAgentRouter = router({return {contractVersion: 2 as const,...(resolution.conversationUrl && { conversationUrl: resolution.conversationUrl }),- ...(dispatch.execution && { execution: dispatch.execution }),+ ...(dispatch.execution && { execution: toClientExecAgentResult(dispatch.execution) }),state: resolution.state,status: dispatch.status,success: true as const,diff --git a/apps/server/src/routers/lambda/topic.ts b/apps/server/src/routers/lambda/topic.tsindex c6dfb33918e..92ff2217fd8 100644--- a/apps/server/src/routers/lambda/topic.ts+++ b/apps/server/src/routers/lambda/topic.ts@@ -1114,7 +1114,12 @@ export const topicRouter = router({// Same visitor guard as `batchMoveTopics`/`cloneTopic` above.await assertCreatorTopicTargets(guardCtx(ctx), [input.id]);- return ctx.topicModel.settleRunningOperation(input.id, input.operationId, input.status);+ // Client-reported end: never clear the marker of a run the server is still+ // driving (an early / mirrored terminal event would otherwise drop the+ // supervisor's topic reservation mid group turn).+ return ctx.topicModel.settleRunningOperation(input.id, input.operationId, input.status, {+ rejectInFlightOperation: true,+ });}),});diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.tsindex 2e53facdaae..556d89d8955 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts@@ -602,6 +602,68 @@ describe('AgentRuntimeService', () => {}});+ // Codex P1 on #20093: the member bridge lived only in the 2h runtime+ // snapshot, so a late approval continued the supervisor instead.+ it("keeps a durable copy of a group member's completion bridge on the row", async () => {+ const recordStart = vi+ .spyOn(AgentOperationModel.prototype, 'recordStart')+ .mockResolvedValue(undefined);+ const bridge = {+ anchorMessageId: 'msg-speak',+ expectedMembers: 1,+ groupToolMessageId: 'msg-speak',+ mode: 'in_group',+ onComplete: 'resume',+ parentOperationId: 'op-supervisor',+ };++ await service.createOperation({+ ...mockParams,+ hooks: [+ {+ handler: vi.fn(),+ id: 'group-member-bridge',+ type: 'onComplete',+ webhook: { body: bridge, url: '/api/agent/webhooks/group-member-callback' },+ },+ ],+ } as any);++ expect(recordStart.mock.calls[0][0].metadata).toMatchObject({ groupMemberBridge: bridge });+ });++ // Codex P2 on #20093: a transient start-row failure used to be swallowed,+ // so the member ran without the durable bridge its Stop / late approval need.+ it('refuses to start a group member whose bridge row could not be persisted', async () => {+ vi.spyOn(AgentOperationModel.prototype, 'recordStart').mockRejectedValue(+ new Error('db down'),+ );++ await expect(+ service.createOperation({+ ...mockParams,+ hooks: [+ {+ handler: vi.fn(),+ id: 'group-member-bridge',+ type: 'onComplete',+ webhook: {+ body: {+ anchorMessageId: 'msg-speak',+ expectedMembers: 1,+ groupToolMessageId: 'msg-speak',+ mode: 'in_group',+ onComplete: 'resume',+ parentOperationId: 'op-supervisor',+ },+ url: '/api/agent/webhooks/group-member-callback',+ },+ },+ ],+ } as any),+ ).rejects.toThrow('Failed to durably persist group member');+ });+it('keeps the frozen model facts on the run state but out of durable storage', async () => {const recordStart = vi.spyOn(AgentOperationModel.prototype, 'recordStart')@@ -3133,6 +3195,68 @@ describe('AgentRuntimeService', () => {});});+ describe('loadGroupMemberBridge', () => {+ const bridge = {+ anchorMessageId: 'msg-speak',+ expectedMembers: 1,+ groupToolMessageId: 'msg-speak',+ mode: 'isolated',+ onComplete: 'resume',+ parentOperationId: 'op-supervisor',+ threadId: 'thd-1',+ };++ it('reads the member and its bridge from the live runtime snapshot', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ host: { hooks: [{ id: 'group-member-bridge', webhook: { body: bridge } }] },+ origin: {+ agentId: 'agt-carol',+ groupId: 'cg-1',+ lineage: { orchestrationRole: 'member' },+ threadId: 'thd-1',+ topicId: 'tpc-1',+ },+ });++ expect(await service.loadGroupMemberBridge('op-carol')).toEqual({+ agentId: 'agt-carol',+ bridge,+ groupId: 'cg-1',+ threadId: 'thd-1',+ topicId: 'tpc-1',+ });+ });++ it('falls back to the durable row once the snapshot has expired', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue(null);+ vi.spyOn((service as any).agentOperationModel, 'findById').mockResolvedValue({+ agentId: 'agt-carol',+ chatGroupId: 'cg-1',+ metadata: { groupMemberBridge: bridge },+ threadId: 'thd-1',+ topicId: 'tpc-1',+ });++ expect(await service.loadGroupMemberBridge('op-carol')).toEqual({+ agentId: 'agt-carol',+ bridge,+ groupId: 'cg-1',+ threadId: 'thd-1',+ topicId: 'tpc-1',+ });+ });++ it('is undefined for a run that is not a group member', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue(null);+ vi.spyOn((service as any).agentOperationModel, 'findById').mockResolvedValue({+ agentId: 'agt-solo',+ metadata: {},+ });++ expect(await service.loadGroupMemberBridge('op-solo')).toBeUndefined();+ });+ });+describe('completeGroupActionMember', () => {const memberState = {messages: [@@ -3154,6 +3278,30 @@ describe('AgentRuntimeService', () => {resumeSpy = vi.spyOn(service, 'tryResumeParentFromAsyncTool').mockResolvedValue(true);});+ // G-05 follow-through: a member that inherits manual approval parks on+ // `waiting_for_human`; that is a pause, not an answer, so the supervisor+ // must stay parked until the approval continuation reports back.+ it.each(['in_group', 'isolated'] as const)(+ 'holds the supervisor while a %s member waits for approval',+ async (mode) => {+ const won = await service.completeGroupActionMember({+ anchorMessageId: 'grp-tool-1',+ expectedMembers: 1,+ finalState: { ...memberState, status: 'waiting_for_human' } as any,+ groupToolMessageId: 'grp-tool-1',+ mode,+ onComplete: 'resume',+ operationId: 'child-1',+ parentOperationId: 'parent-1',+ reason: 'waiting_for_human',+ });++ expect(won).toBe(false);+ expect(updateToolMessage).not.toHaveBeenCalled();+ expect(resumeSpy).not.toHaveBeenCalled();+ },+ );+it('single in-group member: backfills a receipt onto the group tool and resumes', async () => {const won = await service.completeGroupActionMember({anchorMessageId: 'grp-tool-1',diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.tsindex 94caa98e765..91106efdeda 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts@@ -785,6 +785,52 @@ export class AgentRuntimeService {return this.coordinator.loadAgentState(operationId);}+ /**+ * The completion bridge of a group member run: from its runtime snapshot+ * while it lives, else from the durable copy recorded on the operation row+ * at start. Undefined for any run that is not a group member.+ */+ async loadGroupMemberBridge(operationId: string): Promise<+ | {+ agentId: string;+ bridge: Omit<GroupActionMemberBridgeParams, 'operationId' | 'reason'>;+ groupId?: string;+ threadId?: string;+ topicId?: string;+ }+ | undefined+ > {+ const state = await this.coordinator.loadAgentState(operationId);+ if (state) {+ const origin = state.origin;+ const bridge = state.host?.hooks?.find((hook) => hook.id === 'group-member-bridge')?.webhook+ ?.body as Omit<GroupActionMemberBridgeParams, 'operationId' | 'reason'> | undefined;+ if (origin?.lineage?.orchestrationRole !== 'member' || !origin.agentId || !bridge) {+ return undefined;+ }+ return {+ agentId: origin.agentId,+ bridge,+ groupId: origin.groupId ?? undefined,+ threadId: origin.threadId ?? undefined,+ topicId: origin.topicId ?? undefined,+ };+ }++ const row = await this.agentOperationModel.findById(operationId);+ const bridge = (row?.metadata as Record<string, unknown> | null | undefined)+ ?.groupMemberBridge as+ Omit<GroupActionMemberBridgeParams, 'operationId' | 'reason'> | undefined;+ if (!row?.agentId || !bridge) return undefined;+ return {+ agentId: row.agentId,+ bridge,+ groupId: row.chatGroupId ?? undefined,+ threadId: row.threadId ?? undefined,+ topicId: row.topicId ?? undefined,+ };+ }+/*** Re-enqueue a continuation whose durable state was written but whose first* queue delivery may have been lost with the resolving HTTP process. The@@ -1066,6 +1112,11 @@ export class AgentRuntimeService {// ends of the persistence lifecycle (start row here, terminal update// in dispatchHooks) and swallows DB errors so runtime startup is never// blocked.+ // A group member's completion bridge lives in the runtime snapshot, which+ // expires (2h). Keep a durable copy on the row so a late approval or a+ // stop can still reach the member's supervisor (`loadGroupMemberBridge`).+ const groupMemberBridge = hooks?.find((hook) => hook.id === 'group-member-bridge')?.webhook+ ?.body as Omit<GroupActionMemberBridgeParams, 'operationId' | 'reason'> | undefined;const operationStartPersisted = await this.completionLifecycle.recordStart({agentId: appContext?.agentId ?? null,appContext: {@@ -1082,13 +1133,14 @@ export class AgentRuntimeService {// Persist the Agent Signal run marker on the operation row so server-side// self-iteration tools can read it back (operation.metadata.agentSignal) at tool-call// time β the trimmed appContext above intentionally drops it.- ...(appContext?.agentSignal || interventionResolution+ ...(appContext?.agentSignal || interventionResolution || groupMemberBridge? {metadata: {...(appContext?.agentSignal ? { agentSignal: appContext.agentSignal } : {}),...(interventionResolution? { agentInterventionContinuation: interventionResolution }: {}),+ ...(groupMemberBridge ? { groupMemberBridge } : {}),},}: {}),@@ -1108,6 +1160,13 @@ export class AgentRuntimeService {);}+ // A member's durable bridge is what a Stop or a late approval falls back+ // to once the runtime snapshot expires; a member without it could strand+ // its supervisor, so fail the start instead.+ if (groupMemberBridge && !operationStartPersisted) {+ throw new Error(`Failed to durably persist group member ${operationId} before dispatch`);+ }+if (interventionResolution) {const durableOperation = await this.agentOperationModel.findById(operationId);const persistedProvenance = durableOperation?.metadata?.agentInterventionContinuation;@@ -3772,6 +3831,20 @@ export class AgentRuntimeService {} = params;const failed = reason === 'error' || reason === 'interrupted' || reason === 'timeout';+ // Members answer to the supervisor's approval mode, so a member can park on+ // a tool that needs the user's approval. That segment fires `onComplete`+ // (so the approval surfaces), but the member has not answered yet: leave its+ // anchor pending and the supervisor parked. The approval continuation+ // inherits this bridge hook and reports the member's real outcome.+ if (reason === 'waiting_for_human') {+ log(+ '[%s] group-member bridge: member parked for human approval, holding parent %s',+ operationId,+ parentOperationId,+ );+ return false;+ }+const finalState =params.finalState ?? (await this.coordinator.loadAgentState(operationId)) ?? undefined;diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.tsindex 1c9ae103c2f..7e5f08c143c 100644--- a/apps/server/src/services/agentRuntime/types.ts+++ b/apps/server/src/services/agentRuntime/types.ts@@ -307,6 +307,8 @@ export interface GroupActionMemberBridgeParams {* collapse the anchor onto the group tool call itself).*/anchorMessageId: string;+ /** Member deadline (epoch ms), carried for approval continuations. */+ deadlineAt?: number;/** Total members forked under this group tool call β the K=N barrier target. */expectedMembers: number;/** Child member op's final state β passed in local mode; loaded otherwise. */@@ -381,6 +383,13 @@ export interface ExecGroupMemberParams {timeout?: number;/** Group topic id. */topicId: string;+ /**+ * The supervisor run's approval policy. Members answer to the same mode the+ * user picked for the turn, so a `humanIntervention: 'required'` tool still+ * asks for approval when a member calls it. Falls back to headless only when+ * the supervisor carries none.+ */+ userInterventionConfig?: UserInterventionConfig;}export interface ExecGroupMemberResult {diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.tsindex e15c2769607..57d3598e53d 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts@@ -11,6 +11,8 @@ import {import { AiAgentService } from '../index';const {+ mockCompleteGroupActionMember,+ mockLoadGroupMemberBridge,mockCreateOperation,mockFindById,mockFindMessagePlugin,@@ -31,6 +33,8 @@ const {mockReleaseTaskCallbackReservation,mockTryReserveTaskCallback,} = vi.hoisted(() => ({+ mockCompleteGroupActionMember: vi.fn(),+ mockLoadGroupMemberBridge: vi.fn(),mockEnsureInterventionContinuationStarted: vi.fn(),mockFindOperationById: vi.fn(),mockRecordCompletion: vi.fn(),@@ -148,9 +152,11 @@ vi.mock('@/database/models/userMemory/persona', () => ({vi.mock('@/server/services/agentRuntime', () => ({AgentRuntimeService: vi.fn().mockImplementation(function () {return {+ completeGroupActionMember: mockCompleteGroupActionMember,createOperation: mockCreateOperation,ensureInterventionContinuationStarted: mockEnsureInterventionContinuationStarted,interruptOperation: mockInterruptOperation,+ loadGroupMemberBridge: mockLoadGroupMemberBridge,loadInterventionContinuationState: mockLoadInterventionContinuationState,};}),@@ -1131,9 +1137,49 @@ describe('AiAgentService.stopPendingApproval', () => {});mockRecordCompletion.mockResolvedValue(undefined);mockInterruptOperation.mockResolvedValue(true);+ mockLoadGroupMemberBridge.mockResolvedValue(undefined);+ mockCompleteGroupActionMember.mockResolvedValue(true);service = new AiAgentService({} as unknown as LobeChatDatabase, 'user-1');});+ // Codex P1 on #20093: a member stopped on its approval never reached its own+ // completion, so the supervisor stayed parked on the member barrier forever.+ it("reports a stopped group member through its bridge so the supervisor isn't stranded", async () => {+ const bridge = {+ anchorMessageId: 'msg-speak',+ expectedMembers: 1,+ groupToolMessageId: 'msg-speak',+ mode: 'in_group',+ onComplete: 'resume',+ parentOperationId: 'op-supervisor',+ };+ mockLoadGroupMemberBridge.mockResolvedValue({ agentId: 'agt-carol', bridge });++ await service.stopPendingApproval({+ batchId: 'batch-1',+ operationId: 'op-parked-1',+ toolMessageIds: ['tool-msg-1', 'tool-msg-2'],+ topicId: 'topic-1',+ });++ expect(mockCompleteGroupActionMember).toHaveBeenCalledWith({+ ...bridge,+ operationId: 'op-parked-1',+ reason: 'interrupted',+ });+ });++ it('does not touch any bridge when the stopped run is not a group member', async () => {+ await service.stopPendingApproval({+ batchId: 'batch-1',+ operationId: 'op-parked-1',+ toolMessageIds: ['tool-msg-1', 'tool-msg-2'],+ topicId: 'topic-1',+ });++ expect(mockCompleteGroupActionMember).not.toHaveBeenCalled();+ });+it('settles every pending row in place and retires the parked operation', async () => {const result = await service.stopPendingApproval({batchId: 'batch-1',diff --git a/apps/server/src/services/aiAgent/__tests__/execGroupMember.test.ts b/apps/server/src/services/aiAgent/__tests__/execGroupMember.test.tsnew file mode 100644index 00000000000..f7c8696af78--- /dev/null+++ b/apps/server/src/services/aiAgent/__tests__/execGroupMember.test.ts@@ -0,0 +1,328 @@+import { ThreadStatus, ThreadType } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { ExecGroupMemberParams } from '@/server/services/agentRuntime/types';++import { AiAgentService } from '../index';++// Mock trusted client to avoid server-side env access+vi.mock('@/libs/trusted-client', () => ({+ generateTrustedClientToken: vi.fn().mockReturnValue(undefined),+ getTrustedClientTokenForSession: vi.fn().mockResolvedValue(undefined),+ isTrustedClientEnabled: vi.fn().mockReturnValue(false),+}));++// Mock ThreadModel+const mockThreadModel = {+ claimForRun: vi.fn(),+ create: vi.fn(),+ findById: vi.fn(),+ update: vi.fn(),+};++const mockOperationFindById = vi.fn();+const mockLoadGroupMemberBridge = vi.fn();+const mockFindMessagePlugin = vi.fn();++vi.mock('@/database/models/thread', () => ({+ ThreadModel: vi.fn().mockImplementation(function () {+ return mockThreadModel;+ }),+}));++vi.mock('@/database/models/agentOperation', () => ({+ AgentOperationModel: vi.fn().mockImplementation(function () {+ return {+ findById: mockOperationFindById,+ };+ }),+}));++// Mock other models+vi.mock('@/database/models/agent', () => ({+ AgentModel: vi.fn().mockImplementation(function () {+ return {+ getAgentConfig: vi.fn(),+ queryAgents: vi.fn().mockResolvedValue([]),+ };+ }),+}));++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([]),+ update: vi.fn().mockResolvedValue({}),+ };+ }),+}));++vi.mock('@/database/models/plugin', () => ({+ PluginModel: vi.fn().mockImplementation(function () {+ return {+ query: vi.fn().mockResolvedValue([]),+ };+ }),+}));++vi.mock('@/database/models/topic', () => ({+ TopicModel: vi.fn().mockImplementation(function () {+ return {+ releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),+ tryReserveTaskCallback: vi.fn().mockResolvedValue(true),+ create: vi.fn().mockResolvedValue({ id: 'topic-1' }),+ findById: vi.fn().mockResolvedValue(null),+ };+ }),+}));++// Mock AgentService+vi.mock('@/server/services/agent', () => ({+ AgentService: vi.fn().mockImplementation(function () {+ return {+ getAgentConfig: vi.fn().mockResolvedValue({+ chatConfig: {},+ id: 'agent-1',+ model: 'gpt-4',+ plugins: [],+ provider: 'openai',+ }),+ };+ }),+}));++const mockScheduleGroupMemberTimeout = vi.fn();++// Mock AgentRuntimeService+vi.mock('@/server/services/agentRuntime', () => ({+ AgentRuntimeService: vi.fn().mockImplementation(function () {+ return {+ createOperation: vi.fn().mockResolvedValue({+ autoStarted: true,+ messageId: 'queue-msg-1',+ operationId: 'op-123',+ success: true,+ }),+ loadGroupMemberBridge: mockLoadGroupMemberBridge,+ scheduleGroupMemberTimeout: mockScheduleGroupMemberTimeout,+ };+ }),+}));++// Mock MarketService+vi.mock('@/server/services/market', () => ({+ MarketService: vi.fn().mockImplementation(function () {+ return {+ getLobehubSkillManifests: vi.fn().mockResolvedValue([]),+ };+ }),+}));++// Mock ComposioService+vi.mock('@/server/services/composio', () => ({+ ComposioService: vi.fn().mockImplementation(function () {+ return {+ getComposioManifests: vi.fn().mockResolvedValue([]),+ };+ }),+}));++vi.mock('@/server/modules/ModelRuntime', () => ({+ initModelRuntimeFromDB: vi.fn(),+}));++const execAgentResult = {+ agentId: 'agt_carol',+ assistantMessageId: 'assistant-msg-1',+ autoStarted: true,+ createdAt: new Date().toISOString(),+ message: 'Agent operation created successfully',+ messageId: 'queue-msg-1',+ operationId: 'op-member',+ status: 'created',+ success: true,+ timestamp: new Date().toISOString(),+ topicId: 'topic-1',+ userMessageId: 'user-msg-1',+};++const memberParams = (overrides: Partial<ExecGroupMemberParams> = {}): ExecGroupMemberParams => ({+ agentId: 'agt_carol',+ anchorMessageId: 'anchor-1',+ expectedMembers: 1,+ groupId: 'group-1',+ groupToolMessageId: 'anchor-1',+ instruction: 'Run the script',+ mode: 'in_group',+ onComplete: 'resume',+ parentOperationId: 'op-sup',+ supervisorMessageId: 'sup-msg-1',+ topicId: 'topic-1',+ ...overrides,+});++describe('AiAgentService.execGroupMember', () => {+ let service: AiAgentService;++ beforeEach(() => {+ vi.clearAllMocks();+ mockThreadModel.create.mockResolvedValue({+ agentId: 'agt_carol',+ groupId: 'group-1',+ id: 'thread-123',+ status: ThreadStatus.Active,+ topicId: 'topic-1',+ type: ThreadType.Isolation,+ });+ mockThreadModel.update.mockResolvedValue({});+ mockOperationFindById.mockResolvedValue({ trigger: 'chat' });+ service = new AiAgentService({} as any, 'test-user-id');+ });++ // G-05: a member answers to the approval mode the user picked for the turn.+ // A hard-coded headless let a member silently run a `humanIntervention:+ // 'required'` tool (execScript) that the supervisor itself had to ask for.+ describe('approval policy', () => {+ const manual = { approvalMode: 'manual' } as const;++ it.each(['in_group', 'isolated'] as const)(+ 'forwards the supervisor approval mode to a %s member',+ async (mode) => {+ const execAgentSpy = vi.spyOn(service, 'execAgent').mockResolvedValue(execAgentResult);++ await service.execGroupMember(memberParams({ mode, userInterventionConfig: manual }));++ expect(execAgentSpy).toHaveBeenCalledWith(+ expect.objectContaining({ userInterventionConfig: manual }),+ );+ },+ );++ it('keeps headless when the supervisor carries no approval policy', async () => {+ const execAgentSpy = vi.spyOn(service, 'execAgent').mockResolvedValue(execAgentResult);++ await service.execGroupMember(memberParams());++ expect(execAgentSpy).toHaveBeenCalledWith(+ expect.objectContaining({ userInterventionConfig: { approvalMode: 'headless' } }),+ );+ });+ });++ // Codex P2 on #20093: the client told a member continuation apart by+ // comparing agent ids, which misfires when the supervisor dispatched itself.+ it('flags an approval that continues a group member', async () => {+ mockFindMessagePlugin.mockResolvedValue({+ intervention: { operationId: 'op-carol', status: 'pending' },+ });+ mockLoadGroupMemberBridge.mockResolvedValue({+ agentId: 'agt_sup',+ bridge: {+ anchorMessageId: 'msg-speak',+ expectedMembers: 1,+ groupToolMessageId: 'msg-speak',+ mode: 'in_group',+ onComplete: 'resume',+ parentOperationId: 'op-sup',+ },+ groupId: 'group-1',+ topicId: 'topic-1',+ });+ const original = service.execAgent.bind(service);+ vi.spyOn(service, 'execAgent')+ .mockImplementationOnce(original)+ .mockResolvedValueOnce(execAgentResult);++ const result = await service.execAgent({+ agentId: 'agt_sup',+ appContext: { groupId: 'group-1', topicId: 'topic-1' },+ prompt: '',+ resumeApproval: { decision: 'approved', parentMessageId: 'msg-tool', toolCallId: 'call-1' },+ } as any);++ expect(result).toMatchObject({ groupMemberContinuation: true });+ });++ // Codex P1 on #20093: an approval continuation retires the parked member op,+ // which disarmed the member's timeout watchdog.+ describe('member deadline across an approval continuation', () => {+ const continueMember = async (deadlineAt?: number) => {+ mockFindMessagePlugin.mockResolvedValue({+ intervention: { operationId: 'op-carol', status: 'pending' },+ });+ mockLoadGroupMemberBridge.mockResolvedValue({+ agentId: 'agt_carol',+ bridge: {+ anchorMessageId: 'msg-task',+ ...(deadlineAt && { deadlineAt }),+ expectedMembers: 1,+ groupToolMessageId: 'msg-task',+ mode: 'isolated',+ onComplete: 'resume',+ parentOperationId: 'op-sup',+ },+ groupId: 'group-1',+ topicId: 'topic-1',+ });+ const original = service.execAgent.bind(service);+ vi.spyOn(service, 'execAgent')+ .mockImplementationOnce(original)+ .mockResolvedValueOnce({ ...execAgentResult, operationId: 'op-carol-continued' });++ await service.execAgent({+ agentId: 'agt_sup',+ appContext: { groupId: 'group-1', topicId: 'topic-1' },+ prompt: '',+ resumeApproval: { decision: 'approved', parentMessageId: 'msg-tool', toolCallId: 'call-1' },+ } as any);+ };++ it('re-arms the remaining time on the continuation', async () => {+ await continueMember(Date.now() + 60_000);++ expect(mockScheduleGroupMemberTimeout).toHaveBeenCalledWith(+ expect.objectContaining({+ memberOperationId: 'op-carol-continued',+ mode: 'isolated',+ parentOperationId: 'op-sup',+ }),+ expect.any(Number),+ );+ const [, delayMs] = mockScheduleGroupMemberTimeout.mock.calls[0];+ expect(delayMs).toBeGreaterThan(55_000);+ expect(delayMs).toBeLessThanOrEqual(60_000);+ });++ it("records an isolated member's absolute deadline in its bridge", async () => {+ const execAgentSpy = vi.spyOn(service, 'execAgent').mockResolvedValue(execAgentResult);+ const before = Date.now();++ await service.execGroupMember(memberParams({ mode: 'isolated', timeout: 30_000 }));++ const hooks = execAgentSpy.mock.calls[0][0].hooks ?? [];+ const body = hooks.find((hook) => hook.id === 'group-member-bridge')?.webhook?.body as+ { deadlineAt?: number } | undefined;+ expect(body?.deadlineAt).toBeGreaterThanOrEqual(before + 30_000);+ expect(body?.deadlineAt).toBeLessThanOrEqual(Date.now() + 30_000);+ });++ it('fires at once when the deadline passed while the approval waited', async () => {+ await continueMember(Date.now() - 1000);++ expect(mockScheduleGroupMemberTimeout).toHaveBeenCalledWith(+ expect.objectContaining({ memberOperationId: 'op-carol-continued' }),+ 1,+ );+ });++ it('arms nothing for a member without a timeout', async () => {+ await continueMember();++ expect(mockScheduleGroupMemberTimeout).not.toHaveBeenCalled();+ });+ });+});diff --git a/apps/server/src/services/aiAgent/hooks/threadRunHooks.ts b/apps/server/src/services/aiAgent/hooks/threadRunHooks.tsindex 38eefb319cc..9c5d8718c59 100644--- a/apps/server/src/services/aiAgent/hooks/threadRunHooks.ts+++ b/apps/server/src/services/aiAgent/hooks/threadRunHooks.ts@@ -385,6 +385,11 @@ export function createGroupActionMemberBridgeHook(agentRuntimeService: AgentRuntimeService,params: {anchorMessageId: string;+ /**+ * Absolute member deadline (epoch ms). Carried in the serialized bridge so+ * an approval continuation can re-arm the timeout watchdog.+ */+ deadlineAt?: number;expectedMembers: number;groupToolMessageId: string;mode: GroupActionMemberMode;@@ -395,6 +400,7 @@ export function createGroupActionMemberBridgeHook(): AgentHook {const {anchorMessageId,+ deadlineAt,expectedMembers,groupToolMessageId,mode,@@ -430,6 +436,7 @@ export function createGroupActionMemberBridgeHook(webhook: {body: {anchorMessageId,+ ...(deadlineAt && { deadlineAt }),expectedMembers,groupToolMessageId,mode,diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex 8cc75aa3e2c..7fd45312db2 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -54,10 +54,18 @@ import { MarketService } from '@/server/services/market';import { markdownToTxt } from '@/utils/markdownToTxt';import { createGraphAwareAgentFactory } from './helpers/agentFactory';-import { createGroupActionMemberBridgeHook } from './hooks/threadRunHooks';+import {+ createGroupActionMemberBridgeHook,+ createThreadHooks,+ pickThreadUsageBaseline,+} from './hooks/threadRunHooks';import { InterventionController } from './intervention/InterventionController';import type { ApprovalClaimState } from './pipeline/approvalResume';import { claimApprovalResume, tryReuseInterventionContinuation } from './pipeline/approvalResume';+import {+ type GroupMemberBridgeParams,+ resolveGroupMemberApprovalContinuation,+} from './pipeline/groupMemberApproval';import { dispatchHeteroAgent } from './pipeline/heteroDispatch';import { buildOperationInitRequest, runOperationInit } from './pipeline/operationInit';import { createHistoryMessagesLoader } from './pipeline/operationPrep';@@ -514,6 +522,46 @@ export class AiAgentService {* β AgentRuntimeService.createOperation(...)*/async execAgent(inputParams: InternalExecAgentParams): Promise<ExecAgentResult> {+ // An approval on a group member's tool continues that member, not the+ // conversation's supervisor (see `resolveGroupMemberApprovalContinuation`).+ const memberContinuation = await resolveGroupMemberApprovalContinuation(+ {+ createBridgeHook: (bridge) =>+ createGroupActionMemberBridgeHook(this.agentRuntimeService, bridge),+ createThreadHooks: async (threadId) => {+ const thread = await this.threadModel.findById(threadId);+ if (!thread?.sourceMessageId) return [];+ return createThreadHooks(+ this.agentRuntimeService,+ this.threadModel,+ this.messageModel,+ thread.id,+ thread.metadata?.startedAt ?? new Date().toISOString(),+ thread.sourceMessageId,+ 'execVirtualSubAgent',+ pickThreadUsageBaseline(thread.metadata),+ );+ },+ findMessagePlugin: (messageId) => this.messageModel.findMessagePlugin(messageId),+ loadMember: (operationId) => this.agentRuntimeService.loadGroupMemberBridge(operationId),+ },+ inputParams,+ );+ if (memberContinuation) {+ log(+ 'execAgent: approval targets group member %s, continuing it under supervisor op %s',+ memberContinuation.agentId,+ memberContinuation.parentOperationId,+ );+ const continuation = await this.execAgent(memberContinuation);+ await this.rearmGroupMemberDeadline(memberContinuation, continuation);+ return {+ ...continuation,+ groupMemberContinuation: true,+ supervisorOperationId: memberContinuation.parentOperationId,+ };+ }+// Creating the thread here (rather than inside the turn) means a run that// asked for one is already a thread run by the time the reservation check// below reads `appContext.threadId` β same isolation as a follow-up inside@@ -1502,6 +1550,33 @@ export class AiAgentService {resumeParentOnComplete: true,});+ /**+ * An approval continuation retires the parked member op, which silently+ * disarms the timeout watchdog scheduled for it. Re-arm the same absolute+ * deadline on the continuation (immediately when it has already passed).+ */+ private rearmGroupMemberDeadline = async (+ continuationParams: InternalExecAgentParams,+ continuation: ExecAgentResult,+ ): Promise<void> => {+ const bridge = continuationParams.hooks?.find((hook) => hook.id === 'group-member-bridge')+ ?.webhook?.body as GroupMemberBridgeParams | undefined;+ if (!bridge?.deadlineAt || !continuation.success || !continuation.operationId) return;++ await this.agentRuntimeService.scheduleGroupMemberTimeout(+ {+ anchorMessageId: bridge.anchorMessageId,+ expectedMembers: bridge.expectedMembers,+ groupToolMessageId: bridge.groupToolMessageId,+ memberOperationId: continuation.operationId,+ mode: bridge.mode,+ onComplete: bridge.onComplete,+ parentOperationId: bridge.parentOperationId,+ },+ Math.max(1, bridge.deadlineAt - Date.now()),+ );+ };+/*** Fork a single group member ("call agent member") under a `lobe-group-management`* tool call. Dispatches to the in-group (non-isolated, shared group session)@@ -1515,6 +1590,8 @@ export class AiAgentService {if (params.mode === 'isolated') {// Isolated members reuse the sub-agent isolation-thread machinery, swapping// in the group-action member bridge (K=N barrier + resume/finish).+ const deadlineAt =+ params.timeout && params.timeout > 0 ? Date.now() + params.timeout : undefined;const result = await execAgentThreadRun(this.subAgentRunDeps,{@@ -1531,6 +1608,7 @@ export class AiAgentService {bridgeHookFactory: (threadId) =>createGroupActionMemberBridgeHook(this.agentRuntimeService, {anchorMessageId: params.anchorMessageId,+ deadlineAt,expectedMembers: params.expectedMembers,groupToolMessageId: params.groupToolMessageId,mode: 'isolated',@@ -1544,6 +1622,7 @@ export class AiAgentService {// resume through the group bridge (its own timeout), not the sub-agent one.orchestrationRole: 'member',resumeParentOnComplete: true,+ userInterventionConfig: params.userInterventionConfig,},);diff --git a/apps/server/src/services/aiAgent/intervention/InterventionController.ts b/apps/server/src/services/aiAgent/intervention/InterventionController.tsindex be55a7a8e8a..a7582ca3e7b 100644--- a/apps/server/src/services/aiAgent/intervention/InterventionController.ts+++ b/apps/server/src/services/aiAgent/intervention/InterventionController.ts@@ -383,6 +383,9 @@ export class InterventionController {);}+ // Read before the interrupt retires the runtime snapshot.+ const groupMember = await this.deps.agentRuntimeService.loadGroupMemberBridge(operationId);+if (operation.status !== 'interrupted') {await this.deps.agentRuntimeService.interruptOperation(operationId);await this.deps.agentOperationModel.recordCompletion(operationId, {@@ -392,6 +395,18 @@ export class InterventionController {});}+ // A group member stopped on its approval never reaches its own completion,+ // so its bridge never fires and the supervisor stays parked on the member+ // barrier. Report the stop through the bridge (idempotent: backfills and the+ // supervisor resume are CAS-guarded, so a retried stop is safe).+ if (groupMember) {+ await this.deps.agentRuntimeService.completeGroupActionMember({+ ...groupMember.bridge,+ operationId,+ reason: 'interrupted',+ });+ }+log('stopPendingApproval: settled %d tool message(s), retired operation %s',targets.length,diff --git a/apps/server/src/services/aiAgent/pipeline/groupMemberApproval.test.ts b/apps/server/src/services/aiAgent/pipeline/groupMemberApproval.test.tsnew file mode 100644index 00000000000..0e3f8ebe291--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/groupMemberApproval.test.ts@@ -0,0 +1,142 @@+import { describe, expect, it, vi } from 'vitest';++import { resolveGroupMemberApprovalContinuation } from './groupMemberApproval';++const bridgeBody = {+ anchorMessageId: 'msg_speak',+ expectedMembers: 1,+ groupToolMessageId: 'msg_speak',+ mode: 'in_group',+ onComplete: 'resume',+ parentOperationId: 'op_sup',+};++const member = {+ agentId: 'agt_carol',+ bridge: bridgeBody,+ groupId: 'cg_team',+ topicId: 'tpc_1',+};++const approveParams = {+ agentId: 'agt_sup',+ appContext: { groupId: 'cg_team', orchestrationRole: 'supervisor', topicId: 'tpc_1' },+ prompt: '',+ resumeApproval: {+ decision: 'approved',+ parentMessageId: 'msg_exec_script',+ toolCallId: 'call_x',+ },+} as any;++const createDeps = (parked: unknown) => {+ const bridgeHook = { handler: vi.fn(), id: 'group-member-bridge', type: 'onComplete' };+ return {+ bridgeHook,+ deps: {+ createBridgeHook: vi.fn().mockReturnValue(bridgeHook),+ createThreadHooks: vi+ .fn()+ .mockResolvedValue([{ handler: vi.fn(), id: 'thread-completion', type: 'onComplete' }]),+ findMessagePlugin: vi+ .fn()+ .mockResolvedValue({ intervention: { operationId: 'op_carol', status: 'pending' } }),+ loadMember: vi.fn().mockResolvedValue(parked),+ },+ };+};++// G-05 follow-through: approving a member's tool from the group conversation+// used to continue the SUPERVISOR as a fresh op β the member never finished and+// the parked supervisor op waited on its member barrier forever.+describe('resolveGroupMemberApprovalContinuation', () => {+ it('continues the member that parked the tool, under the supervisor op', async () => {+ const { bridgeHook, deps } = createDeps(member);++ const result = await resolveGroupMemberApprovalContinuation(deps as any, approveParams);++ expect(deps.findMessagePlugin).toHaveBeenCalledWith('msg_exec_script');+ expect(deps.loadMember).toHaveBeenCalledWith('op_carol');+ expect(deps.createBridgeHook).toHaveBeenCalledWith(bridgeBody);+ expect(result).toMatchObject({+ agentId: 'agt_carol',+ appContext: {+ groupId: 'cg_team',+ orchestrationRole: 'member',+ scope: 'group',+ topicId: 'tpc_1',+ },+ hooks: [bridgeHook],+ parentOperationId: 'op_sup',+ resumeApproval: approveParams.resumeApproval,+ topicStartOwnerOperationId: 'op_sup',+ });+ });++ it('keeps an isolated member in its own thread', async () => {+ const { deps } = createDeps({ ...member, threadId: 'thd_1' });++ const result = await resolveGroupMemberApprovalContinuation(deps as any, approveParams);++ expect(result?.appContext).toMatchObject({+ isolationThread: true,+ isSubAgent: true,+ threadId: 'thd_1',+ });+ });++ // Codex P1 on #20093: the continuation used to install only the bridge, so+ // the isolation thread never ran its completion hook and stayed processing.+ it("rebuilds an isolated member's thread lifecycle hooks before the bridge", async () => {+ const { bridgeHook, deps } = createDeps({ ...member, threadId: 'thd_1' });++ const result = await resolveGroupMemberApprovalContinuation(deps as any, approveParams);++ expect(deps.createThreadHooks).toHaveBeenCalledWith('thd_1');+ expect(result?.hooks?.map((hook) => hook.id)).toEqual(['thread-completion', bridgeHook.id]);+ });++ it('adds no thread hooks for an in_group member', async () => {+ const { bridgeHook, deps } = createDeps(member);++ const result = await resolveGroupMemberApprovalContinuation(deps as any, approveParams);++ expect(deps.createThreadHooks).not.toHaveBeenCalled();+ expect(result?.hooks).toEqual([bridgeHook]);+ });++ it('leaves a non-member approval untouched', async () => {+ const { deps } = createDeps(undefined);++ expect(await resolveGroupMemberApprovalContinuation(deps as any, approveParams)).toBe(+ undefined,+ );+ });++ it('does not re-enter once the continuation carries hooks', async () => {+ const { deps } = createDeps(member);++ expect(+ await resolveGroupMemberApprovalContinuation(deps as any, {+ ...approveParams,+ hooks: [{ id: 'x' }],+ }),+ ).toBe(undefined);+ expect(deps.loadMember).not.toHaveBeenCalled();+ });++ it('ignores a call that is not an approval resume', async () => {+ const { deps } = createDeps(member);++ expect(+ await resolveGroupMemberApprovalContinuation(+ deps as any,+ {+ agentId: 'agt_sup',+ prompt: 'hi',+ } as any,+ ),+ ).toBe(undefined);+ expect(deps.findMessagePlugin).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/aiAgent/pipeline/groupMemberApproval.ts b/apps/server/src/services/aiAgent/pipeline/groupMemberApproval.tsnew file mode 100644index 00000000000..776d643b085--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/groupMemberApproval.ts@@ -0,0 +1,116 @@+import type { MessagePluginItem } from '@lobechat/types';++import type { AgentHook } from '@/server/services/agentRuntime/hooks/types';+import type {+ GroupActionMemberMode,+ GroupActionOnComplete,+} from '@/server/services/agentRuntime/types';++import type { InternalExecAgentParams } from '../types';++/** Bridge params persisted on a group member run's serialized `group-member-bridge` hook. */+export interface GroupMemberBridgeParams {+ anchorMessageId: string;+ /** Member deadline (epoch ms); absent when the member runs without a timeout. */+ deadlineAt?: number;+ expectedMembers: number;+ groupToolMessageId: string;+ mode: GroupActionMemberMode;+ onComplete: GroupActionOnComplete;+ parentOperationId: string;+ threadId?: string;+}++export interface GroupMemberApprovalDeps {+ createBridgeHook: (params: GroupMemberBridgeParams) => AgentHook;+ /**+ * Rebuild the isolation thread's lifecycle hooks (metadata + completion+ * status) for a continued isolated member. Hooks are not carried over from+ * the parked op, so without these the thread never leaves processing.+ */+ createThreadHooks: (threadId: string) => Promise<AgentHook[]>;+ findMessagePlugin: (messageId: string) => Promise<MessagePluginItem | undefined>;+ /**+ * The parked member run's identity and completion bridge β from its runtime+ * snapshot, or the durable copy on its operation row once the snapshot+ * expired. Undefined when the run is not a group member.+ */+ loadMember: (operationId: string) => Promise<ParkedGroupMember | undefined>;+}++export interface ParkedGroupMember {+ agentId: string;+ bridge: GroupMemberBridgeParams;+ groupId?: string;+ threadId?: string;+ topicId?: string;+}++/**+ * Route an approval decision on a group MEMBER's tool back to that member.+ *+ * Members answer to the supervisor's approval mode, so a member can park on a+ * tool that needs approval. The client resolves it from the group conversation,+ * whose agent is the supervisor β taken literally, the continuation would run+ * the supervisor as a fresh op while the member never finishes and the parked+ * supervisor op waits forever on its member barrier.+ *+ * When the decision targets a tool parked by a member run, continue as that+ * member instead: same agent, group member context, the supervisor as parent+ * (topic reservation + stream mirroring + stop cascade), and the member's+ * completion bridge rebuilt from its serialized hook so the member's real+ * outcome backfills its anchor and resumes the supervisor.+ *+ * Returns undefined for every other resume (including a call that already+ * carries hooks, which is how the redirected call avoids re-entering).+ */+export const resolveGroupMemberApprovalContinuation = async (+ deps: GroupMemberApprovalDeps,+ params: InternalExecAgentParams,+): Promise<InternalExecAgentParams | undefined> => {+ if (params.hooks?.length) return undefined;++ const targetMessageId =+ params.resumeApproval?.parentMessageId ?? params.resumeApprovals?.[0]?.parentMessageId;+ if (!targetMessageId) return undefined;++ const sourceOperationId =+ params.approvalSourceOperationId ??+ (await deps.findMessagePlugin(targetMessageId))?.intervention?.operationId;+ if (!sourceOperationId) return undefined;++ const member = await deps.loadMember(sourceOperationId);+ const bridge = member?.bridge;+ if (+ !member ||+ !bridge?.parentOperationId ||+ !bridge.anchorMessageId ||+ !bridge.groupToolMessageId+ ) {+ return undefined;+ }++ const threadId = member.threadId;+ // Same order as the original isolated start: thread hooks first, bridge last+ // so its tool-message backfill is the final write.+ const threadHooks = threadId ? await deps.createThreadHooks(threadId) : [];++ return {+ ...params,+ agentId: member.agentId,+ appContext: {+ ...params.appContext,+ groupId: member.groupId ?? params.appContext?.groupId,+ // An isolated member runs in its own thread on the supervisor's topic and+ // must not claim the topic's running mark (see `execAgentThreadRun`).+ ...(threadId && { isolationThread: true, isSubAgent: true, threadId }),+ orchestrationRole: 'member',+ scope: 'group',+ topicId: member.topicId ?? params.appContext?.topicId,+ },+ hooks: [...threadHooks, deps.createBridgeHook(bridge)],+ parentOperationId: bridge.parentOperationId,+ slug: undefined,+ topicStartOwnerOperationId: bridge.parentOperationId,+ };+};diff --git a/apps/server/src/services/aiAgent/subAgentRuns.ts b/apps/server/src/services/aiAgent/subAgentRuns.tsindex c736797e729..860edaf3e9e 100644--- a/apps/server/src/services/aiAgent/subAgentRuns.ts+++ b/apps/server/src/services/aiAgent/subAgentRuns.ts@@ -6,6 +6,7 @@ import type {ExecVirtualSubAgentParams,LobeAgentChatConfig,ThreadMetadata,+ UserInterventionConfig,} from '@lobechat/types';import { isAgentOperationInFlight, ThreadStatus, ThreadType } from '@lobechat/types';import debug from 'debug';@@ -30,6 +31,8 @@ import {} from './hooks/threadRunHooks';import type { InternalExecAgentParams } from './types';+const HEADLESS_INTERVENTION: UserInterventionConfig = { approvalMode: 'headless' };+const log = debug('lobe-server:ai-agent-service');export interface SubAgentRunDeps {@@ -83,6 +86,11 @@ export interface ExecAgentThreadRunOptions {orchestrationRole?: 'member';provider?: string;resumeParentOnComplete?: boolean;+ /**+ * Approval policy for the spawned run. Isolated group members inherit the+ * supervisor's; unset keeps the headless default of async sub-agent runs.+ */+ userInterventionConfig?: UserInterventionConfig;}type ThreadRow = NonNullable<Awaited<ReturnType<ThreadModel['findById']>>>;@@ -317,7 +325,8 @@ 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+ // Headless (skip human approval) unless the caller hands down the parent's+ // policy β isolated group members answer to the supervisor's approval mode.let result: ExecAgentResult;try {result = await deps.execAgent({@@ -334,7 +343,7 @@ export const execAgentThreadRun = async (prompt: instruction,provider: options.provider,trigger: inheritedTrigger,- userInterventionConfig: { approvalMode: 'headless' },+ userInterventionConfig: options.userInterventionConfig ?? HEADLESS_INTERVENTION,});} catch (error) {// Without an operation id a `processing` thread reads as "still running"@@ -527,7 +536,10 @@ export const execAgentMember = async (suppressUserMessage: true,topicStartOwnerOperationId: parentOperationId,trigger: inheritedTrigger,- userInterventionConfig: { approvalMode: 'headless' },+ // The member answers to the approval mode the user picked for the turn: a+ // hard-coded headless let members silently run `humanIntervention:+ // 'required'` tools that the supervisor itself would have to ask for.+ userInterventionConfig: params.userInterventionConfig ?? HEADLESS_INTERVENTION,});log(diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/groupAgentBuilder.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/groupAgentBuilder.test.tsindex 2f5c8e0e6ed..881fedd2ee0 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/groupAgentBuilder.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/groupAgentBuilder.test.ts@@ -6,6 +6,8 @@ import { groupAgentBuilderRuntime } from '../groupAgentBuilder';const {mockAddAgentsToGroup,mockBatchCreate,+ mockAssertCanPerformResourceAction,+ mockBuilderInstallPlugin,mockBuilderUpdateConfig,mockFindById,mockGetAccessLevel,@@ -19,6 +21,8 @@ const {} = vi.hoisted(() => ({mockAddAgentsToGroup: vi.fn(),mockBatchCreate: vi.fn(),+ mockAssertCanPerformResourceAction: vi.fn(),+ mockBuilderInstallPlugin: vi.fn(),mockBuilderUpdateConfig: vi.fn(),mockFindById: vi.fn(),mockGetAccessLevel: vi.fn(),@@ -77,7 +81,7 @@ vi.mock('@/server/services/agentGroup', () => ({}));vi.mock('@/server/services/resourcePermission', () => ({- assertCanPerformResourceAction: vi.fn(async () => undefined),+ assertCanPerformResourceAction: mockAssertCanPerformResourceAction,}));vi.mock('@/server/routers/lambda/_helpers/resourceConfigGuard', () => ({@@ -86,7 +90,10 @@ vi.mock('@/server/routers/lambda/_helpers/resourceConfigGuard', () => ({vi.mock('../agentBuilder', () => ({agentBuilderRuntime: {- factory: () => ({ updateConfig: mockBuilderUpdateConfig }),+ factory: () => ({+ installPlugin: mockBuilderInstallPlugin,+ updateConfig: mockBuilderUpdateConfig,+ }),identifier: 'lobe-agent-builder',},}));@@ -109,6 +116,7 @@ describe('groupAgentBuilderRuntime', () => {{ agentId: 'agt_sup', description: null, role: 'supervisor', title: 'Supervisor' },]);mockGetResourceConfigAccess.mockResolvedValue('full');+ mockAssertCanPerformResourceAction.mockResolvedValue(undefined);});// The bug: gateway mode executes every builtin tool server-side, and a missing@@ -283,6 +291,94 @@ describe('groupAgentBuilderRuntime', () => {expect.objectContaining({ editingAgentId: 'agt_sup' }),);});++ // G-01: group edit + member view must not reconfigure the linked member β+ // the same rule `updateAgentPrompt` and `agent.updateAgentConfig` enforce.+ it('rejects a roster member whose config the caller cannot edit', async () => {+ mockGetGroupAgentsWithMeta.mockResolvedValue([+ { agentId: 'agt_sup', role: 'supervisor' },+ { agentId: 'agt_alice', role: 'participant' },+ ]);+ mockGetResourceConfigAccess.mockImplementation(async (_ctx, _type, id) =>+ id === 'agt_alice' ? 'profile' : 'full',+ );++ const result = await createRuntime('ws_1').updateConfig(+ { agentId: 'agt_alice', model: 'gpt-4o-mini', provider: 'openai' },+ groupCtx,+ );++ expect(mockGetResourceConfigAccess).toHaveBeenCalledWith(+ expect.anything(),+ 'agent',+ 'agt_alice',+ );+ expect(result).toMatchObject({+ content: 'No permission to access the configuration of agent "agt_alice"',+ error: { type: 'Forbidden' },+ success: false,+ });+ expect(mockBuilderUpdateConfig).not.toHaveBeenCalled();+ });++ // N-1: a group-edit denial reads like every other builder tool instead of+ // escaping as a raw TRPC FORBIDDEN error.+ it('returns a tool failure when the group is not editable', async () => {+ mockAssertCanPerformResourceAction.mockRejectedValue(+ new Error('You do not have permission to edit this resource'),+ );++ const result = await createRuntime('ws_1').updateConfig({ model: 'gpt-5' }, groupCtx);++ expect(result).toEqual({+ content: 'Failed to update agent config: You do not have permission to edit this resource',+ success: false,+ });+ expect(mockBuilderUpdateConfig).not.toHaveBeenCalled();+ });+ });++ describe('installPlugin', () => {+ it('installs onto the supervisor when the caller has full config access', async () => {+ await createRuntime('ws_1').installPlugin(+ { identifier: 'lobe-web-browsing', source: 'official' },+ groupCtx,+ );++ expect(mockBuilderInstallPlugin).toHaveBeenCalledWith(+ { identifier: 'lobe-web-browsing', source: 'official' },+ expect.objectContaining({ editingAgentId: 'agt_sup' }),+ );+ });++ it('rejects when the caller cannot edit the supervisor config', async () => {+ mockGetResourceConfigAccess.mockResolvedValue('profile');++ const result = await createRuntime('ws_1').installPlugin(+ { identifier: 'lobe-web-browsing', source: 'official' },+ groupCtx,+ );++ expect(result).toMatchObject({ error: { type: 'Forbidden' }, success: false });+ expect(mockBuilderInstallPlugin).not.toHaveBeenCalled();+ });++ it('returns a tool failure when the group is not editable', async () => {+ mockAssertCanPerformResourceAction.mockRejectedValue(+ new Error('You do not have permission to edit this resource'),+ );++ const result = await createRuntime('ws_1').installPlugin(+ { identifier: 'lobe-web-browsing', source: 'official' },+ groupCtx,+ );++ expect(result).toEqual({+ content: 'Failed to install plugin: You do not have permission to edit this resource',+ success: false,+ });+ expect(mockBuilderInstallPlugin).not.toHaveBeenCalled();+ });});describe('updateGroupPrompt', () => {diff --git a/apps/server/src/services/toolExecution/serverRuntimes/groupAgentBuilder.ts b/apps/server/src/services/toolExecution/serverRuntimes/groupAgentBuilder.tsindex 662c2dafa15..603154a9b28 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/groupAgentBuilder.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/groupAgentBuilder.ts@@ -821,7 +821,18 @@ export const groupAgentBuilderRuntime: ServerRuntimeRegistration = {};}- if (groupId) await assertGroupEditable(groupId);+ try {+ if (groupId) await assertGroupEditable(groupId);++ // Group edit alone is not enough (same rule as `updateAgentPrompt`):+ // a linked standalone member keeps its own ACL, and model / provider /+ // plugins are edit-level config that also apply outside this group.+ if ((await getConfigAccess('agent', agentId)) !== 'full') {+ return configAccessDenied(agentId);+ }+ } catch (error) {+ return handleError(error, 'Failed to update agent config');+ }return builder.updateConfig(rest, withEditingAgent(ctx, agentId));},@@ -844,7 +855,15 @@ export const groupAgentBuilderRuntime: ServerRuntimeRegistration = {};}- if (groupId) await assertGroupEditable(groupId);+ try {+ if (groupId) await assertGroupEditable(groupId);++ if ((await getConfigAccess('agent', agentId)) !== 'full') {+ return configAccessDenied(agentId);+ }+ } catch (error) {+ return handleError(error, 'Failed to install plugin');+ }return builder.installPlugin(params, withEditingAgent(ctx, agentId));},diff --git a/packages/agent-runtime/src/executors/tool.test.ts b/packages/agent-runtime/src/executors/tool.test.tsindex 4b244dbb4dd..22a771bded2 100644--- a/packages/agent-runtime/src/executors/tool.test.ts+++ b/packages/agent-runtime/src/executors/tool.test.ts@@ -611,6 +611,38 @@ describe('tool executors', () => {);});+ // An approved async tool (group member task / sub-agent) resumes with the+ // approve op's seeded "β¦" placeholder still on state. Parking keeps nothing in+ // it: the server-side resume writes its own reply, and the empty seed left+ // under the tool hid that reply.+ it('retires the resume-seeded placeholder when an approved async tool parks', async () => {+ runTool.mockResolvedValue({+ attempts: 1,+ result: {+ content: '',+ deferred: true,+ state: { status: 'pending', toolMessageId: 'approved-tool' },+ success: true,+ },+ });++ const result = await callTool(host)(+ {+ payload: {+ parentMessageId: 'approved-tool',+ skipCreateToolMessage: true,+ toolCalling: createToolCall('task-call', 'lobe-group-management'),+ },+ type: 'call_tool',+ },+ createState({ pendingAssistantMessageId: 'seeded-placeholder' } as any),+ );++ expect(result.newState.status).toBe('waiting_for_async_tool');+ expect(host.transports.messages.deleteMessage).toHaveBeenCalledWith('seeded-placeholder');+ expect(result.newState.pendingAssistantMessageId).toBeUndefined();+ });+it('omits toolMessageIds when a deferred tool reports no placeholder', async () => {runTool.mockResolvedValue({attempts: 1,diff --git a/packages/agent-runtime/src/executors/tool.ts b/packages/agent-runtime/src/executors/tool.tsindex a9d00f8674a..a0eee656c6b 100644--- a/packages/agent-runtime/src/executors/tool.ts+++ b/packages/agent-runtime/src/executors/tool.ts@@ -442,6 +442,22 @@ const pauseForTools = async ({};newState.pendingToolsCalling = toolsCalling;+ // Same rule as the human-approval pause: an approve resume seeds an assistant+ // placeholder for its first `call_llm`, but an approved async tool (a group+ // member task, a sub-agent) parks the run instead. The server-side resume+ // writes its own reply once the tool lands, so the seed would stay behind as+ // an empty "β¦" sibling that hides that reply. A client-tool pause keeps it:+ // its result resumes this same turn and fills the seed.+ if (reason === 'async_tool' && newState.pendingAssistantMessageId) {+ const orphanId = newState.pendingAssistantMessageId;+ newState.pendingAssistantMessageId = undefined;+ try {+ await host.transports.messages.deleteMessage(orphanId);+ } catch {+ // leaving the placeholder is cosmetic; parking correctly is not+ }+ }+return {events: [{diff --git a/packages/database/src/models/__tests__/topic.test.ts b/packages/database/src/models/__tests__/topic.test.tsindex 6e06a332b3c..9e38358cfc1 100644--- a/packages/database/src/models/__tests__/topic.test.ts+++ b/packages/database/src/models/__tests__/topic.test.ts@@ -1248,6 +1248,68 @@ describe('TopicModel', () => {expect(row?.status).toBe('active');});+ // G-03: a client that heard an early / mirrored terminal event must not+ // clear the marker of a supervisor still parked for its group members.+ it.each(['running', 'waiting_for_async_tool'] as const)(+ 'keeps the marker when a client settles an operation still %s',+ async (operationStatus) => {+ const operationId = `op-sup-${operationStatus}`;+ const topic = await topicModel.create({+ metadata: {+ runningOperation: { assistantMessageId: 'msg-sup', operationId },+ },+ title: 'supervisor parked',+ });+ await topicModel.update(topic.id, { status: 'running' });+ await serverDB.insert(agentOperations).values({+ id: operationId,+ startedAt: new Date(),+ status: operationStatus,+ topicId: topic.id,+ userId,+ });++ const result = await topicModel.settleRunningOperation(topic.id, operationId, 'active', {+ rejectInFlightOperation: true,+ });++ expect(result).toEqual({+ activeOperationId: operationId,+ operationStatus,+ status: 'in_flight',+ });+ const row = await topicModel.findById(topic.id);+ expect(row?.metadata?.runningOperation?.operationId).toBe(operationId);+ expect(row?.status).toBe('running');+ },+ );++ it('still settles a client-reported end once the operation is terminal', async () => {+ const topic = await topicModel.create({+ metadata: {+ runningOperation: { assistantMessageId: 'msg-sup', operationId: 'op-sup-done' },+ },+ title: 'supervisor done',+ });+ await topicModel.update(topic.id, { status: 'running' });+ await serverDB.insert(agentOperations).values({+ id: 'op-sup-done',+ startedAt: new Date(),+ status: 'done',+ topicId: topic.id,+ userId,+ });++ const result = await topicModel.settleRunningOperation(topic.id, 'op-sup-done', 'active', {+ rejectInFlightOperation: true,+ });++ expect(result.status).toBe('settled');+ const row = await topicModel.findById(topic.id);+ expect(row?.metadata?.runningOperation).toBeNull();+ expect(row?.status).toBe('active');+ });+it('atomically removes only a matching child operation', async () => {const childHooks = [{diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.tsindex e21d6a0a328..89fef22bbf5 100644--- a/packages/database/src/models/topic.ts+++ b/packages/database/src/models/topic.ts@@ -1,5 +1,6 @@import { AGENT_SHARE_VISITOR_TOPIC_LIST_LIMIT } from '@lobechat/const';import type {+ AgentOperationStatus,ChatTopicMetadata,ChatTopicStatus,DBMessageItem,@@ -103,6 +104,26 @@ const LIVE_OPERATION_STATUSES = new Set([/** Parked states are exempt from the abandoned-age backstop β see above. */const UNBOUNDED_OPERATION_STATUSES = new Set(['waiting_for_human', 'waiting_for_async_tool']);+/**+ * Operation statuses in which the server is still driving the run, so a+ * client-reported end must not clear its topic marker. `waiting_for_human` is+ * excluded on purpose: a run parked for approval is stream-terminal for the+ * client, which settles it to stop the spinner.+ */+const CLIENT_UNSETTLEABLE_OPERATION_STATUSES = new Set<AgentOperationStatus>([+ 'running',+ 'waiting_for_async_tool',+]);++export interface SettleRunningOperationOptions {+ /**+ * Refuse to clear a marker whose operation row is still `running` /+ * `waiting_for_async_tool`. Set for client-reported settles, which can be+ * triggered by an early or mirrored terminal event.+ */+ rejectInFlightOperation?: boolean;+}+export interface TopicListItem extends TopicItem {/** The topic's last non-empty assistant reply, truncated with a trailing `β¦`. Only set when `queryTopics` is called with `withLastMessage`. */lastAssistantMessage?: string | null;@@ -1853,6 +1874,7 @@ export class TopicModel {id: string,operationId: string,status: TopicItem['status'] = 'unread',+ options: SettleRunningOperationOptions = {},) => {return this.db.transaction(async (tx) => {const [existing] = await tx@@ -1900,6 +1922,31 @@ export class TopicModel {return { activeOperationId: runningOperation.operationId, status: 'conflict' as const };}+ // A client only learns a run ended from a stream event, and a mirrored or+ // early event can arrive while the server is still driving the run (e.g. a+ // supervisor parked on `waiting_for_async_tool` for its group members).+ // Clearing the marker then drops the run's topic reservation, so the next+ // member start fails as "Topic β¦ remained busy". The server's own+ // `finish` clears the marker before it publishes the terminal event, so a+ // genuine end never reaches this check with the marker still in place.+ if (options.rejectInFlightOperation) {+ const [operationRow] = await tx+ .select({ status: agentOperations.status })+ .from(agentOperations)+ .where(eq(agentOperations.id, operationId))+ .limit(1);+ if (+ operationRow &&+ CLIENT_UNSETTLEABLE_OPERATION_STATUSES.has(operationRow.status as AgentOperationStatus)+ ) {+ return {+ activeOperationId: runningOperation.operationId,+ operationStatus: operationRow.status as AgentOperationStatus,+ status: 'in_flight' as const,+ };+ }+ }+const metadata = {...existing.metadata,...(isRoot ? { lastSettledOperationId: operationId } : {}),diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.tsindex 2eb27844c60..b422761fcf7 100644--- a/packages/types/src/agentExecution/index.ts+++ b/packages/types/src/agentExecution/index.ts@@ -324,12 +324,26 @@ export interface ExecAgentResult {error?: string;/** Structured availability context when a device dispatch failed before acceptance. */errorData?: DeviceUnavailableErrorData;+ /**+ * The run continues a group member's approved tool under the supervisor's+ * run (the supervisor keeps the topic and its stream). Explicit, because the+ * member can be the supervisor agent itself.+ */+ groupMemberContinuation?: boolean;/*** External heterogeneous producer for this run. `null` explicitly denotes* the normal AgentRuntime path; `undefined` is reserved for rolling clients* talking to an older server that did not yet return this discriminator.*/heteroType?: string | null;+ /**+ * With `groupMemberContinuation`: the member's continuation operation. The+ * client-facing `operationId` then names the supervisor's run, so a client+ * released before this field keeps following the supervisor (its stream+ * carries the member's continuation and the supervisor's closing) instead of+ * taking the topic over and dropping it.+ */+ memberOperationId?: string;/** Status message */message: string;/** Queue message ID if auto-started */@@ -340,6 +354,11 @@ export interface ExecAgentResult {status: string;/** Whether the operation was created successfully */success: boolean;+ /**+ * Server-side only, with `groupMemberContinuation`: the supervisor run the+ * member continues under. Mapped into the client shape by the router.+ */+ supervisorOperationId?: string;/*** The failure was already announced through the run's terminal lifecycle β* `CompletionLifecycle` fired its `onComplete` hooks, so every consumer ofdiff --git a/src/features/Conversation/store/slices/data/action.test.ts b/src/features/Conversation/store/slices/data/action.test.tsindex 9fce176a9c8..fd7a17f6602 100644--- a/src/features/Conversation/store/slices/data/action.test.ts+++ b/src/features/Conversation/store/slices/data/action.test.ts@@ -10,6 +10,7 @@ import {runMessageListQuery,} from '@/services/message/cache';import { useChatStore } from '@/store/chat';+import { operationSelectors } from '@/store/chat/selectors';import { LOCAL_MESSAGE_SCOPE } from '@/store/chat/utils/localMessages';import { createStore } from '../../index';@@ -835,6 +836,97 @@ describe('DataSlice', () => {});});+ describe('while an agent run is in flight in this conversation', () => {+ const context = { agentId: 'test-session', threadId: null, topicId: 'test-topic' };+ const fetched: UIChatMessage[] = [+ {+ content: 'Run the script',+ createdAt: 1000,+ id: 'msg-user',+ role: 'user',+ updatedAt: 1000,+ },+ ];++ it('still lands the first load, so a parked run does not leave a skeleton (G-05)', async () => {+ // A group supervisor parked on a member's approval stays `running`+ // indefinitely; dropping the first load there never initializes the list.+ const running = vi+ .spyOn(operationSelectors, 'isAgentRuntimeRunningByContext')+ .mockReturnValue(() => true);+ vi.mocked(messageService.getMessages).mockResolvedValue(fetched);+ const store = createStore({ context });+ store.setState({ messagesInit: false });++ store.getState().useFetchMessages(context);++ await waitFor(() => {+ expect(store.getState().messagesInit).toBe(true);+ });+ expect(store.getState().dbMessages.map((m) => m.id)).toEqual(['msg-user']);+ running.mockRestore();+ });++ it('keeps loaded rows but lands rows the list has never seen (G-05)', async () => {+ // A stale cached first load can miss the parked member's rows; the fresh+ // read that follows must still bring them in, without touching the+ // rows the stream owns.+ const running = vi+ .spyOn(operationSelectors, 'isAgentRuntimeRunningByContext')+ .mockReturnValue(() => true);+ const streamed = {+ content: 'streamed so far',+ createdAt: 2000,+ id: 'msg-supervisor',+ role: 'assistant',+ updatedAt: 2000,+ } as UIChatMessage;+ const memberTool = {+ content: '',+ createdAt: 3000,+ id: 'msg-member-tool',+ role: 'tool',+ updatedAt: 3000,+ } as UIChatMessage;+ vi.mocked(messageService.getMessages).mockResolvedValue([+ ...fetched,+ { ...streamed, content: '' },+ memberTool,+ ]);+ const store = createStore({ context });+ store.setState({ dbMessages: [...fetched, streamed], messagesInit: true });++ store.getState().useFetchMessages(context);++ await waitFor(() => {+ expect(store.getState().dbMessages.map((m) => m.id)).toContain('msg-member-tool');+ });+ expect(store.getState().dbMessages.find((m) => m.id === 'msg-supervisor')?.content).toBe(+ 'streamed so far',+ );+ running.mockRestore();+ });++ it('drops a refetch that brings nothing new', async () => {+ const running = vi+ .spyOn(operationSelectors, 'isAgentRuntimeRunningByContext')+ .mockReturnValue(() => true);+ vi.mocked(messageService.getMessages).mockResolvedValue(fetched);+ const store = createStore({ context });+ const loaded = [{ ...fetched[0], content: 'local' }];+ store.setState({ dbMessages: loaded, messagesInit: true });++ store.getState().useFetchMessages(context);++ await waitFor(() => {+ expect(messageService.getMessages).toHaveBeenCalled();+ });+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(store.getState().dbMessages).toBe(loaded);+ running.mockRestore();+ });+ });+it('discards a fetch result that resolves after switching conversations', async () => {let resolveFetch!: (messages: UIChatMessage[]) => void;vi.mocked(messageService.getMessages).mockReturnValue(diff --git a/src/features/Conversation/store/slices/data/action.ts b/src/features/Conversation/store/slices/data/action.tsindex d90f36ed649..23594fac8df 100644--- a/src/features/Conversation/store/slices/data/action.ts+++ b/src/features/Conversation/store/slices/data/action.ts@@ -374,15 +374,29 @@ export const dataSlice: StateCreator<// updatedAt tie-breaker handles most cases on its own, but the// updatedAt comparison degenerates when server's pushed snapshot// carries a DB updatedAt equal to a later stale fetch's row.- if (operationSelectors.isAgentRuntimeRunningByContext(context)(getChatStoreState()))- return;-+ //+ // Only rows the store already holds are protected. The first load, and+ // rows the store has never seen, still land: a run can stay `running`+ // for a long time (a group supervisor parked on a member's approval),+ // and dropping them left a reloaded list on its skeleton, or on a stale+ // cached snapshot missing the parked member's rows, for good.const prevDbMessages = get().dbMessages;+ let fetchedMessages = data;+ if (+ get().messagesInit &&+ operationSelectors.isAgentRuntimeRunningByContext(context)(getChatStoreState())+ ) {+ const knownIds = new Set(prevDbMessages.map((m) => m.id));+ const unseen = data.filter((m) => !knownIds.has(m.id));+ if (unseen.length === 0) return;+ fetchedMessages = [...prevDbMessages, ...unseen];+ }+const activeVoiceMessageIds = new Set(Object.keys(getChatStoreState().voiceMessageUploadMap),);const mergedMessages = mergeFetchedMessagesWithLocalState(- data,+ fetchedMessages,prevDbMessages,activeVoiceMessageIds,);diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.tsindex f99e8c43a8d..e96d49c0118 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts@@ -980,6 +980,75 @@ describe('ConversationControl actions', () => {executeGatewayAgentSpy.mockRestore();});+ it("keeps a group supervisor's live run when approving its member's tool (G-05)", async () => {+ // The supervisor is not paused: it waits on the member whose tool is being+ // approved, and streams the continuation plus its own closing on its open+ // gateway channel. Retiring it dropped the closing from the screen.+ const { result } = renderHook(() => useChatStore());++ const agentId = 'agt_supervisor';+ const groupId = 'cg_launch';+ const topicId = 'tpc_group';+ const context = { agentId, groupId, scope: 'group', threadId: null, topicId } as any;+ const chatKey = messageMapKey(context);++ const userMessage = createMockMessage({ id: 'group-user-msg', role: 'user' });+ const memberAssistant = createMockMessage({+ agentId: 'agt_carol',+ id: 'carol-msg',+ parentId: userMessage.id,+ role: 'assistant',+ } as any);+ const memberTool = createMockMessage({+ agentId: 'agt_carol',+ id: 'carol-tool',+ parentId: memberAssistant.id,+ plugin: {+ apiName: 'execScript',+ arguments: '{"command":"echo hi"}',+ identifier: 'lobe-skills',+ type: 'builtin',+ },+ role: 'tool',+ tool_call_id: 'call_carol',+ } as any);++ let supervisorOpId!: string;+ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ activeTopicId: topicId,+ dbMessagesMap: { [chatKey]: [userMessage, memberAssistant, memberTool] },+ gatewayConnections: { 'server-supervisor-op': { status: 'connected' } } as any,+ messagesMap: { [chatKey]: [userMessage, memberAssistant, memberTool] },+ });+ supervisorOpId = result.current.startOperation({+ context,+ metadata: { serverOperationId: 'server-supervisor-op' },+ type: 'execServerAgentRuntime',+ }).operationId;+ });++ vi.spyOn(result.current, 'isGatewayModeEnabled').mockReturnValue(true);+ vi.spyOn(result.current, 'optimisticUpdateMessagePlugin').mockResolvedValue(undefined);+ const executeGatewayAgentSpy = vi+ .spyOn(result.current, 'executeGatewayAgent')+ .mockResolvedValue({} as any);++ await act(async () => {+ await result.current.approveToolCalling('carol-tool', 'group-1', context);+ });++ expect(executeGatewayAgentSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ resumeApproval: expect.objectContaining({ parentMessageId: 'carol-tool' }),+ }),+ );+ expect(result.current.operations[supervisorOpId].status).toBe('running');++ executeGatewayAgentSpy.mockRestore();+ });+it('uses the generic source claim for a durable edited approval and adopts its precreated op', async () => {const { result } = renderHook(() => useChatStore());const agentId = 'server-agent';@@ -1626,6 +1695,31 @@ describe('ConversationControl actions', () => {);});+ // A stopped group member's card stayed on screen until a reload: its stop+ // ends no stream this client listens on, so no refetch lands the aborted row.+ it('settles the stopped card locally', async () => {+ const { result } = renderHook(() => useChatStore());+ seedDurableTerminalCard(result);+ vi.spyOn(result.current, 'executeGatewayAgent').mockResolvedValue({} as any);+ vi.mocked(lambdaClient.aiAgent.resolveAgentInterventionBySource.mutate).mockResolvedValueOnce(+ {+ contractVersion: 2,+ state: 'claimed',+ status: 'stopped',+ success: true,+ },+ );++ await act(async () => {+ await result.current.stopPendingApproval(['tool-msg-terminal-source']);+ });++ const row = result.current.dbMessagesMap[chatKey].find(+ (message) => message.id === 'tool-msg-terminal-source',+ );+ expect(row?.pluginIntervention?.status).toBe('aborted');+ });+it('completes only the local action when custom cancel wins the durable claim', async () => {const { result } = renderHook(() => useChatStore());const pausedOperationId = seedDurableTerminalCard(result);diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.tsindex 3eed2ee3d29..fe510562054 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts@@ -11,6 +11,8 @@ import { aiAgentService } from '@/services/aiAgent';import { messageService } from '@/services/message';import { shareChatService } from '@/services/shareChat';import { topicService } from '@/services/topic';+import { getChatGroupStoreState, useAgentGroupStore } from '@/store/agentGroup';+import { topicSelectors } from '@/store/chat/slices/topic/selectors';import { messageMapKey } from '@/store/chat/utils/messageMapKey';import * as serverConfigStore from '@/store/serverConfig';@@ -960,6 +962,226 @@ describe('GatewayActionImpl', () => {);});+ // G-05: an approval on a group member's tool continues that member under+ // the supervisor's run.+ describe('group member approval continuation', () => {+ const groupId = 'cg_team';+ const execResult = {+ agentId: 'agt_sup',+ assistantMessageId: 'ast-1',+ autoStarted: true,+ createdAt: new Date().toISOString(),+ message: 'ok',+ operationId: 'server-op-1',+ status: 'created',+ success: true,+ timestamp: new Date().toISOString(),+ token: 'test-token',+ topicId: 'topic-1',+ userMessageId: 'usr-1',+ } as const;+ let previousGroupMap: ReturnType<typeof getChatGroupStoreState>['groupMap'];++ beforeEach(() => {+ previousGroupMap = getChatGroupStoreState().groupMap;+ useAgentGroupStore.setState({+ groupMap: {+ ...previousGroupMap,+ [groupId]: { id: groupId, supervisorAgentId: 'agt_sup' } as any,+ },+ });+ vi.mocked(aiAgentService.execAgentTask).mockResolvedValue(execResult as any);+ });++ afterEach(() => {+ useAgentGroupStore.setState({ groupMap: previousGroupMap });+ });++ // An approval on a member's tool continues that member under the+ // supervisor's run. The supervisor keeps the topic, and its open stream+ // carries the continuation and the closing β taking the marker over and+ // dropping that stream left a reloaded page with no closing and a run+ // that never ended (G-05).+ it("keeps the supervisor's marker and stream when an approval continues a member", async () => {+ const { action, internalDispatchTopic } = createExecuteTestAction();+ vi.mocked(aiAgentService.execAgentTask).mockResolvedValue({+ ...execResult,+ agentId: 'agt_carol',+ groupMemberContinuation: true,+ memberOperationId: 'server-member-op',+ operationId: 'server-supervisor-op',+ } as any);+ const topicSpy = vi.spyOn(topicSelectors, 'getTopicById').mockReturnValue(+ () =>+ ({+ id: 'topic-1',+ metadata: { runningOperation: { operationId: 'server-supervisor-op' } },+ }) as any,+ );+ const disconnect = vi.spyOn(action, 'disconnectFromGateway');++ await action.executeGatewayAgent({+ context: {+ agentId: 'agt_sup',+ groupId,+ scope: 'group',+ threadId: null,+ topicId: 'topic-1',+ },+ message: '',+ parentMessageId: 'carol-tool',+ });++ expect(disconnect).not.toHaveBeenCalledWith('server-supervisor-op');+ expect(internalDispatchTopic).not.toHaveBeenCalledWith(+ expect.objectContaining({+ value: expect.objectContaining({+ metadata: expect.objectContaining({+ runningOperation: expect.objectContaining({ operationId: 'server-member-op' }),+ }),+ }),+ }),+ );+ topicSpy.mockRestore();+ });++ // Codex P2 on #20093: the supervisor can dispatch itself as a member, so+ // the continuation is told apart by the server's flag, not by agent ids.+ it("keeps the supervisor's marker when the continued member is the supervisor itself", async () => {+ const { action, internalDispatchTopic } = createExecuteTestAction();+ vi.mocked(aiAgentService.execAgentTask).mockResolvedValue({+ ...execResult,+ groupMemberContinuation: true,+ memberOperationId: 'server-member-op',+ operationId: 'server-supervisor-op',+ } as any);+ const topicSpy = vi.spyOn(topicSelectors, 'getTopicById').mockReturnValue(+ () =>+ ({+ id: 'topic-1',+ metadata: { runningOperation: { operationId: 'server-supervisor-op' } },+ }) as any,+ );+ const disconnect = vi.spyOn(action, 'disconnectFromGateway');++ await action.executeGatewayAgent({+ context: {+ agentId: 'agt_sup',+ groupId,+ scope: 'group',+ threadId: null,+ topicId: 'topic-1',+ },+ message: '',+ parentMessageId: 'sup-self-tool',+ });++ expect(disconnect).not.toHaveBeenCalledWith('server-supervisor-op');+ expect(internalDispatchTopic).not.toHaveBeenCalledWith(+ expect.objectContaining({+ value: expect.objectContaining({+ metadata: expect.objectContaining({+ runningOperation: expect.objectContaining({ operationId: 'server-member-op' }),+ }),+ }),+ }),+ );+ topicSpy.mockRestore();+ });++ // Codex P1 on #20093: the server names the supervisor's run as operationId+ // so older clients keep following it; this client runs the member op.+ it('follows the member continuation op the server sets aside', async () => {+ const { action, connectToGateway } = createExecuteTestAction();+ vi.mocked(aiAgentService.execAgentTask).mockResolvedValue({+ ...execResult,+ agentId: 'agt_carol',+ groupMemberContinuation: true,+ memberOperationId: 'server-member-op',+ operationId: 'server-supervisor-op',+ } as any);++ await action.executeGatewayAgent({+ context: {+ agentId: 'agt_sup',+ groupId,+ scope: 'group',+ threadId: null,+ topicId: 'topic-1',+ },+ message: '',+ parentMessageId: 'carol-tool',+ });++ expect(connectToGateway.mock.calls[0][0]).toMatchObject({+ operationId: 'server-member-op',+ });+ });++ it("still takes over a stale marker for the supervisor's own new run", async () => {+ const { action } = createExecuteTestAction();+ const topicSpy = vi.spyOn(topicSelectors, 'getTopicById').mockReturnValue(+ () =>+ ({+ id: 'topic-1',+ metadata: { runningOperation: { operationId: 'server-old-op' } },+ }) as any,+ );+ const disconnect = vi.spyOn(action, 'disconnectFromGateway');++ await action.executeGatewayAgent({+ context: {+ agentId: 'agt_sup',+ groupId,+ scope: 'group',+ threadId: null,+ topicId: 'topic-1',+ },+ message: 'hi',+ });++ expect(disconnect).toHaveBeenCalledWith('server-old-op');+ topicSpy.mockRestore();+ });+ // The continuation ends while the supervisor keeps running: the topic is+ // still the supervisor's to settle (G-05).+ it("leaves the topic settle to the supervisor when a member's continuation ends", async () => {+ const { action, connectToGateway } = createExecuteTestAction();+ vi.mocked(aiAgentService.execAgentTask).mockResolvedValue({+ ...execResult,+ agentId: 'agt_carol',+ groupMemberContinuation: true,+ memberOperationId: 'server-member-op',+ operationId: 'server-supervisor-op',+ } as any);+ (action as any).clearLocalRunningOperation = vi.fn();+ vi.mocked(topicService.settleRunningOperation).mockClear();++ await action.executeGatewayAgent({+ context: {+ agentId: 'agt_sup',+ groupId,+ scope: 'group',+ threadId: null,+ topicId: 'topic-1',+ },+ message: '',+ parentMessageId: 'carol-tool',+ });+ const { onSessionComplete } = connectToGateway.mock.calls[0][0];+ (action as any).completeOperation = vi.fn();++ onSessionComplete({+ authFailed: false,+ completion: { source: 'resume_status', status: 'completed' },+ succeeded: true,+ terminalReceived: true,+ });++ expect(topicService.settleRunningOperation).not.toHaveBeenCalled();+ });+ });+it('should not include parentMessageId when not provided (normal send)', async () => {const { action } = createExecuteTestAction();diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts b/src/store/chat/slices/agentRun/actions/entries/conversationControl.tsindex 0fbdccf4749..4de7cdc2a2d 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts@@ -314,10 +314,26 @@ export class ConversationControlActionImpl {})(this.#get());return ops.filter((op) =>- op.type === 'execServerAgentRuntime' && op.status === 'running' && !op.metadata?.isAborting,+ op.type === 'execServerAgentRuntime' &&+ op.status === 'running' &&+ !op.metadata?.isAborting &&+ !(groupId && this.#isLiveGatewayOp(op)),);};+ /**+ * Whether an op's gateway stream is still open. In a group chat that is the+ * supervisor waiting on its members (e.g. a member parked on the approval+ * being resolved): it is not paused, it will stream the members' continuation+ * and its own closing, and retiring it would drop both from the screen.+ */+ #isLiveGatewayOp = (op: Operation) => {+ const serverOperationId = op.metadata?.serverOperationId;+ if (!serverOperationId) return false;+ const status = this.#get().gatewayConnections[serverOperationId]?.status;+ return !!status && status !== 'disconnected';+ };+#resolveHeteroInterventionExecutionOperation = (initialOperationId: string,): { operation?: Operation; operationId: string } => {@@ -1001,6 +1017,12 @@ export class ConversationControlActionImpl {topicId,});}+ // Settle the cards locally. A group member's stop ends no stream this+ // client still listens on, so no refetch would ever land the aborted rows+ // and the card would stay on screen until a reload.+ for (const id of addressable) {+ this.#dispatchInterventionState(id, { status: 'aborted' }, { context: effectiveContext });+ }this.#completeOpsById(pausedOpIds);} catch (error) {console.error('[stopPendingApproval] failed:', error);diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex 7a48d26ae88..6669626f7a4 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -70,7 +70,7 @@ import type { RunScope } from '../../lifecycle/types';import { createGatewayEventBuffer } from './gatewayEventBuffer';import { createGatewayEventHandler, isCompletedRuntimeEnd } from './gatewayEventHandler';import { createGatewayEventRouter } from './gatewayEventRouter';-import { createGatewayMemberStreamHandler } from './gatewayMemberStreamHandler';+import { createGatewayMemberStreamHandler, mergeGroupSnapshot } from './gatewayMemberStreamHandler';import {type GatewayMuxIdentity,getGatewayMux,@@ -964,7 +964,7 @@ export class GatewayActionImpl {// decided server-side by the share config, never by this client.const agentShareId = executionContext.agentShareId;- const result =+ const serverResult =precreatedResult ??(agentShareId? await shareChatService.execAgentTask(@@ -1047,6 +1047,12 @@ export class GatewayActionImpl {},{ signal: abortSignal },));+ // A member continuation names the supervisor's run as `operationId` (safe+ // for older clients); this run is the member's continuation.+ const result: ExecAgentResult =+ serverResult.groupMemberContinuation && serverResult.memberOperationId+ ? { ...serverResult, operationId: serverResult.memberOperationId }+ : serverResult;// Persistence is the ownership boundary. Notify before later UI synchronization awaits and// before handling a late abort so callers never delete a file already attached server-side.@@ -1314,7 +1320,13 @@ export class GatewayActionImpl {// useGatewayReconnect doesn't fire for a stale previous operation while the new// gateway connection is being established. Also disconnect any live reconnect// connection that was already established for the old operation.- if (result.topicId) {+ //+ // Not for an approval that continues a group member: the server runs it+ // under the supervisor's run (flagged by the server; the member may be the+ // supervisor agent itself), so the supervisor keeps the topic, and its open+ // stream is what delivers the members' continuation and its own closing.+ const continuesGroupMember = !!result.groupMemberContinuation;+ if (result.topicId && !continuesGroupMember) {const existingTopic = topicSelectors.getTopicById(result.topicId)(this.#get());const staleOpId = existingTopic?.metadata?.runningOperation?.operationId;if (staleOpId && staleOpId !== result.operationId) {@@ -1384,7 +1396,10 @@ export class GatewayActionImpl {parentMessageId: result.assistantMessageId,parentMessageType: 'assistant',runId: gatewayOpId,- runScope: (resolvedExecutionContext.scope === 'sub_agent'+ // A member's approval continuation is nested inside the supervisor's+ // run: top-level terminal effects (queue drain, unread, notification)+ // belong to the supervisor's own terminal, not to the member's.+ runScope: (resolvedExecutionContext.scope === 'sub_agent' || continuesGroupMember? 'sub_agent': 'top_level') as RunScope,runtimeType: 'gateway',@@ -1438,7 +1453,8 @@ export class GatewayActionImpl {succeeded,});- if (result.topicId) {+ // The supervisor still owns the topic while a member continuation ends.+ if (result.topicId && !continuesGroupMember) {// The server already settled this topic: the runtime's `finish`// executor settles to 'unread' before it publishes the terminal event// this callback rides on, so by now the mark is legitimately gone and@@ -1804,16 +1820,26 @@ export class GatewayActionImpl {context: ConversationContext,parentOperationId: string,): ((memberOperationId: string) => (event: AgentStreamEvent) => void) => {+ const liveMessageIds = new Set<string>();+ const bucketKey = messageMapKey({+ agentId: context.agentId ?? '',+ groupId: context.groupId,+ scope: context.scope,+ threadId: context.threadId,+ topicId: context.topicId,+ });+ // Rejects on failure so the approval refresh can retry. Keeps rows other+ // member handlers are still streaming (see `mergeGroupSnapshot`).+ const refreshGroup = () =>+ messageService.getMessages(context).then((messages) => {+ const current = this.#get().dbMessagesMap[bucketKey] ?? [];+ this.#get().replaceMessages(mergeGroupSnapshot(messages, current, liveMessageIds), {+ context,+ });+ });let hydration: Promise<void> | undefined;const ensureGroupHydrated = () => {- if (!hydration) {- hydration = messageService- .getMessages(context)- .then((messages) => {- this.#get().replaceMessages(messages, { context });- })- .catch(() => {});- }+ if (!hydration) hydration = refreshGroup().catch(() => {});return hydration;};@@ -1821,8 +1847,10 @@ export class GatewayActionImpl {createGatewayMemberStreamHandler(this.#get, {context,ensureGroupHydrated,+ liveMessageIds,memberOperationId,parentOperationId,+ refreshGroup,});};diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayMemberStreamHandler.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayMemberStreamHandler.test.tsindex f0bfa4149d4..dc7f3690530 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayMemberStreamHandler.test.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayMemberStreamHandler.test.ts@@ -5,7 +5,7 @@ import { describe, expect, it, vi } from 'vitest';import type { ChatStore } from '@/store/chat/store';import { messageMapKey } from '@/store/chat/utils/messageMapKey';-import { createGatewayMemberStreamHandler } from './gatewayMemberStreamHandler';+import { createGatewayMemberStreamHandler, mergeGroupSnapshot } from './gatewayMemberStreamHandler';const context = {agentId: 'member-agent',@@ -55,8 +55,10 @@ describe('createGatewayMemberStreamHandler', () => {const handler = createGatewayMemberStreamHandler(() => store, {context,ensureGroupHydrated: vi.fn().mockResolvedValue(undefined),+ liveMessageIds: new Set<string>(),memberOperationId: 'server-member-op',parentOperationId: 'owner-op',+ refreshGroup: vi.fn().mockResolvedValue(undefined),});handler(makeEvent('stream_start', { assistantMessage: { id: 'member-msg' } }));@@ -76,8 +78,10 @@ describe('createGatewayMemberStreamHandler', () => {const handler = createGatewayMemberStreamHandler(() => store, {context,ensureGroupHydrated: vi.fn().mockResolvedValue(undefined),+ liveMessageIds: new Set<string>(),memberOperationId: 'server-member-op',parentOperationId: 'owner-op',+ refreshGroup: vi.fn().mockResolvedValue(undefined),});handler(makeEvent('stream_start', { assistantMessage: { id: 'member-msg' } }));@@ -85,4 +89,124 @@ describe('createGatewayMemberStreamHandler', () => {expect(store.updateOperationMetadata).not.toHaveBeenCalled();});++ // G-05: a member parked on a human approval ends while the supervisor keeps+ // waiting on it, so no terminal refetch ever brings its pending tool row in β+ // without a read of its own the approval card only shows after a reload.+ describe('member parked on a human approval', () => {+ const setup = () => {+ const store = createStore();+ const refreshGroup = vi.fn().mockResolvedValue(undefined);+ const ensureGroupHydrated = vi.fn().mockResolvedValue(undefined);+ const liveMessageIds = new Set<string>();+ const handler = createGatewayMemberStreamHandler(() => store, {+ context,+ ensureGroupHydrated,+ liveMessageIds,+ memberOperationId: 'server-member-op',+ parentOperationId: 'owner-op',+ refreshGroup,+ });+ handler(makeEvent('stream_start', { assistantMessage: { id: 'member-msg' } }));+ return { ensureGroupHydrated, handler, liveMessageIds, refreshGroup, store };+ };++ it('re-reads the group tree so the approval card lands live (G-05)', async () => {+ const { handler, refreshGroup, store } = setup();++ handler(makeEvent('agent_runtime_end', { reason: 'waiting_for_human' }));+ await vi.waitFor(() => expect(refreshGroup).toHaveBeenCalledTimes(1));++ expect(store.completeOperation).toHaveBeenCalledWith('local-member-op');+ });++ // Codex P1 on #20093: both reads replace the whole bucket, so the refresh+ // must not race an in-flight stream_start hydration that could land last.+ it('waits for the in-flight hydration before refreshing', async () => {+ const { ensureGroupHydrated, handler, refreshGroup } = setup();+ let finishHydration!: () => void;+ ensureGroupHydrated.mockReturnValue(+ new Promise<void>((resolve) => {+ finishHydration = resolve;+ }),+ );++ handler(makeEvent('agent_runtime_end', { reason: 'waiting_for_human' }));+ await Promise.resolve();+ expect(refreshGroup).not.toHaveBeenCalled();++ finishHydration();+ await vi.waitFor(() => expect(refreshGroup).toHaveBeenCalledTimes(1));+ });++ // Codex P1 on #20093: a failed approval read used to be swallowed, leaving+ // the parked turn without its card until a reload.+ it('retries a failed approval refresh', async () => {+ const { handler, refreshGroup } = setup();+ refreshGroup+ .mockRejectedValueOnce(new Error('network'))+ .mockRejectedValueOnce(new Error('network'))+ .mockResolvedValue(undefined);++ handler(makeEvent('agent_runtime_end', { reason: 'waiting_for_human' }));++ await vi.waitFor(() => expect(refreshGroup).toHaveBeenCalledTimes(3), { timeout: 4000 });+ });++ it('leaves a normal member end to the supervisor terminal refetch', () => {+ const { handler, refreshGroup } = setup();++ handler(makeEvent('agent_runtime_end', { reason: 'completed' }));++ expect(refreshGroup).not.toHaveBeenCalled();+ });+ });++ // Codex P1 on #20093: the approval re-read replaced the whole bucket, rolling+ // a still-streaming sibling's column back to its lagging database snapshot.+ describe('live sibling rows', () => {+ it('tracks the row a member is streaming until it ends', () => {+ const liveMessageIds = new Set<string>();+ const handler = createGatewayMemberStreamHandler(() => createStore(), {+ context,+ ensureGroupHydrated: vi.fn().mockResolvedValue(undefined),+ liveMessageIds,+ memberOperationId: 'server-member-op',+ parentOperationId: 'owner-op',+ refreshGroup: vi.fn().mockResolvedValue(undefined),+ });++ handler(makeEvent('stream_start', { assistantMessage: { id: 'member-msg' } }));+ expect([...liveMessageIds]).toEqual(['member-msg']);++ handler(makeEvent('agent_runtime_end', { reason: 'waiting_for_human' }));+ expect(liveMessageIds.size).toBe(0);+ });++ it("keeps a live sibling's in-memory row and takes the snapshot for the rest", () => {+ const fetched = [+ { content: 'db stale', id: 'sibling-msg', role: 'assistant' },+ {+ content: '',+ id: 'approval-tool',+ pluginIntervention: { status: 'pending' },+ role: 'tool',+ },+ ] as any[];+ const current = [+ { content: 'live streamed text', id: 'sibling-msg', role: 'assistant' },+ ] as any[];++ expect(mergeGroupSnapshot(fetched, current, new Set(['sibling-msg']))).toEqual([+ current[0],+ fetched[1],+ ]);+ });++ it('takes the snapshot as-is when no member is streaming', () => {+ const fetched = [{ content: 'db', id: 'a', role: 'assistant' }] as any[];++ expect(mergeGroupSnapshot(fetched, [], new Set())).toBe(fetched);+ });+ });});diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayMemberStreamHandler.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayMemberStreamHandler.tsindex bcb60edeb52..cf2311e36c2 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayMemberStreamHandler.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayMemberStreamHandler.ts@@ -26,6 +26,13 @@ export interface GatewayMemberStreamHandlerParams {* `replaceMessages` and clobber each other's in-flight streamed content.*/ensureGroupHydrated: () => Promise<void>;+ /**+ * Assistant rows currently being streamed by this run's member handlers,+ * shared across them. A group re-read keeps these rows' in-memory copies:+ * chunk persistence lags the socket, so the database snapshot would roll a+ * sibling's live column back.+ */+ liveMessageIds: Set<string>;/*** The member's server-side operationId (the op whose events are forwarded* onto the supervisor's WebSocket).@@ -36,6 +43,13 @@ export interface GatewayMemberStreamHandlerParams {* recorded as its child for lineage.*/parentOperationId?: string;+ /**+ * Re-read the group tree unconditionally (not memoized; rejects on failure so+ * the caller can retry). Used when a member parks on a human approval: the+ * supervisor keeps waiting on it, so no terminal refetch comes, and the+ * pending tool row (the approval card) only lands with a read of its own.+ */+ refreshGroup: () => Promise<void>;}/**@@ -59,11 +73,55 @@ export interface GatewayMemberStreamHandlerParams {* dispatch the full accumulated content (not deltas), any chunk that lands* before hydration completes is repainted once the row exists β self-healing.*/+/**+ * Merge a group re-read into the bucket without rolling back live member+ * streams: rows in `liveMessageIds` keep their in-memory copy when one exists;+ * every other row takes the fetched snapshot.+ */+export const mergeGroupSnapshot = (+ fetched: UIChatMessage[],+ current: UIChatMessage[],+ liveMessageIds: ReadonlySet<string>,+): UIChatMessage[] => {+ if (liveMessageIds.size === 0) return fetched;+ const currentById = new Map(current.map((message) => [message.id, message]));+ return fetched.map((message) =>+ liveMessageIds.has(message.id) ? (currentById.get(message.id) ?? message) : message,+ );+};++const APPROVAL_REFRESH_ATTEMPTS = 3;+const APPROVAL_REFRESH_BASE_DELAY_MS = 500;+export const createGatewayMemberStreamHandler = (get: () => ChatStore,params: GatewayMemberStreamHandlerParams,): ((event: AgentStreamEvent) => void) => {- const { context, ensureGroupHydrated, memberOperationId, parentOperationId } = params;+ const {+ context,+ ensureGroupHydrated,+ liveMessageIds,+ memberOperationId,+ parentOperationId,+ refreshGroup,+ } = params;++ // A failed read would leave the parked turn without its approval card and+ // nothing else to fetch it until a focus or reload, so retry with backoff.+ const refreshApprovalWithRetry = async () => {+ for (let attempt = 0; attempt < APPROVAL_REFRESH_ATTEMPTS; attempt += 1) {+ try {+ await refreshGroup();+ return;+ } catch {+ if (attempt < APPROVAL_REFRESH_ATTEMPTS - 1) {+ await new Promise((resolve) =>+ setTimeout(resolve, APPROVAL_REFRESH_BASE_DELAY_MS * 2 ** attempt),+ );+ }+ }+ }+ };const bucketKey = messageMapKey({agentId: context.agentId ?? '',@@ -115,7 +173,9 @@ export const createGatewayMemberStreamHandler = (if (!id) break;ensureLocalOp();+ if (currentAssistantMessageId) liveMessageIds.delete(currentAssistantMessageId);currentAssistantMessageId = id;+ liveMessageIds.add(id);if (localOperationId) get().associateMessageWithOperation(id, localOperationId);accumulatedContent = '';accumulatedReasoning = '';@@ -173,9 +233,20 @@ export const createGatewayMemberStreamHandler = (case 'agent_runtime_end':case 'error': {ended = true;+ if (currentAssistantMessageId) liveMessageIds.delete(currentAssistantMessageId);// The member row's final structure (tools, content, metadata) is// reconciled by the supervisor op's terminal refetch / council barrier.// This handler owns only the live text, so just retire the loading op.+ // A member parked on a human approval is the exception (see `refreshGroup`).+ if (+ event.type === 'agent_runtime_end' &&+ (event.data as { reason?: string } | undefined)?.reason === 'waiting_for_human'+ ) {+ // Chained after the stream_start hydration: both reads replace the+ // whole bucket, so an older in-flight snapshot landing last would+ // drop the pending row again.+ void ensureGroupHydrated().then(refreshApprovalWithRetry);+ }if (localOperationId) get().completeOperation(localOperationId);break;}