π€― 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): keep the supervisor's gateway session alive across member terminals (stack L2: G-02, G-03) (#20102)
Arvin Xud4c051aa692c
diff --git a/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts b/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.tsindex 6ff94917cf6..638223bbb1e 100644--- a/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts+++ b/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts@@ -95,6 +95,7 @@ export class AgentRuntimeCoordinator {async createAgentOperation(operationId: string,data: {+ acceptsMemberRuntimeEnd?: boolean;agentConfig?: any;visitorRedaction?: { showErrorDetails?: boolean; showModelInfo?: boolean };mirrorToOperationId?: string;diff --git a/apps/server/src/modules/AgentRuntime/AgentStateManager.ts b/apps/server/src/modules/AgentRuntime/AgentStateManager.tsindex 4ebf45a1f1d..27d06783aed 100644--- a/apps/server/src/modules/AgentRuntime/AgentStateManager.ts+++ b/apps/server/src/modules/AgentRuntime/AgentStateManager.ts@@ -54,6 +54,13 @@ export interface StepResult {}export interface AgentOperationMetadata {+ /**+ * The client that started this operation handles `member_runtime_end`. Only+ * then does the Gateway stream notifier rename a mirrored group member's+ * terminal on this operation's channel; a client released before the rename+ * still gets the verbatim `agent_runtime_end` it retires member columns on.+ */+ acceptsMemberRuntimeEnd?: boolean;agentConfig?: any;createdAt: string;lastActiveAt: string;@@ -313,6 +320,7 @@ export class AgentStateManager {}return {+ acceptsMemberRuntimeEnd: metadata.acceptsMemberRuntimeEnd === 'true' || undefined,agentConfig: metadata.agentConfig ? JSON.parse(metadata.agentConfig) : undefined,visitorRedaction: metadata.visitorRedaction? JSON.parse(metadata.visitorRedaction)@@ -342,6 +350,7 @@ export class AgentStateManager {async createOperationMetadata(operationId: string,data: {+ acceptsMemberRuntimeEnd?: boolean;agentConfig?: any;visitorRedaction?: { showErrorDetails?: boolean; showModelInfo?: boolean };mirrorToOperationId?: string;@@ -355,6 +364,7 @@ export class AgentStateManager {try {const metadata: AgentOperationMetadata = {+ acceptsMemberRuntimeEnd: data.acceptsMemberRuntimeEnd,agentConfig: data.agentConfig,visitorRedaction: data.visitorRedaction,createdAt: new Date().toISOString(),@@ -383,6 +393,7 @@ export class AgentStateManager {if (metadata.workspaceId) redisData.workspaceId = metadata.workspaceId;if (metadata.mirrorToOperationId)redisData.mirrorToOperationId = metadata.mirrorToOperationId;+ if (metadata.acceptsMemberRuntimeEnd) redisData.acceptsMemberRuntimeEnd = 'true';if (metadata.modelRuntimeConfig)redisData.modelRuntimeConfig = JSON.stringify(metadata.modelRuntimeConfig);if (metadata.agentConfig) redisData.agentConfig = JSON.stringify(metadata.agentConfig);diff --git a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.tsindex f5ea9154ed5..880b4bd2f66 100644--- a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts+++ b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts@@ -76,6 +76,25 @@ const projectGatewayEventData = (data: unknown, eventType: unknown): unknown =>return data;};+/**+ * Shape an event for delivery on ANOTHER op's channel (a group member's events+ * mirrored onto the supervisor's socket).+ *+ * The gateway DO ends its session on any `agent_runtime_end` it receives,+ * whichever op the event names β so a member's terminal, mirrored verbatim,+ * closed the supervisor's session and every later supervisor step (the resume+ * after the member barrier, its final reply) was never streamed. The mirrored+ * copy is renamed to the non-terminal `member_runtime_end`: the client's member+ * handler still retires that member's column on it, while the DO, which only+ * reacts to `agent_runtime_end`, keeps the supervisor session open. The+ * member's own channel still receives the real terminal.+ *+ * Only applied when the mirror target's client declared it handles the new+ * event (`acceptsMemberRuntimeEnd`) β see `GatewayStreamNotifier.mirrorPush`.+ */+export const toMirroredEvent = (event: Record<string, unknown>): Record<string, unknown> =>+ event.type === 'agent_runtime_end' ? { ...event, type: 'member_runtime_end' } : event;+const POST_TIMEOUT = 5000; // 5s per requestconst MAX_INFLIGHT = 20; // bounded concurrency@@ -139,6 +158,13 @@ export interface GatewayStreamNotifierOptions {* over β otherwise an unawaited push can be lost with the invocation.*/deferPushes?: boolean;+ /**+ * Whether the client that started `operationId` handles `member_runtime_end`+ * (from persisted op metadata). Lets a queue worker that never ran the+ * supervisor's init still rename the member terminals it mirrors. Omitted β+ * in-process knowledge only; unknown β the verbatim `agent_runtime_end`.+ */+ resolveAcceptsMemberRuntimeEnd?: (operationId: string) => Promise<boolean>;}export class GatewayStreamNotifier implements IStreamEventManager {@@ -190,6 +216,15 @@ export class GatewayStreamNotifier implements IStreamEventManager {/** In-flight resolutions, deduped per op so concurrent events share one read. */private mirrorResolving = new Map<string, Promise<string | undefined>>();+ /**+ * `mirror target op β whether its client handles member_runtime_end`. Set from+ * the target's own init (fast path) or resolved once from persisted metadata+ * (queue path). A client released before the rename only retires a member+ * column on `agent_runtime_end`, so it keeps getting that. Cleared at the+ * target's `publishAgentRuntimeEnd`.+ */+ private memberEndTargets = new Map<string, Promise<boolean>>();+/*** `operationId β visitor redaction policy` for confirmed shared-agent visitor* runs. `step_start` events carry neither `streamOwnerUserId` (only on@@ -283,6 +318,9 @@ export class GatewayStreamNotifier implements IStreamEventManager {this.mirrorTargets.set(operationId, mirrorTo);log('mirror registered: %s β %s', operationId, mirrorTo);}+ if (initialState?.acceptsMemberRuntimeEnd === true) {+ this.memberEndTargets.set(operationId, Promise.resolve(true));+ }// Ordering barrier: a subscriber connects immediately after execAgent// returns and asks the Gateway for the operation's authoritative status.@@ -432,6 +470,7 @@ export class GatewayStreamNotifier implements IStreamEventManager {this.mirrorTargets.delete(operationId);this.mirrorResolved.delete(operationId);this.mirrorResolving.delete(operationId);+ this.memberEndTargets.delete(operationId);this.shareVisitorOps.delete(operationId);this.shareVisitorResolved.delete(operationId);this.shareVisitorResolving.delete(operationId);@@ -601,13 +640,27 @@ export class GatewayStreamNotifier implements IStreamEventManager {}}- private mirrorPush(mirrorTo: string, event: Record<string, unknown>): Promise<void> {+ private async mirrorPush(mirrorTo: string, event: Record<string, unknown>): Promise<void> {+ const mirrored =+ event.type === 'agent_runtime_end' && (await this.acceptsMemberRuntimeEnd(mirrorTo))+ ? toMirroredEvent(event)+ : event;return this.httpPost('/api/operations/push-event', {- event,+ event: mirrored,operationId: mirrorTo,});}+ private acceptsMemberRuntimeEnd(target: string): Promise<boolean> {+ let accepted = this.memberEndTargets.get(target);+ if (!accepted) {+ const resolve = this.options.resolveAcceptsMemberRuntimeEnd;+ accepted = resolve ? resolve(target).catch(() => false) : Promise.resolve(false);+ this.memberEndTargets.set(target, accepted);+ }+ return accepted;+ }+/*** Resolve and cache an op's mirror target from persisted metadata. Returns the* target (cached in `mirrorTargets`) or undefined when the op has none. Dedupeddiff --git a/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts b/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.tsindex 6aca6daaad1..d72f70e6990 100644--- a/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts+++ b/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts@@ -108,6 +108,7 @@ export class InMemoryAgentStateManager implements IAgentStateManager {async createOperationMetadata(operationId: string,data: {+ acceptsMemberRuntimeEnd?: boolean;agentConfig?: any;visitorRedaction?: { showErrorDetails?: boolean; showModelInfo?: boolean };mirrorToOperationId?: string;@@ -118,6 +119,7 @@ export class InMemoryAgentStateManager implements IAgentStateManager {},): Promise<void> {const metadata: AgentOperationMetadata = {+ acceptsMemberRuntimeEnd: data.acceptsMemberRuntimeEnd,agentConfig: data.agentConfig,visitorRedaction: data.visitorRedaction,createdAt: new Date().toISOString(),diff --git a/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.tsindex 5b0c4590eb8..43d53ac8eaa 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts@@ -53,6 +53,24 @@ describe('AgentStateManager', () => {await expect(stateManager.createOperationMetadata(operationId, data)).resolves.not.toThrow();});++ it('round-trips the client member_runtime_end declaration', async () => {+ await stateManager.createOperationMetadata('op-supervisor', {+ acceptsMemberRuntimeEnd: true,+ userId: 'user-123',+ });+ const stored = redisMock.hmset.mock.calls.at(-1)?.[1] as Record<string, string>;+ expect(stored.acceptsMemberRuntimeEnd).toBe('true');++ redisMock.hgetall.mockResolvedValueOnce(stored);+ const meta = await stateManager.getOperationMetadata('op-supervisor');+ expect(meta?.acceptsMemberRuntimeEnd).toBe(true);++ redisMock.hgetall.mockResolvedValueOnce({ ...stored, acceptsMemberRuntimeEnd: undefined });+ expect((await stateManager.getOperationMetadata('op-old'))?.acceptsMemberRuntimeEnd).toBe(+ undefined,+ );+ });});describe('saveAgentState', () => {diff --git a/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.tsindex a3626c4b49c..5d06c2810e9 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts@@ -1131,6 +1131,83 @@ describe('GatewayStreamNotifier', () => {expect(pushes.map((p) => p.operationId)).toEqual(['op-plain']);});+ it('mirrors a member terminal as a non-terminal member_runtime_end so the supervisor channel stays open (G-02)', async () => {+ await notifier.publishAgentRuntimeInit('op-supervisor', { acceptsMemberRuntimeEnd: true });+ await notifier.publishAgentRuntimeInit('op-member', { mirrorToOperationId: 'op-supervisor' });++ await notifier.publishAgentRuntimeEnd({+ finalState: {} as any,+ operationId: 'op-member',+ reason: 'done',+ stepIndex: 1,+ });++ await new Promise((r) => setTimeout(r, 50));++ const ends = pushEventCalls().filter(+ (b) => b.event?.type === 'agent_runtime_end' || b.event?.type === 'member_runtime_end',+ );+ // The member's own channel still gets its real terminal.+ expect(ends.filter((p) => p.operationId === 'op-member').map((p) => p.event.type)).toEqual([+ 'agent_runtime_end',+ ]);+ // The supervisor's channel must NOT receive an `agent_runtime_end`: the+ // gateway DO treats any such event as the end of ITS session and+ // broadcasts `session_complete`, cutting the supervisor stream short.+ const mirrored = ends.filter((p) => p.operationId === 'op-supervisor');+ expect(mirrored.map((p) => p.event.type)).toEqual(['member_runtime_end']);+ expect(mirrored[0].event.operationId).toBe('op-member');+ expect(mirrored[0].event.data.reason).toBe('done');+ });++ // Codex P1 on #20102: a client released before the rename (desktop, or a web+ // tab from before a rolling deploy) only retires a member column on+ // `agent_runtime_end`; renaming it for that client left the column running.+ it('keeps the verbatim agent_runtime_end for a supervisor whose client predates member_runtime_end', async () => {+ await notifier.publishAgentRuntimeInit('op-supervisor', {});+ await notifier.publishAgentRuntimeInit('op-member', { mirrorToOperationId: 'op-supervisor' });++ await notifier.publishAgentRuntimeEnd({+ finalState: {} as any,+ operationId: 'op-member',+ reason: 'done',+ stepIndex: 1,+ });+ await new Promise((r) => setTimeout(r, 50));++ const mirrored = pushEventCalls().filter(+ (b) =>+ b.operationId === 'op-supervisor' &&+ (b.event?.type === 'agent_runtime_end' || b.event?.type === 'member_runtime_end'),+ );+ expect(mirrored.map((p) => p.event.type)).toEqual(['agent_runtime_end']);+ expect(mirrored[0].event.operationId).toBe('op-member');+ });++ it('queue worker path: reads the supervisor client declaration from persisted metadata', async () => {+ const resolveAccepts = vi.fn(async (op: string) => op === 'op-supervisor-q');+ const workerNotifier = new GatewayStreamNotifier(+ inner,+ gatewayUrl,+ serviceToken,+ async (op) => (op === 'op-member-q' ? 'op-supervisor-q' : undefined),+ undefined,+ { resolveAcceptsMemberRuntimeEnd: resolveAccepts },+ );++ await workerNotifier.publishAgentRuntimeEnd({+ finalState: {} as any,+ operationId: 'op-member-q',+ reason: 'done',+ stepIndex: 1,+ });+ await new Promise((r) => setTimeout(r, 50));++ const mirrored = pushEventCalls().filter((b) => b.operationId === 'op-supervisor-q');+ expect(mirrored.map((p) => p.event.type)).toEqual(['member_runtime_end']);+ expect(resolveAccepts).toHaveBeenCalledWith('op-supervisor-q');+ });+it('stops mirroring after the member op reaches a terminal state', async () => {await notifier.publishAgentRuntimeInit('op-member', { mirrorToOperationId: 'op-supervisor' });diff --git a/apps/server/src/modules/AgentRuntime/__tests__/InMemoryAgentStateManager.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/InMemoryAgentStateManager.test.tsindex c8c27c8c039..b52b5950b9e 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/InMemoryAgentStateManager.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/InMemoryAgentStateManager.test.ts@@ -45,6 +45,14 @@ describe('InMemoryAgentStateManager', () => {expect(typeof meta!.lastActiveAt).toBe('string');});+ it('stores the client member_runtime_end declaration', async () => {+ await manager.createOperationMetadata('op-member-end', { acceptsMemberRuntimeEnd: true });++ expect((await manager.getOperationMetadata('op-member-end'))!.acceptsMemberRuntimeEnd).toBe(+ true,+ );+ });+it('should store provided userId, agentConfig and modelRuntimeConfig', async () => {await manager.createOperationMetadata('op-2', {agentConfig: { maxSteps: 10 },diff --git a/apps/server/src/modules/AgentRuntime/factory.ts b/apps/server/src/modules/AgentRuntime/factory.tsindex 57422230890..2103bdb0e3c 100644--- a/apps/server/src/modules/AgentRuntime/factory.ts+++ b/apps/server/src/modules/AgentRuntime/factory.ts@@ -101,7 +101,15 @@ export const createStreamEventManager = (if (!meta?.streamOwnerUserId) return null;return meta.visitorRedaction ?? FULL_STRIP_REDACTION;},- options,+ {+ ...options,+ // Same again for the supervisor's `member_runtime_end` declaration: the+ // worker mirroring a member's terminal may never have seen its init.+ resolveAcceptsMemberRuntimeEnd: async (operationId) => {+ const meta = await stateManager.getOperationMetadata(operationId);+ return meta?.acceptsMemberRuntimeEnd === true;+ },+ },);}diff --git a/apps/server/src/modules/AgentRuntime/types.ts b/apps/server/src/modules/AgentRuntime/types.tsindex 8d7542083c9..d9079f852cf 100644--- a/apps/server/src/modules/AgentRuntime/types.ts+++ b/apps/server/src/modules/AgentRuntime/types.ts@@ -42,6 +42,8 @@ export interface IAgentStateManager {createOperationMetadata: (operationId: string,data: {+ /** See {@link AgentOperationMetadata.acceptsMemberRuntimeEnd}. */+ acceptsMemberRuntimeEnd?: boolean;agentConfig?: any;visitorRedaction?: { showErrorDetails?: boolean; showModelInfo?: boolean };mirrorToOperationId?: string;diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIngest.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIngest.test.tsindex 8c5162a7fec..6ef285e6245 100644--- a/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIngest.test.ts+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIngest.test.ts@@ -45,8 +45,10 @@ vi.mock('@/server/services/aiChat', () => ({}),}));+// Server-only wire types a producer never emits: the v2 message delta and the+// relayed terminal of a mirrored (group member) operation.type HeterogeneousAgentStreamEvent = Omit<AgentStreamEvent, 'type'> & {- type: Exclude<AgentStreamEvent['type'], 'message_patch'>;+ type: Exclude<AgentStreamEvent['type'], 'member_runtime_end' | 'message_patch'>;};const buildEvent = (diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.test.tsindex 9774887b202..81d8bb4fc77 100644--- a/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts@@ -189,6 +189,36 @@ describe('AI Agent Router Integration Tests', () => {expect(await serverDB.select().from(topics).where(eq(topics.userId, userId))).toEqual([]);});+ // G-02: only a client that declares `member_runtime_end` gets mirrored member+ // terminals under that name (Codex on #20102: the batch route dropped it).+ it('forwards a declared member_runtime_end stream feature on both routes', async () => {+ const { AgentRuntimeService } = await import('@/server/services/agentRuntime');+ const caller = aiAgentRouter.createCaller(createTestContext());+ const createOperationCalls = () =>+ vi+ .mocked(AgentRuntimeService)+ .mock.results.flatMap((r) => (r.value as any).createOperation.mock.calls)+ .map(([params]) => params.acceptsMemberRuntimeEnd);++ vi.mocked(AgentRuntimeService).mockClear();+ await caller.execAgent({+ agentId: testAgentId,+ prompt: 'single',+ streamFeatures: ['member_runtime_end'],+ });+ await caller.execAgents({+ tasks: [{ agentId: testAgentId, prompt: 'batch', streamFeatures: ['member_runtime_end'] }],+ });+ expect(createOperationCalls()).toEqual([true, true]);++ vi.mocked(AgentRuntimeService).mockClear();+ // A client that declares nothing (a released desktop, a stale tab) is an+ // explicit `false`, so a continuation never inherits a newer client's `true`.+ await caller.execAgent({ agentId: testAgentId, prompt: 'undeclared single' });+ await caller.execAgents({ tasks: [{ agentId: testAgentId, prompt: 'undeclared' }] });+ expect(createOperationCalls()).toEqual([false, false]);+ });+it('should create a new topic when topicId is not provided', async () => {const caller = aiAgentRouter.createCaller(createTestContext());diff --git a/apps/server/src/routers/lambda/_schema/agentIntervention.test.ts b/apps/server/src/routers/lambda/_schema/agentIntervention.test.tsindex 95b3ea8afa2..e4132d9e44e 100644--- a/apps/server/src/routers/lambda/_schema/agentIntervention.test.ts+++ b/apps/server/src/routers/lambda/_schema/agentIntervention.test.ts@@ -145,6 +145,16 @@ describe('ResolveAgentInterventionBySourceSchema', () => {targets: [{ toolCallId: 'call-1', toolMessageId: 'message-1' }],};+ it('accepts the resolving client stream features', () => {+ expect(+ ResolveAgentInterventionBySourceSchema.parse({+ ...source,+ action: { scope: 'once', type: 'approve_tool' },+ streamFeatures: ['member_runtime_end'],+ }).streamFeatures,+ ).toEqual(['member_runtime_end']);+ });+it('accepts exact source-locator Web actions without durable item authority', () => {expect(ResolveAgentInterventionBySourceSchema.parse({diff --git a/apps/server/src/routers/lambda/_schema/agentIntervention.ts b/apps/server/src/routers/lambda/_schema/agentIntervention.tsindex b26cede587b..8bf2ef256d0 100644--- a/apps/server/src/routers/lambda/_schema/agentIntervention.ts+++ b/apps/server/src/routers/lambda/_schema/agentIntervention.ts@@ -236,6 +236,8 @@ export const ResolveAgentInterventionBySourceSchema = zbatchId: z.string().min(1),operationId: z.string().min(1),resolutionRequestId: z.string().uuid(),+ /** Gateway stream features the resolving client handles β see `ExecAgentSchema`. */+ streamFeatures: z.array(z.string()).optional(),targets: AgentInterventionSourceTargetsSchema,}).strict()diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.tsindex 70ca75ce8b0..bf544432f28 100644--- a/apps/server/src/routers/lambda/aiAgent.ts+++ b/apps/server/src/routers/lambda/aiAgent.ts@@ -525,6 +525,13 @@ const resolveContinuationUserInterventionConfig = async (const dispatchClaimedAgentIntervention = async (resolution: ClaimedAgentInterventionResolution,ctx: AgentInterventionDispatchContext,+ /**+ * `acceptsMemberRuntimeEnd`: the resolving client's own declaration when that+ * client is the one subscribing to the continuation (the Web source bridge).+ * Left unset for a resolver that isn't (token Review), so the continuation+ * inherits the parked operation's declaration.+ */+ options: { acceptsMemberRuntimeEnd?: boolean } = {},): Promise<{ execution?: ExecAgentResult; status: AgentInterventionReviewStatus }> => {const { runtimeAction } = resolution;let execution: ExecAgentResult | undefined;@@ -608,6 +615,7 @@ const dispatchClaimedAgentIntervention = async (const skipped = customAction.type === 'skipped';execution = await ctx.aiAgentService.execAgent({agentId: runtimeAction.agentId,+ acceptsMemberRuntimeEnd: options.acceptsMemberRuntimeEnd,approvalResolutionRequestId: resolution.resolutionRequestId,approvalSourceOperationId: runtimeAction.operationId,appContext: runtimeAction.appContext,@@ -642,6 +650,7 @@ const dispatchClaimedAgentIntervention = async (const [singleDecision] = runtimeAction.decisions;execution = await ctx.aiAgentService.execAgent({agentId: runtimeAction.agentId,+ acceptsMemberRuntimeEnd: options.acceptsMemberRuntimeEnd,approvalResolutionRequestId: resolution.resolutionRequestId,approvalSourceOperationId: runtimeAction.operationId,appContext: runtimeAction.appContext,@@ -662,6 +671,7 @@ const dispatchClaimedAgentIntervention = async (case 'resume_tool_result': {execution = await ctx.aiAgentService.execAgent({agentId: runtimeAction.agentId,+ acceptsMemberRuntimeEnd: options.acceptsMemberRuntimeEnd,approvalResolutionRequestId: resolution.resolutionRequestId,approvalSourceOperationId: runtimeAction.operationId,appContext: runtimeAction.appContext,@@ -1009,9 +1019,26 @@ const StartExecutionSchema = z.object({/*** Schema for execAgent - execute a single Agent*/+/**+ * Whether the calling client declared it handles `member_runtime_end`+ * (`streamFeatures`). Always a boolean for a client-facing route: a client that+ * declares nothing (a released desktop, a stale tab) is a `false` of its own,+ * never "unknown" β only a server-internal continuation, with no caller of its+ * own, inherits the parked operation's declaration.+ */+const acceptsMemberRuntimeEndOf = (streamFeatures: string[] | undefined): boolean =>+ streamFeatures?.includes('member_runtime_end') ?? false;+const ExecAgentSchema = z.object({includeFinalState: z.boolean().optional(),+ /**+ * Gateway stream features the calling client handles. `member_runtime_end`:+ * a group member's terminal arrives on the supervisor's channel under that+ * name instead of `agent_runtime_end`. Free-form strings so an older server+ * ignores features it does not know rather than rejecting the run.+ */+ streamFeatures: z.array(z.string()).optional(),/** The agent ID to run (either agentId or slug is required) */agentId: z.string().optional(),/** Application context for message storage */@@ -2401,7 +2428,9 @@ export const aiAgentRouter = router({if (sourceResolution.state === 'already_resolved') {throw new HumanApprovalAlreadyResolvedError(parentMessageId ?? 'intervention');}- const dispatch = await dispatchClaimedAgentIntervention(sourceResolution, ctx);+ const dispatch = await dispatchClaimedAgentIntervention(sourceResolution, ctx, {+ acceptsMemberRuntimeEnd: acceptsMemberRuntimeEndOf(input.streamFeatures),+ });if (!dispatch.execution) {throw new Error('Durable intervention resume did not create an operation');}@@ -2411,6 +2440,7 @@ export const aiAgentRouter = router({}const result = await ctx.aiAgentService.execAgent({+ acceptsMemberRuntimeEnd: acceptsMemberRuntimeEndOf(input.streamFeatures),agentId,appContext,autoStart,@@ -2576,6 +2606,7 @@ export const aiAgentRouter = router({workspaceId: ctx.workspaceId,});const result = await ctx.aiAgentService.execAgent({+ acceptsMemberRuntimeEnd: acceptsMemberRuntimeEndOf(task.streamFeatures),includeFinalState: task.includeFinalState,agentId,appContext,@@ -3503,7 +3534,9 @@ export const aiAgentRouter = router({};}- const dispatch = await dispatchClaimedAgentIntervention(resolution, ctx);+ const dispatch = await dispatchClaimedAgentIntervention(resolution, ctx, {+ acceptsMemberRuntimeEnd: acceptsMemberRuntimeEndOf(input.streamFeatures),+ });return {contractVersion: 2 as const,...(resolution.conversationUrl && { conversationUrl: resolution.conversationUrl }),diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.tsindex a08c8fca330..794b3f6f7ca 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts@@ -758,6 +758,16 @@ export class AgentRuntimeService {return true;}+ /**+ * Whether the client that started this operation declared it handles+ * `member_runtime_end`. An unknown or expired operation reads as `false`, so+ * a continuation then keeps the verbatim terminal every client understands.+ */+ async acceptsMemberRuntimeEnd(operationId: string): Promise<boolean> {+ const metadata = await this.coordinator.getOperationMetadata(operationId).catch(() => null);+ return metadata?.acceptsMemberRuntimeEnd === true;+ }+/*** Record whether the client still holds user messages queued behind a run.* Only the run's owner may flag it; an unknown or foreign operation is a@@ -1071,6 +1081,7 @@ export class AgentRuntimeService {*/async createOperation(params: OperationCreationParams): Promise<OperationCreationResult> {const {+ acceptsMemberRuntimeEnd,activeDeviceId,activeDeviceScope,operationId,@@ -1349,6 +1360,7 @@ export class AgentRuntimeService {const mirrorToOperationId =appContext?.orchestrationRole === 'member' ? (parentOperationId ?? undefined) : undefined;await this.coordinator.createAgentOperation(operationId, {+ acceptsMemberRuntimeEnd,agentConfig,// Persisted so a queue worker that never ran this op's init still// applies the owner-configured visitor redaction policy instead of thediff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.tsindex 7e5f08c143c..18fff93f10b 100644--- a/apps/server/src/services/agentRuntime/types.ts+++ b/apps/server/src/services/agentRuntime/types.ts@@ -403,6 +403,13 @@ export interface ExecGroupMemberResult {}export interface OperationCreationParams {+ /**+ * The client starting this run handles `member_runtime_end` (declared via+ * `aiAgent.execAgent`'s `streamFeatures`). Persisted on the op's metadata so+ * the Gateway stream notifier renames the group member terminals it mirrors+ * onto this op's channel only for a client that recognizes the new event.+ */+ acceptsMemberRuntimeEnd?: boolean;activeDeviceId?: string;/*** Principal pool the routed `activeDeviceId` lives in. `personal` when adiff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.tsindex 57d3598e53d..b8a1512f77c 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts@@ -152,6 +152,7 @@ vi.mock('@/database/models/userMemory/persona', () => ({vi.mock('@/server/services/agentRuntime', () => ({AgentRuntimeService: vi.fn().mockImplementation(function () {return {+ acceptsMemberRuntimeEnd: vi.fn().mockResolvedValue(false),completeGroupActionMember: mockCompleteGroupActionMember,createOperation: mockCreateOperation,ensureInterventionContinuationStarted: mockEnsureInterventionContinuationStarted,diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex 7256a917a96..8a56700f605 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -1516,6 +1516,7 @@ export class AiAgentService {},runContext,{+ acceptsMemberRuntimeEnd: params.acceptsMemberRuntimeEnd,approvalClaim,approvalSourceOperationId,approvalSourceToolMessageIds,diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.memberRuntimeEnd.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.memberRuntimeEnd.test.tsnew file mode 100644index 00000000000..6fec94fa304--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.memberRuntimeEnd.test.ts@@ -0,0 +1,111 @@+import { describe, expect, it, vi } from 'vitest';++import { startOperation } from '../startOperation';++vi.mock('@/libs/trpc/utils/internalJwt', () => ({+ signUserJWT: vi.fn().mockResolvedValue('jwt'),+}));++const setup = (sourceAccepts: boolean) => {+ const calls: string[] = [];+ const agentRuntimeService = {+ acceptsMemberRuntimeEnd: vi.fn(async () => {+ calls.push('read-source');+ return sourceAccepts;+ }),+ createOperation: vi.fn(async () => ({ autoStarted: true, messageId: 'msg-assistant' })),+ };+ const deps = {+ agentRuntimeService,+ messageModel: {},+ retirePendingApprovalOperation: vi.fn(async () => {+ calls.push('retire-source');+ }),+ topicModel: { updateMetadata: vi.fn() },+ userId: 'user-1',+ withholdGatewayToken: true,+ } as any;+ const ctx = {+ agentConfig: {},+ assistantMessageId: 'msg-assistant',+ model: 'gpt',+ provider: 'openai',+ resolvedAgentId: 'agt-supervisor',+ topicId: 'tpc-1',+ userMessageId: 'msg-user',+ } as any;+ const input = (extra: Record<string, unknown>) =>+ ({+ approvalClaim: {},+ approvalSourceToolMessageIds: [],+ autoStart: true,+ discovery: {+ credentialFactsPromise: Promise.resolve(undefined),+ modelMediaCapabilities: {},+ toolsResult: { enabledToolIds: [] },+ },+ initialContext: {},+ operationId: 'op-new',+ prep: { allMessages: [], deviceSystemInfo: {} },+ updateAbortedAssistantMessage: vi.fn(),+ userInterventionConfig: { approvalMode: 'manual' },+ ...extra,+ }) as any;+ return { agentRuntimeService, calls, ctx, deps, input };+};++describe('startOperation βΊ member_runtime_end declaration', () => {+ it('records the calling client declaration on the new operation', async () => {+ const { agentRuntimeService, ctx, deps, input } = setup(false);++ await startOperation(deps, ctx, input({ acceptsMemberRuntimeEnd: true }));++ expect(agentRuntimeService.createOperation).toHaveBeenCalledWith(+ expect.objectContaining({ acceptsMemberRuntimeEnd: true }),+ );+ expect(agentRuntimeService.acceptsMemberRuntimeEnd).not.toHaveBeenCalled();+ });++ // The v2 approval endpoint starts the continuation server-side, without the+ // client's `streamFeatures`: it is the same client, so the parked op's+ // declaration carries over (read before that op is retired).+ it('carries the parked operation declaration over to an approval continuation', async () => {+ const { agentRuntimeService, calls, ctx, deps, input } = setup(true);++ await startOperation(deps, ctx, input({ approvalSourceOperationId: 'op-parked' }));++ expect(agentRuntimeService.acceptsMemberRuntimeEnd).toHaveBeenCalledWith('op-parked');+ expect(agentRuntimeService.createOperation).toHaveBeenCalledWith(+ expect.objectContaining({ acceptsMemberRuntimeEnd: true }),+ );+ expect(calls).toEqual(['read-source', 'retire-source']);+ });++ // Codex P1 on #20102: an older client resuming an approval of a run a newer+ // client started must get what IT declared (nothing β false), not the parked+ // operation's `true`.+ it('keeps a resuming client explicit false over the parked operation declaration', async () => {+ const { agentRuntimeService, ctx, deps, input } = setup(true);++ await startOperation(+ deps,+ ctx,+ input({ acceptsMemberRuntimeEnd: false, approvalSourceOperationId: 'op-parked' }),+ );++ expect(agentRuntimeService.acceptsMemberRuntimeEnd).not.toHaveBeenCalled();+ expect(agentRuntimeService.createOperation).toHaveBeenCalledWith(+ expect.objectContaining({ acceptsMemberRuntimeEnd: false }),+ );+ });++ it('leaves the declaration unset for a client that did not make one', async () => {+ const { agentRuntimeService, ctx, deps, input } = setup(true);++ await startOperation(deps, ctx, input({}));++ expect(agentRuntimeService.createOperation).toHaveBeenCalledWith(+ expect.objectContaining({ acceptsMemberRuntimeEnd: undefined }),+ );+ });+});diff --git a/apps/server/src/services/aiAgent/pipeline/startOperation.ts b/apps/server/src/services/aiAgent/pipeline/startOperation.tsindex 57cbcafd845..e7356673e1d 100644--- a/apps/server/src/services/aiAgent/pipeline/startOperation.ts+++ b/apps/server/src/services/aiAgent/pipeline/startOperation.ts@@ -25,6 +25,8 @@ export interface StartOperationDeps {}export interface StartOperationInput {+ /** See {@link InternalExecAgentParams.acceptsMemberRuntimeEnd}. */+ acceptsMemberRuntimeEnd?: boolean;approvalClaim: ApprovalClaimState;approvalSourceOperationId?: string;approvalSourceToolMessageIds: string[];@@ -93,6 +95,7 @@ export const startOperation = async (userMessageId,} = ctx;const {+ acceptsMemberRuntimeEnd,approvalClaim,approvalSourceOperationId,approvalSourceToolMessageIds,@@ -145,7 +148,17 @@ export const startOperation = async (// Wrap in try-catch to handle operation startup failures (e.g., QStash unavailable)// If createOperation fails, we still have valid messages that need error infotry {+ // A server-internal approval continuation (no client of its own declared+ // anything β client-facing routes always pass a boolean) streams to the+ // parked operation's client: carry its `member_runtime_end` declaration over+ // (read here, before the parked operation is retired below).+ const memberRuntimeEndAccepted =+ acceptsMemberRuntimeEnd ??+ (approvalSourceOperationId+ ? await deps.agentRuntimeService.acceptsMemberRuntimeEnd(approvalSourceOperationId)+ : undefined);const result = await deps.agentRuntimeService.createOperation({+ acceptsMemberRuntimeEnd: memberRuntimeEndAccepted,includeFinalState: input.includeFinalState,activeDeviceId: discovery.activeDeviceId,activeDeviceScope: discovery.activeDeviceScope,diff --git a/apps/server/src/services/aiAgent/types.ts b/apps/server/src/services/aiAgent/types.tsindex 3fd6b7d8b70..502ea8499da 100644--- a/apps/server/src/services/aiAgent/types.ts+++ b/apps/server/src/services/aiAgent/types.ts@@ -74,6 +74,12 @@ export interface ExecRunContext {* This extends the public ExecAgentParams with server-side only options*/export interface InternalExecAgentParams extends ExecAgentParams {+ /**+ * The calling client handles `member_runtime_end`, derived from the+ * `streamFeatures` it declared on `aiAgent.execAgent`. See+ * `OperationCreationParams.acceptsMemberRuntimeEnd`.+ */+ acceptsMemberRuntimeEnd?: boolean;/** Additional plugin IDs to inject (e.g., task tool during task execution) */additionalPluginIds?: string[];/**diff --git a/packages/agent-gateway-client/src/client.test.ts b/packages/agent-gateway-client/src/client.test.tsindex e0b19b9fb09..9c6b64bef92 100644--- a/packages/agent-gateway-client/src/client.test.ts+++ b/packages/agent-gateway-client/src/client.test.ts@@ -370,6 +370,76 @@ describe('AgentStreamClient', () => {expect(client.connectionStatus).toBe('disconnected');});+ it('ignores the session_complete echo of a mirrored member terminal (G-02)', async () => {+ // A gateway that ends a session on ANY agent_runtime_end answers a+ // member's mirrored terminal with session_complete for the supervisor.+ // That is the member's echo, not the supervisor's end.+ const client = createClient(); // operationId: 'op-123'+ const onComplete = vi.fn();+ client.on('session_complete', onComplete);++ const ws = await connectAndAuth(client);+ ws.simulateMessage({+ event: {+ data: { reason: 'done' },+ operationId: 'op-member-456',+ stepIndex: 0,+ timestamp: 1,+ type: 'agent_runtime_end',+ },+ type: 'agent_event',+ });+ ws.simulateMessage({ type: 'session_complete' });++ expect(onComplete).not.toHaveBeenCalled();+ expect(client.connectionStatus).toBe('connected');++ // The supervisor keeps streaming and still ends on its own terminal.+ const events: any[] = [];+ client.on('agent_event', (e) => events.push(e));+ ws.simulateMessage({+ event: {+ data: { chunkType: 'text', content: 'SUP DONE' },+ operationId: 'op-123',+ stepIndex: 2,+ timestamp: 2,+ type: 'stream_chunk',+ },+ type: 'agent_event',+ });+ expect(events).toHaveLength(1);+ ws.simulateMessage({ type: 'session_complete' });+ expect(onComplete).toHaveBeenCalledOnce();+ expect(client.connectionStatus).toBe('disconnected');+ });++ // Codex P2 on #20102: a suspended tab handles the queued echo late but in+ // order; wall-clock time must not turn it into the supervisor's end.+ it('still reads a late echo as the member terminal and honors the next end (G-02)', async () => {+ const client = createClient(); // op-123+ const onComplete = vi.fn();+ client.on('session_complete', onComplete);++ const ws = await connectAndAuth(client);+ ws.simulateMessage({+ event: {+ data: { reason: 'done' },+ operationId: 'op-member-456',+ stepIndex: 0,+ timestamp: 1,+ type: 'agent_runtime_end',+ },+ type: 'agent_event',+ });+ await vi.advanceTimersByTimeAsync(30_000); // renderer suspended+ ws.simulateMessage({ type: 'session_complete' });+ expect(onComplete).not.toHaveBeenCalled();++ // The echo is spent: a further session end is the supervisor's own.+ ws.simulateMessage({ type: 'session_complete' });+ expect(onComplete).toHaveBeenCalledOnce();+ });+it('should emit session_complete and disconnect', async () => {const client = createClient();const onComplete = vi.fn();@@ -463,6 +533,102 @@ describe('AgentStreamClient', () => {expect(client.connectionStatus).toBe('disconnected');});+ // Codex P1 on #20102: a gateway that ends on ANY agent_runtime_end also+ // leaves its status terminal after a member's mirrored terminal, and a+ // resubscribe then reported the running supervisor as finished.+ describe('after a replayed mirrored member terminal (G-02)', () => {+ const replay = (+ ws: MockWebSocket,+ id: string,+ operationId: string,+ type: string,+ data = {},+ ) =>+ ws.simulateMessage({+ event: { data, operationId, stepIndex: 0, timestamp: 1, type },+ id,+ type: 'agent_event',+ });++ it('keeps the supervisor subscribed on the status that member left behind', async () => {+ const client = createClient({ resumeOnConnect: true }); // op-123+ const onComplete = vi.fn();+ client.on('session_complete', onComplete);++ const ws = await connectAndAuthResume(client);+ replay(ws, 'evt-1', 'op-member-456', 'agent_runtime_end', { reason: 'done' });+ // The supervisor's continuation after the member β still no own terminal.+ replay(ws, 'evt-2', 'op-123', 'step_start');+ ws.simulateMessage({ status: 'completed', type: 'resume_complete' });++ expect(onComplete).not.toHaveBeenCalled();+ expect(client.connectionStatus).toBe('connected');++ // The supervisor's own terminal still ends the session.+ ws.simulateMessage({+ event: {+ data: { reason: 'done' },+ operationId: 'op-123',+ stepIndex: 3,+ timestamp: 2,+ type: 'agent_runtime_end',+ },+ id: 'evt-3',+ type: 'agent_event',+ });+ expect(client.connectionStatus).toBe('disconnected');+ });++ it('still completes on a status the member terminal cannot explain', async () => {+ const client = createClient({ resumeOnConnect: true });+ const onComplete = vi.fn();+ client.on('session_complete', onComplete);++ const ws = await connectAndAuthResume(client);+ replay(ws, 'evt-1', 'op-member-456', 'agent_runtime_end', { reason: 'done' });+ // e.g. the inactivity watchdog failed the supervisor afterwards.+ ws.simulateMessage({ status: 'error', type: 'resume_complete' });++ expect(onComplete).toHaveBeenCalledWith({ source: 'resume_status', status: 'error' });+ });++ // Codex P1 on #20102 (3rd pass): a member terminal seen before the+ // disconnect proves nothing about the resumed DO β it may have hibernated+ // away the supervisor's own terminal while keeping `completed`.+ it('trusts the status after an empty replay, even with a member terminal seen before', async () => {+ const client = createClient({ resumeOnConnect: true });+ const onComplete = vi.fn();+ client.on('session_complete', onComplete);++ const ws = await connectAndAuthResume(client);+ ws.simulateMessage({ status: 'running', type: 'resume_complete' });+ replay(ws, 'evt-1', 'op-member-456', 'agent_runtime_end', { reason: 'done' });++ ws.simulateClose();+ await vi.advanceTimersByTimeAsync(1000); // reconnect delay+ await vi.advanceTimersByTimeAsync(1);+ const ws2 = getLatestWs();+ ws2.simulateMessage({ type: 'auth_success' });+ // Hibernated buffer: nothing after evt-1 is replayed.+ ws2.simulateMessage({ status: 'completed', type: 'resume_complete' });++ expect(onComplete).toHaveBeenCalledWith({ source: 'resume_status', status: 'completed' });+ });++ it('completes once the supervisor terminal was replayed after the member', async () => {+ const client = createClient({ resumeOnConnect: true });+ const onComplete = vi.fn();+ client.on('session_complete', onComplete);++ const ws = await connectAndAuthResume(client);+ replay(ws, 'evt-1', 'op-member-456', 'agent_runtime_end', { reason: 'done' });+ replay(ws, 'evt-2', 'op-123', 'agent_runtime_end', { reason: 'done' });+ ws.simulateMessage({ status: 'completed', type: 'resume_complete' });++ expect(client.connectionStatus).toBe('disconnected');+ });+ });+it('flushes replayed events before completing on a terminal status', async () => {const client = createClient({ resumeOnConnect: true });const events: any[] = [];diff --git a/packages/agent-gateway-client/src/client.ts b/packages/agent-gateway-client/src/client.tsindex 83578781944..0967ceb9866 100644--- a/packages/agent-gateway-client/src/client.ts+++ b/packages/agent-gateway-client/src/client.ts@@ -1,3 +1,4 @@+import { MirroredTerminalEchoGuard } from './mirroredTerminalEcho';import type {AgentStreamClientEvents,AgentStreamClientOptions,@@ -83,6 +84,7 @@ export class AgentStreamClient extends TypedEmitter {private readonly autoReconnect: boolean;private readonly resumeOnConnect: boolean;private token: string;+ private readonly terminalEchoGuard: MirroredTerminalEchoGuard;constructor(options: AgentStreamClientOptions) {super();@@ -92,6 +94,7 @@ export class AgentStreamClient extends TypedEmitter {this.autoReconnect = options.autoReconnect ?? true;this.resumeOnConnect = options.resumeOnConnect ?? false;this.lastEventId = options.lastEventId ?? '';+ this.terminalEchoGuard = new MirroredTerminalEchoGuard(options.operationId);}// βββ Public API βββ@@ -250,6 +253,7 @@ export class AgentStreamClient extends TypedEmitter {// gateway will hand back the real session status. Legacy gateways// ignore the flag and just replay β we then rely on live events, never// guessing completion from silence.+ this.terminalEchoGuard.beginReplay();this.sendMessage({ lastEventId: this.lastEventId, type: 'resume', wantStatus: true });this.emit('connected');break;@@ -276,6 +280,7 @@ export class AgentStreamClient extends TypedEmitter {case 'agent_event': {const agentEvent: AgentStreamEvent = message.event;if (message.id) this.lastEventId = message.id;+ this.terminalEchoGuard.observe(agentEvent);// A single WebSocket is multiplexed: alongside this op's events it may// carry forwarded events from other operations (e.g. broadcast council@@ -329,9 +334,11 @@ export class AgentStreamClient extends TypedEmitter {}const terminal =- message.status === 'completed' ||- message.status === 'error' ||- message.status === 'interrupted';+ (message.status === 'completed' ||+ message.status === 'error' ||+ message.status === 'interrupted') &&+ // A status left by a mirrored member's terminal, not this op's end.+ !this.terminalEchoGuard.isStaleResumeStatus(message.status);if (terminal) {this.sessionEnded = true;@@ -349,6 +356,9 @@ export class AgentStreamClient extends TypedEmitter {}case 'session_complete': {+ // A member's mirrored terminal, echoed back as the end of THIS+ // session by gateways that end on any `agent_runtime_end`.+ if (this.terminalEchoGuard.consumeEcho('session_complete')) break;this.sessionEnded = true;// Flush any buffered resume events before disconnectingif (this.resumeMode) {diff --git a/packages/agent-gateway-client/src/index.ts b/packages/agent-gateway-client/src/index.tsindex 817e095db39..bf8eb56e807 100644--- a/packages/agent-gateway-client/src/index.ts+++ b/packages/agent-gateway-client/src/index.ts@@ -1,5 +1,10 @@export { AgentStreamClient } from './client';export { sanitizeAgentInterventionRequestForReview } from './intervention';+export {+ MirroredTerminalEchoGuard,+ type MirroredTerminalEchoProtocol,+ type MirroredTerminalEchoSignal,+} from './mirroredTerminalEcho';export {createOperationClient,type OperationClient,@@ -47,6 +52,7 @@ export type {AgentInterventionRequestData,AgentInterventionResponseData,AgentStreamClientEvents,+ AgentStreamClientFeature,AgentStreamClientOptions,AgentStreamEvent,AgentStreamEventType,diff --git a/packages/agent-gateway-client/src/mirroredTerminalEcho.ts b/packages/agent-gateway-client/src/mirroredTerminalEcho.tsnew file mode 100644index 00000000000..1bae0bb000c--- /dev/null+++ b/packages/agent-gateway-client/src/mirroredTerminalEcho.ts@@ -0,0 +1,161 @@+import type { AgentStreamEvent, SessionStatus } from './types';++/** The status the gateway DO derives from an `agent_runtime_end` (see `AgentOperationDO.pushEvent`). */+const sessionStatusOf = (event: AgentStreamEvent): SessionStatus => {+ const reason = (event.data as { reason?: string } | undefined)?.reason;+ return reason === 'error' ? 'error' : reason === 'interrupted' ? 'interrupted' : 'completed';+};++/**+ * Recognizes a session end that was caused by ANOTHER operation's terminal.+ *+ * A group member's events are mirrored onto the supervisor's channel. Servers+ * that predate `member_runtime_end` mirror the member's terminal verbatim, and+ * gateway builds that end a session on any `agent_runtime_end` then answer it+ * with `session_complete` (or a terminal lifecycle status) for the supervisor β+ * even though the supervisor is still running. Treating that as the owner's end+ * cut the supervisor stream short, cleared its running mark and dropped its+ * queued follow-ups.+ */+/** A session-ending signal a gateway echoes for a mirrored member terminal. */+export type MirroredTerminalEchoSignal = 'session_complete' | 'status_change';++/** Which gateway protocol the guarded subscription speaks. */+export type MirroredTerminalEchoProtocol = 'v1' | 'v2';++/**+ * The echoes a gateway sends for an `agent_runtime_end` that left `status`.+ * v1 answers every ending with `session_complete`. v2 sends a terminal+ * `status_change` carrying the status for `error` / `interrupted`, and+ * `session_complete` for `completed` (PROTOCOL_V2.md Β§6) β plus, from builds+ * that still send both, a `status_change{completed}`. Tolerating that one is+ * safe: the owner's own completion arrives with its own `agent_runtime_end`+ * (which clears everything owed) or ends on the `session_complete` after it.+ */+const echoKeysOf = (protocol: MirroredTerminalEchoProtocol, status: SessionStatus): string[] => {+ if (protocol === 'v1') return ['session_complete'];+ return status === 'completed'+ ? ['session_complete', 'status_change:completed']+ : [`status_change:${status}`];+};++export class MirroredTerminalEchoGuard {+ /**+ * Echoes still owed for verbatim foreign terminals, keyed by the exact signal+ * (see `echoKeysOf`). Counted by message+ * order, not wall-clock time: a suspended tab or renderer delivers the echo+ * late but still in order. Only the signal that will actually arrive is owed,+ * so nothing stays armed to swallow the owner's own end. An owner event proves+ * the owner alive and clears it. A v1 resume clears it; a v2 resume carries it+ * into the replay (echoes are sequenced, so one sent after the last event this+ * client saw is replayed) and drops what the replay did not deliver.+ */+ private pendingEchoes = new Map<string, number>();+ /** The status the latest foreign terminal left, while its echoes are owed. */+ private owedForeignStatus: SessionStatus | undefined;+ /** A v2 resume replay is in flight (between `beginReplay` and `endReplay`). */+ private replaying = false;+ /**+ * The session status another operation's `agent_runtime_end` REPLAYED BY THE+ * CURRENT RESUME would have left on this channel's DO, while no terminal of+ * our own has arrived since. Scoped to one resume on purpose: only a replay+ * that still carries the member's terminal proves the buffer after it is+ * intact β a terminal seen before a disconnect proves nothing once the DO may+ * have hibernated away the owner's own terminal.+ */+ private replayForeignStatus: SessionStatus | undefined;++ constructor(+ private readonly operationId: string,+ private readonly protocol: MirroredTerminalEchoProtocol = 'v1',+ ) {}++ /** Record an incoming agent event. */+ observe(event: AgentStreamEvent): void {+ const isOwn = !event.operationId || event.operationId === this.operationId;+ if (isOwn) {+ // The owner is demonstrably alive after the member ended.+ this.clearPendingEchoes();+ if (event.type === 'agent_runtime_end' || event.type === 'error') {+ this.replayForeignStatus = undefined;+ }+ return;+ }+ if (event.type === 'agent_runtime_end') {+ const status = sessionStatusOf(event);+ for (const key of echoKeysOf(this.protocol, status)) {+ this.pendingEchoes.set(key, (this.pendingEchoes.get(key) ?? 0) + 1);+ }+ this.owedForeignStatus = status;+ this.replayForeignStatus = status;+ }+ }++ /** A resume / (re)subscribe is starting: only what it replays counts from here. */+ beginReplay(): void {+ this.replayForeignStatus = undefined;+ if (this.protocol === 'v1') {+ // v1 echoes are not replayed: one not received on the old connection is+ // not owed on this one.+ this.clearPendingEchoes();+ return;+ }+ // v2 echoes are sequenced: a member terminal acknowledged just before the+ // socket dropped leaves its echo to this replay. Keep owing it.+ this.replaying = true;+ }++ /**+ * The v2 resume replay is over (`resume_complete`, not `pending`). An echo it+ * did not deliver is not coming, so stop owing it.+ */+ endReplay(): void {+ if (!this.replaying) return;+ this.replaying = false;+ this.clearPendingEchoes();+ }++ /**+ * Whether a terminal status reported on resume is the one a mirrored member+ * terminal left on this DO. Such a gateway sets its status on ANY+ * `agent_runtime_end` and never resets it on later events, so a (re)subscribe+ * after a member ended reads the supervisor as finished while it still runs β+ * even when supervisor events were replayed after the member's end.+ *+ * Only trusted when this resume replayed that member terminal (or, on v2, an+ * echo still owed for it) and nothing was dropped (`gap`): the buffer only+ * loses its oldest events, so the member's terminal or its echo still being+ * there means any later owner terminal would be too. Without that+ * provenance β an empty replay after hibernation, a gapped replay, a member+ * terminal and its echo only seen before the disconnect β the DO's+ * authoritative status wins. So does any other status (a watchdog's `error`).+ */+ isStaleResumeStatus(status: SessionStatus | undefined, options?: { gap?: boolean }): boolean {+ if (options?.gap) return false;+ return this.replayForeignStatus !== undefined && status === this.replayForeignStatus;+ }++ /**+ * Whether a session-ending signal arriving now is a mirrored terminal's echo.+ * Consumes one owed echo of that kind, so a genuine end arriving after the+ * echoes (a watchdog's status, the owner's own session end) is honored.+ */+ consumeEcho(signal: MirroredTerminalEchoSignal, status?: SessionStatus): boolean {+ const key = signal === 'status_change' ? `status_change:${status}` : signal;+ const owed = this.pendingEchoes.get(key) ?? 0;+ if (owed === 0) return false;+ if (owed === 1) this.pendingEchoes.delete(key);+ else this.pendingEchoes.set(key, owed - 1);+ // An echo replayed after the member terminal proves the buffer from there on+ // is intact, just as the replayed terminal itself would.+ if (this.replaying && this.owedForeignStatus !== undefined) {+ this.replayForeignStatus = this.owedForeignStatus;+ }+ return true;+ }++ private clearPendingEchoes(): void {+ this.pendingEchoes.clear();+ this.owedForeignStatus = undefined;+ }+}diff --git a/packages/agent-gateway-client/src/mux/GatewayMuxClient.test.ts b/packages/agent-gateway-client/src/mux/GatewayMuxClient.test.tsindex 4c73dbb93d7..770855a4e46 100644--- a/packages/agent-gateway-client/src/mux/GatewayMuxClient.test.ts+++ b/packages/agent-gateway-client/src/mux/GatewayMuxClient.test.ts@@ -621,6 +621,347 @@ describe('GatewayMuxClient', () => {expect(sub.active).toBe(false);});+ it('ignores the session end echoed after a mirrored member terminal (G-02)', async () => {+ const { mux } = createMux();+ const ws = await connectAndReady(mux);+ const sub = mux.subscribe('op-1');+ const onComplete = vi.fn();+ sub.on('session_complete', onComplete);++ ws.simulateMessage(agentEvent('op-1', '1', 'agent_runtime_end', 'op-member'));+ ws.simulateMessage({+ id: '2',+ operationId: 'op-1',+ status: 'completed',+ type: 'status_change',+ });+ ws.simulateMessage({ operationId: 'op-1', type: 'session_complete' } as any);++ expect(onComplete).not.toHaveBeenCalled();+ expect(sub.active).toBe(true);++ ws.simulateMessage(agentEvent('op-1', '3', 'agent_runtime_end'));+ expect(onComplete).toHaveBeenCalledOnce();+ expect(sub.active).toBe(false);+ });++ // Codex P1 on #20102: the resubscribe reply reports the status a member's+ // mirrored terminal left on the supervisor's DO.+ it('keeps a resubscribed supervisor alive on the status a replayed member terminal left (G-02)', async () => {+ const { mux } = createMux();+ const ws = await connectAndReady(mux);+ const sub = mux.subscribe('op-1');+ const onComplete = vi.fn();+ sub.on('session_complete', onComplete);++ ws.simulateMessage({+ event: {+ data: { reason: 'done' },+ operationId: 'op-member',+ stepIndex: 0,+ timestamp: 1,+ type: 'agent_runtime_end',+ } as any,+ id: '1',+ operationId: 'op-1',+ type: 'agent_event',+ });+ ws.simulateMessage(agentEvent('op-1', '2', 'step_start'));+ ws.simulateMessage({+ gap: false,+ operationId: 'op-1',+ status: 'completed',+ type: 'resume_complete',+ });++ expect(onComplete).not.toHaveBeenCalled();+ expect(sub.active).toBe(true);++ // A status the member's terminal cannot explain still ends it.+ ws.simulateMessage({+ gap: false,+ operationId: 'op-1',+ status: 'error',+ type: 'resume_complete',+ });+ expect(onComplete).toHaveBeenCalledWith({ source: 'resume_status', status: 'error' });+ expect(sub.active).toBe(false);+ });++ // Codex P1 on #20102 (3rd pass): without the member terminal in THIS+ // replay, or with part of the replay dropped, the DO's status wins.+ it('trusts a gapped resume status even after a replayed member terminal', async () => {+ const { mux } = createMux();+ const ws = await connectAndReady(mux);+ const sub = mux.subscribe('op-1');+ const onComplete = vi.fn();+ sub.on('session_complete', onComplete);++ ws.simulateMessage({+ event: {+ data: { reason: 'done' },+ operationId: 'op-member',+ stepIndex: 0,+ timestamp: 1,+ type: 'agent_runtime_end',+ } as any,+ id: '1',+ operationId: 'op-1',+ type: 'agent_event',+ });+ ws.simulateMessage({+ gap: true,+ operationId: 'op-1',+ status: 'completed',+ type: 'resume_complete',+ });++ expect(onComplete).toHaveBeenCalledWith({ source: 'resume_status', status: 'completed' });+ });++ it('trusts the resubscribe status when the member terminal was only seen before the reconnect', async () => {+ const { mux } = createMux();+ const sub = mux.subscribe('op-1');+ const ws = await connectAndReady(mux);+ const onComplete = vi.fn();+ sub.on('session_complete', onComplete);++ ws.simulateMessage({+ gap: false,+ operationId: 'op-1',+ status: 'running',+ type: 'resume_complete',+ });+ ws.simulateMessage({+ event: {+ data: { reason: 'done' },+ operationId: 'op-member',+ stepIndex: 0,+ timestamp: 1,+ type: 'agent_runtime_end',+ } as any,+ id: '1',+ operationId: 'op-1',+ type: 'agent_event',+ });++ ws.simulateClose();+ await vi.advanceTimersByTimeAsync(500);+ const ws2 = await settle();+ ws2.simulateMessage(READY);+ // Hibernated DO: empty replay, authoritative `completed`.+ ws2.simulateMessage({+ gap: false,+ operationId: 'op-1',+ status: 'completed',+ type: 'resume_complete',+ });++ expect(onComplete).toHaveBeenCalledWith({ source: 'resume_status', status: 'completed' });+ });++ // Codex P1 on #20102 (round 2): the member terminal was acknowledged before+ // the socket dropped, so the resubscribe replays only its sequenced echo.+ describe('carries an owed echo across a reconnect (G-02)', () => {+ const memberEnd = (reason: string): MuxServerMessage => ({+ event: {+ data: { reason },+ operationId: 'op-member',+ stepIndex: 0,+ timestamp: 1,+ type: 'agent_runtime_end',+ } as any,+ id: '1',+ operationId: 'op-1',+ type: 'agent_event',+ });++ const reconnectAfterMemberEnd = async (reason: string) => {+ const { mux } = createMux();+ const sub = mux.subscribe('op-1');+ const ws = await connectAndReady(mux);+ const onComplete = vi.fn();+ sub.on('session_complete', onComplete);+ ws.simulateMessage(memberEnd(reason));++ ws.simulateClose();+ await vi.advanceTimersByTimeAsync(500);+ const ws2 = await settle();+ ws2.simulateMessage(READY);+ return { onComplete, sub, ws2 };+ };++ it('reads a replayed session_complete echo and its stamped status as the member end', async () => {+ const { onComplete, sub, ws2 } = await reconnectAfterMemberEnd('done');++ ws2.simulateMessage({ id: '2', operationId: 'op-1', type: 'session_complete' } as any);+ ws2.simulateMessage({+ gap: false,+ operationId: 'op-1',+ status: 'completed',+ type: 'resume_complete',+ });++ expect(onComplete).not.toHaveBeenCalled();+ expect(sub.active).toBe(true);++ ws2.simulateMessage(agentEvent('op-1', '3', 'agent_runtime_end'));+ expect(onComplete).toHaveBeenCalledOnce();+ expect(sub.active).toBe(false);+ });++ it('reads a replayed terminal status_change echo as the member end', async () => {+ const { onComplete, sub, ws2 } = await reconnectAfterMemberEnd('error');++ ws2.simulateMessage({+ id: '2',+ operationId: 'op-1',+ status: 'error',+ type: 'status_change',+ });+ ws2.simulateMessage({+ gap: false,+ operationId: 'op-1',+ status: 'error',+ type: 'resume_complete',+ });++ expect(onComplete).not.toHaveBeenCalled();+ expect(sub.active).toBe(true);+ });++ it('stops owing an echo the replay did not deliver', async () => {+ const { onComplete, ws2 } = await reconnectAfterMemberEnd('error');++ ws2.simulateMessage({+ gap: false,+ operationId: 'op-1',+ status: 'running',+ type: 'resume_complete',+ });+ // A later watchdog error is the supervisor's genuine end.+ ws2.simulateMessage({+ id: '2',+ operationId: 'op-1',+ status: 'error',+ type: 'status_change',+ });++ expect(onComplete).toHaveBeenCalledWith({ source: 'status_change', status: 'error' });+ });+ });++ // Codex P2 on #20102: echoes are counted by order, not by a time window.+ it('reads late echoes as the member terminal and honors the next end (G-02)', async () => {+ const { mux } = createMux();+ const ws = await connectAndReady(mux);+ const sub = mux.subscribe('op-1');+ const onComplete = vi.fn();+ sub.on('session_complete', onComplete);++ ws.simulateMessage(agentEvent('op-1', '1', 'agent_runtime_end', 'op-member'));+ await vi.advanceTimersByTimeAsync(30_000); // renderer suspended+ ws.simulateMessage({+ id: '2',+ operationId: 'op-1',+ status: 'completed',+ type: 'status_change',+ });+ ws.simulateMessage({ operationId: 'op-1', type: 'session_complete' } as any);+ expect(onComplete).not.toHaveBeenCalled();+ expect(sub.active).toBe(true);++ // Echoes spent: a watchdog's terminal status now ends the supervisor.+ ws.simulateMessage({ id: '3', operationId: 'op-1', status: 'error', type: 'status_change' });+ expect(onComplete).toHaveBeenCalledWith({ source: 'status_change', status: 'error' });+ });++ // Codex P1 on #20102: v2 echoes a member ending with ONE signal, chosen by+ // its status β only that one may be owed, or the leftover swallows the+ // supervisor's own end.+ describe('owes only the v2 echo the member status produces (G-02)', () => {+ const memberEnd = (reason: string) =>+ ({+ event: {+ data: { reason },+ operationId: 'op-member',+ stepIndex: 0,+ timestamp: 1,+ type: 'agent_runtime_end',+ } as any,+ id: '1',+ operationId: 'op-1',+ type: 'agent_event',+ }) as MuxServerMessage;++ it('interrupted member, then the supervisor completes via session_complete', async () => {+ const { mux } = createMux();+ const ws = await connectAndReady(mux);+ const sub = mux.subscribe('op-1');+ const onComplete = vi.fn();+ sub.on('session_complete', onComplete);++ ws.simulateMessage(memberEnd('interrupted'));+ ws.simulateMessage({+ id: '2',+ operationId: 'op-1',+ status: 'interrupted',+ type: 'status_change',+ });+ expect(onComplete).not.toHaveBeenCalled();++ ws.simulateMessage({ id: '3', operationId: 'op-1', type: 'session_complete' } as any);+ expect(onComplete).toHaveBeenCalledWith({ source: 'raw_session_complete' });+ expect(sub.active).toBe(false);+ });++ it('completed member, then the supervisor fails via status_change{error}', async () => {+ const { mux } = createMux();+ const ws = await connectAndReady(mux);+ const sub = mux.subscribe('op-1');+ const onComplete = vi.fn();+ sub.on('session_complete', onComplete);++ ws.simulateMessage(memberEnd('done'));+ ws.simulateMessage({ id: '2', operationId: 'op-1', type: 'session_complete' } as any);+ expect(onComplete).not.toHaveBeenCalled();++ ws.simulateMessage({+ id: '3',+ operationId: 'op-1',+ status: 'error',+ type: 'status_change',+ });+ expect(onComplete).toHaveBeenCalledWith({ source: 'status_change', status: 'error' });+ expect(sub.active).toBe(false);+ });++ it('errored member, then the supervisor is interrupted', async () => {+ const { mux } = createMux();+ const ws = await connectAndReady(mux);+ const sub = mux.subscribe('op-1');+ const onComplete = vi.fn();+ sub.on('session_complete', onComplete);++ ws.simulateMessage(memberEnd('error'));+ ws.simulateMessage({+ id: '2',+ operationId: 'op-1',+ status: 'error',+ type: 'status_change',+ });+ expect(onComplete).not.toHaveBeenCalled();++ ws.simulateMessage({+ id: '3',+ operationId: 'op-1',+ status: 'interrupted',+ type: 'status_change',+ });+ expect(onComplete).toHaveBeenCalledWith({ source: 'status_change', status: 'interrupted' });+ });+ });+it('subscribe_failed emits auth_failed and ends the subscription', async () => {const { mux } = createMux();const ws = await connectAndReady(mux);diff --git a/packages/agent-gateway-client/src/mux/GatewayMuxClient.ts b/packages/agent-gateway-client/src/mux/GatewayMuxClient.tsindex 5eb57a0f9ba..49e6313ceb2 100644--- a/packages/agent-gateway-client/src/mux/GatewayMuxClient.ts+++ b/packages/agent-gateway-client/src/mux/GatewayMuxClient.ts@@ -1,3 +1,4 @@+import { MirroredTerminalEchoGuard } from '../mirroredTerminalEcho';import type {AgentStreamEvent,AgentStreamSessionCompletion,@@ -100,6 +101,7 @@ class OperationSubscriptionImpl implements OperationSubscription {private _lastEventId: string;private lastSeq: number;private readonly listeners: ListenerMap;+ private readonly terminalEchoGuard: MirroredTerminalEchoGuard;constructor(private readonly mux: GatewayMuxClient,@@ -111,6 +113,7 @@ class OperationSubscriptionImpl implements OperationSubscription {this._lastEventId = options.lastEventId ?? '';this.lastSeq = Number(this._lastEventId) || 0;this.listeners = new ListenerMap(`GatewayMuxClient:${operationId}`);+ this.terminalEchoGuard = new MirroredTerminalEchoGuard(operationId, 'v2');}get active(): boolean {@@ -183,6 +186,11 @@ class OperationSubscriptionImpl implements OperationSubscription {this.end();}+ /** @internal A (re)subscribe was sent: its replay starts now. */+ beginReplay(): void {+ this.terminalEchoGuard.beginReplay();+ }+/** @internal */handleMessage(message: MuxOperationMessage): void {if (!this._active) return;@@ -215,17 +223,26 @@ class OperationSubscriptionImpl implements OperationSubscription {const isOwnTerminal =(agentEvent.type === 'agent_runtime_end' || agentEvent.type === 'error') &&(!agentEvent.operationId || agentEvent.operationId === this.operationId);+ this.terminalEchoGuard.observe(agentEvent);this.listeners.emit('agent_event', agentEvent);if (isOwnTerminal) this.finish({ source: 'agent_event' });break;}case 'session_complete': {+ // A member's mirrored terminal echoed back as the end of this op β see+ // `MirroredTerminalEchoGuard`.+ if (this.terminalEchoGuard.consumeEcho('session_complete')) break;this.finish({ source: 'raw_session_complete' });break;}case 'status_change': {+ if (+ isTerminalStatus(message.status) &&+ this.terminalEchoGuard.consumeEcho('status_change', message.status)+ )+ break;this.listeners.emit('status_change', message.status);if (isTerminalStatus(message.status)) {this.finish({ source: 'status_change', status: message.status });@@ -242,9 +259,17 @@ class OperationSubscriptionImpl implements OperationSubscription {// `pending` = the op DO has not seen `init` yet; the hub replays later.// Non-terminal status = the run is alive, keep streaming. Never guess// completion from silence (see v1 AgentStreamClient).- if (!message.pending && isTerminalStatus(message.status)) {+ if (+ !message.pending &&+ isTerminalStatus(message.status) &&+ // A status left by a mirrored member's terminal β see+ // `MirroredTerminalEchoGuard.isStaleResumeStatus`.+ !this.terminalEchoGuard.isStaleResumeStatus(message.status, { gap: message.gap })+ ) {this.finish({ source: 'resume_status', status: message.status });+ break;}+ if (!message.pending) this.terminalEchoGuard.endReplay();break;}@@ -871,6 +896,7 @@ export class GatewayMuxClient {type: 'subscribe',});if (!sent) return;+ subscription.beginReplay();subscription.notifyStatus('connected');subscription.emit('connected');}diff --git a/packages/agent-gateway-client/src/types.ts b/packages/agent-gateway-client/src/types.tsindex ed2cb200d1f..fda0b40c3d1 100644--- a/packages/agent-gateway-client/src/types.ts+++ b/packages/agent-gateway-client/src/types.ts@@ -2,9 +2,26 @@ import type { UIChatMessage } from '@lobechat/types';// βββ Agent Stream Event (mirrors server StreamEvent) βββ+/**+ * Stream features a client declares when it starts a run+ * (`aiAgent.execAgent`'s `streamFeatures`), so the server only sends event+ * shapes that client understands.+ *+ * - `member_runtime_end`: a mirrored group member's terminal arrives on the+ * supervisor's channel as `member_runtime_end` instead of `agent_runtime_end`.+ */+export type AgentStreamClientFeature = 'member_runtime_end';+export type AgentStreamEventType =| 'agent_runtime_init'| 'agent_runtime_end'+ /**+ * A mirrored operation's terminal, delivered on another operation's channel+ * (a group member finishing, forwarded onto the supervisor's socket). Same+ * payload as `agent_runtime_end`, but NOT terminal for the channel it rides+ * on: the gateway only closes a session on `agent_runtime_end`.+ */+ | 'member_runtime_end'| 'stream_start'| 'stream_chunk'| 'stream_end'diff --git a/src/services/aiAgent.execAgentTask.test.ts b/src/services/aiAgent.execAgentTask.test.tsnew file mode 100644index 00000000000..df9db0a6385--- /dev/null+++ b/src/services/aiAgent.execAgentTask.test.ts@@ -0,0 +1,29 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { aiAgentService } from './aiAgent';++const mocks = vi.hoisted(() => ({ execAgent: vi.fn() }));++vi.mock('@/libs/trpc/client', () => ({+ lambdaClient: { aiAgent: { execAgent: { mutate: mocks.execAgent } } },+}));++describe('aiAgentService.execAgentTask', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ // The server renames a mirrored group member terminal to `member_runtime_end`+ // only for a client that declares it handles the new event.+ it('declares that this client handles member_runtime_end', async () => {+ mocks.execAgent.mockResolvedValueOnce({ success: true });+ const signal = new AbortController().signal;++ await aiAgentService.execAgentTask({ agentId: 'agt-1', prompt: 'hi' }, { signal });++ expect(mocks.execAgent).toHaveBeenCalledWith(+ { agentId: 'agt-1', prompt: 'hi', streamFeatures: ['member_runtime_end'] },+ { signal },+ );+ });+});diff --git a/src/services/aiAgent.intervention.test.ts b/src/services/aiAgent.intervention.test.tsindex b5a8e6e1a27..9dbaeda67d4 100644--- a/src/services/aiAgent.intervention.test.ts+++ b/src/services/aiAgent.intervention.test.ts@@ -29,6 +29,19 @@ describe('aiAgentService.resolveAgentInterventionBySource', () => {vi.clearAllMocks();});+ // G-02: the resolving client subscribes to the continuation, so it declares+ // its own `member_runtime_end` support rather than inheriting the parked run's.+ it('declares this client stream features with the resolution', async () => {+ mocks.resolveAgentInterventionBySource.mockResolvedValueOnce({ success: false });++ await aiAgentService.resolveAgentInterventionBySource(params);++ expect(mocks.resolveAgentInterventionBySource).toHaveBeenCalledWith({+ ...params,+ streamFeatures: ['member_runtime_end'],+ });+ });+it('preserves a claimed result and its precreated execution', async () => {const execution = {autoStarted: true,diff --git a/src/services/aiAgent.ts b/src/services/aiAgent.tsindex 784217a6a2c..c019f5a6937 100644--- a/src/services/aiAgent.ts+++ b/src/services/aiAgent.ts@@ -1,3 +1,4 @@+import type { AgentStreamClientFeature } from '@lobechat/agent-gateway-client';import type {ExecAgentAppContext,ExecAgentResult,@@ -11,6 +12,9 @@ import { lambdaClient } from '@/libs/trpc/client';export type { ExecAgentResult, ScheduleAgentRunParams, ScheduleAgentRunResult };+/** Gateway stream features every run started from this client handles. */+const STREAM_FEATURES: AgentStreamClientFeature[] = ['member_runtime_end'];+/*** Resume instruction for an operation that hit `human_approve_required`. When* present, the new op acts as the "continue" step: server reads the target tool@@ -257,7 +261,10 @@ class AiAgentService {params: ExecAgentTaskParams,options?: { signal?: AbortSignal },): Promise<ExecAgentResult> {- return await lambdaClient.aiAgent.execAgent.mutate(params, options);+ return await lambdaClient.aiAgent.execAgent.mutate(+ { ...params, streamFeatures: STREAM_FEATURES },+ options,+ );}/**@@ -341,7 +348,11 @@ class AiAgentService {async resolveAgentInterventionBySource(params: ResolveAgentInterventionBySourceParams,): Promise<ResolveAgentInterventionBySourceResult> {- const result = await lambdaClient.aiAgent.resolveAgentInterventionBySource.mutate(params);+ const result = await lambdaClient.aiAgent.resolveAgentInterventionBySource.mutate({+ ...params,+ // This client subscribes to the continuation it starts.+ streamFeatures: STREAM_FEATURES,+ });if (!result.success) return { handled: false };diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.tsindex e96d49c0118..d3f7764ede3 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts@@ -1114,6 +1114,7 @@ describe('ConversationControl actions', () => {batchId: 'batch-durable',operationId: 'operation-durable',resolutionRequestId: expect.any(String),+ streamFeatures: ['member_runtime_end'],targets: [{ toolCallId: 'call-durable', toolMessageId: 'tool-msg-durable' }],});expect(result.current.dbMessagesMap[chatKey][0].plugin?.arguments).toBe(@@ -3138,6 +3139,7 @@ describe('ConversationControl actions', () => {batchId: `batch-${interactionKind}`,operationId: `server-operation-${interactionKind}`,resolutionRequestId: expect.any(String),+ streamFeatures: ['member_runtime_end'],targets: [{ toolCallId: `call-${interactionKind}`, toolMessageId: toolMessage.id }],});const resolvingIntervention = {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 dc7f3690530..50af004e219 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@@ -153,6 +153,17 @@ describe('createGatewayMemberStreamHandler', () => {await vi.waitFor(() => expect(refreshGroup).toHaveBeenCalledTimes(3), { timeout: 4000 });});+ // G-02: the server mirrors a member's terminal onto the supervisor's+ // channel as `member_runtime_end`, so the gateway keeps that session open.+ it('re-reads the group tree on the mirrored member_runtime_end (G-02)', async () => {+ const { handler, refreshGroup, store } = setup();++ handler(makeEvent('member_runtime_end', { reason: 'waiting_for_human' }));+ await vi.waitFor(() => expect(refreshGroup).toHaveBeenCalledTimes(1));++ expect(store.completeOperation).toHaveBeenCalledWith('local-member-op');+ });+it('leaves a normal member end to the supervisor terminal refetch', () => {const { handler, refreshGroup } = setup();@@ -209,4 +220,21 @@ describe('createGatewayMemberStreamHandler', () => {expect(mergeGroupSnapshot(fetched, [], new Set())).toBe(fetched);});});++ it('retires the member column on the mirrored member_runtime_end (G-02)', () => {+ const store = createStore();+ const handler = createGatewayMemberStreamHandler(() => store, {+ context,+ ensureGroupHydrated: vi.fn().mockResolvedValue(undefined),+ liveMessageIds: new Set(),+ memberOperationId: 'server-member-op',+ parentOperationId: 'owner-op',+ refreshGroup: vi.fn().mockResolvedValue(undefined),+ });+ handler(makeEvent('stream_start', { assistantMessage: { id: 'member-msg' } }));++ handler(makeEvent('member_runtime_end', { reason: 'completed' }));++ expect(store.completeOperation).toHaveBeenCalledWith('local-member-op');+ });});diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayMemberStreamHandler.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayMemberStreamHandler.tsindex cf2311e36c2..b76f4800bd5 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayMemberStreamHandler.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayMemberStreamHandler.ts@@ -230,6 +230,10 @@ export const createGatewayMemberStreamHandler = (break;}+ // `member_runtime_end` is how the server mirrors a member's terminal onto+ // the supervisor's channel; `agent_runtime_end` is the pre-rename shape+ // older servers still send.+ case 'member_runtime_end':case 'agent_runtime_end':case 'error': {ended = true;@@ -239,7 +243,7 @@ export const createGatewayMemberStreamHandler = (// 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.type !== 'error' &&(event.data as { reason?: string } | undefined)?.reason === 'waiting_for_human') {// Chained after the stream_start hydration: both reads replace the