🤯 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
✨ feat(agent): align approval workflows with web (#18645)
Tsuki1b6a2b740bfe
diff --git a/apps/cli/src/commands/hetero.ts b/apps/cli/src/commands/hetero.tsindex e5d75ede9db..9a92f15e87c 100644--- a/apps/cli/src/commands/hetero.ts+++ b/apps/cli/src/commands/hetero.ts@@ -490,11 +490,17 @@ const exec = async (options: ExecOptions): Promise<void> => {serverIngester) {if (agentType === 'cursor') {- askBridge = new AskUserBridge(operationId);+ askBridge = new AskUserBridge(operationId, {+ identifier: 'claude-code',+ provider: 'cursor',+ });} else {askServer = new LobeBuiltinMcpServer();await askServer.start();- askBridge = askServer.registerOperation(operationId);+ askBridge = askServer.registerOperation(+ operationId,+ new AskUserBridge(operationId, { identifier: agentType, provider: agentType }),+ );askMcpConfigPath = path.join(os.tmpdir(), `lobe-cc-mcp-${operationId}.json`);await writeFile(askMcpConfigPath,@@ -511,17 +517,14 @@ const exec = async (options: ExecOptions): Promise<void> => {);}- // (i) Forward bridge events into the same ordered ingest path as CC's. The- // request always goes out. For responses, only forward the ones the browser- // can't have published itself — producer-side timeout / session_ended — so- // the renderer's card un-sticks; browser-originated answers (success /- // user_cancelled) are already on the stream via `submitHeteroIntervention`.+ // (i) Forward every bridge event into the same ordered durable ingest path+ // as CC's. Browser submit already XADDed a response for producer delivery,+ // but that is only transport acceptance. The bridge echo after resolve is+ // the producer ACK (producerAck=true + resolutionRequestId) that transitions+ // Cloud from `resolving` to terminal. Persistence de-dupes transitions by+ // (operationId, toolCallId, transition).void (async () => {for await (const event of askBridge!.events()) {- if (event.type === 'agent_intervention_response') {- const reason = (event.data as { cancelReason?: string })?.cancelReason;- if (reason !== 'timeout' && reason !== 'session_ended') continue;- }serverIngester!.push(event as AgentStreamEvent);}})();@@ -530,7 +533,11 @@ const exec = async (options: ExecOptions): Promise<void> => {// actually pending, so an idle run holds no server invocation.void (async () => {const client = await getTrpcClient();- let lastEventId = '$';+ // Start at the beginning of this operation stream. A response can be+ // published after `pendingCount` flips but before the first XREAD; `$`+ // would skip that already-present response and strand the CLI until the+ // bridge timeout. Unknown/stale tool ids are harmless (`resolve` no-ops).+ let lastEventId = '0-0';while (!askPollAbort.signal.aborted) {if (askBridge!.pendingCount === 0) {await sleep(200);@@ -547,6 +554,7 @@ const exec = async (options: ExecOptions): Promise<void> => {cancelReason?: 'session_ended' | 'timeout' | 'user_cancelled';cancelled?: boolean;result?: unknown;+ resolutionRequestId?: string;toolCallId: string;};// Idempotent: resolve() no-ops on an unknown / already-settled id.@@ -554,11 +562,12 @@ const exec = async (options: ExecOptions): Promise<void> => {cancelReason: data.cancelReason,cancelled: data.cancelled,result: data.result,+ resolutionRequestId: data.resolutionRequestId,});}} catch {// Transient (server hiccup / token refresh) — back off and retry.- // The bridge's 5-min timeout still bounds the overall wait.+ // The bridge's 10-min timeout still bounds the overall wait.await sleep(1000);}}diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.tsindex 1da28e4ab94..1dbf4aebf01 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts@@ -996,7 +996,12 @@ export default class HeterogeneousAgentCtr {bridge: AskUserBridge;cleanup: () => Promise<void>;} {- const bridge = new AskUserBridge(operationId);+ // Cursor reuses the Claude Code AskUserQuestion renderer, but provider is+ // explicit so consumers never mistake renderer compatibility for origin.+ const bridge = new AskUserBridge(operationId, {+ identifier: 'claude-code',+ provider: 'cursor',+ });const pumpDone = (async () => {for await (const event of bridge.events()) {this.broadcast('heteroAgentEvent', { event, sessionId });@@ -1060,10 +1065,14 @@ export default class HeterogeneousAgentCtr {*/private async setupInterventionForOp(operationId: string,+ provider: 'claude-code' | 'qoder',browserBinding?: BrowserRunBinding,): Promise<{ bridge: AskUserBridge; cleanup: () => Promise<void>; tmpConfigPath: string }> {const server = await this.ensureBuiltinMcpServerStarted();- const bridge = server.registerOperation(operationId);+ const bridge = server.registerOperation(+ operationId,+ new AskUserBridge(operationId, { identifier: provider, provider }),+ );if (browserBinding?.agentId || browserBinding?.topicId) {this.opIdToBrowserBinding.set(operationId, browserBinding);}@@ -1421,7 +1430,7 @@ export default class HeterogeneousAgentCtr {// into `--mcp-config`. Other agents skip this entirely.const intervention =session.agentType === 'claude-code' || session.agentType === 'qoder'- ? await this.setupInterventionForOp(params.operationId, {+ ? await this.setupInterventionForOp(params.operationId, session.agentType, {agentId: params.agentId,topicId: params.topicId,}).catch((err) => {diff --git a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.tsindex 29056678c7b..5c2aa7b0947 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts@@ -227,6 +227,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {findToolMessageIdByToolCallId: vi.fn().mockResolvedValue(null),query: vi.fn().mockResolvedValue([]),update: vi.fn().mockResolvedValue({}),+ updateMessagePlugin: vi.fn().mockResolvedValue({ success: true }),updateToolMessage: vi.fn().mockResolvedValue({ success: true }),};@@ -3749,7 +3750,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {agentId: 'agent-123',content: '',parentId: 'assistant-msg-1',- pluginIntervention: { status: 'pending' },+ pluginIntervention: expect.objectContaining({ status: 'pending' }),role: 'tool',tool_call_id: 'tool-call-1',topicId: 'topic-123',@@ -3759,7 +3760,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {2,expect.objectContaining({parentId: 'assistant-msg-1',- pluginIntervention: { status: 'pending' },+ pluginIntervention: expect.objectContaining({ status: 'pending' }),tool_call_id: 'tool-call-2',}),);@@ -3817,6 +3818,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {await executors.request_human_approve!({+ parentMessageId: 'assistant-msg-1',pendingToolsCalling: makePendingTools(),skipCreateToolMessage: true,type: 'request_human_approve' as const,@@ -3825,6 +3827,16 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {);expect(mockMessageModel.create).not.toHaveBeenCalled();+ expect(mockMessageModel.updateMessagePlugin).toHaveBeenCalledTimes(2);+ expect(mockMessageModel.updateMessagePlugin).toHaveBeenNthCalledWith(1, 'existing-tool-1', {+ intervention: {+ batchId: 'op-123:0:assistant-msg-1',+ itemIndex: 0,+ operationId: 'op-123',+ status: 'pending',+ stepIndex: 0,+ },+ });const chunkCall = mockStreamManager.publishStreamChunk.mock.calls.find((call: any[]) => call[2]?.chunkType === 'tools_calling',);diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIntervention.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIntervention.test.tsindex 4c8be5b62e0..164737ad2ca 100644--- a/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIntervention.test.ts+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIntervention.test.ts@@ -1,11 +1,46 @@// @vitest-environment nodeimport { type LobeChatDatabase } from '@lobechat/database';+import { agents, messagePlugins, messages, topics } from '@lobechat/database/schemas';import { getTestDB } from '@lobechat/database/test-utils';+import { AskUserBridge } from '@lobechat/heterogeneous-agents/askUser';+import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import {+ deriveAgentInterventionContinuationOperationId,+ deriveAgentInterventionQueueDeduplicationId,+} from '@/business/server/agent-run/agentInterventionIdentity';+import { aiAgentRouter } from '../aiAgent';import { cleanupTestUser, createTestUser } from './integration/setup';+const business = vi.hoisted(() => ({+ getHeteroInterventionReview: vi.fn(),+ onHeteroInterventionResolutionPublished: vi.fn(),+ resolveHeteroIntervention: vi.fn(),+ rollbackHeteroInterventionResolution: vi.fn(),+}));+vi.mock('@/business/server/agent-run/heteroInterventionReview', () => business);++const businessV2 = vi.hoisted(() => ({+ getAgentInterventionReview: vi.fn(),+ getAgentInterventionReviewBySource: vi.fn(),+ onAgentInterventionResolutionPublished: vi.fn(),+ resolveAgentIntervention: vi.fn(),+ resolveAgentInterventionBySource: vi.fn(),+ rollbackAgentInterventionResolution: vi.fn(),+}));+vi.mock('@/business/server/agent-run/agentInterventionReview', () => businessV2);++const aiAgentService = vi.hoisted(() => ({+ ensureInterventionContinuationStarted: vi.fn(),+ execAgent: vi.fn(),+ loadInterventionContinuationState: vi.fn(),+ repairInterventionContinuationTopicAnchor: vi.fn(),+ retirePendingApprovalOperation: vi.fn(),+ stopPendingApproval: vi.fn(),+}));+// Mock getServerDB to return our test database instancelet testDB: LobeChatDatabase;vi.mock('@/database/core/db-adaptor', () => ({@@ -17,10 +52,13 @@ vi.mock('@/database/core/db-adaptor', () => ({// tiny store-backed stub of the factory is enough to exercise the round-trip// without a live Redis. An unknown `lastEventId` reads from the start (mirrors// Redis `XREAD 0`); `'$'` means from-now.-const { store } = vi.hoisted(() => ({ store: { events: [] as any[], seq: 0 } }));+const { store } = vi.hoisted(() => ({+ store: { events: [] as any[], failPublish: false, seq: 0 },+}));vi.mock('@/server/modules/AgentRuntime/factory', () => ({createStreamEventManager: () => ({async publishStreamEvent(operationId: string, event: any) {+ if (store.failPublish) throw new Error('stream publish failed');const id = String(++store.seq);store.events.push({ ...event, id, operationId });return id;@@ -41,7 +79,7 @@ vi.mock('@/server/services/agentRuntime', () => ({AgentRuntimeService: vi.fn().mockImplementation(() => ({})),}));vi.mock('@/server/services/aiAgent', () => ({- AiAgentService: vi.fn().mockImplementation(() => ({})),+ AiAgentService: vi.fn().mockImplementation(() => aiAgentService),}));vi.mock('@/server/services/aiChat', () => ({AiChatService: vi.fn().mockImplementation(() => ({})),@@ -59,7 +97,28 @@ describe('aiAgentRouter — remote Human-in-the-loop', () => {testDB = serverDB;userId = await createTestUser(serverDB);store.events.length = 0;+ store.failPublish = false;store.seq = 0;+ business.getHeteroInterventionReview.mockResolvedValue({ status: 'unavailable' });+ business.onHeteroInterventionResolutionPublished.mockResolvedValue(undefined);+ business.resolveHeteroIntervention.mockResolvedValue({ handled: false });+ business.rollbackHeteroInterventionResolution.mockResolvedValue(undefined);+ businessV2.getAgentInterventionReview.mockResolvedValue({+ authorization: { canResolve: false, canView: false },+ contractVersion: 2,+ status: 'unavailable',+ });+ businessV2.getAgentInterventionReviewBySource.mockResolvedValue({ handled: false });+ businessV2.onAgentInterventionResolutionPublished.mockResolvedValue(undefined);+ businessV2.resolveAgentIntervention.mockResolvedValue({ handled: false });+ businessV2.resolveAgentInterventionBySource.mockResolvedValue({ handled: false });+ businessV2.rollbackAgentInterventionResolution.mockResolvedValue(undefined);+ aiAgentService.execAgent.mockResolvedValue(undefined);+ aiAgentService.ensureInterventionContinuationStarted.mockResolvedValue('scheduled');+ aiAgentService.loadInterventionContinuationState.mockResolvedValue(null);+ aiAgentService.repairInterventionContinuationTopicAnchor.mockResolvedValue(undefined);+ aiAgentService.retirePendingApprovalOperation.mockResolvedValue(undefined);+ aiAgentService.stopPendingApproval.mockResolvedValue(undefined);});afterEach(async () => {@@ -108,14 +167,48 @@ describe('aiAgentRouter — remote Human-in-the-loop', () => {await serverDB.insert(agentOperations).values({ id, status: 'running', userId: ownerId });};+ const insertPendingTool = async (params: {+ batchId: string;+ messageId: string;+ operationId: string;+ ownerUserId?: string;+ toolCallId: string;+ }) => {+ const ownerUserId = params.ownerUserId ?? userId;+ await serverDB.insert(messages).values({+ content: '',+ id: params.messageId,+ role: 'tool',+ userId: ownerUserId,+ });+ await serverDB.insert(messagePlugins).values({+ apiName: 'editFile',+ arguments: '{"path":"/tmp/a"}',+ id: params.messageId,+ identifier: 'lobe-local-system',+ intervention: {+ batchId: params.batchId,+ operationId: params.operationId,+ status: 'pending',+ },+ toolCallId: params.toolCallId,+ type: 'default',+ userId: ownerUserId,+ });+ };+it('submit → wait round-trips a structured answer, filtered to the response', async () => {const operationId = 'op-roundtrip';await insertOperation(operationId, userId);- await userCaller().submitHeteroIntervention({- operationId,- result: { 'Which env?': 'prod' },- toolCallId: 't1',- });+ const resolutionRequestId = '018fbd8e-7baf-7c6d-8000-000000000001';+ await expect(+ userCaller().submitHeteroIntervention({+ operationId,+ resolutionRequestId,+ result: { 'Which env?': 'prod' },+ toolCallId: 't1',+ }),+ ).resolves.toEqual({ status: 'resolving', success: true });const res = await heteroCaller(operationId).waitInterventionResponse({lastEventId: '0',@@ -126,11 +219,1180 @@ describe('aiAgentRouter — remote Human-in-the-loop', () => {expect(res.events[0].type).toBe('agent_intervention_response');expect(res.events[0].data).toMatchObject({result: { 'Which env?': 'prod' },+ producerAck: false,+ resolutionRequestId,toolCallId: 't1',});expect(res.events[0].data.cancelled).toBeUndefined();});+ it('looks up cold-start review by a strict 32-byte base64url token', async () => {+ const reviewToken = 'a'.repeat(43);+ business.getHeteroInterventionReview.mockResolvedValueOnce({+ review: {+ apiName: 'askUserQuestion',+ deadline: 1_900_000_000_000,+ interactionKind: 'permission',+ provider: 'cursor',+ renderArguments: '{"questions":[]}',+ summary: 'Cursor permission',+ },+ status: 'pending',+ });++ await expect(userCaller().getHeteroInterventionReview({ reviewToken })).resolves.toMatchObject({+ review: { interactionKind: 'permission', provider: 'cursor' },+ status: 'pending',+ });+ expect(business.getHeteroInterventionReview).toHaveBeenCalledWith({+ reviewToken,+ userId,+ workspaceId: undefined,+ });+ await expect(+ userCaller().getHeteroInterventionReview({ reviewToken: 'too-short' }),+ ).rejects.toThrow();+ });++ it('forwards authenticated v2 Review lookup through the POST-body business slot', async () => {+ const reviewToken = 'b'.repeat(43);+ businessV2.getAgentInterventionReview.mockResolvedValueOnce({+ authorization: { canResolve: true, canView: true },+ contractVersion: 2,+ conversationUrl: '/chat/topic-1',+ review: {+ batch: {+ allowedActions: [],+ id: 'batch-1',+ itemIds: ['item-1'],+ kind: 'single',+ version: 1,+ },+ context: { operationId: 'op-v2', topicId: 'topic-1' },+ id: 'review-1',+ items: [],+ summary: 'Review request',+ systemActionEligibility: 'review_only',+ },+ status: 'pending',+ });++ await expect(userCaller().getAgentInterventionReview({ reviewToken })).resolves.toMatchObject({+ authorization: { canResolve: true, canView: true },+ contractVersion: 2,+ status: 'pending',+ });+ expect(businessV2.getAgentInterventionReview).toHaveBeenCalledWith({+ reviewToken,+ userId,+ workspaceId: undefined,+ });+ });++ it('returns a read-only authoritative source Review before chat controls are rendered', async () => {+ businessV2.getAgentInterventionReviewBySource.mockResolvedValueOnce({+ authorization: { canResolve: false, canView: true, denialReason: 'view_only' },+ contractVersion: 2,+ handled: true,+ review: {+ batch: {+ allowedActions: [],+ id: 'batch-source-read',+ itemIds: ['item-source-read'],+ kind: 'single',+ version: 1,+ },+ context: { operationId: 'operation-source-read', topicId: 'topic-source-read' },+ id: 'review-source-read',+ items: [],+ summary: 'Review request',+ systemActionEligibility: 'review_only',+ },+ sourceItemMap: { 'message-source-read': 'item-source-read' },+ status: 'pending',+ });++ await expect(+ userCaller().getAgentInterventionReviewBySource({+ batchId: 'batch-source-read',+ operationId: 'operation-source-read',+ targets: [{ toolCallId: 'call-source-read', toolMessageId: 'message-source-read' }],+ }),+ ).resolves.toMatchObject({+ authorization: { canResolve: false, canView: true, denialReason: 'view_only' },+ contractVersion: 2,+ handled: true,+ sourceItemMap: { 'message-source-read': 'item-source-read' },+ status: 'pending',+ });+ expect(businessV2.getAgentInterventionReviewBySource).toHaveBeenCalledWith({+ actorUserId: userId,+ batchId: 'batch-source-read',+ operationId: 'operation-source-read',+ targets: [{ toolCallId: 'call-source-read', toolMessageId: 'message-source-read' }],+ workspaceId: undefined,+ });+ });++ it('publishes a claimed heterogeneous v2 response and leaves it resolving until producer ACK', async () => {+ const reviewToken = 'c'.repeat(43);+ const resolutionRequestId = '018fbd8e-7baf-7c6d-8000-000000000011';+ businessV2.resolveAgentIntervention.mockResolvedValueOnce({+ claimId: 'claim-v2',+ contractVersion: 2,+ handled: true,+ ownerUserId: 'owner-v2',+ resolutionRequestId,+ runtimeAction: {+ operationId: 'op-v2',+ response: {+ producerAck: false,+ resolutionRequestId,+ result: { 'Which env?': 'prod' },+ toolCallId: 'tool-v2',+ },+ stepIndex: 4,+ type: 'heterogeneous_response',+ },+ state: 'claimed',+ workspaceId: 'workspace-v2',+ });++ await expect(+ userCaller().resolveAgentIntervention({+ action: {+ itemId: 'item-v2',+ result: { question_1: 'prod' },+ type: 'submit_answers',+ },+ expectedBatchVersion: 1,+ expectedRequestRevisions: {+ 'item-v2': { hash: 'a'.repeat(64), version: 1 },+ },+ resolutionRequestId,+ reviewToken,+ }),+ ).resolves.toEqual({ contractVersion: 2, status: 'resolving', success: true });++ expect(store.events.at(-1)).toMatchObject({+ data: {+ producerAck: false,+ resolutionRequestId,+ toolCallId: 'tool-v2',+ },+ operationId: 'op-v2',+ stepIndex: 4,+ type: 'agent_intervention_response',+ });+ expect(businessV2.onAgentInterventionResolutionPublished).toHaveBeenCalledWith({+ actorUserId: userId,+ claimId: 'claim-v2',+ ownerUserId: 'owner-v2',+ resolutionRequestId,+ status: 'resolving',+ workspaceId: 'workspace-v2',+ });+ expect(businessV2.rollbackAgentInterventionResolution).not.toHaveBeenCalled();+ });++ it('routes an active Web approval through the same generic first-winner claim', async () => {+ const resolutionRequestId = '018fbd8e-7baf-7c6d-8000-000000000021';+ const execution = {+ autoStarted: true,+ messageId: 'assistant-web',+ operationId: 'operation-web-resumed',+ success: true,+ };+ await insertPendingTool({+ batchId: 'batch-web',+ messageId: 'message-web',+ operationId: 'operation-web',+ toolCallId: 'call-web',+ });+ businessV2.resolveAgentInterventionBySource.mockResolvedValueOnce({+ claimId: 'claim-web',+ contractVersion: 2,+ handled: true,+ ownerUserId: userId,+ resolutionRequestId,+ runtimeAction: {+ agentId: 'agent-web',+ appContext: { topicId: 'topic-web' },+ decisions: [+ {+ decision: 'approved',+ parentMessageId: 'message-web',+ toolCallId: 'call-web',+ },+ ],+ operationId: 'operation-web',+ parentMessageId: 'message-web',+ type: 'resume_approval',+ },+ state: 'claimed',+ });+ aiAgentService.execAgent.mockResolvedValueOnce(execution);++ await expect(+ userCaller().resolveAgentInterventionBySource({+ action: { scope: 'once', type: 'approve_tool' },+ batchId: 'batch-web',+ operationId: 'operation-web',+ resolutionRequestId,+ targets: [{ toolCallId: 'call-web', toolMessageId: 'message-web' }],+ }),+ ).resolves.toEqual({+ contractVersion: 2,+ execution,+ state: 'claimed',+ status: 'approved',+ success: true,+ });++ expect(businessV2.resolveAgentInterventionBySource).toHaveBeenCalledWith({+ action: { scope: 'once', type: 'approve_tool' },+ actorUserId: userId,+ batchId: 'batch-web',+ operationId: 'operation-web',+ resolutionRequestId,+ targets: [{ toolCallId: 'call-web', toolMessageId: 'message-web' }],+ workspaceId: undefined,+ });+ expect(aiAgentService.execAgent).toHaveBeenCalledTimes(1);+ expect(businessV2.onAgentInterventionResolutionPublished).toHaveBeenCalledWith(+ expect.objectContaining({ claimId: 'claim-web', status: 'approved' }),+ );+ });++ it('does not dispatch again when another surface already won the source claim', async () => {+ businessV2.resolveAgentInterventionBySource.mockResolvedValueOnce({+ contractVersion: 2,+ handled: true,+ ownerUserId: userId,+ state: 'already_resolved',+ status: 'approved',+ });++ await expect(+ userCaller().resolveAgentInterventionBySource({+ action: { scope: 'once', type: 'approve_tool' },+ batchId: 'batch-race',+ operationId: 'operation-race',+ resolutionRequestId: '018fbd8e-7baf-7c6d-8000-000000000022',+ targets: [{ toolCallId: 'call-race', toolMessageId: 'message-race' }],+ }),+ ).resolves.toEqual({+ contractVersion: 2,+ state: 'already_resolved',+ status: 'approved',+ success: true,+ });++ expect(aiAgentService.execAgent).not.toHaveBeenCalled();+ expect(businessV2.onAgentInterventionResolutionPublished).not.toHaveBeenCalled();+ });++ it('does not synthesize a claim state when the durable source is unavailable', async () => {+ await insertPendingTool({+ batchId: 'batch-unavailable',+ messageId: 'message-unavailable',+ operationId: 'operation-unavailable',+ toolCallId: 'call-unavailable',+ });+ businessV2.resolveAgentInterventionBySource.mockResolvedValueOnce({ handled: false });++ await expect(+ userCaller().resolveAgentInterventionBySource({+ action: { scope: 'once', type: 'approve_tool' },+ batchId: 'batch-unavailable',+ operationId: 'operation-unavailable',+ resolutionRequestId: '018fbd8e-7baf-7c6d-8000-000000000027',+ targets: [{ toolCallId: 'call-unavailable', toolMessageId: 'message-unavailable' }],+ }),+ ).resolves.toEqual({+ contractVersion: 2,+ status: 'unavailable',+ success: false,+ });++ expect(aiAgentService.execAgent).not.toHaveBeenCalled();+ });++ it('prevents an old direct execAgent approval from bypassing a generic race winner', async () => {+ await insertPendingTool({+ batchId: 'batch-legacy-race',+ messageId: 'message-legacy-race',+ operationId: 'operation-legacy-race',+ toolCallId: 'call-legacy-race',+ });+ businessV2.resolveAgentInterventionBySource.mockResolvedValueOnce({+ contractVersion: 2,+ handled: true,+ ownerUserId: userId,+ state: 'already_resolved',+ status: 'approved',+ });++ await expect(+ userCaller().execAgent({+ agentId: 'agent-legacy-race',+ parentMessageId: 'message-legacy-race',+ prompt: '',+ resumeApproval: {+ decision: 'approved',+ parentMessageId: 'message-legacy-race',+ toolCallId: 'call-legacy-race',+ },+ }),+ ).rejects.toThrow(/already been resolved/i);++ expect(businessV2.resolveAgentInterventionBySource).toHaveBeenCalledWith(+ expect.objectContaining({+ action: { scope: 'once', type: 'approve_tool' },+ actorUserId: userId,+ batchId: 'batch-legacy-race',+ operationId: 'operation-legacy-race',+ targets: [{ toolCallId: 'call-legacy-race', toolMessageId: 'message-legacy-race' }],+ }),+ );+ expect(aiAgentService.execAgent).not.toHaveBeenCalled();+ });++ it('fails an old pre-mutated edit closed on the durable revision conflict', async () => {+ await insertPendingTool({+ batchId: 'batch-legacy-edit',+ messageId: 'message-legacy-edit',+ operationId: 'operation-legacy-edit',+ toolCallId: 'call-legacy-edit',+ });+ businessV2.resolveAgentInterventionBySource.mockRejectedValueOnce(+ new Error('Approval request changed. Refresh before approving edited arguments.'),+ );++ await expect(+ userCaller().execAgent({+ agentId: 'agent-legacy-edit',+ parentMessageId: 'message-legacy-edit',+ prompt: '',+ resumeApproval: {+ decision: 'approved',+ parentMessageId: 'message-legacy-edit',+ toolCallId: 'call-legacy-edit',+ },+ }),+ ).rejects.toThrow(/refresh before approving edited arguments/i);++ expect(aiAgentService.execAgent).not.toHaveBeenCalled();+ });++ it('dispatches an old direct execAgent approval exactly once through the generic claim', async () => {+ await insertPendingTool({+ batchId: 'batch-legacy-claim',+ messageId: 'message-legacy-claim',+ operationId: 'operation-legacy-claim',+ toolCallId: 'call-legacy-claim',+ });+ const execution = {+ autoStarted: true,+ messageId: 'assistant-resumed',+ operationId: 'operation-resumed',+ success: true,+ };+ aiAgentService.execAgent.mockResolvedValueOnce(execution);+ businessV2.resolveAgentInterventionBySource.mockResolvedValueOnce({+ claimId: 'claim-legacy',+ contractVersion: 2,+ handled: true,+ ownerUserId: userId,+ resolutionRequestId: '018fbd8e-7baf-7c6d-8000-000000000026',+ runtimeAction: {+ agentId: 'agent-legacy-claim',+ appContext: { topicId: '' },+ decisions: [+ {+ decision: 'approved',+ parentMessageId: 'message-legacy-claim',+ toolCallId: 'call-legacy-claim',+ },+ ],+ operationId: 'operation-legacy-claim',+ parentMessageId: 'message-legacy-claim',+ type: 'resume_approval',+ },+ state: 'claimed',+ });++ await expect(+ userCaller().execAgent({+ agentId: 'agent-legacy-claim',+ parentMessageId: 'message-legacy-claim',+ prompt: '',+ resumeApproval: {+ decision: 'approved',+ parentMessageId: 'message-legacy-claim',+ toolCallId: 'call-legacy-claim',+ },+ }),+ ).resolves.toEqual(execution);++ expect(aiAgentService.execAgent).toHaveBeenCalledTimes(1);+ expect(aiAgentService.execAgent).toHaveBeenCalledWith(+ expect.objectContaining({+ resumeApproval: expect.objectContaining({+ parentMessageId: 'message-legacy-claim',+ toolCallId: 'call-legacy-claim',+ }),+ }),+ );+ expect(businessV2.onAgentInterventionResolutionPublished).toHaveBeenCalledWith(+ expect.objectContaining({ claimId: 'claim-legacy', status: 'approved' }),+ );+ });++ it('prevents an old direct Stop from bypassing a generic race winner', async () => {+ await insertPendingTool({+ batchId: 'batch-legacy-stop',+ messageId: 'message-legacy-stop',+ operationId: 'operation-legacy-stop',+ toolCallId: 'call-legacy-stop',+ });+ businessV2.resolveAgentInterventionBySource.mockResolvedValueOnce({+ contractVersion: 2,+ handled: true,+ ownerUserId: userId,+ state: 'already_resolved',+ status: 'stopped',+ });++ await expect(+ userCaller().stopPendingApproval({+ batchId: 'batch-legacy-stop',+ operationId: 'operation-legacy-stop',+ toolMessageIds: ['message-legacy-stop'],+ topicId: '',+ }),+ ).rejects.toThrow(/already been resolved/i);++ expect(aiAgentService.stopPendingApproval).not.toHaveBeenCalled();+ });++ it('dispatches only the authoritative remaining pending rows for a mixed partial Stop', async () => {+ const resolutionRequestId = '018fbd8e-7baf-7c6d-8000-000000000023';+ await insertPendingTool({+ batchId: 'batch-stop',+ messageId: 'message-pending',+ operationId: 'operation-stop',+ toolCallId: 'call-pending',+ });+ businessV2.resolveAgentInterventionBySource.mockResolvedValueOnce({+ claimId: 'claim-stop',+ contractVersion: 2,+ handled: true,+ ownerUserId: userId,+ resolutionRequestId,+ runtimeAction: {+ batchId: 'batch-stop',+ operationId: 'operation-stop',+ terminalStatus: 'stopped',+ // Cloud derived this pending subset from the full sealed snapshot; a+ // terminal sibling is intentionally absent and remains immutable.+ toolMessageIds: ['message-pending'],+ topicId: 'topic-stop',+ type: 'stop',+ },+ state: 'claimed',+ });++ await userCaller().resolveAgentInterventionBySource({+ action: { scope: 'operation', type: 'stop' },+ batchId: 'batch-stop',+ operationId: 'operation-stop',+ resolutionRequestId,+ targets: [{ toolCallId: 'call-pending', toolMessageId: 'message-pending' }],+ });++ expect(aiAgentService.stopPendingApproval).toHaveBeenCalledWith({+ approvalResolutionRequestId: resolutionRequestId,+ batchId: 'batch-stop',+ operationId: 'operation-stop',+ toolMessageIds: ['message-pending'],+ topicId: 'topic-stop',+ });+ });++ it('restores the authoritative page/task message-map context for a runtime resume', async () => {+ const reviewToken = 'd'.repeat(43);+ const resolutionRequestId = '018fbd8e-7baf-7c6d-8000-000000000012';+ await insertPendingTool({+ batchId: 'batch-runtime',+ messageId: 'assistant-runtime',+ operationId: 'operation-runtime',+ ownerUserId: userId,+ toolCallId: 'tool-runtime',+ });+ businessV2.resolveAgentIntervention.mockResolvedValueOnce({+ claimId: 'claim-runtime',+ contractVersion: 2,+ handled: true,+ ownerUserId: userId,+ resolutionRequestId,+ runtimeAction: {+ agentId: 'agent-runtime',+ appContext: {+ documentId: 'document-runtime',+ groupId: 'group-runtime',+ scope: 'task',+ taskId: 'task-runtime',+ threadId: 'thread-runtime',+ topicId: 'topic-runtime',+ },+ decisions: [+ {+ decision: 'approved',+ parentMessageId: 'assistant-runtime',+ toolCallId: 'tool-runtime',+ },+ ],+ operationId: 'operation-runtime',+ parentMessageId: 'assistant-runtime',+ type: 'resume_approval',+ },+ state: 'claimed',+ });++ await expect(+ userCaller().resolveAgentIntervention({+ action: {+ itemIds: ['item-runtime'],+ scope: 'once',+ type: 'approve_tool',+ },+ expectedBatchVersion: 1,+ expectedRequestRevisions: {+ 'item-runtime': { hash: 'b'.repeat(64), version: 1 },+ },+ resolutionRequestId,+ reviewToken,+ }),+ ).resolves.toEqual({ contractVersion: 2, status: 'approved', success: true });++ expect(aiAgentService.execAgent).toHaveBeenCalledWith(+ expect.objectContaining({+ appContext: expect.objectContaining({+ documentId: 'document-runtime',+ scope: 'task',+ taskId: 'task-runtime',+ }),+ taskId: 'task-runtime',+ }),+ );+ expect(aiAgentService.repairInterventionContinuationTopicAnchor).toHaveBeenCalledWith(+ expect.objectContaining({+ sourceOperationId: 'operation-runtime',+ threadId: 'thread-runtime',+ topicId: 'topic-runtime',+ }),+ );+ });++ it('surfaces a durable published-hook failure after dispatch instead of reporting success', async () => {+ const reviewToken = 'e'.repeat(43);+ const resolutionRequestId = '018fbd8e-7baf-7c6d-8000-000000000013';+ await insertPendingTool({+ batchId: 'batch-hook-fail',+ messageId: 'assistant-runtime',+ operationId: 'operation-hook-fail',+ ownerUserId: userId,+ toolCallId: 'tool-runtime',+ });+ businessV2.resolveAgentIntervention.mockResolvedValueOnce({+ claimId: 'claim-hook-fail',+ contractVersion: 2,+ handled: true,+ ownerUserId: userId,+ resolutionRequestId,+ runtimeAction: {+ agentId: 'agent-runtime',+ appContext: { topicId: 'topic-runtime' },+ content: 'skipped',+ operationId: 'operation-hook-fail',+ outcome: 'skipped',+ parentMessageId: 'assistant-runtime',+ toolCallId: 'tool-runtime',+ type: 'resume_tool_result',+ },+ state: 'claimed',+ });+ businessV2.onAgentInterventionResolutionPublished.mockRejectedValueOnce(+ new Error('durable completion failed'),+ );++ await expect(+ userCaller().resolveAgentIntervention({+ action: { itemId: 'item-runtime', type: 'skip_interaction' },+ expectedBatchVersion: 1,+ expectedRequestRevisions: {+ 'item-runtime': { hash: 'c'.repeat(64), version: 1 },+ },+ resolutionRequestId,+ reviewToken,+ }),+ ).rejects.toThrow('durable completion failed');++ expect(aiAgentService.execAgent).toHaveBeenCalledTimes(1);+ // Runtime dispatch already happened; releasing the claim here could let a+ // second actor execute it again. The idempotent published hook is retried+ // under the same resolutionRequestId instead.+ expect(businessV2.rollbackAgentInterventionResolution).not.toHaveBeenCalled();+ });++ it('retries only the published transition after runtime dispatch already settled the source', async () => {+ const reviewToken = 'f'.repeat(43);+ const messageId = 'message-published-retry';+ const operationId = 'operation-published-retry';+ const resolutionRequestId = '018fbd8e-7baf-7c6d-8000-000000000014';+ await insertPendingTool({+ batchId: 'batch-published-retry',+ messageId,+ operationId,+ toolCallId: 'call-published-retry',+ });+ const claimed = {+ claimId: 'claim-published-retry',+ contractVersion: 2 as const,+ handled: true as const,+ ownerUserId: userId,+ resolutionRequestId,+ runtimeAction: {+ agentId: 'agent-runtime',+ appContext: { topicId: 'topic-runtime' },+ content: 'answer',+ operationId,+ outcome: 'submitted' as const,+ parentMessageId: messageId,+ toolCallId: 'call-published-retry',+ type: 'resume_tool_result' as const,+ },+ state: 'claimed' as const,+ };+ businessV2.resolveAgentIntervention.mockResolvedValue(claimed);+ aiAgentService.execAgent.mockImplementationOnce(async (params) => {+ expect(params).toMatchObject({ approvalResolutionRequestId: resolutionRequestId });+ await serverDB+ .update(messagePlugins)+ .set({+ intervention: {+ batchId: 'batch-published-retry',+ operationId,+ resolutionRequestId,+ status: 'approved',+ },+ })+ .where(eq(messagePlugins.id, messageId));+ return { operationId: 'continued-operation' };+ });+ const continuationOperationId = deriveAgentInterventionContinuationOperationId({+ resolutionRequestId,+ userId,+ });+ const { agentOperations } = await import('@/database/schemas');+ await serverDB.insert(agents).values({ id: 'agent-runtime', userId });+ await serverDB.insert(topics).values({ id: 'topic-runtime', userId });+ await serverDB.insert(agentOperations).values({+ agentId: 'agent-runtime',+ appContext: { sourceMessageId: messageId },+ id: continuationOperationId,+ metadata: {+ agentInterventionContinuation: {+ resolutionRequestId,+ sourceOperationId: operationId,+ sourceToolMessageIds: [messageId],+ },+ agentInterventionDispatch: {+ deduplicationId: deriveAgentInterventionQueueDeduplicationId(continuationOperationId, 0),+ messageId: 'qstash-message-published-retry',+ resolutionRequestId,+ scheduledAt: new Date().toISOString(),+ state: 'scheduled',+ },+ },+ status: 'running',+ topicId: 'topic-runtime',+ userId,+ });+ businessV2.onAgentInterventionResolutionPublished.mockRejectedValueOnce(+ new Error('published transition unavailable'),+ );+ const input = {+ action: {+ itemId: 'item-runtime',+ result: { question_1: 'answer' },+ type: 'submit_answers' as const,+ },+ expectedBatchVersion: 1,+ expectedRequestRevisions: {+ 'item-runtime': { hash: 'd'.repeat(64), version: 1 },+ },+ resolutionRequestId,+ reviewToken,+ };++ await expect(userCaller().resolveAgentIntervention(input)).rejects.toThrow(+ 'published transition unavailable',+ );+ await expect(userCaller().resolveAgentIntervention(input)).resolves.toMatchObject({+ contractVersion: 2,+ status: 'resolved',+ success: true,+ });++ expect(aiAgentService.execAgent).toHaveBeenCalledTimes(1);+ expect(aiAgentService.retirePendingApprovalOperation).toHaveBeenCalledTimes(2);+ expect(aiAgentService.retirePendingApprovalOperation).toHaveBeenCalledWith(operationId);+ expect(businessV2.onAgentInterventionResolutionPublished).toHaveBeenCalledTimes(2);+ expect(businessV2.rollbackAgentInterventionResolution).not.toHaveBeenCalled();+ });++ it('backfills a lost queue ACK from ready state without rebuilding the continuation', async () => {+ const reviewToken = 'g'.repeat(43);+ const messageId = 'message-ack-backfill';+ const operationId = 'operation-ack-backfill';+ const resolutionRequestId = '018fbd8e-7baf-7c6d-8000-000000000015';+ await insertPendingTool({+ batchId: 'batch-ack-backfill',+ messageId,+ operationId,+ toolCallId: 'call-ack-backfill',+ });+ await serverDB+ .update(messagePlugins)+ .set({+ intervention: {+ batchId: 'batch-ack-backfill',+ operationId,+ resolutionRequestId,+ status: 'approved',+ },+ })+ .where(eq(messagePlugins.id, messageId));+ const claimed = {+ claimId: 'claim-ack-backfill',+ contractVersion: 2 as const,+ handled: true as const,+ ownerUserId: userId,+ resolutionRequestId,+ runtimeAction: {+ agentId: 'agent-ack-backfill',+ appContext: { topicId: 'topic-ack-backfill' },+ content: 'answer',+ operationId,+ outcome: 'submitted' as const,+ parentMessageId: messageId,+ toolCallId: 'call-ack-backfill',+ type: 'resume_tool_result' as const,+ },+ state: 'claimed' as const,+ };+ businessV2.resolveAgentIntervention.mockResolvedValueOnce(claimed);+ const continuationOperationId = deriveAgentInterventionContinuationOperationId({+ resolutionRequestId,+ userId,+ });+ const deduplicationId = deriveAgentInterventionQueueDeduplicationId(continuationOperationId, 0);+ const { agentOperations } = await import('@/database/schemas');+ await serverDB.insert(agents).values({ id: 'agent-ack-backfill', userId });+ await serverDB.insert(topics).values({ id: 'topic-ack-backfill', userId });+ await serverDB.insert(agentOperations).values({+ agentId: 'agent-ack-backfill',+ appContext: { sourceMessageId: messageId },+ id: continuationOperationId,+ metadata: {+ agentInterventionContinuation: {+ resolutionRequestId,+ sourceOperationId: operationId,+ sourceToolMessageIds: [messageId],+ },+ agentInterventionPreparation: {+ deduplicationId,+ resolutionRequestId,+ state: 'ready',+ stepIndex: 0,+ },+ },+ status: 'running',+ topicId: 'topic-ack-backfill',+ userId,+ });+ aiAgentService.loadInterventionContinuationState.mockResolvedValue({+ metadata: {+ agentId: 'agent-ack-backfill',+ agentInterventionContinuation: {+ resolutionRequestId,+ sourceOperationId: operationId,+ sourceToolMessageIds: [messageId],+ },+ agentInterventionPreparation: {+ deduplicationId,+ resolutionRequestId,+ state: 'ready',+ stepIndex: 0,+ },+ sourceMessageId: messageId,+ topicId: 'topic-ack-backfill',+ userId,+ },+ operationId: continuationOperationId,+ status: 'running',+ });+ aiAgentService.ensureInterventionContinuationStarted.mockResolvedValueOnce('scheduled');++ await expect(+ userCaller().resolveAgentIntervention({+ action: {+ itemId: 'item-ack-backfill',+ result: { question_1: 'answer' },+ type: 'submit_answers',+ },+ expectedBatchVersion: 1,+ expectedRequestRevisions: {+ 'item-ack-backfill': { hash: 'e'.repeat(64), version: 1 },+ },+ resolutionRequestId,+ reviewToken,+ }),+ ).resolves.toMatchObject({ success: true });++ expect(aiAgentService.ensureInterventionContinuationStarted).toHaveBeenCalledWith(+ continuationOperationId,+ );+ expect(aiAgentService.execAgent).not.toHaveBeenCalled();+ expect(aiAgentService.repairInterventionContinuationTopicAnchor).toHaveBeenCalledTimes(1);+ expect(aiAgentService.retirePendingApprovalOperation).toHaveBeenCalledWith(operationId);+ expect(businessV2.onAgentInterventionResolutionPublished).toHaveBeenCalledTimes(1);+ });++ it('fails closed when ready state disappears between probe and ACK repair', async () => {+ const reviewToken = 'h'.repeat(43);+ const messageId = 'message-ready-disappears';+ const operationId = 'operation-ready-disappears';+ const resolutionRequestId = '018fbd8e-7baf-7c6d-8000-000000000016';+ await insertPendingTool({+ batchId: 'batch-ready-disappears',+ messageId,+ operationId,+ toolCallId: 'call-ready-disappears',+ });+ await serverDB+ .update(messagePlugins)+ .set({+ intervention: {+ batchId: 'batch-ready-disappears',+ operationId,+ resolutionRequestId,+ status: 'approved',+ },+ })+ .where(eq(messagePlugins.id, messageId));+ businessV2.resolveAgentIntervention.mockResolvedValueOnce({+ claimId: 'claim-ready-disappears',+ contractVersion: 2,+ handled: true,+ ownerUserId: userId,+ resolutionRequestId,+ runtimeAction: {+ agentId: 'agent-ready-disappears',+ appContext: { topicId: 'topic-ready-disappears' },+ content: 'answer',+ operationId,+ outcome: 'submitted',+ parentMessageId: messageId,+ toolCallId: 'call-ready-disappears',+ type: 'resume_tool_result',+ },+ state: 'claimed',+ });+ const continuationOperationId = deriveAgentInterventionContinuationOperationId({+ resolutionRequestId,+ userId,+ });+ const deduplicationId = deriveAgentInterventionQueueDeduplicationId(continuationOperationId, 0);+ const { agentOperations } = await import('@/database/schemas');+ await serverDB.insert(agents).values({ id: 'agent-ready-disappears', userId });+ await serverDB.insert(topics).values({ id: 'topic-ready-disappears', userId });+ await serverDB.insert(agentOperations).values({+ agentId: 'agent-ready-disappears',+ appContext: { sourceMessageId: messageId },+ id: continuationOperationId,+ metadata: {+ agentInterventionContinuation: {+ resolutionRequestId,+ sourceOperationId: operationId,+ sourceToolMessageIds: [messageId],+ },+ agentInterventionPreparation: {+ deduplicationId,+ resolutionRequestId,+ state: 'ready',+ stepIndex: 0,+ },+ },+ status: 'running',+ topicId: 'topic-ready-disappears',+ userId,+ });+ aiAgentService.loadInterventionContinuationState+ .mockResolvedValueOnce({+ metadata: {+ agentId: 'agent-ready-disappears',+ agentInterventionContinuation: {+ resolutionRequestId,+ sourceOperationId: operationId,+ sourceToolMessageIds: [messageId],+ },+ agentInterventionPreparation: {+ deduplicationId,+ resolutionRequestId,+ state: 'ready',+ stepIndex: 0,+ },+ sourceMessageId: messageId,+ topicId: 'topic-ready-disappears',+ userId,+ },+ operationId: continuationOperationId,+ status: 'idle',+ })+ .mockResolvedValue(null);+ aiAgentService.ensureInterventionContinuationStarted.mockResolvedValueOnce('missing');++ await expect(+ userCaller().resolveAgentIntervention({+ action: {+ itemId: 'item-ready-disappears',+ result: { question_1: 'answer' },+ type: 'submit_answers',+ },+ expectedBatchVersion: 1,+ expectedRequestRevisions: {+ 'item-ready-disappears': { hash: 'f'.repeat(64), version: 1 },+ },+ resolutionRequestId,+ reviewToken,+ }),+ ).rejects.toThrow(/state disappeared during dispatch recovery/);++ expect(aiAgentService.ensureInterventionContinuationStarted).toHaveBeenCalledTimes(1);+ expect(aiAgentService.execAgent).not.toHaveBeenCalled();+ expect(aiAgentService.repairInterventionContinuationTopicAnchor).not.toHaveBeenCalled();+ expect(aiAgentService.retirePendingApprovalOperation).not.toHaveBeenCalled();+ expect(businessV2.onAgentInterventionResolutionPublished).not.toHaveBeenCalled();+ expect(businessV2.rollbackAgentInterventionResolution).not.toHaveBeenCalled();+ });++ it('does not rebuild a durable ready continuation after its runtime state is gone', async () => {+ const reviewToken = 'i'.repeat(43);+ const messageId = 'message-durable-ready-missing';+ const operationId = 'operation-durable-ready-missing';+ const resolutionRequestId = '018fbd8e-7baf-7c6d-8000-000000000017';+ await insertPendingTool({+ batchId: 'batch-durable-ready-missing',+ messageId,+ operationId,+ toolCallId: 'call-durable-ready-missing',+ });+ await serverDB+ .update(messagePlugins)+ .set({+ intervention: {+ batchId: 'batch-durable-ready-missing',+ operationId,+ resolutionRequestId,+ status: 'approved',+ },+ })+ .where(eq(messagePlugins.id, messageId));+ businessV2.resolveAgentIntervention.mockResolvedValueOnce({+ claimId: 'claim-durable-ready-missing',+ contractVersion: 2,+ handled: true,+ ownerUserId: userId,+ resolutionRequestId,+ runtimeAction: {+ agentId: 'agent-durable-ready-missing',+ appContext: { topicId: 'topic-durable-ready-missing' },+ content: 'answer',+ operationId,+ outcome: 'submitted',+ parentMessageId: messageId,+ toolCallId: 'call-durable-ready-missing',+ type: 'resume_tool_result',+ },+ state: 'claimed',+ });+ const continuationOperationId = deriveAgentInterventionContinuationOperationId({+ resolutionRequestId,+ userId,+ });+ const { agentOperations } = await import('@/database/schemas');+ await serverDB.insert(agents).values({ id: 'agent-durable-ready-missing', userId });+ await serverDB.insert(topics).values({ id: 'topic-durable-ready-missing', userId });+ await serverDB.insert(agentOperations).values({+ agentId: 'agent-durable-ready-missing',+ appContext: {+ sourceMessageId: messageId,+ },+ id: continuationOperationId,+ metadata: {+ agentInterventionContinuation: {+ resolutionRequestId,+ sourceOperationId: operationId,+ sourceToolMessageIds: [messageId],+ },+ agentInterventionPreparation: {+ deduplicationId: deriveAgentInterventionQueueDeduplicationId(continuationOperationId, 0),+ resolutionRequestId,+ state: 'ready',+ stepIndex: 0,+ },+ },+ status: 'running',+ topicId: 'topic-durable-ready-missing',+ userId,+ });+ aiAgentService.loadInterventionContinuationState.mockResolvedValue(null);++ await expect(+ userCaller().resolveAgentIntervention({+ action: {+ itemId: 'item-durable-ready-missing',+ result: { question_1: 'answer' },+ type: 'submit_answers',+ },+ expectedBatchVersion: 1,+ expectedRequestRevisions: {+ 'item-durable-ready-missing': { hash: 'a'.repeat(64), version: 1 },+ },+ resolutionRequestId,+ reviewToken,+ }),+ ).rejects.toThrow(/provenance conflict/);++ expect(aiAgentService.ensureInterventionContinuationStarted).not.toHaveBeenCalled();+ expect(aiAgentService.execAgent).not.toHaveBeenCalled();+ expect(businessV2.onAgentInterventionResolutionPublished).not.toHaveBeenCalled();+ expect(businessV2.rollbackAgentInterventionResolution).not.toHaveBeenCalled();+ });++ it('calls the resolving hook only after a claimed response is published', async () => {+ const operationId = 'op-claimed';+ const resolutionRequestId = '018fbd8e-7baf-7c6d-8000-000000000003';+ await insertOperation(operationId, userId);+ business.resolveHeteroIntervention.mockResolvedValueOnce({+ claimId: 'claim-1',+ handled: true,+ operationId,+ resolutionRequestId,+ response: { result: { approved: true }, toolCallId: 't-claimed' },+ state: 'claimed',+ workspaceId: 'workspace-claimed',+ });++ await expect(+ userCaller().submitHeteroIntervention({+ operationId,+ resolutionRequestId,+ result: { approved: true },+ toolCallId: 't-claimed',+ }),+ ).resolves.toEqual({ status: 'resolving', success: true });++ expect(store.events[0].data).toMatchObject({+ producerAck: false,+ resolutionRequestId,+ toolCallId: 't-claimed',+ });+ expect(business.onHeteroInterventionResolutionPublished).toHaveBeenCalledWith({+ claimId: 'claim-1',+ operationId,+ resolutionRequestId,+ status: 'resolving',+ toolCallId: 't-claimed',+ userId,+ workspaceId: 'workspace-claimed',+ });+ expect(business.rollbackHeteroInterventionResolution).not.toHaveBeenCalled();+ });++ it('round-trips XADD → long-poll → bridge producer ACK with the same request id', async () => {+ const operationId = 'op-bridge-ack';+ const resolutionRequestId = '018fbd8e-7baf-7c6d-8000-000000000005';+ await insertOperation(operationId, userId);+ const bridge = new AskUserBridge(operationId, { provider: 'cursor' });+ const events = bridge.events()[Symbol.asyncIterator]();+ const pending = bridge.pending({+ arguments: { questions: [] },+ interactionKind: 'permission',+ toolCallId: 't-bridge',+ });+ expect((await events.next()).value?.type).toBe('agent_intervention_request');++ await userCaller().submitHeteroIntervention({+ operationId,+ resolutionRequestId,+ result: { approved: true },+ toolCallId: 't-bridge',+ });+ const polled = await heteroCaller(operationId).waitInterventionResponse({+ lastEventId: '0-0',+ operationId,+ });+ bridge.resolve('t-bridge', polled.events[0].data as any);+ await expect(pending).resolves.toEqual({ result: { approved: true } });++ const producerEcho = (await events.next()).value as any;+ expect(producerEcho.data).toMatchObject({+ producerAck: true,+ resolutionRequestId,+ toolCallId: 't-bridge',+ });+ bridge.cancelAll();+ });++ it('conditionally rolls back a claimed response when publish fails', async () => {+ const operationId = 'op-publish-fail';+ const resolutionRequestId = '018fbd8e-7baf-7c6d-8000-000000000004';+ await insertOperation(operationId, userId);+ business.resolveHeteroIntervention.mockResolvedValueOnce({+ claimId: 'claim-fail',+ handled: true,+ operationId,+ resolutionRequestId,+ response: { result: { approved: true }, toolCallId: 't-fail' },+ state: 'claimed',+ workspaceId: 'workspace-fail',+ });+ store.failPublish = true;++ await expect(+ userCaller().submitHeteroIntervention({+ operationId,+ resolutionRequestId,+ result: { approved: true },+ toolCallId: 't-fail',+ }),+ ).rejects.toThrow('stream publish failed');++ expect(business.rollbackHeteroInterventionResolution).toHaveBeenCalledWith({+ claimId: 'claim-fail',+ operationId,+ resolutionRequestId,+ toolCallId: 't-fail',+ userId,+ workspaceId: 'workspace-fail',+ });+ expect(business.onHeteroInterventionResolutionPublished).not.toHaveBeenCalled();+ });+it('cancel clears the result and defaults the reason', async () => {const operationId = 'op-cancel';await insertOperation(operationId, userId);diff --git a/apps/server/src/routers/lambda/__tests__/pushToken.test.ts b/apps/server/src/routers/lambda/__tests__/pushToken.test.tsindex 90883d6ea25..7bf88db4204 100644--- a/apps/server/src/routers/lambda/__tests__/pushToken.test.ts+++ b/apps/server/src/routers/lambda/__tests__/pushToken.test.ts@@ -1,12 +1,25 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { beforeEach, describe, expect, expectTypeOf, it, vi } from 'vitest';+import type { AgentInterventionReviewStatus } from '@/business/server/agent-run/agentInterventionReview';+import type * as LiveActivityBusiness from '@/business/server/notification/liveActivity';import { pushTokenRouter } from '@/server/routers/lambda/pushToken';const mockUpsert = vi.fn();const mockUnregister = vi.fn();+const mockUnregisterLiveActivities = vi.fn();const mockDeleteByExpoTokenAndDevice = vi.fn();+const mockRegisterPushToStart = vi.fn();+const mockRegisterLiveActivity = vi.fn();++vi.mock('@/business/server/notification/liveActivity', () => ({+ registerAgentInterventionLiveActivity: (...args: unknown[]) => mockRegisterLiveActivity(...args),+ registerLiveActivityPushToStartToken: (...args: unknown[]) => mockRegisterPushToStart(...args),+}));vi.mock('@/database/models/pushToken', () => ({+ PushLiveActivityModel: vi.fn(() => ({+ unregisterDevice: mockUnregisterLiveActivities,+ })),PushTokenModel: vi.fn(() => ({unregister: mockUnregister,upsert: mockUpsert,@@ -70,6 +83,33 @@ describe('pushTokenRouter', () => {});});+ it('persists the iOS push-to-start token through the business slot', async () => {+ mockUpsert.mockResolvedValueOnce({ id: 'row-1' });+ mockRegisterPushToStart.mockResolvedValueOnce(undefined);+ const caller = createCaller();++ await caller.register({+ apnsEnvironment: 'production',+ deviceId: 'iphone',+ expoToken: 'ExponentPushToken[abc]',+ liveActivityPushToStartToken: 'push-to-start-token',+ platform: 'ios',+ });++ expect(mockUpsert).toHaveBeenCalledWith({+ deviceId: 'iphone',+ expoToken: 'ExponentPushToken[abc]',+ platform: 'ios',+ });+ expect(mockRegisterPushToStart).toHaveBeenCalledWith({+ apnsEnvironment: 'production',+ deviceId: 'iphone',+ liveActivityPushToStartToken: 'push-to-start-token',+ userId: 'user-1',+ workspaceId: undefined,+ });+ });+it('should reject empty deviceId', async () => {const caller = createCaller();await expect(@@ -93,6 +133,115 @@ describe('pushTokenRouter', () => {});});+ describe('registerLiveActivity', () => {+ it('exposes the exact terminal fallback from the OSS business slot', async () => {+ const business = await vi.importActual<typeof LiveActivityBusiness>(+ '@/business/server/notification/liveActivity',+ );++ const result = await business.registerAgentInterventionLiveActivity({+ activityId: 'native-activity-1',+ activityKey: 'batch-1',+ apnsEnvironment: 'sandbox',+ deviceId: 'iphone',+ operationId: 'op-1',+ pushToken: 'activity-update-token',+ userId: 'user-1',+ });++ expect(result).toEqual({ interventionStatus: 'unavailable', interventionTerminal: true });+ expectTypeOf<LiveActivityBusiness.RegisterAgentInterventionLiveActivityResult>().toEqualTypeOf<{+ interventionStatus: AgentInterventionReviewStatus;+ interventionTerminal: boolean;+ }>();+ });++ it('registers by durable activityKey and returns interventionStatus', async () => {+ mockRegisterLiveActivity.mockResolvedValueOnce({+ interventionStatus: 'resolved',+ interventionTerminal: true,+ });+ const caller = createCaller();++ const result = await caller.registerLiveActivity({+ activityId: 'native-activity-1',+ activityKey: 'op-1:tool-1',+ apnsEnvironment: 'sandbox',+ deviceId: 'iphone',+ operationId: 'op-1',+ pushToken: 'activity-update-token',+ });++ expect(mockRegisterLiveActivity).toHaveBeenCalledWith({+ activityId: 'native-activity-1',+ activityKey: 'op-1:tool-1',+ apnsEnvironment: 'sandbox',+ deviceId: 'iphone',+ operationId: 'op-1',+ pushToken: 'activity-update-token',+ userId: 'user-1',+ workspaceId: undefined,+ });+ expect(result).toEqual({ interventionStatus: 'resolved', interventionTerminal: true });+ expectTypeOf(+ result,+ ).toEqualTypeOf<LiveActivityBusiness.RegisterAgentInterventionLiveActivityResult>();+ expectTypeOf(result.interventionStatus).toEqualTypeOf<AgentInterventionReviewStatus>();+ });++ it.each([+ { interventionStatus: 'approved', interventionTerminal: true },+ { interventionStatus: 'rejected', interventionTerminal: true },+ { interventionStatus: 'mixed', interventionTerminal: false },+ { interventionStatus: 'mixed', interventionTerminal: true },+ ] satisfies LiveActivityBusiness.RegisterAgentInterventionLiveActivityResult[])(+ 'preserves generic status $interventionStatus with terminal=$interventionTerminal',+ async (registrationResult) => {+ mockRegisterLiveActivity.mockResolvedValueOnce(registrationResult);+ const caller = createCaller();++ const result = await caller.registerLiveActivity({+ activityId: 'native-activity-1',+ activityKey: 'batch-1',+ apnsEnvironment: 'sandbox',+ deviceId: 'iphone',+ operationId: 'op-1',+ pushToken: 'activity-update-token',+ });++ expect(result).toEqual(registrationResult);+ },+ );++ it('rejects a legacy activityId-only registration without a durable activityKey', async () => {+ const caller = createCaller();+ await expect(+ // @ts-expect-error validates that activityKey is mandatory+ caller.registerLiveActivity({+ activityId: 'local-activity-id',+ apnsEnvironment: 'production',+ deviceId: 'iphone',+ operationId: 'op-1',+ pushToken: 'token',+ }),+ ).rejects.toThrow();+ });++ it('rejects an activityKey-only registration without the native activityId', async () => {+ const caller = createCaller();+ await expect(+ // @ts-expect-error validates that activityId is mandatory+ caller.registerLiveActivity({+ activityKey: 'op-1:tool-1',+ apnsEnvironment: 'production',+ deviceId: 'iphone',+ operationId: 'op-1',+ pushToken: 'token',+ }),+ ).rejects.toThrow();+ });+ });+describe('unregister', () => {it('should delete by (expoToken, deviceId) when expoToken is provided', async () => {mockDeleteByExpoTokenAndDevice.mockResolvedValueOnce(undefined);@@ -123,6 +272,7 @@ describe('pushTokenRouter', () => {const result = await caller.unregister({ deviceId: 'device-1' });expect(mockUnregister).toHaveBeenCalledWith('device-1');+ expect(mockUnregisterLiveActivities).toHaveBeenCalledWith('device-1');expect(mockDeleteByExpoTokenAndDevice).not.toHaveBeenCalled();expect(result).toEqual({ success: true });});@@ -137,6 +287,7 @@ describe('pushTokenRouter', () => {expect(mockDeleteByExpoTokenAndDevice).not.toHaveBeenCalled();expect(mockUnregister).not.toHaveBeenCalled();+ expect(mockUnregisterLiveActivities).not.toHaveBeenCalled();expect(result).toEqual({ success: true });});@@ -152,6 +303,7 @@ describe('pushTokenRouter', () => {expect(result).toEqual({ success: true });expect(mockDeleteByExpoTokenAndDevice).toHaveBeenCalled();expect(mockUnregister).not.toHaveBeenCalled();+ expect(mockUnregisterLiveActivities).not.toHaveBeenCalled();});it('should prefer expoToken precision over the legacy userId fallback', async () => {@@ -175,9 +327,7 @@ describe('pushTokenRouter', () => {it('should reject empty expoToken when provided', async () => {const caller = createCaller();- await expect(- caller.unregister({ deviceId: 'device-1', expoToken: '' }),- ).rejects.toThrow();+ await expect(caller.unregister({ deviceId: 'device-1', expoToken: '' })).rejects.toThrow();});});});diff --git a/apps/server/src/routers/lambda/_helpers/conversationResourceGuard.test.ts b/apps/server/src/routers/lambda/_helpers/conversationResourceGuard.test.tsindex aa18e5f1485..99b79253927 100644--- a/apps/server/src/routers/lambda/_helpers/conversationResourceGuard.test.ts+++ b/apps/server/src/routers/lambda/_helpers/conversationResourceGuard.test.ts@@ -15,6 +15,7 @@ import {assertCanUseMessageTargets,assertCanUseSessionTargets,assertCanUseTopicTargets,+ assertCanViewConversationTargets,assertCanViewTopicTargets,filterUserIdsByTopicViewAccess,} from './conversationResourceGuard';@@ -142,6 +143,32 @@ describe('assertCanUseConversationTargets', () => {});});+describe('assertCanViewConversationTargets', () => {+ it('checks authoritative agent/group context with view access and returns what was gated', async () => {+ const resolved = await assertCanViewConversationTargets(baseCtx(createDb([])), [+ { agentId: 'agent-1', groupId: 'group-1' },+ ]);++ expect(resolved.map(({ resourceId, resourceType }) => ({ resourceId, resourceType }))).toEqual([+ { resourceId: 'group-1', resourceType: 'agentGroup' },+ { resourceId: 'agent-1', resourceType: 'agent' },+ ]);+ expect(assertActionMock).toHaveBeenCalledTimes(2);+ expect(assertActionMock).toHaveBeenCalledWith(+ expect.objectContaining({ action: 'view', resourceId: 'agent-1' }),+ );+ });++ it('returns an empty result for an unbacked workspace target so callers can fail closed', async () => {+ getResourceMetaMock.mockResolvedValue(null);++ await expect(+ assertCanViewConversationTargets(baseCtx(createDb([])), [{ agentId: 'missing-agent' }]),+ ).resolves.toEqual([]);+ expect(assertActionMock).not.toHaveBeenCalled();+ });+});+describe('assertCanUseMessageTargets', () => {it('resolves the owning agent from the message rows', async () => {const db = createDb([[{ agentId: 'agent-1', groupId: null, topicId: 't-1' }]]);diff --git a/apps/server/src/routers/lambda/_helpers/conversationResourceGuard.ts b/apps/server/src/routers/lambda/_helpers/conversationResourceGuard.tsindex 7424c73bdfb..d921279e760 100644--- a/apps/server/src/routers/lambda/_helpers/conversationResourceGuard.ts+++ b/apps/server/src/routers/lambda/_helpers/conversationResourceGuard.ts@@ -28,7 +28,7 @@ export interface CreateMessageTarget extends ConversationTarget {topicId?: string | null;}-interface ResolvedConversationTarget {+export interface ResolvedConversationTarget {meta: NonNullable<Awaited<ReturnType<typeof getResourceMeta>>>;resourceId: string;resourceType: 'agent' | 'agentGroup';@@ -98,9 +98,9 @@ const assertCanAccessConversationTargets = async (ctx: ConversationGuardCtx,targets: ConversationTarget[],action: 'use' | 'view',-): Promise<void> => {+): Promise<ResolvedConversationTarget[]> => {const workspaceId = ctx.workspaceId ?? undefined;- if (!workspaceId) return;+ if (!workspaceId) return [];const resolved = await resolveConversationTargets(ctx, targets);for (const { meta, resourceId, resourceType } of resolved) {@@ -115,12 +115,25 @@ const assertCanAccessConversationTargets = async (workspaceId,});}+ return resolved;};export const assertCanUseConversationTargets = async (ctx: ConversationGuardCtx,targets: ConversationTarget[],-): Promise<void> => assertCanAccessConversationTargets(ctx, targets, 'use');+): Promise<ResolvedConversationTarget[]> => assertCanAccessConversationTargets(ctx, targets, 'use');++/**+ * Assert read-only access to authoritative agent/group context and return the+ * resources that were actually checked. An empty workspace result is a+ * vacuous pass, not authorization; token/operation callers must fail closed or+ * fall back to an independently resolved topic resource.+ */+export const assertCanViewConversationTargets = async (+ ctx: ConversationGuardCtx,+ targets: ConversationTarget[],+): Promise<ResolvedConversationTarget[]> =>+ assertCanAccessConversationTargets(ctx, targets, 'view');/*** Resolve message ids to their owning agent/group from the DB rows (client@@ -151,6 +164,37 @@ export const assertCanUseMessageTargets = async (}};+/**+ * Read-only counterpart used by source-locator Review. Message ids locate the+ * authoritative conversation resource but never grant access themselves.+ * Missing rows are intentionally not treated as authorization; the durable+ * business lookup must require an all-or-none source match and fail closed on+ * partial/mismatched batches.+ */+export const assertCanViewMessageTargets = async (+ ctx: ConversationGuardCtx,+ messageIds: string[],+): Promise<void> => {+ if (!ctx.workspaceId || messageIds.length === 0) return;++ const rows = await ctx.db+ .select({ agentId: messages.agentId, groupId: messages.groupId, topicId: messages.topicId })+ .from(messages)+ .where(inArray(messages.id, messageIds));++ const targets: ConversationTarget[] = [];+ const fallbackTopicIds = new Set<string>();+ for (const row of rows) {+ if (row.agentId || row.groupId) targets.push(row);+ else if (row.topicId) fallbackTopicIds.add(row.topicId);+ }++ await assertCanViewConversationTargets(ctx, targets);+ if (fallbackTopicIds.size > 0) {+ await assertCanViewTopicTargets(ctx, [...fallbackTopicIds]);+ }+};+const resolveTopicTargets = async (ctx: Pick<ConversationGuardCtx, 'db' | 'workspaceId'>,topicIds: string[],diff --git a/apps/server/src/routers/lambda/_schema/agentIntervention.test.ts b/apps/server/src/routers/lambda/_schema/agentIntervention.test.tsnew file mode 100644index 00000000000..95b3ea8afa2--- /dev/null+++ b/apps/server/src/routers/lambda/_schema/agentIntervention.test.ts@@ -0,0 +1,236 @@+import { describe, expect, it } from 'vitest';++import {+ AgentInterventionRequestRevisionSchema,+ GetAgentInterventionReviewBySourceSchema,+ ResolveAgentInterventionBySourceSchema,+ ResolveAgentInterventionSchema,+} from './agentIntervention';++const revision = {+ hash: 'a'.repeat(64),+ version: 1,+};++const wrapper = {+ expectedBatchVersion: 1,+ expectedRequestRevisions: { 'item-1': revision },+ resolutionRequestId: '3db6ef38-701a-426f-832d-027369533b29',+ reviewToken: 'a'.repeat(43),+};++describe('ResolveAgentInterventionSchema', () => {+ it('accepts the frozen approve contract without client authority fields', () => {+ expect(+ ResolveAgentInterventionSchema.parse({+ ...wrapper,+ action: {+ itemIds: ['item-1'],+ scope: 'remember',+ type: 'approve_tool',+ },+ }),+ ).toMatchObject(wrapper);+ });++ it('strictly rejects the removed skip reason and any client operation/tool authority', () => {+ expect(+ ResolveAgentInterventionSchema.safeParse({+ ...wrapper,+ action: { itemId: 'item-1', reason: 'not in v2', type: 'skip_interaction' },+ }).success,+ ).toBe(false);+ expect(+ ResolveAgentInterventionSchema.safeParse({+ ...wrapper,+ action: { itemId: 'item-1', type: 'skip_interaction' },+ canonicalToolKey: 'lobe-local-system/editFile',+ operationId: 'client-operation',+ }).success,+ ).toBe(false);+ });++ it('accepts only operation-scoped Stop', () => {+ expect(+ ResolveAgentInterventionSchema.safeParse({+ ...wrapper,+ action: { scope: 'operation', type: 'stop' },+ }).success,+ ).toBe(true);+ expect(+ ResolveAgentInterventionSchema.safeParse({+ ...wrapper,+ action: { scope: 'batch', type: 'stop' },+ }).success,+ ).toBe(false);+ });++ it('requires a complete non-empty revision map and lowercase SHA-256 hashes', () => {+ expect(+ ResolveAgentInterventionSchema.safeParse({+ ...wrapper,+ action: { itemId: 'item-1', type: 'skip_interaction' },+ expectedRequestRevisions: {},+ }).success,+ ).toBe(false);+ expect(+ AgentInterventionRequestRevisionSchema.safeParse({ ...revision, hash: 'A'.repeat(64) })+ .success,+ ).toBe(false);+ });++ it('allows argument edits only for one selected intervention', () => {+ expect(+ ResolveAgentInterventionSchema.safeParse({+ ...wrapper,+ action: {+ edits: { 'item-1': { path: '/tmp/a' }, 'item-2': { path: '/tmp/b' } },+ itemIds: ['item-1', 'item-2'],+ scope: 'once',+ type: 'approve_tool',+ },+ expectedRequestRevisions: { 'item-1': revision, 'item-2': revision },+ }).success,+ ).toBe(false);+ });++ it('bounds private edited arguments by key count and serialized size', () => {+ const parse = (editedArguments: Record<string, unknown>) =>+ ResolveAgentInterventionSchema.safeParse({+ ...wrapper,+ action: {+ edits: { 'item-1': editedArguments },+ itemIds: ['item-1'],+ scope: 'once',+ type: 'approve_tool',+ },+ }).success;++ expect(+ parse(Object.fromEntries(Array.from({ length: 101 }, (_, index) => [`k${index}`, 1]))),+ ).toBe(false);+ expect(parse({ content: 'x'.repeat(65 * 1024) })).toBe(false);+ expect(parse({ content: 'bounded' })).toBe(true);+ });++ it('keeps the marketplace external result discriminator exact', () => {+ expect(+ ResolveAgentInterventionSchema.safeParse({+ ...wrapper,+ action: {+ itemId: 'item-1',+ result: { kind: 'agent_marketplace', selectedIds: ['agent-1'] },+ type: 'submit_custom',+ },+ }).success,+ ).toBe(false);+ expect(+ ResolveAgentInterventionSchema.safeParse({+ ...wrapper,+ action: {+ itemId: 'item-1',+ result: { kind: 'agent_marketplace', selectedTemplateIds: ['agent-1'] },+ type: 'submit_custom',+ },+ }).success,+ ).toBe(true);+ });+});++describe('ResolveAgentInterventionBySourceSchema', () => {+ const source = {+ batchId: 'op-1:2:assistant-1',+ operationId: 'op-1',+ resolutionRequestId: '3db6ef38-701a-426f-832d-027369533b29',+ targets: [{ toolCallId: 'call-1', toolMessageId: 'message-1' }],+ };++ it('accepts exact source-locator Web actions without durable item authority', () => {+ expect(+ ResolveAgentInterventionBySourceSchema.parse({+ ...source,+ action: { scope: 'once', type: 'approve_tool' },+ }),+ ).toMatchObject(source);+ expect(+ ResolveAgentInterventionBySourceSchema.safeParse({+ ...source,+ action: {+ result: { kind: 'agent_marketplace', selectedTemplateIds: ['template-1'] },+ type: 'submit_custom',+ },+ }).success,+ ).toBe(true);+ });++ it('accepts only operation-scoped source Stop', () => {+ expect(+ ResolveAgentInterventionBySourceSchema.safeParse({+ ...source,+ action: { scope: 'operation', type: 'stop' },+ }).success,+ ).toBe(true);+ expect(+ ResolveAgentInterventionBySourceSchema.safeParse({+ ...source,+ action: { scope: 'batch', type: 'stop' },+ }).success,+ ).toBe(false);+ });++ it('applies the same edit bounds to source actions', () => {+ expect(+ ResolveAgentInterventionBySourceSchema.safeParse({+ ...source,+ action: {+ edits: { 'message-1': { content: 'x'.repeat(65 * 1024) } },+ scope: 'once',+ type: 'approve_tool',+ },+ }).success,+ ).toBe(false);+ });++ it('rejects duplicate source targets and generic submit/skip payloads', () => {+ expect(+ ResolveAgentInterventionBySourceSchema.safeParse({+ ...source,+ action: { result: {}, type: 'submit' },+ }).success,+ ).toBe(false);+ expect(+ ResolveAgentInterventionBySourceSchema.safeParse({+ ...source,+ action: { reason: 'removed', type: 'skip_interaction' },+ }).success,+ ).toBe(false);+ expect(+ ResolveAgentInterventionBySourceSchema.safeParse({+ ...source,+ action: { scope: 'operation', type: 'stop' },+ targets: [source.targets[0], source.targets[0]],+ }).success,+ ).toBe(false);+ });++ it('reuses the exact strict locator contract for read-only source Review', () => {+ const locator = {+ batchId: source.batchId,+ operationId: source.operationId,+ targets: source.targets,+ };+ expect(GetAgentInterventionReviewBySourceSchema.parse(locator)).toEqual(locator);+ expect(+ GetAgentInterventionReviewBySourceSchema.safeParse({+ ...locator,+ action: { scope: 'once', type: 'approve_tool' },+ }).success,+ ).toBe(false);+ expect(+ GetAgentInterventionReviewBySourceSchema.safeParse({+ ...locator,+ targets: [source.targets[0], source.targets[0]],+ }).success,+ ).toBe(false);+ });+});diff --git a/apps/server/src/routers/lambda/_schema/agentIntervention.ts b/apps/server/src/routers/lambda/_schema/agentIntervention.tsnew file mode 100644index 00000000000..b26cede587b--- /dev/null+++ b/apps/server/src/routers/lambda/_schema/agentIntervention.ts@@ -0,0 +1,261 @@+import { z } from 'zod';++export const AgentInterventionReviewTokenSchema = z+ .string()+ .regex(/^[\w-]{43}$/, 'Invalid intervention review token');++export const AgentInterventionRequestRevisionSchema = z+ .object({+ hash: z.string().regex(/^[a-f0-9]{64}$/),+ version: z.number().int().nonnegative(),+ })+ .strict();++const ExpectedRevisionMapSchema = z+ .record(z.string().min(1), AgentInterventionRequestRevisionSchema)+ .refine((revisions) => Object.keys(revisions).length > 0, {+ message: 'Expected revisions must cover the sealed batch',+ });++const UniqueItemIdsSchema = z+ .array(z.string().min(1))+ .min(1)+ .refine((ids) => new Set(ids).size === ids.length, { message: 'Duplicate item ids' });++const MAX_EDIT_ARGUMENT_KEYS = 100;+const MAX_SERIALIZED_EDIT_BYTES = 64 * 1024;+const isBoundedSerializedJSON = (value: unknown): boolean => {+ try {+ return new TextEncoder().encode(JSON.stringify(value)).byteLength <= MAX_SERIALIZED_EDIT_BYTES;+ } catch {+ return false;+ }+};+const EditedArgumentsSchema = z+ .record(+ z.string().min(1).max(500),+ z+ .record(z.string().min(1).max(500), z.unknown())+ .refine((arguments_) => Object.keys(arguments_).length <= MAX_EDIT_ARGUMENT_KEYS, {+ message: 'Too many edited argument keys',+ }),+ )+ .refine(isBoundedSerializedJSON, { message: 'Edited arguments are too large' });++const SelectProviderOptionSchema = z+ .object({+ itemId: z.string().min(1),+ optionId: z.string().min(1),+ type: z.literal('select_provider_option'),+ })+ .strict();++const ApproveToolSchema = z+ .object({+ edits: EditedArgumentsSchema.optional(),+ itemIds: UniqueItemIdsSchema,+ scope: z.enum(['once', 'remember']),+ type: z.literal('approve_tool'),+ })+ .strict()+ .superRefine((data, ctx) => {+ if (data.edits && data.itemIds.length !== 1) {+ ctx.addIssue({+ code: 'custom',+ message: 'Argument edits are allowed only for a single tool approval',+ path: ['edits'],+ });+ }+ if (data.edits && Object.keys(data.edits).some((id) => id !== data.itemIds[0])) {+ ctx.addIssue({+ code: 'custom',+ message: 'Argument edits must target the selected intervention',+ path: ['edits'],+ });+ }+ });++const RejectContinueSchema = z+ .object({+ itemIds: UniqueItemIdsSchema,+ reason: z.string().trim().max(2000).optional(),+ type: z.literal('reject_continue'),+ })+ .strict();++const StopSchema = z+ .object({+ scope: z.literal('operation'),+ type: z.literal('stop'),+ })+ .strict();++const SubmitAnswersSchema = z+ .object({+ itemId: z.string().min(1),+ result: z+ .record(+ z.string().min(1).max(500),+ z.union([z.string().max(4000), z.array(z.string().max(1000)).max(50)]),+ )+ .refine((result) => Object.keys(result).length > 0, {+ message: 'At least one answer is required',+ })+ .refine((result) => Object.keys(result).length <= 50, {+ message: 'Too many answers',+ }),+ type: z.literal('submit_answers'),+ })+ .strict();++const SubmitCustomSchema = z+ .object({+ itemId: z.string().min(1),+ // Exact external marketplace result. The Cloud adapter maps this to its+ // internal `selectedIds`; requestId/categoryHints are loaded from the+ // durable row and are never accepted from the client.+ result: z+ .object({+ kind: z.literal('agent_marketplace'),+ selectedTemplateIds: z.array(z.string().min(1)).min(1).max(50),+ })+ .strict(),+ type: z.literal('submit_custom'),+ })+ .strict();++const SkipInteractionSchema = z+ .object({+ itemId: z.string().min(1),+ type: z.literal('skip_interaction'),+ })+ .strict();++const CancelInteractionSchema = z+ .object({+ itemId: z.string().min(1),+ type: z.literal('cancel_interaction'),+ })+ .strict();++export const AgentInterventionResolutionActionSchema = z.discriminatedUnion('type', [+ SelectProviderOptionSchema,+ ApproveToolSchema,+ RejectContinueSchema,+ StopSchema,+ SubmitAnswersSchema,+ SubmitCustomSchema,+ SkipInteractionSchema,+ CancelInteractionSchema,+]);++export const GetAgentInterventionReviewSchema = z+ .object({ reviewToken: AgentInterventionReviewTokenSchema })+ .strict();++export const ResolveAgentInterventionSchema = z+ .object({+ action: AgentInterventionResolutionActionSchema,+ expectedBatchVersion: z.number().int().nonnegative(),+ expectedRequestRevisions: ExpectedRevisionMapSchema,+ resolutionRequestId: z.string().uuid(),+ reviewToken: AgentInterventionReviewTokenSchema,+ })+ .strict();++const AgentInterventionSourceTargetSchema = z+ .object({+ toolCallId: z.string().min(1),+ toolMessageId: z.string().min(1),+ })+ .strict();++const AgentInterventionSourceTargetsSchema = z+ .array(AgentInterventionSourceTargetSchema)+ .min(1)+ .max(100)+ .superRefine((targets, ctx) => {+ const toolCallIds = targets.map(({ toolCallId }) => toolCallId);+ const toolMessageIds = targets.map(({ toolMessageId }) => toolMessageId);+ if (+ new Set(toolCallIds).size !== toolCallIds.length ||+ new Set(toolMessageIds).size !== toolMessageIds.length+ ) {+ ctx.addIssue({ code: 'custom', message: 'Duplicate source targets' });+ }+ });++export const GetAgentInterventionReviewBySourceSchema = z+ .object({+ batchId: z.string().min(1),+ operationId: z.string().min(1),+ targets: AgentInterventionSourceTargetsSchema,+ })+ .strict();++const AgentInterventionSourceActionSchema = z.discriminatedUnion('type', [+ z+ .object({+ optionId: z.string().min(1),+ type: z.literal('select_provider_option'),+ })+ .strict(),+ z+ .object({+ edits: EditedArgumentsSchema.optional(),+ scope: z.enum(['once', 'remember']),+ type: z.literal('approve_tool'),+ })+ .strict(),+ z+ .object({+ reason: z.string().trim().max(2000).optional(),+ type: z.literal('reject_continue'),+ })+ .strict(),+ z.object({ scope: z.literal('operation'), type: z.literal('stop') }).strict(),+ z+ .object({+ result: SubmitAnswersSchema.shape.result,+ type: z.literal('submit_answers'),+ })+ .strict(),+ z+ .object({+ result: SubmitCustomSchema.shape.result,+ type: z.literal('submit_custom'),+ })+ .strict(),+ z.object({ type: z.literal('skip_interaction') }).strict(),+ z.object({ type: z.literal('cancel_interaction') }).strict(),+]);++export const ResolveAgentInterventionBySourceSchema = z+ .object({+ action: AgentInterventionSourceActionSchema,+ batchId: z.string().min(1),+ operationId: z.string().min(1),+ resolutionRequestId: z.string().uuid(),+ targets: AgentInterventionSourceTargetsSchema,+ })+ .strict()+ .superRefine((data, ctx) => {+ if (data.action.type !== 'approve_tool' || !data.action.edits) return;+ if (data.targets.length !== 1) {+ ctx.addIssue({+ code: 'custom',+ message: 'Argument edits are allowed only for one source target',+ path: ['action', 'edits'],+ });+ return;+ }+ const [target] = data.targets;+ const editedMessageIds = Object.keys(data.action.edits);+ if (editedMessageIds.length !== 1 || editedMessageIds[0] !== target.toolMessageId) {+ ctx.addIssue({+ code: 'custom',+ message: 'Argument edits must target the source tool message',+ path: ['action', 'edits'],+ });+ }+ });diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.tsindex 246d523c837..b28de426c94 100644--- a/apps/server/src/routers/lambda/aiAgent.ts+++ b/apps/server/src/routers/lambda/aiAgent.ts@@ -1,8 +1,10 @@+import { randomUUID } from 'node:crypto';+import { type AgentStreamEvent } from '@lobechat/agent-gateway-client';import { LOADING_FLAT } from '@lobechat/const';import { isFullAccessApiKey } from '@lobechat/const/apiKeyScope';import { parse } from '@lobechat/conversation-flow';-import type { TaskCurrentActivity, TaskStatusResult } from '@lobechat/types';+import type { ExecAgentResult, TaskCurrentActivity, TaskStatusResult } from '@lobechat/types';import {entityIdPattern,LocalHeterogeneousAgentTypeSchema,@@ -18,10 +20,34 @@ import { and, eq, isNull } from 'drizzle-orm';import pMap from 'p-map';import { z } from 'zod';+import {+ deriveAgentInterventionContinuationMessageId,+ deriveAgentInterventionContinuationOperationId,+ deriveAgentInterventionQueueDeduplicationId,+} from '@/business/server/agent-run/agentInterventionIdentity';+import {+ type AgentInterventionReviewStatus,+ type AgentInterventionRuntimeAction,+ type AgentInterventionSourceAction,+ getAgentInterventionReview,+ getAgentInterventionReviewBySource,+ onAgentInterventionResolutionPublished,+ resolveAgentIntervention,+ resolveAgentInterventionBySource,+ type ResolveAgentInterventionResult,+ rollbackAgentInterventionResolution,+} from '@/business/server/agent-run/agentInterventionReview';+import { executeAgentMarketplaceIntervention } from '@/business/server/agent-run/executeCustomIntervention';+import {+ getHeteroInterventionReview,+ onHeteroInterventionResolutionPublished,+ resolveHeteroIntervention,+ rollbackHeteroInterventionResolution,+} from '@/business/server/agent-run/heteroInterventionReview';import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';import { AgentOperationModel } from '@/database/models/agentOperation';-import { MessageModel } from '@/database/models/message';+import { HumanApprovalAlreadyResolvedError, MessageModel } from '@/database/models/message';import { ThreadModel } from '@/database/models/thread';import { TopicModel } from '@/database/models/topic';import { UserModel } from '@/database/models/user';@@ -41,8 +67,15 @@ import {import {assertCanUseMessageTargets,assertCanUseTopicTargets,+ assertCanViewMessageTargets,} from '@/server/routers/lambda/_helpers/conversationResourceGuard';import { assertCanUseWorkspaceAgent } from '@/server/routers/lambda/_helpers/workspaceAgentGuard';+import {+ GetAgentInterventionReviewBySourceSchema,+ GetAgentInterventionReviewSchema,+ ResolveAgentInterventionBySourceSchema,+ ResolveAgentInterventionSchema,+} from '@/server/routers/lambda/_schema/agentIntervention';import { AgentRuntimeService } from '@/server/services/agentRuntime';import { AiAgentService } from '@/server/services/aiAgent';import { AiChatService } from '@/server/services/aiChat';@@ -55,6 +88,596 @@ import {const log = debug('lobe-server:ai-agent-router');+type ClaimedAgentInterventionResolution = Extract<+ ResolveAgentInterventionResult,+ { state: 'claimed' }+>;++interface AgentInterventionDispatchContext {+ aiAgentService: AiAgentService;+ serverDB: LobeChatDatabase;+ userId: string;+ workspaceId?: string | null;+}++const publishedStatusForRuntimeAction = (+ runtimeAction: AgentInterventionRuntimeAction,+): AgentInterventionReviewStatus => {+ switch (runtimeAction.type) {+ case 'execute_custom_interaction': {+ return runtimeAction.input.action.type === 'cancelled'+ ? 'cancelled'+ : runtimeAction.input.action.type === 'skipped'+ ? 'skipped'+ : 'resolved';+ }+ case 'heterogeneous_response': {+ return 'resolving';+ }+ case 'resume_approval': {+ return runtimeAction.decisions.every(({ decision }) => decision === 'approved')+ ? 'approved'+ : runtimeAction.decisions.every(({ decision }) => decision === 'rejected_continue')+ ? 'rejected'+ : 'mixed';+ }+ case 'resume_tool_result': {+ return runtimeAction.outcome === 'skipped' ? 'skipped' : 'resolved';+ }+ case 'stop': {+ return runtimeAction.terminalStatus;+ }+ }+};++type RuntimeActionDispatchProbe =+ | { state: 'conflict' }+ | { state: 'dispatched' }+ | { retry: 'rebuild' | 'schedule' | 'stop'; state: 'prepared' }+ | { state: 'unclaimed' };++const sameNullable = (left: unknown, right: unknown): boolean => (left ?? null) === (right ?? null);++const sameStringSet = (left: string[], right: string[]): boolean => {+ const a = [...left].sort();+ const b = [...right].sort();+ return a.length === b.length && a.every((value, index) => value === b[index]);+};++const continuationRuntimeAction = (+ runtimeAction: AgentInterventionRuntimeAction,+): Extract<+ AgentInterventionRuntimeAction,+ { type: 'execute_custom_interaction' | 'resume_approval' | 'resume_tool_result' }+> | null => {+ if (runtimeAction.type === 'resume_approval' || runtimeAction.type === 'resume_tool_result') {+ return runtimeAction;+ }+ if (+ runtimeAction.type === 'execute_custom_interaction' &&+ runtimeAction.input.action.type !== 'cancelled'+ ) {+ return runtimeAction;+ }+ return null;+};++/**+ * Probe a retry against both the source-message claim and the deterministic+ * continuation operation. A message marker alone only proves the request was+ * prepared; a matching owner-scoped operation plus runtime state proves it was+ * dispatched. This closes the crash window between message CAS and scheduling.+ */+const probeRuntimeActionDispatch = async (+ resolution: ClaimedAgentInterventionResolution,+ ctx: AgentInterventionDispatchContext,+): Promise<RuntimeActionDispatchProbe> => {+ const { runtimeAction } = resolution;+ const expected: Array<{ messageId: string; skipped?: true; status: string }> = [];++ switch (runtimeAction.type) {+ case 'execute_custom_interaction': {+ if (runtimeAction.input.action.type === 'cancelled') {+ expected.push(+ ...runtimeAction.toolMessageIds.map((messageId) => ({ messageId, status: 'aborted' })),+ );+ } else {+ expected.push({+ messageId: runtimeAction.parentMessageId,+ ...(runtimeAction.input.action.type === 'skipped' && { skipped: true as const }),+ status: runtimeAction.input.action.type === 'skipped' ? 'rejected' : 'approved',+ });+ }+ break;+ }+ case 'heterogeneous_response': {+ // The producer de-duplicates the stable resolutionRequestId. There is no+ // runtime message claim that can prove whether XADD happened before a+ // crash, so a resolving retry republishes the same idempotency key.+ return { state: 'unclaimed' };+ }+ case 'resume_approval': {+ expected.push(+ ...runtimeAction.decisions.map((decision) => ({+ messageId: decision.parentMessageId,+ status: decision.decision === 'approved' ? 'approved' : 'rejected',+ })),+ );+ break;+ }+ case 'resume_tool_result': {+ expected.push({+ messageId: runtimeAction.parentMessageId,+ ...(runtimeAction.outcome === 'skipped' && { skipped: true as const }),+ status: runtimeAction.outcome === 'skipped' ? 'rejected' : 'approved',+ });+ break;+ }+ case 'stop': {+ expected.push(+ ...runtimeAction.toolMessageIds.map((messageId) => ({ messageId, status: 'aborted' })),+ );+ break;+ }+ }++ if (expected.length === 0) return { state: 'unclaimed' };+ const messageModel = new MessageModel(+ ctx.serverDB,+ resolution.ownerUserId,+ resolution.workspaceId ?? ctx.workspaceId ?? undefined,+ );+ const plugins = await Promise.all(+ expected.map(({ messageId }) => messageModel.findMessagePlugin(messageId)),+ );++ if (plugins.every((plugin) => plugin?.intervention?.status === 'pending')) {+ return { state: 'unclaimed' };+ }++ const sourceClaimMatches = plugins.every((plugin, index) => {+ const expectedIntervention = expected[index];+ return (+ plugin?.intervention?.resolutionRequestId === resolution.resolutionRequestId &&+ plugin.intervention.status === expectedIntervention.status &&+ (!expectedIntervention.skipped || plugin.intervention.skipped === true)+ );+ });+ if (!sourceClaimMatches) return { state: 'conflict' };++ // Stop and current custom-cancel semantics settle the parked operation+ // itself. The message claim is only complete when that exact operation is+ // durably interrupted; a crash between the two is retryable preparation.+ if (+ runtimeAction.type === 'stop' ||+ (runtimeAction.type === 'execute_custom_interaction' &&+ runtimeAction.input.action.type === 'cancelled')+ ) {+ const operationModel = new AgentOperationModel(+ ctx.serverDB,+ resolution.ownerUserId,+ resolution.workspaceId ?? ctx.workspaceId ?? undefined,+ );+ const operation = await operationModel.findById(runtimeAction.operationId);+ const topicId =+ runtimeAction.type === 'stop' ? runtimeAction.topicId : runtimeAction.appContext.topicId;+ if (!operation || operation.topicId !== topicId) return { state: 'conflict' };+ if (operation.status === 'interrupted') return { state: 'dispatched' };+ return operation.status === 'waiting_for_human'+ ? { retry: 'stop', state: 'prepared' }+ : { state: 'conflict' };+ }++ const continuation = continuationRuntimeAction(runtimeAction);+ if (!continuation) return { state: 'conflict' };+ const continuationOperationId = deriveAgentInterventionContinuationOperationId({+ resolutionRequestId: resolution.resolutionRequestId,+ userId: resolution.ownerUserId,+ workspaceId: resolution.workspaceId ?? ctx.workspaceId,+ });+ const operationModel = new AgentOperationModel(+ ctx.serverDB,+ resolution.ownerUserId,+ resolution.workspaceId ?? ctx.workspaceId ?? undefined,+ );+ const operation = await operationModel.findById(continuationOperationId);+ if (!operation) return { retry: 'rebuild', state: 'prepared' };++ const sourceToolMessageIds =+ continuation.type === 'resume_approval'+ ? continuation.decisions.map(({ parentMessageId }) => parentMessageId)+ : [continuation.parentMessageId];+ const provenance = operation.metadata?.agentInterventionContinuation as+ | {+ resolutionRequestId?: unknown;+ sourceOperationId?: unknown;+ sourceToolMessageIds?: unknown;+ }+ | undefined;+ const rowContextMatches =+ operation.agentId === continuation.agentId &&+ operation.topicId === continuation.appContext.topicId &&+ sameNullable(operation.threadId, continuation.appContext.threadId) &&+ sameNullable(operation.taskId, continuation.appContext.taskId) &&+ sameNullable(operation.chatGroupId, continuation.appContext.groupId) &&+ sameNullable(operation.appContext?.documentId, continuation.appContext.documentId) &&+ sameNullable(operation.appContext?.groupId, continuation.appContext.groupId) &&+ sameNullable(operation.appContext?.scope, continuation.appContext.scope) &&+ sameNullable(operation.appContext?.sessionId, continuation.appContext.sessionId) &&+ operation.appContext?.sourceMessageId === continuation.parentMessageId &&+ provenance?.resolutionRequestId === resolution.resolutionRequestId &&+ provenance.sourceOperationId === continuation.operationId &&+ Array.isArray(provenance.sourceToolMessageIds) &&+ provenance.sourceToolMessageIds.every((id) => typeof id === 'string') &&+ sameStringSet(provenance.sourceToolMessageIds as string[], sourceToolMessageIds);+ if (!rowContextMatches) return { state: 'conflict' };++ const expectedDeduplicationId = deriveAgentInterventionQueueDeduplicationId(+ continuationOperationId,+ 0,+ );+ const dispatchMarker = operation.metadata?.agentInterventionDispatch as+ | {+ deduplicationId?: unknown;+ resolutionRequestId?: unknown;+ state?: unknown;+ }+ | undefined;+ if (dispatchMarker) {+ return dispatchMarker.state === 'scheduled' &&+ dispatchMarker.resolutionRequestId === resolution.resolutionRequestId &&+ dispatchMarker.deduplicationId === expectedDeduplicationId+ ? { state: 'dispatched' }+ : { state: 'conflict' };+ }++ const durablePreparation = operation.metadata?.agentInterventionPreparation as+ | {+ deduplicationId?: unknown;+ resolutionRequestId?: unknown;+ state?: unknown;+ stepIndex?: unknown;+ }+ | undefined;+ const durablePreparationMatches =+ durablePreparation?.state === 'ready' &&+ durablePreparation.resolutionRequestId === resolution.resolutionRequestId &&+ durablePreparation.stepIndex === 0 &&+ durablePreparation.deduplicationId === expectedDeduplicationId;+ if (durablePreparation && !durablePreparationMatches) return { state: 'conflict' };++ const state = await ctx.aiAgentService.loadInterventionContinuationState(continuationOperationId);+ if (!state) {+ // A row alone is never dispatch proof: recordStart precedes state + queue,+ // and even `abandoned` can be watchdog settlement of that bare row. Only a+ // provider ACK marker or an owner/context-matching live state can advance+ // lifecycle completion. Unknown terminal/no-state combinations fail closed.+ return !durablePreparation && operation.status === 'running'+ ? { retry: 'rebuild', state: 'prepared' }+ : { state: 'conflict' };+ }++ const stateProvenance = state.metadata?.agentInterventionContinuation as+ typeof provenance | undefined;+ const statePreparation = state.metadata?.agentInterventionPreparation as+ | {+ deduplicationId?: unknown;+ resolutionRequestId?: unknown;+ state?: unknown;+ stepIndex?: unknown;+ }+ | undefined;+ const stateContextMatches =+ state.operationId === continuationOperationId &&+ state.metadata?.userId === resolution.ownerUserId &&+ sameNullable(+ state.metadata?.workspaceId,+ resolution.workspaceId ?? ctx.workspaceId ?? undefined,+ ) &&+ state.metadata?.agentId === continuation.agentId &&+ state.metadata?.topicId === continuation.appContext.topicId &&+ sameNullable(state.metadata?.threadId, continuation.appContext.threadId) &&+ sameNullable(state.metadata?.taskId, continuation.appContext.taskId) &&+ sameNullable(state.metadata?.groupId, continuation.appContext.groupId) &&+ sameNullable(state.metadata?.documentId, continuation.appContext.documentId) &&+ sameNullable(state.metadata?.scope, continuation.appContext.scope) &&+ sameNullable(state.metadata?.sessionId, continuation.appContext.sessionId) &&+ state.metadata?.sourceMessageId === continuation.parentMessageId &&+ stateProvenance?.resolutionRequestId === resolution.resolutionRequestId &&+ stateProvenance.sourceOperationId === continuation.operationId &&+ Array.isArray(stateProvenance.sourceToolMessageIds) &&+ stateProvenance.sourceToolMessageIds.every((id) => typeof id === 'string') &&+ sameStringSet(stateProvenance.sourceToolMessageIds as string[], sourceToolMessageIds);+ if (!stateContextMatches) return { state: 'conflict' };++ if (+ statePreparation?.state !== 'ready' ||+ statePreparation.resolutionRequestId !== resolution.resolutionRequestId ||+ statePreparation.stepIndex !== 0 ||+ statePreparation.deduplicationId !== expectedDeduplicationId+ ) {+ return !durablePreparation && state.status === 'idle'+ ? { retry: 'rebuild', state: 'prepared' }+ : { state: 'conflict' };+ }++ // Ready state without the durable provider-ACK marker is still preparation,+ // even if a fast worker already advanced it to running/terminal. Re-enqueue+ // with the same dedupe key to recover the ACK before topic repair/publish.+ return { retry: 'schedule', state: 'prepared' };+};++const retireRuntimeActionSourceOperation = async (+ runtimeAction: AgentInterventionRuntimeAction,+ ctx: AgentInterventionDispatchContext,+): Promise<void> => {+ switch (runtimeAction.type) {+ case 'execute_custom_interaction': {+ if (runtimeAction.input.action.type !== 'cancelled') {+ await ctx.aiAgentService.retirePendingApprovalOperation(runtimeAction.operationId);+ }+ return;+ }+ case 'resume_approval':+ case 'resume_tool_result': {+ await ctx.aiAgentService.retirePendingApprovalOperation(runtimeAction.operationId);+ return;+ }+ case 'heterogeneous_response':+ case 'stop': {+ return;+ }+ }+};++const repairRuntimeActionContinuationAnchor = async (+ resolution: ClaimedAgentInterventionResolution,+ ctx: AgentInterventionDispatchContext,+): Promise<void> => {+ const continuation = continuationRuntimeAction(resolution.runtimeAction);+ if (!continuation) return;+ const identity = {+ resolutionRequestId: resolution.resolutionRequestId,+ userId: resolution.ownerUserId,+ workspaceId: resolution.workspaceId ?? ctx.workspaceId,+ };+ await ctx.aiAgentService.repairInterventionContinuationTopicAnchor({+ assistantMessageId: deriveAgentInterventionContinuationMessageId(identity),+ continuationOperationId: deriveAgentInterventionContinuationOperationId(identity),+ resolutionRequestId: resolution.resolutionRequestId,+ scope: continuation.appContext.scope,+ sourceOperationId: continuation.operationId,+ sourceToolMessageIds:+ continuation.type === 'resume_approval'+ ? continuation.decisions.map(({ parentMessageId }) => parentMessageId)+ : [continuation.parentMessageId],+ threadId: continuation.appContext.threadId,+ topicId: continuation.appContext.topicId,+ });+};++/**+ * One dispatch boundary shared by token Review and the active Web source+ * bridge. Both paths arrive here only after Cloud has won the same durable+ * first-winner claim.+ */+const dispatchClaimedAgentIntervention = async (+ resolution: ClaimedAgentInterventionResolution,+ ctx: AgentInterventionDispatchContext,+): Promise<{ execution?: ExecAgentResult; status: AgentInterventionReviewStatus }> => {+ const { runtimeAction } = resolution;+ let execution: ExecAgentResult | undefined;+ let durableCustomSideEffect = false;+ const publishedStatus = publishedStatusForRuntimeAction(runtimeAction);+ const dispatchProbe = await probeRuntimeActionDispatch(resolution, ctx);+ const deterministicContinuationOperationId = continuationRuntimeAction(runtimeAction)+ ? deriveAgentInterventionContinuationOperationId({+ resolutionRequestId: resolution.resolutionRequestId,+ userId: resolution.ownerUserId,+ workspaceId: resolution.workspaceId ?? ctx.workspaceId,+ })+ : undefined;++ try {+ if (dispatchProbe.state === 'conflict') {+ throw new Error('Agent intervention continuation provenance conflict');+ }++ let shouldDispatchRuntimeAction =+ dispatchProbe.state === 'unclaimed' ||+ (dispatchProbe.state === 'prepared' && dispatchProbe.retry !== 'schedule');++ if (dispatchProbe.state === 'prepared' && dispatchProbe.retry === 'schedule') {+ const continuationOperationId = deriveAgentInterventionContinuationOperationId({+ resolutionRequestId: resolution.resolutionRequestId,+ userId: resolution.ownerUserId,+ workspaceId: resolution.workspaceId ?? ctx.workspaceId,+ });+ const start =+ await ctx.aiAgentService.ensureInterventionContinuationStarted(continuationOperationId);+ if (start === 'missing') {+ // The first probe observed a complete ready state. If it disappears+ // before the enqueue repair, rebuilding cannot distinguish a TTL from+ // a worker that already ran after a lost provider ACK. Keep the durable+ // claim and fail closed; a later retry must recover from authoritative+ // operation evidence rather than replaying the continuation.+ throw new Error(+ `Intervention continuation state disappeared during dispatch recovery: ${continuationOperationId}`,+ );+ }+ shouldDispatchRuntimeAction = false;+ }++ if (dispatchProbe.state !== 'dispatched' && shouldDispatchRuntimeAction) {+ switch (runtimeAction.type) {+ case 'execute_custom_interaction': {+ const customAction = runtimeAction.input.action;+ const customResult = await executeAgentMarketplaceIntervention({+ action: customAction,+ actorUserId: ctx.userId,+ categoryHints: runtimeAction.input.categoryHints,+ requestId: runtimeAction.input.requestId,+ resolutionRequestId: resolution.resolutionRequestId,+ topicId: runtimeAction.appContext.topicId,+ userId: resolution.ownerUserId,+ workspaceId: resolution.workspaceId ?? ctx.workspaceId ?? undefined,+ });+ durableCustomSideEffect = true;+ if (customAction.type === 'cancelled') {+ await ctx.aiAgentService.stopPendingApproval({+ approvalResolutionRequestId: resolution.resolutionRequestId,+ batchId: runtimeAction.batchId,+ operationId: runtimeAction.operationId,+ toolMessageIds: runtimeAction.toolMessageIds,+ topicId: runtimeAction.appContext.topicId,+ });+ } else {+ const skipped = customAction.type === 'skipped';+ execution = await ctx.aiAgentService.execAgent({+ agentId: runtimeAction.agentId,+ approvalResolutionRequestId: resolution.resolutionRequestId,+ approvalSourceOperationId: runtimeAction.operationId,+ appContext: runtimeAction.appContext,+ parentMessageId: runtimeAction.parentMessageId,+ prompt: '',+ replacesOperationId: runtimeAction.operationId,+ resume: true,+ taskId: runtimeAction.appContext.taskId ?? undefined,+ resumeToolResult: {+ content: customResult.content,+ outcome: skipped ? 'skipped' : 'submitted',+ parentMessageId: runtimeAction.parentMessageId,+ pluginState: customResult.pluginState,+ toolCallId: runtimeAction.toolCallId,+ },+ topicStartReservationId: deterministicContinuationOperationId,+ });+ }+ break;+ }+ case 'heterogeneous_response': {+ await createStreamEventManager().publishStreamEvent(runtimeAction.operationId, {+ data: runtimeAction.response,+ stepIndex: runtimeAction.stepIndex ?? 0,+ type: 'agent_intervention_response',+ });+ break;+ }+ case 'resume_approval': {+ const [singleDecision] = runtimeAction.decisions;+ execution = await ctx.aiAgentService.execAgent({+ agentId: runtimeAction.agentId,+ approvalResolutionRequestId: resolution.resolutionRequestId,+ approvalSourceOperationId: runtimeAction.operationId,+ appContext: runtimeAction.appContext,+ parentMessageId: runtimeAction.parentMessageId,+ prompt: '',+ replacesOperationId: runtimeAction.operationId,+ resume: true,+ taskId: runtimeAction.appContext.taskId ?? undefined,+ ...(runtimeAction.decisions.length === 1+ ? { resumeApproval: singleDecision }+ : { resumeApprovals: runtimeAction.decisions }),+ topicStartReservationId: deterministicContinuationOperationId,+ });+ break;+ }+ case 'resume_tool_result': {+ execution = await ctx.aiAgentService.execAgent({+ agentId: runtimeAction.agentId,+ approvalResolutionRequestId: resolution.resolutionRequestId,+ approvalSourceOperationId: runtimeAction.operationId,+ appContext: runtimeAction.appContext,+ parentMessageId: runtimeAction.parentMessageId,+ prompt: '',+ replacesOperationId: runtimeAction.operationId,+ resume: true,+ taskId: runtimeAction.appContext.taskId ?? undefined,+ resumeToolResult: {+ content: runtimeAction.content,+ outcome: runtimeAction.outcome,+ parentMessageId: runtimeAction.parentMessageId,+ pluginState: runtimeAction.pluginState,+ rejectionReason: runtimeAction.rejectionReason,+ toolCallId: runtimeAction.toolCallId,+ },+ topicStartReservationId: deterministicContinuationOperationId,+ });+ break;+ }+ case 'stop': {+ await ctx.aiAgentService.stopPendingApproval({+ approvalResolutionRequestId: resolution.resolutionRequestId,+ batchId: runtimeAction.batchId,+ operationId: runtimeAction.operationId,+ toolMessageIds: runtimeAction.toolMessageIds,+ topicId: runtimeAction.topicId,+ });+ break;+ }+ }+ }++ if (execution?.success === false || execution?.autoStarted === false) {+ throw new Error('Agent intervention continuation was not scheduled');+ }+ await repairRuntimeActionContinuationAnchor(resolution, ctx);+ await retireRuntimeActionSourceOperation(runtimeAction, ctx);+ } catch (error) {+ const retryProbe = await probeRuntimeActionDispatch(resolution, ctx);+ if (retryProbe.state === 'dispatched') {+ log(+ 'v2 intervention retry observed prior dispatch operation claim=%s request=%s',+ resolution.claimId,+ resolution.resolutionRequestId,+ );+ // The prior call may have scheduled the replacement operation and failed+ // while retiring its parked predecessor. Retry that lifecycle transition+ // under the same source identity; never roll back a generic claim after+ // the tool/result side effect is authoritatively visible.+ await repairRuntimeActionContinuationAnchor(resolution, ctx);+ await retireRuntimeActionSourceOperation(runtimeAction, ctx);+ } else if (retryProbe.state === 'unclaimed' && !durableCustomSideEffect) {+ await rollbackAgentInterventionResolution({+ actorUserId: ctx.userId,+ claimId: resolution.claimId,+ ownerUserId: resolution.ownerUserId,+ resolutionRequestId: resolution.resolutionRequestId,+ workspaceId: resolution.workspaceId ?? ctx.workspaceId ?? undefined,+ }).catch((rollbackError) => {+ log(+ 'conditional v2 intervention rollback failed claim=%s: %O',+ resolution.claimId,+ rollbackError,+ );+ });+ throw error;+ } else {+ // `prepared` means this exact request owns the source rows but has not+ // reached a provably started continuation yet. Keep the generic claim so+ // the same id can rebuild/requeue it; rolling back here would let a second+ // actor win against already-settled source messages. `conflict` is also+ // fail-closed and must never reopen the claim.+ throw error;+ }+ }++ // Runtime dispatch is authoritative. The durable published/completion+ // transition is part of the mutation's success boundary: swallowing a hook+ // failure would leave the row permanently resolving while telling clients+ // the action completed. Cloud makes this idempotent by request id.+ await onAgentInterventionResolutionPublished({+ actorUserId: ctx.userId,+ claimId: resolution.claimId,+ ownerUserId: resolution.ownerUserId,+ resolutionRequestId: resolution.resolutionRequestId,+ status: publishedStatus,+ workspaceId: resolution.workspaceId ?? ctx.workspaceId ?? undefined,+ });++ return { execution, status: publishedStatus };+};+const resolveHeteroTopicWorkspace = async (params: {db: LobeChatDatabase;requestedWorkspaceId?: string | null;@@ -374,6 +997,10 @@ const ExecAgentSchema = zparentMessageId: z.string(),/** Optional plugin state to persist on the tool message. */pluginState: z.record(z.string(), z.unknown()).optional(),+ /** Whether the form was submitted or explicitly skipped. */+ outcome: z.enum(['submitted', 'skipped']).optional().default('submitted'),+ /** Optional skip reason, persisted only when outcome is skipped. */+ rejectionReason: z.string().optional(),/** tool_call_id of the pending tool call being answered. */toolCallId: z.string(),})@@ -412,6 +1039,73 @@ const ExecAgentSchema = z}).refine((data) => data.agentId || data.slug, {message: 'Either agentId or slug must be provided',+ })+ .superRefine((data, ctx) => {+ const resumePayloadCount = [+ data.resumeApproval,+ data.resumeApprovals,+ data.resumeToolResult,+ ].filter(Boolean).length;+ if (resumePayloadCount > 1) {+ ctx.addIssue({+ code: 'custom',+ message: 'Only one of resumeApproval, resumeApprovals, or resumeToolResult is allowed',+ path: ['resumeApproval'],+ });+ }++ if (resumePayloadCount > 0 && !data.parentMessageId) {+ ctx.addIssue({+ code: 'custom',+ message: 'parentMessageId is required for an intervention resume',+ path: ['parentMessageId'],+ });+ }++ if (+ data.resumeApproval &&+ data.parentMessageId &&+ data.resumeApproval.parentMessageId !== data.parentMessageId+ ) {+ ctx.addIssue({+ code: 'custom',+ message: 'resumeApproval must target parentMessageId',+ path: ['resumeApproval', 'parentMessageId'],+ });+ }+ if (+ data.resumeToolResult &&+ data.parentMessageId &&+ data.resumeToolResult.parentMessageId !== data.parentMessageId+ ) {+ ctx.addIssue({+ code: 'custom',+ message: 'resumeToolResult must target parentMessageId',+ path: ['resumeToolResult', 'parentMessageId'],+ });+ }++ if (data.resumeApprovals) {+ const messageIds = data.resumeApprovals.map(({ parentMessageId }) => parentMessageId);+ const toolCallIds = data.resumeApprovals.map(({ toolCallId }) => toolCallId);+ if (+ new Set(messageIds).size !== messageIds.length ||+ new Set(toolCallIds).size !== toolCallIds.length+ ) {+ ctx.addIssue({+ code: 'custom',+ message: 'resumeApprovals cannot contain duplicate targets',+ path: ['resumeApprovals'],+ });+ }+ if (data.parentMessageId && !messageIds.includes(data.parentMessageId)) {+ ctx.addIssue({+ code: 'custom',+ message: 'parentMessageId must be one of the resumeApprovals targets',+ path: ['parentMessageId'],+ });+ }+ }});/**@@ -690,12 +1384,96 @@ const SubmitHeteroInterventionSchema = z.object({cancelReason: z.enum(['timeout', 'user_cancelled', 'session_ended']).optional(),cancelled: z.boolean().optional(),operationId: z.string().min(1),+ /** Optional only for backward compatibility with pre-contract Web clients. */+ resolutionRequestId: z.string().uuid().optional(),result: z.unknown().optional(),/** Producer step index; harmless placeholder — correlation is by toolCallId. */stepIndex: z.number().int().nonnegative().default(0),toolCallId: z.string().min(1),});+const HeteroInterventionReviewTokenSchema = z.object({+ /** 32 random bytes encoded as base64url without padding. */+ reviewToken: z.string().regex(/^[\w-]{43}$/),+});++const ResolveHeteroInterventionReviewSchema = z.object({+ action: z.enum(['submit', 'skip']),+ resolutionRequestId: z.string().uuid(),+ result: z.unknown().optional(),+ reviewToken: z.string().regex(/^[\w-]{43}$/),+});++const publishClaimedHeteroIntervention = async (params: {+ claim: Extract<+ Awaited<ReturnType<typeof resolveHeteroIntervention>>,+ { handled: true; state: 'claimed' }+ >;+ userId: string;+ workspaceId?: string | null;+}) => {+ const { claim, userId, workspaceId } = params;+ const resolvedWorkspaceId = claim.workspaceId ?? workspaceId ?? undefined;+ const streamEventManager = createStreamEventManager();++ try {+ await streamEventManager.publishStreamEvent(claim.operationId, {+ data: {+ ...claim.response,+ producerAck: false,+ resolutionRequestId: claim.resolutionRequestId,+ },+ stepIndex: claim.stepIndex ?? 0,+ type: 'agent_intervention_response',+ });+ } catch (error) {+ await rollbackHeteroInterventionResolution({+ claimId: claim.claimId,+ operationId: claim.operationId,+ resolutionRequestId: claim.resolutionRequestId,+ toolCallId: claim.response.toolCallId,+ userId,+ workspaceId: resolvedWorkspaceId,+ }).catch((rollbackError) => {+ log(+ 'conditional intervention rollback failed claim=%s op=%s: %O',+ claim.claimId,+ claim.operationId,+ rollbackError,+ );+ });+ throw error;+ }++ // Notification surfaces may switch to `resolving` only after XADD has+ // succeeded. This best-effort side effect must not roll back a response the+ // producer can already consume from the stream.+ await onHeteroInterventionResolutionPublished({+ claimId: claim.claimId,+ operationId: claim.operationId,+ resolutionRequestId: claim.resolutionRequestId,+ status: 'resolving',+ toolCallId: claim.response.toolCallId,+ userId,+ workspaceId: resolvedWorkspaceId,+ }).catch((notificationError) => {+ log(+ 'intervention published hook failed claim=%s op=%s: %O',+ claim.claimId,+ claim.operationId,+ notificationError,+ );+ });++ return {+ // XADD only acknowledges transport acceptance. The producer's echoed+ // response is the authoritative terminal transition persisted by the+ // intervention reducer; until then the durable row remains resolving.+ status: 'resolving' as const,+ success: true as const,+ };+};+const aiAgentBaseProcedure = wsCompatProcedure.use(serverDatabase);const aiAgentProcedure = aiAgentBaseProcedure.use(async (opts) => {@@ -1298,6 +2076,140 @@ export const aiAgentRouter = router({userId: ctx.userId,workspaceId: ctx.workspaceId,});++ // Cross-version bridge: older Web clients call execAgent directly with+ // resume payloads and know nothing about the v2 source endpoint. Recover+ // the authoritative operation/batch from the tool rows and claim the+ // same generic intervention before the legacy message CAS can run.+ const legacyResumeTargets = [+ ...(resumeApprovals ?? []),+ ...(resumeApproval ? [resumeApproval] : []),+ ...(resumeToolResult+ ? [+ {+ decision: 'approved' as const,+ parentMessageId: resumeToolResult.parentMessageId,+ toolCallId: resumeToolResult.toolCallId,+ },+ ]+ : []),+ ];+ if (legacyResumeTargets.length > 0) {+ const plugins = await Promise.all(+ legacyResumeTargets.map(({ parentMessageId }) =>+ ctx.messageModel.findMessagePlugin(parentMessageId),+ ),+ );+ const firstIntervention = plugins[0]?.intervention;+ const hasGenericSource = Boolean(+ firstIntervention?.operationId &&+ firstIntervention.batchId &&+ plugins.every(+ (plugin) =>+ plugin?.intervention?.operationId === firstIntervention.operationId &&+ plugin?.intervention?.batchId === firstIntervention.batchId,+ ),+ );++ if (hasGenericSource) {+ let sourceAction: AgentInterventionSourceAction | undefined;+ if (resumeToolResult) {+ if (resumeToolResult.outcome === 'skipped') {+ sourceAction = { type: 'skip_interaction' };+ } else {+ const pluginState = resumeToolResult.pluginState as+ | {+ askUserAnswers?: Record<string, unknown>;+ selectedAgentIds?: unknown;+ }+ | undefined;+ const answers = pluginState?.askUserAnswers;+ if (+ answers &&+ Object.keys(answers).length > 0 &&+ Object.values(answers).every(+ (answer) =>+ typeof answer === 'string' ||+ (Array.isArray(answer) && answer.every((item) => typeof item === 'string')),+ )+ ) {+ sourceAction = {+ result: answers as Record<string, string | string[]>,+ type: 'submit_answers',+ };+ } else if (+ plugins[0]?.identifier === 'lobe-web-onboarding' &&+ plugins[0]?.apiName === 'showAgentMarketplace' &&+ Array.isArray(pluginState?.selectedAgentIds) &&+ pluginState.selectedAgentIds.every((id) => typeof id === 'string')+ ) {+ sourceAction = {+ result: {+ kind: 'agent_marketplace',+ selectedTemplateIds: pluginState.selectedAgentIds as string[],+ },+ type: 'submit_custom',+ };+ }+ }+ } else if (legacyResumeTargets.every(({ decision }) => decision === 'approved')) {+ // The legacy resume envelope has neither staged edits nor remember+ // intent. Cloud therefore compares the durable revision with the+ // authoritative message arguments and rejects a pre-mutated old+ // edit as stale with a refresh-required conflict; it must never+ // reinterpret already-written client state as an atomic edit.+ // Old clients may also have changed their personal allow-list+ // before this call, which remains a rollout-only non-atomic edge.+ // Current Web sends both edits and remember through the source+ // endpoint before any side effect.+ sourceAction = { scope: 'once', type: 'approve_tool' };+ } else if (+ legacyResumeTargets.every(+ ({ decision }) => decision === 'rejected' || decision === 'rejected_continue',+ )+ ) {+ const reasons = [+ ...new Set(+ legacyResumeTargets+ .map(({ rejectionReason }) => rejectionReason)+ .filter((reason): reason is string => Boolean(reason)),+ ),+ ];+ sourceAction = {+ ...(reasons.length === 1 && { reason: reasons[0] }),+ type: 'reject_continue',+ };+ }++ if (!sourceAction) {+ throw new Error('Unsupported legacy intervention payload for a durable generic row');+ }++ const sourceResolution = await resolveAgentInterventionBySource({+ action: sourceAction,+ actorUserId: ctx.userId,+ batchId: firstIntervention!.batchId!,+ operationId: firstIntervention!.operationId!,+ resolutionRequestId: randomUUID(),+ targets: legacyResumeTargets.map(({ parentMessageId, toolCallId }) => ({+ toolCallId,+ toolMessageId: parentMessageId,+ })),+ workspaceId: ctx.workspaceId ?? undefined,+ });+ if (sourceResolution.handled) {+ if (sourceResolution.state === 'already_resolved') {+ throw new HumanApprovalAlreadyResolvedError(parentMessageId ?? 'intervention');+ }+ const dispatch = await dispatchClaimedAgentIntervention(sourceResolution, ctx);+ if (!dispatch.execution) {+ throw new Error('Durable intervention resume did not create an operation');+ }+ return dispatch.execution;+ }+ }+ }+return await ctx.aiAgentService.execAgent({agentId,appContext,@@ -1338,6 +2250,14 @@ export const aiAgentRouter = router({throw error;}+ if (error instanceof HumanApprovalAlreadyResolvedError) {+ throw new TRPCError({+ cause: error,+ code: 'CONFLICT',+ message: 'This approval has already been resolved.',+ });+ }+// A primary-key collision on a client-supplied id (a retried send// replaying the same `clientIds`) is client-correctable — surface it as// CONFLICT, not a 500. Generic message on purpose: echoing the id would@@ -1943,6 +2863,10 @@ export const aiAgentRouter = router({stopPendingApproval: aiAgentWriteProcedure.input(z.object({+ /** Stable sealed batch id stamped on every pending tool row. */+ batchId: z.string().min(1),+ /** Exact parked operation to stop; never inferred from topic recency. */+ operationId: z.string().min(1),/** Pending `role='tool'` message ids to settle — the active batch. */toolMessageIds: z.array(z.string()).min(1),topicId: z.string(),@@ -1959,7 +2883,47 @@ export const aiAgentRouter = router({workspaceId: ctx.workspaceId,});+ const stopPlugins = await Promise.all(+ input.toolMessageIds.map((id) => ctx.messageModel.findMessagePlugin(id)),+ );+ const hasGenericSource = stopPlugins.every(+ (plugin) =>+ Boolean(plugin?.toolCallId) &&+ plugin?.intervention?.operationId === input.operationId &&+ plugin.intervention.batchId === input.batchId,+ );+ if (hasGenericSource) {+ const sourceResolution = await resolveAgentInterventionBySource({+ action: { scope: 'operation', type: 'stop' },+ actorUserId: ctx.userId,+ batchId: input.batchId,+ operationId: input.operationId,+ resolutionRequestId: randomUUID(),+ targets: stopPlugins.map((plugin, index) => ({+ toolCallId: plugin!.toolCallId!,+ toolMessageId: input.toolMessageIds[index],+ })),+ workspaceId: ctx.workspaceId ?? undefined,+ });+ if (sourceResolution.handled) {+ if (sourceResolution.state === 'already_resolved') {+ throw new TRPCError({+ code: 'CONFLICT',+ message: 'This approval has already been resolved.',+ });+ }+ await dispatchClaimedAgentIntervention(sourceResolution, ctx);+ return {+ operationId: input.operationId,+ settledToolMessageIds: input.toolMessageIds,+ success: true,+ };+ }+ }+return ctx.aiAgentService.stopPendingApproval({+ batchId: input.batchId,+ operationId: input.operationId,toolMessageIds: input.toolMessageIds,topicId: input.topicId,});@@ -2147,6 +3111,191 @@ export const aiAgentRouter = router({};}),+ /**+ * Authenticated v2 review lookup. The opaque token is only a locator: the+ * business implementation must resolve the row, then evaluate view and+ * resolve access against the intervention's current conversation resource.+ * Keep the token in a POST body rather than a query URL retained by access+ * logs and browser history.+ */+ getAgentInterventionReview: aiAgentBaseProcedure+ .input(GetAgentInterventionReviewSchema)+ .mutation(({ input, ctx }) =>+ getAgentInterventionReview({+ reviewToken: input.reviewToken,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId ?? undefined,+ }),+ ),++ /**+ * Read-only counterpart to the active Web source resolver. Chat surfaces+ * fetch authoritative authorization before rendering controls, so a+ * view-only collaborator sees the request with actions disabled instead of+ * discovering the denial only after a mutation. Source ids remain locators;+ * Cloud applies the final resource ACL after resolving the durable row.+ */+ getAgentInterventionReviewBySource: aiAgentBaseProcedure+ .input(GetAgentInterventionReviewBySourceSchema)+ .mutation(async ({ input, ctx }) => {+ await assertCanViewMessageTargets(+ { db: ctx.serverDB, userId: ctx.userId, workspaceId: ctx.workspaceId },+ input.targets.map(({ toolMessageId }) => toolMessageId),+ );++ return getAgentInterventionReviewBySource({+ actorUserId: ctx.userId,+ batchId: input.batchId,+ operationId: input.operationId,+ targets: input.targets,+ workspaceId: ctx.workspaceId ?? undefined,+ });+ }),++ /**+ * Active Web approval bridge. Source ids only locate the durable runtime+ * rows; Cloud re-resolves their operation, sealed batch, membership,+ * revisions and conversation ACL before using the same atomic claim as+ * Review. OSS returns unavailable so its existing message-row path remains+ * the compatibility fallback.+ */+ resolveAgentInterventionBySource: aiAgentWriteProcedure+ .input(ResolveAgentInterventionBySourceSchema)+ .mutation(async ({ input, ctx }) => {+ await assertCanUseAgentRunConversation({+ db: ctx.serverDB,+ messageIds: input.targets.map(({ toolMessageId }) => toolMessageId),+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });++ const resolution = await resolveAgentInterventionBySource({+ action: input.action,+ actorUserId: ctx.userId,+ batchId: input.batchId,+ operationId: input.operationId,+ resolutionRequestId: input.resolutionRequestId,+ targets: input.targets,+ workspaceId: ctx.workspaceId ?? undefined,+ });++ if (!resolution.handled) {+ return {+ contractVersion: 2 as const,+ status: 'unavailable' as const,+ success: false as const,+ };+ }+ if (resolution.state === 'already_resolved') {+ return {+ contractVersion: 2 as const,+ ...(resolution.conversationUrl && { conversationUrl: resolution.conversationUrl }),+ state: resolution.state,+ status: resolution.status,+ success: true as const,+ };+ }++ const dispatch = await dispatchClaimedAgentIntervention(resolution, ctx);+ return {+ contractVersion: 2 as const,+ ...(resolution.conversationUrl && { conversationUrl: resolution.conversationUrl }),+ ...(dispatch.execution && { execution: dispatch.execution }),+ state: resolution.state,+ status: dispatch.status,+ success: true as const,+ };+ }),++ /**+ * Resolve one v2 review through the durable first-winner claim. The client+ * supplies only review/item ids plus revisions; the business slot derives+ * every runtime authority (operation, tool call, message, canonical tool+ * key) after ACL + batch membership checks.+ */+ resolveAgentIntervention: aiAgentWriteProcedure+ .input(ResolveAgentInterventionSchema)+ .mutation(async ({ input, ctx }) => {+ const resolution = await resolveAgentIntervention({+ action: input.action,+ expectedBatchVersion: input.expectedBatchVersion,+ expectedRequestRevisions: input.expectedRequestRevisions,+ resolutionRequestId: input.resolutionRequestId,+ reviewToken: input.reviewToken,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId ?? undefined,+ });++ if (!resolution.handled) {+ return {+ contractVersion: 2 as const,+ status: 'unavailable' as const,+ success: false as const,+ };+ }+ if (resolution.state === 'already_resolved') {+ return {+ contractVersion: 2 as const,+ conversationUrl: resolution.conversationUrl,+ status: resolution.status,+ success: true as const,+ };+ }++ const { status: publishedStatus } = await dispatchClaimedAgentIntervention(resolution, ctx);++ return {+ contractVersion: 2 as const,+ conversationUrl: resolution.conversationUrl,+ status: publishedStatus,+ success: true as const,+ };+ }),++ /**+ * Authenticated cold-start review lookup. The opaque token is the only+ * client-supplied locator; Cloud resolves operation/tool ownership inside+ * the business slot. Keep this read-only operation on the mutation transport+ * so the review token is carried in the POST body instead of a query URL that+ * infrastructure access logs commonly retain. OSS reports `unavailable`+ * without exposing internals.+ */+ getHeteroInterventionReview: aiAgentBaseProcedure+ .input(HeteroInterventionReviewTokenSchema)+ .mutation(({ input, ctx }) =>+ getHeteroInterventionReview({+ reviewToken: input.reviewToken,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId ?? undefined,+ }),+ ),++ /** Token-only atomic resolution path used by Mobile review/deep links. */+ resolveHeteroIntervention: aiAgentWriteProcedure+ .input(ResolveHeteroInterventionReviewSchema)+ .mutation(async ({ input, ctx }) => {+ const resolution = await resolveHeteroIntervention({+ action: input.action,+ cancelReason: input.action === 'skip' ? 'user_cancelled' : undefined,+ result: input.action === 'submit' ? input.result : undefined,+ resolutionRequestId: input.resolutionRequestId,+ target: { reviewToken: input.reviewToken },+ userId: ctx.userId,+ workspaceId: ctx.workspaceId ?? undefined,+ });++ if (!resolution.handled) return { status: 'unavailable' as const, success: false as const };+ if (resolution.state === 'already_resolved') {+ return { status: resolution.status, success: true as const };+ }++ return publishClaimedHeteroIntervention({+ claim: resolution,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ }),+/*** Browser leg of remote Human-in-the-loop (user auth). Publishes the user's* answer to an `agent_intervention_request` back onto the op's Redis stream@@ -2158,7 +3307,14 @@ export const aiAgentRouter = router({submitHeteroIntervention: aiAgentWriteProcedure.input(SubmitHeteroInterventionSchema).mutation(async ({ input, ctx }) => {- const { operationId, toolCallId, stepIndex, result, cancelled, cancelReason } = input;+ const {+ operationId,+ toolCallId,+ stepIndex,+ result,+ cancelled,+ resolutionRequestId = randomUUID(),+ } = input;log('submitHeteroIntervention: op=%s toolCallId=%s cancelled=%s',@@ -2174,19 +3330,47 @@ export const aiAgentRouter = router({workspaceId: ctx.workspaceId,});+ // Cloud overrides this as an atomic first-winner claim shared by Web and+ // Mobile. OSS returns `handled:false` and preserves the legacy stream+ // publish below. A claimed response is authoritative: client-supplied+ // operation/tool fields cannot override what Cloud resolved durably.+ const businessResolution = await resolveHeteroIntervention({+ action: cancelled ? 'skip' : 'submit',+ cancelReason: cancelled ? 'user_cancelled' : undefined,+ result: cancelled ? undefined : result,+ resolutionRequestId,+ target: { operationId, toolCallId },+ userId: ctx.userId,+ workspaceId: ctx.workspaceId ?? undefined,+ });+ if (businessResolution.handled) {+ if (businessResolution.state === 'already_resolved') {+ return { status: businessResolution.status, success: true as const };+ }+ return publishClaimedHeteroIntervention({+ claim: businessResolution,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ }+const streamEventManager = createStreamEventManager();await streamEventManager.publishStreamEvent(operationId, {data: {- cancelReason: cancelled ? (cancelReason ?? 'user_cancelled') : undefined,+ // Client-driven cancellation cannot impersonate producer timeout or+ // session teardown; those terminal reasons originate from bridge ACKs.+ cancelReason: cancelled ? 'user_cancelled' : undefined,cancelled,+ producerAck: false,result: cancelled ? undefined : result,+ resolutionRequestId,toolCallId,},stepIndex,type: 'agent_intervention_response',});- return { success: true as const };+ return { status: 'resolving' as const, success: true as const };}),processHumanIntervention: aiAgentWriteProcedurediff --git a/apps/server/src/routers/lambda/pushToken.ts b/apps/server/src/routers/lambda/pushToken.tsindex ac40b518090..ddb96faeb95 100644--- a/apps/server/src/routers/lambda/pushToken.ts+++ b/apps/server/src/routers/lambda/pushToken.ts@@ -1,7 +1,12 @@import { z } from 'zod';+import {+ registerAgentInterventionLiveActivity,+ registerLiveActivityPushToStartToken,+} from '@/business/server/notification/liveActivity';import {deletePushTokenByExpoTokenAndDevice,+ PushLiveActivityModel,PushTokenModel,} from '@/database/models/pushToken';import { authedProcedure, publicProcedure, router } from '@/libs/trpc/lambda';@@ -19,17 +24,52 @@ export const pushTokenRouter = router({register: authedPushTokenProcedure.input(z.object({+ apnsEnvironment: z.enum(['sandbox', 'production']).optional(),appVersion: z.string().optional(),deviceId: z.string().min(1),expoToken: z.string().min(1),+ liveActivityPushToStartToken: z.string().min(1).max(512).optional(),locale: z.string().optional(),platform: z.enum(['ios', 'android']),}),).mutation(async ({ ctx, input }) => {- return ctx.pushTokenModel.upsert(input);+ const { apnsEnvironment, liveActivityPushToStartToken, ...pushToken } = input;+ const row = await ctx.pushTokenModel.upsert(pushToken);++ if (apnsEnvironment && liveActivityPushToStartToken) {+ await registerLiveActivityPushToStartToken({+ apnsEnvironment,+ deviceId: input.deviceId,+ liveActivityPushToStartToken,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId ?? undefined,+ });+ }++ return row;}),+ /** Register/rotate one ActivityKit update token by durable intervention id. */+ registerLiveActivity: authedPushTokenProcedure+ .input(+ z.object({+ activityId: z.string().min(1).max(200),+ activityKey: z.string().min(1).max(200),+ apnsEnvironment: z.enum(['sandbox', 'production']),+ deviceId: z.string().min(1),+ operationId: z.string().min(1),+ pushToken: z.string().min(1).max(512),+ }),+ )+ .mutation(({ ctx, input }) =>+ registerAgentInterventionLiveActivity({+ ...input,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId ?? undefined,+ }),+ ),+/*** Public on purpose: clients call this during sign-out, and in the wild many* of those calls arrive after the session is already gone (expired OIDC@@ -71,7 +111,11 @@ export const pushTokenRouter = router({// Path B: legacy v1.0.7 + valid session — fall back to (userId, deviceId)if (ctx.userId) {const pushTokenModel = new PushTokenModel(ctx.serverDB, ctx.userId);- await pushTokenModel.unregister(deviceId);+ const liveActivityModel = new PushLiveActivityModel(ctx.serverDB, ctx.userId);+ await Promise.all([+ pushTokenModel.unregister(deviceId),+ liveActivityModel.unregisterDevice(deviceId),+ ]);return { success: true };}diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.tsindex 63dee1bbcc9..3d12892a3b5 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts@@ -46,6 +46,10 @@ import { isRecord } from '@lobechat/utils/object';import debug from 'debug';import urlJoin from 'url-join';+import {+ deriveAgentInterventionQueueDeduplicationId,+ matchesAgentInterventionContinuationProvenance,+} from '@/business/server/agent-run/agentInterventionIdentity';import { AgentOperationModel } from '@/database/models/agentOperation';import { MessageModel } from '@/database/models/message';import { type LobeChatDatabase } from '@/database/type';@@ -73,6 +77,7 @@ import { stateHasEntityFileEdits } from '@/server/services/workRegistration';import { isAbortError, throwIfAborted } from './abort';import {CompletionLifecycle,+ CriticalAgentInterventionPersistenceError,extractTextFromMessage,findLastAssistantMessage,isSuccessLikeCompletionReason,@@ -144,6 +149,12 @@ const STEP_ABORT_POLL_MAX_BACKOFF = 8;const STEP_LOCK_HEARTBEAT_MS = 30_000;const DURABLE_LEASE_HEARTBEAT_EVERY_TICKS = 3;const EVAL_TOOL_FORWARDING_HOOK_ID = 'eval-tool-forwarding';+const INTERVENTION_LIFECYCLE_CHECKPOINT_KEY = '_agentInterventionLifecycle';++interface InterventionLifecycleCheckpoint {+ state: 'completed' | 'pending';+ stepIndex: number;+}const toToolForwardingFailure = (error?: unknown): ToolRunResult => ({content: error === undefined ? 'Tool forwarding failed' : String(error),@@ -551,6 +562,178 @@ export class AgentRuntimeService {return true;}+ /** Load the authoritative runtime state for a deterministic intervention continuation. */+ async loadInterventionContinuationState(operationId: string): Promise<AgentState | null> {+ return this.coordinator.loadAgentState(operationId);+ }++ /**+ * Re-enqueue a continuation whose durable state was written but whose first+ * queue delivery may have been lost with the resolving HTTP process. The+ * operation id and step index are stable, so the ordinary distributed step+ * lock de-duplicates concurrent/repeated schedules.+ */+ async ensureInterventionContinuationStarted(+ operationId: string,+ ): Promise<'already_started' | 'missing' | 'scheduled'> {+ const state = await this.coordinator.loadAgentState(operationId);+ if (!state) return 'missing';++ const provenance = state.metadata?.agentInterventionContinuation as+ | {+ resolutionRequestId?: unknown;+ sourceOperationId?: unknown;+ sourceToolMessageIds?: unknown;+ }+ | undefined;+ const preparation = state.metadata?.agentInterventionPreparation as+ | {+ deduplicationId?: unknown;+ resolutionRequestId?: unknown;+ state?: unknown;+ stepIndex?: unknown;+ }+ | undefined;+ if (+ typeof provenance?.resolutionRequestId !== 'string' ||+ typeof provenance.sourceOperationId !== 'string' ||+ !Array.isArray(provenance.sourceToolMessageIds) ||+ !provenance.sourceToolMessageIds.every((id) => typeof id === 'string')+ ) {+ throw new Error(`Intervention continuation provenance missing: ${operationId}`);+ }+ if (+ preparation?.state !== 'ready' ||+ preparation.resolutionRequestId !== provenance.resolutionRequestId ||+ typeof preparation.stepIndex !== 'number' ||+ !Number.isSafeInteger(preparation.stepIndex) ||+ preparation.stepIndex < 0+ ) {+ throw new Error(`Intervention continuation is not ready to schedule: ${operationId}`);+ }+ const stepIndex = preparation.stepIndex;+ const deduplicationId = deriveAgentInterventionQueueDeduplicationId(operationId, stepIndex);+ if (preparation.deduplicationId !== deduplicationId) {+ throw new Error(`Intervention continuation dedupe provenance conflict: ${operationId}`);+ }+ const operation = await this.agentOperationModel.findById(operationId);+ if (+ !operation ||+ !matchesAgentInterventionContinuationProvenance(+ operation.metadata?.agentInterventionContinuation,+ provenance as {+ resolutionRequestId: string;+ sourceOperationId: string;+ sourceToolMessageIds: string[];+ },+ )+ ) {+ throw new Error(`Intervention continuation durable provenance conflict: ${operationId}`);+ }+ const durablePreparation = operation.metadata?.agentInterventionPreparation as+ | {+ deduplicationId?: unknown;+ resolutionRequestId?: unknown;+ state?: unknown;+ stepIndex?: unknown;+ }+ | undefined;+ if (+ durablePreparation &&+ (durablePreparation.state !== 'ready' ||+ durablePreparation.resolutionRequestId !== provenance.resolutionRequestId ||+ durablePreparation.stepIndex !== stepIndex ||+ durablePreparation.deduplicationId !== deduplicationId)+ ) {+ throw new Error(`Intervention continuation durable preparation conflict: ${operationId}`);+ }+ if (!durablePreparation) {+ const persisted = await this.agentOperationModel.recordAgentInterventionPreparation(+ operationId,+ {+ deduplicationId,+ resolutionRequestId: provenance.resolutionRequestId,+ state: 'ready',+ stepIndex,+ },+ );+ if (!persisted) {+ throw new Error(`Failed to backfill intervention preparation: ${operationId}`);+ }+ }+ const dispatchMarker = operation.metadata?.agentInterventionDispatch as+ | {+ deduplicationId?: unknown;+ messageId?: unknown;+ resolutionRequestId?: unknown;+ state?: unknown;+ }+ | undefined;+ if (dispatchMarker) {+ if (+ dispatchMarker.state !== 'scheduled' ||+ dispatchMarker.resolutionRequestId !== provenance.resolutionRequestId ||+ dispatchMarker.deduplicationId !== deduplicationId+ ) {+ throw new Error(`Intervention continuation dispatch marker conflict: ${operationId}`);+ }+ return 'already_started';+ }+ if (!this.queueService) {+ throw new Error(`Cannot schedule intervention continuation ${operationId}`);+ }++ // Missing provider ACK is never inferred from `state.status`: a worker may+ // have raced the HTTP response and advanced this state to running/terminal.+ // Re-publish with the same provider dedupe key to recover the ACK without a+ // second actual delivery, then persist the authoritative dispatch marker.+ const messageId = await this.queueService.scheduleMessage({+ context: (state as AgentState & { initialContext: AgentRuntimeContext }).initialContext,+ deduplicationId,+ delay: 0,+ endpoint: `${this.baseURL}/run`,+ operationId,+ priority: 'high',+ retryDelay:+ typeof state.metadata?.queueRetryDelay === 'string'+ ? state.metadata.queueRetryDelay+ : undefined,+ retries:+ typeof state.metadata?.queueRetries === 'number' ? state.metadata.queueRetries : undefined,+ stepIndex,+ });+ await this.persistInterventionDispatchAck({+ deduplicationId,+ messageId,+ operationId,+ resolutionRequestId: provenance.resolutionRequestId,+ });++ return 'scheduled';+ }++ private async persistInterventionDispatchAck(params: {+ deduplicationId: string;+ messageId: string;+ operationId: string;+ resolutionRequestId: string;+ }): Promise<void> {+ const marker = {+ deduplicationId: params.deduplicationId,+ messageId: params.messageId,+ resolutionRequestId: params.resolutionRequestId,+ scheduledAt: new Date().toISOString(),+ state: 'scheduled' as const,+ };+ const persisted = await this.agentOperationModel.recordAgentInterventionDispatch(+ params.operationId,+ marker,+ );+ if (!persisted) {+ throw new Error(`Failed to persist intervention queue ACK: ${params.operationId}`);+ }+ }+// ==================== Operation Management ====================/**@@ -569,6 +752,8 @@ export class AgentRuntimeService {autoStart = true,stream,initialMessages = [],+ interventionResolution,+ onInterventionPrepared,appContext,toolSet,hooks,@@ -600,13 +785,14 @@ 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.- await this.completionLifecycle.recordStart({+ const operationStartPersisted = await this.completionLifecycle.recordStart({agentId: appContext?.agentId ?? null,appContext: {defaultTaskAssigneeAgentId: appContext?.defaultTaskAssigneeAgentId,documentId: appContext?.documentId,groupId: appContext?.groupId,scope: appContext?.scope,+ sessionId: appContext?.sessionId,sourceMessageId: appContext?.sourceMessageId,},chatGroupId: appContext?.groupId ?? null,@@ -614,7 +800,16 @@ export class AgentRuntimeService {// Persist the Agent Signal run marker on the operation row so server-side// self-iteration tools can read it back (metadata.agentSignal) at tool-call// time — the trimmed appContext above intentionally drops it.- ...(appContext?.agentSignal ? { metadata: { agentSignal: appContext.agentSignal } } : {}),+ ...(appContext?.agentSignal || interventionResolution+ ? {+ metadata: {+ ...(appContext?.agentSignal ? { agentSignal: appContext.agentSignal } : {}),+ ...(interventionResolution+ ? { agentInterventionContinuation: interventionResolution }+ : {}),+ },+ }+ : {}),model: modelRuntimeConfig?.model,modelRuntimeConfig,operationId,@@ -625,6 +820,22 @@ export class AgentRuntimeService {topicId: appContext?.topicId ?? null,trigger: appContext?.trigger,});+ if (interventionResolution && !operationStartPersisted) {+ throw new Error(+ `Failed to durably persist intervention continuation ${operationId} before dispatch`,+ );+ }++ if (interventionResolution) {+ const durableOperation = await this.agentOperationModel.findById(operationId);+ const persistedProvenance = durableOperation?.metadata?.agentInterventionContinuation;+ if (+ !durableOperation ||+ !matchesAgentInterventionContinuationProvenance(persistedProvenance, interventionResolution)+ ) {+ throw new Error(`Intervention continuation operation identity conflict: ${operationId}`);+ }+ }const operationToolSet = toolSet;let operationCreated = false;@@ -685,6 +896,9 @@ export class AgentRuntimeService {evalContext,evalRuntime,executionPlan,+ ...(interventionResolution+ ? { agentInterventionContinuation: interventionResolution }+ : {}),// need be removedmodelRuntimeConfig,queueRetries,@@ -755,17 +969,55 @@ export class AgentRuntimeService {}}+ if (interventionResolution) {+ const preparedState = await this.coordinator.loadAgentState(operationId);+ if (!preparedState) {+ throw new Error(`Intervention continuation state disappeared: ${operationId}`);+ }+ const preparation = {+ deduplicationId: deriveAgentInterventionQueueDeduplicationId(+ operationId,+ initialStepCount,+ ),+ resolutionRequestId: interventionResolution.resolutionRequestId,+ state: 'ready' as const,+ stepIndex: initialStepCount,+ };+ await this.coordinator.saveAgentState(operationId, {+ ...preparedState,+ metadata: {+ ...preparedState.metadata,+ agentInterventionPreparation: preparation,+ },+ });+ const preparationPersisted =+ await this.agentOperationModel.recordAgentInterventionPreparation(+ operationId,+ preparation,+ );+ if (!preparationPersisted) {+ throw new Error(+ `Failed to persist intervention continuation preparation: ${operationId}`,+ );+ }+ onInterventionPrepared?.();+ }+throwIfAborted(signal, 'Agent execution aborted before first step scheduling');let messageId: string | undefined;let autoStarted = false;if (autoStart && this.queueService) {+ const deduplicationId = interventionResolution+ ? deriveAgentInterventionQueueDeduplicationId(operationId, initialStepCount)+ : undefined;// Both local and queue modes use scheduleMessage// LocalQueueServiceImpl uses setTimeout + callback mechanism// QStashQueueServiceImpl schedules HTTP requestsmessageId = await this.queueService.scheduleMessage({context: initialContext,+ deduplicationId,delay: 50, // Short delay for startupendpoint: `${this.baseURL}/run`,operationId,@@ -774,6 +1026,14 @@ export class AgentRuntimeService {retries: queueRetries,stepIndex: initialStepCount,});+ if (interventionResolution && deduplicationId) {+ await this.persistInterventionDispatchAck({+ deduplicationId,+ messageId,+ operationId,+ resolutionRequestId: interventionResolution.resolutionRequestId,+ });+ }autoStarted = true;log('[%s] Scheduled first step (messageId: %s)', operationId, messageId);}@@ -964,6 +1224,26 @@ export class AgentRuntimeService {const currentStepCount = currentState?.stepCount;if (currentState && typeof currentStepCount === 'number' && currentStepCount > stepIndex) {+ if (+ this.shouldReplayPendingInterventionLifecycle(currentState, stepIndex, externalRetryCount)+ ) {+ // This is a retry of a completed human-approval step whose Review+ // lifecycle did not finish. Do not ACK it while another delivery still+ // owns the step lock: once that owner releases the lock, QStash must+ // redeliver so the lifecycle-only replay below can publish the Review.+ log(+ '[%s][%d] Pending intervention lifecycle retry is still locked; requesting redelivery',+ operationId,+ stepIndex,+ );+ return {+ locked: true,+ nextStepScheduled: false,+ state: currentState,+ success: false,+ };+ }+log('[%s][%d] Step lock conflict is stale (stepCount=%d), skipping',operationId,@@ -1114,6 +1394,45 @@ export class AgentRuntimeService {throw new Error(`Agent state not found for operation ${operationId}`);}+ // A parked approval step is already durable before its generic Review+ // is published. When that final Review write fails, the request returns+ // non-2xx and QStash retries this SAME step with `upstash-retried > 0`.+ // The runtime state now has stepCount > stepIndex, so the ordinary stale+ // delivery guard below would ACK it and permanently strand the Review.+ // Replay only the idempotent completion lifecycle: never run beforeStep,+ // runtime.step (LLM/tools), afterStep, or saveStepResult again.+ if (+ agentState.stepCount > stepIndex &&+ this.shouldReplayPendingInterventionLifecycle(agentState, stepIndex, externalRetryCount)+ ) {+ agentState.metadata = {+ ...agentState.metadata,+ externalRetryCount,+ };++ const reason = 'waiting_for_human' as const;+ const completionSignalEvents = await this.completionLifecycle.emitSignalEvents(+ operationId,+ agentState,+ reason,+ );+ await this.completionLifecycle.dispatchHooks(operationId, agentState, reason);+ await this.recordInterventionLifecycleCompletion(operationId, agentState, stepIndex);+ await this.traceRecorder.finalize(operationId, {+ appendEventsToLastStep: completionSignalEvents,+ completionReason: reason,+ state: agentState,+ });++ log('[%s][%d] Replayed pending intervention lifecycle', operationId, stepIndex);+ return {+ nextStepScheduled: false,+ state: agentState,+ stepResult: null,+ success: true,+ };+ }+const stepStartUiMessages = await this.queryUiMessages(agentState, { skipWorks: true });await this.streamManager.publishStreamEvent(operationId, {data: {@@ -1476,13 +1795,21 @@ export class AgentRuntimeService {// dispatchHooks backstop below no-ops via the state marker.if (!shouldContinue) {const preSaveReason = this.determineCompletionReason(stepResult.newState);+ if (preSaveReason === 'waiting_for_human') {+ stepResult.newState.metadata = {+ ...stepResult.newState.metadata,+ [INTERVENTION_LIFECYCLE_CHECKPOINT_KEY]: {+ state: 'pending',+ stepIndex,+ } satisfies InterventionLifecycleCheckpoint,+ };+ }+// Success-like reasons ONLY — a `waiting_for_human` park must NOT- // register: the approval resume continues the SAME operationId- // (`processHumanIntervention` reschedules it), so pre-park edits are- // covered by the real terminal completion's scan. Registering at the- // park would persist the `_fileWorksRegistered` marker into the park- // snapshot (skipping the terminal registration entirely) and freeze- // per-(op, file) versions at pre-approval content.+ // register because it is not a completed deliverable boundary. The+ // fresh approval continuation sees the complete authoritative+ // history and performs the terminal scan after the decision runs;+ // registering here would freeze pre-approval content too early.if (isSuccessLikeCompletionReason(preSaveReason)) {await this.completionLifecycle.registerFileWorks(operationId, stepResult.newState);logToolCallPc(operationId, stepIndex, 'post.file_works_registered', () => ({}));@@ -1716,6 +2043,14 @@ export class AgentRuntimeService {await this.completionLifecycle.dispatchHooks(operationId, stepResult.newState, reason);logToolCallPc(operationId, stepIndex, 'post.completion_hooks', () => ({ reason }));+ if (reason === 'waiting_for_human') {+ await this.recordInterventionLifecycleCompletion(+ operationId,+ stepResult.newState,+ stepIndex,+ );+ }+// Park-time self-check: sub-agents are dispatched mid-step, so a// fast child can complete BEFORE this op's parked state/row were// persisted — its resume attempt then no-ops against the status@@ -1772,16 +2107,37 @@ export class AgentRuntimeService {};});} catch (error) {+ const isInterventionPersistenceFailure =+ error instanceof CriticalAgentInterventionPersistenceError;invokeAgentSpan.recordException(error as Error);invokeAgentSpan.setStatus({code: SpanStatusCode.ERROR,message: error instanceof Error ? error.message : String(error),});invokeAgentSpan.setAttributes(- buildInvokeAgentResultAttributes({ completionReason: 'error' }),+ buildInvokeAgentResultAttributes({+ completionReason: isInterventionPersistenceFailure ? 'waiting_for_human' : 'error',+ }),);log('Step %d failed for operation %s: %O', stepIndex, operationId, error);++ // The runtime step and its waiting_for_human state are already durable;+ // only the idempotent generic Review publication failed. Turning this+ // infrastructure failure into an agent error would overwrite the parked+ // state/operation row and make the QStash redelivery terminal-short-circuit.+ // Preserve the parked state and propagate non-2xx so the completed-step+ // lifecycle replay above can retry Review persistence without repeating+ // any LLM or tool side effects.+ if (isInterventionPersistenceFailure) {+ log(+ '[%s][%d] Intervention Review persistence failed; keeping operation parked for retry',+ operationId,+ stepIndex,+ );+ throw error;+ }+const formattedError = formatErrorForState(error);// Build error state — try loading current state from coordinator, but if that@@ -3223,6 +3579,68 @@ export class AgentRuntimeService {return true;}+ /**+ * Identify a provider redelivery that must replay a completed approval+ * lifecycle instead of being acknowledged as an ordinary stale step.+ *+ * `pendingApprovalBatch` is the durable, sealed runtime marker written before+ * Review publication. The QStash retry header distinguishes a failed request+ * redelivery from a benign duplicate that arrived after a successful ACK.+ */+ private shouldReplayPendingInterventionLifecycle(+ state: AgentState,+ stepIndex: number,+ externalRetryCount: number,+ ): boolean {+ const checkpoint = state.metadata?.[INTERVENTION_LIFECYCLE_CHECKPOINT_KEY] as+ InterventionLifecycleCheckpoint | undefined;++ return (+ externalRetryCount > 0 &&+ state.status === 'waiting_for_human' &&+ state.pendingApprovalBatch?.sealed === true &&+ // A missing checkpoint is a rollout-compatible pending state. Once a+ // successful lifecycle writes `completed`, a lost HTTP response can be+ // ACKed without publishing the Review or onComplete hook a second time.+ (!checkpoint || (checkpoint.stepIndex === stepIndex && checkpoint.state === 'pending'))+ );+ }++ /**+ * Checkpoint a fully delivered Review + onComplete lifecycle before the step+ * request returns. This closes the common response-loss window: QStash may+ * redeliver, but the stale-step guard can ACK a completed checkpoint without+ * duplicating either side effect. The Review itself remains batch-idempotent+ * for the smaller crash window before this checkpoint is saved.+ */+ private async recordInterventionLifecycleCompletion(+ operationId: string,+ state: AgentState,+ stepIndex: number,+ ): Promise<void> {+ state.metadata = {+ ...state.metadata,+ [INTERVENTION_LIFECYCLE_CHECKPOINT_KEY]: {+ state: 'completed',+ stepIndex,+ } satisfies InterventionLifecycleCheckpoint,+ };++ try {+ await this.coordinator.saveAgentState(operationId, state);+ } catch (error) {+ // The Review and hook are already delivered. Do not turn a best-effort+ // dedup checkpoint failure into an agent error; a rare later redelivery+ // safely retries the batch-idempotent Review and at-least-once hook.+ log(+ '[%s][%d] Failed to save intervention lifecycle checkpoint: %O',+ operationId,+ stepIndex,+ error,+ );+ }+ }+/*** Calculate step delay*/diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle.tsindex d4bda3f8e93..c5c991ae783 100644--- a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts@@ -3,6 +3,7 @@ import { deserializeParts } from '@lobechat/utils';import { isRecord } from '@lobechat/utils/object';import debug from 'debug';+import { notifyAgentInterventionRequired } from '@/business/server/agent-run/agentInterventionReview';import { notifyAgentRunCompleted } from '@/business/server/agent-run/notifyAgentRunCompleted';import {AgentOperationModel,@@ -22,6 +23,7 @@ import { instantiateVerifyPlanOnStart, runVerifyOnCompletion } from '@/server/seimport { registerWorksForOperation } from '@/server/services/workRegistration';import { after } from '@/server/utils/scheduleAfterResponse';+import { buildRuntimeInterventionNotification } from './agentInterventionNotification';import { CriticalHookDeliveryError, hookDispatcher, type SerializedHook } from './hooks';const log = debug('lobe-server:completion-lifecycle');@@ -37,6 +39,18 @@ const log = debug('lobe-server:completion-lifecycle');export const isSuccessLikeCompletionReason = (reason: string): boolean =>reason === 'done' || reason === 'max_steps' || reason === 'cost_limit';+/**+ * A parked human-approval run is not safely published until its generic Review+ * batch is durable. Unlike ordinary notification fanout, this error must reach+ * the queue/request boundary so the idempotent lifecycle delivery can retry.+ */+export class CriticalAgentInterventionPersistenceError extends Error {+ constructor(operationId: string, cause: unknown) {+ super(`Failed to persist intervention Review for parked operation ${operationId}`, { cause });+ this.name = 'CriticalAgentInterventionPersistenceError';+ }+}+type SignalEvent = { [key: string]: unknown; type: string };/**@@ -177,6 +191,64 @@ export class CompletionLifecycle {return persisted;}+ /**+ * Publish a provider-neutral Review snapshot only after every referenced tool+ * row can be read back as a member of this exact sealed parked batch. The+ * business slot is idempotent by batch id; repeated lifecycle delivery is+ * therefore safe, while a partial/mismatched write fails closed.+ */+ private async notifyPendingAgentIntervention(operationId: string, state: any): Promise<void> {+ try {+ const notification = await buildRuntimeInterventionNotification({+ operationId,+ state,+ userId: state?.metadata?.userId || this.userId,+ workspaceId: this.workspaceId,+ });+ if (!notification) return;++ const persistedRows = await Promise.all(+ notification.items.map(async (item, itemIndex) => {+ if (item.sourceRef.type !== 'runtime') return;+ const [message, plugin] = await Promise.all([+ this.messageModel.findById(item.sourceRef.toolMessageId),+ this.messageModel.findMessagePlugin(item.sourceRef.toolMessageId),+ ]);+ if (+ !message ||+ message.role !== 'tool' ||+ message.parentId !== notification.context.assistantMessageId ||+ message.topicId !== notification.context.topicId ||+ !plugin ||+ plugin.toolCallId !== item.sourceRef.toolCallId ||+ plugin.intervention?.status !== 'pending' ||+ plugin.intervention.operationId !== operationId ||+ plugin.intervention.batchId !== notification.batch.id ||+ plugin.intervention.stepIndex !== notification.batch.stepIndex ||+ plugin.intervention.itemIndex !== itemIndex+ ) {+ return;+ }+ return true;+ }),+ );++ if (persistedRows.some((persisted) => persisted !== true)) {+ throw new Error(+ 'Cannot create intervention Review because the sealed pending batch is not durable',+ );+ }++ // Contract boundary: Cloud resolves only after the generic batch is+ // durable. Push/Live Activity fanout failures are handled inside the+ // Cloud override and must not reject this call after persistence.+ await notifyAgentInterventionRequired(notification);+ } catch (error) {+ if (error instanceof CriticalAgentInterventionPersistenceError) throw error;+ throw new CriticalAgentInterventionPersistenceError(operationId, error);+ }+ }+/*** Map a completion reason to the terminal `agent_operations.status` value.* `waiting_for_human` / `waiting_for_async_tool` keep their own status so@@ -627,7 +699,8 @@ export class CompletionLifecycle {* Dispatch `onComplete` (and `onError` for `reason='error'`) hooks via* the global `hookDispatcher`. On the error path, also writes the error* back onto the assistant message row so the frontend can render it.- * Fire-and-forget; always unregisters the operation from the dispatcher.+ * Fire-and-forget; unregisters the operation after a settled lifecycle while+ * preserving registrations across retryable critical delivery failures.*/async dispatchHooks(operationId: string,@@ -639,11 +712,13 @@ export class CompletionLifecycle {// status (the async-tool resume CAS reads it) but must NOT fire `onComplete`// or unregister hooks — the op resumes under this same id and reaches its// real terminal state later, which is when consumers should be notified.- // (`waiting_for_human` also resumes under the same operationId, but its- // park DOES fire `onComplete` — hook consumers surface the approval request- // as the run's outcome; the final completion re-dispatches with the- // serialized hooks carried on `metadata._hooks`.)+ // `waiting_for_human` is different: the parked segment fires `onComplete`+ // so hook consumers can surface the approval request. A winning decision+ // schedules a fresh continuation operation and then retires this parked+ // segment; the continuation receives the serialized hooks through+ // `metadata._hooks`.const isAsyncToolPark = reason === 'waiting_for_async_tool';+ let shouldRetainHooksForRetry = false;try {const { assistantMessageId, event, metadata } = this.buildLifecycleEvent(@@ -660,6 +735,13 @@ export class CompletionLifecycle {return;}+ // At this point the parked operation state has been durably projected to+ // agent_operations. Verify the tool rows independently before creating a+ // durable Review so a partial batch can never reach notification UI.+ if (reason === 'waiting_for_human') {+ await this.notifyPendingAgentIntervention(operationId, state);+ }+if (isAsyncToolPark) return;// `lastAssistantContent` comes off the Redis-backed `state.messages`,@@ -767,12 +849,11 @@ export class CompletionLifecycle {// reasons, not `done` alone: a run stopped by a step/cost cap still// produced its edits and persists as status='done'.//- // `waiting_for_human` deliberately does NOT register: the approval resume- // continues the SAME operationId (`processHumanIntervention` reschedules- // it), so pre-park edits are covered by the real terminal completion's- // scan. Registering at the park would persist `_fileWorksRegistered` into- // the park snapshot — skipping the terminal registration entirely — and- // freeze per-(op, file) versions at pre-approval content.+ // `waiting_for_human` deliberately does NOT register: the park is not a+ // successful deliverable boundary. The fresh approval continuation is+ // built from the complete authoritative history and performs the real+ // terminal scan. Registering here would freeze pre-approval file content+ // as a completed Work before the user decision has run.if (isSuccessLikeCompletionReason(reason)) {await this.registerFileWorks(operationId, state);}@@ -808,12 +889,22 @@ export class CompletionLifecycle {}}} catch (error) {- if (error instanceof CriticalHookDeliveryError) throw error;+ if (+ error instanceof CriticalHookDeliveryError ||+ error instanceof CriticalAgentInterventionPersistenceError+ ) {+ // A queue retry may run in this same process (local callback / warm+ // worker). Keep the in-memory registration until that lifecycle really+ // settles; queue mode can additionally reconstruct from metadata._hooks.+ shouldRetainHooksForRetry = true;+ throw error;+ }log('[%s] Hook dispatch error (non-fatal): %O', operationId, error);} finally {// Keep hooks registered across an async-tool park so the eventual resume- // (same operationId) can still fire onComplete/onError.- if (!isAsyncToolPark) {+ // (same operationId) can still fire onComplete/onError. Critical delivery+ // failures likewise keep them until the provider redelivery settles.+ if (!isAsyncToolPark && !shouldRetainHooksForRetry) {hookDispatcher.unregister(operationId);// The instantiation has settled (awaited above) or this op never opted in// — drop the entry so the map doesn't grow across the service's lifetime.diff --git a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.tsindex 4c1210e3c38..75e3161548c 100644--- a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts@@ -3,25 +3,46 @@ import { type Message, parse } from '@lobechat/conversation-flow';import { ChatErrorType } from '@lobechat/types';import { afterEach, describe, expect, it, vi } from 'vitest';+import type { NotifyAgentInterventionRequiredParams } from '@/business/server/agent-run/agentInterventionReview';import * as agentSignalService from '@/server/services/agentSignal';import * as verifyServices from '@/server/services/verify';import { registerWorksForOperation } from '@/server/services/workRegistration';-import { CompletionLifecycle, isSuccessLikeCompletionReason } from '../CompletionLifecycle';+import {+ CompletionLifecycle,+ CriticalAgentInterventionPersistenceError,+ isSuccessLikeCompletionReason,+} from '../CompletionLifecycle';import { CriticalHookDeliveryError, hookDispatcher } from '../hooks';// Default async no-op implementation: the production code chains `.catch` on// the returned promise, so a bare vi.fn() (returning undefined) would throw// inside every unrelated `done`-path test. mockRestore/mockReset fall back to// this original implementation.-const { mockNotifyAgentRunCompleted } = vi.hoisted(() => ({+const {+ mockBuildRuntimeInterventionNotification,+ mockNotifyAgentInterventionRequired,+ mockNotifyAgentRunCompleted,+} = vi.hoisted(() => ({+ mockBuildRuntimeInterventionNotification: vi.fn<+ () => Promise<NotifyAgentInterventionRequiredParams | undefined>+ >(async () => undefined),+ mockNotifyAgentInterventionRequired: vi.fn(async () => {}),mockNotifyAgentRunCompleted: vi.fn(async () => {}),}));+vi.mock('@/business/server/agent-run/agentInterventionReview', () => ({+ notifyAgentInterventionRequired: mockNotifyAgentInterventionRequired,+}));+vi.mock('@/business/server/agent-run/notifyAgentRunCompleted', () => ({notifyAgentRunCompleted: mockNotifyAgentRunCompleted,}));+vi.mock('../agentInterventionNotification', () => ({+ buildRuntimeInterventionNotification: mockBuildRuntimeInterventionNotification,+}));+vi.mock('@/server/services/workRegistration', () => ({registerWorksForOperation: vi.fn(),}));@@ -814,15 +835,220 @@ describe('CompletionLifecycle.dispatchHooks — completion notification', () =>describe('CompletionLifecycle.dispatchHooks — parks do not register file works', () => {afterEach(() => {vi.restoreAllMocks();+ mockBuildRuntimeInterventionNotification.mockReset();+ mockBuildRuntimeInterventionNotification.mockResolvedValue(undefined);+ mockNotifyAgentInterventionRequired.mockReset();+ mockNotifyAgentInterventionRequired.mockResolvedValue(undefined);+ });++ const pendingNotification: NotifyAgentInterventionRequiredParams = {+ approvalMode: 'manual' as const,+ batch: {+ activityKey: '4369e854-719f-5301-bfa4-1f0742eec6ac',+ allowedActions: ['approve_tool', 'reject_continue', 'stop'],+ id: 'batch-1',+ kind: 'single' as const,+ sealed: true as const,+ stepIndex: 3,+ },+ context: {+ assistantMessageId: 'assistant-1',+ operationId: 'op-1',+ topicId: 'topic-1',+ },+ items: [+ {+ allowedActions: ['approve_tool', 'reject_continue', 'stop'],+ interactionKind: 'tool_approval' as const,+ requestRevision: { hash: 'a'.repeat(64), version: 0 },+ sourceRef: {+ toolCallId: 'call-1',+ toolMessageId: 'tool-1',+ type: 'runtime' as const,+ },+ summary: 'Run command',+ surface: 'binary' as const,+ },+ ],+ summary: 'Approval required',+ systemActionEligibility: 'safe_single_binary' as const,+ userId: 'user-1',+ };++ const stubDurablePendingRows = (lifecycle: CompletionLifecycle) => {+ (lifecycle as any).messageModel = {+ findById: vi.fn().mockResolvedValue({+ id: 'tool-1',+ parentId: 'assistant-1',+ role: 'tool',+ topicId: 'topic-1',+ }),+ findMessagePlugin: vi.fn().mockResolvedValue({+ intervention: {+ batchId: 'batch-1',+ itemIndex: 0,+ operationId: 'op-1',+ status: 'pending',+ stepIndex: 3,+ },+ toolCallId: 'call-1',+ }),+ };+ };++ it('publishes Review only after operation and every sealed batch row are durable', async () => {+ const lifecycle = buildLifecycle();+ const order: string[] = [];+ vi.spyOn(lifecycle as any, 'persistCompletion').mockImplementation(async () => {+ order.push('persist-operation');+ return true;+ });+ mockBuildRuntimeInterventionNotification.mockResolvedValue(pendingNotification);+ mockNotifyAgentInterventionRequired.mockImplementation(async () => {+ order.push('notify');+ });+ (lifecycle as any).messageModel = {+ findById: vi.fn().mockImplementation(async () => {+ order.push('read-message');+ return {+ id: 'tool-1',+ parentId: 'assistant-1',+ role: 'tool',+ topicId: 'topic-1',+ };+ }),+ findMessagePlugin: vi.fn().mockImplementation(async () => {+ order.push('read-plugin');+ return {+ intervention: {+ batchId: 'batch-1',+ itemIndex: 0,+ operationId: 'op-1',+ status: 'pending',+ stepIndex: 3,+ },+ toolCallId: 'call-1',+ };+ }),+ };+ vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);+ vi.spyOn(hookDispatcher, 'unregister').mockImplementation(() => {});++ await lifecycle.dispatchHooks(+ 'op-1',+ { metadata: { _hooks: [], agentId: 'a' }, status: 'waiting_for_human' },+ 'waiting_for_human',+ );++ expect(mockNotifyAgentInterventionRequired).toHaveBeenCalledWith(pendingNotification);+ expect(order[0]).toBe('persist-operation');+ expect(order.at(-1)).toBe('notify');+ });++ it('fails the parked lifecycle when one row is outside the sealed batch', async () => {+ const lifecycle = buildLifecycle();+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(true);+ mockBuildRuntimeInterventionNotification.mockResolvedValue(pendingNotification);+ (lifecycle as any).messageModel = {+ findById: vi.fn().mockResolvedValue({+ id: 'tool-1',+ parentId: 'assistant-1',+ role: 'tool',+ topicId: 'topic-1',+ }),+ findMessagePlugin: vi.fn().mockResolvedValue({+ intervention: {+ batchId: 'late-batch',+ itemIndex: 0,+ operationId: 'op-1',+ status: 'pending',+ stepIndex: 3,+ },+ toolCallId: 'call-1',+ }),+ };+ vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);+ vi.spyOn(hookDispatcher, 'unregister').mockImplementation(() => {});++ await expect(+ lifecycle.dispatchHooks(+ 'op-1',+ { metadata: { _hooks: [], agentId: 'a' }, status: 'waiting_for_human' },+ 'waiting_for_human',+ ),+ ).rejects.toBeInstanceOf(CriticalAgentInterventionPersistenceError);++ expect(mockNotifyAgentInterventionRequired).not.toHaveBeenCalled();+ });++ it('propagates a durable Review create failure so the parked lifecycle can retry', async () => {+ const lifecycle = buildLifecycle();+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(true);+ mockBuildRuntimeInterventionNotification.mockResolvedValue(pendingNotification);+ mockNotifyAgentInterventionRequired.mockRejectedValueOnce(new Error('database unavailable'));+ stubDurablePendingRows(lifecycle);+ vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);+ const unregister = vi.spyOn(hookDispatcher, 'unregister').mockImplementation(() => {});++ await expect(+ lifecycle.dispatchHooks(+ 'op-1',+ { metadata: { _hooks: [], agentId: 'a' }, status: 'waiting_for_human' },+ 'waiting_for_human',+ ),+ ).rejects.toMatchObject({+ cause: expect.objectContaining({ message: 'database unavailable' }),+ name: 'CriticalAgentInterventionPersistenceError',+ });++ expect(hookDispatcher.dispatch).not.toHaveBeenCalled();+ expect(unregister).not.toHaveBeenCalled();+ });++ it('continues after post-create push fanout fails inside the business slot', async () => {+ const lifecycle = buildLifecycle();+ const pushFanout = vi.fn().mockRejectedValue(new Error('APNs unavailable'));+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(true);+ mockBuildRuntimeInterventionNotification.mockResolvedValue(pendingNotification);+ mockNotifyAgentInterventionRequired.mockImplementation(async () => {+ // Cloud owns this boundary: the generic row is already durable here, so+ // downstream delivery is best-effort and must not reject the slot.+ await pushFanout().catch(() => undefined);+ });+ stubDurablePendingRows(lifecycle);+ vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);+ vi.spyOn(hookDispatcher, 'unregister').mockImplementation(() => {});++ await expect(+ lifecycle.dispatchHooks(+ 'op-1',+ { metadata: { _hooks: [], agentId: 'a' }, status: 'waiting_for_human' },+ 'waiting_for_human',+ ),+ ).resolves.toBeUndefined();++ expect(pushFanout).toHaveBeenCalledOnce();+ expect(hookDispatcher.dispatch).toHaveBeenCalledOnce();+ });++ it('does not build a Review when the parked operation persistence loses its CAS', async () => {+ const lifecycle = buildLifecycle();+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(false);++ await lifecycle.dispatchHooks(+ 'op-1',+ { metadata: { _hooks: [], agentId: 'a' }, status: 'waiting_for_human' },+ 'waiting_for_human',+ );++ expect(mockBuildRuntimeInterventionNotification).not.toHaveBeenCalled();+ expect(mockNotifyAgentInterventionRequired).not.toHaveBeenCalled();});- // Regression: the approval resume continues the SAME operationId- // (`processHumanIntervention` reschedules it), so the real terminal- // completion's scan covers pre-park edits. Registering at the park would- // persist `_fileWorksRegistered` into the park snapshot (skipping the- // terminal registration entirely) and freeze per-(op, file) versions at- // pre-approval content.- it('does NOT register on a human-approval park (same op resumes and registers later)', async () => {+ // Regression: the park is not a completed deliverable boundary. The fresh+ // continuation sees the complete history and performs the terminal scan;+ // registering here would freeze pre-approval file content too early.+ it('does NOT register on a human-approval park before its continuation', async () => {const mockRegister = vi.mocked(registerWorksForOperation);mockRegister.mockClear();mockRegister.mockResolvedValue({ attempted: 0, failed: 0 });diff --git a/apps/server/src/services/agentRuntime/__tests__/agentInterventionIdentity.test.ts b/apps/server/src/services/agentRuntime/__tests__/agentInterventionIdentity.test.tsnew file mode 100644index 00000000000..abed0f33f73--- /dev/null+++ b/apps/server/src/services/agentRuntime/__tests__/agentInterventionIdentity.test.ts@@ -0,0 +1,103 @@+// @vitest-environment node+import { describe, expect, it } from 'vitest';++import {+ deriveAgentInterventionActivityKey,+ deriveAgentInterventionContinuationMessageId,+ deriveAgentInterventionContinuationOperationId,+ deriveAgentInterventionQueueDeduplicationId,+ hashAgentInterventionRequestRevision,+ matchesAgentInterventionContinuationProvenance,+} from '@/business/server/agent-run/agentInterventionIdentity';++describe('agent intervention identity', () => {+ it('shares the raw-arguments revision vector used by the database CAS', () => {+ expect(hashAgentInterventionRequestRevision('{"path":"/tmp/a"}')).toBe(+ '15df809ad5fadb66f0b31bafc206dcfe620d8da8767fb76e41d3603a45dc870d',+ );+ expect(hashAgentInterventionRequestRevision('{ "path": "/tmp/a" }')).not.toBe(+ hashAgentInterventionRequestRevision('{"path":"/tmp/a"}'),+ );+ });++ it('shares the domain-separated Cloud activity-key vector', () => {+ expect(+ deriveAgentInterventionActivityKey({+ batchId: 'batch-1',+ operationId: 'operation-1',+ userId: 'user-1',+ workspaceId: 'workspace-1',+ }),+ ).toBe('4369e854-719f-5301-bfa4-1f0742eec6ac');+ });++ it('separates personal and workspace activity identities', () => {+ const common = {+ batchId: 'batch-1',+ operationId: 'operation-1',+ userId: 'user-1',+ };+ expect(deriveAgentInterventionActivityKey(common)).not.toBe(+ deriveAgentInterventionActivityKey({ ...common, workspaceId: 'workspace-1' }),+ );+ });++ it('derives one stable continuation operation from the resolution request', () => {+ const identity = {+ resolutionRequestId: '018fbd8e-7baf-7c6d-8000-000000000014',+ userId: 'user-1',+ workspaceId: 'workspace-1',+ };+ expect(deriveAgentInterventionContinuationOperationId(identity)).toBe(+ 'op_intervention_51a814d5e7e4ad0ecfb33c23accbe0a8',+ );+ expect(deriveAgentInterventionContinuationMessageId(identity)).toBe(+ 'msg_intervention_d923f5edbc2c59f46743dca97689eb73',+ );+ expect(+ deriveAgentInterventionQueueDeduplicationId(+ 'op_intervention_51a814d5e7e4ad0ecfb33c23accbe0a8',+ 0,+ ),+ ).toBe('agent-intervention:op_intervention_51a814d5e7e4ad0ecfb33c23accbe0a8:0');+ expect(+ deriveAgentInterventionContinuationOperationId({ ...identity, userId: 'user-2' }),+ ).not.toBe(deriveAgentInterventionContinuationOperationId(identity));+ });++ it('matches JSONB provenance by exact semantic fields and unordered item ids', () => {+ const expected = {+ resolutionRequestId: 'request-1',+ sourceOperationId: 'operation-source',+ sourceToolMessageIds: ['tool-b', 'tool-a'],+ };+ expect(+ matchesAgentInterventionContinuationProvenance(+ {+ sourceToolMessageIds: ['tool-a', 'tool-b'],+ sourceOperationId: 'operation-source',+ resolutionRequestId: 'request-1',+ },+ expected,+ ),+ ).toBe(true);+ expect(+ matchesAgentInterventionContinuationProvenance(+ { ...expected, sourceToolMessageIds: ['tool-a', 'tool-other'] },+ expected,+ ),+ ).toBe(false);+ expect(+ matchesAgentInterventionContinuationProvenance(+ { ...expected, sourceOperationId: 'operation-other' },+ expected,+ ),+ ).toBe(false);+ expect(+ matchesAgentInterventionContinuationProvenance(+ { ...expected, unexpectedAuthority: 'do-not-ignore' },+ expected,+ ),+ ).toBe(false);+ });+});diff --git a/apps/server/src/services/agentRuntime/__tests__/agentInterventionNotification.test.ts b/apps/server/src/services/agentRuntime/__tests__/agentInterventionNotification.test.tsnew file mode 100644index 00000000000..695be1f6f5d--- /dev/null+++ b/apps/server/src/services/agentRuntime/__tests__/agentInterventionNotification.test.ts@@ -0,0 +1,290 @@+// @vitest-environment node+import { describe, expect, it, vi } from 'vitest';++import { deriveAgentInterventionActivityKey } from '@/business/server/agent-run/agentInterventionIdentity';++import { buildRuntimeInterventionNotification } from '../agentInterventionNotification';++vi.mock('@/business/server/agent-run/executeCustomIntervention', () => ({+ getAgentMarketplaceInterventionReview: vi.fn(async () => []),+}));++const binaryTool = {+ apiName: 'editFile',+ arguments: '{"path":"/tmp/a"}',+ id: 'call-1',+ identifier: 'lobe-local-system',+ type: 'builtin' as const,+};++const buildState = (overrides: Record<string, unknown> = {}) => ({+ metadata: {+ agentId: 'agent-1',+ scope: 'main',+ sessionId: 'session-1',+ sourceMessageId: 'user-1',+ taskId: 'task-1',+ topicId: 'topic-1',+ },+ pendingApprovalBatch: {+ assistantMessageId: 'assistant-1',+ id: 'batch-1',+ sealed: true,+ stepIndex: 1,+ },+ pendingToolMessageIds: { 'call-1': 'tool-message-1' },+ pendingToolsCalling: [binaryTool],+ status: 'waiting_for_human',+ toolManifestMap: {+ 'lobe-local-system': {+ api: [{ name: 'editFile' }],+ identifier: 'lobe-local-system',+ },+ },+ userInterventionConfig: { approvalMode: 'manual' },+ ...overrides,+});++describe('buildRuntimeInterventionNotification', () => {+ it('builds the fixed identity/revision contract for a safe single binary request', async () => {+ const result = await buildRuntimeInterventionNotification({+ operationId: 'operation-1',+ state: buildState(),+ userId: 'user-1',+ workspaceId: 'workspace-1',+ });++ expect(result).toMatchObject({+ approvalMode: 'manual',+ batch: {+ activityKey: '4369e854-719f-5301-bfa4-1f0742eec6ac',+ allowedActions: ['approve_tool', 'reject_continue', 'stop'],+ id: 'batch-1',+ kind: 'single',+ sealed: true,+ stepIndex: 1,+ },+ context: {+ assistantMessageId: 'assistant-1',+ operationId: 'operation-1',+ scope: 'main',+ sessionId: 'session-1',+ taskId: 'task-1',+ topicId: 'topic-1',+ triggerMessageId: 'user-1',+ },+ items: [+ {+ allowedActions: ['approve_tool', 'edit_arguments', 'reject_continue', 'stop'],+ canonicalToolKey: 'lobe-local-system/editFile',+ interactionKind: 'tool_approval',+ requestRevision: {+ hash: '15df809ad5fadb66f0b31bafc206dcfe620d8da8767fb76e41d3603a45dc870d',+ version: 1,+ },+ sourceRef: {+ toolCallId: 'call-1',+ toolMessageId: 'tool-message-1',+ type: 'runtime',+ },+ surface: 'binary',+ },+ ],+ systemActionEligibility: 'safe_single_binary',+ });+ expect(result?.items[0]).not.toHaveProperty('arguments');+ expect(result?.items[0]).not.toHaveProperty('detail');+ });++ it('offers remember only when the authoritative approval mode is allow-list', async () => {+ const result = await buildRuntimeInterventionNotification({+ operationId: 'operation-1',+ state: buildState({ userInterventionConfig: { approvalMode: 'allow-list' } }),+ userId: 'user-1',+ });++ expect(result?.approvalMode).toBe('allow-list');+ expect(result?.items[0].allowedActions).toEqual([+ 'approve_tool',+ 'approve_tool_remember',+ 'edit_arguments',+ 'reject_continue',+ 'stop',+ ]);+ expect(result?.batch.allowedActions).toEqual(['approve_tool', 'reject_continue', 'stop']);+ });++ it('keeps unknown and incomplete manifest APIs Review-only', async () => {+ const unknown = await buildRuntimeInterventionNotification({+ operationId: 'operation-1',+ state: buildState({ toolManifestMap: {} }),+ userId: 'user-1',+ });+ const missingApi = await buildRuntimeInterventionNotification({+ operationId: 'operation-1',+ state: buildState({+ toolManifestMap: {+ 'lobe-local-system': {+ api: [{ name: 'readFile' }],+ identifier: 'lobe-local-system',+ },+ },+ }),+ userId: 'user-1',+ });++ expect(unknown?.systemActionEligibility).toBe('review_only');+ expect(missingApi?.systemActionEligibility).toBe('review_only');+ });++ it('makes custom/mixed batches Review-only and emits explicit AskUser capabilities', async () => {+ const question = {+ apiName: 'askUserQuestion',+ arguments: JSON.stringify({+ questions: [+ {+ id: 'runtime-question',+ options: [{ description: 'Use Postgres', label: 'Postgres', value: 'postgres' }],+ question: 'Which database?',+ },+ ],+ title: 'Choose storage',+ }),+ id: 'call-2',+ identifier: 'lobe-agent',+ type: 'builtin' as const,+ };+ const state = buildState({+ pendingToolMessageIds: {+ 'call-1': 'tool-message-1',+ 'call-2': 'tool-message-2',+ },+ pendingToolsCalling: [binaryTool, question],+ });++ const result = await buildRuntimeInterventionNotification({+ operationId: 'operation-1',+ state,+ userId: 'user-1',+ });++ expect(result?.batch).toMatchObject({ allowedActions: ['stop'], kind: 'mixed' });+ expect(result?.systemActionEligibility).toBe('review_only');+ expect(result?.items[1]).toMatchObject({+ allowedActions: ['submit_answers', 'skip_interaction', 'stop'],+ detail: {+ answerPolicy: { allowFreeform: true, allowSupplement: true },+ questions: [+ expect.objectContaining({+ allowCustomAnswer: true,+ id: 'runtime-question',+ options: [expect.objectContaining({ id: 'postgres' })],+ }),+ ],+ type: 'question',+ },+ interactionKind: 'question',+ surface: 'form',+ });+ });++ it('matches Web marketplace actions without advertising reserved cancel', async () => {+ const marketplace = {+ apiName: 'showAgentMarketplace',+ arguments: '{"requestId":"request-1","categoryHints":["coding"]}',+ id: 'call-marketplace',+ identifier: 'lobe-web-onboarding',+ type: 'builtin' as const,+ };+ const result = await buildRuntimeInterventionNotification({+ operationId: 'operation-1',+ state: buildState({+ pendingToolMessageIds: { 'call-marketplace': 'tool-marketplace' },+ pendingToolsCalling: [marketplace],+ toolManifestMap: {+ 'lobe-web-onboarding': {+ api: [{ name: 'showAgentMarketplace' }],+ identifier: 'lobe-web-onboarding',+ },+ },+ }),+ userId: 'user-1',+ });++ expect(result?.items[0].allowedActions).toEqual(['submit_custom', 'skip_interaction', 'stop']);+ expect(result?.items[0].allowedActions).not.toContain('cancel_interaction');+ expect(result?.systemActionEligibility).toBe('review_only');+ });++ it('emits an exact old-batch supersession for a partially resolved re-park', async () => {+ const result = await buildRuntimeInterventionNotification({+ operationId: 'operation-2',+ state: buildState({+ pendingApprovalBatch: {+ assistantMessageId: 'assistant-1',+ id: 'batch-2',+ sealed: true,+ stepIndex: 1,+ supersedes: {+ batchId: 'batch-1',+ operationId: 'operation-1',+ toolCallIds: ['call-1'],+ },+ },+ }),+ userId: 'user-1',+ workspaceId: 'workspace-1',+ });++ expect(result?.supersedes).toEqual({+ activityKey: deriveAgentInterventionActivityKey({+ batchId: 'batch-1',+ operationId: 'operation-1',+ userId: 'user-1',+ workspaceId: 'workspace-1',+ }),+ batchId: 'batch-1',+ operationId: 'operation-1',+ toolCallIds: ['call-1'],+ });+ });++ it('fails closed when supersession does not cover the exact rebound members', async () => {+ await expect(+ buildRuntimeInterventionNotification({+ operationId: 'operation-2',+ state: buildState({+ pendingApprovalBatch: {+ assistantMessageId: 'assistant-1',+ id: 'batch-2',+ sealed: true,+ stepIndex: 1,+ supersedes: {+ batchId: 'batch-1',+ operationId: 'operation-1',+ toolCallIds: ['another-call'],+ },+ },+ }),+ userId: 'user-1',+ }),+ ).rejects.toThrow('Invalid superseded intervention batch identity');+ });++ it('fails closed for incomplete runtime state and normalizes an unknown approval mode', async () => {+ await expect(+ buildRuntimeInterventionNotification({+ operationId: 'operation-1',+ state: buildState({ pendingToolMessageIds: {} }),+ userId: 'user-1',+ }),+ ).resolves.toBeUndefined();++ const result = await buildRuntimeInterventionNotification({+ operationId: 'operation-1',+ state: buildState({ userInterventionConfig: { approvalMode: 'future-mode' } }),+ userId: 'user-1',+ });+ expect(result?.approvalMode).toBe('manual');+ });+});diff --git a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.tsindex 4e06f509a66..b4415070688 100644--- a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts@@ -3,9 +3,14 @@ import { GeneralChatAgent, GraphAgent } from '@lobechat/agent-runtime';import type { AgentGraph } from '@lobechat/types';import { describe, expect, it, vi } from 'vitest';+import {+ type AgentInterventionContinuationProvenance,+ deriveAgentInterventionQueueDeduplicationId,+} from '@/business/server/agent-run/agentInterventionIdentity';import { createRuntimeExecutors } from '@/server/modules/AgentRuntime/RuntimeExecutors';import { AgentRuntimeService } from '../AgentRuntimeService';+import { CriticalAgentInterventionPersistenceError } from '../CompletionLifecycle';import { hookDispatcher } from '../hooks';// Mock all heavy dependencies to isolate executeStep logic@@ -54,6 +59,122 @@ vi.mock('@lobechat/builtin-tools/dynamicInterventionAudits', () => ({dynamicInterventionAudits: [],}));+describe('AgentRuntimeService intervention continuation dispatch recovery', () => {+ const operationId = 'op-intervention-recovery';+ const provenance: AgentInterventionContinuationProvenance = {+ resolutionRequestId: 'request-intervention-recovery',+ sourceOperationId: 'op-source',+ sourceToolMessageIds: ['tool-message'],+ };+ const deduplicationId = deriveAgentInterventionQueueDeduplicationId(operationId, 0);+ const preparation = {+ deduplicationId,+ resolutionRequestId: provenance.resolutionRequestId,+ state: 'ready' as const,+ stepIndex: 0,+ };+ const readyState = (status: 'done' | 'idle' | 'running' = 'idle') => ({+ initialContext: { phase: 'user_input' },+ metadata: {+ agentInterventionContinuation: provenance,+ agentInterventionPreparation: preparation,+ },+ operationId,+ status,+ });++ it.each(['idle', 'running', 'done'] as const)(+ 'backfills durable preparation and a stable queue ACK from %s state',+ async (status) => {+ const scheduleMessage = vi.fn().mockResolvedValue('queue-message');+ const service = new AgentRuntimeService({} as any, 'user-1', {+ queueService: { getImpl: () => ({}), scheduleMessage } as any,+ });+ const coordinator = (service as any).coordinator;+ coordinator.loadAgentState = vi.fn().mockResolvedValue(readyState(status));+ const operationModel = (service as any).agentOperationModel;+ operationModel.findById = vi.fn().mockResolvedValue({+ metadata: { agentInterventionContinuation: provenance },+ });+ operationModel.recordAgentInterventionPreparation = vi.fn().mockResolvedValue(true);+ operationModel.recordAgentInterventionDispatch = vi.fn().mockResolvedValue(true);++ await expect(service.ensureInterventionContinuationStarted(operationId)).resolves.toBe(+ 'scheduled',+ );++ expect(operationModel.recordAgentInterventionPreparation).toHaveBeenCalledWith(+ operationId,+ preparation,+ );+ expect(scheduleMessage).toHaveBeenCalledTimes(1);+ expect(scheduleMessage).toHaveBeenCalledWith(+ expect.objectContaining({ deduplicationId, operationId, stepIndex: 0 }),+ );+ expect(operationModel.recordAgentInterventionDispatch).toHaveBeenCalledWith(+ operationId,+ expect.objectContaining({+ deduplicationId,+ messageId: 'queue-message',+ resolutionRequestId: provenance.resolutionRequestId,+ state: 'scheduled',+ }),+ );+ },+ );++ it('does not enqueue again when the exact durable queue ACK already exists', async () => {+ const scheduleMessage = vi.fn();+ const service = new AgentRuntimeService({} as any, 'user-1', {+ queueService: { getImpl: () => ({}), scheduleMessage } as any,+ });+ const coordinator = (service as any).coordinator;+ coordinator.loadAgentState = vi.fn().mockResolvedValue(readyState('running'));+ const operationModel = (service as any).agentOperationModel;+ operationModel.findById = vi.fn().mockResolvedValue({+ metadata: {+ agentInterventionContinuation: provenance,+ agentInterventionDispatch: {+ deduplicationId,+ messageId: 'queue-message',+ resolutionRequestId: provenance.resolutionRequestId,+ state: 'scheduled',+ },+ agentInterventionPreparation: preparation,+ },+ });+ operationModel.recordAgentInterventionPreparation = vi.fn();++ await expect(service.ensureInterventionContinuationStarted(operationId)).resolves.toBe(+ 'already_started',+ );++ expect(operationModel.recordAgentInterventionPreparation).not.toHaveBeenCalled();+ expect(scheduleMessage).not.toHaveBeenCalled();+ });++ it('fails closed on a conflicting durable preparation marker', async () => {+ const scheduleMessage = vi.fn();+ const service = new AgentRuntimeService({} as any, 'user-1', {+ queueService: { getImpl: () => ({}), scheduleMessage } as any,+ });+ const coordinator = (service as any).coordinator;+ coordinator.loadAgentState = vi.fn().mockResolvedValue(readyState());+ const operationModel = (service as any).agentOperationModel;+ operationModel.findById = vi.fn().mockResolvedValue({+ metadata: {+ agentInterventionContinuation: provenance,+ agentInterventionPreparation: { ...preparation, resolutionRequestId: 'foreign-request' },+ },+ });++ await expect(service.ensureInterventionContinuationStarted(operationId)).rejects.toThrow(+ /durable preparation conflict/,+ );+ expect(scheduleMessage).not.toHaveBeenCalled();+ });+});+describe('AgentRuntimeService.executeStep - early exit on terminal state', () => {const createService = () => {const service = new AgentRuntimeService({} as any, 'user-1', { queueService: null });@@ -355,6 +476,157 @@ describe('AgentRuntimeService.executeStep - early exit on terminal state', () =>});});+describe('AgentRuntimeService.executeStep - durable Review lifecycle retry', () => {+ it('keeps the operation parked and replays only Review lifecycle on the same-step retry', async () => {+ const service = new AgentRuntimeService({} as any, 'user-1', { queueService: null });+ const coordinator = (service as any).coordinator;+ const streamManager = (service as any).streamManager;+ const completionLifecycle = (service as any).completionLifecycle;++ let storedState: any = {+ cost: { currency: 'USD', total: 0 },+ lastModified: new Date().toISOString(),+ messages: [],+ metadata: { _hooks: [] },+ operationId: 'op-review-retry',+ status: 'running',+ stepCount: 0,+ toolManifestMap: {},+ usage: {},+ };+ const parkedState = {+ ...storedState,+ pendingApprovalBatch: {+ assistantMessageId: 'assistant-1',+ id: 'op-review-retry:1:assistant-1',+ sealed: true as const,+ stepIndex: 1,+ },+ pendingToolMessageIds: { 'call-1': 'tool-1' },+ pendingToolsCalling: [{ apiName: 'run', id: 'call-1', identifier: 'shell' }],+ status: 'waiting_for_human' as const,+ stepCount: 1,+ };++ coordinator.loadAgentState = vi.fn().mockImplementation(async () => storedState);+ coordinator.saveStepResult = vi.fn().mockImplementation(async (_operationId, stepResult) => {+ storedState = stepResult.newState;+ });+ coordinator.saveAgentState = vi.fn().mockImplementation(async (_operationId, state) => {+ storedState = state;+ });+ streamManager.publishStreamEvent = vi.fn().mockResolvedValue(undefined);++ const runtimeStep = vi.fn().mockResolvedValue({+ events: [],+ newState: parkedState,+ nextContext: undefined,+ });+ vi.spyOn(service as any, 'createAgentRuntime').mockResolvedValue({+ runtime: { step: runtimeStep },+ });+ vi.spyOn(completionLifecycle, 'emitSignalEvents').mockResolvedValue([]);+ vi.spyOn(completionLifecycle as any, 'persistCompletion').mockResolvedValue(true);+ const notifyPendingReview = vi+ .spyOn(completionLifecycle as any, 'notifyPendingAgentIntervention')+ .mockRejectedValueOnce(+ new CriticalAgentInterventionPersistenceError(+ 'op-review-retry',+ new Error('Review store unavailable'),+ ),+ )+ .mockResolvedValueOnce(undefined);+ const hookDispatch = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);+ const finalizeTrace = vi.spyOn((service as any).traceRecorder, 'finalize');++ await expect(+ service.executeStep({+ context: { phase: 'agent_step' } as any,+ operationId: 'op-review-retry',+ stepIndex: 0,+ }),+ ).rejects.toBeInstanceOf(CriticalAgentInterventionPersistenceError);++ expect(storedState.status).toBe('waiting_for_human');+ expect(storedState.error).toBeUndefined();+ expect(storedState.metadata._agentInterventionLifecycle).toEqual({+ state: 'pending',+ stepIndex: 0,+ });+ expect(coordinator.saveAgentState).not.toHaveBeenCalled();+ expect(notifyPendingReview).toHaveBeenCalledTimes(1);++ const retryResult = await service.executeStep({+ context: { phase: 'agent_step' } as any,+ externalRetryCount: 1,+ operationId: 'op-review-retry',+ stepIndex: 0,+ });++ expect(retryResult).toMatchObject({+ nextStepScheduled: false,+ state: { status: 'waiting_for_human' },+ stepResult: null,+ success: true,+ });+ expect(notifyPendingReview).toHaveBeenCalledTimes(2);+ expect(runtimeStep).toHaveBeenCalledTimes(1);+ expect(coordinator.saveStepResult).toHaveBeenCalledTimes(1);+ expect(storedState.metadata._agentInterventionLifecycle).toEqual({+ state: 'completed',+ stepIndex: 0,+ });+ expect(+ streamManager.publishStreamEvent.mock.calls.filter(([, event]: any) =>+ ['step_start', 'step_complete'].includes(event.type),+ ),+ ).toHaveLength(2);+ expect(+ hookDispatch.mock.calls.filter(([, hookType]) => hookType === 'beforeStep'),+ ).toHaveLength(1);+ expect(hookDispatch.mock.calls.filter(([, hookType]) => hookType === 'afterStep')).toHaveLength(+ 1,+ );+ expect(+ hookDispatch.mock.calls.filter(([, hookType]) => hookType === 'onComplete'),+ ).toHaveLength(1);+ expect(hookDispatch).toHaveBeenCalledWith(+ 'op-review-retry',+ 'onComplete',+ expect.objectContaining({ reason: 'waiting_for_human' }),+ [],+ );+ expect(finalizeTrace).toHaveBeenCalledTimes(1);+ expect(finalizeTrace).toHaveBeenCalledWith(+ 'op-review-retry',+ expect.objectContaining({ completionReason: 'waiting_for_human' }),+ );++ // The Review + hook finished, but the provider did not observe our HTTP+ // response and redelivered once more. The durable completion checkpoint+ // makes this an ordinary stale ACK: neither side effect runs again.+ const responseLossRetry = await service.executeStep({+ context: { phase: 'agent_step' } as any,+ externalRetryCount: 2,+ operationId: 'op-review-retry',+ stepIndex: 0,+ });++ expect(responseLossRetry).toMatchObject({+ nextStepScheduled: false,+ state: { status: 'waiting_for_human' },+ stepResult: null,+ success: true,+ });+ expect(notifyPendingReview).toHaveBeenCalledTimes(2);+ expect(runtimeStep).toHaveBeenCalledTimes(1);+ expect(coordinator.saveStepResult).toHaveBeenCalledTimes(1);+ expect(+ hookDispatch.mock.calls.filter(([, hookType]) => hookType === 'onComplete'),+ ).toHaveLength(1);+ });+});+describe('AgentRuntimeService.executeStep - step idempotency (distributed lock)', () => {const createService = () => {const service = new AgentRuntimeService({} as any, 'user-1', { queueService: null });@@ -545,6 +817,39 @@ describe('AgentRuntimeService.executeStep - step idempotency (distributed lock)'expect(coordinator.releaseStepLock).not.toHaveBeenCalled();});+ it('keeps a locked completed-step Review retry non-acknowledged for redelivery', async () => {+ const service = createService();+ const coordinator = (service as any).coordinator;+ coordinator.tryClaimStep = vi.fn().mockResolvedValue(false);+ coordinator.loadAgentState = vi.fn().mockResolvedValue({+ metadata: {+ _agentInterventionLifecycle: { state: 'pending', stepIndex: 0 },+ },+ pendingApprovalBatch: {+ assistantMessageId: 'assistant-1',+ id: 'op-locked-review:1:assistant-1',+ sealed: true,+ stepIndex: 1,+ },+ status: 'waiting_for_human',+ stepCount: 1,+ });++ const result = await service.executeStep({+ externalRetryCount: 1,+ operationId: 'op-locked-review',+ stepIndex: 0,+ });++ expect(result).toMatchObject({+ locked: true,+ nextStepScheduled: false,+ state: { status: 'waiting_for_human' },+ success: false,+ });+ expect(coordinator.releaseStepLock).not.toHaveBeenCalled();+ });+it('should skip execution when stepCount > stepIndex (delayed retry after lock TTL)', async () => {const service = createService();const coordinator = (service as any).coordinator;@@ -1410,10 +1715,9 @@ describe('AgentRuntimeService.executeStep - pre-snapshot file-Work registration'expect(registerSpy).not.toHaveBeenCalled();});- // Regression: the approval resume continues the SAME operationId, so the- // terminal completion's scan covers pre-park edits. Registering at the park- // would persist `_fileWorksRegistered` into the park snapshot — skipping the- // terminal registration — and freeze versions at pre-approval content.+ // Regression: the park is not a completed deliverable boundary. The fresh+ // continuation sees the complete history and performs the terminal scan;+ // registering here would freeze pre-approval content too early.it('skips pre-save registration when parking on waiting_for_human', async () => {const { registerSpy } = await runTerminalStep(doneState('waiting_for_human'));diff --git a/apps/server/src/services/agentRuntime/agentInterventionNotification.ts b/apps/server/src/services/agentRuntime/agentInterventionNotification.tsnew file mode 100644index 00000000000..6ca535f212e--- /dev/null+++ b/apps/server/src/services/agentRuntime/agentInterventionNotification.ts@@ -0,0 +1,403 @@+import { DEFAULT_SECURITY_BLACKLIST, InterventionChecker } from '@lobechat/agent-runtime';+import {+ type ChatToolPayload,+ classifyToolInterventionPresentation,+ type MessageMapScope,+} from '@lobechat/types';++import {+ deriveAgentInterventionActivityKey,+ hashAgentInterventionRequestRevision,+} from '@/business/server/agent-run/agentInterventionIdentity';+import type {+ AgentInterventionAllowedAction,+ AgentInterventionReviewDetail,+ NotifyAgentInterventionItem,+ NotifyAgentInterventionRequiredParams,+} from '@/business/server/agent-run/agentInterventionReview';+import { getAgentMarketplaceInterventionReview } from '@/business/server/agent-run/executeCustomIntervention';++const MAX_SHORT_TEXT = 200;+const MAX_LONG_TEXT = 1000;++const boundedString = (value: unknown, max = MAX_SHORT_TEXT): string | undefined => {+ if (typeof value !== 'string') return;+ const normalized = value.trim();+ if (!normalized) return;+ return normalized.slice(0, max);+};++const parseArguments = (value: string): Record<string, unknown> => {+ try {+ const parsed = JSON.parse(value || '{}');+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};+ } catch {+ return {};+ }+};++const boundedStringList = (value: unknown, maxItems = 8): string[] => {+ if (!Array.isArray(value)) return [];+ return value+ .map((item) => boundedString(item))+ .filter((item): item is string => Boolean(item))+ .slice(0, maxItems);+};++const MESSAGE_MAP_SCOPES = new Set<MessageMapScope>([+ 'main',+ 'thread',+ 'group',+ 'group_agent',+ 'group_agent_builder',+ 'page',+ 'task',+ 'agent_builder',+ 'sub_agent',+]);++const APPROVAL_MODES = new Set<NotifyAgentInterventionRequiredParams['approvalMode']>([+ 'allow-list',+ 'auto-run',+ 'headless',+ 'manual',+]);++const messageMapScope = (value: unknown): MessageMapScope | undefined =>+ typeof value === 'string' && MESSAGE_MAP_SCOPES.has(value as MessageMapScope)+ ? (value as MessageMapScope)+ : undefined;++const approvalMode = (value: unknown): NotifyAgentInterventionRequiredParams['approvalMode'] =>+ typeof value === 'string' &&+ APPROVAL_MODES.has(value as NotifyAgentInterventionRequiredParams['approvalMode'])+ ? (value as NotifyAgentInterventionRequiredParams['approvalMode'])+ : 'manual';++const buildQuestionDetail = (+ args: Record<string, unknown>,+): Extract<AgentInterventionReviewDetail, { type: 'question' }> => {+ const questions = Array.isArray(args.questions) ? args.questions : [];++ return {+ // The shared Web AskUser form exposes both whole-form freeform and a+ // supplemental note. Persist these as explicit capabilities so native+ // clients never infer them from the presence of questions.+ answerPolicy: { allowFreeform: true, allowSupplement: true },+ questions: questions+ .filter((question): question is Record<string, unknown> =>+ Boolean(question && typeof question === 'object' && !Array.isArray(question)),+ )+ .slice(0, 4)+ .map((question, questionIndex) => {+ const rawOptions = Array.isArray(question.options) ? question.options : [];+ return {+ // Every question in the shared AskUser surface has the trailing+ // "write your own" row; make that server-authored policy explicit.+ allowCustomAnswer: true,+ header: boundedString(question.header),+ id:+ boundedString(question.id) ??+ boundedString(question.question) ??+ `question_${questionIndex + 1}`,+ multiple: question.multiSelect === true || question.multiple === true,+ options: rawOptions+ .filter((option): option is Record<string, unknown> =>+ Boolean(option && typeof option === 'object' && !Array.isArray(option)),+ )+ .slice(0, 8)+ .map((option, optionIndex) => ({+ description: boundedString(option.description, MAX_LONG_TEXT),+ id:+ boundedString(option.id) ??+ boundedString(option.value) ??+ boundedString(option.label) ??+ `option_${optionIndex + 1}`,+ label:+ boundedString(option.label) ??+ boundedString(option.value) ??+ `Option ${optionIndex + 1}`,+ })),+ question:+ boundedString(question.question, MAX_LONG_TEXT) ?? `Question ${questionIndex + 1}`,+ };+ }),+ title: boundedString(args.title) ?? boundedString(args.prompt, MAX_LONG_TEXT),+ type: 'question',+ };+};++const revisionFor = (tool: ChatToolPayload) => ({+ // Must exactly match the DB edit/claim CAS: the canonical revision is the+ // SHA-256 of the raw arguments string, without parsing or tool metadata.+ hash: hashAgentInterventionRequestRevision(tool.arguments || ''),+ version: 1,+});++const actionsFor = (+ surface: 'binary' | 'form',+ interactionKind: NotifyAgentInterventionItem['interactionKind'],+ resolvedApprovalMode: NotifyAgentInterventionRequiredParams['approvalMode'],+): AgentInterventionAllowedAction[] => {+ if (surface === 'binary') {+ return [+ 'approve_tool',+ ...(resolvedApprovalMode === 'allow-list' ? (['approve_tool_remember'] as const) : []),+ 'edit_arguments',+ 'reject_continue',+ 'stop',+ ];+ }++ if (interactionKind === 'question') {+ // Standard runtime AskUser has Submit / Skip semantics. Cancel is a+ // provider/custom terminal action and has no runtime handler here.+ return ['submit_answers', 'skip_interaction', 'stop'];+ }++ // Web marketplace exposes Submit / Skip / Stop. Keep cancel_interaction in+ // the reserved v2 union, but never advertise it until an operation-wide+ // atomic cancel emitter exists across Web and Mobile.+ return ['submit_custom', 'skip_interaction', 'stop'];+};++/**+ * Direct system actions are an elevated capability, so classification alone+ * is insufficient. Require the exact API to exist in the immutable operation+ * manifest (or a dynamically activated manifest that was durably resolved).+ * Unknown tools and incomplete discovery placeholders remain Review-only.+ */+const hasAuthoritativeApiDefinition = (state: any, tool: ChatToolPayload): boolean => {+ const baseManifestMap = state?.operationToolSet?.manifestMap ?? state?.toolManifestMap ?? {};+ const activatedManifestMap = Object.fromEntries(+ (Array.isArray(state?.activatedStepTools) ? state.activatedStepTools : [])+ .filter(+ (activation: unknown): activation is { id: string; manifest: Record<string, unknown> } =>+ Boolean(+ activation &&+ typeof activation === 'object' &&+ typeof (activation as { id?: unknown }).id === 'string' &&+ (activation as { manifest?: unknown }).manifest &&+ typeof (activation as { manifest?: unknown }).manifest === 'object',+ ),+ )+ .map((activation: { id: string; manifest: Record<string, unknown> }) => [+ activation.id,+ activation.manifest,+ ]),+ );+ const manifest = activatedManifestMap[tool.identifier] ?? baseManifestMap[tool.identifier];++ return Boolean(+ manifest &&+ typeof manifest === 'object' &&+ Array.isArray((manifest as { api?: unknown }).api) &&+ (manifest as { api: unknown[] }).api.some(+ (api) => api && typeof api === 'object' && (api as { name?: unknown }).name === tool.apiName,+ ),+ );+};++interface BuildRuntimeInterventionNotificationParams {+ operationId: string;+ state: any;+ userId: string;+ workspaceId?: string;+}++/**+ * Build the notification-safe snapshot for one sealed runtime approval batch.+ * Raw tool arguments are used only to derive a revision and bounded custom+ * detail; they are never copied into the durable notification contract.+ */+export const buildRuntimeInterventionNotification = async ({+ operationId,+ state,+ userId,+ workspaceId,+}: BuildRuntimeInterventionNotificationParams): Promise<+ NotifyAgentInterventionRequiredParams | undefined+> => {+ const pendingTools: ChatToolPayload[] = Array.isArray(state?.pendingToolsCalling)+ ? state.pendingToolsCalling+ : [];+ const batch = state?.pendingApprovalBatch;+ const toolMessageIds = state?.pendingToolMessageIds;+ const metadata = state?.metadata ?? {};++ if (+ state?.status !== 'waiting_for_human' ||+ !batch?.sealed ||+ typeof batch.id !== 'string' ||+ typeof batch.assistantMessageId !== 'string' ||+ !Number.isInteger(batch.stepIndex) ||+ !toolMessageIds ||+ typeof toolMessageIds !== 'object' ||+ pendingTools.length === 0+ ) {+ return;+ }++ const items: NotifyAgentInterventionItem[] = [];+ const securityBlacklist = state?.securityBlacklist ?? DEFAULT_SECURITY_BLACKLIST;+ const resolvedApprovalMode = approvalMode(state?.userInterventionConfig?.approvalMode);++ for (const tool of pendingTools) {+ const toolMessageId = toolMessageIds[tool.id];+ if (typeof toolMessageId !== 'string' || !toolMessageId) return;++ const args = parseArguments(tool.arguments);+ const { interactionKind, surface } = classifyToolInterventionPresentation(+ tool.identifier,+ tool.apiName,+ );+ const security = InterventionChecker.checkSecurityBlacklist(securityBlacklist, args);+ const item: NotifyAgentInterventionItem = {+ allowedActions: actionsFor(surface, interactionKind, resolvedApprovalMode),+ canonicalToolKey: `${tool.identifier}/${tool.apiName}`,+ interactionKind,+ provider:+ boundedString(state?.modelRuntimeConfig?.provider) ??+ boundedString(metadata?.modelRuntimeConfig?.provider) ??+ boundedString(metadata?.provider),+ requestRevision: revisionFor(tool),+ ...(security.blocked && {+ risk: {+ level: 'critical' as const,+ summary: boundedString(security.reason, MAX_LONG_TEXT) ?? 'Blocked by a security policy',+ },+ }),+ sourceRef: { toolCallId: tool.id, toolMessageId, type: 'runtime' },+ surface,+ summary: `${tool.identifier} / ${tool.apiName}`.slice(0, MAX_SHORT_TEXT),+ };++ if (interactionKind === 'question') {+ item.detail = buildQuestionDetail(args);+ } else if (+ interactionKind === 'custom' &&+ tool.identifier === 'lobe-web-onboarding' &&+ tool.apiName === 'showAgentMarketplace'+ ) {+ const requestId = boundedString(args.requestId) ?? tool.id;+ const categoryHints = boundedStringList(args.categoryHints);+ const agents = await getAgentMarketplaceInterventionReview({+ categoryHints,+ prompt: boundedString(args.prompt, MAX_LONG_TEXT),+ requestId,+ userId,+ workspaceId,+ });+ item.detail = {+ agents: agents+ .map((agent) => ({+ avatar: boundedString(agent.avatar, MAX_LONG_TEXT),+ description: boundedString(agent.description, MAX_LONG_TEXT),+ id: boundedString(agent.id),+ title: boundedString(agent.title),+ }))+ .filter((agent): agent is typeof agent & { id: string; title: string } =>+ Boolean(agent.id && agent.title),+ )+ .slice(0, 50),+ kind: 'agent_marketplace',+ multiple: true,+ title: boundedString(args.prompt, MAX_LONG_TEXT) ?? 'Choose agents',+ type: 'custom',+ };+ item.request = { categoryHints, kind: 'agent_marketplace', requestId };+ }++ items.push(item);+ }++ const allBinary = items.every((item) => item.surface === 'binary');+ const hasSecurityRisk = items.some((item) => item.risk?.level !== undefined);+ const allApisAuthoritative = pendingTools.every((tool) =>+ hasAuthoritativeApiDefinition(state, tool),+ );+ const batchAllowedActions: AgentInterventionAllowedAction[] = allBinary+ ? ['approve_tool', 'reject_continue', 'stop']+ : ['stop'];+ const first = items[0];+ const homogeneous = items.every(+ (item) => item.surface === first.surface && item.interactionKind === first.interactionKind,+ );+ let supersedes: NotifyAgentInterventionRequiredParams['supersedes'];+ if (batch.supersedes) {+ const previousToolCallIds = batch.supersedes.toolCallIds;+ const pendingToolCallIds = pendingTools.map((tool) => tool.id);+ const exactMembers =+ Array.isArray(previousToolCallIds) &&+ previousToolCallIds.length === pendingToolCallIds.length &&+ new Set(previousToolCallIds).size === previousToolCallIds.length &&+ previousToolCallIds.every((toolCallId: unknown) =>+ pendingToolCallIds.includes(toolCallId as string),+ );+ if (+ typeof batch.supersedes.batchId !== 'string' ||+ !batch.supersedes.batchId ||+ typeof batch.supersedes.operationId !== 'string' ||+ !batch.supersedes.operationId ||+ (batch.supersedes.batchId === batch.id && batch.supersedes.operationId === operationId) ||+ !exactMembers+ ) {+ throw new Error('Invalid superseded intervention batch identity');+ }+ supersedes = {+ activityKey: deriveAgentInterventionActivityKey({+ batchId: batch.supersedes.batchId,+ operationId: batch.supersedes.operationId,+ userId,+ workspaceId,+ }),+ batchId: batch.supersedes.batchId,+ operationId: batch.supersedes.operationId,+ toolCallIds: previousToolCallIds,+ };+ }++ return {+ agentId: boundedString(metadata.agentId),+ approvalMode: resolvedApprovalMode,+ batch: {+ activityKey: deriveAgentInterventionActivityKey({+ batchId: batch.id,+ operationId,+ userId,+ workspaceId,+ }),+ allowedActions: batchAllowedActions,+ id: batch.id,+ kind: items.length === 1 ? 'single' : homogeneous ? 'parallel' : 'mixed',+ sealed: true,+ stepIndex: batch.stepIndex,+ },+ context: {+ agentId: boundedString(metadata.agentId),+ assistantMessageId: batch.assistantMessageId,+ groupId: boundedString(metadata.groupId),+ operationId,+ pageId: boundedString(metadata.documentId),+ scope: messageMapScope(metadata.scope),+ sessionId: boundedString(metadata.sessionId),+ taskId: boundedString(metadata.taskId),+ threadId: boundedString(metadata.threadId),+ topicId: boundedString(metadata.topicId),+ triggerMessageId: boundedString(metadata.sourceMessageId),+ workspaceId,+ },+ items,+ summary:+ items.length === 1+ ? `${items[0].summary} requires review`+ : `${items.length} actions require review`,+ systemActionEligibility:+ items.length === 1 && allBinary && !hasSecurityRisk && allApisAuthoritative+ ? 'safe_single_binary'+ : 'review_only',+ ...(supersedes && { supersedes }),+ userId,+ workspaceId,+ };+};diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.tsindex 11fb0104dfc..f631ecf11af 100644--- a/apps/server/src/services/agentRuntime/types.ts+++ b/apps/server/src/services/agentRuntime/types.ts@@ -383,6 +383,8 @@ export interface OperationCreationParams {*/orchestrationRole?: 'supervisor' | 'member';scope?: string | null;+ /** Conversation/session locator used to rebuild an authenticated Review route. */+ sessionId?: string;/** Source user message ID used for same-turn Agent Signal procedure suppression. */sourceMessageId?: string;/**@@ -453,8 +455,21 @@ export interface OperationCreationParams {initialMessages?: any[];/** Initial step count offset for resumed operations (accumulated from previous runs) */initialStepCount?: number;+ /**+ * Server-authored provenance for a continuation created from a durable human+ * intervention claim. It is persisted in both agent_operations.metadata and+ * runtime state so a retry can distinguish this exact continuation from an+ * unrelated operation that happens to reuse an id. Never client-passable.+ */+ interventionResolution?: {+ resolutionRequestId: string;+ sourceOperationId: string;+ sourceToolMessageIds: string[];+ };maxSteps?: number;modelRuntimeConfig?: any;+ /** Marks the source claim non-rollbackable once deterministic runtime state is durable. */+ onInterventionPrepared?: () => void;operationId: string;/** Operation-level skill set for SkillResolver */operationSkillSet?: OperationSkillSet;diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.tsindex bd65c7f33e9..64303516558 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts@@ -1075,6 +1075,7 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>);expect(topicMock.tryReserveTaskCallback).toHaveBeenCalledWith('topic-1', expect.any(String), {allowRunningOperationId: 'parent-operation',+ allowSameReservationReentry: true,ignoreRunningOperation: undefined,replacesOperationId: undefined,});diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.tsindex b974d1599ad..5b190ce12ab 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts@@ -2,6 +2,12 @@ import type { LobeChatDatabase } from '@lobechat/database';import type * as ModelBankModule from 'model-bank';import { beforeEach, describe, expect, it, vi } from 'vitest';+import {+ deriveAgentInterventionContinuationMessageId,+ deriveAgentInterventionContinuationOperationId,+ deriveAgentInterventionQueueDeduplicationId,+} from '@/business/server/agent-run/agentInterventionIdentity';+import { AiAgentService } from '../index';const {@@ -10,22 +16,40 @@ const {mockFindMessagePlugin,mockMessageCreate,mockMessageQuery,+ mockListMessagePluginsByTopic,+ mockResolveHumanApproval,+ mockRestoreHumanApproval,mockUpdateMessagePlugin,+ mockUpdateTopicMetadata,mockUpdateToolMessage,- mockFindLatestParkedOperationId,+ mockFindOperationById,mockRecordCompletion,+ mockRepairAgentInterventionContinuation,mockInterruptOperation,+ mockEnsureInterventionContinuationStarted,+ mockLoadInterventionContinuationState,+ mockReleaseTaskCallbackReservation,+ mockTryReserveTaskCallback,} = vi.hoisted(() => ({- mockFindLatestParkedOperationId: vi.fn(),+ mockEnsureInterventionContinuationStarted: vi.fn(),+ mockFindOperationById: vi.fn(),mockRecordCompletion: vi.fn(),+ mockRepairAgentInterventionContinuation: vi.fn(),mockInterruptOperation: vi.fn(),+ mockLoadInterventionContinuationState: vi.fn(),+ mockReleaseTaskCallbackReservation: vi.fn(),mockCreateOperation: vi.fn(),mockFindById: vi.fn(),mockFindMessagePlugin: vi.fn(),+ mockListMessagePluginsByTopic: vi.fn(),mockMessageCreate: vi.fn(),mockMessageQuery: vi.fn(),+ mockResolveHumanApproval: vi.fn(),+ mockRestoreHumanApproval: vi.fn(),mockUpdateMessagePlugin: vi.fn(),+ mockUpdateTopicMetadata: vi.fn(),mockUpdateToolMessage: vi.fn(),+ mockTryReserveTaskCallback: vi.fn(),}));vi.mock('@/libs/trusted-client', () => ({@@ -35,13 +59,17 @@ vi.mock('@/libs/trusted-client', () => ({}));vi.mock('@/database/models/message', () => ({+ HumanApprovalAlreadyResolvedError: class HumanApprovalAlreadyResolvedError extends Error {},MessageModel: vi.fn().mockImplementation(() => ({create: mockMessageCreate,getLatestNonToolMessageId: vi.fn().mockResolvedValue(undefined),getLatestSpineMessageId: vi.fn().mockResolvedValue(undefined),findById: mockFindById,findMessagePlugin: mockFindMessagePlugin,+ listMessagePluginsByTopic: mockListMessagePluginsByTopic,query: mockMessageQuery,+ resolveHumanApproval: mockResolveHumanApproval,+ restoreHumanApproval: mockRestoreHumanApproval,update: vi.fn().mockResolvedValue({}),updateMessagePlugin: mockUpdateMessagePlugin,updateToolMessage: mockUpdateToolMessage,@@ -72,11 +100,12 @@ vi.mock('@/database/models/plugin', () => ({vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({- releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),- tryReserveTaskCallback: vi.fn().mockResolvedValue(true),+ releaseTaskCallbackReservation: mockReleaseTaskCallbackReservation,+ repairAgentInterventionContinuation: mockRepairAgentInterventionContinuation,+ tryReserveTaskCallback: mockTryReserveTaskCallback,create: vi.fn().mockResolvedValue({ id: 'topic-1' }),findById: vi.fn().mockResolvedValue(null),- updateMetadata: vi.fn(),+ updateMetadata: mockUpdateTopicMetadata,})),}));@@ -103,13 +132,15 @@ vi.mock('@/database/models/userMemory/persona', () => ({vi.mock('@/server/services/agentRuntime', () => ({AgentRuntimeService: vi.fn().mockImplementation(() => ({createOperation: mockCreateOperation,+ ensureInterventionContinuationStarted: mockEnsureInterventionContinuationStarted,interruptOperation: mockInterruptOperation,+ loadInterventionContinuationState: mockLoadInterventionContinuationState,})),}));vi.mock('@/database/models/agentOperation', () => ({AgentOperationModel: vi.fn().mockImplementation(() => ({- findLatestParkedOperationId: mockFindLatestParkedOperationId,+ findById: mockFindOperationById,recordCompletion: mockRecordCompletion,})),}));@@ -178,6 +209,7 @@ describe('AiAgentService.execAgent - resumeApproval', () => {apiName: 'runCommand',arguments: '{"command":"echo"}',identifier: 'lobe-local-system',+ intervention: { status: 'pending' },toolCallId: 'call_xyz',type: 'builtin',};@@ -190,11 +222,21 @@ describe('AiAgentService.execAgent - resumeApproval', () => {operationId: 'op-123',success: true,});- mockFindById.mockResolvedValue(pendingToolMessage);+ mockFindById.mockImplementation(async (id: string) =>+ id === pendingToolMessage.id ? pendingToolMessage : undefined,+ );mockFindMessagePlugin.mockResolvedValue(pendingToolPlugin);mockMessageQuery.mockResolvedValue([{ content: 'hi', id: 'history-1', role: 'user' }]);mockMessageCreate.mockResolvedValue({ id: 'assistant-msg-new' });+ mockResolveHumanApproval.mockResolvedValue('applied');+ mockLoadInterventionContinuationState.mockResolvedValue(null);+ mockEnsureInterventionContinuationStarted.mockResolvedValue('scheduled');+ mockReleaseTaskCallbackReservation.mockResolvedValue('released');+ mockRepairAgentInterventionContinuation.mockResolvedValue('repaired');+ mockTryReserveTaskCallback.mockResolvedValue(true);+ mockRestoreHumanApproval.mockResolvedValue(undefined);mockUpdateMessagePlugin.mockResolvedValue(undefined);+ mockUpdateTopicMetadata.mockResolvedValue(undefined);mockUpdateToolMessage.mockResolvedValue(undefined);// `MessageModel` is fully mocked above, so the service never touches the// raw `db` arg — cast an empty stub through `unknown` to satisfy the@@ -220,9 +262,15 @@ describe('AiAgentService.execAgent - resumeApproval', () => {},});- expect(mockUpdateMessagePlugin).toHaveBeenCalledWith('tool-msg-1', {- intervention: { status: 'approved' },- });+ expect(mockResolveHumanApproval).toHaveBeenCalledWith([+ {+ id: 'tool-msg-1',+ intervention: {+ resolutionRequestId: expect.stringMatching(/^legacy_/),+ status: 'approved',+ },+ },+ ]);// `approved` decision never writes tool content — the content arrives// when the approved tool actually executes.expect(mockUpdateToolMessage).not.toHaveBeenCalled();@@ -245,18 +293,133 @@ describe('AiAgentService.execAgent - resumeApproval', () => {}),);});++ it('stamps the server-authored generic resolution id for retry detection', async () => {+ const approvalResolutionRequestId = '018fbd8e-7baf-7c6d-8000-000000000099';++ await service.execAgent({+ ...baseParams,+ approvalResolutionRequestId,+ resumeApproval: {+ decision: 'approved',+ parentMessageId: 'tool-msg-1',+ toolCallId: 'call_xyz',+ },+ });++ expect(mockResolveHumanApproval).toHaveBeenCalledWith([+ {+ id: 'tool-msg-1',+ intervention: { resolutionRequestId: approvalResolutionRequestId, status: 'approved' },+ },+ ]);+ expect(mockUpdateTopicMetadata).not.toHaveBeenCalled();+ });++ it('retires the authoritative parked operation only after scheduling its continuation', async () => {+ mockFindMessagePlugin.mockResolvedValue({+ ...pendingToolPlugin,+ intervention: {+ batchId: 'batch-parked',+ operationId: 'op-parked',+ status: 'pending',+ },+ });+ mockFindOperationById.mockResolvedValue({+ id: 'op-parked',+ status: 'waiting_for_human',+ });+ mockInterruptOperation.mockResolvedValue(true);+ mockRecordCompletion.mockResolvedValue(true);++ await service.execAgent({+ ...baseParams,+ approvalSourceOperationId: 'op-parked',+ resumeApproval: {+ decision: 'approved',+ parentMessageId: 'tool-msg-1',+ toolCallId: 'call_xyz',+ },+ });++ expect(mockCreateOperation.mock.invocationCallOrder[0]).toBeLessThan(+ mockInterruptOperation.mock.invocationCallOrder[0],+ );+ expect(mockInterruptOperation).toHaveBeenCalledWith('op-parked');+ expect(mockRecordCompletion).toHaveBeenCalledWith('op-parked', {+ completedAt: expect.any(Date),+ completionReason: 'done',+ status: 'done',+ });+ expect(mockRestoreHumanApproval).not.toHaveBeenCalled();+ });++ it('defers generic old-operation retirement to the shared dispatch boundary', async () => {+ mockFindMessagePlugin.mockResolvedValue({+ ...pendingToolPlugin,+ intervention: {+ batchId: 'batch-parked',+ operationId: 'op-parked',+ status: 'pending',+ },+ });++ const result = await service.execAgent({+ ...baseParams,+ approvalResolutionRequestId: '018fbd8e-7baf-7c6d-8000-000000000098',+ approvalSourceOperationId: 'op-parked',+ resumeApproval: {+ decision: 'approved',+ parentMessageId: 'tool-msg-1',+ toolCallId: 'call_xyz',+ },+ });++ expect(result.success).toBe(true);+ expect(mockCreateOperation).toHaveBeenCalledTimes(1);+ expect(mockInterruptOperation).not.toHaveBeenCalled();+ expect(mockRecordCompletion).not.toHaveBeenCalled();+ expect(mockRestoreHumanApproval).not.toHaveBeenCalled();+ });++ it('does not restore an executed claim when old-operation retirement must be retried', async () => {+ mockFindMessagePlugin.mockResolvedValue({+ ...pendingToolPlugin,+ intervention: { operationId: 'op-parked', status: 'pending' },+ });+ mockFindOperationById.mockResolvedValue({+ id: 'op-parked',+ status: 'waiting_for_human',+ });+ mockInterruptOperation.mockResolvedValue(true);+ mockRecordCompletion.mockResolvedValue(false);++ const result = await service.execAgent({+ ...baseParams,+ approvalSourceOperationId: 'op-parked',+ resumeApproval: {+ decision: 'approved',+ parentMessageId: 'tool-msg-1',+ toolCallId: 'call_xyz',+ },+ });++ expect(mockCreateOperation).toHaveBeenCalledTimes(1);+ expect(result).toMatchObject({+ error: 'retirePendingApprovalOperation: failed to settle op-parked',+ success: false,+ });+ expect(mockRestoreHumanApproval).not.toHaveBeenCalled();+ });});- // Server handles `rejected` and `rejected_continue` identically — both- // persist the rejection and resume the LLM with the updated history so it- // can respond to the user. The client-side split is only about optimistic- // writes / button UX; beyond the DB write there's nothing meaningful to- // differentiate once the decision is persisted.+ // Both rejection variants persist a tool result and enter the pending-sibling+ // barrier. The final decision continues the LLM; a partial one re-parks.describe.each([['rejected' as const, 'not appropriate', 'with reason: not appropriate'],['rejected_continue' as const, 'too risky', 'with reason: too risky'],])('decision=%s', (decision, rejectionReason, expectedSuffix) => {- it(`persists rejection + resumes LLM with user_input phase`, async () => {+ it(`persists rejection + resumes through the tool-result sibling barrier`, async () => {await service.execAgent({...baseParams,resumeApproval: {@@ -267,21 +430,25 @@ describe('AiAgentService.execAgent - resumeApproval', () => {},});- expect(mockUpdateToolMessage).toHaveBeenCalledWith('tool-msg-1', {- content: `User reject this tool calling ${expectedSuffix}`,- });- expect(mockUpdateMessagePlugin).toHaveBeenCalledWith('tool-msg-1', {- intervention: { rejectedReason: rejectionReason, status: 'rejected' },- });+ expect(mockResolveHumanApproval).toHaveBeenCalledWith([+ {+ content: `User reject this tool calling ${expectedSuffix}`,+ id: 'tool-msg-1',+ intervention: {+ rejectedReason: rejectionReason,+ resolutionRequestId: expect.stringMatching(/^legacy_/),+ status: 'rejected',+ },+ },+ ]);expect(mockCreateOperation).toHaveBeenCalledWith(expect.objectContaining({initialContext: expect.objectContaining({payload: expect.objectContaining({- message: [{ content: '' }],parentMessageId: 'tool-msg-1',}),- phase: 'user_input',+ phase: 'tool_result',}),}),);@@ -298,9 +465,400 @@ describe('AiAgentService.execAgent - resumeApproval', () => {},});- expect(mockUpdateToolMessage).toHaveBeenCalledWith('tool-msg-1', {- content: 'User reject this tool calling without reason',+ expect(mockResolveHumanApproval).toHaveBeenCalledWith([+ {+ content: 'User reject this tool calling without reason',+ id: 'tool-msg-1',+ intervention: {+ rejectedReason: undefined,+ resolutionRequestId: expect.stringMatching(/^legacy_/),+ status: 'rejected',+ },+ },+ ]);+ });++ it('restores the claimed rows when preparation fails before the continuation starts', async () => {+ mockMessageQuery.mockRejectedValueOnce(new Error('history unavailable'));++ await expect(+ service.execAgent({+ ...baseParams,+ resumeApproval: {+ decision: 'approved',+ parentMessageId: 'tool-msg-1',+ toolCallId: 'call_xyz',+ },+ }),+ ).rejects.toThrow('history unavailable');++ const claimedResolutionRequestId = mockResolveHumanApproval.mock.calls[0][0][0].intervention+ .resolutionRequestId as string;+ expect(mockRestoreHumanApproval).toHaveBeenCalledWith([+ {+ claimedResolutionRequestId,+ id: 'tool-msg-1',+ intervention: { status: 'pending' },+ pluginState: null,+ replacePluginState: true,+ },+ ]);+ expect(mockCreateOperation).not.toHaveBeenCalled();+ });++ it('rebuilds an incomplete idle continuation instead of scheduling it without hooks', async () => {+ const approvalResolutionRequestId = '018fbd8e-7baf-7c6d-8000-000000000097';+ mockFindMessagePlugin.mockResolvedValue({+ ...pendingToolPlugin,+ intervention: { operationId: 'op-parked', status: 'pending' },+ });+ mockLoadInterventionContinuationState.mockImplementation(async (operationId: string) => ({+ metadata: {+ agentId: 'agent-1',+ agentInterventionContinuation: {+ resolutionRequestId: approvalResolutionRequestId,+ sourceOperationId: 'op-parked',+ sourceToolMessageIds: ['tool-msg-1'],+ },+ sourceMessageId: 'tool-msg-1',+ topicId: 'topic-1',+ userId: 'user-1',+ },+ operationId,+ status: 'idle',+ }));++ await service.execAgent({+ ...baseParams,+ approvalResolutionRequestId,+ approvalSourceOperationId: 'op-parked',+ resumeApproval: {+ decision: 'approved',+ parentMessageId: 'tool-msg-1',+ toolCallId: 'call_xyz',+ },+ });++ expect(mockEnsureInterventionContinuationStarted).not.toHaveBeenCalled();+ expect(mockCreateOperation).toHaveBeenCalledWith(+ expect.objectContaining({+ interventionResolution: expect.objectContaining({+ resolutionRequestId: approvalResolutionRequestId,+ }),+ operationId: expect.stringMatching(/^op_intervention_/),+ }),+ );+ });++ it('uses a non-reentrant short fence for a thread continuation without replacing the main anchor', async () => {+ const approvalResolutionRequestId = '018fbd8e-7baf-7c6d-8000-000000000095';+ const reservationId = deriveAgentInterventionContinuationOperationId({+ resolutionRequestId: approvalResolutionRequestId,+ userId: 'user-1',+ });+ mockFindMessagePlugin.mockResolvedValue({+ ...pendingToolPlugin,+ intervention: { operationId: 'op-parked', status: 'pending' },+ });++ await service.execAgent({+ ...baseParams,+ approvalResolutionRequestId,+ approvalSourceOperationId: 'op-parked',+ resumeApproval: {+ decision: 'approved',+ parentMessageId: 'tool-msg-1',+ toolCallId: 'call_xyz',+ },+ topicStartReservationId: reservationId,+ });++ expect(mockTryReserveTaskCallback).toHaveBeenCalledWith('topic-1', reservationId, {+ allowRunningOperationId: undefined,+ allowSameReservationReentry: false,+ ignoreRunningOperation: true,+ replacesOperationId: undefined,});+ expect(mockReleaseTaskCallbackReservation).toHaveBeenCalledWith('topic-1', reservationId);+ expect(mockUpdateTopicMetadata).not.toHaveBeenCalled();+ });++ it('validates a thread continuation ACK and releases only its exact fence', async () => {+ const resolutionRequestId = '018fbd8e-7baf-7c6d-8000-000000000092';+ const identity = { resolutionRequestId, userId: 'user-1' };+ const continuationOperationId = deriveAgentInterventionContinuationOperationId(identity);+ const assistantMessageId = deriveAgentInterventionContinuationMessageId(identity);+ mockFindOperationById.mockResolvedValue({+ id: continuationOperationId,+ metadata: {+ agentInterventionContinuation: {+ resolutionRequestId,+ sourceOperationId: 'op-parked',+ sourceToolMessageIds: ['tool-msg-1'],+ },+ agentInterventionDispatch: {+ deduplicationId: deriveAgentInterventionQueueDeduplicationId(continuationOperationId, 0),+ resolutionRequestId,+ state: 'scheduled',+ },+ },+ startedAt: new Date('2026-08-26T00:00:00.000Z'),+ status: 'running',+ topicId: 'topic-1',+ });+ mockFindById.mockImplementation(async (id: string) =>+ id === assistantMessageId+ ? { id, role: 'assistant', topicId: 'topic-1' }+ : id === pendingToolMessage.id+ ? pendingToolMessage+ : undefined,+ );++ await service.repairInterventionContinuationTopicAnchor({+ assistantMessageId,+ continuationOperationId,+ resolutionRequestId,+ sourceOperationId: 'op-parked',+ sourceToolMessageIds: ['tool-msg-1'],+ threadId: 'thread-1',+ topicId: 'topic-1',+ });++ expect(mockReleaseTaskCallbackReservation).toHaveBeenCalledWith(+ 'topic-1',+ continuationOperationId,+ );+ expect(mockRepairAgentInterventionContinuation).not.toHaveBeenCalled();+ expect(mockUpdateTopicMetadata).not.toHaveBeenCalled();+ });++ it('fails closed when a thread continuation sees a foreign live fence', async () => {+ const resolutionRequestId = '018fbd8e-7baf-7c6d-8000-000000000091';+ const identity = { resolutionRequestId, userId: 'user-1' };+ const continuationOperationId = deriveAgentInterventionContinuationOperationId(identity);+ const assistantMessageId = deriveAgentInterventionContinuationMessageId(identity);+ mockFindOperationById.mockResolvedValue({+ id: continuationOperationId,+ metadata: {+ agentInterventionContinuation: {+ resolutionRequestId,+ sourceOperationId: 'op-parked',+ sourceToolMessageIds: ['tool-msg-1'],+ },+ agentInterventionDispatch: {+ deduplicationId: deriveAgentInterventionQueueDeduplicationId(continuationOperationId, 0),+ resolutionRequestId,+ state: 'scheduled',+ },+ },+ status: 'running',+ topicId: 'topic-1',+ });+ mockFindById.mockImplementation(async (id: string) =>+ id === assistantMessageId+ ? { id, role: 'assistant', topicId: 'topic-1' }+ : pendingToolMessage,+ );+ mockReleaseTaskCallbackReservation.mockResolvedValueOnce('foreign');++ await expect(+ service.repairInterventionContinuationTopicAnchor({+ assistantMessageId,+ continuationOperationId,+ resolutionRequestId,+ sourceOperationId: 'op-parked',+ sourceToolMessageIds: ['tool-msg-1'],+ threadId: 'thread-1',+ topicId: 'topic-1',+ }),+ ).rejects.toThrow(/foreign reservation/);++ expect(mockRepairAgentInterventionContinuation).not.toHaveBeenCalled();+ });++ it('keeps a concurrent same-request thread initializer out of createOperation', async () => {+ vi.useFakeTimers();+ const approvalResolutionRequestId = '018fbd8e-7baf-7c6d-8000-000000000094';+ const reservationId = deriveAgentInterventionContinuationOperationId({+ resolutionRequestId: approvalResolutionRequestId,+ userId: 'user-1',+ });+ let finishInitializer!: (result: {+ autoStarted: boolean;+ operationId: string;+ success: boolean;+ }) => void;+ let markInitializerStarted!: () => void;+ const initializerStarted = new Promise<void>((resolve) => {+ markInitializerStarted = resolve;+ });+ mockCreateOperation.mockImplementationOnce(() => {+ markInitializerStarted();+ return new Promise((resolve) => {+ finishInitializer = resolve;+ });+ });+ mockFindMessagePlugin.mockResolvedValue({+ ...pendingToolPlugin,+ intervention: { operationId: 'op-parked', status: 'pending' },+ });+ mockTryReserveTaskCallback.mockResolvedValueOnce(true).mockResolvedValue(false);+ const input = {+ ...baseParams,+ approvalResolutionRequestId,+ approvalSourceOperationId: 'op-parked',+ resumeApproval: {+ decision: 'approved' as const,+ parentMessageId: 'tool-msg-1',+ toolCallId: 'call_xyz',+ },+ topicStartReservationId: reservationId,+ };++ const initializer = service.execAgent(input);+ let initializerFinished = false;+ try {+ await initializerStarted;+ expect(mockCreateOperation).toHaveBeenCalledTimes(1);+ const concurrentRetry = service.execAgent(input);+ const retryExpectation = expect(concurrentRetry).rejects.toThrow(/remained busy/);+ await vi.runAllTimersAsync();+ await retryExpectation;+ finishInitializer({ autoStarted: true, operationId: 'op-continuation', success: true });+ initializerFinished = true;+ await expect(initializer).resolves.toMatchObject({ success: true });++ expect(mockCreateOperation).toHaveBeenCalledTimes(1);+ expect(mockRestoreHumanApproval).not.toHaveBeenCalled();+ } finally {+ if (!initializerFinished && finishInitializer) {+ finishInitializer({ autoStarted: true, operationId: 'op-continuation', success: true });+ await initializer.catch(() => undefined);+ }+ vi.useRealTimers();+ }+ });++ it('keeps a concurrent same-request main initializer out of createOperation', async () => {+ vi.useFakeTimers();+ const approvalResolutionRequestId = '018fbd8e-7baf-7c6d-8000-000000000093';+ let finishInitializer!: (result: {+ autoStarted: boolean;+ operationId: string;+ success: boolean;+ }) => void;+ let markInitializerStarted!: () => void;+ const initializerStarted = new Promise<void>((resolve) => {+ markInitializerStarted = resolve;+ });+ mockCreateOperation.mockImplementationOnce(() => {+ markInitializerStarted();+ return new Promise((resolve) => {+ finishInitializer = resolve;+ });+ });+ mockFindMessagePlugin.mockResolvedValue({+ ...pendingToolPlugin,+ intervention: { operationId: 'op-parked', status: 'pending' },+ });+ mockFindById.mockImplementation(async (id: string) =>+ id === pendingToolMessage.id ? { ...pendingToolMessage, threadId: null } : undefined,+ );+ mockTryReserveTaskCallback.mockResolvedValueOnce(true).mockResolvedValue(false);+ const input = {+ ...baseParams,+ appContext: { sessionId: 'session-1', topicId: 'topic-1' },+ approvalResolutionRequestId,+ approvalSourceOperationId: 'op-parked',+ resumeApproval: {+ decision: 'approved' as const,+ parentMessageId: 'tool-msg-1',+ toolCallId: 'call_xyz',+ },+ };++ const initializer = service.execAgent(input);+ let initializerFinished = false;+ try {+ await initializerStarted;+ const concurrentRetry = service.execAgent(input);+ const retryExpectation = expect(concurrentRetry).rejects.toThrow(/remained busy/);+ await vi.runAllTimersAsync();+ await retryExpectation;+ finishInitializer({ autoStarted: true, operationId: 'op-continuation', success: true });+ initializerFinished = true;+ await expect(initializer).resolves.toMatchObject({ success: true });++ expect(mockCreateOperation).toHaveBeenCalledTimes(1);+ expect(mockRestoreHumanApproval).not.toHaveBeenCalled();+ } finally {+ if (!initializerFinished && finishInitializer) {+ finishInitializer({ autoStarted: true, operationId: 'op-continuation', success: true });+ await initializer.catch(() => undefined);+ }+ vi.useRealTimers();+ }+ });++ it('keeps a generic claim through a busy concurrent retry and rebuilds after release', async () => {+ vi.useFakeTimers();+ const approvalResolutionRequestId = '018fbd8e-7baf-7c6d-8000-000000000096';+ mockFindMessagePlugin.mockResolvedValue({+ ...pendingToolPlugin,+ intervention: { operationId: 'op-parked', status: 'pending' },+ });+ let rejectFirstHistory!: (error: Error) => void;+ let markFirstHistoryStarted!: () => void;+ const firstHistoryStarted = new Promise<void>((resolve) => {+ markFirstHistoryStarted = resolve;+ });+ const firstHistory = new Promise<never>((_, reject) => {+ rejectFirstHistory = reject;+ });+ mockResolveHumanApproval.mockResolvedValueOnce('applied').mockResolvedValueOnce('idempotent');+ mockTryReserveTaskCallback.mockResolvedValueOnce(true).mockResolvedValue(false);+ mockMessageQuery+ .mockImplementationOnce(() => {+ markFirstHistoryStarted();+ return firstHistory;+ })+ .mockResolvedValueOnce([{ content: 'hi', id: 'history-1', role: 'user' }]);+ const input = {+ ...baseParams,+ approvalResolutionRequestId,+ approvalSourceOperationId: 'op-parked',+ resumeApproval: {+ decision: 'approved' as const,+ parentMessageId: 'tool-msg-1',+ toolCallId: 'call_xyz',+ },+ };++ const appliedAttempt = service.execAgent(input);+ let firstSettled = false;+ try {+ await firstHistoryStarted;+ const busyRetry = service.execAgent(input);+ const busyExpectation = expect(busyRetry).rejects.toThrow(/remained busy/);+ await vi.runAllTimersAsync();+ await busyExpectation;++ rejectFirstHistory(new Error('first attempt crashed before ready'));+ await expect(appliedAttempt).rejects.toThrow('first attempt crashed before ready');+ firstSettled = true;+ expect(mockRestoreHumanApproval).not.toHaveBeenCalled();++ mockTryReserveTaskCallback.mockResolvedValue(true);+ await expect(service.execAgent(input)).resolves.toMatchObject({ success: true });+ expect(mockCreateOperation).toHaveBeenCalledTimes(1);+ expect(mockRestoreHumanApproval).not.toHaveBeenCalled();+ } finally {+ if (!firstSettled) {+ rejectFirstHistory(new Error('test cleanup'));+ await appliedAttempt.catch(() => undefined);+ }+ vi.useRealTimers();+ }});describe('validation guards', () => {@@ -387,21 +945,43 @@ describe('AiAgentService.execAgent - resumeApproval', () => {id,parentId: 'assistant-new',}));+ mockFindMessagePlugin.mockResolvedValue({+ ...pendingToolPlugin,+ intervention: {+ batchId: 'batch-parked',+ operationId: 'op-parked',+ status: 'pending',+ },+ });+ mockFindOperationById.mockResolvedValue({ id: 'op-parked', status: 'waiting_for_human' });+ mockInterruptOperation.mockResolvedValue(true);+ mockRecordCompletion.mockResolvedValue(true);await service.execAgent({...baseParams,+ approvalSourceOperationId: 'op-parked',resumeApprovals: [{ decision: 'approved', parentMessageId: 'tool-msg-1', toolCallId: 'call_xyz' },{ decision: 'approved', parentMessageId: 'tool-msg-2', toolCallId: 'call_xyz' },],});- expect(mockUpdateMessagePlugin).toHaveBeenCalledWith('tool-msg-1', {- intervention: { status: 'approved' },- });- expect(mockUpdateMessagePlugin).toHaveBeenCalledWith('tool-msg-2', {- intervention: { status: 'approved' },- });+ expect(mockResolveHumanApproval).toHaveBeenCalledWith([+ {+ id: 'tool-msg-1',+ intervention: {+ resolutionRequestId: expect.stringMatching(/^legacy_/),+ status: 'approved',+ },+ },+ {+ id: 'tool-msg-2',+ intervention: {+ resolutionRequestId: expect.stringMatching(/^legacy_/),+ status: 'approved',+ },+ },+ ]);expect(mockCreateOperation).toHaveBeenCalledWith(expect.objectContaining({initialContext: expect.objectContaining({@@ -410,6 +990,11 @@ describe('AiAgentService.execAgent - resumeApproval', () => {}),}),);+ expect(mockInterruptOperation).toHaveBeenCalledWith('op-parked');+ expect(mockRecordCompletion).toHaveBeenCalledWith(+ 'op-parked',+ expect.objectContaining({ completionReason: 'done', status: 'done' }),+ );});});});@@ -427,9 +1012,31 @@ describe('AiAgentService.stopPendingApproval', () => {beforeEach(() => {vi.clearAllMocks();mockFindById.mockImplementation(async (id: string) => ({ ...pendingToolMessage, id }));+ mockFindMessagePlugin.mockResolvedValue({+ intervention: {+ batchId: 'batch-1',+ operationId: 'op-parked-1',+ status: 'pending',+ },+ });+ mockListMessagePluginsByTopic.mockResolvedValue(+ ['tool-msg-1', 'tool-msg-2'].map((id) => ({+ id,+ intervention: {+ batchId: 'batch-1',+ operationId: 'op-parked-1',+ status: 'pending',+ },+ })),+ );+ mockResolveHumanApproval.mockResolvedValue([]);mockUpdateMessagePlugin.mockResolvedValue(undefined);mockUpdateToolMessage.mockResolvedValue(undefined);- mockFindLatestParkedOperationId.mockResolvedValue('op-parked-1');+ mockFindOperationById.mockResolvedValue({+ id: 'op-parked-1',+ status: 'waiting_for_human',+ topicId: 'topic-1',+ });mockRecordCompletion.mockResolvedValue(undefined);mockInterruptOperation.mockResolvedValue(true);service = new AiAgentService({} as unknown as LobeChatDatabase, 'user-1');@@ -437,6 +1044,8 @@ describe('AiAgentService.stopPendingApproval', () => {it('settles every pending row in place and retires the parked operation', async () => {const result = await service.stopPendingApproval({+ batchId: 'batch-1',+ operationId: 'op-parked-1',toolMessageIds: ['tool-msg-1', 'tool-msg-2'],topicId: 'topic-1',});@@ -444,17 +1053,21 @@ describe('AiAgentService.stopPendingApproval', () => {// In place: the approval pause already wrote these rows. Inserting fresh// aborted rows would duplicate every tool AND leave the originals pending,// which is what keeps the approval cards on screen after a stop.- for (const id of ['tool-msg-1', 'tool-msg-2']) {- expect(mockUpdateToolMessage).toHaveBeenCalledWith(id, {+ expect(mockResolveHumanApproval).toHaveBeenCalledWith([+ {content: 'Tool execution was aborted by user.',- });- expect(mockUpdateMessagePlugin).toHaveBeenCalledWith(id, {+ id: 'tool-msg-1',intervention: { status: 'aborted' },- });- }+ },+ {+ content: 'Tool execution was aborted by user.',+ id: 'tool-msg-2',+ intervention: { status: 'aborted' },+ },+ ]);- // The parked op is resolved from the topic — the client has lost its id by- // the time the user decides to stop.+ // The exact parked operation and sealed batch identity are validated; a+ // newer operation in the same topic can never be guessed and interrupted.expect(mockInterruptOperation).toHaveBeenCalledWith('op-parked-1');expect(mockRecordCompletion).toHaveBeenCalledWith('op-parked-1',@@ -463,8 +1076,43 @@ describe('AiAgentService.stopPendingApproval', () => {expect(result.settledToolMessageIds).toEqual(['tool-msg-1', 'tool-msg-2']);});+ it('stamps the generic resolution id on every stopped row', async () => {+ const approvalResolutionRequestId = '018fbd8e-7baf-7c6d-8000-000000000098';++ await service.stopPendingApproval({+ approvalResolutionRequestId,+ batchId: 'batch-1',+ operationId: 'op-parked-1',+ toolMessageIds: ['tool-msg-1', 'tool-msg-2'],+ topicId: 'topic-1',+ });++ expect(mockResolveHumanApproval).toHaveBeenCalledWith(+ expect.arrayContaining([+ expect.objectContaining({+ intervention: { resolutionRequestId: approvalResolutionRequestId, status: 'aborted' },+ }),+ ]),+ );+ });+it('nothing runs and the model is not continued', async () => {- await service.stopPendingApproval({ toolMessageIds: ['tool-msg-1'], topicId: 'topic-1' });+ mockListMessagePluginsByTopic.mockResolvedValue([+ {+ id: 'tool-msg-1',+ intervention: {+ batchId: 'batch-1',+ operationId: 'op-parked-1',+ status: 'pending',+ },+ },+ ]);+ await service.stopPendingApproval({+ batchId: 'batch-1',+ operationId: 'op-parked-1',+ toolMessageIds: ['tool-msg-1'],+ topicId: 'topic-1',+ });// A stop is not a rejection: a rejection resumes the model so it can// respond, a stop ends the turn outright.@@ -480,6 +1128,8 @@ describe('AiAgentService.stopPendingApproval', () => {await expect(service.stopPendingApproval({+ batchId: 'batch-1',+ operationId: 'op-parked-1',toolMessageIds: ['tool-msg-1', 'tool-msg-2'],topicId: 'topic-1',}),@@ -487,7 +1137,7 @@ describe('AiAgentService.stopPendingApproval', () => {// Validation runs before any write, so a refused stop cannot half-clear the// batch and strand the rest against a run that is already gone.- expect(mockUpdateMessagePlugin).not.toHaveBeenCalled();+ expect(mockResolveHumanApproval).not.toHaveBeenCalled();expect(mockInterruptOperation).not.toHaveBeenCalled();});});diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeToolResult.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeToolResult.test.tsindex 9677b96525a..7322cc0ff0b 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeToolResult.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeToolResult.test.ts@@ -10,6 +10,9 @@ const {mockFindMessagePlugin,mockMessageCreate,mockMessageQuery,+ mockLoadInterventionContinuationState,+ mockResolveHumanApproval,+ mockRestoreHumanApproval,mockUpdateMessagePlugin,mockUpdatePluginState,mockUpdateToolMessage,@@ -19,6 +22,9 @@ const {mockFindMessagePlugin: vi.fn(),mockMessageCreate: vi.fn(),mockMessageQuery: vi.fn(),+ mockLoadInterventionContinuationState: vi.fn(),+ mockResolveHumanApproval: vi.fn(),+ mockRestoreHumanApproval: vi.fn(),mockUpdateMessagePlugin: vi.fn(),mockUpdatePluginState: vi.fn(),mockUpdateToolMessage: vi.fn(),@@ -31,6 +37,7 @@ vi.mock('@/libs/trusted-client', () => ({}));vi.mock('@/database/models/message', () => ({+ HumanApprovalAlreadyResolvedError: class HumanApprovalAlreadyResolvedError extends Error {},MessageModel: vi.fn().mockImplementation(() => ({create: mockMessageCreate,getLatestNonToolMessageId: vi.fn().mockResolvedValue(undefined),@@ -38,6 +45,8 @@ vi.mock('@/database/models/message', () => ({findById: mockFindById,findMessagePlugin: mockFindMessagePlugin,query: mockMessageQuery,+ resolveHumanApproval: mockResolveHumanApproval,+ restoreHumanApproval: mockRestoreHumanApproval,update: vi.fn().mockResolvedValue({}),updateMessagePlugin: mockUpdateMessagePlugin,updatePluginState: mockUpdatePluginState,@@ -100,6 +109,8 @@ vi.mock('@/database/models/userMemory/persona', () => ({vi.mock('@/server/services/agentRuntime', () => ({AgentRuntimeService: vi.fn().mockImplementation(() => ({createOperation: mockCreateOperation,+ ensureInterventionContinuationStarted: vi.fn().mockResolvedValue('scheduled'),+ loadInterventionContinuationState: mockLoadInterventionContinuationState,})),}));@@ -164,6 +175,7 @@ describe('AiAgentService.execAgent - resumeToolResult', () => {apiName: 'askUserQuestion',arguments: '{"question":"favorite color?"}',identifier: 'lobe-agent',+ intervention: { status: 'pending' },toolCallId: 'call_ask',type: 'builtin',};@@ -176,10 +188,15 @@ describe('AiAgentService.execAgent - resumeToolResult', () => {operationId: 'op-123',success: true,});- mockFindById.mockResolvedValue(pendingToolMessage);+ mockFindById.mockImplementation(async (id: string) =>+ id === pendingToolMessage.id ? pendingToolMessage : undefined,+ );mockFindMessagePlugin.mockResolvedValue(pendingToolPlugin);mockMessageQuery.mockResolvedValue([{ content: 'hi', id: 'history-1', role: 'user' }]);mockMessageCreate.mockResolvedValue({ id: 'assistant-msg-new' });+ mockResolveHumanApproval.mockResolvedValue('applied');+ mockLoadInterventionContinuationState.mockResolvedValue(null);+ mockRestoreHumanApproval.mockResolvedValue(undefined);mockUpdateMessagePlugin.mockResolvedValue(undefined);mockUpdatePluginState.mockResolvedValue(undefined);mockUpdateToolMessage.mockResolvedValue(undefined);@@ -203,14 +220,18 @@ describe('AiAgentService.execAgent - resumeToolResult', () => {},});- // The human answer becomes the tool message's result content.- expect(mockUpdateToolMessage).toHaveBeenCalledWith('tool-msg-1', {- content: 'My favorite color is blue',- });- // Intervention is marked approved so the pending state clears.- expect(mockUpdateMessagePlugin).toHaveBeenCalledWith('tool-msg-1', {- intervention: { status: 'approved' },- });+ // Content, intervention, and optional form state share one row-locking+ // first-winner boundary.+ expect(mockResolveHumanApproval).toHaveBeenCalledWith([+ expect.objectContaining({+ content: 'My favorite color is blue',+ id: 'tool-msg-1',+ intervention: {+ resolutionRequestId: expect.stringMatching(/^legacy_/),+ status: 'approved',+ },+ }),+ ]);// Resumes from `tool_result` — NOT `human_approved_tool` (which would// re-dispatch the tool and overwrite the answer).@@ -240,9 +261,11 @@ describe('AiAgentService.execAgent - resumeToolResult', () => {},});- expect(mockUpdatePluginState).toHaveBeenCalledWith('tool-msg-1', {- askUserAnswers: { 'favorite color?': 'blue' },- });+ expect(mockResolveHumanApproval).toHaveBeenCalledWith([+ expect.objectContaining({+ pluginState: { askUserAnswers: { 'favorite color?': 'blue' } },+ }),+ ]);});it('does not persist pluginState when omitted', async () => {@@ -255,7 +278,9 @@ describe('AiAgentService.execAgent - resumeToolResult', () => {},});- expect(mockUpdatePluginState).not.toHaveBeenCalled();+ expect(mockResolveHumanApproval).toHaveBeenCalledWith([+ expect.objectContaining({ pluginState: undefined }),+ ]);});describe('validation guards', () => {diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.spineAnchor.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.spineAnchor.test.tsindex d87ab50e696..0c706ba98fe 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.spineAnchor.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.spineAnchor.test.ts@@ -203,6 +203,7 @@ describe('AiAgentService.execAgent - user turn spine anchoring', () => {expect(mockGetLatestNonToolMessageId).not.toHaveBeenCalled();expect(mockTryReserve).toHaveBeenCalledWith('topic-1', expect.stringMatching(/^agent-start-/), {allowRunningOperationId: undefined,+ allowSameReservationReentry: true,ignoreRunningOperation: undefined,replacesOperationId: undefined,});diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex 798e527481f..a17181e1334 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -100,6 +100,12 @@ import { TRPCError } from '@trpc/server';import debug from 'debug';import type { ModelAbilities } from 'model-bank';+import {+ deriveAgentInterventionContinuationMessageId,+ deriveAgentInterventionContinuationOperationId,+ deriveAgentInterventionQueueDeduplicationId,+ matchesAgentInterventionContinuationProvenance,+} from '@/business/server/agent-run/agentInterventionIdentity';import { AgentModel } from '@/database/models/agent';import { AgentOperationModel } from '@/database/models/agentOperation';import { AgentSkillModel } from '@/database/models/agentSkill';@@ -111,7 +117,11 @@ import { ConnectorToolModel } from '@/database/models/connectorTool';import { DeviceModel } from '@/database/models/device';import { ExpertiseModel } from '@/database/models/expertise';import { FileModel } from '@/database/models/file';-import { MessageModel } from '@/database/models/message';+import {+ HumanApprovalAlreadyResolvedError,+ type HumanApprovalResolution,+ MessageModel,+} from '@/database/models/message';import { PluginModel } from '@/database/models/plugin';import { TaskModel } from '@/database/models/task';import { ThreadModel } from '@/database/models/thread';@@ -387,6 +397,18 @@ const buildBotConversationGroupContext = (interface InternalExecAgentParams extends ExecAgentParams {/** Additional plugin IDs to inject (e.g., task tool during task execution) */additionalPluginIds?: string[];+ /**+ * Server-authored generic intervention claim id. When present, the message+ * claim stores this exact id so a retry after dispatch-but-before-publish can+ * prove the runtime side effect already happened. Never client-passable.+ */+ approvalResolutionRequestId?: string;+ /**+ * Server-authored parked operation expected on every claimed tool row. Used+ * to retire its Redis/agent_operations lifecycle only after the replacement+ * continuation has been scheduled. Never client-passable.+ */+ approvalSourceOperationId?: string;/** Bot context for topic metadata (platform, applicationId, platformThreadId) */botContext?: ChatTopicBotContext;/** Bot platform context for injecting platform capabilities (e.g. markdown support) */@@ -508,8 +530,10 @@ interface InternalExecAgentParams extends ExecAgentParams {*/resumeToolResult?: {content: string;+ outcome?: 'skipped' | 'submitted';parentMessageId: string;pluginState?: Record<string, unknown>;+ rejectionReason?: string;toolCallId: string;};/**@@ -1348,19 +1372,43 @@ export class AiAgentService {*/async execAgent(params: InternalExecAgentParams): Promise<ExecAgentResult> {const topicId = params.appContext?.topicId;+ const interventionReservationId = params.approvalResolutionRequestId+ ? deriveAgentInterventionContinuationOperationId({+ resolutionRequestId: params.approvalResolutionRequestId,+ userId: this.userId,+ workspaceId: this.workspaceId,+ })+ : undefined;+ if (+ interventionReservationId &&+ params.topicStartReservationId &&+ params.topicStartReservationId !== interventionReservationId+ ) {+ throw new Error('Intervention continuation reservation identity conflict');+ }+ const reservationId =+ interventionReservationId ?? params.topicStartReservationId ?? `agent-start-${nanoid()}`;+ const isInterventionThreadStart = Boolean(+ topicId &&+ params.appContext?.threadId &&+ interventionReservationId &&+ params.approvalResolutionRequestId,+ );// Thread runs are isolated under an explicit parent message and do not// advance the topic's main spine. They may start while their parent// operation owns `runningOperation` (for example callAgent/callSubAgent),// so making them wait for the topic-start claim deadlocks the child start.- if (!topicId || params.appContext?.threadId) {- return this.execAgentWithReservation(params);+ if (!topicId || (params.appContext?.threadId && !isInterventionThreadStart)) {+ return this.execAgentWithApprovalRollback(params);}- const reservationId = params.topicStartReservationId ?? `agent-start-${nanoid()}`;const reserved = await acquireTopicStartReservation({- replacesOperationId: params.replacesOperationId,+ allowSameReservationReentry: !params.approvalResolutionRequestId,+ replacesOperationId: isInterventionThreadStart ? undefined : params.replacesOperationId,allowRunningOperationId: params.topicStartOwnerOperationId,- ignoreRunningOperation: params.interactiveStart,+ // A thread continuation shares the topic row but never owns/replaces its+ // main runningOperation anchor. It uses only the short initializer fence.+ ignoreRunningOperation: isInterventionThreadStart || params.interactiveStart,reservationId,topicId,topicModel: this.topicModel,@@ -1371,14 +1419,51 @@ export class AiAgentService {}try {- return await this.execAgentWithReservation(params);+ return await this.execAgentWithApprovalRollback(params);} finally {await this.topicModel.releaseTaskCallbackReservation(topicId, reservationId);}}+ /**+ * A human decision is claimed before the rest of operation preparation reads+ * message history. Keep its rollback guard outside the large preparation+ * routine so every throw and every early return before createOperation starts+ * restores the exact pending rows, not only queue-start failures.+ */+ private async execAgentWithApprovalRollback(+ params: InternalExecAgentParams,+ ): Promise<ExecAgentResult> {+ const approvalClaim = {+ continuationPrepared: false,+ continuationStarted: false,+ rollbackSnapshot: [] as HumanApprovalResolution[],+ };++ try {+ return await this.execAgentWithReservation(params, approvalClaim);+ } finally {+ if (+ !approvalClaim.continuationPrepared &&+ !approvalClaim.continuationStarted &&+ approvalClaim.rollbackSnapshot.length > 0+ ) {+ await this.messageModel.restoreHumanApproval(approvalClaim.rollbackSnapshot);+ log(+ 'execAgent: restored %d approval rows before continuation startup',+ approvalClaim.rollbackSnapshot.length,+ );+ }+ }+ }+private async execAgentWithReservation(params: InternalExecAgentParams,+ approvalClaim: {+ continuationPrepared: boolean;+ continuationStarted: boolean;+ rollbackSnapshot: HumanApprovalResolution[];+ },): Promise<ExecAgentResult> {const {additionalPluginIds,@@ -1425,6 +1510,8 @@ export class AiAgentService {resumeApproval,resumeApprovals,resumeToolResult,+ approvalResolutionRequestId: providedApprovalResolutionRequestId,+ approvalSourceOperationId: providedApprovalSourceOperationId,selectedToolIds,mentionedAgents,suppressUserMessage,@@ -1436,7 +1523,21 @@ export class AiAgentService {// parentMessageId), and a replayed id there would collide with the row the// original send already created — so those paths drop the ids defensively// rather than trusting every caller to omit them.- const isResumeLike = !!resume || !!resumeApproval || !!resumeToolResult || !!parentMessageId;+ const interventionResumeCount = [resumeApproval, resumeApprovals, resumeToolResult].filter(+ Boolean,+ ).length;+ if (interventionResumeCount > 1) {+ throw new Error(+ 'Only one of resumeApproval, resumeApprovals, or resumeToolResult may be provided',+ );+ }++ const isResumeLike =+ !!resume ||+ !!resumeApproval ||+ !!resumeApprovals?.length ||+ !!resumeToolResult ||+ !!parentMessageId;const clientIds = isResumeLike ? undefined : params.clientIds;// Validate that either agentId or slug is provided@@ -1839,12 +1940,16 @@ export class AiAgentService {}[] = [];/** Assistant that emitted this batch — the pending tool rows' shared parent. */let approvalOwnerAssistantId: string | undefined;+ let approvalResolutionRequestId: string | undefined;+ let approvalSourceOperationId: string | undefined;+ let approvalSourceToolMessageIds: string[] = [];// Load and validate EVERY decision before applying any of them. The apply// step writes per entry, so validating inline would leave a rejected batch// half-persisted — some tools already marked approved with no run to// execute them.const validatedDecisions: {+ alreadyClaimed: boolean;entry: (typeof approvalDecisions)[number];plugin: MessagePluginItem;targetMessage: NonNullable<typeof resumeParentMessage>;@@ -1884,8 +1989,16 @@ export class AiAgentService {`stored=${plugin.toolCallId}, requested=${decisionEntry.toolCallId}`,);}+ const expectedStatus = decisionEntry.decision === 'approved' ? 'approved' : 'rejected';+ const alreadyClaimed =+ plugin.intervention?.status === expectedStatus &&+ Boolean(providedApprovalResolutionRequestId) &&+ plugin.intervention.resolutionRequestId === providedApprovalResolutionRequestId;+ if (plugin.intervention?.status !== 'pending' && !alreadyClaimed) {+ throw new HumanApprovalAlreadyResolvedError(decisionEntry.parentMessageId);+ }- validatedDecisions.push({ entry: decisionEntry, plugin, targetMessage });+ validatedDecisions.push({ alreadyClaimed, entry: decisionEntry, plugin, targetMessage });}// A batch resume executes every approved tool as ONE `call_tools_batch`@@ -1906,31 +2019,81 @@ export class AiAgentService {);}+ if (validatedDecisions.length > 0) {+ const sourceOperationIds = new Set(+ validatedDecisions+ .map(({ plugin }) => plugin.intervention?.operationId)+ .filter((id): id is string => typeof id === 'string' && !!id),+ );+ if (+ sourceOperationIds.size > 1 ||+ (providedApprovalSourceOperationId &&+ (sourceOperationIds.size !== 1 ||+ !sourceOperationIds.has(providedApprovalSourceOperationId)))+ ) {+ throw new Error('Approval targets do not match the authoritative parked operation');+ }+ approvalSourceOperationId = providedApprovalSourceOperationId ?? [...sourceOperationIds][0];+ approvalSourceToolMessageIds = validatedDecisions.map(({ entry }) => entry.parentMessageId);+ approvalResolutionRequestId = providedApprovalResolutionRequestId ?? `legacy_${nanoid()}`;+ const unclaimedDecisions = validatedDecisions.filter(({ alreadyClaimed }) => !alreadyClaimed);+ const approvalRollbackSnapshot = unclaimedDecisions.map(({ plugin, targetMessage }) => ({+ claimedResolutionRequestId: approvalResolutionRequestId,+ ...(typeof targetMessage.content === 'string' ? { content: targetMessage.content } : {}),+ id: targetMessage.id,+ intervention: (plugin.intervention ?? { status: 'pending' }) as Record<string, unknown>,+ pluginState: (plugin.state ?? null) as Record<string, unknown> | null,+ replacePluginState: true,+ }));++ // Shared exactly-once boundary for Web, Mobile, Stop, and signed system+ // actions. All rows are locked and checked before the first write.+ if (unclaimedDecisions.length > 0) {+ const claimState = await this.messageModel.resolveHumanApproval(+ unclaimedDecisions.map(({ entry }) => {+ if (entry.decision === 'approved') {+ return {+ id: entry.parentMessageId,+ intervention: {+ resolutionRequestId: approvalResolutionRequestId,+ status: 'approved',+ },+ };+ }+ return {+ content: entry.rejectionReason+ ? `User reject this tool calling with reason: ${entry.rejectionReason}`+ : 'User reject this tool calling without reason',+ id: entry.parentMessageId,+ intervention: {+ rejectedReason: entry.rejectionReason,+ resolutionRequestId: approvalResolutionRequestId,+ status: 'rejected',+ },+ };+ }),+ );+ if (claimState === 'applied') {+ approvalClaim.rollbackSnapshot = approvalRollbackSnapshot;+ }+ }+ if (providedApprovalResolutionRequestId) {+ // A generic durable claim is recovered by this same request id. Never+ // locally reopen its source rows: a concurrent reentrant same-id call+ // may already have created the deterministic assistant/op/state.+ approvalClaim.continuationPrepared = true;+ }+ }+for (const { entry: decisionEntry, plugin, targetMessage } of validatedDecisions) {- const { decision, rejectionReason } = decisionEntry;+ const { decision } = decisionEntry;if (decision === 'approved') {- await this.messageModel.updateMessagePlugin(decisionEntry.parentMessageId, {- intervention: { status: 'approved' },- });approvedToolEntries.push({createdAt: targetMessage.createdAt,plugin,toolMessageId: decisionEntry.parentMessageId,});approvalOwnerAssistantId ??= targetMessage.parentId ?? undefined;- } else {- // rejected / rejected_continue both write the same rejection content- // + intervention state. The difference surfaces later in how the new- // op's initial state/context are configured (halt vs. continue LLM).- const rejectionContent = rejectionReason- ? `User reject this tool calling with reason: ${rejectionReason}`- : 'User reject this tool calling without reason';- await this.messageModel.updateToolMessage(decisionEntry.parentMessageId, {- content: rejectionContent,- });- await this.messageModel.updateMessagePlugin(decisionEntry.parentMessageId, {- intervention: { rejectedReason: rejectionReason, status: 'rejected' },- });}// Kept for the single-decision resume context at 16b, which reads the@@ -1998,18 +2161,67 @@ export class AiAgentService {`stored=${resumeToolResultPlugin.toolCallId}, requested=${resumeToolResult.toolCallId}`,);}+ const skipped = resumeToolResult.outcome === 'skipped';+ const expectedToolResultStatus = skipped ? 'rejected' : 'approved';+ const alreadyClaimed =+ resumeToolResultPlugin.intervention?.status === expectedToolResultStatus &&+ Boolean(providedApprovalResolutionRequestId) &&+ resumeToolResultPlugin.intervention.resolutionRequestId ===+ providedApprovalResolutionRequestId &&+ (!skipped || resumeToolResultPlugin.intervention.skipped === true);+ if (resumeToolResultPlugin.intervention?.status !== 'pending' && !alreadyClaimed) {+ throw new HumanApprovalAlreadyResolvedError(resumeToolResult.parentMessageId);+ }+ const toolResultSourceOperationId = resumeToolResultPlugin.intervention?.operationId;+ if (+ providedApprovalSourceOperationId &&+ toolResultSourceOperationId !== providedApprovalSourceOperationId+ ) {+ throw new Error('Approval target does not match the authoritative parked operation');+ }+ approvalSourceOperationId =+ providedApprovalSourceOperationId ?? toolResultSourceOperationId ?? undefined;+ approvalSourceToolMessageIds = [resumeToolResult.parentMessageId];- await this.messageModel.updateToolMessage(resumeToolResult.parentMessageId, {- content: resumeToolResult.content,- });- await this.messageModel.updateMessagePlugin(resumeToolResult.parentMessageId, {- intervention: { status: 'approved' },- });- if (resumeToolResult.pluginState) {- await this.messageModel.updatePluginState(- resumeToolResult.parentMessageId,- resumeToolResult.pluginState,- );+ approvalResolutionRequestId = providedApprovalResolutionRequestId ?? `legacy_${nanoid()}`;+ const approvalRollbackSnapshot = alreadyClaimed+ ? []+ : [+ {+ claimedResolutionRequestId: approvalResolutionRequestId,+ ...(typeof resumeParentMessage.content === 'string'+ ? { content: resumeParentMessage.content }+ : {}),+ id: resumeToolResult.parentMessageId,+ intervention: (resumeToolResultPlugin.intervention ?? {+ status: 'pending',+ }) as Record<string, unknown>,+ pluginState: (resumeToolResultPlugin.state ?? null) as Record<string, unknown> | null,+ replacePluginState: true,+ },+ ];+ if (!alreadyClaimed) {+ const claimState = await this.messageModel.resolveHumanApproval([+ {+ content: resumeToolResult.content,+ id: resumeToolResult.parentMessageId,+ intervention: skipped+ ? {+ rejectedReason: resumeToolResult.rejectionReason,+ resolutionRequestId: approvalResolutionRequestId,+ skipped: true,+ status: 'rejected',+ }+ : { resolutionRequestId: approvalResolutionRequestId, status: 'approved' },+ pluginState: resumeToolResult.pluginState,+ },+ ]);+ if (claimState === 'applied') {+ approvalClaim.rollbackSnapshot = approvalRollbackSnapshot;+ }+ }+ if (providedApprovalResolutionRequestId) {+ approvalClaim.continuationPrepared = true;}log(@@ -2021,6 +2233,111 @@ export class AiAgentService {// 3. Handle topic creation: if no topicId provided, create a new topic; otherwise reuse existinglet topicId = appContext?.topicId;+ const continuationIdentity = providedApprovalResolutionRequestId+ ? {+ resolutionRequestId: providedApprovalResolutionRequestId,+ userId: this.userId,+ workspaceId: this.workspaceId,+ }+ : undefined;+ const continuationOperationId = continuationIdentity+ ? deriveAgentInterventionContinuationOperationId(continuationIdentity)+ : undefined;+ const continuationAssistantId = continuationIdentity+ ? deriveAgentInterventionContinuationMessageId(continuationIdentity)+ : undefined;++ // This check runs *inside* the topic-start reservation. Two same-request+ // callers may both probe before the first claim is visible, but only the+ // winner reaches createOperation; the follower observes and reuses its+ // deterministic state here instead of overwriting it. Idle state is+ // explicitly requeued from its saved initialContext; operation+step locks+ // de-duplicate concurrent queue delivery.+ if (+ continuationOperationId &&+ continuationAssistantId &&+ providedApprovalResolutionRequestId &&+ approvalSourceOperationId &&+ topicId+ ) {+ const existingState =+ await this.agentRuntimeService.loadInterventionContinuationState(continuationOperationId);+ const preparation = existingState?.metadata?.agentInterventionPreparation as+ { resolutionRequestId?: unknown; state?: unknown } | undefined;+ if (+ existingState &&+ preparation?.state === 'ready' &&+ preparation.resolutionRequestId === providedApprovalResolutionRequestId+ ) {+ const existingOperation = await this.agentOperationModel.findById(continuationOperationId);+ const expectedProvenance = {+ resolutionRequestId: providedApprovalResolutionRequestId,+ sourceOperationId: approvalSourceOperationId,+ sourceToolMessageIds: [...approvalSourceToolMessageIds].sort(),+ };+ const existingAssistant = await this.messageModel.findById(continuationAssistantId);+ const matches =+ existingOperation?.agentId === resolvedAgentId &&+ existingOperation.topicId === topicId &&+ existingOperation.appContext?.sourceMessageId === parentMessageId &&+ matchesAgentInterventionContinuationProvenance(+ existingOperation.metadata?.agentInterventionContinuation,+ expectedProvenance,+ ) &&+ existingState.operationId === continuationOperationId &&+ existingState.metadata?.userId === this.userId &&+ (existingState.metadata?.workspaceId ?? null) === (this.workspaceId ?? null) &&+ existingState.metadata?.agentId === resolvedAgentId &&+ existingState.metadata?.topicId === topicId &&+ existingState.metadata?.sourceMessageId === parentMessageId &&+ matchesAgentInterventionContinuationProvenance(+ existingState.metadata?.agentInterventionContinuation,+ expectedProvenance,+ ) &&+ existingAssistant?.role === 'assistant' &&+ existingAssistant.topicId === topicId;+ if (!matches) {+ throw new Error(+ `Intervention continuation operation identity conflict: ${continuationOperationId}`,+ );+ }++ const start =+ await this.agentRuntimeService.ensureInterventionContinuationStarted(+ continuationOperationId,+ );+ if (start === 'missing') {+ throw new Error(+ `Intervention continuation state disappeared: ${continuationOperationId}`,+ );+ }+ approvalClaim.continuationStarted = true;++ let gatewayToken: string | undefined;+ if (!this.withholdGatewayToken) {+ try {+ gatewayToken = await signUserJWT(this.userId);+ } catch {+ log('execAgent: failed to sign gateway JWT for reused intervention continuation');+ }+ }+ const now = new Date().toISOString();+ return {+ agentId: resolvedAgentId,+ assistantMessageId: continuationAssistantId,+ autoStarted: true,+ createdAt: now,+ message: 'Agent intervention continuation already created',+ operationId: continuationOperationId,+ status: 'created',+ success: true,+ timestamp: now,+ token: gatewayToken,+ topicId,+ userMessageId: parentMessageId ?? '',+ };+ }+ }const isFixedExecutionTargetSelection =!!this.workspaceId && agentConfig.agencyConfig?.executionTargetSelectionPolicy === 'fixed';const isFixedDeviceTarget =@@ -2284,29 +2601,52 @@ export class AiAgentService {// / `turn_metadata` (backfilled by HeterogeneousPersistenceHandler), and// seeding the agent's chat model would leak it into the model tag. A normal// run seeds model + provider as usual.- const assistantMessageRecord = await this.messageModel.create(- {- agentId: assistantAgentId,- content: LOADING_FLAT,- // Stamp groupId so the assistant turn is visible in the group read path- // (MessageModel.query filters group chats by messages.groupId).- groupId: appContext?.groupId ?? undefined,- metadata: orchestrationMetadata,- model: isHeteroAgent ? undefined : model,- // Chain onto the user turn we just persisted; `parentMessageId` is the- // anchor only on a resume, where no user message is created. A batch- // approval overrides it with the assistant that emitted the batch — the- // previous LLM call — so the spine stays one node per call and never- // depends on which of the batch's tool rows the client sent as anchor.- parentId: userMessageRecord?.id ?? batchApprovalAnchorId ?? parentMessageId,- provider: isHeteroAgent ? heteroType : provider,- role: 'assistant',- threadId: appContext?.threadId ?? undefined,- topicId,- },- // The id the client's assistant placeholder already renders under.- clientIds?.assistantMessageId,- );+ const assistantParentId = userMessageRecord?.id ?? batchApprovalAnchorId ?? parentMessageId;+ const existingContinuationAssistant = continuationAssistantId+ ? await this.messageModel.findById(continuationAssistantId)+ : undefined;++ if (+ existingContinuationAssistant &&+ (existingContinuationAssistant.role !== 'assistant' ||+ existingContinuationAssistant.topicId !== topicId ||+ (existingContinuationAssistant.threadId ?? undefined) !==+ (appContext?.threadId ?? undefined) ||+ (existingContinuationAssistant.parentId ?? undefined) !== assistantParentId ||+ existingContinuationAssistant.agentId !== assistantAgentId)+ ) {+ throw new Error(+ `Intervention continuation assistant identity conflict: ${continuationAssistantId}`,+ );+ }++ const assistantMessageRecord =+ existingContinuationAssistant ??+ (await this.messageModel.create(+ {+ agentId: assistantAgentId,+ content: LOADING_FLAT,+ // Stamp groupId so the assistant turn is visible in the group read path+ // (MessageModel.query filters group chats by messages.groupId).+ groupId: appContext?.groupId ?? undefined,+ metadata: orchestrationMetadata,+ model: isHeteroAgent ? undefined : model,+ // Chain onto the user turn we just persisted; `parentMessageId` is the+ // anchor only on a resume, where no user message is created. A batch+ // approval overrides it with the assistant that emitted the batch — the+ // previous LLM call — so the spine stays one node per call and never+ // depends on which of the batch's tool rows the client sent as anchor.+ parentId: assistantParentId,+ provider: isHeteroAgent ? heteroType : provider,+ role: 'assistant',+ threadId: appContext?.threadId ?? undefined,+ topicId,+ },+ // Generic intervention continuations use a stable placeholder so a+ // crash after this insert but before operation-state creation can+ // safely re-enter without creating a second assistant turn.+ continuationAssistantId ?? clientIds?.assistantMessageId,+ ));selfMessageIds.add(assistantMessageRecord.id);assistantMessageRef.current = assistantMessageRecord.id;log('execAgent: created assistant message %s', assistantMessageRecord.id);@@ -4356,7 +4696,8 @@ export class AiAgentService {// 15. Generate operation ID: agt_{timestamp}_{agentId}_{topicId}_{random}const timestamp = Date.now();- const operationId = `op_${timestamp}_${resolvedAgentId}_${topicId}_${nanoid(8)}`;+ const operationId =+ continuationOperationId ?? `op_${timestamp}_${resolvedAgentId}_${topicId}_${nanoid(8)}`;if (params.topicStartOwnerOperationId) {const attached = await this.topicModel.appendRunningOperationChild(@@ -4482,48 +4823,63 @@ export class AiAgentService {// intervention status, so `allMessages` reflects the decision for the// LLM / runner on the first step.//- // `rejected` and `rejected_continue` share the same server-side path:- // both surface the rejection to the LLM as user feedback via- // `phase: 'user_input'`. The client-side split (halt vs. continue) is- // only about the UX of the button and the optimistic writes — once the- // decision is persisted, there's nothing meaningful to do differently- // server-side, and letting the LLM produce a brief acknowledgement keeps- // the conversation cleanly terminated either way.+ // `rejected` and `rejected_continue` share the same persisted tool-result+ // path. Starting at `tool_result` (not `user_input`) is critical for a+ // partial same-turn decision: GeneralChatAgent first checks for pending+ // siblings and re-parks them, and only the final decision continues the+ // LLM. A direct user_input continuation would fork an LLM call while the+ // unresolved tool rows were still empty.// Batch approval: hand the runtime every approved tool at once so it runs a// single `call_tools_batch` against the existing pending rows and continues// the LLM exactly once, with the complete result set. Taken whenever the// caller used the batch wire form; the single `resumeApproval` form keeps// the established `call_tool` + `skipCreateToolMessage` path below.- if (resumeApprovals?.length && approvedToolEntries.length > 0) {- initialContext = {- initialContext: initialContext.initialContext,- payload: {- approvedToolCalls: approvedToolEntries.map(({ plugin }) => ({- apiName: plugin.apiName,- arguments: plugin.arguments,- id: plugin.toolCallId,- identifier: plugin.identifier,- type: plugin.type ?? 'default',- })),- assistantMessageId: assistantMessageRecord.id,- // The tool rows already exist and are parented to the assistant that- // emitted the calls; the batch executor addresses them through- // `toolMessageIds` and never inserts, so this only anchors the spine.- parentMessageId: approvalOwnerAssistantId ?? assistantMessageRecord.id,- toolMessageIds: Object.fromEntries(- approvedToolEntries- .filter(({ plugin }) => !!plugin.toolCallId)- .map(({ plugin, toolMessageId }) => [plugin.toolCallId!, toolMessageId]),- ),- } as any,- phase: 'human_approved_tool' as const,- session: {- messageCount: allMessages.length,- sessionId: operationId,- status: 'idle' as const,- stepCount: 0,- },- };+ if (resumeApprovals?.length) {+ initialContext =+ approvedToolEntries.length > 0+ ? {+ initialContext: initialContext.initialContext,+ payload: {+ approvedToolCalls: approvedToolEntries.map(({ plugin }) => ({+ apiName: plugin.apiName,+ arguments: plugin.arguments,+ id: plugin.toolCallId,+ identifier: plugin.identifier,+ type: plugin.type ?? 'default',+ })),+ assistantMessageId: assistantMessageRecord.id,+ // The tool rows already exist and are parented to the assistant that+ // emitted the calls; the batch executor addresses them through+ // `toolMessageIds` and never inserts, so this only anchors the spine.+ parentMessageId: approvalOwnerAssistantId ?? assistantMessageRecord.id,+ toolMessageIds: Object.fromEntries(+ approvedToolEntries+ .filter(({ plugin }) => !!plugin.toolCallId)+ .map(({ plugin, toolMessageId }) => [plugin.toolCallId!, toolMessageId]),+ ),+ } as any,+ phase: 'human_approved_tool' as const,+ session: {+ messageCount: allMessages.length,+ sessionId: operationId,+ status: 'idle' as const,+ stepCount: 0,+ },+ }+ : {+ initialContext: initialContext.initialContext,+ payload: {+ assistantMessageId: assistantMessageRecord.id,+ parentMessageId: parentMessageId ?? resumeApprovals[0].parentMessageId,+ } as any,+ phase: 'tool_result' as const,+ session: {+ messageCount: allMessages.length,+ sessionId: operationId,+ status: 'idle' as const,+ stepCount: 0,+ },+ };} else if (resumeApproval && resumeApprovalPlugin) {if (resumeApproval.decision === 'approved') {// Ask the runtime to execute the approved tool directly. Matches the@@ -4556,12 +4912,17 @@ export class AiAgentService {};} else {initialContext = {- ...initialContext,+ initialContext: initialContext.initialContext,payload: {- ...(initialContext.payload as any),- isFirstMessage: false,- message: [{ content: '' }],+ assistantMessageId: assistantMessageRecord.id,parentMessageId: resumeApproval.parentMessageId,+ } as any,+ phase: 'tool_result' as const,+ session: {+ messageCount: allMessages.length,+ sessionId: operationId,+ status: 'idle' as const,+ stepCount: 0,},};}@@ -4856,6 +5217,7 @@ export class AiAgentService {// member ('member') from a genuine callSubAgent child.orchestrationRole: appContext?.orchestrationRole,scope: appContext?.scope,+ sessionId: appContext?.sessionId,sourceMessageId: userMessageRecord?.id ?? parentMessageId ?? undefined,// Live-progress anchor for a callSubAgent child — carries the parked// parent's operationId + placeholder tool message so the child's step@@ -4878,6 +5240,22 @@ export class AiAgentService {initialContext,initialMessages: allMessages,initialStepCount,+ ...(providedApprovalResolutionRequestId && approvalSourceOperationId+ ? {+ interventionResolution: {+ resolutionRequestId: providedApprovalResolutionRequestId,+ sourceOperationId: approvalSourceOperationId,+ sourceToolMessageIds: [...approvalSourceToolMessageIds].sort(),+ },+ }+ : {}),+ ...(providedApprovalResolutionRequestId+ ? {+ onInterventionPrepared: () => {+ approvalClaim.continuationPrepared = true;+ },+ }+ : {}),maxSteps,modelRuntimeConfig: { model, provider },hooks,@@ -4901,6 +5279,17 @@ export class AiAgentService {userMemory,workspaceId: this.workspaceId,});+ approvalClaim.continuationStarted = true;++ // The approval continuation is a fresh operation. Legacy direct callers+ // retire the old parked runtime here, only after createOperation has+ // durably scheduled the replacement. Generic v2 calls carry a durable+ // resolution id and defer this transition to the shared router dispatch+ // boundary, which can retry it without losing this successful ExecAgent+ // result (and therefore the WebSocket subscription credentials).+ if (approvalSourceOperationId && !providedApprovalResolutionRequestId) {+ await this.retirePendingApprovalOperation(approvalSourceOperationId);+ }log('execAgent: created operation %s (autoStarted: %s)', operationId, result.autoStarted);@@ -4916,7 +5305,11 @@ export class AiAgentService {// `appContext.subAgentProgress`.// `orchestrationRole` is public rendering metadata. Only the internally// propagated parent operation id proves child ownership of this topic.- if (!appContext?.isolationThread && !params.topicStartOwnerOperationId) {+ if (+ !appContext?.isolationThread &&+ !appContext?.threadId &&+ !params.topicStartOwnerOperationId+ ) {await this.topicModel.updateMetadata(topicId, {runningOperation: {assistantMessageId: assistantMessageRecord.id,@@ -4964,6 +5357,13 @@ export class AiAgentService {log('execAgent: createOperation aborted for %s: %s', operationId, error.message);throw error;}+ if (providedApprovalResolutionRequestId && approvalClaim.continuationPrepared) {+ // The source claim + deterministic state are now the retry record. A+ // queue ACK may have been accepted even when its HTTP response or our+ // follow-up marker write failed, so do not paint the stable assistant+ // as terminal error and do not collapse this into success:false.+ throw error;+ }// Operation startup failed (e.g., QStash queue service unavailable)// Update assistant message with error so user can see what went wrong@@ -6059,27 +6459,42 @@ export class AiAgentService {** Why it can't reuse the ordinary cancel path: when the runtime parks it* emits a stream-terminal `waiting_for_human`, so the client marks its own- * operation `completed` and prunes it ~30s later, and the topic's- * `runningOperation` pointer is cleared. By the time the user decides to- * stop, the client no longer knows the parked operation id — so we resolve it- * here from the topic instead of trusting the caller.+ * operation `completed` and prunes it ~30s later. The pending tool rows retain+ * the authoritative operation and sealed-batch identity; callers must send+ * that exact correlation and this service verifies it against both the+ * operation record and every batch member before claiming anything.** The tool rows are settled IN PLACE (the approval pause already created one* row per pending call). Inserting fresh aborted rows would duplicate every* tool in the turn and leave the originals `pending`, which is exactly what* keeps the approval cards on screen after a stop.*/- async stopPendingApproval(params: { toolMessageIds: string[]; topicId: string }): Promise<{- operationId?: string;+ async stopPendingApproval(params: {+ approvalResolutionRequestId?: string;+ batchId: string;+ operationId: string;+ toolMessageIds: string[];+ topicId: string;+ }): Promise<{+ operationId: string;settledToolMessageIds: string[];success: boolean;}> {- const { toolMessageIds, topicId } = params;+ const { approvalResolutionRequestId, batchId, operationId, toolMessageIds, topicId } = params;++ const operation = await this.agentOperationModel.findById(operationId);+ if (+ !operation ||+ operation.topicId !== topicId ||+ (operation.status !== 'waiting_for_human' && operation.status !== 'interrupted')+ ) {+ throw new Error('stopPendingApproval: operation is not the parked owner of this topic');+ }- // Validate every target before writing any of them: a half-settled batch- // would clear some cards while leaving the rest pointing at a run that is- // already gone.- const targets: { id: string }[] = [];+ // Validate identity and complete sealed-batch membership before the atomic+ // claim. The caller cannot stop a hand-picked subset or a stale batch from+ // another parked operation.+ const targets: { alreadyClaimed: boolean; id: string }[] = [];for (const toolMessageId of toolMessageIds) {const message = await this.messageModel.findById(toolMessageId);if (!message)@@ -6092,25 +6507,67 @@ export class AiAgentService {if (message.topicId !== topicId) {throw new Error('stopPendingApproval: topicId does not match the target tool message');}- targets.push({ id: toolMessageId });+ const plugin = await this.messageModel.findMessagePlugin(toolMessageId);+ const intervention = plugin?.intervention;+ if (+ !intervention ||+ intervention.operationId !== operationId ||+ intervention.batchId !== batchId+ ) {+ throw new Error('stopPendingApproval: target is not in the requested batch');+ }+ const alreadyClaimed =+ intervention.status === 'aborted' &&+ Boolean(approvalResolutionRequestId) &&+ intervention.resolutionRequestId === approvalResolutionRequestId;+ if (intervention.status !== 'pending' && !alreadyClaimed) {+ throw new HumanApprovalAlreadyResolvedError(toolMessageId);+ }+ targets.push({ alreadyClaimed, id: toolMessageId });}- for (const target of targets) {- await this.messageModel.updateToolMessage(target.id, {- content: STOPPED_TOOL_CONTENT,- });- await this.messageModel.updateMessagePlugin(target.id, {- intervention: { status: 'aborted' },- } as any);+ const fullBatchIds = (await this.messageModel.listMessagePluginsByTopic(topicId))+ .filter(+ (plugin) =>+ plugin.intervention?.operationId === operationId &&+ plugin.intervention?.batchId === batchId,+ )+ .map(({ id }) => id)+ .sort();+ const requestedIds = targets.map(({ id }) => id).sort();+ if (+ fullBatchIds.length !== requestedIds.length ||+ fullBatchIds.some((id, index) => id !== requestedIds[index])+ ) {+ throw new Error('stopPendingApproval: targets must cover the complete sealed batch');+ }++ const alreadyClaimedCount = targets.filter(({ alreadyClaimed }) => alreadyClaimed).length;+ if (alreadyClaimedCount !== 0 && alreadyClaimedCount !== targets.length) {+ throw new Error('stopPendingApproval: batch has a partial resolution claim');+ }+ if (operation.status === 'interrupted' && alreadyClaimedCount !== targets.length) {+ throw new Error('stopPendingApproval: interrupted operation has unsettled batch members');+ }++ if (alreadyClaimedCount === 0) {+ await this.messageModel.resolveHumanApproval(+ targets.map((target) => ({+ content: STOPPED_TOOL_CONTENT,+ id: target.id,+ intervention: {+ ...(approvalResolutionRequestId && {+ resolutionRequestId: approvalResolutionRequestId,+ }),+ status: 'aborted',+ },+ })),+ );}- // Retire the parked operation so the topic does not keep a run that can- // never be resumed. Resolved from the topic because the client has lost the- // id by now (see the doc comment above).- const parkedOperationId = await this.agentOperationModel.findLatestParkedOperationId(topicId);- if (parkedOperationId) {- await this.agentRuntimeService.interruptOperation(parkedOperationId);- await this.agentOperationModel.recordCompletion(parkedOperationId, {+ if (operation.status !== 'interrupted') {+ await this.agentRuntimeService.interruptOperation(operationId);+ await this.agentOperationModel.recordCompletion(operationId, {completedAt: new Date(),completionReason: 'interrupted',status: 'interrupted',@@ -6120,13 +6577,148 @@ export class AiAgentService {log('stopPendingApproval: settled %d tool message(s), retired operation %s',targets.length,- parkedOperationId ?? '(none)',+ operationId,);return {- operationId: parkedOperationId,+ operationId,settledToolMessageIds: targets.map((t) => t.id),success: true,};}++ /**+ * Retire the operation segment that parked on an approval after its+ * replacement continuation has been scheduled. The Redis state is stopped+ * first; the durable row then converges waiting_for_human -> done. Repeating+ * this call is safe, including after Cloud supersession won the race.+ */+ async retirePendingApprovalOperation(operationId: string): Promise<void> {+ await this.agentRuntimeService.interruptOperation(operationId);++ const operation = await this.agentOperationModel.findById(operationId);+ if (!operation) {+ throw new Error(`retirePendingApprovalOperation: operation not found: ${operationId}`);+ }+ if (operation.status === 'done' || operation.status === 'interrupted') return;+ if (operation.status !== 'waiting_for_human') {+ throw new Error(+ `retirePendingApprovalOperation: expected waiting_for_human, got ${operation.status}`,+ );+ }++ const completed = await this.agentOperationModel.recordCompletion(operationId, {+ completedAt: new Date(),+ completionReason: 'done',+ status: 'done',+ });+ if (!completed) {+ const latest = await this.agentOperationModel.findById(operationId);+ if (latest?.status !== 'done' && latest?.status !== 'interrupted') {+ throw new Error(`retirePendingApprovalOperation: failed to settle ${operationId}`);+ }+ }+ }++ /** Owner-scoped runtime state used by the v2 router's crash-safe retry probe. */+ async loadInterventionContinuationState(operationId: string): Promise<AgentState | null> {+ return this.agentRuntimeService.loadInterventionContinuationState(operationId);+ }++ /** Requeue an idle deterministic continuation without rebuilding its assistant turn. */+ async ensureInterventionContinuationStarted(+ operationId: string,+ ): Promise<'already_started' | 'missing' | 'scheduled'> {+ return this.agentRuntimeService.ensureInterventionContinuationStarted(operationId);+ }++ /**+ * Repair the topic reconnect marker and release the exact start reservation+ * after a durable queue ACK. A foreign newer running operation fails closed.+ */+ async repairInterventionContinuationTopicAnchor(params: {+ assistantMessageId: string;+ continuationOperationId: string;+ resolutionRequestId: string;+ scope?: string | null;+ sourceOperationId: string;+ sourceToolMessageIds: string[];+ threadId?: string | null;+ topicId: string;+ }): Promise<void> {+ const operation = await this.agentOperationModel.findById(params.continuationOperationId);+ const expectedProvenance = {+ resolutionRequestId: params.resolutionRequestId,+ sourceOperationId: params.sourceOperationId,+ sourceToolMessageIds: [...params.sourceToolMessageIds].sort(),+ };+ const assistant = await this.messageModel.findById(params.assistantMessageId);+ const dispatchMarker = operation?.metadata?.agentInterventionDispatch as+ | {+ deduplicationId?: unknown;+ resolutionRequestId?: unknown;+ state?: unknown;+ }+ | undefined;+ const expectedDeduplicationId = deriveAgentInterventionQueueDeduplicationId(+ params.continuationOperationId,+ 0,+ );+ if (+ !operation ||+ operation.topicId !== params.topicId ||+ !matchesAgentInterventionContinuationProvenance(+ operation.metadata?.agentInterventionContinuation,+ expectedProvenance,+ ) ||+ dispatchMarker?.state !== 'scheduled' ||+ dispatchMarker.resolutionRequestId !== params.resolutionRequestId ||+ dispatchMarker.deduplicationId !== expectedDeduplicationId ||+ assistant?.role !== 'assistant' ||+ assistant.topicId !== params.topicId+ ) {+ throw new Error('Intervention continuation topic repair provenance conflict');+ }++ // Thread continuations use the deterministic topic reservation only as a+ // short single-initializer fence. They never own the topic's main+ // runningOperation anchor, so ACK recovery must release exactly their+ // reservation without promoting the thread into the main conversation+ // spine. A foreign reservation is intentionally left untouched.+ if (params.threadId) {+ const released = await this.topicModel.releaseTaskCallbackReservation(+ params.topicId,+ params.continuationOperationId,+ );+ if (released === 'foreign') {+ throw new Error('Intervention continuation topic repair found a foreign reservation');+ }+ return;+ }++ const state = await this.agentRuntimeService.loadInterventionContinuationState(+ params.continuationOperationId,+ );+ const runtimeTerminal =+ state?.status === 'done' || state?.status === 'error' || state?.status === 'interrupted';+ const durableTerminal =+ operation.status === 'done' ||+ operation.status === 'error' ||+ operation.status === 'interrupted' ||+ operation.status === 'abandoned';+ const result = await this.topicModel.repairAgentInterventionContinuation({+ active: !runtimeTerminal && !durableTerminal,+ assistantMessageId: params.assistantMessageId,+ continuationOperationId: params.continuationOperationId,+ reservationId: params.continuationOperationId,+ scope: params.scope,+ sourceOperationId: params.sourceOperationId,+ startedAt: operation.startedAt?.toISOString() ?? new Date().toISOString(),+ threadId: params.threadId,+ topicId: params.topicId,+ });+ if (result === 'conflict') {+ throw new Error('Intervention continuation topic repair found a foreign running operation');+ }+ }}diff --git a/apps/server/src/services/aiAgent/topicStartReservation.test.ts b/apps/server/src/services/aiAgent/topicStartReservation.test.tsindex 8b05920d1ac..629a053b147 100644--- a/apps/server/src/services/aiAgent/topicStartReservation.test.ts+++ b/apps/server/src/services/aiAgent/topicStartReservation.test.ts@@ -55,6 +55,7 @@ describe('acquireTopicStartReservation', () => {expect(tryReserveTaskCallback).toHaveBeenCalledWith('topic-1', 'new-start', {allowRunningOperationId: undefined,+ allowSameReservationReentry: undefined,ignoreRunningOperation: undefined,replacesOperationId: 'old-operation',});@@ -75,6 +76,7 @@ describe('acquireTopicStartReservation', () => {expect(tryReserveTaskCallback).toHaveBeenCalledWith('topic-1', 'child-operation', {allowRunningOperationId: 'parent-operation',+ allowSameReservationReentry: undefined,ignoreRunningOperation: undefined,replacesOperationId: undefined,});@@ -93,6 +95,27 @@ describe('acquireTopicStartReservation', () => {expect(tryReserveTaskCallback).toHaveBeenCalledWith('topic-1', 'composer-send', {allowRunningOperationId: undefined,+ allowSameReservationReentry: undefined,+ ignoreRunningOperation: true,+ replacesOperationId: undefined,+ });+ });++ it('forwards the non-reentrant intervention initializer fence', async () => {+ const tryReserveTaskCallback = vi.fn().mockResolvedValue(true);+ const topicModel = { tryReserveTaskCallback } as unknown as TopicModel;++ await acquireTopicStartReservation({+ allowSameReservationReentry: false,+ ignoreRunningOperation: true,+ reservationId: 'op-intervention',+ topicId: 'topic-1',+ topicModel,+ });++ expect(tryReserveTaskCallback).toHaveBeenCalledWith('topic-1', 'op-intervention', {+ allowRunningOperationId: undefined,+ allowSameReservationReentry: false,ignoreRunningOperation: true,replacesOperationId: undefined,});diff --git a/apps/server/src/services/aiAgent/topicStartReservation.ts b/apps/server/src/services/aiAgent/topicStartReservation.tsindex f8820c9ca1d..32bf337b4f4 100644--- a/apps/server/src/services/aiAgent/topicStartReservation.ts+++ b/apps/server/src/services/aiAgent/topicStartReservation.ts@@ -22,6 +22,7 @@ const delay = (milliseconds: number): Promise<void> =>*/export const acquireTopicStartReservation = async ({allowRunningOperationId,+ allowSameReservationReentry,ignoreRunningOperation,replacesOperationId,reservationId,@@ -29,6 +30,7 @@ export const acquireTopicStartReservation = async ({topicModel,}: {allowRunningOperationId?: string;+ allowSameReservationReentry?: boolean;/*** Serialize only on the short reservation, not on `runningOperation`. Set by* interactive sends — see `TopicModel.tryReserveTaskCallback`.@@ -42,6 +44,7 @@ export const acquireTopicStartReservation = async ({for (let attempt = 0; attempt < MAX_RESERVATION_ATTEMPTS; attempt += 1) {const reservation = await topicModel.tryReserveTaskCallback(topicId, reservationId, {allowRunningOperationId,+ allowSameReservationReentry,ignoreRunningOperation,replacesOperationId,});diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.tsindex 57a37985c96..e34b7b063c4 100644--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts@@ -1,7 +1,14 @@-import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';+import {+ type AgentInterventionInteractionKind,+ type AgentInterventionProvider,+ type AgentInterventionRequestData,+ type AgentStreamEvent,+ sanitizeAgentInterventionRequestForReview,+} from '@lobechat/agent-gateway-client';import { LOADING_FLAT } from '@lobechat/const';import type {MainAgentIntent,+ MainAgentInterventionTransition,MainAgentReduceCtx,MainAgentRunState,MainAgentTurnToolState,@@ -19,6 +26,17 @@ import { type ChatToolPayload, ThreadStatus, ThreadType } from '@lobechat/types'import { createNanoId } from '@lobechat/utils';import debug from 'debug';+import {+ deriveAgentInterventionActivityKey,+ hashAgentInterventionRequestRevision,+} from '@/business/server/agent-run/agentInterventionIdentity';+import {+ acknowledgeAgentInterventionProducerResolution,+ type AgentInterventionAllowedAction,+ type AgentInterventionReviewDetail,+ notifyAgentInterventionRequired,+ type NotifyAgentInterventionRequiredParams,+} from '@/business/server/agent-run/agentInterventionReview';import type { MessageModel } from '@/database/models/message';import type { ThreadModel } from '@/database/models/thread';import type { TopicModel } from '@/database/models/topic';@@ -121,6 +139,8 @@ interface OperationState {lastAppliedToolStateSeqByCallId: Map<string, number>;lastStepIndex: number;main: MainAgentRunState;+ /** `(operationId, toolCallId, transition)` notification dedupe ledger. */+ notifiedInterventionTransitions: Set<string>;operationId: string;processedKeys: Set<string>;/**@@ -167,8 +187,106 @@ export interface HeterogeneousPersistenceHandlerDeps {messageModel: MessageModel;threadModel: ThreadModel;topicModel: TopicModel;+ userId?: string;+ workspaceId?: string;}+interface StoredHeterogeneousIntervention {+ deadline?: number;+ interactionKind?: AgentInterventionInteractionKind;+ notificationTransition?: MainAgentInterventionTransition;+ provider?: AgentInterventionProvider;+ resolutionRequestId?: string;+ summary?: string;+ transition?: MainAgentInterventionTransition;+}++const HETEROGENEOUS_INTERVENTION_STATE_KEY = 'heterogeneousIntervention';++const interventionSummary = (request?: AgentInterventionRequestData): string => {+ const provider = request?.provider ?? 'heterogeneous-agent';+ const kind = request?.interactionKind ?? 'question';+ const apiName = request?.apiName || 'interaction';+ return `${provider} ${kind}: ${apiName}`.slice(0, 160);+};++const buildHeterogeneousReviewDetail = (+ request: AgentInterventionRequestData,+): Extract<AgentInterventionReviewDetail, { type: 'permission' | 'plan' | 'question' }> => {+ const parsed = JSON.parse(request.arguments) as {+ questions: Array<{+ header: string;+ multiSelect: boolean;+ options: Array<{ description?: string; id?: string; label: string }>;+ question: string;+ }>;+ };+ const questions = parsed.questions.map((question, questionIndex) => ({+ header: question.header || undefined,+ id: `question_${questionIndex + 1}`,+ multiple: question.multiSelect,+ options: question.options.map((option) => ({+ description: option.description,+ id: option.id ?? option.label,+ label: option.label,+ })),+ question: question.question,+ }));+ const first = questions[0];++ switch (request.interactionKind) {+ case 'permission': {+ return {+ description: first.header,+ options: first.options,+ title: first.question,+ type: 'permission',+ };+ }+ case 'plan': {+ return {+ content: first.question,+ options: first.options,+ title: first.header ?? 'Review plan',+ type: 'plan',+ };+ }+ case 'question': {+ return { questions, title: first.header, type: 'question' };+ }+ default: {+ throw new Error('Unsupported heterogeneous intervention kind');+ }+ }+};++const heterogeneousActionsFor = (+ interactionKind: AgentInterventionInteractionKind,+): AgentInterventionAllowedAction[] =>+ interactionKind === 'question'+ ? ['submit_answers', 'skip_interaction']+ : ['select_provider_option', 'skip_interaction'];++const INTERVENTION_TRANSITIONS = new Set<MainAgentInterventionTransition>([+ 'cancelled',+ 'pending',+ 'resolved',+ 'session_ended',+ 'timed_out',+]);++const INTERVENTION_KINDS = new Set<AgentInterventionInteractionKind>([+ 'permission',+ 'plan',+ 'question',+]);++const INTERVENTION_PROVIDERS = new Set<AgentInterventionProvider>([+ 'claude-code',+ 'cursor',+ 'qoder',+]);+/*** Server-side persistence for `lh hetero exec` event streams. Mirrors the* desktop renderer's `executeHeterogeneousAgent` (1.8k lines) for the DB@@ -489,6 +607,7 @@ export class HeterogeneousPersistenceHandler {lastAppliedToolStateSeqByCallId: new Map(),main: createMainAgentRunState(currentAssistantMessageId),operationId,+ notifiedInterventionTransitions: new Set(),processedKeys: new Set(),publishedKeys: new Set(),toolMsgIdByCallId: new Map(),@@ -572,6 +691,68 @@ export class HeterogeneousPersistenceHandler {const toolPlugins = await this.deps.messageModel.listMessagePluginsByTopic(state.topicId);for (const plugin of toolPlugins) {if (plugin.toolCallId) state.toolMsgIdByCallId.set(plugin.toolCallId, plugin.id);+ if (plugin.toolCallId && plugin.state && typeof plugin.state === 'object') {+ const stored = (plugin.state as Record<string, unknown>)[+ HETEROGENEOUS_INTERVENTION_STATE_KEY+ ];+ if (stored && typeof stored === 'object') {+ const metadata = stored as Record<string, unknown>;+ const transition = INTERVENTION_TRANSITIONS.has(+ metadata.transition as MainAgentInterventionTransition,+ )+ ? (metadata.transition as MainAgentInterventionTransition)+ : undefined;+ const interactionKind = INTERVENTION_KINDS.has(+ metadata.interactionKind as AgentInterventionInteractionKind,+ )+ ? (metadata.interactionKind as AgentInterventionInteractionKind)+ : undefined;+ const provider = INTERVENTION_PROVIDERS.has(+ metadata.provider as AgentInterventionProvider,+ )+ ? (metadata.provider as AgentInterventionProvider)+ : undefined;++ if (transition) {+ const request =+ typeof plugin.apiName === 'string' &&+ typeof plugin.arguments === 'string' &&+ typeof plugin.identifier === 'string' &&+ typeof metadata.deadline === 'number'+ ? {+ apiName: plugin.apiName,+ arguments: plugin.arguments,+ deadline: metadata.deadline,+ identifier: plugin.identifier,+ interactionKind,+ provider,+ toolCallId: plugin.toolCallId,+ }+ : undefined;+ state.main.interventionsByCallId.set(plugin.toolCallId, {+ intervention:+ plugin.intervention ??+ (transition === 'pending'+ ? { status: 'pending' }+ : transition === 'resolved'+ ? { status: 'approved' }+ : { rejectedReason: transition, status: 'rejected' }),+ request,+ resolutionRequestId:+ typeof metadata.resolutionRequestId === 'string'+ ? metadata.resolutionRequestId+ : undefined,+ transition,+ });++ if (metadata.notificationTransition === transition) {+ state.notifiedInterventionTransitions.add(+ `${state.operationId}:${plugin.toolCallId}:${transition}`,+ );+ }+ }+ }+ }if (plugin.toolCallId &&plugin.metadata?.heterogeneousToolStateOperationId === state.operationId &&@@ -895,7 +1076,7 @@ export class HeterogeneousPersistenceHandler {if ('threadId' in intent) {await this.applySubagentIntent(state, intent as SubagentIntent);} else {- await this.applyMainIntent(state, intent as MainAgentIntent);+ await this.applyMainIntent(state, intent as MainAgentIntent, event.stepIndex);}}@@ -921,7 +1102,7 @@ export class HeterogeneousPersistenceHandler {return out;}- private async applyMainIntent(state: OperationState, intent: MainAgentIntent) {+ private async applyMainIntent(state: OperationState, intent: MainAgentIntent, stepIndex: number) {switch (intent.kind) {case 'createAssistant': {const createMetadata: Record<string, any> = {@@ -1032,6 +1213,11 @@ export class HeterogeneousPersistenceHandler {return;}+ case 'setToolIntervention': {+ await this.applyToolIntervention(state, intent, stepIndex);+ return;+ }+case 'recordUsage': {const update: Record<string, any> = {};if (intent.usage !== undefined) {@@ -1124,6 +1310,146 @@ export class HeterogeneousPersistenceHandler {);}+ private async applyToolIntervention(+ state: OperationState,+ intent: Extract<MainAgentIntent, { kind: 'setToolIntervention' }>,+ stepIndex: number,+ ): Promise<void> {+ const toolMsgId = state.toolMsgIdByCallId.get(intent.toolCallId);+ if (!toolMsgId) {+ throw new Error(+ `intervention for unknown toolCallId=${intent.toolCallId} op=${state.operationId}`,+ );+ }++ const summary = interventionSummary(intent.request);+ const reviewRequest = sanitizeAgentInterventionRequestForReview(intent.request);+ const durableState: StoredHeterogeneousIntervention = {+ deadline: intent.request?.deadline,+ interactionKind: intent.request?.interactionKind,+ provider: intent.request?.provider,+ resolutionRequestId: intent.resolutionRequestId,+ summary,+ transition: intent.transition,+ };++ // Persist before any business side effect. The existing JSON plugin-state+ // column carries only correlation metadata; no schema/migration is needed.+ await this.deps.messageModel.updateMessagePlugin(toolMsgId, {+ intervention: intent.intervention,+ });+ await this.deps.messageModel.updatePluginState(toolMsgId, {+ [HETEROGENEOUS_INTERVENTION_STATE_KEY]: durableState,+ });++ const transitionKey = `${state.operationId}:${intent.toolCallId}:${intent.transition}`;+ if (!this.deps.userId || state.notifiedInterventionTransitions.has(transitionKey)) return;++ const pendingTransitionKey = `${state.operationId}:${intent.toolCallId}:pending`;+ if (!state.notifiedInterventionTransitions.has(pendingTransitionKey)) {+ if (!reviewRequest?.interactionKind || !reviewRequest.provider) {+ throw new Error(+ `Unsafe heterogeneous intervention review payload toolCallId=${intent.toolCallId}`,+ );+ }+ const assistantMessageId = state.main.currentAssistantId;+ if (!assistantMessageId) {+ throw new Error(+ `Missing assistant owner for heterogeneous intervention toolCallId=${intent.toolCallId}`,+ );+ }+ // Heterogeneous callbacks are individually sealed. Include the tool call+ // so two concurrent interventions emitted by one assistant step never+ // claim the same batch identity with conflicting item-0 contents.+ const batchId = `${state.operationId}:${stepIndex}:${assistantMessageId}:${intent.toolCallId}`;+ // The generic Web source bridge reads the same authoritative correlation+ // from the tool row. Stamp it before notify so a card can never appear+ // actionable while its operation/batch locator is still absent.+ await this.deps.messageModel.updateMessagePlugin(toolMsgId, {+ intervention: {+ ...intent.intervention,+ batchId,+ itemIndex: 0,+ operationId: state.operationId,+ stepIndex,+ },+ });+ const allowedActions = heterogeneousActionsFor(reviewRequest.interactionKind);+ const notification: NotifyAgentInterventionRequiredParams = {+ agentId: state.agentId ?? undefined,+ approvalMode: 'manual',+ batch: {+ activityKey: deriveAgentInterventionActivityKey({+ batchId,+ operationId: state.operationId,+ userId: this.deps.userId,+ workspaceId: this.deps.workspaceId,+ }),+ allowedActions: [],+ id: batchId,+ kind: 'single',+ sealed: true,+ stepIndex,+ },+ context: {+ agentId: state.agentId ?? undefined,+ assistantMessageId,+ operationId: state.operationId,+ topicId: state.topicId,+ workspaceId: this.deps.workspaceId,+ },+ deadline: reviewRequest.deadline,+ items: [+ {+ allowedActions,+ detail: buildHeterogeneousReviewDetail(reviewRequest),+ interactionKind: reviewRequest.interactionKind,+ provider: reviewRequest.provider,+ requestRevision: {+ hash: hashAgentInterventionRequestRevision(intent.request?.arguments ?? ''),+ version: 1,+ },+ sourceRef: {+ operationId: state.operationId,+ toolCallId: intent.toolCallId,+ type: 'heterogeneous',+ },+ summary,+ surface: 'form',+ },+ ],+ summary,+ systemActionEligibility: 'review_only',+ userId: this.deps.userId,+ workspaceId: this.deps.workspaceId,+ };+ await notifyAgentInterventionRequired(notification);+ state.notifiedInterventionTransitions.add(pendingTransitionKey);+ }++ if (intent.transition !== 'pending') {+ await acknowledgeAgentInterventionProducerResolution({+ operationId: state.operationId,+ ownerUserId: this.deps.userId,+ resolutionRequestId: intent.resolutionRequestId,+ status: intent.transition,+ toolCallId: intent.toolCallId,+ workspaceId: this.deps.workspaceId,+ });+ }+ state.notifiedInterventionTransitions.add(transitionKey);++ // Cold-replica dedupe marker. Cloud's override must still use the same+ // `(operationId, toolCallId, transition)` idempotency key because a process+ // can die after the external side effect but before this best-effort stamp.+ await this.deps.messageModel.updatePluginState(toolMsgId, {+ [HETEROGENEOUS_INTERVENTION_STATE_KEY]: {+ ...durableState,+ notificationTransition: intent.transition,+ },+ });+ }+private buildToolBatchUpdate(tools: Array<{ payload: ToolCallPayload; toolMessageId: string }>,options: { content?: string; reasoning?: string; withResult: boolean },diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.eventBranches.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.eventBranches.test.tsindex c31c72d7566..d95978aa3dd 100644--- a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.eventBranches.test.ts+++ b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.eventBranches.test.ts@@ -7,6 +7,16 @@ import {HeterogeneousPersistenceHandler,} from '../HeterogeneousPersistenceHandler';+const { acknowledgeAgentInterventionProducerResolution, notifyAgentInterventionRequired } =+ vi.hoisted(() => ({+ acknowledgeAgentInterventionProducerResolution: vi.fn(),+ notifyAgentInterventionRequired: vi.fn(),+ }));+vi.mock('@/business/server/agent-run/agentInterventionReview', () => ({+ acknowledgeAgentInterventionProducerResolution,+ notifyAgentInterventionRequired,+}));+/*** Branch-coverage tests against every event type / sub-type the renderer* (`heterogeneousAgentExecutor.ts:1314–1632`) dispatches on. Each describe@@ -160,6 +170,16 @@ const createHarness = (},),listMessagePluginsByTopic: vi.fn(async (_topicId: string) => []),+ updateMessagePlugin: vi.fn(async (id: string, patch: Record<string, unknown>) => {+ const existing = messages.get(id);+ if (existing) messages.set(id, { ...existing, plugin: { ...existing.plugin, ...patch } });+ }),+ updatePluginState: vi.fn(async (id: string, patch: Record<string, unknown>) => {+ const existing = messages.get(id);+ if (existing) {+ messages.set(id, { ...existing, pluginState: { ...existing.pluginState, ...patch } });+ }+ }),};const threadModel = {@@ -195,6 +215,7 @@ const createHarness = (messageModel: messageModel as any,threadModel: threadModel as any,topicModel: topicModel as any,+ userId: 'user-test',});return {@@ -227,7 +248,11 @@ const ingest = async (h: ReturnType<typeof createHarness>, events: AgentStreamEvh.handler.ingest({ events, operationId: h.operationId, topicId: h.topicId });describe('HeterogeneousPersistenceHandler — event branch coverage', () => {- beforeEach(() => __resetOperationStatesForTesting());+ beforeEach(() => {+ __resetOperationStatesForTesting();+ acknowledgeAgentInterventionProducerResolution.mockReset();+ notifyAgentInterventionRequired.mockReset();+ });afterEach(() => __resetOperationStatesForTesting());// ─── step_complete ────────────────────────────────────────────────────────@@ -923,4 +948,188 @@ describe('HeterogeneousPersistenceHandler — event branch coverage', () => {// Run state cleaned up after finalize});});++ describe('agent_intervention producer ACK', () => {+ it('notifies pending once, ignores the publish leg, and notifies terminal only on ACK', async () => {+ const h = createHarness({ topicAgentId: 'agent-test' });+ const requestId = '018fbd8e-7baf-7c6d-8000-000000000001';+ const request = buildEvent('agent_intervention_request', 0, {+ apiName: 'askUserQuestion',+ arguments: JSON.stringify({+ privateRawArgument: 'must be stripped',+ questions: [+ {+ header: 'Permission',+ multiSelect: false,+ options: [+ { id: 'allow', label: 'Allow', raw: 'strip me' },+ { id: 'deny', label: 'Deny' },+ ],+ question: 'Run command?',+ },+ ],+ }),+ deadline: 1_900_000_000_000,+ identifier: 'claude-code',+ interactionKind: 'permission',+ provider: 'cursor',+ toolCallId: 'permission-1',+ });++ await ingest(h, [request]);+ await ingest(h, [{ ...request, timestamp: request.timestamp + 1 }]);++ expect(notifyAgentInterventionRequired).toHaveBeenCalledTimes(1);+ const pending = notifyAgentInterventionRequired.mock.calls[0][0];+ expect(pending).toMatchObject({+ agentId: 'agent-test',+ approvalMode: 'manual',+ batch: {+ allowedActions: [],+ id: 'op-test:0:asst-seeded:permission-1',+ kind: 'single',+ sealed: true,+ stepIndex: 0,+ },+ context: {+ assistantMessageId: 'asst-seeded',+ operationId: 'op-test',+ topicId: 'topic-test',+ },+ items: [+ {+ allowedActions: ['select_provider_option', 'skip_interaction'],+ detail: {+ description: 'Permission',+ options: [+ { description: undefined, id: 'allow', label: 'Allow' },+ { description: undefined, id: 'deny', label: 'Deny' },+ ],+ title: 'Run command?',+ type: 'permission',+ },+ interactionKind: 'permission',+ provider: 'cursor',+ sourceRef: {+ operationId: 'op-test',+ toolCallId: 'permission-1',+ type: 'heterogeneous',+ },+ surface: 'form',+ },+ ],+ systemActionEligibility: 'review_only',+ });+ expect(pending.batch.activityKey).toMatch(+ /^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,+ );+ expect(pending.items[0].requestRevision).toEqual({+ hash: expect.stringMatching(/^[0-9a-f]{64}$/),+ version: 1,+ });+ expect(JSON.stringify(pending)).not.toContain('privateRawArgument');++ await ingest(h, [+ buildEvent('agent_intervention_response', 1, {+ producerAck: false,+ resolutionRequestId: requestId,+ result: { 'Run command?': 'allow' },+ toolCallId: 'permission-1',+ }),+ ]);+ expect(notifyAgentInterventionRequired).toHaveBeenCalledTimes(1);+ expect(acknowledgeAgentInterventionProducerResolution).not.toHaveBeenCalled();++ await ingest(h, [+ buildEvent('agent_intervention_response', 2, {+ producerAck: true,+ resolutionRequestId: requestId,+ result: { 'Run command?': 'allow' },+ toolCallId: 'permission-1',+ }),+ ]);++ expect(notifyAgentInterventionRequired).toHaveBeenCalledTimes(1);+ expect(acknowledgeAgentInterventionProducerResolution).toHaveBeenCalledTimes(1);+ expect(acknowledgeAgentInterventionProducerResolution).toHaveBeenCalledWith({+ operationId: 'op-test',+ ownerUserId: 'user-test',+ resolutionRequestId: requestId,+ status: 'resolved',+ toolCallId: 'permission-1',+ workspaceId: undefined,+ });+ });++ it('gives concurrent callbacks in one assistant step distinct sealed batch identities', async () => {+ const h = createHarness({ topicAgentId: 'agent-test' });+ const intervention = (toolCallId: string) =>+ buildEvent('agent_intervention_request', 0, {+ apiName: 'askUserQuestion',+ arguments: JSON.stringify({+ questions: [+ {+ header: 'Question',+ multiSelect: false,+ options: [{ label: 'Continue' }],+ question: `Continue ${toolCallId}?`,+ },+ ],+ }),+ deadline: 1_900_000_000_000,+ identifier: 'claude-code',+ interactionKind: 'question',+ provider: 'claude-code',+ toolCallId,+ });++ await ingest(h, [intervention('question-1'), intervention('question-2')]);++ expect(notifyAgentInterventionRequired).toHaveBeenCalledTimes(2);+ const notifications = notifyAgentInterventionRequired.mock.calls.map(([params]) => params);+ expect(notifications.map(({ batch }) => batch.id)).toEqual([+ 'op-test:0:asst-seeded:question-1',+ 'op-test:0:asst-seeded:question-2',+ ]);+ expect(new Set(notifications.map(({ batch }) => batch.activityKey)).size).toBe(2);+ expect(notifications.every(({ batch }) => batch.allowedActions.length === 0)).toBe(true);+ for (const notification of notifications) {+ expect(notification.items[0].allowedActions).toEqual([+ 'submit_answers',+ 'skip_interaction',+ ]);+ }+ });++ it('matches Web plan actions without advertising reserved cancel', async () => {+ const h = createHarness({ topicAgentId: 'agent-test' });+ await ingest(h, [+ buildEvent('agent_intervention_request', 0, {+ apiName: 'askUserQuestion',+ arguments: JSON.stringify({+ questions: [+ {+ header: 'Plan',+ multiSelect: false,+ options: [{ id: 'accept', label: 'Accept plan' }],+ question: 'Proceed with this plan?',+ },+ ],+ }),+ deadline: 1_900_000_000_000,+ identifier: 'cursor',+ interactionKind: 'plan',+ provider: 'cursor',+ toolCallId: 'plan-1',+ }),+ ]);++ const pending = notifyAgentInterventionRequired.mock.calls[0][0];+ expect(pending.items[0]).toMatchObject({+ allowedActions: ['select_provider_option', 'skip_interaction'],+ interactionKind: 'plan',+ });+ expect(pending.items[0].allowedActions).not.toContain('cancel_interaction');+ });+ });});diff --git a/apps/server/src/services/heterogeneousAgent/index.ts b/apps/server/src/services/heterogeneousAgent/index.tsindex 1a05bda60d4..a96e70c0382 100644--- a/apps/server/src/services/heterogeneousAgent/index.ts+++ b/apps/server/src/services/heterogeneousAgent/index.ts@@ -163,6 +163,8 @@ export class HeterogeneousAgentService {messageModel: this.messageModel,threadModel: new ThreadModel(db, userId, workspaceId),topicModel: this.topicModel,+ userId,+ workspaceId,});}diff --git a/apps/server/src/services/push/PushChannel.ts b/apps/server/src/services/push/PushChannel.tsindex dcbe3e6aab4..b8621fe43f0 100644--- a/apps/server/src/services/push/PushChannel.ts+++ b/apps/server/src/services/push/PushChannel.ts@@ -47,9 +47,23 @@ export class PushChannel {return { failedReason: 'no_tokens', status: 'failed' };}- // Build messages, keeping the order so we can map tickets back to tokens by index- const validTokens = tokens.filter((t) => Expo.isExpoPushToken(t.expoToken));+ // Build messages, keeping the order so we can map tickets back to tokens by index.+ // Filtering by the stable row deviceId (not the mutable Expo token) lets+ // callers de-duplicate a system-specific delivery without weakening+ // fallback for the user's other devices.+ const excludedDeviceIds = new Set(ctx.pushPresentation?.excludeDeviceIds);+ const validTokens = tokens.filter(+ (t) => !excludedDeviceIds.has(t.deviceId) && Expo.isExpoPushToken(t.expoToken),+ );if (validTokens.length === 0) {+ if (tokens.every((token) => excludedDeviceIds.has(token.deviceId))) {+ log('All devices excluded from ordinary push for userId=%s', ctx.userId);+ // The caller excluded these devices only after another system surface+ // accepted delivery, so this is a satisfied channel, not a retryable+ // ordinary-push failure.+ return { status: 'delivered' };+ }+log('All tokens malformed for userId=%s', ctx.userId);return { failedReason: 'invalid_tokens', status: 'failed' };}@@ -84,18 +98,19 @@ export class PushChannel {tickets.forEach((ticket, i) => {const expoToken = chunk[i].to as string;+ const deviceId = validTokens[cursor + i]?.deviceId;if (ticket.status === 'ok') {ticketRecords.push({ expoToken, ticketId: ticket.id });} else {// Per-message error at send time — receipt phase won't see this one.- // Common cases: bad token format that slipped past isExpoPushToken,- // payload too big. Logged but not enough to fail the whole delivery.+ // Provider messages are intentionally omitted: they are opaque and+ // may echo the Expo token. Keep diagnostics categorical and scoped+ // to our own stable device id.log(- 'Send-time error for token=%s: %s (%s)',- expoToken,- ticket.message,- ticket.details?.error,+ 'Send-time error for deviceId=%s category=%s',+ deviceId,+ ticket.details?.error ?? 'unknown',);}});diff --git a/apps/server/src/services/push/__tests__/PushChannel.test.ts b/apps/server/src/services/push/__tests__/PushChannel.test.tsindex d73247da350..9ea3a14dc6e 100644--- a/apps/server/src/services/push/__tests__/PushChannel.test.ts+++ b/apps/server/src/services/push/__tests__/PushChannel.test.ts@@ -4,6 +4,9 @@ import { PushChannel } from '../PushChannel';import type { PushDeliveryContext, PushTicketRecord } from '../types';const mockListByUserId = vi.fn();+const { mockLog } = vi.hoisted(() => ({ mockLog: vi.fn() }));++vi.mock('debug', () => ({ default: () => mockLog }));vi.mock('@/database/models/pushToken', () => ({PushTokenModel: vi.fn(() => ({@@ -97,6 +100,47 @@ describe('PushChannel', () => {});});+ it('excludes only devices already delivered through another system surface', async () => {+ mockListByUserId.mockResolvedValueOnce([+ { deviceId: 'activitykit-success', expoToken: 'ExponentPushToken[A]' },+ { deviceId: 'activitykit-failed', expoToken: 'ExponentPushToken[B]' },+ { deviceId: 'android-fallback', expoToken: 'ExponentPushToken[C]' },+ ]);++ const expo = makeExpoMock();+ expo.sendPushNotificationsAsync.mockResolvedValueOnce([+ { id: 'ticket-2', status: 'ok' },+ { id: 'ticket-3', status: 'ok' },+ ]);++ const channel = new PushChannel(expo as any);+ const result = await channel.deliver({+ ...ctx,+ pushPresentation: { excludeDeviceIds: ['activitykit-success'] },+ });++ expect(result.status).toBe('sent');+ expect(+ expo.sendPushNotificationsAsync.mock.calls[0][0].map((message: any) => message.to),+ ).toEqual(['ExponentPushToken[B]', 'ExponentPushToken[C]']);+ });++ it('does not call Expo when every registered device was explicitly excluded', async () => {+ mockListByUserId.mockResolvedValueOnce([+ { deviceId: 'iphone', expoToken: 'ExponentPushToken[A]' },+ ]);++ const expo = makeExpoMock();+ const channel = new PushChannel(expo as any);+ const result = await channel.deliver({+ ...ctx,+ pushPresentation: { excludeDeviceIds: ['iphone'] },+ });++ expect(result).toEqual({ status: 'delivered' });+ expect(expo.sendPushNotificationsAsync).not.toHaveBeenCalled();+ });+it('adds mutable content, image, and custom data for a rich agent notification', async () => {mockListByUserId.mockResolvedValueOnce([{ deviceId: 'iphone', expoToken: 'ExponentPushToken[A]' },@@ -139,6 +183,23 @@ describe('PushChannel', () => {});});+ it('preserves an absolute review URL without logging its credential', async () => {+ const reviewToken = 'A'.repeat(43);+ const reviewUrl = `https://app.lobehub.com/agent-approval?reviewToken=${reviewToken}`;+ mockListByUserId.mockResolvedValueOnce([+ { deviceId: 'iphone', expoToken: 'ExponentPushToken[A]' },+ ]);++ const expo = makeExpoMock();+ expo.sendPushNotificationsAsync.mockResolvedValueOnce([{ id: 'ticket-1', status: 'ok' }]);++ const channel = new PushChannel(expo as any);+ await channel.deliver({ ...ctx, actionUrl: reviewUrl });++ expect(expo.sendPushNotificationsAsync.mock.calls[0][0][0].data.url).toBe(reviewUrl);+ expect(JSON.stringify(mockLog.mock.calls)).not.toContain(reviewToken);+ });+it('drops send-time errors but still returns sent if at least one ticket succeeded', async () => {mockListByUserId.mockResolvedValueOnce([{ deviceId: 'a', expoToken: 'ExponentPushToken[A]' },@@ -150,7 +211,8 @@ describe('PushChannel', () => {{ id: 'ticket-1', status: 'ok' },{details: { error: 'DeviceNotRegistered' },- message: 'token-b dead',+ // Provider-owned messages are untrusted and may echo the credential.+ message: 'ExponentPushToken[B]',status: 'error',},]);@@ -161,6 +223,12 @@ describe('PushChannel', () => {expect(result.status).toBe('sent');const records = JSON.parse(result.providerMessageId!) as PushTicketRecord[];expect(records).toEqual([{ expoToken: 'ExponentPushToken[A]', ticketId: 'ticket-1' }]);+ expect(mockLog).toHaveBeenCalledWith(+ 'Send-time error for deviceId=%s category=%s',+ 'b',+ 'DeviceNotRegistered',+ );+ expect(JSON.stringify(mockLog.mock.calls)).not.toContain('ExponentPushToken[B]');});it('returns all_send_failed when every ticket fails at send time', async () => {diff --git a/apps/server/src/services/push/types.ts b/apps/server/src/services/push/types.tsindex 93c5805ef3e..a165893e40a 100644--- a/apps/server/src/services/push/types.ts+++ b/apps/server/src/services/push/types.ts@@ -10,7 +10,11 @@* but ignored by the push implementation.*/export interface PushDeliveryContext {- /** URL to navigate to when user taps the notification (sent as `data.url`) */+ /**+ * URL to navigate to when the user taps the notification (sent verbatim as+ * `data.url`). Universal-link/cold-start surfaces should provide an absolute+ * HTTPS URL; legacy in-app routes may remain relative.+ */actionUrl?: string;/** Notification body text */content: string;@@ -20,6 +24,12 @@ export interface PushDeliveryContext {pushPresentation?: {/** Extra JSON-safe string values merged into Expo's custom data payload. */data?: Record<string, string>;+ /**+ * Device ids that already received the same notification through another+ * system surface (for example ActivityKit). They are excluded from the+ * ordinary Expo push while all other registered devices retain fallback.+ */+ excludeDeviceIds?: string[];/** Public HTTPS image used by supported system notification surfaces. */image?: string;/** Sets APNs `mutable-content: 1` so an iOS service extension can enrich the alert. */diff --git a/apps/server/src/services/queue/__tests__/QueueService.test.ts b/apps/server/src/services/queue/__tests__/QueueService.test.tsindex 6322810cbb9..c8dbc1c5a1d 100644--- a/apps/server/src/services/queue/__tests__/QueueService.test.ts+++ b/apps/server/src/services/queue/__tests__/QueueService.test.ts@@ -63,6 +63,32 @@ describe('QueueService', () => {expect(taskId).toMatch(/^local-test-op-0-\d+$/);});+ it('deduplicates retries with the same stable execution key', async () => {+ vi.useFakeTimers();+ const execution = vi.fn().mockResolvedValue(undefined);+ const { LocalQueueServiceImpl } = await import('../impls/local');+ const impl = new LocalQueueServiceImpl();+ impl.setExecutionCallback(execution);+ const message = {+ context: { phase: 'user_input' } as any,+ deduplicationId: 'agent-intervention:op-stable:0',+ delay: 0,+ endpoint: 'http://test.com',+ operationId: 'op-stable',+ priority: 'normal' as const,+ stepIndex: 0,+ };++ const [firstTaskId, retryTaskId] = await Promise.all([+ impl.scheduleMessage(message),+ impl.scheduleMessage(message),+ ]);++ expect(retryTaskId).toBe(firstTaskId);+ await vi.runAllTimersAsync();+ expect(execution).toHaveBeenCalledTimes(1);+ });+it('should schedule batch messages in local mode', async () => {const { QueueService } = await import('../QueueService');const service = new QueueService();@@ -219,6 +245,27 @@ describe('QueueService', () => {expect(qstashMocks.publishJSON.mock.calls[0][0]).toMatchObject({ delay: 2 });});++ it('passes the stable intervention deduplication key to QStash', async () => {+ qstashMocks.publishJSON.mockResolvedValue({ messageId: 'msg-test' });++ const { QStashQueueServiceImpl } = await import('../impls/qstash');+ const impl = new QStashQueueServiceImpl({ qstashToken: 'test-qstash-token' });++ await impl.scheduleMessage({+ context: { phase: 'user_input' } as any,+ deduplicationId: 'agent-intervention:op-stable:0',+ delay: 0,+ endpoint: 'https://example.com/api/agent/run',+ operationId: 'op-stable',+ priority: 'high',+ stepIndex: 0,+ });++ expect(qstashMocks.publishJSON).toHaveBeenCalledWith(+ expect.objectContaining({ deduplicationId: 'agent-intervention:op-stable:0' }),+ );+ });});describe('isQueueAgentRuntimeEnabled', () => {diff --git a/apps/server/src/services/queue/impls/local.ts b/apps/server/src/services/queue/impls/local.tsindex 1616a6de153..b1b60c5d563 100644--- a/apps/server/src/services/queue/impls/local.ts+++ b/apps/server/src/services/queue/impls/local.ts@@ -27,6 +27,7 @@ export type LocalExecutionCallback = (*/export class LocalQueueServiceImpl implements QueueServiceImpl {private executionCallback: LocalExecutionCallback | null = null;+ private deduplicatedExecutions: Map<string, string> = new Map();private pendingExecutions: Set<string> = new Set();/**@@ -38,9 +39,15 @@ export class LocalQueueServiceImpl implements QueueServiceImpl {}async scheduleMessage(message: QueueMessage): Promise<string> {- const { operationId, stepIndex, context, payload, delay = 50 } = message;+ const { operationId, stepIndex, context, payload, delay = 50, deduplicationId } = message;++ if (deduplicationId) {+ const existingTaskId = this.deduplicatedExecutions.get(deduplicationId);+ if (existingTaskId) return existingTaskId;+ }const taskId = `local-${operationId}-${stepIndex}-${Date.now()}`;+ if (deduplicationId) this.deduplicatedExecutions.set(deduplicationId, taskId);log('Local execution scheduled for step %d of operation %s (delay: %dms)',diff --git a/apps/server/src/services/queue/impls/qstash.ts b/apps/server/src/services/queue/impls/qstash.tsindex bb493e82da9..55d3a488d91 100644--- a/apps/server/src/services/queue/impls/qstash.ts+++ b/apps/server/src/services/queue/impls/qstash.ts@@ -38,6 +38,7 @@ export class QStashQueueServiceImpl implements QueueServiceImpl {operationId,stepIndex,context,+ deduplicationId,endpoint,payload,delay = 50,@@ -60,6 +61,7 @@ export class QStashQueueServiceImpl implements QueueServiceImpl {timestamp: Date.now(),},...(qstashDelay === undefined ? {} : { delay: qstashDelay }),+ ...(deduplicationId ? { deduplicationId } : {}),headers: {'Content-Type': 'application/json','X-Agent-Operation-Id': operationId,diff --git a/apps/server/src/services/queue/types.ts b/apps/server/src/services/queue/types.tsindex fdf59956724..82d66d05efd 100644--- a/apps/server/src/services/queue/types.ts+++ b/apps/server/src/services/queue/types.ts@@ -2,6 +2,8 @@ import { type AgentRuntimeContext } from '@lobechat/agent-runtime';export interface QueueMessage {context?: AgentRuntimeContext;+ /** Stable provider-side execute-once key for crash-safe enqueue retries. */+ deduplicationId?: string;delay?: number;endpoint: string;operationId: string;diff --git a/locales/en-US/notification.json b/locales/en-US/notification.jsonindex 3833d265dd2..3f25d7f9bff 100644--- a/locales/en-US/notification.json+++ b/locales/en-US/notification.json@@ -7,6 +7,8 @@"agent_cron_job_failed_paused": "Your scheduled task \"{{jobName}}\" was paused after {{count}} consecutive failures. Review the error and resume it when ready.","agent_cron_job_failed_paused_title": "Scheduled task paused","agent_cron_job_failed_title": "Scheduled task failed",+ "agent_intervention_required": "{{agent}} needs your input: {{summary}}",+ "agent_intervention_required_title": "{{agent}} needs your review","agent_run_completed": "{{preview}}","agent_run_completed_title": "Agent task completed","agent_transfer_reassigned": "A workspace owner transferred your agent \"{{agentTitle}}\" to {{recipientLabel}}.",diff --git a/locales/zh-CN/notification.json b/locales/zh-CN/notification.jsonindex 3ce2e6f4b99..41c3d5b1892 100644--- a/locales/zh-CN/notification.json+++ b/locales/zh-CN/notification.json@@ -7,6 +7,8 @@"agent_cron_job_failed_paused": "定时任务「{{jobName}}」连续失败 {{count}} 次,已自动暂停。请检查错误后手动恢复运行。","agent_cron_job_failed_paused_title": "定时任务已暂停","agent_cron_job_failed_title": "定时任务执行失败",+ "agent_intervention_required": "{{agent}} 需要你的输入:{{summary}}",+ "agent_intervention_required_title": "{{agent}} 等待你的审核","agent_run_completed": "{{preview}}","agent_run_completed_title": "Agent 任务已完成","agent_transfer_reassigned": "工作区所有者已将您的代理 \"{{agentTitle}}\" 转移至 {{recipientLabel}}。",diff --git a/packages/agent-gateway-client/src/index.ts b/packages/agent-gateway-client/src/index.tsindex c994d5009c7..62a8d18c34a 100644--- a/packages/agent-gateway-client/src/index.ts+++ b/packages/agent-gateway-client/src/index.ts@@ -1,5 +1,11 @@export { AgentStreamClient } from './client';+export { sanitizeAgentInterventionRequestForReview } from './intervention';export type {+ AgentInterventionInteractionKind,+ AgentInterventionProvider,+ AgentInterventionRenderArguments,+ AgentInterventionRenderOption,+ AgentInterventionRenderQuestion,AgentInterventionRequestData,AgentInterventionResponseData,AgentStreamClientEvents,diff --git a/packages/agent-gateway-client/src/intervention.test.ts b/packages/agent-gateway-client/src/intervention.test.tsnew file mode 100644index 00000000000..c61b0455055--- /dev/null+++ b/packages/agent-gateway-client/src/intervention.test.ts@@ -0,0 +1,90 @@+import { describe, expect, it } from 'vitest';++import { sanitizeAgentInterventionRequestForReview } from './intervention';+import type { AgentInterventionRequestData } from './types';++const request = (overrides: Partial<AgentInterventionRequestData> = {}) => ({+ apiName: 'askUserQuestion',+ arguments: JSON.stringify({+ ignoredRawToolField: 'secret',+ questions: [+ {+ header: 'Permission',+ multiSelect: false,+ options: [+ { id: 'allow_once', ignored: 'secret', label: 'Allow' },+ { id: 'deny', label: 'Deny' },+ ],+ question: 'Edit README?',+ },+ ],+ }),+ deadline: Date.now() + 60_000,+ identifier: 'claude-code',+ interactionKind: 'permission' as const,+ provider: 'cursor' as const,+ toolCallId: 'permission-1',+ ...overrides,+});++describe('sanitizeAgentInterventionRequestForReview', () => {+ it('keeps only canonical review fields and exact provider option ids', () => {+ const sanitized = sanitizeAgentInterventionRequestForReview(request());++ expect(JSON.parse(sanitized!.arguments)).toEqual({+ questions: [+ {+ header: 'Permission',+ multiSelect: false,+ options: [+ { id: 'allow_once', label: 'Allow' },+ { id: 'deny', label: 'Deny' },+ ],+ question: 'Edit README?',+ },+ ],+ });+ });++ it('fails closed when a permission option lacks an id or ids are duplicated', () => {+ const missingId = request({+ arguments: JSON.stringify({+ questions: [+ {+ header: 'Permission',+ multiSelect: false,+ options: [{ label: 'Allow' }],+ question: 'Proceed?',+ },+ ],+ }),+ });+ const duplicateIds = request({+ arguments: JSON.stringify({+ questions: [+ {+ header: 'Permission',+ multiSelect: false,+ options: [+ { id: 'same', label: 'Allow' },+ { id: 'same', label: 'Deny' },+ ],+ question: 'Proceed?',+ },+ ],+ }),+ });++ expect(sanitizeAgentInterventionRequestForReview(missingId)).toBeUndefined();+ expect(sanitizeAgentInterventionRequestForReview(duplicateIds)).toBeUndefined();+ });++ it('requires explicit provider and interaction kind for durable review', () => {+ expect(+ sanitizeAgentInterventionRequestForReview(request({ provider: undefined })),+ ).toBeUndefined();+ expect(+ sanitizeAgentInterventionRequestForReview(request({ interactionKind: undefined })),+ ).toBeUndefined();+ });+});diff --git a/packages/agent-gateway-client/src/intervention.ts b/packages/agent-gateway-client/src/intervention.tsnew file mode 100644index 00000000000..57f0f5ed5fd--- /dev/null+++ b/packages/agent-gateway-client/src/intervention.ts@@ -0,0 +1,114 @@+import type {+ AgentInterventionInteractionKind,+ AgentInterventionProvider,+ AgentInterventionRenderArguments,+ AgentInterventionRenderOption,+ AgentInterventionRequestData,+} from './types';++const INTERACTION_KINDS = new Set<AgentInterventionInteractionKind>([+ 'permission',+ 'plan',+ 'question',+]);+const PROVIDERS = new Set<AgentInterventionProvider>(['claude-code', 'cursor', 'qoder']);++const asRecord = (value: unknown): Record<string, unknown> | undefined =>+ value !== null && typeof value === 'object' && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : undefined;++const boundedString = (value: unknown, maxLength: number): string | undefined =>+ typeof value === 'string' && value.length > 0 && value.length <= maxLength ? value : undefined;++/**+ * Reconstruct the only request payload that may cross the durable Review+ * boundary. Unknown keys and raw tool arguments are discarded, malformed or+ * ambiguous provider choices fail closed, and permission/plan option ids are+ * mandatory so a label can never be mistaken for provider consent.+ */+export const sanitizeAgentInterventionRequestForReview = (+ request: AgentInterventionRequestData | undefined,+): AgentInterventionRequestData | undefined => {+ if (+ !request ||+ request.apiName !== 'askUserQuestion' ||+ !request.interactionKind ||+ !INTERACTION_KINDS.has(request.interactionKind) ||+ !request.provider ||+ !PROVIDERS.has(request.provider) ||+ !Number.isFinite(request.deadline)+ ) {+ return;+ }++ let parsed: unknown;+ try {+ parsed = JSON.parse(request.arguments);+ } catch {+ return;+ }++ const rawQuestions = asRecord(parsed)?.questions;+ if (!Array.isArray(rawQuestions) || rawQuestions.length < 1 || rawQuestions.length > 4) return;++ const questions: AgentInterventionRenderArguments['questions'] = [];+ for (const rawQuestion of rawQuestions) {+ const questionRecord = asRecord(rawQuestion);+ if (!questionRecord) return;++ const question = boundedString(questionRecord.question, 4000);+ const header = questionRecord.header === '' ? '' : boundedString(questionRecord.header, 200);+ const rawOptions = questionRecord.options;+ if (+ question === undefined ||+ header === undefined ||+ typeof questionRecord.multiSelect !== 'boolean' ||+ !Array.isArray(rawOptions) ||+ rawOptions.length < 1 ||+ rawOptions.length > 16+ ) {+ return;+ }++ const options: AgentInterventionRenderOption[] = [];+ const optionIds = new Set<string>();+ for (const rawOption of rawOptions) {+ const optionRecord = asRecord(rawOption);+ const label = boundedString(optionRecord?.label, 200);+ const id = boundedString(optionRecord?.id, 200);+ const description =+ optionRecord?.description === undefined+ ? undefined+ : boundedString(optionRecord.description, 1000);+ if (+ !optionRecord ||+ !label ||+ (optionRecord.description !== undefined && description === undefined) ||+ (request.interactionKind !== 'question' && !id) ||+ (id !== undefined && optionIds.has(id))+ ) {+ return;+ }+ if (id) optionIds.add(id);+ options.push({ ...(description ? { description } : {}), ...(id ? { id } : {}), label });+ }++ questions.push({+ header,+ multiSelect: questionRecord.multiSelect === true,+ options,+ question,+ });+ }++ return {+ apiName: request.apiName,+ arguments: JSON.stringify({ questions } satisfies AgentInterventionRenderArguments),+ deadline: request.deadline,+ identifier: request.identifier,+ interactionKind: request.interactionKind,+ provider: request.provider,+ toolCallId: request.toolCallId,+ };+};diff --git a/packages/agent-gateway-client/src/types.ts b/packages/agent-gateway-client/src/types.tsindex 1cebd0ddc0a..6b621a1d656 100644--- a/packages/agent-gateway-client/src/types.ts+++ b/packages/agent-gateway-client/src/types.ts@@ -193,6 +193,32 @@ export interface OperationHeartbeatData extends StepCompleteData {phase: 'operation_heartbeat';}+/** Semantic interaction shape, independent of the legacy tool renderer id. */+export type AgentInterventionInteractionKind = 'permission' | 'plan' | 'question';++/** Producer that owns the blocked interaction. */+export type AgentInterventionProvider = 'claude-code' | 'cursor' | 'qoder';++/** Whitelisted option surface that may be persisted for cold-start review. */+export interface AgentInterventionRenderOption {+ description?: string;+ /** Required for provider-owned permission/plan choices. */+ id?: string;+ label: string;+}++/** Canonical AskUserQuestion surface shared by every supported provider. */+export interface AgentInterventionRenderQuestion {+ header: string;+ multiSelect: boolean;+ options: AgentInterventionRenderOption[];+ question: string;+}++export interface AgentInterventionRenderArguments {+ questions: AgentInterventionRenderQuestion[];+}+/*** Producer → consumer: structured-input request the user must answer* directly (no tool execution involved). The producer's tool handler stays@@ -208,6 +234,17 @@ export interface AgentInterventionRequestData {deadline: number;/** Tool plugin identifier (e.g. `'claude-code'`). */identifier: string;+ /**+ * Semantic interaction shape. Optional only for older wire producers; all+ * current producers stamp it explicitly so consumers never infer behavior+ * from `identifier`.+ */+ interactionKind?: AgentInterventionInteractionKind;+ /**+ * Agent provider that owns the blocked request. Optional for backward wire+ * compatibility; current producers always include it.+ */+ provider?: AgentInterventionProvider;/** Correlation key. Stable for the lifetime of the intervention. */toolCallId: string;}@@ -221,6 +258,13 @@ export interface AgentInterventionResponseData {cancelled?: boolean;/** When `cancelled`, optional reason for telemetry/logging. */cancelReason?: 'timeout' | 'user_cancelled' | 'session_ended';+ /** True only on the producer's post-resolution echo (durable ACK boundary). */+ producerAck?: boolean;+ /**+ * Client-minted idempotency key. Present on user-driven responses and echoed+ * unchanged by the producer so durable storage can cross the ACK boundary.+ */+ resolutionRequestId?: string;/** User-supplied answer (JSON-serializable). Absent when cancelled. */result?: unknown;toolCallId: string;diff --git a/packages/agent-runtime/src/agents/GeneralChatAgent.ts b/packages/agent-runtime/src/agents/GeneralChatAgent.tsindex 7a9e68b3907..5a186f2b1b5 100644--- a/packages/agent-runtime/src/agents/GeneralChatAgent.ts+++ b/packages/agent-runtime/src/agents/GeneralChatAgent.ts@@ -111,31 +111,6 @@ export class GeneralChatAgent implements Agent {return !!config && typeof config === 'object' && !Array.isArray(config) && 'dynamic' in config;}- private matchesAlwaysPolicy(- config: HumanInterventionConfig | undefined,- toolArgs: Record<string, any>,- ): boolean {- if (!config) return false;- if (config === 'always') return true;- if (!Array.isArray(config)) return false;-- return config.some((rule) => {- if (rule.policy !== 'always') return false;- if (!rule.match) return true;-- return Object.entries(rule.match).every(([paramName, matcher]) => {- const paramValue = toolArgs[paramName];- if (paramValue === undefined) return false;-- if (typeof matcher === 'string') {- return String(paramValue).includes(matcher) || matcher.includes('*');- }-- return true;- });- });- }-private resolveDynamicPolicy(config: ExtendedHumanInterventionConfig | undefined,toolArgs: Record<string, any>,@@ -193,20 +168,28 @@ export class GeneralChatAgent implements Agent {}// Phase 1: Run global resolvers (e.g., security blacklist)- let globalBlocked = false;- let globalPolicy: HumanInterventionPolicy = 'always';-- // Default global audits are ordered so always-block rules match first+ let globalPolicy: HumanInterventionPolicy | undefined;++ // Evaluate every audit and retain the strictest match. Security does not+ // depend on registration order: a preceding `required` match must never+ // hide a later non-bypassable `always` match.+ const policyRank: Record<HumanInterventionPolicy, number> = {+ always: 2,+ never: 0,+ required: 1,+ };for (const globalResolver of globalResolvers) {if (await globalResolver.resolver(toolArgs, resolverMetadata)) {- globalBlocked = true;- globalPolicy = globalResolver.policy ?? 'always';- break;+ const matchedPolicy = globalResolver.policy ?? 'always';+ if (!globalPolicy || policyRank[matchedPolicy] > policyRank[globalPolicy]) {+ globalPolicy = matchedPolicy;+ }}}- // For non-headless modes: 'always' global block requires intervention unconditionally- if (globalBlocked && globalPolicy === 'always') {+ // Global `always` is non-bypassable in every interactive mode (headless+ // is converted to a blocked tool result by the runner).+ if (globalPolicy === 'always') {toolsNeedingIntervention.push(toolCalling);continue;}@@ -221,49 +204,45 @@ export class GeneralChatAgent implements Agent {const staticConfig = isDynamicConfig? undefined: (config as HumanInterventionConfig | undefined);+ const staticPolicy = InterventionChecker.shouldIntervene({+ config: staticConfig,+ // Global audits already performed the security pass above. Passing an+ // explicit empty list reuses the canonical rule matcher without+ // re-running the default blacklist or maintaining a divergent matcher.+ securityBlacklist: [],+ toolArgs,+ });if (dynamicPolicy !== undefined) {- if (dynamicPolicy === 'never') {- toolsToExecute.push(toolCalling);- } else if (- (approvalMode === 'auto-run' || approvalMode === 'headless') &&- dynamicPolicy !== 'always'- ) {- toolsToExecute.push(toolCalling);- } else {+ if (dynamicPolicy === 'always') {toolsNeedingIntervention.push(toolCalling);+ continue;}+ } else if (staticPolicy === 'always') {+ toolsNeedingIntervention.push(toolCalling);continue;}- // Phase 3.5: Headless mode auto-runs global blocks with non-always policy- if (approvalMode === 'headless' && globalBlocked && globalPolicy !== 'always') {+ // auto-run/headless bypass `required` policies, but never `always`+ // (already handled above).+ if (approvalMode === 'headless' || approvalMode === 'auto-run') {toolsToExecute.push(toolCalling);continue;}- // Phase 3.5: Handle overridable global block (policy !== 'always')- if (globalBlocked && globalPolicy !== 'always') {- toolsNeedingIntervention.push(toolCalling);- continue;- }-- // Phase 4: Check 'always' policy - overrides auto-run mode- if (this.matchesAlwaysPolicy(staticConfig, toolArgs)) {+ // A global `required` audit is stronger than a per-tool dynamic `never`.+ // It remains mandatory in manual/allow-list modes; previously the early+ // dynamic branch could silently execute the audited call.+ if (globalPolicy === 'required') {toolsNeedingIntervention.push(toolCalling);continue;}- // Headless/CLI has no approval UI. Auto-run overridable tool-level policies,- // while preserving non-bypassable `always` blocks handled above.- if (approvalMode === 'headless') {- toolsToExecute.push(toolCalling);- continue;- }-- // Phase 5: User config is 'auto-run', all tools execute directly- if (approvalMode === 'auto-run') {- toolsToExecute.push(toolCalling);+ if (dynamicPolicy !== undefined) {+ if (dynamicPolicy === 'never') toolsToExecute.push(toolCalling);+ else if (approvalMode === 'allow-list' && allowList.includes(toolKey))+ toolsToExecute.push(toolCalling);+ else toolsNeedingIntervention.push(toolCalling);continue;}@@ -288,13 +267,7 @@ export class GeneralChatAgent implements Agent {}// Phase 7: User config is 'manual' (default), use tool's own config- const policy = InterventionChecker.shouldIntervene({- config: staticConfig,- securityBlacklist,- toolArgs,- });-- if (policy === 'never') {+ if (staticPolicy === 'never') {toolsToExecute.push(toolCalling);} else {toolsNeedingIntervention.push(toolCalling);@@ -423,6 +396,69 @@ export class GeneralChatAgent implements Agent {return [];}+ /**+ * Build the partial-decision parking instruction from authoritative message+ * rows. The plain tool payload intentionally omits renderer-only intervention+ * fields, so correlation travels beside it as a server-only supersession+ * descriptor. A partially stamped or cross-batch set fails closed instead of+ * creating a second independently actionable Review.+ */+ private buildPendingApprovalRepark(pendingToolMessages: any[]): AgentInstruction {+ const parentIds = new Set(+ pendingToolMessages+ .map((message) => message.parentId)+ .filter((parentId): parentId is string => typeof parentId === 'string' && !!parentId),+ );+ if (parentIds.size !== 1) {+ throw new Error('Cannot re-park interventions without one authoritative assistant owner');+ }++ const pendingTools = pendingToolMessages+ .map((message: any) => message.plugin)+ .filter(Boolean) as ChatToolPayload[];+ const previousIdentities = pendingToolMessages.map((message: any) => ({+ batchId: message.pluginIntervention?.batchId,+ operationId: message.pluginIntervention?.operationId,+ toolCallId: message.tool_call_id ?? message.plugin?.id,+ }));+ const hasDurableIdentity = previousIdentities.some(+ ({ batchId, operationId }) => batchId || operationId,+ );+ let supersedes: Extract<AgentInstruction, { type: 'request_human_approve' }>['supersedes'];+ if (hasDurableIdentity) {+ const first = previousIdentities[0];+ if (+ typeof first.batchId !== 'string' ||+ !first.batchId ||+ typeof first.operationId !== 'string' ||+ !first.operationId ||+ previousIdentities.some(+ (identity) =>+ identity.batchId !== first.batchId ||+ identity.operationId !== first.operationId ||+ typeof identity.toolCallId !== 'string' ||+ !identity.toolCallId,+ )+ ) {+ throw new Error('Cannot re-park a partial or mixed durable intervention batch');+ }+ supersedes = {+ batchId: first.batchId,+ operationId: first.operationId,+ toolCallIds: previousIdentities.map(({ toolCallId }) => toolCallId as string),+ };+ }++ return {+ parentMessageId: [...parentIds][0],+ pendingToolsCalling: pendingTools,+ reason: 'Some tools still pending approval',+ skipCreateToolMessage: true,+ ...(supersedes && { supersedes }),+ type: 'request_human_approve',+ };+ }+/*** Every pending tool message visible in `state.messages`, across BOTH shapes* and WITHOUT turn scoping.@@ -786,14 +822,7 @@ export class GeneralChatAgent implements Agent {// If there are pending tools, wait for human approvalif (pendingToolMessages.length > 0) {- const pendingTools = pendingToolMessages.map((m: any) => m.plugin).filter(Boolean);-- return {- pendingToolsCalling: pendingTools,- reason: 'Some tools still pending approval',- skipCreateToolMessage: true,- type: 'request_human_approve',- };+ return this.buildPendingApprovalRepark(pendingToolMessages);}if (context.stepContext?.hasQueuedMessages) {@@ -826,14 +855,7 @@ export class GeneralChatAgent implements Agent {// If there are pending tools, wait for human approvalif (pendingToolMessages.length > 0) {- const pendingTools = pendingToolMessages.map((m: any) => m.plugin).filter(Boolean);-- return {- pendingToolsCalling: pendingTools,- reason: 'Some tools still pending approval',- skipCreateToolMessage: true,- type: 'request_human_approve',- };+ return this.buildPendingApprovalRepark(pendingToolMessages);}// If there are queued user messages, finish early so the queuediff --git a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.tsindex 8f0dbac898d..b3cb672a2e3 100644--- a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts+++ b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts@@ -1,4 +1,8 @@-import { type ChatToolPayload, type GlobalInterventionAuditConfig } from '@lobechat/types';+import {+ type ArgumentMatcher,+ type ChatToolPayload,+ type GlobalInterventionAuditConfig,+} from '@lobechat/types';import { describe, expect, it } from 'vitest';import { type AgentRuntimeContext, type AgentState } from '../../types';@@ -1187,6 +1191,7 @@ describe('GeneralChatAgent', () => {const result = await agent.runner(context, state);expect(result).toEqual({+ parentMessageId: 'assistant-1',type: 'request_human_approve',pendingToolsCalling: [pendingPlugin],reason: 'Some tools still pending approval',@@ -1253,6 +1258,7 @@ describe('GeneralChatAgent', () => {const result = await agent.runner(context, state);expect(result).toEqual({+ parentMessageId: 'assistant-1',type: 'request_human_approve',pendingToolsCalling: [pendingPlugin],reason: 'Some tools still pending approval',@@ -1441,6 +1447,7 @@ describe('GeneralChatAgent', () => {const result = await agent.runner(context, state);expect(result).toEqual({+ parentMessageId: 'assistant-1',type: 'request_human_approve',pendingToolsCalling: [pendingPlugin],reason: 'Some tools still pending approval',@@ -1521,6 +1528,7 @@ describe('GeneralChatAgent', () => {const result = await agent.runner(context, state);expect(result).toEqual({+ parentMessageId: 'assistant-1',type: 'request_human_approve',pendingToolsCalling: [pendingPlugin],reason: 'Some tools still pending approval',@@ -3042,6 +3050,116 @@ describe('GeneralChatAgent', () => {},]);});++ it.each(['manual', 'allow-list'] as const)(+ 'does not let a dynamic never policy bypass a global required audit in %s mode',+ async (approvalMode) => {+ const agent = new GeneralChatAgent({+ agentConfig: { maxSteps: 100 },+ dynamicInterventionAudits: { safePath: async () => false },+ globalInterventionAudits: [+ { policy: 'required', resolver: async () => true, type: 'workspaceAudit' },+ ],+ modelRuntimeConfig: mockModelRuntimeConfig,+ operationId: 'test-session',+ });+ const toolCall: ChatToolPayload = {+ apiName: 'readFile',+ arguments: '{"path":"/workspace/a"}',+ id: 'call-1',+ identifier: 'local-system',+ type: 'builtin',+ };+ const state = createMockState({+ toolManifestMap: {+ 'local-system': {+ api: [+ {+ humanIntervention: {+ dynamic: { default: 'never', policy: 'required', type: 'safePath' },+ },+ name: 'readFile',+ },+ ],+ identifier: 'local-system',+ },+ },+ userInterventionConfig: {+ allowList: ['local-system/readFile'],+ approvalMode,+ },+ });++ const result = await agent.runner(+ createMockContext('llm_result', {+ hasToolsCalling: true,+ parentMessageId: 'msg-1',+ toolsCalling: [toolCall],+ }),+ state,+ );++ expect(result).toEqual([+ {+ parentMessageId: 'msg-1',+ pendingToolsCalling: [toolCall],+ reason: 'human_intervention_required',+ type: 'request_human_approve',+ },+ ]);+ },+ );++ it.each<[string, ArgumentMatcher, string]>([+ ['wildcard string', '*.env', '/tmp/readme.md'],+ ['object prefix', { pattern: '/etc/', type: 'prefix' as const }, '/tmp/etc/hosts'],+ ])(+ 'does not treat a non-matching %s always matcher as unconditional',+ async (_, matcher, path) => {+ const agent = new GeneralChatAgent({+ agentConfig: { maxSteps: 100 },+ modelRuntimeConfig: mockModelRuntimeConfig,+ operationId: 'test-session',+ });+ const toolCall: ChatToolPayload = {+ apiName: 'writeFile',+ arguments: JSON.stringify({ path }),+ id: 'call-1',+ identifier: 'file-system',+ type: 'builtin',+ };+ const state = createMockState({+ toolManifestMap: {+ 'file-system': {+ api: [+ {+ humanIntervention: [+ { match: { path: matcher }, policy: 'always' },+ { policy: 'never' },+ ],+ name: 'writeFile',+ },+ ],+ identifier: 'file-system',+ },+ },+ userInterventionConfig: { approvalMode: 'auto-run' },+ });++ const result = await agent.runner(+ createMockContext('llm_result', {+ hasToolsCalling: true,+ parentMessageId: 'msg-1',+ toolsCalling: [toolCall],+ }),+ state,+ );++ expect(result).toEqual([+ { payload: { parentMessageId: 'msg-1', toolCalling: toolCall }, type: 'call_tool' },+ ]);+ },+ );});describe('global intervention resolvers', () => {@@ -3327,12 +3445,12 @@ describe('GeneralChatAgent', () => {expect(Array.isArray(capturedMetadata!.securityBlacklist)).toBe(true);});- it('should evaluate global resolvers in array order and stop at first match', async () => {+ it('should evaluate every global resolver and retain always over an earlier required match', async () => {const callOrder: string[] = [];const resolver1: GlobalInterventionAuditConfig = {type: 'first',- policy: 'always',+ policy: 'required',resolver: async () => {callOrder.push('first');return true; // matches@@ -3341,7 +3459,7 @@ describe('GeneralChatAgent', () => {const resolver2: GlobalInterventionAuditConfig = {type: 'second',- policy: 'required',+ policy: 'always',resolver: async () => {callOrder.push('second');return true;@@ -3365,6 +3483,7 @@ describe('GeneralChatAgent', () => {const state = createMockState({toolManifestMap: { 'my-tool': { identifier: 'my-tool' } },+ userInterventionConfig: { approvalMode: 'auto-run' },});const context = createMockContext('llm_result', {@@ -3373,10 +3492,17 @@ describe('GeneralChatAgent', () => {parentMessageId: 'msg-1',});- await agent.runner(context, state);+ const result = await agent.runner(context, state);- // Only first resolver should be called (break on first match)- expect(callOrder).toEqual(['first']);+ expect(callOrder).toEqual(['first', 'second']);+ expect(result).toEqual([+ {+ parentMessageId: 'msg-1',+ pendingToolsCalling: [toolCall],+ reason: 'human_intervention_required',+ type: 'request_human_approve',+ },+ ]);});it('should use default security blacklist audit when globalInterventionAudits is not provided', async () => {@@ -3848,7 +3974,7 @@ describe('GeneralChatAgent', () => {// `role: 'assistantGroup'` message. Matching only the raw shape made this// guard a permanent no-op there: approving one tool of a parallel batch// resumed the LLM while the siblings were still pending empty rows.- const groupedToolEntry = (id: string, status: 'pending' | 'approved') => ({+ const groupedToolEntry = (id: string, status: 'pending' | 'approved' | 'rejected') => ({apiName: 'calculate',arguments: `{"expression":"${id}"}`,id,@@ -3872,6 +3998,20 @@ describe('GeneralChatAgent', () => {] as any,});+ const durableGroupedToolEntry = (+ id: string,+ status: 'pending' | 'approved' | 'rejected',+ apiName = 'calculate',+ ) => ({+ ...groupedToolEntry(id, status),+ apiName,+ intervention: {+ batchId: 'old-operation:0:msg-assistant',+ operationId: 'old-operation',+ status,+ },+ });+it('re-parks on the parsed assistantGroup shape while siblings are still pending', async () => {const agent = new GeneralChatAgent({agentConfig: { maxSteps: 100 },@@ -3935,6 +4075,86 @@ describe('GeneralChatAgent', () => {expect((result as any).type).toBe('call_llm');});+ it.each([+ ['approved', 'rejected'],+ ['rejected', 'approved'],+ ] as const)(+ 're-parks two binary cards after a first %s decision and calls the LLM once after %s',+ async (firstDecision, finalDecision) => {+ const agent = new GeneralChatAgent({+ agentConfig: { maxSteps: 100 },+ operationId: 'continued-operation',+ modelRuntimeConfig: mockModelRuntimeConfig,+ });+ const first = await agent.runner(+ createMockContext('tool_result', { parentMessageId: 'tool-msg-call-a' }),+ parsedStateWith([+ durableGroupedToolEntry('call-a', firstDecision),+ durableGroupedToolEntry('call-b', 'pending'),+ ]),+ );+ const last = await agent.runner(+ createMockContext('tool_result', { parentMessageId: 'tool-msg-call-b' }),+ parsedStateWith([+ durableGroupedToolEntry('call-a', firstDecision),+ durableGroupedToolEntry('call-b', finalDecision),+ ]),+ );++ expect(first).toMatchObject({+ parentMessageId: 'msg-assistant',+ skipCreateToolMessage: true,+ supersedes: {+ batchId: 'old-operation:0:msg-assistant',+ operationId: 'old-operation',+ toolCallIds: ['call-b'],+ },+ type: 'request_human_approve',+ });+ expect(+ [first, last].filter((instruction: any) => instruction.type === 'call_llm'),+ ).toHaveLength(1);+ expect((last as any).type).toBe('call_llm');+ },+ );++ it.each([+ ['binary-first', 'calculate', 'askUserQuestion'],+ ['question-first', 'askUserQuestion', 'calculate'],+ ] as const)(+ 'keeps a mixed binary + AskUser batch behind one continuation (%s)',+ async (_label, settledApiName, pendingApiName) => {+ const agent = new GeneralChatAgent({+ agentConfig: { maxSteps: 100 },+ operationId: 'continued-operation',+ modelRuntimeConfig: mockModelRuntimeConfig,+ });+ const first = await agent.runner(+ createMockContext('tool_result', { parentMessageId: 'tool-msg-call-settled' }),+ parsedStateWith([+ durableGroupedToolEntry('call-settled', 'approved', settledApiName),+ durableGroupedToolEntry('call-pending', 'pending', pendingApiName),+ ]),+ );+ const last = await agent.runner(+ createMockContext('tool_result', { parentMessageId: 'tool-msg-call-pending' }),+ parsedStateWith([+ durableGroupedToolEntry('call-settled', 'approved', settledApiName),+ durableGroupedToolEntry('call-pending', 'approved', pendingApiName),+ ]),+ );++ expect(first).toMatchObject({+ supersedes: { toolCallIds: ['call-pending'] },+ type: 'request_human_approve',+ });+ expect(+ [first, last].filter((instruction: any) => instruction.type === 'call_llm'),+ ).toHaveLength(1);+ expect((last as any).type).toBe('call_llm');+ },+ );+it('still re-parks on the raw assistant + tool-row shape', async () => {const agent = new GeneralChatAgent({agentConfig: { maxSteps: 100 },diff --git a/packages/agent-runtime/src/executors/humanApprove.test.ts b/packages/agent-runtime/src/executors/humanApprove.test.tsindex 1ca35459cdc..20297ef49fb 100644--- a/packages/agent-runtime/src/executors/humanApprove.test.ts+++ b/packages/agent-runtime/src/executors/humanApprove.test.ts@@ -50,12 +50,14 @@ describe('requestHumanApprove', () => {let createToolMessage: ReturnType<typeof vi.fn>;let deleteMessage: ReturnType<typeof vi.fn>;let query: ReturnType<typeof vi.fn>;+ let updateToolIntervention: ReturnType<typeof vi.fn>;let host: AgentRuntimeHost;beforeEach(() => {createToolMessage = vi.fn().mockResolvedValue({ id: 'tool-msg-1' });deleteMessage = vi.fn().mockResolvedValue(undefined);query = vi.fn().mockResolvedValue([]);+ updateToolIntervention = vi.fn().mockResolvedValue(undefined);host = {lifecycle: { dispatch: vi.fn().mockResolvedValue(undefined) },@@ -66,7 +68,7 @@ describe('requestHumanApprove', () => {topicId: 'topic-1',},transports: {- messages: { createToolMessage, deleteMessage, query },+ messages: { createToolMessage, deleteMessage, query, updateToolIntervention },stream: { publishChunk: vi.fn(), publishEvent: vi.fn() },},} as unknown as AgentRuntimeHost;@@ -160,7 +162,96 @@ describe('requestHumanApprove', () => {expect((host.transports.stream.publishChunk as ReturnType<typeof vi.fn>).mock.calls[0][0],).toMatchObject({ toolMessageIds: { call_ask_1: 'tool-msg-existing' } });+ expect(updateToolIntervention).toHaveBeenCalledWith('tool-msg-existing', {+ batchId: 'op-1:1:assistant-current',+ itemIndex: 0,+ operationId: 'op-1',+ status: 'pending',+ stepIndex: 1,+ });+ });++ it('carries the exact previous sealed batch when pending siblings are rebound', async () => {+ const secondPendingTool = {+ ...pendingTool,+ id: 'call_ask_2',+ intervention: {+ batchId: 'old-op:0:assistant-current',+ operationId: 'old-op',+ status: 'pending' as const,+ },+ };+ const firstPendingTool = {+ ...pendingTool,+ intervention: {+ batchId: 'old-op:0:assistant-current',+ operationId: 'old-op',+ status: 'pending' as const,+ },+ };+ query.mockResolvedValue([+ { id: 'tool-msg-existing-1', role: 'tool', tool_call_id: 'call_ask_1' },+ { id: 'tool-msg-existing-2', role: 'tool', tool_call_id: 'call_ask_2' },+ ]);++ const result = await requestHumanApprove(host)(+ {+ parentMessageId: 'assistant-current',+ pendingToolsCalling: [firstPendingTool, secondPendingTool],+ skipCreateToolMessage: true,+ type: 'request_human_approve',+ },+ createState(),+ );++ expect(result.newState.pendingApprovalBatch).toEqual({+ assistantMessageId: 'assistant-current',+ id: 'op-1:1:assistant-current',+ sealed: true,+ stepIndex: 1,+ supersedes: {+ batchId: 'old-op:0:assistant-current',+ operationId: 'old-op',+ toolCallIds: ['call_ask_1', 'call_ask_2'],+ },+ });});++ it('fails closed instead of superseding a partial or mixed durable batch', async () => {+ await expect(+ requestHumanApprove(host)(+ {+ parentMessageId: 'assistant-current',+ pendingToolsCalling: [+ {+ ...pendingTool,+ intervention: { batchId: 'old-batch', operationId: 'old-op', status: 'pending' },+ },+ { ...pendingTool, id: 'call_ask_2' },+ ],+ skipCreateToolMessage: true,+ type: 'request_human_approve',+ },+ createState(),+ ),+ ).rejects.toThrow(/partial or mixed durable intervention batch/);+ expect(updateToolIntervention).not.toHaveBeenCalled();+ });++ it('fails closed when a resumed batch cannot locate every durable tool row', async () => {+ const instruction: Extract<AgentInstruction, { type: 'request_human_approve' }> = {+ parentMessageId: 'assistant-current',+ pendingToolsCalling: [pendingTool],+ skipCreateToolMessage: true,+ type: 'request_human_approve',+ };++ await expect(requestHumanApprove(host)(instruction, createState())).rejects.toThrow(+ /Missing durable tool message/,+ );+ expect(updateToolIntervention).not.toHaveBeenCalled();+ });+describe('unconsumed assistant placeholder', () => {// A resume op (approve / answer) seeds an assistant placeholder so the UI// shows a spinner, and the first `call_llm` claims it. Parking here means no@@ -174,6 +265,12 @@ describe('requestHumanApprove', () => {type: 'request_human_approve',} as unknown as AgentInstruction;+ beforeEach(() => {+ query.mockResolvedValue([+ { id: 'tool-msg-existing', role: 'tool', tool_call_id: 'call_ask_1' },+ ]);+ });+it('retires the seeded placeholder when the run parks without calling the LLM', async () => {const result = await requestHumanApprove(host)(instruction,diff --git a/packages/agent-runtime/src/executors/humanApprove.ts b/packages/agent-runtime/src/executors/humanApprove.tsindex 87d415f6cfe..3ff01bd759a 100644--- a/packages/agent-runtime/src/executors/humanApprove.ts+++ b/packages/agent-runtime/src/executors/humanApprove.ts@@ -14,10 +14,12 @@ import type { AgentEvent, AgentInstruction, AnyHookEvent, InstructionExecutor }export const requestHumanApprove =(host: AgentRuntimeHost): InstructionExecutor =>async (instruction, state) => {- const { parentMessageId, pendingToolsCalling, skipCreateToolMessage } = instruction as Extract<- AgentInstruction,- { type: 'request_human_approve' }- >;+ const {+ parentMessageId,+ pendingToolsCalling,+ skipCreateToolMessage,+ supersedes: instructionSupersedes,+ } = instruction as Extract<AgentInstruction, { type: 'request_human_approve' }>;const { operation, transports, lifecycle } = host;const { operationId, stepIndex, userId } = operation;const agentId = operation.agentId ?? state.metadata?.agentId;@@ -78,12 +80,64 @@ export const requestHumanApprove =// Map of toolCallId -> toolMessageId, populated either by creating fresh// pending tool messages or (in resumption mode) by looking up existing ones.const toolMessageIds: Record<string, string> = {};+ let approvalAssistantMessageId = parentMessageId;+ let supersedes: { batchId: string; operationId: string; toolCallIds: string[] } | undefined;if (skipCreateToolMessage) {+ // The payloads came from the authoritative pending tool rows. Preserve+ // their previous generic batch identity before rebinding the rows below,+ // so the server can atomically terminal that batch when it persists the+ // replacement. A partially-stamped set is unsafe: creating a second+ // Review would otherwise leave the old token and Live Activity active.+ const previousIdentities = pendingToolsCalling.map((toolPayload) => ({+ batchId: toolPayload.intervention?.batchId,+ operationId: toolPayload.intervention?.operationId,+ toolCallId: toolPayload.id,+ }));+ const hasPreviousDurableIdentity = previousIdentities.some(+ ({ batchId, operationId: previousOperationId }) => batchId || previousOperationId,+ );+ if (instructionSupersedes) {+ const pendingToolCallIds = pendingToolsCalling.map(({ id }) => id);+ if (+ instructionSupersedes.toolCallIds.length !== pendingToolCallIds.length ||+ new Set(instructionSupersedes.toolCallIds).size !== pendingToolCallIds.length ||+ instructionSupersedes.toolCallIds.some((id) => !pendingToolCallIds.includes(id))+ ) {+ throw new Error(+ `[request_human_approve] Supersession does not match rebound members (op=${operationId})`,+ );+ }+ supersedes = instructionSupersedes;+ } else if (hasPreviousDurableIdentity) {+ const firstPrevious = previousIdentities[0];+ if (+ !firstPrevious.batchId ||+ !firstPrevious.operationId ||+ previousIdentities.some(+ (identity) =>+ !identity.batchId ||+ !identity.operationId ||+ identity.batchId !== firstPrevious.batchId ||+ identity.operationId !== firstPrevious.operationId,+ )+ ) {+ throw new Error(+ `[request_human_approve] Cannot rebind a partial or mixed durable intervention batch (op=${operationId})`,+ );+ }+ supersedes = {+ batchId: firstPrevious.batchId,+ operationId: firstPrevious.operationId,+ toolCallIds: previousIdentities.map(({ toolCallId }) => toolCallId),+ };+ }+// Resumption mode: tool messages already exist. Look them up by// tool_call_id so we can still ship the mapping to the client.+ let dbMessages: Awaited<ReturnType<typeof transports.messages.query>> = [];try {- const dbMessages = await transports.messages.query({+ dbMessages = await transports.messages.query({agentId,// Group runs need groupId or the query returns no group messages, so// the existing tool-message lookup on resume would find nothing.@@ -91,17 +145,43 @@ export const requestHumanApprove =threadId,topicId,});- for (const toolPayload of pendingToolsCalling) {- const existing = dbMessages.find(- (m: any) => m.role === 'tool' && m.tool_call_id === toolPayload.id,+ } catch {+ // The explicit missing-row guard below keeps the parked batch closed.+ }+ for (const toolPayload of pendingToolsCalling) {+ const existing = dbMessages.find(+ (m: any) => m.role === 'tool' && m.tool_call_id === toolPayload.id,+ );+ if (!existing) {+ throw new Error(+ `[request_human_approve] Missing durable tool message for resumed intervention ${toolPayload.id}`,);- if (existing) {- toolMessageIds[toolPayload.id] = existing.id;- }}- } catch {- // best-effort lookup — a miss just omits the mapping+ toolMessageIds[toolPayload.id] = existing.id;+ }++ if (!approvalAssistantMessageId) {+ throw new Error(+ `[request_human_approve] Missing assistant owner for resumed intervention (op=${operationId})`,+ );}++ // A partial resolution starts a new runtime operation and can park the+ // unresolved siblings again. Rebind those durable rows to the new parked+ // owner and sealed batch; retaining the previous operation id would let+ // Stop target a stale run and make notification durability checks fail.+ const batchId = `${operationId}:${stepIndex}:${approvalAssistantMessageId}`;+ await Promise.all(+ pendingToolsCalling.map((toolPayload, itemIndex) =>+ transports.messages.updateToolIntervention(toolMessageIds[toolPayload.id], {+ batchId,+ itemIndex,+ operationId,+ status: 'pending',+ stepIndex,+ }),+ ),+ );} else {// Resolve the assistant message that owns these tool calls.//@@ -175,14 +255,22 @@ export const requestHumanApprove =);}- for (const toolPayload of pendingToolsCalling) {+ approvalAssistantMessageId = parentAssistant.id;+ const batchId = `${operationId}:${stepIndex}:${parentAssistant.id}`;+ for (const [itemIndex, toolPayload] of pendingToolsCalling.entries()) {const toolMessage = await transports.messages.createToolMessage({agentId,content: '',groupId: groupId ?? parentAssistant.groupId ?? undefined,parentId: parentAssistant.id,plugin: toolPayload as any,- pluginIntervention: { status: 'pending' },+ pluginIntervention: {+ batchId,+ itemIndex,+ operationId,+ status: 'pending',+ stepIndex,+ },role: 'tool',threadId,tool_call_id: toolPayload.id,@@ -199,6 +287,17 @@ export const requestHumanApprove =}}+ newState.pendingToolMessageIds = toolMessageIds;+ if (approvalAssistantMessageId) {+ newState.pendingApprovalBatch = {+ assistantMessageId: approvalAssistantMessageId,+ id: `${operationId}:${stepIndex}:${approvalAssistantMessageId}`,+ sealed: true,+ stepIndex,+ ...(supersedes && { supersedes }),+ };+ }+// Notify frontend to display approval UI through streaming system.// `toolMessageIds` is a new optional field; legacy consumers ignore it.await transports.stream.publishChunk({diff --git a/packages/agent-runtime/src/types/instruction.ts b/packages/agent-runtime/src/types/instruction.tsindex 382c99f9eb7..701a85af0d4 100644--- a/packages/agent-runtime/src/types/instruction.ts+++ b/packages/agent-runtime/src/types/instruction.ts@@ -355,15 +355,22 @@ export interface AgentInstructionRequestHumanApprove extends AgentInstructionBas* creates pending tool rows should set it, so those rows land under their real* owner — see the parent resolution comment in `executors/humanApprove.ts`.*- * Optional for the `skipCreateToolMessage` (resume) paths, which create no- * rows, and for backwards compatibility with producers that omit it: the- * executor still falls back to scanning `state.messages`, which is accurate- * only within a single step.+ * Required by `skipCreateToolMessage` (resume) paths so an unresolved subset+ * can be rebound to its authoritative assistant owner. Optional only for+ * backwards compatibility with fresh producers that omit it: the executor+ * still falls back to scanning `state.messages`, which is accurate only+ * within a single step.*/parentMessageId?: string;pendingToolsCalling: ChatToolPayload[];reason?: string;skipCreateToolMessage?: boolean;+ /** Previous sealed batch for a partial-decision re-park. */+ supersedes?: {+ batchId: string;+ operationId: string;+ toolCallIds: string[];+ };type: 'request_human_approve';}diff --git a/packages/agent-runtime/src/types/state.ts b/packages/agent-runtime/src/types/state.tsindex e3acd080795..db097e63715 100644--- a/packages/agent-runtime/src/types/state.ts+++ b/packages/agent-runtime/src/types/state.ts@@ -96,6 +96,24 @@ export interface AgentState {/** Operation-level tool set snapshot (immutable after creation) */operationToolSet?: OperationToolSet;+ pendingApprovalBatch?: {+ assistantMessageId: string;+ id: string;+ sealed: true;+ stepIndex: number;+ /**+ * Previous durable batch whose still-pending rows were rebound into this+ * parked operation. The server notification adapter turns this into an+ * atomic generic-store supersession; keeping only authoritative source+ * identities here avoids coupling the runtime package to ActivityKit or a+ * Cloud database model.+ */+ supersedes?: {+ batchId: string;+ operationId: string;+ toolCallIds: string[];+ };+ };// --- HIL ---/*** Assistant placeholder seeded for a resume that starts by executing a tool@@ -105,14 +123,16 @@ export interface AgentState {* Cleared once consumed.*/pendingAssistantMessageId?: string;- pendingHumanPrompt?: { metadata?: Record<string, unknown>; prompt: string };+ pendingHumanPrompt?: { metadata?: Record<string, unknown>; prompt: string };pendingHumanSelect?: {metadata?: Record<string, unknown>;multi?: boolean;options: Array<{ label: string; value: string }>;prompt?: string;};+ /** toolCallId -> durable pending tool-message id for the current sealed batch. */+ pendingToolMessageIds?: Record<string, string>;/*** When status is 'waiting_for_human', this stores pending requests* for human-in-the-loop operations.diff --git a/packages/builtin-tool-claude-code/src/client/Intervention/AskUserQuestion/index.tsx b/packages/builtin-tool-claude-code/src/client/Intervention/AskUserQuestion/index.tsxindex d04996f1098..ec633d938b7 100644--- a/packages/builtin-tool-claude-code/src/client/Intervention/AskUserQuestion/index.tsx+++ b/packages/builtin-tool-claude-code/src/client/Intervention/AskUserQuestion/index.tsx@@ -32,7 +32,7 @@ import { useChatStore } from '@/store/chat';*/const AskUserQuestionIntervention = memo<BuiltinInterventionProps<AskUserQuestionArgs>>((props) => {const { t } = useTranslation('tool');- const { actionsPortalTarget, args, messageId, onInteractionAction } = props;+ const { actionsPortalTarget, args, disabled, messageId, onInteractionAction } = props;// Persisted draft — read from the tool message's pluginState so the form// stays where the user left it across unmount / HMR / refresh.@@ -49,6 +49,7 @@ const AskUserQuestionIntervention = memo<BuiltinInterventionProps<AskUserQuestioconst form = useAskUserForm({args,countdownMs: DEFAULT_COUNTDOWN_MS,+ disabled,onInteractionAction,persistedDraft,writeDraft,diff --git a/packages/builtin-tool-user-interaction/src/client/Intervention/AskUserQuestion/index.tsx b/packages/builtin-tool-user-interaction/src/client/Intervention/AskUserQuestion/index.tsxindex cdec13f133f..087caeb20d8 100644--- a/packages/builtin-tool-user-interaction/src/client/Intervention/AskUserQuestion/index.tsx+++ b/packages/builtin-tool-user-interaction/src/client/Intervention/AskUserQuestion/index.tsx@@ -32,7 +32,8 @@ import { useChatStore } from '@/store/chat';*/const AskUserQuestionIntervention = memo<BuiltinInterventionProps<AskUserQuestionArgs>>((props) => {const { t } = useTranslation('tool');- const { actionsPortalTarget, args, interactionMode, messageId, onInteractionAction } = props;+ const { actionsPortalTarget, args, disabled, interactionMode, messageId, onInteractionAction } =+ props;const persistedDraft = useConversationStore((s) => {const msg = dataSelectors.getDbMessageById(messageId)(s);@@ -46,6 +47,7 @@ const AskUserQuestionIntervention = memo<BuiltinInterventionProps<AskUserQuestioconst form = useAskUserForm({args,+ disabled,onInteractionAction,persistedDraft,writeDraft,diff --git a/packages/builtin-tool-web-onboarding/src/agentMarketplace/client/Intervention/PickAgents/index.tsx b/packages/builtin-tool-web-onboarding/src/agentMarketplace/client/Intervention/PickAgents/index.tsxindex 6511a85f6f5..630c33b1a0b 100644--- a/packages/builtin-tool-web-onboarding/src/agentMarketplace/client/Intervention/PickAgents/index.tsx+++ b/packages/builtin-tool-web-onboarding/src/agentMarketplace/client/Intervention/PickAgents/index.tsx@@ -1,7 +1,8 @@'use client';import type { BuiltinInterventionProps } from '@lobechat/types';-import { Avatar, Button, Flexbox, Text } from '@lobehub/ui';+import { Avatar, Flexbox, Text } from '@lobehub/ui';+import { Button } from '@lobehub/ui/base-ui';import { cx } from 'antd-style';import type { KeyboardEvent } from 'react';import { memo, useCallback, useEffect, useMemo, useState } from 'react';@@ -21,7 +22,7 @@ import { styles } from './style';const EMPTY_TEMPLATES: AgentTemplate[] = [];const PickAgentsIntervention = memo<BuiltinInterventionProps<ShowAgentMarketplaceArgs>>(- ({ args, interactionMode, onInteractionAction }) => {+ ({ args, disabled = false, interactionMode, onInteractionAction }) => {const { t } = useTranslation('ui');const { t: tTool } = useTranslation('tool');const isCustom = interactionMode === 'custom';@@ -80,17 +81,21 @@ const PickAgentsIntervention = memo<BuiltinInterventionProps<ShowAgentMarketplacconst [selected, setSelected] = useState<Set<string>>(() => new Set());const [submitting, setSubmitting] = useState(false);- const toggle = useCallback((id: string) => {- setSelected((prev) => {- const next = new Set(prev);- if (next.has(id)) next.delete(id);- else next.add(id);- return next;- });- }, []);+ const toggle = useCallback(+ (id: string) => {+ if (disabled) return;+ setSelected((prev) => {+ const next = new Set(prev);+ if (next.has(id)) next.delete(id);+ else next.add(id);+ return next;+ });+ },+ [disabled],+ );const handleSubmit = useCallback(async () => {- if (!onInteractionAction || selected.size === 0) return;+ if (!onInteractionAction || selected.size === 0 || disabled) return;setSubmitting(true);try {await onInteractionAction({@@ -102,24 +107,25 @@ const PickAgentsIntervention = memo<BuiltinInterventionProps<ShowAgentMarketplac} finally {setSubmitting(false);}- }, [args.requestId, categoryHints, onInteractionAction, selected]);+ }, [args.requestId, categoryHints, disabled, onInteractionAction, selected]);const handleSkip = useCallback(async () => {- if (!onInteractionAction) return;+ if (!onInteractionAction || disabled) return;await onInteractionAction({payload: { categoryHints, requestId: args.requestId },type: 'skip',});- }, [args.requestId, categoryHints, onInteractionAction]);+ }, [args.requestId, categoryHints, disabled, onInteractionAction]);const handleCardKeyDown = useCallback((event: KeyboardEvent<HTMLDivElement>, id: string) => {+ if (disabled) return;if (event.key === 'Enter' || event.key === ' ') {event.preventDefault();toggle(id);}},- [toggle],+ [disabled, toggle],);if (!isCustom) {@@ -172,6 +178,7 @@ const PickAgentsIntervention = memo<BuiltinInterventionProps<ShowAgentMarketplac<buttonaria-selected={isActive}className={cx(styles.categoryItem, isActive && styles.categoryItemActive)}+ disabled={disabled}key={category}role="tab"type="button"@@ -193,11 +200,12 @@ const PickAgentsIntervention = memo<BuiltinInterventionProps<ShowAgentMarketplacconst avatar = tpl.avatar;return (<div+ aria-disabled={disabled}aria-pressed={isSelected}className={cx(styles.card, isSelected && styles.cardSelected)}key={tpl.id}role="button"- tabIndex={0}+ tabIndex={disabled ? -1 : 0}onClick={() => toggle(tpl.id)}onKeyDown={(event) => handleCardKeyDown(event, tpl.id)}>@@ -218,11 +226,15 @@ const PickAgentsIntervention = memo<BuiltinInterventionProps<ShowAgentMarketplac)}<div className={styles.footer}>- <Text className={styles.skipLink} type="secondary" onClick={handleSkip}>+ <Text+ className={styles.skipLink}+ type="secondary"+ onClick={disabled ? undefined : handleSkip}+ >{t('form.skip')}</Text><Button- disabled={selected.size === 0}+ disabled={disabled || selected.size === 0}loading={submitting}type="primary"onClick={handleSubmit}diff --git a/packages/business-server/package.json b/packages/business-server/package.jsonindex e2f8bf2a6ba..68752cc8fb7 100644--- a/packages/business-server/package.json+++ b/packages/business-server/package.json@@ -6,6 +6,7 @@"./*": "./src/*.ts"},"dependencies": {+ "@lobechat/agent-gateway-client": "workspace:*","@lobechat/database": "workspace:*","@lobechat/model-runtime": "workspace:*","@lobechat/trpc": "workspace:*",diff --git a/packages/business-server/src/agent-run/agentInterventionIdentity.ts b/packages/business-server/src/agent-run/agentInterventionIdentity.tsnew file mode 100644index 00000000000..caf0acaa4c5--- /dev/null+++ b/packages/business-server/src/agent-run/agentInterventionIdentity.ts@@ -0,0 +1,123 @@+import { createHash } from 'node:crypto';++const AGENT_INTERVENTION_ACTIVITY_KEY_DOMAIN = 'lobehub:agent-intervention:activity-key:v2';+const AGENT_INTERVENTION_CONTINUATION_OPERATION_DOMAIN =+ 'lobehub:agent-intervention:continuation-operation:v1';++export interface AgentInterventionContinuationProvenance {+ resolutionRequestId: string;+ sourceOperationId: string;+ sourceToolMessageIds: string[];+}++/** Compare JSONB provenance by fields, never by object key insertion order. */+export const matchesAgentInterventionContinuationProvenance = (+ actual: unknown,+ expected: AgentInterventionContinuationProvenance,+): boolean => {+ if (!actual || typeof actual !== 'object' || Array.isArray(actual)) return false;+ const candidate = actual as Partial<AgentInterventionContinuationProvenance>;+ const candidateKeys = Object.keys(candidate).sort();+ if (+ candidateKeys.length !== 3 ||+ candidateKeys[0] !== 'resolutionRequestId' ||+ candidateKeys[1] !== 'sourceOperationId' ||+ candidateKeys[2] !== 'sourceToolMessageIds'+ ) {+ return false;+ }+ if (+ candidate.resolutionRequestId !== expected.resolutionRequestId ||+ candidate.sourceOperationId !== expected.sourceOperationId ||+ !Array.isArray(candidate.sourceToolMessageIds) ||+ !candidate.sourceToolMessageIds.every((id) => typeof id === 'string') ||+ candidate.sourceToolMessageIds.length !== expected.sourceToolMessageIds.length+ ) {+ return false;+ }++ const actualIds = [...candidate.sourceToolMessageIds].sort();+ const expectedIds = [...expected.sourceToolMessageIds].sort();+ return actualIds.every((id, index) => id === expectedIds[index]);+};++/** Canonical edit/claim CAS hash. The raw JSON string is intentionally not normalized. */+export const hashAgentInterventionRequestRevision = (rawArguments: string): string =>+ createHash('sha256').update(rawArguments).digest('hex');++/**+ * Stable operation id for one durable resolution request. A retry after the+ * source message claim can therefore prove whether the exact continuation was+ * durably created instead of treating the pre-dispatch message patch itself as+ * execution evidence.+ */+export const deriveAgentInterventionContinuationOperationId = (params: {+ resolutionRequestId: string;+ userId: string;+ workspaceId?: string | null;+}): string =>+ `op_intervention_${createHash('sha256')+ .update(+ JSON.stringify([+ AGENT_INTERVENTION_CONTINUATION_OPERATION_DOMAIN,+ params.userId,+ params.workspaceId ?? null,+ params.resolutionRequestId,+ ]),+ )+ .digest('hex')+ .slice(0, 32)}`;++/** Stable assistant placeholder paired with the continuation operation above. */+export const deriveAgentInterventionContinuationMessageId = (+ params: Parameters<typeof deriveAgentInterventionContinuationOperationId>[0],+): string =>+ `msg_intervention_${createHash('sha256')+ .update(+ JSON.stringify([+ `${AGENT_INTERVENTION_CONTINUATION_OPERATION_DOMAIN}:assistant-message`,+ params.userId,+ params.workspaceId ?? null,+ params.resolutionRequestId,+ ]),+ )+ .digest('hex')+ .slice(0, 32)}`;++/** Stable QStash/local-queue execute-once key for the continuation's first step. */+export const deriveAgentInterventionQueueDeduplicationId = (+ operationId: string,+ stepIndex: number,+): string => `agent-intervention:${operationId}:${stepIndex}`;++/**+ * Deterministic RFC-4122-shaped activity correlation for a sealed batch.+ * Tenant, owner, operation and batch are all domain-separated; idempotent+ * producer delivery therefore reuses one Live Activity without exposing the+ * producer's compound batch id.+ */+export const deriveAgentInterventionActivityKey = (params: {+ batchId: string;+ operationId: string;+ userId: string;+ workspaceId?: string;+}): string => {+ const digest = createHash('sha256')+ .update(+ JSON.stringify([+ AGENT_INTERVENTION_ACTIVITY_KEY_DOMAIN,+ params.userId,+ params.workspaceId ?? null,+ params.operationId,+ params.batchId,+ ]),+ )+ .digest('hex')+ .slice(0, 32)+ .split('');++ digest[12] = '5';+ digest[16] = ((Number.parseInt(digest[16], 16) & 0x3) | 0x8).toString(16);+ const value = digest.join('');+ return `${value.slice(0, 8)}-${value.slice(8, 12)}-${value.slice(12, 16)}-${value.slice(16, 20)}-${value.slice(20)}`;+};diff --git a/packages/business-server/src/agent-run/agentInterventionReview.ts b/packages/business-server/src/agent-run/agentInterventionReview.tsnew file mode 100644index 00000000000..a1d8bff61c8--- /dev/null+++ b/packages/business-server/src/agent-run/agentInterventionReview.ts@@ -0,0 +1,590 @@+import type { MessageMapScope } from '@lobechat/types';++export type AgentInterventionReviewStatus =+ | 'approved'+ | 'cancelled'+ | 'mixed'+ | 'pending'+ | 'rejected'+ | 'resolving'+ | 'resolved'+ | 'session_ended'+ | 'skipped'+ | 'stopped'+ | 'timed_out'+ | 'unavailable';++export type AgentInterventionAllowedAction =+ | 'approve_tool'+ | 'approve_tool_remember'+ | 'cancel_interaction'+ | 'edit_arguments'+ | 'reject_continue'+ | 'select_provider_option'+ | 'skip_interaction'+ | 'stop'+ | 'submit_answers'+ | 'submit_custom';++export interface AgentInterventionRequestRevision {+ hash: string;+ version: number;+}++export interface AgentInterventionReviewAuthorization {+ canResolve: boolean;+ canView: boolean;+ denialReason?: 'permission' | 'stale' | 'view_only';+}++export interface AgentInterventionReviewContext {+ /** ACL-hydrated display metadata; never copied from a notification payload. */+ agent?: { avatar?: string; title?: string };+ agentId?: string;+ assistantMessageId?: string;+ groupId?: string;+ operationId: string;+ pageId?: string;+ scope?: MessageMapScope;+ sessionId?: string;+ taskId?: string;+ threadId?: string;+ /** ACL-hydrated display metadata; never copied from a notification payload. */+ topic?: { title?: string };+ topicId?: string;+ triggerMessageId?: string;+ /** Hydrated and bounded only after ACL; never stored in notification rows. */+ triggerRequest?: { messageId: string; text?: string };+ workspaceId?: string;+}++export interface AgentInterventionReviewOption {+ description?: string;+ id: string;+ label: string;+}++export interface AgentInterventionReviewQuestion {+ allowCustomAnswer?: boolean;+ header?: string;+ id: string;+ multiple?: boolean;+ options: AgentInterventionReviewOption[];+ question: string;+}++export interface AgentMarketplaceReviewAgent {+ avatar?: string;+ description?: string;+ id: string;+ title: string;+}++export type AgentInterventionReviewDetail =+ | {+ /** Hydrated only after the context ACL succeeds; never copied into notification storage. */+ arguments?: Record<string, unknown>;+ description?: string;+ title: string;+ type: 'tool_approval';+ }+ | {+ answerPolicy?: { allowFreeform?: boolean; allowSupplement?: boolean };+ questions: AgentInterventionReviewQuestion[];+ title?: string;+ type: 'question';+ }+ | {+ description?: string;+ options: AgentInterventionReviewOption[];+ title: string;+ type: 'permission';+ }+ | {+ content: string;+ options?: AgentInterventionReviewOption[];+ title: string;+ type: 'plan';+ }+ | {+ agents: AgentMarketplaceReviewAgent[];+ kind: 'agent_marketplace';+ multiple: true;+ selectedIds?: string[];+ title: string;+ type: 'custom';+ };++export interface AgentInterventionRisk {+ level: 'critical' | 'high' | 'low' | 'medium' | 'none';+ summary: string;+ warnings?: string[];+}++export interface AgentInterventionReviewItem {+ allowedActions: AgentInterventionAllowedAction[];+ detail: AgentInterventionReviewDetail;+ id: string;+ interactionKind: 'custom' | 'permission' | 'plan' | 'question' | 'tool_approval';+ requestRevision: AgentInterventionRequestRevision;+ risk?: AgentInterventionRisk;+ source: 'heterogeneous' | 'runtime';+ /** Per-item state; batch status alone is insufficient for partially resolved turns. */+ status: AgentInterventionReviewStatus;+ surface: 'binary' | 'form';+}++export interface AgentInterventionReviewBatch {+ /** Only actions valid for the batch as a whole. Per-item actions live on each item. */+ allowedActions: AgentInterventionAllowedAction[];+ id: string;+ itemIds: string[];+ kind: 'mixed' | 'parallel' | 'single';+ version: number;+}++export interface AgentInterventionReviewV2 {+ batch: AgentInterventionReviewBatch;+ context: AgentInterventionReviewContext;+ deadline?: number;+ id: string;+ items: AgentInterventionReviewItem[];+ summary: string;+ /** Persisted server assertion; clients must never infer this from item shape or risk. */+ systemActionEligibility: 'review_only' | 'safe_single_binary';+}++export interface GetAgentInterventionReviewParams {+ reviewToken: string;+ userId: string;+ workspaceId?: string;+}++export interface GetAgentInterventionReviewResult {+ authorization: AgentInterventionReviewAuthorization;+ contractVersion: 2;+ /** Server-generated after context ACL; available even when the review is terminal. */+ conversationUrl?: string;+ review?: AgentInterventionReviewV2;+ status: AgentInterventionReviewStatus;+}++export type AgentInterventionResolutionAction =+ | {+ itemId: string;+ optionId: string;+ type: 'select_provider_option';+ }+ | {+ edits?: Record<string, Record<string, unknown>>;+ itemIds: string[];+ scope: 'once' | 'remember';+ type: 'approve_tool';+ }+ | {+ itemIds: string[];+ reason?: string;+ type: 'reject_continue';+ }+ | {+ scope: 'operation';+ type: 'stop';+ }+ | {+ itemId: string;+ result: Record<string, string | string[]>;+ type: 'submit_answers';+ }+ | {+ itemId: string;+ /** Validated fail-closed by the agent-marketplace server handler before claim. */+ result: { kind: 'agent_marketplace'; selectedTemplateIds: string[] };+ type: 'submit_custom';+ }+ | {+ itemId: string;+ type: 'skip_interaction';+ }+ | {+ itemId: string;+ type: 'cancel_interaction';+ };++export interface ResolveAgentInterventionParams {+ action: AgentInterventionResolutionAction;+ expectedBatchVersion: number;+ /** Must cover every member of the sealed batch, not only selected items. */+ expectedRequestRevisions: Record<string, AgentInterventionRequestRevision>;+ resolutionRequestId: string;+ reviewToken: string;+ userId: string;+ workspaceId?: string;+}++/**+ * Exact Web action semantics keyed by canonical runtime source locators.+ *+ * Web does not know durable intervention row ids or revisions. A Cloud+ * implementation resolves these locators to the complete sealed batch, checks+ * the conversation ACL, snapshots every row version/revision, then performs+ * the same atomic claim used by token-based Review. Operation/batch/message+ * ids are locators only and must never be treated as authorization.+ */+export type AgentInterventionSourceAction =+ | { optionId: string; type: 'select_provider_option' }+ | {+ /** Single-target only; Cloud maps the source message id to its durable item id. */+ edits?: Record<string, Record<string, unknown>>;+ scope: 'once' | 'remember';+ type: 'approve_tool';+ }+ | { reason?: string; type: 'reject_continue' }+ | { scope: 'operation'; type: 'stop' }+ | { result: Record<string, string | string[]>; type: 'submit_answers' }+ | {+ result: { kind: 'agent_marketplace'; selectedTemplateIds: string[] };+ type: 'submit_custom';+ }+ | { type: 'skip_interaction' }+ | { type: 'cancel_interaction' };++export interface AgentInterventionSourceTarget {+ toolCallId: string;+ toolMessageId: string;+}++export interface GetAgentInterventionReviewBySourceParams {+ actorUserId: string;+ batchId: string;+ operationId: string;+ targets: AgentInterventionSourceTarget[];+ workspaceId?: string;+}++/**+ * Source lookup distinguishes a deployment with no durable row from a found+ * review that is terminal, stale or view-only. `handled: false` is permitted+ * only when every source locator is absent; a partial/mismatched batch must+ * fail closed instead of falling back to unauthoritative client state.+ */+export type GetAgentInterventionReviewBySourceResult =+ | { handled: false }+ | (GetAgentInterventionReviewResult & {+ handled: true;+ /**+ * Read-only card-to-item mapping. It covers exactly the requested source+ * targets and is never accepted back as resolution authority.+ */+ sourceItemMap: Record<string, string>;+ });++export interface ResolveAgentInterventionBySourceParams {+ action: AgentInterventionSourceAction;+ actorUserId: string;+ batchId: string;+ operationId: string;+ resolutionRequestId: string;+ targets: AgentInterventionSourceTarget[];+ workspaceId?: string;+}++/**+ * Authoritative conversation location recovered from the durable operation.+ *+ * This deliberately mirrors the subset of `ExecAgentAppContext` required to+ * resume an existing message map. In particular, page and task runs must not+ * silently fall back to the main chat scope when a cold-start Review action is+ * dispatched. None of these values are accepted from the Review client.+ */+export interface AgentInterventionRuntimeAppContext {+ documentId?: string | null;+ groupId?: string | null;+ scope?: MessageMapScope;+ sessionId?: string;+ taskId?: string | null;+ threadId?: string | null;+ topicId: string;+}++export type AgentInterventionRuntimeAction =+ | {+ agentId: string;+ appContext: AgentInterventionRuntimeAppContext;+ batchId: string;+ handler: 'agent_marketplace';+ input: {+ action:+ | { selectedTemplateIds: string[]; type: 'submitted' }+ | { type: 'skipped' }+ | { type: 'cancelled' };+ categoryHints: string[];+ requestId: string;+ };+ operationId: string;+ parentMessageId: string;+ toolCallId: string;+ toolMessageIds: string[];+ type: 'execute_custom_interaction';+ }+ | {+ agentId: string;+ appContext: AgentInterventionRuntimeAppContext;+ decisions: Array<{+ decision: 'approved' | 'rejected_continue';+ parentMessageId: string;+ rejectionReason?: string;+ toolCallId: string;+ }>;+ /** Authoritative parked operation being continued; never client input. */+ operationId: string;+ parentMessageId: string;+ type: 'resume_approval';+ }+ | {+ agentId: string;+ appContext: AgentInterventionRuntimeAppContext;+ content: string;+ outcome: 'skipped' | 'submitted';+ /** Authoritative parked operation being continued; never client input. */+ operationId: string;+ parentMessageId: string;+ pluginState?: Record<string, unknown>;+ rejectionReason?: string;+ toolCallId: string;+ type: 'resume_tool_result';+ }+ | {+ batchId: string;+ operationId: string;+ terminalStatus: 'cancelled' | 'stopped';+ toolMessageIds: string[];+ topicId: string;+ type: 'stop';+ }+ | {+ operationId: string;+ response: {+ cancelReason?: 'user_cancelled';+ cancelled?: boolean;+ producerAck: false;+ resolutionRequestId: string;+ result?: unknown;+ toolCallId: string;+ };+ stepIndex?: number;+ type: 'heterogeneous_response';+ };++export type ResolveAgentInterventionResult =+ | { handled: false }+ | {+ contractVersion: 2;+ conversationUrl?: string;+ handled: true;+ /** Durable row owner; distinct from the resolving collaborator actor. */+ ownerUserId: string;+ state: 'already_resolved';+ status: Exclude<AgentInterventionReviewStatus, 'pending' | 'unavailable'>;+ }+ | {+ claimId: string;+ contractVersion: 2;+ conversationUrl?: string;+ handled: true;+ ownerUserId: string;+ resolutionRequestId: string;+ runtimeAction: AgentInterventionRuntimeAction;+ state: 'claimed';+ workspaceId?: string;+ };++/**+ * Source resolution preserves the durable claim outcome for Web callers.+ * `handled: false` is the OSS compatibility fallback and must not imply a+ * durable claim state.+ */+export type ResolveAgentInterventionBySourceResult =+ { handled: false; state?: never } | Extract<ResolveAgentInterventionResult, { handled: true }>;++export interface RollbackAgentInterventionResolutionParams {+ actorUserId: string;+ claimId: string;+ ownerUserId: string;+ resolutionRequestId: string;+ workspaceId?: string;+}++export interface AgentInterventionResolutionPublishedParams {+ actorUserId: string;+ claimId: string;+ ownerUserId: string;+ resolutionRequestId: string;+ /** Runtime actions complete here; heterogeneous actions stay resolving until producer ACK. */+ status: AgentInterventionReviewStatus;+ workspaceId?: string;+}++/**+ * Server-internal producer callback. The user id is the durable run owner, not+ * the actor that originally resolved the review. Cloud must still recover the+ * authoritative row/resolution before applying the transition.+ */+export interface AcknowledgeAgentInterventionProducerResolutionParams {+ operationId: string;+ ownerUserId: string;+ resolutionRequestId?: string;+ status: 'cancelled' | 'resolved' | 'session_ended' | 'timed_out';+ toolCallId: string;+ workspaceId?: string;+}++export interface NotifyAgentInterventionItem {+ allowedActions: AgentInterventionAllowedAction[];+ /** Server-derived only; never accepted from a resolution client. */+ canonicalToolKey?: string;+ /** Strictly notification-safe structured data; never raw runtime arguments. */+ detail?: Exclude<AgentInterventionReviewDetail, { type: 'tool_approval' }>;+ interactionKind: AgentInterventionReviewItem['interactionKind'];+ provider?: string;+ /**+ * Strictly bounded server execution context. It is persisted for cold-start+ * custom resolution but is not accepted back from, or necessarily exposed+ * to, a Review client.+ */+ request?: {+ categoryHints: string[];+ kind: 'agent_marketplace';+ requestId: string;+ };+ requestRevision: AgentInterventionRequestRevision;+ risk?: AgentInterventionRisk;+ /** Canonical server locator. Cloud must not copy raw arguments into the durable row. */+ sourceRef:+ | { toolCallId: string; toolMessageId: string; type: 'runtime' }+ | { operationId: string; toolCallId: string; type: 'heterogeneous' };+ summary: string;+ surface: AgentInterventionReviewItem['surface'];+}++export interface NotifyAgentInterventionRequiredParams {+ agentId?: string;+ /** Authoritative run snapshot; Cloud must not infer it from allowed actions. */+ approvalMode: 'allow-list' | 'auto-run' | 'headless' | 'manual';+ batch: {+ /** Stable opaque activity correlation, distinct from the producer batch id. */+ activityKey: string;+ allowedActions: AgentInterventionAllowedAction[];+ /** Stable producer/runtime id bound to this exact assistant turn. */+ id: string;+ kind: AgentInterventionReviewBatch['kind'];+ sealed: true;+ stepIndex: number;+ };+ context: Omit<AgentInterventionReviewContext, 'agent' | 'topic' | 'triggerRequest'>;+ deadline?: number;+ items: NotifyAgentInterventionItem[];+ summary: string;+ /**+ * A partial per-card decision may re-park the unresolved rows in a new+ * runtime operation. Cloud must terminal these exact old pending members and+ * create/observe the replacement batch in one durable transaction. The+ * winning old row may still be `resolving` because runtime scheduling races+ * the published hook; the transaction must converge that persisted claim to+ * its action-derived terminal outcome, and a late published hook is+ * idempotent. Only after this boundary may delivery end the old Activity and+ * fan out the new one.+ */+ supersedes?: {+ activityKey: string;+ batchId: string;+ operationId: string;+ toolCallIds: string[];+ };+ /**+ * A server-side eligibility assertion, not authorization. Cloud must still+ * have its signed direct-action capability explicitly enabled; every other+ * batch is Review-only.+ */+ systemActionEligibility: 'review_only' | 'safe_single_binary';+ userId: string;+ workspaceId?: string;+}++/** OSS has no durable intervention review store. Cloud overrides this module. */+export async function getAgentInterventionReview(+ _params: GetAgentInterventionReviewParams,+): Promise<GetAgentInterventionReviewResult> {+ return {+ authorization: { canResolve: false, canView: false },+ contractVersion: 2,+ status: 'unavailable',+ };+}++/**+ * Authenticated read-only lookup for an active chat card. Cloud resolves the+ * source locators, applies the conversation view ACL, and returns the same v2+ * review snapshot used by token Review. OSS has no durable generic store.+ */+export async function getAgentInterventionReviewBySource(+ _params: GetAgentInterventionReviewBySourceParams,+): Promise<GetAgentInterventionReviewBySourceResult> {+ return { handled: false };+}++/** Atomic, idempotent first-winner claim. OSS fails closed for token-based v2 resolution. */+export async function resolveAgentIntervention(+ _params: ResolveAgentInterventionParams,+): Promise<ResolveAgentInterventionResult> {+ return { handled: false };+}++/**+ * Authenticated Web bridge into the generic first-winner claim.+ *+ * Cloud resolves the source locators and builds the canonical item action.+ * For a mixed partially-settled Stop it supplies a full-batch version/revision+ * snapshot while selecting only rows that are still pending; terminal siblings+ * remain immutable. OSS has no durable generic store and falls back to its+ * existing in-request message-row claim.+ */+export async function resolveAgentInterventionBySource(+ _params: ResolveAgentInterventionBySourceParams,+): Promise<ResolveAgentInterventionBySourceResult> {+ return { handled: false };+}++/** Cloud conditionally releases only the still-owned claim after runtime dispatch fails. */+export async function rollbackAgentInterventionResolution(+ _params: RollbackAgentInterventionResolutionParams,+): Promise<void> {}++/** Runs only after the authoritative runtime dispatch succeeds. */+export async function onAgentInterventionResolutionPublished(+ _params: AgentInterventionResolutionPublishedParams,+): Promise<void> {}++/**+ * Completes a heterogeneous resolution only at the producer ACK boundary.+ * Cloud uses `resolutionRequestId` when present; legacy timeout/session-end+ * callbacks may recover the sealed batch through the operation/tool locator.+ */+export async function acknowledgeAgentInterventionProducerResolution(+ _params: AcknowledgeAgentInterventionProducerResolutionParams,+): Promise<void> {}++/**+ * Called only after the pending runtime state and all referenced tool messages+ * are durable. In a Cloud override, resolving this promise is the durable+ * Review-create boundary: the provider-neutral batch must already exist (or+ * have been idempotently observed). A rejection means persistence did not+ * succeed and is intentionally fatal/retryable to the parked lifecycle.+ *+ * Push / Live Activity fanout happens only after that create boundary and must+ * be caught, logged, or durably retried inside the Cloud implementation. A+ * downstream delivery failure must never reject this slot after persistence.+ * OSS deliberately has no durable store and therefore keeps the no-op default.+ */+export async function notifyAgentInterventionRequired(+ _params: NotifyAgentInterventionRequiredParams,+): Promise<void> {}diff --git a/packages/business-server/src/agent-run/executeCustomIntervention.ts b/packages/business-server/src/agent-run/executeCustomIntervention.tsnew file mode 100644index 00000000000..ed55a47c01a--- /dev/null+++ b/packages/business-server/src/agent-run/executeCustomIntervention.ts@@ -0,0 +1,64 @@+export interface ExecuteAgentMarketplaceInterventionParams {+ action:+ | { selectedTemplateIds: string[]; type: 'submitted' }+ | { type: 'skipped' }+ | { type: 'cancelled' };+ actorUserId: string;+ categoryHints: string[];+ requestId: string;+ /** Stable generic-resolution idempotency key for durable execute-once semantics. */+ resolutionRequestId: string;+ topicId: string;+ userId: string;+ workspaceId?: string;+}++export interface ExecuteCustomInterventionResult {+ content: string;+ pluginState: Record<string, unknown>;+}++export interface GetAgentMarketplaceInterventionReviewParams {+ categoryHints: string[];+ prompt?: string;+ requestId: string;+ userId: string;+ workspaceId?: string;+}++export interface AgentMarketplaceInterventionReviewAgent {+ avatar?: string;+ description?: string;+ id: string;+ title: string;+}++/**+ * Notification-safe marketplace projection. Cloud overrides this alongside+ * the post-claim executor so Review clients can render an actual picker while+ * the OSS default remains inert.+ */+export async function getAgentMarketplaceInterventionReview(+ _params: GetAgentMarketplaceInterventionReviewParams,+): Promise<AgentMarketplaceInterventionReviewAgent[]> {+ return [];+}++/**+ * Post-claim server-side custom interaction registry.+ *+ * Cloud overrides this handler to install the selected marketplace agents,+ * persist the onboarding pick on the authoritative topic, and return the+ * final tool result/plugin state. The implementation MUST be strongly+ * idempotent by `resolutionRequestId`: a retry after the durable side effect+ * but before the source message/continuation write must reconstruct the same+ * result without installing or recording twice. It may only return after that+ * execute-once record is durable, and post-commit fanout errors must not escape.+ * The default OSS build fails closed: custom side effects must never fall back+ * to an unvalidated browser-only action when a token-based resolver is used.+ */+export async function executeAgentMarketplaceIntervention(+ _params: ExecuteAgentMarketplaceInterventionParams,+): Promise<ExecuteCustomInterventionResult> {+ throw new Error('Agent marketplace intervention is unavailable on this server');+}diff --git a/packages/business-server/src/agent-run/heteroInterventionReview.ts b/packages/business-server/src/agent-run/heteroInterventionReview.tsnew file mode 100644index 00000000000..e87d33268fc--- /dev/null+++ b/packages/business-server/src/agent-run/heteroInterventionReview.ts@@ -0,0 +1,124 @@+import type {+ AgentInterventionInteractionKind,+ AgentInterventionProvider,+ AgentInterventionResponseData,+} from '@lobechat/agent-gateway-client';++export type HeteroInterventionReviewStatus =+ | 'cancelled'+ | 'pending'+ | 'resolving'+ | 'resolved'+ | 'session_ended'+ | 'timed_out'+ | 'unavailable';++export interface HeteroInterventionReview {+ apiName: string;+ deadline: number;+ interactionKind: AgentInterventionInteractionKind;+ provider: AgentInterventionProvider;+ /**+ * Canonical, whitelisted AskUserQuestion JSON needed to render the review.+ * It may contain only questions and their display fields; permission/plan+ * options must retain exact provider ids. Never expose raw tool arguments.+ */+ renderArguments: string;+ /** Privacy-safe notification/review title. */+ summary: string;+}++export interface GetHeteroInterventionReviewParams {+ reviewToken: string;+ userId: string;+ workspaceId?: string;+}++export interface GetHeteroInterventionReviewResult {+ review?: HeteroInterventionReview;+ status: HeteroInterventionReviewStatus;+}++export type HeteroInterventionResolutionTarget =+ { operationId: string; toolCallId: string } | { reviewToken: string };++export interface ResolveHeteroInterventionParams {+ action: 'skip' | 'submit';+ cancelReason?: 'user_cancelled';+ /** Client-minted retry key; the same user intent must reuse the same UUID. */+ resolutionRequestId: string;+ result?: unknown;+ target: HeteroInterventionResolutionTarget;+ userId: string;+ workspaceId?: string;+}++export type ResolveHeteroInterventionResult =+ | { handled: false }+ | {+ handled: true;+ state: 'already_resolved';+ status: Exclude<HeteroInterventionReviewStatus, 'pending' | 'unavailable'>;+ }+ | {+ claimId: string;+ handled: true;+ operationId: string;+ /** Echoes the winning client retry key for conditional rollback. */+ resolutionRequestId: string;+ response: AgentInterventionResponseData;+ state: 'claimed';+ stepIndex?: number;+ /** Durable row scope resolved from the opaque token/direct target. */+ workspaceId?: string;+ };++export interface RollbackHeteroInterventionResolutionParams {+ claimId: string;+ operationId: string;+ resolutionRequestId: string;+ toolCallId: string;+ userId: string;+ workspaceId?: string;+}++export interface HeteroInterventionResolutionPublishedParams {+ claimId: string;+ operationId: string;+ resolutionRequestId: string;+ status: 'resolving';+ toolCallId: string;+ userId: string;+ workspaceId?: string;+}++/** OSS has no durable review-token store. Cloud overrides this module. */+export async function getHeteroInterventionReview(+ _params: GetHeteroInterventionReviewParams,+): Promise<GetHeteroInterventionReviewResult> {+ return { status: 'unavailable' };+}++/**+ * Atomic first-winner business slot. `handled: false` preserves the existing+ * OSS direct response-stream behavior; Cloud returns a durable claim.+ */+export async function resolveHeteroIntervention(+ _params: ResolveHeteroInterventionParams,+): Promise<ResolveHeteroInterventionResult> {+ return { handled: false };+}++/** Cloud conditionally releases only the still-owned claim after publish fails. */+export async function rollbackHeteroInterventionResolution(+ _params: RollbackHeteroInterventionResolutionParams,+): Promise<void> {}++/**+ * Runs only after the response-stream publish succeeds. Cloud may override+ * this to update notification surfaces to `resolving`; failure must never+ * release the already-published first-winner claim.+ */+export async function onHeteroInterventionResolutionPublished(+ _params: HeteroInterventionResolutionPublishedParams,+): Promise<void> {}diff --git a/packages/business-server/src/agent-run/notifyAgentIntervention.ts b/packages/business-server/src/agent-run/notifyAgentIntervention.tsnew file mode 100644index 00000000000..a11c4d48d5b--- /dev/null+++ b/packages/business-server/src/agent-run/notifyAgentIntervention.ts@@ -0,0 +1,39 @@+import type {+ AgentInterventionInteractionKind,+ AgentInterventionProvider,+ AgentInterventionRequestData,+} from '@lobechat/agent-gateway-client';++export type AgentInterventionNotificationStatus =+ 'cancelled' | 'pending' | 'resolved' | 'session_ended' | 'timed_out';++/**+ * Durable heterogeneous-intervention notification slot. Cloud overrides this+ * module; OSS deliberately performs no external side effect.+ */+export interface NotifyAgentInterventionParams {+ agentId?: string | null;+ deadline?: number;+ interactionKind: AgentInterventionInteractionKind;+ operationId: string;+ provider: AgentInterventionProvider | 'unknown';+ /**+ * Full producer request only on `pending`. Cloud must reconstruct a+ * canonical AskUserQuestion payload by whitelisting fields before storage,+ * and must never copy `arguments` directly into a push payload.+ */+ request?: AgentInterventionRequestData;+ /** Present on producer-ACK terminal transitions for claim correlation. */+ resolutionRequestId?: string;+ status: AgentInterventionNotificationStatus;+ /** Privacy-safe title; never contains raw tool arguments or answer values. */+ summary: string;+ toolCallId: string;+ topicId: string;+ userId: string;+ workspaceId?: string;+}++export async function notifyAgentIntervention(+ _params: NotifyAgentInterventionParams,+): Promise<void> {}diff --git a/packages/business-server/src/notification/liveActivity.ts b/packages/business-server/src/notification/liveActivity.tsnew file mode 100644index 00000000000..7a6bba1756b--- /dev/null+++ b/packages/business-server/src/notification/liveActivity.ts@@ -0,0 +1,43 @@+import type { AgentInterventionReviewStatus } from '../agent-run/agentInterventionReview';++export type ApnsEnvironment = 'production' | 'sandbox';++export interface RegisterLiveActivityPushToStartTokenParams {+ apnsEnvironment: ApnsEnvironment;+ deviceId: string;+ liveActivityPushToStartToken: string;+ userId: string;+ workspaceId?: string;+}++export interface RegisterAgentInterventionLiveActivityParams {+ /** Native ActivityKit id for diagnostics and token rotation. */+ activityId: string;+ /** Durable intervention identity, independent of ActivityKit's local id. */+ activityKey: string;+ apnsEnvironment: ApnsEnvironment;+ deviceId: string;+ operationId: string;+ pushToken: string;+ userId: string;+ workspaceId?: string;+}++export interface RegisterAgentInterventionLiveActivityResult {+ /** Current durable state so a late token registration can end immediately. */+ interventionStatus: AgentInterventionReviewStatus;+ /** Authoritative aggregate terminality; `mixed` alone cannot determine whether work remains. */+ interventionTerminal: boolean;+}++/** OSS has no APNs ActivityKit token store. Cloud overrides this module. */+export async function registerLiveActivityPushToStartToken(+ _params: RegisterLiveActivityPushToStartTokenParams,+): Promise<void> {}++/** OSS reports unavailable; Cloud validates ownership and persists by activityKey. */+export async function registerAgentInterventionLiveActivity(+ _params: RegisterAgentInterventionLiveActivityParams,+): Promise<RegisterAgentInterventionLiveActivityResult> {+ return { interventionStatus: 'unavailable', interventionTerminal: true };+}diff --git a/packages/database/src/models/__tests__/agentOperation.test.ts b/packages/database/src/models/__tests__/agentOperation.test.tsindex 29663184776..b0cfb628669 100644--- a/packages/database/src/models/__tests__/agentOperation.test.ts+++ b/packages/database/src/models/__tests__/agentOperation.test.ts@@ -2,6 +2,8 @@import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { matchesAgentInterventionContinuationProvenance } from '@/business/server/agent-run/agentInterventionIdentity';+import { getTestDB } from '../../core/getTestDB';import { agentOperations, users } from '../../schemas';import type { LobeChatDatabase } from '../../type';@@ -96,6 +98,95 @@ describe('AgentOperationModel', () => {});});+ describe('agent intervention dispatch recovery markers', () => {+ it('persists ready preparation and queue ACK without replacing provenance', async () => {+ const model = new AgentOperationModel(serverDB, userId);+ const operationId = 'op-intervention-marker';+ const provenance = {+ resolutionRequestId: 'request-intervention-marker',+ sourceOperationId: 'source-operation',+ sourceToolMessageIds: ['tool-message'],+ };+ await model.recordStart({+ metadata: { agentInterventionContinuation: provenance },+ operationId,+ });++ await expect(+ model.recordAgentInterventionPreparation(operationId, {+ deduplicationId: 'agent-intervention:op-intervention-marker:0',+ resolutionRequestId: provenance.resolutionRequestId,+ state: 'ready',+ stepIndex: 0,+ }),+ ).resolves.toBe(true);+ await expect(+ model.recordAgentInterventionDispatch(operationId, {+ deduplicationId: 'agent-intervention:op-intervention-marker:0',+ messageId: 'queue-message',+ resolutionRequestId: provenance.resolutionRequestId,+ scheduledAt: '2026-08-26T00:00:00.000Z',+ state: 'scheduled',+ }),+ ).resolves.toBe(true);++ const row = await model.findById(operationId);+ expect(+ matchesAgentInterventionContinuationProvenance(+ row?.metadata?.agentInterventionContinuation,+ provenance,+ ),+ ).toBe(true);+ expect(row?.metadata).toMatchObject({+ agentInterventionContinuation: provenance,+ agentInterventionDispatch: {+ deduplicationId: 'agent-intervention:op-intervention-marker:0',+ state: 'scheduled',+ },+ agentInterventionPreparation: {+ deduplicationId: 'agent-intervention:op-intervention-marker:0',+ state: 'ready',+ stepIndex: 0,+ },+ });+ });++ it('rejects a preparation marker from another request or owner', async () => {+ const model = new AgentOperationModel(serverDB, userId);+ const attacker = new AgentOperationModel(serverDB, otherUserId);+ const operationId = 'op-intervention-marker-authority';+ await model.recordStart({+ metadata: {+ agentInterventionContinuation: {+ resolutionRequestId: 'request-owner',+ sourceOperationId: 'source-operation',+ sourceToolMessageIds: ['tool-message'],+ },+ },+ operationId,+ });+ const marker = {+ deduplicationId: 'agent-intervention:op-intervention-marker-authority:0',+ resolutionRequestId: 'request-other',+ state: 'ready' as const,+ stepIndex: 0,+ };++ await expect(model.recordAgentInterventionPreparation(operationId, marker)).resolves.toBe(+ false,+ );+ await expect(+ attacker.recordAgentInterventionPreparation(operationId, {+ ...marker,+ resolutionRequestId: 'request-owner',+ }),+ ).resolves.toBe(false);+ expect((await model.findById(operationId))?.metadata).not.toHaveProperty(+ 'agentInterventionPreparation',+ );+ });+ });+describe('recordCompletion', () => {it('updates the row to a terminal status with aggregates and trace key', async () => {const model = new AgentOperationModel(serverDB, userId);diff --git a/packages/database/src/models/__tests__/messages/message.update.test.ts b/packages/database/src/models/__tests__/messages/message.update.test.tsindex 4b0385d2063..d91aa86ae65 100644--- a/packages/database/src/models/__tests__/messages/message.update.test.ts+++ b/packages/database/src/models/__tests__/messages/message.update.test.ts@@ -18,7 +18,7 @@ import {workspaces,} from '../../../schemas';import type { LobeChatDatabase } from '../../../type';-import { MessageModel } from '../../message';+import { HumanApprovalAlreadyResolvedError, MessageModel } from '../../message';import { codeEmbedding } from '../fixtures/embedding';const serverDB: LobeChatDatabase = await getTestDB();@@ -635,6 +635,173 @@ describe('MessageModel Update Tests', () => {});});+ describe('resolveHumanApproval', () => {+ const pendingIdentity = {+ batchId: 'batch-approval-1',+ itemIndex: 0,+ operationId: 'operation-approval-1',+ status: 'pending' as const,+ stepIndex: 4,+ };++ const seedPendingTool = async (+ id: string,+ intervention: Record<string, unknown> = pendingIdentity,+ ) => {+ await serverDB.insert(messages).values({+ content: 'pending content',+ id,+ role: 'tool',+ userId,+ });+ await serverDB.insert(messagePlugins).values({+ apiName: 'editFile',+ arguments: '{"path":"/tmp/a"}',+ id,+ identifier: 'lobe-local-system',+ intervention,+ state: { preserved: true },+ toolCallId: `call-${id}`,+ userId,+ });+ };++ it('preserves sealed operation/batch identity while applying a claim patch', async () => {+ await seedPendingTool('approval-preserves-identity');++ await messageModel.resolveHumanApproval([+ {+ id: 'approval-preserves-identity',+ intervention: {+ resolutionRequestId: 'resolution-1',+ status: 'approved',+ },+ pluginState: { approvedBy: 'review' },+ },+ ]);++ const [plugin] = await serverDB+ .select()+ .from(messagePlugins)+ .where(eq(messagePlugins.id, 'approval-preserves-identity'));+ expect(plugin.intervention).toEqual({+ ...pendingIdentity,+ resolutionRequestId: 'resolution-1',+ status: 'approved',+ });+ expect(plugin.state).toEqual({ approvedBy: 'review', preserved: true });+ });++ it('rejects the whole batch when any sibling already has a winner', async () => {+ await seedPendingTool('approval-atomic-pending');+ await seedPendingTool('approval-atomic-settled', {+ ...pendingIdentity,+ itemIndex: 1,+ status: 'approved',+ });++ await expect(+ messageModel.resolveHumanApproval([+ {+ content: 'must not commit',+ id: 'approval-atomic-pending',+ intervention: { resolutionRequestId: 'resolution-loser', status: 'approved' },+ },+ {+ id: 'approval-atomic-settled',+ intervention: { resolutionRequestId: 'resolution-loser', status: 'approved' },+ },+ ]),+ ).rejects.toBeInstanceOf(HumanApprovalAlreadyResolvedError);++ const [message] = await serverDB+ .select()+ .from(messages)+ .where(eq(messages.id, 'approval-atomic-pending'));+ const [plugin] = await serverDB+ .select()+ .from(messagePlugins)+ .where(eq(messagePlugins.id, 'approval-atomic-pending'));+ expect(message.content).toBe('pending content');+ expect(plugin.intervention).toEqual(pendingIdentity);+ });++ it('returns one applied owner and one idempotent follower for concurrent same-request claims', async () => {+ await seedPendingTool('approval-concurrent-same-request');+ const resolution = {+ content: 'approved once',+ id: 'approval-concurrent-same-request',+ intervention: { resolutionRequestId: 'resolution-concurrent', status: 'approved' as const },+ };++ const results = await Promise.all([+ messageModel.resolveHumanApproval([resolution]),+ messageModel.resolveHumanApproval([resolution]),+ ]);++ expect(results.sort()).toEqual(['applied', 'idempotent']);+ const [message] = await serverDB+ .select()+ .from(messages)+ .where(eq(messages.id, resolution.id));+ const [plugin] = await serverDB+ .select()+ .from(messagePlugins)+ .where(eq(messagePlugins.id, resolution.id));+ expect(message.content).toBe('approved once');+ expect(plugin.intervention).toMatchObject({+ resolutionRequestId: 'resolution-concurrent',+ status: 'approved',+ });+ });++ it('restores the exact pre-claim snapshot only for the owning resolution request', async () => {+ await seedPendingTool('approval-rollback');+ const original = {+ content: 'pending content',+ id: 'approval-rollback',+ intervention: pendingIdentity,+ pluginState: { preserved: true },+ };++ await messageModel.resolveHumanApproval([+ {+ content: 'approved content',+ id: original.id,+ intervention: { resolutionRequestId: 'resolution-owner', status: 'approved' },+ pluginState: { approvedBy: 'review' },+ },+ ]);+ await messageModel.restoreHumanApproval([+ { ...original, claimedResolutionRequestId: 'resolution-loser' },+ ]);++ let [message] = await serverDB.select().from(messages).where(eq(messages.id, original.id));+ let [plugin] = await serverDB+ .select()+ .from(messagePlugins)+ .where(eq(messagePlugins.id, original.id));+ expect(message.content).toBe('approved content');+ expect(plugin.intervention).toMatchObject({+ resolutionRequestId: 'resolution-owner',+ status: 'approved',+ });++ await messageModel.restoreHumanApproval([+ { ...original, claimedResolutionRequestId: 'resolution-owner' },+ ]);++ [message] = await serverDB.select().from(messages).where(eq(messages.id, original.id));+ [plugin] = await serverDB+ .select()+ .from(messagePlugins)+ .where(eq(messagePlugins.id, original.id));+ expect(message.content).toBe(original.content);+ expect(plugin.intervention).toEqual(original.intervention);+ expect(plugin.state).toEqual(original.pluginState);+ });+ });+describe('updateToolMessage', () => {it('should update content only', async () => {await serverDB.insert(messages).values({diff --git a/packages/database/src/models/__tests__/topics/topic.update.test.ts b/packages/database/src/models/__tests__/topics/topic.update.test.tsindex 07ce5423fb2..0b8eece4ce2 100644--- a/packages/database/src/models/__tests__/topics/topic.update.test.ts+++ b/packages/database/src/models/__tests__/topics/topic.update.test.ts@@ -173,6 +173,42 @@ describe('TopicModel - Update', () => {await expect(topicModel.tryReserveTaskCallback(topicId, 'callback-2')).resolves.toBe(false);});+ it('fences a concurrent deterministic intervention initializer with the same id', async () => {+ const topicId = 'topic-start-non-reentrant-intervention';+ await serverDB.insert(topics).values({ id: topicId, title: 'Test', userId });++ await expect(+ topicModel.tryReserveTaskCallback(topicId, 'op-intervention', {+ allowSameReservationReentry: false,+ ignoreRunningOperation: true,+ }),+ ).resolves.toBe(true);+ await expect(+ topicModel.tryReserveTaskCallback(topicId, 'op-intervention', {+ allowSameReservationReentry: false,+ ignoreRunningOperation: true,+ }),+ ).resolves.toBe(false);+ });++ it('grants exactly one non-reentrant initializer under a real concurrent row lock', async () => {+ const topicId = 'topic-start-concurrent-non-reentrant-intervention';+ await serverDB.insert(topics).values({ id: topicId, title: 'Test', userId });++ const results = await Promise.all([+ topicModel.tryReserveTaskCallback(topicId, 'op-intervention', {+ allowSameReservationReentry: false,+ ignoreRunningOperation: true,+ }),+ topicModel.tryReserveTaskCallback(topicId, 'op-intervention', {+ allowSameReservationReentry: false,+ ignoreRunningOperation: true,+ }),+ ]);++ expect(results.sort()).toEqual([false, true]);+ });+it('waits while a foreground operation is running', async () => {const topicId = 'task-callback-running-operation';await serverDB.insert(topics).values({@@ -544,6 +580,174 @@ describe('TopicModel - Update', () => {);});+ it('repairs the exact intervention continuation anchor after queue ACK', async () => {+ const topicId = 'intervention-anchor-repair';+ await serverDB.insert(topics).values({+ id: topicId,+ metadata: {+ runningOperation: {+ assistantMessageId: 'assistant-source',+ operationId: 'operation-source',+ },+ taskCallbackReservation: {+ messageId: 'operation-continuation',+ reservedAt: new Date().toISOString(),+ },+ },+ title: 'Test',+ userId,+ });++ await expect(+ topicModel.repairAgentInterventionContinuation({+ active: true,+ assistantMessageId: 'assistant-continuation',+ continuationOperationId: 'operation-continuation',+ reservationId: 'operation-continuation',+ scope: 'main',+ sourceOperationId: 'operation-source',+ startedAt: '2026-08-26T00:00:00.000Z',+ topicId,+ }),+ ).resolves.toBe('repaired');++ const topic = await topicModel.findById(topicId);+ expect(topic?.metadata?.runningOperation).toMatchObject({+ assistantMessageId: 'assistant-continuation',+ operationId: 'operation-continuation',+ scope: 'main',+ });+ expect(topic?.metadata?.taskCallbackReservation).toBeNull();+ });++ it('releases an exact thread fence without changing the main running anchor', async () => {+ const topicId = 'intervention-thread-reservation-release';+ const mainRunningOperation = {+ assistantMessageId: 'assistant-main',+ operationId: 'operation-main',+ scope: 'main',+ startedAt: '2026-08-26T00:00:00.000Z',+ };+ await serverDB.insert(topics).values({+ id: topicId,+ metadata: {+ runningOperation: mainRunningOperation,+ taskCallbackReservation: {+ messageId: 'operation-thread-continuation',+ reservedAt: new Date().toISOString(),+ },+ },+ title: 'Test',+ userId,+ });++ await expect(+ topicModel.releaseTaskCallbackReservation(topicId, 'operation-thread-continuation'),+ ).resolves.toBe('released');++ const topic = await topicModel.findById(topicId);+ expect(topic?.metadata?.runningOperation).toEqual(mainRunningOperation);+ expect(topic?.metadata?.taskCallbackReservation).toBeNull();+ });++ it('does not release a foreign thread fence or change the main running anchor', async () => {+ const topicId = 'intervention-thread-foreign-reservation';+ const mainRunningOperation = {+ assistantMessageId: 'assistant-main',+ operationId: 'operation-main',+ };+ await serverDB.insert(topics).values({+ id: topicId,+ metadata: {+ runningOperation: mainRunningOperation,+ taskCallbackReservation: {+ messageId: 'foreign-operation',+ reservedAt: new Date().toISOString(),+ },+ },+ title: 'Test',+ userId,+ });++ await expect(+ topicModel.releaseTaskCallbackReservation(topicId, 'operation-thread-continuation'),+ ).resolves.toBe('foreign');++ const topic = await topicModel.findById(topicId);+ expect(topic?.metadata?.runningOperation).toEqual(mainRunningOperation);+ expect(topic?.metadata?.taskCallbackReservation?.messageId).toBe('foreign-operation');+ });++ it('does not repair across a foreign live topic reservation', async () => {+ const topicId = 'intervention-anchor-foreign-reservation';+ await serverDB.insert(topics).values({+ id: topicId,+ metadata: {+ runningOperation: {+ assistantMessageId: 'assistant-source',+ operationId: 'operation-source',+ },+ taskCallbackReservation: {+ messageId: 'foreign-operation',+ reservedAt: new Date().toISOString(),+ },+ },+ title: 'Test',+ userId,+ });++ await expect(+ topicModel.repairAgentInterventionContinuation({+ active: true,+ assistantMessageId: 'assistant-continuation',+ continuationOperationId: 'operation-continuation',+ reservationId: 'operation-continuation',+ sourceOperationId: 'operation-source',+ startedAt: '2026-08-26T00:00:00.000Z',+ topicId,+ }),+ ).resolves.toBe('conflict');++ const topic = await topicModel.findById(topicId);+ expect(topic?.metadata?.runningOperation?.operationId).toBe('operation-source');+ expect(topic?.metadata?.taskCallbackReservation?.messageId).toBe('foreign-operation');+ });++ it('clears a terminal intervention anchor without reactivating it', async () => {+ const topicId = 'intervention-anchor-terminal';+ await serverDB.insert(topics).values({+ id: topicId,+ metadata: {+ runningOperation: {+ assistantMessageId: 'assistant-source',+ operationId: 'operation-source',+ },+ taskCallbackReservation: {+ messageId: 'operation-continuation',+ reservedAt: new Date().toISOString(),+ },+ },+ title: 'Test',+ userId,+ });++ await expect(+ topicModel.repairAgentInterventionContinuation({+ active: false,+ assistantMessageId: 'assistant-continuation',+ continuationOperationId: 'operation-continuation',+ reservationId: 'operation-continuation',+ sourceOperationId: 'operation-source',+ startedAt: '2026-08-26T00:00:00.000Z',+ topicId,+ }),+ ).resolves.toBe('terminal');++ const topic = await topicModel.findById(topicId);+ expect(topic?.metadata?.runningOperation).toBeNull();+ expect(topic?.metadata?.taskCallbackReservation).toBeNull();+ });+it('does not reserve another user topic', async () => {await serverDB.insert(users).values({ id: 'task-callback-other-user' });await serverDB.insert(topics).values({diff --git a/packages/database/src/models/agentOperation.ts b/packages/database/src/models/agentOperation.tsindex a33c2b05cb2..27a8f44e867 100644--- a/packages/database/src/models/agentOperation.ts+++ b/packages/database/src/models/agentOperation.ts@@ -47,6 +47,21 @@ export interface RecordOperationStartParams {trigger?: string;}+export interface AgentInterventionDispatchMarker {+ deduplicationId: string;+ messageId: string;+ resolutionRequestId: string;+ scheduledAt: string;+ state: 'scheduled';+}++export interface AgentInterventionPreparationMarker {+ deduplicationId: string;+ resolutionRequestId: string;+ state: 'ready';+ stepIndex: number;+}+/** Terminal usage summed across every child operation of one parent. All-zero when it has none. */export interface ChildUsageRollup {llmCalls: number;@@ -208,6 +223,57 @@ export class AgentOperationModel {return Boolean(row);}+ /**+ * Persist provider enqueue acknowledgement without replacing other runtime+ * metadata. The provenance request id is checked in SQL so a stale/colliding+ * operation can never be marked scheduled by another intervention.+ */+ async recordAgentInterventionDispatch(+ operationId: string,+ marker: AgentInterventionDispatchMarker,+ ): Promise<boolean> {+ const [row] = await this.db+ .update(agentOperations)+ .set({+ metadata: sql`coalesce(${agentOperations.metadata}, '{}'::jsonb) || ${JSON.stringify({ agentInterventionDispatch: marker })}::jsonb`,+ })+ .where(+ and(+ eq(agentOperations.id, operationId),+ this.ownership(),+ sql`${agentOperations.metadata}->'agentInterventionContinuation'->>'resolutionRequestId' = ${marker.resolutionRequestId}`,+ ),+ )+ .returning({ id: agentOperations.id });+ return Boolean(row);+ }++ /**+ * Persist the crash-recovery boundary after runtime state and serialized+ * hooks are complete, but before the first queue publish. A missing runtime+ * state with this marker is therefore ambiguous (it may already have run)+ * and must never be rebuilt from scratch.+ */+ async recordAgentInterventionPreparation(+ operationId: string,+ marker: AgentInterventionPreparationMarker,+ ): Promise<boolean> {+ const [row] = await this.db+ .update(agentOperations)+ .set({+ metadata: sql`coalesce(${agentOperations.metadata}, '{}'::jsonb) || ${JSON.stringify({ agentInterventionPreparation: marker })}::jsonb`,+ })+ .where(+ and(+ eq(agentOperations.id, operationId),+ this.ownership(),+ sql`${agentOperations.metadata}->'agentInterventionContinuation'->>'resolutionRequestId' = ${marker.resolutionRequestId}`,+ ),+ )+ .returning({ id: agentOperations.id });+ return Boolean(row);+ }+/** Idempotently settle a running operation without rewriting an existing terminal outcome. */async settleRunning(operationId: string,diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.tsindex 425a9619f9a..9057f0abf7c 100644--- a/packages/database/src/models/message.ts+++ b/packages/database/src/models/message.ts@@ -86,6 +86,23 @@ import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';import { recomputeTopicUsage } from './topicUsage';import { WorkModel } from './work';+export class HumanApprovalAlreadyResolvedError extends Error {+ constructor(messageId: string) {+ super(`Human approval is no longer pending for tool message ${messageId}`);+ this.name = 'HumanApprovalAlreadyResolvedError';+ }+}++export interface HumanApprovalResolution {+ /** Conditional owner checked by rollback; never accepted as client authority. */+ claimedResolutionRequestId?: string;+ content?: string;+ id: string;+ intervention: Record<string, unknown>;+ pluginState?: Record<string, unknown> | null;+ replacePluginState?: boolean;+}+/*** Read the operation-final Work root id stamped on a message's metadata by the* Work registry (`metadata.work.rootOperationId`). Mirrors the client-side@@ -2734,6 +2751,130 @@ export class MessageModel {.where(and(eq(messagePlugins.id, id), this.pluginsOwnership()));};+ /**+ * Resolve an approval batch at one row-locking boundary. Every target is+ * checked before any write, so Web, Mobile, Stop, and notification actions+ * cannot each win a subset of the same assistant turn.+ */+ resolveHumanApproval = async (+ resolutions: HumanApprovalResolution[],+ ): Promise<'applied' | 'idempotent'> => {+ if (resolutions.length === 0) return 'idempotent';++ const ids = resolutions.map(({ id }) => id);+ if (new Set(ids).size !== ids.length) {+ throw new Error('Human approval batch contains duplicate tool messages');+ }++ return this.db.transaction(async (trx) => {+ const lockedRows = await trx+ .select({+ id: messagePlugins.id,+ intervention: messagePlugins.intervention,+ state: messagePlugins.state,+ })+ .from(messagePlugins)+ .where(and(inArray(messagePlugins.id, ids), this.pluginsOwnership()))+ .for('update');+ const lockedById = new Map(lockedRows.map((row) => [row.id, row]));++ const rowStates = resolutions.map((resolution) => {+ const row = lockedById.get(resolution.id);+ if (!row) throw new Error(`Plugin not found: ${resolution.id}`);+ if (row.intervention?.status === 'pending') return 'pending' as const;++ const sameRequest =+ Boolean(resolution.intervention.resolutionRequestId) &&+ row.intervention?.resolutionRequestId === resolution.intervention.resolutionRequestId;+ const sameDecision = Object.entries(resolution.intervention).every(+ ([key, value]) =>+ JSON.stringify(row.intervention?.[key as keyof typeof row.intervention]) ===+ JSON.stringify(value),+ );+ if (sameRequest && sameDecision) return 'idempotent' as const;+ throw new HumanApprovalAlreadyResolvedError(resolution.id);+ });+ const pendingCount = rowStates.filter((state) => state === 'pending').length;+ if (pendingCount === 0) return 'idempotent';+ if (pendingCount !== resolutions.length) {+ throw new Error('Human approval batch contains a partial idempotent claim');+ }++ for (const resolution of resolutions) {+ const row = lockedById.get(resolution.id)!;+ if (resolution.content !== undefined) {+ const [updatedMessage] = await trx+ .update(messages)+ .set({ content: resolution.content })+ .where(and(eq(messages.id, resolution.id), this.ownership()))+ .returning({ id: messages.id });+ if (!updatedMessage) throw new Error(`Message not found: ${resolution.id}`);+ }++ const [updatedPlugin] = await trx+ .update(messagePlugins)+ .set({+ // Status/result is a claim patch, not a replacement. Preserve the+ // authoritative operation/batch/item identity stamped when the+ // parked tool row was created so subsequent source reads, Stop,+ // and rollback still address the same sealed batch.+ intervention: merge(row.intervention || {}, resolution.intervention),+ ...(resolution.pluginState !== undefined && {+ state: resolution.replacePluginState+ ? resolution.pluginState+ : merge(row.state || {}, resolution.pluginState || {}),+ }),+ })+ .where(and(eq(messagePlugins.id, resolution.id), this.pluginsOwnership()))+ .returning({ id: messagePlugins.id });+ if (!updatedPlugin) throw new Error(`Plugin not found: ${resolution.id}`);+ }++ return 'applied';+ });+ };++ /** Restore the exact pre-claim snapshot when continuation startup fails. */+ restoreHumanApproval = async (resolutions: HumanApprovalResolution[]): Promise<void> => {+ if (resolutions.length === 0) return;++ await this.db.transaction(async (trx) => {+ const ids = resolutions.map(({ id }) => id);+ const lockedRows = await trx+ .select({ id: messagePlugins.id, intervention: messagePlugins.intervention })+ .from(messagePlugins)+ .where(and(inArray(messagePlugins.id, ids), this.pluginsOwnership()))+ .for('update');+ const lockedById = new Map(lockedRows.map((row) => [row.id, row]));++ for (const resolution of resolutions) {+ const locked = lockedById.get(resolution.id);+ if (!locked) throw new Error(`Plugin not found: ${resolution.id}`);+ if (+ resolution.claimedResolutionRequestId &&+ locked.intervention?.resolutionRequestId !== resolution.claimedResolutionRequestId+ ) {+ continue;+ }+ if (resolution.content !== undefined) {+ const [updatedMessage] = await trx+ .update(messages)+ .set({ content: resolution.content })+ .where(and(eq(messages.id, resolution.id), this.ownership()))+ .returning({ id: messages.id });+ if (!updatedMessage) throw new Error(`Message not found: ${resolution.id}`);+ }+ await trx+ .update(messagePlugins)+ .set({+ intervention: resolution.intervention,+ ...(resolution.pluginState !== undefined && { state: resolution.pluginState }),+ })+ .where(and(eq(messagePlugins.id, resolution.id), this.pluginsOwnership()));+ }+ });+ };+/*** Fetch the `message_plugins` row associated with a tool message. Tool-call* metadata (identifier / apiName / arguments / type / toolCallId /diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.tsindex 2dca5bf492b..b0c3417a08d 100644--- a/packages/database/src/models/topic.ts+++ b/packages/database/src/models/topic.ts@@ -1756,6 +1756,13 @@ export class TopicModel {* reservation.*/allowRunningOperationId?: string;+ /**+ * A deterministic intervention reservation is an initializer fence, not+ * a reentrant mutex. Its concurrent same-id caller must wait until the+ * owner releases (or the lease expires) instead of entering preparation+ * and overwriting an already-running continuation state.+ */+ allowSameReservationReentry?: boolean;/*** Skip the `runningOperation` check entirely and serialize only on the* short reservation. Set by interactive sends: "don't run two foreground@@ -1786,7 +1793,13 @@ export class TopicModel {Number.isFinite(reservedAt) &&Date.now() - reservedAt < TASK_CALLBACK_RESERVATION_TTL_MS;- if (reservation?.messageId === messageId && hasLiveReservation) return true;+ if (+ reservation?.messageId === messageId &&+ hasLiveReservation &&+ options?.allowSameReservationReentry !== false+ ) {+ return true;+ }const runningOperation = existing.metadata?.runningOperation;const ownedRunningOperation =@@ -1827,19 +1840,99 @@ export class TopicModel {return true;});+ /**+ * Repair the reconnect anchor after an intervention queue ACK. The same row+ * lock also releases only this continuation's reservation, closing the crash+ * window between provider ACK and execAgent's ordinary running-marker write.+ */+ repairAgentInterventionContinuation = async (params: {+ active: boolean;+ assistantMessageId: string;+ continuationOperationId: string;+ reservationId: string;+ scope?: string | null;+ sourceOperationId: string;+ startedAt: string;+ threadId?: string | null;+ topicId: string;+ }): Promise<'conflict' | 'repaired' | 'terminal'> =>+ this.db.transaction(async (tx) => {+ const [existing] = await tx+ .select({ metadata: topics.metadata })+ .from(topics)+ .where(and(eq(topics.id, params.topicId), this.ownership()))+ .for('update');+ if (!existing) return 'conflict';++ const current = existing.metadata?.runningOperation;+ const reservation = existing.metadata?.taskCallbackReservation;+ const reservedAt = reservation ? Date.parse(reservation.reservedAt) : 0;+ const hasLiveReservation =+ !!reservation &&+ Number.isFinite(reservedAt) &&+ Date.now() - reservedAt < TASK_CALLBACK_RESERVATION_TTL_MS;+ const ownsCurrent =+ !current ||+ current.operationId === params.sourceOperationId ||+ current.operationId === params.continuationOperationId;+ const ownsReservation = reservation?.messageId === params.reservationId;+ if (hasLiveReservation && !ownsReservation) return 'conflict';+ if (!ownsCurrent) {+ if (ownsReservation) {+ await tx+ .update(topics)+ .set({+ metadata: { ...existing.metadata, taskCallbackReservation: null },+ updatedAt: new Date(),+ })+ .where(and(eq(topics.id, params.topicId), this.ownership()));+ }+ return 'conflict';+ }++ const runningOperation = params.active+ ? {+ ...(current?.operationId === params.continuationOperationId ? current : {}),+ assistantMessageId: params.assistantMessageId,+ operationId: params.continuationOperationId,+ scope: params.scope ?? undefined,+ startedAt: params.startedAt,+ threadId: params.threadId ?? undefined,+ }+ : null;+ await tx+ .update(topics)+ .set({+ metadata: {+ ...existing.metadata,+ runningOperation,+ ...(ownsReservation || !hasLiveReservation ? { taskCallbackReservation: null } : {}),+ },+ updatedAt: new Date(),+ })+ .where(and(eq(topics.id, params.topicId), this.ownership()));++ return params.active ? 'repaired' : 'terminal';+ });+/*** Release only the caller's reservation. The ownership check prevents a* delayed finally block from clearing a newer callback's claim.*/- releaseTaskCallbackReservation = async (id: string, messageId: string): Promise<void> => {- await this.db.transaction(async (tx) => {+ releaseTaskCallbackReservation = async (+ id: string,+ messageId: string,+ ): Promise<'absent' | 'foreign' | 'released'> =>+ this.db.transaction(async (tx) => {const [existing] = await tx.select({ metadata: topics.metadata }).from(topics).where(and(eq(topics.id, id), this.ownership())).for('update');- if (existing?.metadata?.taskCallbackReservation?.messageId !== messageId) return;+ const reservation = existing?.metadata?.taskCallbackReservation;+ if (!reservation) return 'absent';+ if (reservation.messageId !== messageId) return 'foreign';await tx.update(topics)@@ -1850,8 +1943,8 @@ export class TopicModel {},}).where(and(eq(topics.id, id), this.ownership()));+ return 'released';});- };/*** Arm a scheduled run on an owned topic: writes `metadata.scheduledRun` anddiff --git a/packages/heterogeneous-agents/src/askUser/AskUserBridge.test.ts b/packages/heterogeneous-agents/src/askUser/AskUserBridge.test.tsindex 4689db58e37..f969be0cb4a 100644--- a/packages/heterogeneous-agents/src/askUser/AskUserBridge.test.ts+++ b/packages/heterogeneous-agents/src/askUser/AskUserBridge.test.ts@@ -31,6 +31,8 @@ describe('AskUserBridge', () => {expect(req.type).toBe('agent_intervention_request');expect(req.operationId).toBe('op-1');expect(req.data.identifier).toBe('claude-code');+ expect(req.data.interactionKind).toBe('question');+ expect(req.data.provider).toBe('claude-code');expect(req.data.apiName).toBe('askUserQuestion');expect(req.data.toolCallId).toMatch(/^[\da-f-]{36}$/);expect(JSON.parse(req.data.arguments)).toEqual({ questions: [{ q: 'foo' }] });@@ -191,7 +193,10 @@ describe('AskUserBridge', () => {const req = await drain.firstEvent;expect(req.type).toBe('agent_intervention_request');- bridge.resolve('tc-1', { result: { picked: 'red' } });+ bridge.resolve('tc-1', {+ resolutionRequestId: '018fbd8e-7baf-7c6d-8000-000000000001',+ result: { picked: 'red' },+ });await pending;const resp = (await drain.events.next()).value as any;@@ -200,7 +205,9 @@ describe('AskUserBridge', () => {expect(resp.data).toEqual({cancelReason: undefined,cancelled: undefined,+ producerAck: true,result: { picked: 'red' },+ resolutionRequestId: '018fbd8e-7baf-7c6d-8000-000000000001',toolCallId: 'tc-1',});drain.stop();@@ -220,7 +227,9 @@ describe('AskUserBridge', () => {expect(resp.data).toEqual({cancelReason: 'user_cancelled',cancelled: true,+ producerAck: true,result: undefined,+ resolutionRequestId: undefined,toolCallId: 'tc-1',});drain.stop();@@ -240,7 +249,9 @@ describe('AskUserBridge', () => {expect(resp.data).toEqual({cancelReason: 'timeout',cancelled: true,+ producerAck: true,result: undefined,+ resolutionRequestId: undefined,toolCallId: 'tc-1',});drain.stop();diff --git a/packages/heterogeneous-agents/src/askUser/AskUserBridge.ts b/packages/heterogeneous-agents/src/askUser/AskUserBridge.tsindex dc2e5f32627..f8dd50f3651 100644--- a/packages/heterogeneous-agents/src/askUser/AskUserBridge.ts+++ b/packages/heterogeneous-agents/src/askUser/AskUserBridge.ts@@ -1,6 +1,8 @@import { randomUUID } from 'node:crypto';import type {+ AgentInterventionInteractionKind,+ AgentInterventionProvider,AgentInterventionRequestData,AgentInterventionResponseData,AgentStreamEvent,@@ -25,6 +27,8 @@ export interface InterventionAnswer {export interface PendingArgs {/** Whatever the MCP tool's input schema accepted (e.g. `{ questions: [...] }`). */arguments: unknown;+ /** Semantic shape of this interaction. Defaults to `question`. */+ interactionKind?: AgentInterventionInteractionKind;/*** Wire correlation key for this intervention. Used as the `toolCallId`* on outbound `agent_intervention_request` events and looked up by@@ -55,7 +59,7 @@ export interface PendingOptions {/*** Absolute deadline (`Date.now() + timeoutMs`). When it elapses, the* pending promise resolves with `{ cancelled: true, cancelReason: 'timeout' }`.- * Default: 5 minutes.+ * Default: 10 minutes.*/timeoutMs?: number;}@@ -66,7 +70,7 @@ interface PendingEntry {resolve: (answer: InterventionAnswer) => void;}-interface BridgeOptions {+export interface AskUserBridgeOptions {/*** Stamps `stepIndex` on emitted events. The bridge has no visibility into* the CC adapter's own step counter, so the producer (which owns the@@ -74,6 +78,10 @@ interface BridgeOptions {* tests, but real producers should plug in their adapter's current value.*/getStepIndex?: () => number;+ /** Legacy renderer identifier. This is not used to infer the provider. */+ identifier?: string;+ /** Agent provider that owns every request emitted by this bridge. */+ provider?: AgentInterventionProvider;}/**@@ -108,13 +116,17 @@ export class AskUserBridge {private readonly outboundQueue: AgentStreamEvent[] = [];private readonly outboundWaiters: Array<(value: IteratorResult<AgentStreamEvent>) => void> = [];private readonly getStepIndex: () => number;+ private readonly identifier: string;+ private readonly provider: AgentInterventionProvider;private closed = false;constructor(public readonly operationId: string,- options: BridgeOptions = {},+ options: AskUserBridgeOptions = {},) {this.getStepIndex = options.getStepIndex ?? (() => 0);+ this.identifier = options.identifier ?? 'claude-code';+ this.provider = options.provider ?? 'claude-code';}/** Currently-blocked MCP handler count. Useful for telemetry / shutdown gates. */@@ -175,14 +187,16 @@ export class AskUserBridge {// Emit the intervention request AFTER setting up the pending entry,// so any synchronous resolve from a test fixture finds the slot.- // Hardcoded to AskUserQuestion for now — the only intervention shape- // we support. Take an explicit `apiName` in PendingArgs when adding- // more (e.g. CC approval, file picker).+ // The canonical UI payload remains AskUserQuestion-shaped for all three+ // semantic kinds. Consumers use `interactionKind` and `provider` for+ // behavior; `identifier` remains only a renderer compatibility key.const data: AgentInterventionRequestData = {apiName: 'askUserQuestion',arguments: JSON.stringify(args.arguments ?? {}),deadline,- identifier: 'claude-code',+ identifier: this.identifier,+ interactionKind: args.interactionKind ?? 'question',+ provider: this.provider,toolCallId,};this.emit({@@ -206,6 +220,7 @@ export class AskUserBridge {cancelled?: boolean;cancelReason?: InterventionAnswer['cancelReason'];result?: unknown;+ resolutionRequestId?: string;},): void {const entry = this.pending_.get(toolCallId);@@ -220,6 +235,7 @@ export class AskUserBridge {cancelReason: payload.cancelled ? (payload.cancelReason ?? 'user_cancelled') : undefined,cancelled: payload.cancelled,result: payload.cancelled ? undefined : payload.result,+ resolutionRequestId: payload.resolutionRequestId,});entry.resolve(payload.cancelled@@ -306,12 +322,15 @@ export class AskUserBridge {cancelReason?: InterventionAnswer['cancelReason'];cancelled?: boolean;result?: unknown;+ resolutionRequestId?: string;},): void {const data: AgentInterventionResponseData = {cancelled: payload.cancelled,cancelReason: payload.cancelReason,+ producerAck: true,result: payload.result,+ resolutionRequestId: payload.resolutionRequestId,toolCallId,};this.emit({diff --git a/packages/heterogeneous-agents/src/askUser/index.ts b/packages/heterogeneous-agents/src/askUser/index.tsindex e5fa5e19232..83e9e6d9f5d 100644--- a/packages/heterogeneous-agents/src/askUser/index.ts+++ b/packages/heterogeneous-agents/src/askUser/index.ts@@ -13,6 +13,7 @@*/export {AskUserBridge,+ type AskUserBridgeOptions,type InterventionAnswer,type PendingArgs,type PendingOptions,diff --git a/packages/heterogeneous-agents/src/builtinMcp/LobeBuiltinMcpServer.ts b/packages/heterogeneous-agents/src/builtinMcp/LobeBuiltinMcpServer.tsindex 18d0225a44d..c86cb184e56 100644--- a/packages/heterogeneous-agents/src/builtinMcp/LobeBuiltinMcpServer.ts+++ b/packages/heterogeneous-agents/src/builtinMcp/LobeBuiltinMcpServer.ts@@ -483,7 +483,7 @@ export class LobeBuiltinMcpServer {: undefined;const answer = await op.bridge.pending(- { arguments: args, toolCallId },+ { arguments: args, interactionKind: 'question', toolCallId },{onProgress,progressIntervalMs: this.progressIntervalMs,diff --git a/packages/heterogeneous-agents/src/index.ts b/packages/heterogeneous-agents/src/index.tsindex a18258186c2..0e63b4333a9 100644--- a/packages/heterogeneous-agents/src/index.ts+++ b/packages/heterogeneous-agents/src/index.ts@@ -76,12 +76,15 @@ export { getHeterogeneousTypeLabel, HETEROGENEOUS_TYPE_LABELS } from './labels';export type {CreateAssistantIntent,MainAgentIntent,+ MainAgentInterventionState,+ MainAgentInterventionTransition,MainAgentReduceCtx,MainAgentRunState,MainAgentTurnToolState,MainPersistToolBatchIntent,MainRecordUsageIntent,MainResolveToolResultIntent,+ MainSetToolInterventionIntent,MainStreamContentIntent,MainUpdateToolStateIntent,PersistAssistantIntent,diff --git a/packages/heterogeneous-agents/src/mainAgentCoordinator/index.ts b/packages/heterogeneous-agents/src/mainAgentCoordinator/index.tsindex 96e773af900..8f9c43a879c 100644--- a/packages/heterogeneous-agents/src/mainAgentCoordinator/index.ts+++ b/packages/heterogeneous-agents/src/mainAgentCoordinator/index.ts@@ -2,12 +2,15 @@ export { reduce as reduceMainAgent } from './reducer';export type {CreateAssistantIntent,MainAgentIntent,+ MainAgentInterventionState,+ MainAgentInterventionTransition,MainAgentReduceCtx,MainAgentRunState,MainAgentTurnToolState,MainPersistToolBatchIntent,MainRecordUsageIntent,MainResolveToolResultIntent,+ MainSetToolInterventionIntent,MainStreamContentIntent,MainUpdateToolStateIntent,PersistAssistantIntent,diff --git a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.test.ts b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.test.tsindex 7701dcae653..1659dfe3d74 100644--- a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.test.ts+++ b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.test.ts@@ -558,3 +558,96 @@ describe('reduceMainAgent — newStep idempotency key', () => {expect(ofKind(steps[1], 'createAssistant')).toHaveLength(1);});});++describe('reduceMainAgent — heterogeneous intervention ACK boundary', () => {+ const request = {+ data: {+ apiName: 'askUserQuestion',+ arguments: JSON.stringify({+ questions: [+ {+ header: 'Permission',+ multiSelect: false,+ options: [+ { id: 'allow', label: 'Allow' },+ { id: 'deny', label: 'Deny' },+ ],+ question: 'Run command?',+ },+ ],+ }),+ deadline: 1_900_000_000_000,+ identifier: 'claude-code',+ interactionKind: 'permission',+ provider: 'cursor',+ toolCallId: 'permission-1',+ },+ type: 'agent_intervention_request',+ };++ it('materializes a request-before-tool row and persists pending exactly once', () => {+ const { state, steps } = run([request]);++ expect(ofKind(steps[0], 'persistToolBatch')).toHaveLength(1);+ expect(ofKind(steps[0], 'setToolIntervention')).toEqual([+ expect.objectContaining({+ request: expect.objectContaining({ interactionKind: 'permission', provider: 'cursor' }),+ toolCallId: 'permission-1',+ transition: 'pending',+ }),+ ]);+ expect(state.interventionsByCallId.get('permission-1')?.transition).toBe('pending');+ });++ it('keeps the XADD publish leg non-terminal and resolves only on producer ACK', () => {+ const requestId = '018fbd8e-7baf-7c6d-8000-000000000001';+ const publishLeg = {+ data: {+ producerAck: false,+ resolutionRequestId: requestId,+ result: { 'Run command?': 'allow' },+ toolCallId: 'permission-1',+ },+ type: 'agent_intervention_response',+ };+ const producerAck = {+ data: { ...publishLeg.data, producerAck: true },+ type: 'agent_intervention_response',+ };+ const { state, steps } = run([request, publishLeg, producerAck]);++ expect(steps[1]).toEqual([]);+ expect(ofKind(steps[2], 'setToolIntervention')).toEqual([+ expect.objectContaining({+ resolutionRequestId: requestId,+ toolCallId: 'permission-1',+ transition: 'resolved',+ }),+ ]);+ expect(state.interventionsByCallId.get('permission-1')).toMatchObject({+ resolutionRequestId: requestId,+ transition: 'resolved',+ });+ });++ it('buffers a producer ACK that beats the request and replays one terminal write', () => {+ const producerAck = {+ data: {+ producerAck: true,+ resolutionRequestId: '018fbd8e-7baf-7c6d-8000-000000000002',+ result: { 'Run command?': 'deny' },+ toolCallId: 'permission-1',+ },+ type: 'agent_intervention_response',+ };+ const { state, steps } = run([producerAck, request]);++ expect(steps[0]).toEqual([]);+ expect(ofKind(steps[1], 'setToolIntervention')).toHaveLength(1);+ expect(ofKind(steps[1], 'setToolIntervention')[0]).toMatchObject({+ request: expect.objectContaining({ provider: 'cursor' }),+ transition: 'resolved',+ });+ expect(state.interventionsByCallId.get('permission-1')?.transition).toBe('resolved');+ });+});diff --git a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.tsindex 37010597900..858d0cb755c 100644--- a/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts+++ b/packages/heterogeneous-agents/src/mainAgentCoordinator/reducer.ts@@ -1,8 +1,11 @@+import type { AgentInterventionRequestData } from '@lobechat/agent-gateway-client';+import type { SubagentIntent, SubagentReduceCtx } from '../subagentCoordinator';import { getEventScope, reduceSubagentRuns } from '../subagentCoordinator';import type { ToolCallPayload } from '../types';import type {MainAgentIntent,+ MainAgentInterventionState,MainAgentReduceCtx,MainAgentRunState,MainAgentTurnToolState,@@ -47,6 +50,7 @@ const emptyToolState = (): MainAgentTurnToolState => ({/** Deep-copy the parts of state a handler may mutate; subagents is swapped wholesale. */const copyState = (s: MainAgentRunState): MainAgentRunState => ({...s,+ interventionsByCallId: new Map(s.interventionsByCallId),toolState: copyToolState(s.toolState),turnMetadata: { ...s.turnMetadata },});@@ -255,6 +259,7 @@ const reduceToolsChunk = (): ReduceResult => {const next = copyState(state);const newToolMsgIds: string[] = [];+ const newToolCallIds: string[] = [];for (const tool of tools) {if (next.toolState.persistedIds.has(tool.id)) continue;@@ -268,6 +273,7 @@ const reduceToolsChunk = (});const toolMessageId = ctx.newId('message');next.toolState.toolMsgIdByCallId.set(tool.id, toolMessageId);+ newToolCallIds.push(tool.id);newToolMsgIds.push(toolMessageId);}@@ -285,6 +291,16 @@ const reduceToolsChunk = (},];+ // A response can beat the provider's tool lifecycle event. Once the tool+ // row is materialized, replay the buffered latest transition after the+ // persistToolBatch intent so the interpreter always has a valid target.+ for (const toolCallId of newToolCallIds) {+ const intervention = next.interventionsByCallId.get(toolCallId);+ if (intervention) {+ intents.push({ ...intervention, kind: 'setToolIntervention', toolCallId });+ }+ }+// Advance the chain fallback to this turn's last tool message.const lastToolMsgId = newToolMsgIds.at(-1);if (lastToolMsgId) next.lastToolMsgIdEver = lastToolMsgId;@@ -308,6 +324,96 @@ const reduceToolsChunk = (return { intents, state: next };};+const isInterventionRequest = (data: any): boolean =>+ typeof data?.apiName === 'string' &&+ typeof data?.arguments === 'string' &&+ typeof data?.deadline === 'number' &&+ typeof data?.identifier === 'string' &&+ typeof data?.toolCallId === 'string' &&+ data.toolCallId.length > 0;++const reduceInterventionRequest = (+ state: MainAgentRunState,+ data: any,+ ctx: MainAgentReduceCtx,+): ReduceResult => {+ if (!isInterventionRequest(data)) return { intents: [], state };++ const request = data as AgentInterventionRequestData;+ const existing = state.interventionsByCallId.get(request.toolCallId);+ const preparedState = copyState(state);+ const intervention: MainAgentInterventionState = existing+ ? { ...existing, request }+ : { intervention: { status: 'pending' }, request, transition: 'pending' };+ preparedState.interventionsByCallId.set(request.toolCallId, intervention);++ // The bridge and the adapter run on independent async pumps, so the request+ // can arrive before tools_calling. The request already carries the complete+ // canonical tool payload; materialize it here instead of dropping pending+ // state or relying on process affinity for a later replay.+ if (!state.toolState.toolMsgIdByCallId.has(request.toolCallId)) {+ return reduceToolsChunk(+ preparedState,+ [+ {+ apiName: request.apiName,+ arguments: request.arguments,+ id: request.toolCallId,+ identifier: request.identifier,+ type: 'default',+ },+ ],+ ctx,+ );+ }++ return {+ intents: [{ ...intervention, kind: 'setToolIntervention', toolCallId: request.toolCallId }],+ state: preparedState,+ };+};++const reduceInterventionResponse = (state: MainAgentRunState, data: any): ReduceResult => {+ if (typeof data?.toolCallId !== 'string' || data.toolCallId.length === 0) {+ return { intents: [], state };+ }+ // New two-leg resolution: the first XADD only delivers the user's intent to+ // the producer. It becomes terminal only after AskUserBridge echoes an ACK.+ // Legacy responses had no request id, so retain their historical behavior.+ if (typeof data.resolutionRequestId === 'string' && data.producerAck !== true) {+ return { intents: [], state };+ }++ const existing = state.interventionsByCallId.get(data.toolCallId);+ const transition: MainAgentInterventionState['transition'] = !data.cancelled+ ? 'resolved'+ : data.cancelReason === 'timeout'+ ? 'timed_out'+ : data.cancelReason === 'session_ended'+ ? 'session_ended'+ : 'cancelled';+ const intervention: MainAgentInterventionState = {+ intervention: data.cancelled+ ? { rejectedReason: data.cancelReason ?? 'user_cancelled', status: 'rejected' }+ : { status: 'approved' },+ request: existing?.request,+ resolutionRequestId:+ typeof data.resolutionRequestId === 'string' ? data.resolutionRequestId : undefined,+ transition,+ };+ const next = copyState(state);+ next.interventionsByCallId.set(data.toolCallId, intervention);++ if (!state.toolState.toolMsgIdByCallId.has(data.toolCallId)) {+ return { intents: [], state: next };+ }++ return {+ intents: [{ ...intervention, kind: 'setToolIntervention', toolCallId: data.toolCallId }],+ state: next,+ };+};+const reduceStreamChunk = (state: MainAgentRunState,data: any,@@ -466,6 +572,12 @@ export const reduce = (case 'tool_result': {return reduceToolResult(state, event, ctx);}+ case 'agent_intervention_request': {+ return reduceInterventionRequest(state, data, ctx);+ }+ case 'agent_intervention_response': {+ return reduceInterventionResponse(state, data);+ }case 'step_complete': {if (data?.phase === 'turn_metadata') return reduceTurnMetadata(state, data);return { intents: [], state };diff --git a/packages/heterogeneous-agents/src/mainAgentCoordinator/types.ts b/packages/heterogeneous-agents/src/mainAgentCoordinator/types.tsindex 57c4216fd65..0a8304a283f 100644--- a/packages/heterogeneous-agents/src/mainAgentCoordinator/types.ts+++ b/packages/heterogeneous-agents/src/mainAgentCoordinator/types.ts@@ -1,3 +1,6 @@+import type { AgentInterventionRequestData } from '@lobechat/agent-gateway-client';+import type { ToolIntervention } from '@lobechat/types';+import type { PersistToolBatchEntry, SubagentRunsState } from '../subagentCoordinator';import { createSubagentRunsState } from '../subagentCoordinator';import type { ExternalSignalContext, ToolCallPayload } from '../types';@@ -57,6 +60,19 @@ export interface MainAgentTurnToolState {toolMsgIdByCallId: Map<string, string>;}+export type MainAgentInterventionTransition =+ 'cancelled' | 'pending' | 'resolved' | 'session_ended' | 'timed_out';++/** Latest durable projection for one intervention correlation id. */+export interface MainAgentInterventionState {+ intervention: ToolIntervention;+ /** Original request metadata, retained so terminal business hooks stay typed. */+ request?: AgentInterventionRequestData;+ /** User-resolution id echoed by the producer on its terminal ACK. */+ resolutionRequestId?: string;+ transition: MainAgentInterventionTransition;+}+/*** Per-run main-agent state. Lifetime spans the whole CLI run. Designed to be* fully RE-HYDRATABLE from the DB so a stateless server replica can project it@@ -81,6 +97,8 @@ export interface MainAgentRunState {currentMainMessageId: string | undefined;/** Set once a terminal event has been reduced (idempotent finalize). */ended: boolean;+ /** Request/terminal state buffered independently from tool-event ordering. */+ interventionsByCallId: Map<string, MainAgentInterventionState>;/** Highest seen reasoning snapshot sequence (replace-mode de-dup). */lastReasoningSnapshotSeq: number;/**@@ -131,6 +149,7 @@ export const createMainAgentRunState = (seedAssistantId: string): MainAgentRunStlastReasoningSnapshotSeq: 0,lastTextSnapshotSeq: 0,lastToolMsgIdEver: undefined,+ interventionsByCallId: new Map(),subagents: createSubagentRunsState(),toolState: { payloads: [], persistedIds: new Set(), toolMsgIdByCallId: new Map() },turnMetadata: {},@@ -173,6 +192,7 @@ export type MainAgentIntent =| MainPersistToolBatchIntent| MainUpdateToolStateIntent| MainResolveToolResultIntent+ | MainSetToolInterventionIntent| MainRecordUsageIntent| SetErrorIntent;@@ -256,6 +276,12 @@ export interface MainResolveToolResultIntent {toolCallId: string;}+/** Persist one intervention state transition on its correlated tool row. */+export interface MainSetToolInterventionIntent extends MainAgentInterventionState {+ kind: 'setToolIntervention';+ toolCallId: string;+}+/** Attach per-turn usage/model/provider to the current assistant. */export interface MainRecordUsageIntent {kind: 'recordUsage';diff --git a/packages/heterogeneous-agents/src/spawn/cursorAcpSession.test.ts b/packages/heterogeneous-agents/src/spawn/cursorAcpSession.test.tsindex 4030da3bf40..6c9b0bc398f 100644--- a/packages/heterogeneous-agents/src/spawn/cursorAcpSession.test.ts+++ b/packages/heterogeneous-agents/src/spawn/cursorAcpSession.test.ts@@ -190,6 +190,9 @@ const createSessionOptions = (...overrides,});+const createCursorBridge = () =>+ new AskUserBridge('operation-1', { identifier: 'claude-code', provider: 'cursor' });+afterEach(() => {vi.useRealTimers();vi.restoreAllMocks();@@ -327,7 +330,7 @@ describe('CursorAcpSession', () => {const fake = createAcpProcess({ askQuestion: true });spawnMock.mockReturnValue(fake.child);vi.spyOn(process, 'kill').mockImplementation(() => true);- const bridge = new AskUserBridge('operation-1');+ const bridge = createCursorBridge();const options = createSessionOptions({ askUserBridge: bridge });const events: AgentStreamEvent[] = [];options.onEvents = (batch) => {@@ -366,7 +369,7 @@ describe('CursorAcpSession', () => {const fake = createAcpProcess({ askQuestion: true });spawnMock.mockReturnValue(fake.child);vi.spyOn(process, 'kill').mockImplementation(() => true);- const bridge = new AskUserBridge('operation-1');+ const bridge = createCursorBridge();const options = createSessionOptions({ askUserBridge: bridge });const events: AgentStreamEvent[] = [];options.onEvents = (batch) => {@@ -379,6 +382,8 @@ describe('CursorAcpSession', () => {expect(intervention.value).toMatchObject({data: {apiName: 'askUserQuestion',+ interactionKind: 'question',+ provider: 'cursor',toolCallId: 'cursor-question-1',},type: 'agent_intervention_request',@@ -388,7 +393,10 @@ describe('CursorAcpSession', () => {{header: 'Scope',multiSelect: false,- options: [{ label: 'Narrow' }, { label: 'Full' }],+ options: [+ { id: 'narrow', label: 'Narrow' },+ { id: 'full', label: 'Full' },+ ],question: 'How broad should the fix be?',},],@@ -435,7 +443,7 @@ describe('CursorAcpSession', () => {const fake = createAcpProcess({ askQuestion: true });spawnMock.mockReturnValue(fake.child);vi.spyOn(process, 'kill').mockImplementation(() => true);- const bridge = new AskUserBridge('operation-1');+ const bridge = createCursorBridge();const options = createSessionOptions({ askUserBridge: bridge });const eventIterator = bridge.events()[Symbol.asyncIterator]();const run = new CursorAcpSession(options).run();@@ -468,7 +476,7 @@ describe('CursorAcpSession', () => {});spawnMock.mockReturnValue(fake.child);vi.spyOn(process, 'kill').mockImplementation(() => true);- const bridge = new AskUserBridge('operation-1');+ const bridge = createCursorBridge();const events: AgentStreamEvent[] = [];const sessionOptions = createSessionOptions({ askUserBridge: bridge });sessionOptions.onEvents = (batch) => {@@ -479,12 +487,20 @@ describe('CursorAcpSession', () => {const intervention = await eventIterator.next();expect(intervention.value!.data.toolCallId).toBe('cursor-permission-permission-1-tool-1');+ expect(intervention.value!.data).toMatchObject({+ interactionKind: 'permission',+ provider: 'cursor',+ });expect(JSON.parse(intervention.value!.data.arguments)).toEqual({questions: [{header: 'Permission required',multiSelect: false,- options: [{ label: 'Allow once' }, { label: 'Always allow' }, { label: 'Reject' }],+ options: [+ { id: 'allow-once', label: 'Allow once' },+ { id: 'allow-always', label: 'Always allow' },+ { id: 'reject-once', label: 'Reject' },+ ],question: 'Run the test suite',},],@@ -502,7 +518,7 @@ describe('CursorAcpSession', () => {}),);bridge.resolve(intervention.value!.data.toolCallId, {- result: { 'Run the test suite': 'Allow once' },+ result: { 'Run the test suite': 'allow-once' },});await run;@@ -524,6 +540,7 @@ describe('CursorAcpSession', () => {undefined,{ cancelReason: 'user_cancelled', cancelled: true } as const,{ result: { 'Run the test suite': 'Allow everything' } },+ { result: { 'Run the test suite': 'Always allow' } },]) {const fake = createAcpProcess({serverRequest: {@@ -541,7 +558,7 @@ describe('CursorAcpSession', () => {});spawnMock.mockReturnValue(fake.child);vi.spyOn(process, 'kill').mockImplementation(() => true);- const bridge = bridgeAnswer ? new AskUserBridge('operation-1') : undefined;+ const bridge = bridgeAnswer ? createCursorBridge() : undefined;const run = new CursorAcpSession(createSessionOptions({ askUserBridge: bridge })).run();if (bridge) {@@ -556,6 +573,40 @@ describe('CursorAcpSession', () => {}});+ it('uses exact option ids when provider permission labels are duplicated', async () => {+ const fake = createAcpProcess({+ serverRequest: {+ id: 'permission-duplicate-labels',+ method: 'session/request_permission',+ params: {+ options: [+ { kind: 'allow_once', name: 'Continue', optionId: 'allow-once' },+ { kind: 'reject_once', name: 'Continue', optionId: 'reject-once' },+ ],+ toolCall: { title: 'Edit README', toolCallId: 'tool-duplicate-labels' },+ },+ },+ });+ spawnMock.mockReturnValue(fake.child);+ vi.spyOn(process, 'kill').mockImplementation(() => true);+ const bridge = createCursorBridge();+ const run = new CursorAcpSession(createSessionOptions({ askUserBridge: bridge })).run();++ const intervention = await bridge.events()[Symbol.asyncIterator]().next();+ expect(JSON.parse(intervention.value!.data.arguments).questions[0].options).toEqual([+ { id: 'allow-once', label: 'Continue' },+ { id: 'reject-once', label: 'Continue' },+ ]);+ bridge.resolve(intervention.value!.data.toolCallId, {+ result: { 'Edit README': 'reject-once' },+ });+ await run;++ expect(fake.requests.find(({ id }) => id === 'permission-duplicate-labels')?.result).toEqual({+ outcome: { optionId: 'reject-once', outcome: 'selected' },+ });+ });+it.each([['Accept', 'accepted'],['Reject', 'rejected'],@@ -575,7 +626,7 @@ describe('CursorAcpSession', () => {});spawnMock.mockReturnValue(fake.child);vi.spyOn(process, 'kill').mockImplementation(() => true);- const bridge = new AskUserBridge('operation-1');+ const bridge = createCursorBridge();const eventIterator = bridge.events()[Symbol.asyncIterator]();const run = new CursorAcpSession(createSessionOptions({ askUserBridge: bridge })).run();@@ -585,14 +636,18 @@ describe('CursorAcpSession', () => {{header: 'Fix approvals',multiSelect: false,- options: [{ label: 'Accept' }, { label: 'Reject' }],+ options: [+ { id: 'accepted', label: 'Accept' },+ { id: 'rejected', label: 'Reject' },+ ],question: 'Require an explicit decision.\n\n1. Show the plan.\n2. Wait for the user.',},],});bridge.resolve(intervention.value!.data.toolCallId, {result: {- 'Require an explicit decision.\n\n1. Show the plan.\n2. Wait for the user.': selection,+ 'Require an explicit decision.\n\n1. Show the plan.\n2. Wait for the user.':+ selection === 'Accept' ? 'accepted' : 'rejected',},});await run;@@ -613,7 +668,7 @@ describe('CursorAcpSession', () => {});spawnMock.mockReturnValue(fake.child);vi.spyOn(process, 'kill').mockImplementation(() => true);- const bridge = withBridge ? new AskUserBridge('operation-1') : undefined;+ const bridge = withBridge ? createCursorBridge() : undefined;const run = new CursorAcpSession(createSessionOptions({ askUserBridge: bridge })).run();if (bridge) {@@ -639,7 +694,7 @@ describe('CursorAcpSession', () => {});spawnMock.mockReturnValue(fake.child);vi.spyOn(process, 'kill').mockImplementation(() => true);- const bridge = new AskUserBridge('operation-1');+ const bridge = createCursorBridge();const eventIterator = bridge.events()[Symbol.asyncIterator]();const run = new CursorAcpSession(createSessionOptions({ askUserBridge: bridge })).run();diff --git a/packages/heterogeneous-agents/src/spawn/cursorAcpSession.ts b/packages/heterogeneous-agents/src/spawn/cursorAcpSession.tsindex 1165a5d4f21..421fcd46341 100644--- a/packages/heterogeneous-agents/src/spawn/cursorAcpSession.ts+++ b/packages/heterogeneous-agents/src/spawn/cursorAcpSession.ts@@ -77,7 +77,7 @@ interface CanonicalAskQuestionArgs {questions: Array<{header: string;multiSelect: boolean;- options: Array<{ label: string }>;+ options: Array<{ id?: string; label: string }>;question: string;}>;}@@ -105,7 +105,7 @@ export const normalizeCursorQuestion = (questions: request.questions.map((question) => ({header: request.title ?? '',multiSelect: question.allowMultiple === true,- options: question.options.map(({ label }) => ({ label })),+ options: question.options.map(({ id, label }) => ({ id, label })),question: question.prompt,})),});@@ -224,6 +224,7 @@ export class CursorAcpSession extends AcpAgentSession<const request = this.parsePermissionRequest(message.params);const selected = await this.selectBridgeOption({header: 'Permission required',+ interactionKind: 'permission',options: request.options.map(({ name, optionId }) => ({ id: optionId, label: name })),question: request.toolCall.title,toolCallId: this.buildInterventionToolCallId(@@ -256,6 +257,7 @@ export class CursorAcpSession extends AcpAgentSession<if (!this.options.askUserBridge) return { outcome: { outcome: 'cancelled' } };const answer = await this.options.askUserBridge.pending({arguments: args,+ interactionKind: 'question',toolCallId: request.toolCallId,});return this.buildQuestionResponse(request, answer);@@ -266,6 +268,7 @@ export class CursorAcpSession extends AcpAgentSession<const question = [request.overview, request.plan].filter(Boolean).join('\n\n');const selected = await this.selectBridgeOption({header: request.name ?? 'Plan approval',+ interactionKind: 'plan',options: [{ id: 'accepted', label: 'Accept' },{ id: 'rejected', label: 'Reject' },@@ -366,11 +369,13 @@ export class CursorAcpSession extends AcpAgentSession<private async selectBridgeOption({header,+ interactionKind,options,question,toolCallId,}: {header: string;+ interactionKind: 'permission' | 'plan';options: CursorBridgeOption[];question: string;toolCallId: string;@@ -382,7 +387,7 @@ export class CursorAcpSession extends AcpAgentSession<{header,multiSelect: false,- options: options.map(({ label }) => ({ label })),+ options: options.map(({ id, label }) => ({ id, label })),question,},],@@ -396,6 +401,7 @@ export class CursorAcpSession extends AcpAgentSession<});const answer = await this.options.askUserBridge.pending({arguments: arguments_,+ interactionKind,toolCallId,});await this.pushToPipeline({@@ -405,7 +411,10 @@ export class CursorAcpSession extends AcpAgentSession<toolCallId,});const selections = this.getAnswerSelections(answer, question);- return options.find(({ id, label }) => selections.includes(id) || selections.includes(label));+ // Provider-owned permission/plan choices must round-trip the exact stable+ // option id. Labels are display-only and may be duplicated or localized;+ // accepting a label here could approve the wrong provider decision.+ return options.find(({ id }) => selections.includes(id));}private buildInterventionToolCallId(diff --git a/packages/locales/src/default/notification.ts b/packages/locales/src/default/notification.tsindex a4256eff01d..514adf646f2 100644--- a/packages/locales/src/default/notification.ts+++ b/packages/locales/src/default/notification.ts@@ -10,6 +10,8 @@ export default {'Your scheduled task "{{jobName}}" was paused after {{count}} consecutive failures. Review the error and resume it when ready.','agent_cron_job_failed_paused_title': 'Scheduled task paused','agent_cron_job_failed_title': 'Scheduled task failed',+ 'agent_intervention_required': '{{agent}} needs your input: {{summary}}',+ 'agent_intervention_required_title': '{{agent}} needs your review','agent_run_completed': '{{preview}}','agent_run_completed_title': 'Agent task completed','agent_transfer_reassigned':diff --git a/packages/shared-tool-ui/src/AskUserQuestion/AskUserQuestionView.tsx b/packages/shared-tool-ui/src/AskUserQuestion/AskUserQuestionView.tsxindex d7e5904aeb6..e513f0de4b1 100644--- a/packages/shared-tool-ui/src/AskUserQuestion/AskUserQuestionView.tsx+++ b/packages/shared-tool-ui/src/AskUserQuestion/AskUserQuestionView.tsx@@ -13,6 +13,9 @@ import QuestionPanel from './QuestionPanel';import type { AskUserQuestionItem } from './types';import type { AskUserFormApi } from './useAskUserForm';+const optionValue = (option: AskUserQuestionItem['options'][number]): string =>+ option.id ?? option.label;+const styles = createStaticStyles(({ css }) => ({tabs: css`[role='tablist'] {@@ -121,7 +124,7 @@ export const AskUserQuestionView = memo<AskUserQuestionViewProps>((props) => {if (stored != null) return stored;if (!activeQuestion.multiSelect) {const picked = picks[activeQuestion.question];- const idx = activeQuestion.options.findIndex((o) => o.label === picked);+ const idx = activeQuestion.options.findIndex((option) => optionValue(option) === picked);if (idx >= 0) return idx;}return 0;@@ -196,7 +199,7 @@ export const AskUserQuestionView = memo<AskUserQuestionViewProps>((props) => {if (idx < q.options.length) {event.preventDefault();setHighlight(q, idx);- handleToggle(q, q.options[idx].label, { submitOnComplete: true });+ handleToggle(q, optionValue(q.options[idx]), { submitOnComplete: true });} else if (idx === q.options.length) {event.preventDefault();setHighlight(q, q.options.length);@@ -220,7 +223,7 @@ export const AskUserQuestionView = memo<AskUserQuestionViewProps>((props) => {if (!rowNavEnabled || highlightedIndex == null || highlightedIndex >= q.options.length)return;event.preventDefault();- handleToggle(q, q.options[highlightedIndex].label);+ handleToggle(q, optionValue(q.options[highlightedIndex]));return;}@@ -238,10 +241,10 @@ export const AskUserQuestionView = memo<AskUserQuestionViewProps>((props) => {highlightedIndex != null &&highlightedIndex < q.options.length &&!(custom[q.question] ?? '').trim() &&- picks[q.question] !== q.options[highlightedIndex].label+ picks[q.question] !== optionValue(q.options[highlightedIndex])) {event.preventDefault();- handleToggle(q, q.options[highlightedIndex].label, { submitOnComplete: true });+ handleToggle(q, optionValue(q.options[highlightedIndex]), { submitOnComplete: true });return;}if (isSubmitDisabled) return;diff --git a/packages/shared-tool-ui/src/AskUserQuestion/QuestionPanel.tsx b/packages/shared-tool-ui/src/AskUserQuestion/QuestionPanel.tsxindex 6111a8ae0af..eed56e698d7 100644--- a/packages/shared-tool-ui/src/AskUserQuestion/QuestionPanel.tsx+++ b/packages/shared-tool-ui/src/AskUserQuestion/QuestionPanel.tsx@@ -39,7 +39,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({}));interface QuestionPanelProps {- /** The picked option label(s) for this question, if any. */+ /** The picked option id(s), falling back to labels for legacy options. */answer: string | string[] | undefined;/** Placeholder for the trailing "write your own" free-text row. */customPlaceholder: string;@@ -63,7 +63,7 @@ interface QuestionPanelProps {* falls back to the default newline behavior.*/onPressEnter?: () => void;- onToggle: (q: AskUserQuestionItem, label: string) => void;+ onToggle: (q: AskUserQuestionItem, value: string) => void;question: AskUserQuestionItem;/** Badge text for options carrying the "(Recommended)" label marker. */recommendedTag: string;@@ -91,8 +91,8 @@ export const QuestionPanel = memo<QuestionPanelProps>(onPressEnter,recommendedTag,}) => {- const isOptionSelected = (label: string): boolean =>- question.multiSelect ? Array.isArray(answer) && answer.includes(label) : answer === label;+ const isOptionSelected = (value: string): boolean =>+ question.multiSelect ? Array.isArray(answer) && answer.includes(value) : answer === value;return (<Flexbox gap={10}>@@ -107,19 +107,22 @@ export const QuestionPanel = memo<QuestionPanelProps>(<Text strong>{question.question}</Text><Flexbox gap={4} role="listbox">- {question.options.map((opt, optIdx) => (- <OptionCard- description={opt.description}- disabled={disabled}- highlighted={highlightedIndex === optIdx}- index={optIdx + 1}- key={opt.label}- label={opt.label}- recommendedText={opt.recommended ? recommendedTag : undefined}- selected={isOptionSelected(opt.label)}- onToggle={() => onToggle(question, opt.label)}- />- ))}+ {question.options.map((opt, optIdx) => {+ const value = opt.id ?? opt.label;+ return (+ <OptionCard+ description={opt.description}+ disabled={disabled}+ highlighted={highlightedIndex === optIdx}+ index={optIdx + 1}+ key={value}+ label={opt.label}+ recommendedText={opt.recommended ? recommendedTag : undefined}+ selected={isOptionSelected(value)}+ onToggle={() => onToggle(question, value)}+ />+ );+ })}{/* Last item: let the user write their own answer for this question.Numbered as the next option so it reads as one more choice. */}<Flexbox horizontal align="center" className={styles.customRow} gap={12}>diff --git a/packages/shared-tool-ui/src/AskUserQuestion/normalize.test.ts b/packages/shared-tool-ui/src/AskUserQuestion/normalize.test.tsindex 100b811dfa7..167246955a4 100644--- a/packages/shared-tool-ui/src/AskUserQuestion/normalize.test.ts+++ b/packages/shared-tool-ui/src/AskUserQuestion/normalize.test.ts@@ -31,6 +31,26 @@ describe('normalizeAskUserQuestions', () => {]);});+ it('preserves stable option ids while stripping unknown option fields', () => {+ const questions = normalizeAskUserQuestions({+ questions: [+ {+ header: 'Permission',+ options: [+ { id: 'allow-once', ignored: 'raw', label: 'Continue' },+ { id: 'reject-once', label: 'Continue' },+ ],+ question: 'Edit README?',+ },+ ],+ });++ expect(questions[0].options).toEqual([+ { id: 'allow-once', label: 'Continue' },+ { id: 'reject-once', label: 'Continue' },+ ]);+ });+it('accepts a single question object for stale payloads', () => {const questions = normalizeAskUserQuestions({questions: {diff --git a/packages/shared-tool-ui/src/AskUserQuestion/normalize.ts b/packages/shared-tool-ui/src/AskUserQuestion/normalize.tsindex 35beb166274..6f149a3c3b8 100644--- a/packages/shared-tool-ui/src/AskUserQuestion/normalize.ts+++ b/packages/shared-tool-ui/src/AskUserQuestion/normalize.ts@@ -40,8 +40,10 @@ const normalizeOption = (value: unknown): AskUserQuestionOption | undefined => {const recommended = strippedLabel.length > 0 && strippedLabel !== rawLabel;const label = recommended ? strippedLabel : rawLabel;const description = pickString(option?.description);+ const id = pickString(option?.id);return {+ ...(id ? { id } : {}),label,...(description ? { description } : {}),...(recommended ? { recommended } : {}),diff --git a/packages/shared-tool-ui/src/AskUserQuestion/types.ts b/packages/shared-tool-ui/src/AskUserQuestion/types.tsindex 79cad90b202..7db29646d7c 100644--- a/packages/shared-tool-ui/src/AskUserQuestion/types.ts+++ b/packages/shared-tool-ui/src/AskUserQuestion/types.ts@@ -4,6 +4,11 @@*/export interface AskUserQuestionOption {description?: string;+ /**+ * Stable provider-owned value. When present the UI displays `label` but+ * submits this exact id, avoiding ambiguous or localized-label mapping.+ */+ id?: string;label: string;/*** The tool schema has no recommendation field, so models mark their pick bydiff --git a/packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.test.ts b/packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.test.tsindex a035e49cdbf..f6a32b65422 100644--- a/packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.test.ts+++ b/packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.test.ts@@ -47,6 +47,30 @@ const setup = (args: AskUserQuestionArgs, persistedDraft?: unknown) => {};describe('useAskUserForm select-to-submit', () => {+ it('displays labels but submits stable option ids', () => {+ const args: AskUserQuestionArgs = {+ questions: [+ {+ header: 'Permission',+ options: [+ { id: 'allow-once', label: 'Continue' },+ { id: 'reject-once', label: 'Continue' },+ ],+ question: 'Edit README?',+ },+ ],+ };+ const { hook, onInteractionAction } = setup(args);++ act(() => hook.result.current.handleToggle(args.questions[0], 'reject-once'));+ act(() => hook.result.current.handleSubmit());++ expect(onInteractionAction).toHaveBeenCalledExactlyOnceWith({+ payload: { 'Edit README?': 'reject-once' },+ type: 'submit',+ });+ });+it('submits immediately when a keyboard single-select pick completes the form', () => {const { hook, onInteractionAction } = setup(singleQuestionArgs);@@ -153,6 +177,27 @@ describe('useAskUserForm select-to-submit', () => {type: 'submit',});});++ it('keeps a resolving form visible but disables edits and resubmission', () => {+ const onInteractionAction = vi.fn();+ const hook = renderHook(() =>+ useAskUserForm({+ args: singleQuestionArgs,+ disabled: true,+ onInteractionAction,+ persistedDraft: undefined,+ writeDraft: vi.fn(),+ }),+ );++ act(() => hook.result.current.handleToggle(singleQuestionArgs.questions[0], 'Full'));+ act(() => hook.result.current.handleSubmit());++ expect(hook.result.current.picks).toEqual({});+ expect(hook.result.current.isSubmitDisabled).toBe(true);+ expect(hook.result.current.submitting).toBe(true);+ expect(onInteractionAction).not.toHaveBeenCalled();+ });});describe('useAskUserForm additional notes', () => {@@ -324,4 +369,36 @@ describe('useAskUserForm additional notes', () => {hook.unmount();vi.useRealTimers();});++ it('never selects the first provider-owned option when the countdown expires', () => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-08-22T00:00:00Z'));+ const onInteractionAction = vi.fn().mockResolvedValue(undefined);+ const hook = renderHook(() =>+ useAskUserForm({+ args: {+ questions: [+ {+ header: 'Permission',+ options: [+ { id: 'allow-once', label: 'Allow' },+ { id: 'deny', label: 'Deny' },+ ],+ question: 'Run command?',+ },+ ],+ },+ countdownMs: 1000,+ onInteractionAction,+ persistedDraft: undefined,+ writeDraft: vi.fn(),+ }),+ );++ act(() => vi.advanceTimersByTime(1000));++ expect(onInteractionAction).not.toHaveBeenCalled();+ hook.unmount();+ vi.useRealTimers();+ });});diff --git a/packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.ts b/packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.tsindex b57cd30df1e..2f49758ae2b 100644--- a/packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.ts+++ b/packages/shared-tool-ui/src/AskUserQuestion/useAskUserForm.ts@@ -20,6 +20,8 @@ export interface UseAskUserFormParams {* `false`, no timer runs) — used by surfaces with no bridge timeout.*/countdownMs?: number;+ /** Preserve the form but disable every action while a remote submit awaits producer ACK. */+ disabled?: boolean;onInteractionAction?: BuiltinInterventionProps<AskUserQuestionArgs>['onInteractionAction'];/** Raw persisted draft blob read from the host's store (coerced internally). */persistedDraft: unknown;@@ -76,6 +78,7 @@ export interface AskUserFormApi {export const useAskUserForm = ({args,countdownMs,+ disabled = false,onInteractionAction,persistedDraft,writeDraft,@@ -114,6 +117,9 @@ export const useAskUserForm = ({return () => clearInterval(id);}, [countdownEnabled]);const expired = countdownEnabled ? now >= deadline : false;+ const hasProviderOwnedOptionIds = questions.some((question) =>+ question.options.some((option) => !!option.id),+ );/*** Submit `payload` exactly as given. Used by the Submit button (with the@@ -122,7 +128,7 @@ export const useAskUserForm = ({*/const submitWith = useCallback(async (payload: Record<string, string | string[]>) => {- if (!onInteractionAction || submitting) return;+ if (!onInteractionAction || submitting || disabled) return;setSubmitting(true);try {await onInteractionAction({ payload, type: 'submit' });@@ -131,11 +137,12 @@ export const useAskUserForm = ({setSubmitting(false);}},- [onInteractionAction, submitting],+ [disabled, onInteractionAction, submitting],);const handleToggle = useCallback((q: AskUserQuestionItem, label: string, options?: { submitOnComplete?: boolean }) => {+ if (disabled) return;let nextPicks: Record<string, string | string[]>;if (q.multiSelect) {const current = (picks[q.question] as string[] | undefined) ?? [];@@ -200,6 +207,7 @@ export const useAskUserForm = ({[picks,custom,+ disabled,escapeActive,escapeText,questions,@@ -356,7 +364,7 @@ export const useAskUserForm = ({]);const handleSkip = useCallback(async () => {- if (!onInteractionAction || submitting) return;+ if (!onInteractionAction || submitting || disabled) return;setSubmitting(true);try {await onInteractionAction({ type: 'skip' });@@ -364,22 +372,26 @@ export const useAskUserForm = ({console.error('[AskUserQuestion] skip failed:', err);setSubmitting(false);}- }, [onInteractionAction, submitting]);+ }, [disabled, onInteractionAction, submitting]);const allAnswered = useMemo(() => questions.every((q) => isQuestionAnswered(q, picks, custom)),[picks, custom, questions],);- // Timeout fallback: when the countdown hits zero and the user hasn't- // submitted, fill option 1 of each unanswered question and submit. Beats+ // Timeout fallback for legacy question forms: when the countdown hits zero+ // and the user hasn't submitted, fill option 1 of each unanswered question and submit. Beats// letting the bridge time out into a `cancelled` isError — the model gets a// structured answer it can act on. Single-shot via the `submitting` guard.//// Escape-mode special case: if the user is in escape mode with non-empty text// when the clock hits zero, submit that text as-is rather than discarding it.useEffect(() => {- if (!expired || submitting || questions.length === 0) return;+ if (!expired || submitting || disabled || questions.length === 0) return;+ // A stable id means this is a provider-owned choice (permission/plan or a+ // newer exact-id question). Never infer consent by selecting option one:+ // let the producer timeout/cancel fail closed.+ if (hasProviderOwnedOptionIds) return;if (escapeActive && escapeAvailable && escapeText.trim().length > 0) {void submitWith({ [FREEFORM_PAYLOAD_KEY]: escapeText.trim() });return;@@ -402,6 +414,7 @@ export const useAskUserForm = ({}, [expired,submitting,+ disabled,questions,escapeActive,escapeAvailable,@@ -410,10 +423,12 @@ export const useAskUserForm = ({custom,supplementText,submitWith,+ hasProviderOwnedOptionIds,]);const activeQuestion = questions[Number(activeTab)] ?? questions[0];const isSubmitDisabled =+ disabled ||questions.length === 0 ||(inEscape? !escapeText.trim() || submitting || expired@@ -442,7 +457,7 @@ export const useAskUserForm = ({setEscapeMode,setQuestionMode,setSupplementMode,- submitting,+ submitting: submitting || disabled,supplementActive: inSupplement,supplementText,};diff --git a/packages/types/src/message/common/tools.ts b/packages/types/src/message/common/tools.tsindex 6cdb6578548..d85de0cb886 100644--- a/packages/types/src/message/common/tools.ts+++ b/packages/types/src/message/common/tools.ts@@ -5,7 +5,17 @@ import type { LobeToolRenderType } from '../../tool';// ToolIntervention must be defined first to avoid circular dependencyexport interface ToolIntervention {+ /** Stable sealed batch id, bound to one parked operation + assistant turn. */+ batchId?: string;+ /** Declaration order inside the sealed batch. */+ itemIndex?: number;+ /** Parked runtime operation this decision must resume or stop. */+ operationId?: string;rejectedReason?: string;+ /** Server-minted idempotency/rollback owner for an authoritative resolution. */+ resolutionRequestId?: string;+ /** User decision published, awaiting the blocked producer's ACK. */+ resolving?: boolean;/*** The user skipped the interaction (e.g. AskUserQuestion) rather than* rejecting the tool call — still `status: 'rejected'` for the runtime, but@@ -13,11 +23,18 @@ export interface ToolIntervention {*/skipped?: boolean;status?: 'pending' | 'approved' | 'rejected' | 'aborted' | 'none';+ stepIndex?: number;}export const ToolInterventionSchema = z.object({+ batchId: z.string().optional(),+ itemIndex: z.number().int().nonnegative().optional(),+ operationId: z.string().optional(),rejectedReason: z.string().optional(),+ resolving: z.boolean().optional(),+ resolutionRequestId: z.string().optional(),skipped: z.boolean().optional(),+ stepIndex: z.number().int().nonnegative().optional(),status: z.enum(['pending', 'approved', 'rejected', 'aborted', 'none']).optional(),});diff --git a/packages/types/src/tool/builtin.ts b/packages/types/src/tool/builtin.tsindex a18120cf6cc..e8943b02500 100644--- a/packages/types/src/tool/builtin.ts+++ b/packages/types/src/tool/builtin.ts@@ -503,6 +503,8 @@ export interface BuiltinInterventionProps<Arguments = any> {actionsPortalTarget?: HTMLElement | null;apiName?: string;args: Arguments;+ /** Keep the form visible but inert while a remote resolution awaits producer ACK. */+ disabled?: boolean;identifier?: string;interactionMode?: 'approval' | 'custom';messageId: string;diff --git a/packages/types/src/tool/intervention.ts b/packages/types/src/tool/intervention.tsindex dc8dd2ebe49..664f50f661f 100644--- a/packages/types/src/tool/intervention.ts+++ b/packages/types/src/tool/intervention.ts@@ -149,6 +149,51 @@ export const UserInterventionConfigSchema = z.object({approvalMode: z.enum(['auto-run', 'allow-list', 'manual', 'headless']),});+/**+ * Provider-neutral presentation class for a pending human intervention.+ *+ * Keep this helper in the shared tool contract so the runtime notification+ * producer and the Web batch-action gate cannot drift: an inline form must+ * never be treated as a binary approve/reject card merely because both happen+ * to use `plugin.intervention.status = pending` in message storage.+ */+export type ToolInterventionPresentation = {+ interactionKind: 'custom' | 'question' | 'tool_approval';+ surface: 'binary' | 'form';+};++const ASK_USER_QUESTION_IDENTIFIERS = new Set([+ 'claude-code',+ 'cursor',+ 'lobe-agent',+ 'lobe-user-interaction',+ 'qoder',+]);++const HETEROGENEOUS_CUSTOM_INTERACTION_IDENTIFIERS = new Set(['claude-code', 'cursor', 'qoder']);++export const classifyToolInterventionPresentation = (+ identifier: string,+ apiName?: string,+): ToolInterventionPresentation => {+ if (apiName === 'askUserQuestion' && ASK_USER_QUESTION_IDENTIFIERS.has(identifier)) {+ return { interactionKind: 'question', surface: 'form' };+ }++ if (identifier === 'lobe-web-onboarding' && apiName === 'showAgentMarketplace') {+ return { interactionKind: 'custom', surface: 'form' };+ }++ // Claude Code / Cursor ACP / Qoder expose provider-specific intervention+ // forms (permission, plan, bespoke prompts). They are intentionally kept+ // non-binary even when a newly added API name is not yet known to Web.+ if (HETEROGENEOUS_CUSTOM_INTERACTION_IDENTIFIERS.has(identifier)) {+ return { interactionKind: 'custom', surface: 'form' };+ }++ return { interactionKind: 'tool_approval', surface: 'binary' };+};+/*** Security Blacklist Rule* Used to forcefully block dangerous operations regardless of user settingsdiff --git a/public/.well-known/apple-app-site-association b/public/.well-known/apple-app-site-associationindex 1be94bc69f4..e04d7cb5048 100644--- a/public/.well-known/apple-app-site-association+++ b/public/.well-known/apple-app-site-association@@ -1,4 +1,12 @@{+ "applinks": {+ "details": [+ {+ "appIDs": ["4684H589ZU.com.lobehub.app"],+ "components": [{ "/": "/agent-approval" }]+ }+ ]+ },"webcredentials": {"apps": ["4684H589ZU.com.lobehub.app"]}diff --git a/src/features/Conversation/InterventionBar/index.tsx b/src/features/Conversation/InterventionBar/index.tsxindex d1aa6bb629a..2d98726827b 100644--- a/src/features/Conversation/InterventionBar/index.tsx+++ b/src/features/Conversation/InterventionBar/index.tsx@@ -4,6 +4,7 @@ import { memo, useCallback, useMemo, useState } from 'react';import { useConversationResourceAccess } from '../hooks/useConversationResourceAccess';import { useConversationStore } from '../store';import {+ canApproveInterventionBatch,getInterventionBatch,type PendingIntervention,} from '../store/slices/data/pendingInterventions';@@ -67,17 +68,17 @@ const InterventionBar = memo<InterventionBarProps>(({ interventions }) => {// Tabs still list every pending call so nothing is hidden; only the batch// action is scoped to the active turn.const hasMultipleCards = interventions.length > 1;- const canApproveBatch = batch.length > 1;+ const canApproveBatch = canApproveInterventionBatch(batch);return (<ChatInputdata-pending-hotkey-scopeclassName={styles.container}footer={<div className={styles.actions} ref={setActionsPortalTarget} />}- resize={false}// The card's action row — Stop sits beside Submit inside `ApprovalActions`// and the whole row portals in here.maxHeight={'50vh' as any}+ resize={false}>{hasMultipleCards && (<InterventionTabBardiff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/ApprovalActions.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/ApprovalActions.tsxindex 3c6396500f1..2263e79a973 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/ApprovalActions.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/ApprovalActions.tsx@@ -7,8 +7,6 @@ import type { KeyboardEvent as ReactKeyboardEvent } from 'react';import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';-import { useUserStore } from '@/store/user';-import { useConversationResourceAccess } from '../../../../../hooks/useConversationResourceAccess';import { useConversationStore } from '../../../../../store';import { type ApprovalMode } from './index';@@ -23,7 +21,8 @@ interface ApprovalActionsProps {* Callback to be called before approve action* Used to flush pending saves (e.g., debounced saves) from intervention components*/- onBeforeApprove?: () => void | Promise<void>;+ onBeforeApprove?: () =>+ Promise<Record<string, unknown> | undefined> | Record<string, unknown> | undefined;toolCallId: string;}@@ -183,8 +182,6 @@ const ApprovalActions = memo<ApprovalActionsProps>(stopPendingApprovalForCard,messageId,]);- const addToolToAllowList = useUserStore((s) => s.addToolToAllowList);-const handleSubmit = useCallback(async () => {if (loading || isMessageCreating || !canUseResource) return;setLoading(true);@@ -192,17 +189,18 @@ const ApprovalActions = memo<ApprovalActionsProps>(if (choice === 'reject') {await rejectAndContinueToolCall(messageId, reason.trim() || undefined);} else {- if (onBeforeApprove) await onBeforeApprove();- await approveToolCall(messageId, assistantGroupId ?? '');- if (isAllowListMode && choice === 'approve-remember') {- await addToolToAllowList(`${identifier}/${apiName}`);- }+ const editedArguments = await onBeforeApprove?.();+ await approveToolCall(messageId, assistantGroupId ?? '', {+ editedArguments,+ ...(isAllowListMode && choice === 'approve-remember'+ ? { rememberToolKey: `${identifier}/${apiName}` }+ : {}),+ });}} finally {setLoading(false);}}, [- addToolToAllowList,apiName,approveToolCall,assistantGroupId,diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.test.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.test.tsxindex 416f1149cac..285b3096bef 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.test.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.test.tsx@@ -66,6 +66,9 @@ vi.mock('@/store/user/selectors', () => ({}));vi.mock('../../../../../store', () => ({+ dataSelectors: {+ getDbMessageById: () => () => undefined,+ },useConversationStore: (selector: (state: { updatePluginArguments: ReturnType<typeof vi.fn> }) => unknown,) => selector({ updatePluginArguments: vi.fn() }),diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.tsxindex 021f68a561c..4f05cfd4fca 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.tsx@@ -9,7 +9,7 @@ import { ActionIcon, Avatar, Flexbox, Icon } from '@lobehub/ui';import { createStaticStyles } from 'antd-style';import isEqual from 'fast-deep-equal';import { ChevronDown, ChevronRight, Edit3Icon } from 'lucide-react';-import { memo, Suspense, useCallback, useMemo, useState } from 'react';+import { memo, Suspense, useCallback, useMemo, useRef, useState } from 'react';import { createPortal } from 'react-dom';import { useTranslation } from 'react-i18next';@@ -18,7 +18,7 @@ import { toolSelectors } from '@/store/tool/selectors';import { useUserStore } from '@/store/user';import { toolInterventionSelectors } from '@/store/user/selectors';-import { useConversationStore } from '../../../../../store';+import { dataSelectors, useConversationStore } from '../../../../../store';import Arguments from '../Arguments';import ApprovalActions from './ApprovalActions';import KeyValueEditor from './KeyValueEditor';@@ -74,6 +74,14 @@ const FallbackIntervention = memo<FallbackInterventionProps>(const [isEditing, setIsEditing] = useState(false);const [showArgs, setShowArgs] = useState(false);const updatePluginArguments = useConversationStore((s) => s.updatePluginArguments);+ const message = useConversationStore((s) => dataSelectors.getDbMessageById(id)(s));+ const usesDurableServerClaim = Boolean(+ message?.pluginIntervention?.operationId && message.pluginIntervention.batchId,+ );+ const [pendingEditedArguments, setPendingEditedArguments] = useState<+ Record<string, unknown> | undefined+ >();+ const pendingEditedArgumentsRef = useRef<Record<string, unknown> | undefined>(undefined);const pluginMeta = useToolStore(toolSelectors.getMetaById(identifier));const isBuiltin = builtinToolIdentifiers.includes(identifier);@@ -86,7 +94,15 @@ const FallbackIntervention = memo<FallbackInterventionProps>(? t(`builtins.${identifier}.apiName.${apiName}`, { defaultValue: apiName, ns: 'plugin' }): apiName;- const parsedArgs = useMemo(() => safeParseJSON(requestArgs || '') ?? {}, [requestArgs]);+ const parsedArgs = useMemo(+ () => pendingEditedArguments ?? safeParseJSON(requestArgs || '') ?? {},+ [pendingEditedArguments, requestArgs],+ );+ const renderedArgs = useMemo(+ () =>+ pendingEditedArguments ? JSON.stringify(pendingEditedArguments, null, 2) : requestArgs,+ [pendingEditedArguments, requestArgs],+ );const argCount = typeof parsedArgs === 'object' ? Object.keys(parsedArgs).length : 0;const isActivateToolsIntervention =identifier === LobeActivatorIdentifier && apiName === ActivatorApiName.activateTools;@@ -130,21 +146,26 @@ const FallbackIntervention = memo<FallbackInterventionProps>(const newArgsString = JSON.stringify(editedObject, null, 2);if (newArgsString !== requestArgs) {- await updatePluginArguments(toolCallId, editedObject, true);+ if (usesDurableServerClaim) {+ pendingEditedArgumentsRef.current = editedObject;+ setPendingEditedArguments(editedObject);+ } else {+ await updatePluginArguments(toolCallId, editedObject, true);+ }}setIsEditing(false);} catch (error) {console.error('Error stringifying arguments:', error);}},- [requestArgs, toolCallId, updatePluginArguments],+ [requestArgs, toolCallId, updatePluginArguments, usesDurableServerClaim],);if (isEditing)return (- <Suspense fallback={<Arguments arguments={requestArgs} />}>+ <Suspense fallback={<Arguments arguments={renderedArgs} />}><KeyValueEditor- initialValue={safeParseJSON(requestArgs || '')}+ initialValue={parsedArgs}onCancel={handleCancel}onFinish={handleFinish}/>@@ -160,6 +181,7 @@ const FallbackIntervention = memo<FallbackInterventionProps>(identifier={identifier}messageId={id}toolCallId={toolCallId}+ onBeforeApprove={() => pendingEditedArgumentsRef.current}/></Flexbox>);@@ -212,7 +234,7 @@ const FallbackIntervention = memo<FallbackInterventionProps>(/>)}</Flexbox>- {showArgs && <Arguments arguments={requestArgs} />}+ {showArgs && <Arguments arguments={renderedArgs} />}</>)}diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.tsindex b21645b7b12..fc82a6a30cf 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.ts+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.ts@@ -16,6 +16,7 @@ import { installMarketplaceAgents } from '@/services/installMarketplaceAgents';import { topicService } from '@/services/topic';const QODER_IDENTIFIER = 'qoder';+const CURSOR_IDENTIFIER = 'cursor';interface SubmitToolInteractionOptions {createUserMessage?: boolean;@@ -40,7 +41,7 @@ type CustomInteractionSubmitHandler = (context?: CustomInteractionContext,) => Promise<CustomInteractionSubmitResult | undefined>;-const isAgentMarketplaceCall = (identifier: string, apiName?: string) =>+export const isAgentMarketplaceCall = (identifier: string, apiName?: string) =>identifier === WebOnboardingIdentifier && apiName === WebOnboardingApiName.showAgentMarketplace;const isLobeAgentAskUserQuestion = (identifier: string, apiName?: string) =>@@ -165,6 +166,7 @@ const findCustomInteractionSubmitHandler = (identifier: string, apiName?: string*/const HETERO_CUSTOM_INTERACTION_IDENTIFIERS = new Set<string>([ClaudeCodeIdentifier,+ CURSOR_IDENTIFIER,QODER_IDENTIFIER,]);diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsxindex abc987b5905..80958ae20ed 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsx@@ -1,17 +1,19 @@import { getBuiltinIntervention } from '@lobechat/builtin-tools/interventions';import { safeParseJSON } from '@lobechat/utils';import { Flexbox } from '@lobehub/ui';-import { memo, Suspense, useCallback, useMemo, useState } from 'react';+import { memo, Suspense, useCallback, useMemo, useRef, useState } from 'react';import { createPortal } from 'react-dom';import { useSingleton } from '@/hooks/useSingleton';import { useUserStore } from '@/store/user';import { toolInterventionSelectors } from '@/store/user/selectors';+import { useConversationResourceAccess } from '../../../../../hooks/useConversationResourceAccess';import { dataSelectors, useConversationStore } from '../../../../../store';import Arguments from '../Arguments';import ApprovalActions from './ApprovalActions';import {+ isAgentMarketplaceCall,isCustomInteractionIdentifier,isHeteroInteractionIdentifier,prepareCustomInteractionSubmit,@@ -36,8 +38,17 @@ interface InterventionProps {const Intervention = memo<InterventionProps>(({ requestArgs, id, identifier, apiName, toolCallId, assistantGroupId, actionsPortalTarget }) => {const approvalMode = useUserStore(toolInterventionSelectors.approvalMode);+ const { canUseResource } = useConversationResourceAccess();const [isEditing, setIsEditing] = useState(false);const updatePluginArguments = useConversationStore((s) => s.updatePluginArguments);+ const message = useConversationStore((s) => dataSelectors.getDbMessageById(id)(s));+ const usesDurableServerClaim = Boolean(+ message?.pluginIntervention?.operationId && message.pluginIntervention.batchId,+ );+ const [pendingEditedArguments, setPendingEditedArguments] = useState<+ Record<string, unknown> | undefined+ >();+ const pendingEditedArgumentsRef = useRef<Record<string, unknown> | undefined>(undefined);const beforeApproveCallbacks = useSingleton(() => new Map<string, () => void | Promise<void>>(),@@ -56,7 +67,8 @@ const Intervention = memo<InterventionProps>(const handleBeforeApprove = useCallback(async () => {const callbacks = Array.from(beforeApproveCallbacks.values());await Promise.all(callbacks.map((cb) => cb()));- }, [beforeApproveCallbacks]);+ return usesDurableServerClaim ? pendingEditedArgumentsRef.current : undefined;+ }, [beforeApproveCallbacks, usesDurableServerClaim]);const handleCancel = useCallback(() => {setIsEditing(false);@@ -70,30 +82,45 @@ const Intervention = memo<InterventionProps>(const newArgsString = JSON.stringify(editedObject, null, 2);if (newArgsString !== requestArgs) {- await updatePluginArguments(toolCallId, editedObject, true);+ if (usesDurableServerClaim) {+ pendingEditedArgumentsRef.current = editedObject;+ setPendingEditedArguments(editedObject);+ } else {+ await updatePluginArguments(toolCallId, editedObject, true);+ }}setIsEditing(false);} catch (error) {console.error('Error stringifying arguments:', error);}},- [requestArgs, toolCallId, updatePluginArguments],+ [requestArgs, toolCallId, updatePluginArguments, usesDurableServerClaim],);// Callback for builtin intervention components to update argumentsconst handleArgsChange = useCallback(async (newArgs: unknown) => {- if (!toolCallId) return;+ if (!toolCallId || !canUseResource) return;+ if (usesDurableServerClaim && newArgs && typeof newArgs === 'object') {+ const editedArguments = newArgs as Record<string, unknown>;+ pendingEditedArgumentsRef.current = editedArguments;+ setPendingEditedArguments(editedArguments);+ return;+ }await updatePluginArguments(toolCallId, newArgs, true);},- [toolCallId, updatePluginArguments],+ [canUseResource, toolCallId, updatePluginArguments, usesDurableServerClaim],);- const parsedArgs = useMemo(() => safeParseJSON(requestArgs || '') ?? {}, [requestArgs]);+ const parsedArgs = useMemo(+ () => pendingEditedArguments ?? safeParseJSON(requestArgs || '') ?? {},+ [pendingEditedArguments, requestArgs],+ );const isCustomInteraction = isCustomInteractionIdentifier(identifier, apiName);- const topicId = useConversationStore((s) => dataSelectors.getDbMessageById(id)(s)?.topicId);+ const topicId = message?.topicId;+ const interventionResolving = message?.pluginIntervention?.resolving === true;const submitToolInteraction = useConversationStore((s) => s.submitToolInteraction);const skipToolInteraction = useConversationStore((s) => s.skipToolInteraction);const cancelToolInteraction = useConversationStore((s) => s.cancelToolInteraction);@@ -112,12 +139,37 @@ const Intervention = memo<InterventionProps>(| { type: 'skip'; payload?: Record<string, unknown>; reason?: string }| { type: 'cancel'; payload?: Record<string, unknown> },) => {+ if (!canUseResource || interventionResolving) return;if (isHeteroInteractionIdentifier(identifier)) {await submitHeteroIntervention(id, action.type, action.payload);return;}switch (action.type) {case 'submit': {+ if (usesDurableServerClaim && isAgentMarketplaceCall(identifier, apiName)) {+ const selectedTemplateIds = action.payload.selectedTemplateIds;+ if (+ Array.isArray(selectedTemplateIds) &&+ selectedTemplateIds.length > 0 &&+ selectedTemplateIds.every((templateId) => typeof templateId === 'string')+ ) {+ await submitToolInteraction(id, action.payload, {+ agentInterventionAction: {+ result: { kind: 'agent_marketplace', selectedTemplateIds },+ type: 'submit_custom',+ },+ prepareLegacyFallback: async () => {+ const prepared = await prepareCustomInteractionSubmit(+ identifier,+ action.payload,+ { apiName, requestArgs: parsedArgs, topicId },+ );+ return { response: prepared.payload, ...prepared.options };+ },+ });+ break;+ }+ }const { payload, options } = await prepareCustomInteractionSubmit(identifier,action.payload,@@ -131,41 +183,51 @@ const Intervention = memo<InterventionProps>(break;}case 'skip': {- await recordCustomInteractionResolution(- identifier,- 'skipped',- action.payload,- {- apiName,- requestArgs: parsedArgs,- topicId,- },+ const recordSkipped = () =>+ recordCustomInteractionResolution(+ identifier,+ 'skipped',+ action.payload,+ { apiName, requestArgs: parsedArgs, topicId },+ action.reason,+ );+ if (!usesDurableServerClaim) await recordSkipped();+ await skipToolInteraction(+ id,action.reason,+ usesDurableServerClaim ? { onLegacyFallback: recordSkipped } : undefined,);- await skipToolInteraction(id, action.reason);break;}case 'cancel': {- await recordCustomInteractionResolution(identifier, 'cancelled', action.payload, {- apiName,- requestArgs: parsedArgs,- topicId,- });- await cancelToolInteraction(id);+ const recordCancelled = () =>+ recordCustomInteractionResolution(identifier, 'cancelled', action.payload, {+ apiName,+ requestArgs: parsedArgs,+ topicId,+ });+ if (!usesDurableServerClaim) await recordCancelled();+ await cancelToolInteraction(+ id,+ usesDurableServerClaim ? { onLegacyFallback: recordCancelled } : undefined,+ );break;}}},[apiName,+ canUseResource,cancelToolInteraction,id,identifier,+ interventionResolving,parsedArgs,skipToolInteraction,submitHeteroIntervention,submitToolInteraction,topicId,+ usesDurableServerClaim,],);@@ -190,6 +252,7 @@ const Intervention = memo<InterventionProps>(actionsPortalTarget={actionsPortalTarget}apiName={apiName}args={parsedArgs}+ disabled={interventionResolving || !canUseResource}identifier={identifier}interactionMode="custom"messageId={id}diff --git a/src/features/Conversation/store/slices/data/pendingInterventions.test.ts b/src/features/Conversation/store/slices/data/pendingInterventions.test.tsindex cdb3c7b3280..7918afc1f9b 100644--- a/src/features/Conversation/store/slices/data/pendingInterventions.test.ts+++ b/src/features/Conversation/store/slices/data/pendingInterventions.test.ts@@ -1,9 +1,18 @@-import type { UIChatMessage } from '@lobechat/types';+import { classifyToolInterventionPresentation, type UIChatMessage } from '@lobechat/types';import { describe, expect, it } from 'vitest';-import { getInterventionBatch, getPendingInterventions } from './pendingInterventions';+import {+ canApproveInterventionBatch,+ getInterventionBatch,+ getPendingInterventions,+} from './pendingInterventions';-const toolMessage = (id: string, toolCallId: string, parentId?: string): UIChatMessage =>+const toolMessage = (+ id: string,+ toolCallId: string,+ parentId?: string,+ identity?: { batchId?: string; operationId?: string },+): UIChatMessage =>({id,parentId,@@ -14,7 +23,7 @@ const toolMessage = (id: string, toolCallId: string, parentId?: string): UIChatMidentifier: 'lobe-agent',type: 'builtin',},- pluginIntervention: { status: 'pending' },+ pluginIntervention: { ...identity, status: 'pending' },role: 'tool',tool_call_id: toolCallId,}) as any;@@ -91,7 +100,125 @@ describe('getInterventionBatch', () => {expect(getInterventionBatch(pending, active).map((b) => b.toolCallId)).toEqual(['call-1']);});+ it('separates two durable batches that share the same assistant parent', () => {+ const pending = getPendingInterventions([+ toolMessage('msg-a1', 'call-a1', 'assistant-1', {+ batchId: 'batch-a',+ operationId: 'operation-a',+ }),+ toolMessage('msg-a2', 'call-a2', 'assistant-1', {+ batchId: 'batch-a',+ operationId: 'operation-a',+ }),+ toolMessage('msg-b1', 'call-b1', 'assistant-1', {+ batchId: 'batch-b',+ operationId: 'operation-b',+ }),+ ]);++ expect(getInterventionBatch(pending, pending[0]).map((item) => item.toolCallId)).toEqual([+ 'call-a1',+ 'call-a2',+ ]);+ });++ it('never mixes a legacy card with a durable sibling under the same parent', () => {+ const pending = getPendingInterventions([+ toolMessage('msg-legacy', 'call-legacy', 'assistant-1'),+ toolMessage('msg-durable', 'call-durable', 'assistant-1', {+ batchId: 'batch-a',+ operationId: 'operation-a',+ }),+ ]);++ expect(getInterventionBatch(pending, pending[0]).map((item) => item.toolCallId)).toEqual([+ 'call-legacy',+ ]);+ });+it('returns nothing when there is no active card', () => {expect(getInterventionBatch([], undefined)).toEqual([]);});});++describe('canApproveInterventionBatch', () => {+ const pending = (identifier: string, apiName: string, index: number) =>+ ({+ apiName,+ assistantGroupId: 'assistant-1',+ identifier,+ intervention: { status: 'pending' },+ requestArgs: '{}',+ toolCallId: `call-${index}`,+ toolMessageId: `message-${index}`,+ }) as any;++ it('allows a multi-item batch only when every member is binary', () => {+ expect(+ canApproveInterventionBatch([+ pending('lobe-agent', 'createPlan', 1),+ pending('filesystem', 'writeFile', 2),+ ]),+ ).toBe(true);+ });++ it.each([+ [+ 'question',+ [+ pending('lobe-user-interaction', 'askUserQuestion', 1),+ pending('lobe-user-interaction', 'askUserQuestion', 2),+ ],+ ],+ [+ 'marketplace',+ [+ pending('lobe-web-onboarding', 'showAgentMarketplace', 1),+ pending('lobe-web-onboarding', 'showAgentMarketplace', 2),+ ],+ ],+ ['heterogeneous', [pending('claude-code', 'permission', 1), pending('qoder', 'plan', 2)]],+ [+ 'cursor mixed provider form',+ [pending('filesystem', 'writeFile', 1), pending('cursor', 'requestPermission', 2)],+ ],+ [+ 'mixed',+ [+ pending('filesystem', 'writeFile', 1),+ pending('lobe-user-interaction', 'askUserQuestion', 2),+ ],+ ],+ ])('rejects a %s batch', (_name, members) => {+ expect(canApproveInterventionBatch(members as any)).toBe(false);+ });++ it('does not render a bulk action for a single binary card', () => {+ expect(canApproveInterventionBatch([pending('filesystem', 'writeFile', 1)])).toBe(false);+ });++ it('rejects bulk approval when durable identity is partial or mixed', () => {+ const first = pending('filesystem', 'writeFile', 1);+ const second = pending('filesystem', 'writeFile', 2);+ first.operationId = 'operation-a';+ first.batchId = 'batch-a';+ second.operationId = 'operation-b';+ second.batchId = 'batch-b';+ expect(canApproveInterventionBatch([first, second])).toBe(false);++ second.operationId = undefined;+ second.batchId = undefined;+ expect(canApproveInterventionBatch([first, second])).toBe(false);+ });++ it('classifies Cursor AskUser as a question and other ACP approval surfaces as custom forms', () => {+ expect(classifyToolInterventionPresentation('cursor', 'askUserQuestion')).toEqual({+ interactionKind: 'question',+ surface: 'form',+ });+ expect(classifyToolInterventionPresentation('cursor', 'requestPermission')).toEqual({+ interactionKind: 'custom',+ surface: 'form',+ });+ });+});diff --git a/src/features/Conversation/store/slices/data/pendingInterventions.ts b/src/features/Conversation/store/slices/data/pendingInterventions.tsindex 408cf19cf15..b84199179b0 100644--- a/src/features/Conversation/store/slices/data/pendingInterventions.ts+++ b/src/features/Conversation/store/slices/data/pendingInterventions.ts@@ -1,4 +1,9 @@-import type { ChatToolPayloadWithResult, ToolIntervention, UIChatMessage } from '@lobechat/types';+import {+ type ChatToolPayloadWithResult,+ classifyToolInterventionPresentation,+ type ToolIntervention,+ type UIChatMessage,+} from '@lobechat/types';export interface PendingIntervention {apiName: string;@@ -13,8 +18,10 @@ export interface PendingIntervention {* its own group rather than folding it in with the others.*/assistantGroupId?: string;+ batchId?: string;identifier: string;intervention: ToolIntervention & { status: 'pending' };+ operationId?: string;requestArgs: string;toolCallId: string;toolMessageId: string;@@ -37,8 +44,10 @@ export const getPendingInterventions = (apiName: msg.plugin.apiName,// A standalone tool row parents directly to its calling assistant.assistantGroupId: msg.parentId,+ batchId: msg.pluginIntervention.batchId,identifier: msg.plugin.identifier,intervention: msg.pluginIntervention as ToolIntervention & { status: 'pending' },+ operationId: msg.pluginIntervention.operationId,requestArgs: msg.plugin.arguments || '',toolCallId: msg.tool_call_id || msg.id,toolMessageId: msg.id,@@ -76,9 +85,51 @@ export const getInterventionBatch = (active: PendingIntervention | undefined,): PendingIntervention[] => {if (!active) return [];++ if (active.operationId && active.batchId) {+ return interventions.filter(+ (item) => item.operationId === active.operationId && item.batchId === active.batchId,+ );+ }++ // A partially stamped row is neither a trustworthy durable identity nor a+ // legacy row. Keep it isolated so a rollout mismatch cannot broaden a bulk+ // action to cards the server will reject as a different sealed batch.+ if (active.operationId || active.batchId) return [active];+const owner = active.assistantGroupId;if (!owner) return [active];- return interventions.filter((i) => i.assistantGroupId === owner);+ return interventions.filter(+ (item) => !item.operationId && !item.batchId && item.assistantGroupId === owner,+ );+};++/**+ * Approve-all is meaningful only for a fully binary same-turn batch. AskUser,+ * marketplace, provider forms, and mixed batches each carry action-specific+ * payloads and must be resolved card by card.+ */+export const canApproveInterventionBatch = (batch: PendingIntervention[]): boolean => {+ if (batch.length <= 1) return false;++ const hasDurableMember = batch.some(({ batchId, operationId }) => batchId || operationId);+ if (+ hasDurableMember &&+ !batch.every(+ ({ batchId, operationId }) =>+ Boolean(batchId) &&+ Boolean(operationId) &&+ batchId === batch[0].batchId &&+ operationId === batch[0].operationId,+ )+ ) {+ return false;+ }++ return batch.every(+ ({ apiName, identifier }) =>+ classifyToolInterventionPresentation(identifier, apiName).surface === 'binary',+ );};const collectPendingTools = (@@ -95,8 +146,10 @@ const collectPendingTools = (pending.push({apiName: tool.apiName,assistantGroupId,+ batchId: tool.intervention.batchId,identifier: tool.identifier,intervention: tool.intervention as ToolIntervention & { status: 'pending' },+ operationId: tool.intervention.operationId,requestArgs: tool.arguments || '',toolCallId: tool.id,toolMessageId: tool.result_msg_id,diff --git a/src/features/Conversation/store/slices/tool/action.ts b/src/features/Conversation/store/slices/tool/action.tsindex 6745a3d46f8..f0c1f407617 100644--- a/src/features/Conversation/store/slices/tool/action.ts+++ b/src/features/Conversation/store/slices/tool/action.ts@@ -1,3 +1,4 @@+import type { AgentInterventionSourceAction } from '@/services/aiAgent';import { useChatStore } from '@/store/chat';import { type StoreSetter } from '@/store/types';@@ -24,7 +25,11 @@ export class ToolActionImpl {this.#get = get;}- approveToolCall = async (toolMessageId: string, assistantGroupId: string): Promise<void> => {+ approveToolCall = async (+ toolMessageId: string,+ assistantGroupId: string,+ options?: { editedArguments?: Record<string, unknown>; rememberToolKey?: string },+ ): Promise<void> => {const { hooks, context, waitForPendingArgsUpdate } = this.#get();// Wait for any pending args update to complete before approval@@ -38,7 +43,21 @@ export class ToolActionImpl {// Delegate to global ChatStore with context for correct conversation scopeconst chatStore = useChatStore.getState();- await chatStore.approveToolCalling(toolMessageId, assistantGroupId, context);+ const toolCallId = dataSelectors.getDbMessageById(toolMessageId)(this.#get())?.tool_call_id;+ const editedArguments = options?.editedArguments;+ const chatOptions =+ editedArguments && toolCallId+ ? {+ ...options,+ onLegacyEditFallback: () =>+ this.#get().updatePluginArguments(toolCallId, editedArguments, true),+ }+ : options;+ if (chatOptions) {+ await chatStore.approveToolCalling(toolMessageId, assistantGroupId, context, chatOptions);+ } else {+ await chatStore.approveToolCalling(toolMessageId, assistantGroupId, context);+ }// ===== Hook: onToolCallComplete =====if (hooks.onToolCallComplete) {@@ -112,10 +131,13 @@ export class ToolActionImpl {}};- cancelToolInteraction = async (toolMessageId: string): Promise<void> => {+ cancelToolInteraction = async (+ toolMessageId: string,+ options?: { onLegacyFallback?: () => Promise<void> },+ ): Promise<void> => {const { context } = this.#get();const chatStore = useChatStore.getState();- await chatStore.cancelToolInteraction(toolMessageId, context);+ await chatStore.cancelToolInteraction(toolMessageId, context, options);};rejectAndContinueToolCall = async (toolMessageId: string, reason?: string): Promise<void> => {@@ -168,17 +190,31 @@ export class ToolActionImpl {await chatStore.rejectToolCalling(toolMessageId, reason, context);};- skipToolInteraction = async (toolMessageId: string, reason?: string): Promise<void> => {+ skipToolInteraction = async (+ toolMessageId: string,+ reason?: string,+ options?: { onLegacyFallback?: () => Promise<void> },+ ): Promise<void> => {const { context } = this.#get();const chatStore = useChatStore.getState();- await chatStore.skipToolInteraction(toolMessageId, reason, context);+ await chatStore.skipToolInteraction(toolMessageId, reason, context, options);};submitToolInteraction = async (toolMessageId: string,response: Record<string, unknown>,options?: {+ agentInterventionAction?: Extract<+ AgentInterventionSourceAction,+ { type: 'submit_answers' | 'submit_custom' }+ >;createUserMessage?: boolean;+ prepareLegacyFallback?: () => Promise<{+ createUserMessage?: boolean;+ pluginState?: Record<string, unknown>;+ response: Record<string, unknown>;+ toolResultContent?: string;+ }>;pluginState?: Record<string, unknown>;toolResultContent?: string;},diff --git a/src/libs/next/config/appleAppSiteAssociation.test.ts b/src/libs/next/config/appleAppSiteAssociation.test.tsnew file mode 100644index 00000000000..b274a34942b--- /dev/null+++ b/src/libs/next/config/appleAppSiteAssociation.test.ts@@ -0,0 +1,29 @@+import { readFileSync } from 'node:fs';+import path from 'node:path';++import { describe, expect, it } from 'vitest';++const associationPath = path.resolve(+ import.meta.dirname,+ '../../../../public/.well-known/apple-app-site-association',+);++describe('apple-app-site-association', () => {+ it('opens only the agent approval route as a universal link and preserves web credentials', () => {+ const association = JSON.parse(readFileSync(associationPath, 'utf8'));++ expect(association).toEqual({+ applinks: {+ details: [+ {+ appIDs: ['4684H589ZU.com.lobehub.app'],+ components: [{ '/': '/agent-approval' }],+ },+ ],+ },+ webcredentials: {+ apps: ['4684H589ZU.com.lobehub.app'],+ },+ });+ });+});diff --git a/src/services/aiAgent.intervention.test.ts b/src/services/aiAgent.intervention.test.tsnew file mode 100644index 00000000000..b5a8e6e1a27--- /dev/null+++ b/src/services/aiAgent.intervention.test.ts@@ -0,0 +1,82 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { aiAgentService } from './aiAgent';++const mocks = vi.hoisted(() => ({+ resolveAgentInterventionBySource: vi.fn(),+}));++vi.mock('@/libs/trpc/client', () => ({+ lambdaClient: {+ aiAgent: {+ resolveAgentInterventionBySource: {+ mutate: mocks.resolveAgentInterventionBySource,+ },+ },+ },+}));++describe('aiAgentService.resolveAgentInterventionBySource', () => {+ const params = {+ action: { scope: 'once', type: 'approve_tool' } as const,+ batchId: 'batch-1',+ operationId: 'operation-1',+ resolutionRequestId: '018fbd8e-7baf-7c6d-8000-000000000031',+ targets: [{ toolCallId: 'call-1', toolMessageId: 'message-1' }],+ };++ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('preserves a claimed result and its precreated execution', async () => {+ const execution = {+ autoStarted: true,+ messageId: 'assistant-1',+ operationId: 'operation-resumed',+ success: true,+ };+ mocks.resolveAgentInterventionBySource.mockResolvedValueOnce({+ contractVersion: 2,+ execution,+ state: 'claimed',+ status: 'approved',+ success: true,+ });++ await expect(aiAgentService.resolveAgentInterventionBySource(params)).resolves.toEqual({+ execution,+ handled: true,+ state: 'claimed',+ });+ });++ it('preserves an already-resolved result without inventing an execution', async () => {+ mocks.resolveAgentInterventionBySource.mockResolvedValueOnce({+ contractVersion: 2,+ state: 'already_resolved',+ status: 'approved',+ success: true,+ });++ await expect(aiAgentService.resolveAgentInterventionBySource(params)).resolves.toEqual({+ execution: undefined,+ handled: true,+ state: 'already_resolved',+ });+ });++ it('returns only the compatibility fallback when the source is unavailable', async () => {+ mocks.resolveAgentInterventionBySource.mockResolvedValueOnce({+ contractVersion: 2,+ status: 'unavailable',+ success: false,+ });++ const result = await aiAgentService.resolveAgentInterventionBySource(params);++ expect(result).toEqual({ handled: false });+ expect(result).not.toHaveProperty('state');+ expect(result).not.toHaveProperty('execution');+ });+});diff --git a/src/services/aiAgent.ts b/src/services/aiAgent.tsindex 3f01c2e9818..fb72291a017 100644--- a/src/services/aiAgent.ts+++ b/src/services/aiAgent.ts@@ -45,14 +45,57 @@ export interface ResumeApprovalParam {export interface ResumeToolResultParam {/** The human-provided tool result (the answer text). */content: string;+ /** Distinguishes a submitted form from an explicit skip. */+ outcome?: 'skipped' | 'submitted';/** ID of the pending `role='tool'` message this result targets. */parentMessageId: string;/** Optional plugin state to persist on the tool message. */pluginState?: Record<string, unknown>;+ /** Optional user-supplied reason for a skipped interaction. */+ rejectionReason?: string;/** tool_call_id of the pending tool call being answered. */toolCallId: string;}+export type AgentInterventionSourceAction =+ | { optionId: string; type: 'select_provider_option' }+ | {+ edits?: Record<string, Record<string, unknown>>;+ scope: 'once' | 'remember';+ type: 'approve_tool';+ }+ | { reason?: string; type: 'reject_continue' }+ | { scope: 'operation'; type: 'stop' }+ | { result: Record<string, string | string[]>; type: 'submit_answers' }+ | {+ result: { kind: 'agent_marketplace'; selectedTemplateIds: string[] };+ type: 'submit_custom';+ }+ | { type: 'skip_interaction' }+ | { type: 'cancel_interaction' };++export interface ResolveAgentInterventionBySourceParams {+ action: AgentInterventionSourceAction;+ batchId: string;+ operationId: string;+ resolutionRequestId: string;+ targets: Array<{ toolCallId: string; toolMessageId: string }>;+}++export type ResolveAgentInterventionBySourceResult =+ | { execution?: never; handled: false; state?: never }+ | {+ execution?: ExecAgentResult;+ handled: true;+ state: 'already_resolved' | 'claimed';+ };++export interface GetAgentInterventionReviewBySourceParams {+ batchId: string;+ operationId: string;+ targets: Array<{ toolCallId: string; toolMessageId: string }>;+}+export interface ExecAgentTaskParams {agentId?: string;appContext?: ExecAgentAppContext;@@ -246,10 +289,39 @@ class AiAgentService {* Not `interruptTask` — that one assumes a live loop will persist the* outcome, which a parked run does not have.*/- async stopPendingApproval(params: { toolMessageIds: string[]; topicId: string }) {+ async stopPendingApproval(params: {+ batchId: string;+ operationId: string;+ toolMessageIds: string[];+ topicId: string;+ }) {return await lambdaClient.aiAgent.stopPendingApproval.mutate(params);}+ /**+ * Try the Cloud durable first-winner path for an active Web card. A false+ * result means this deployment has no generic intervention store and the+ * caller should use the legacy OSS Gateway resume path.+ */+ async resolveAgentInterventionBySource(+ params: ResolveAgentInterventionBySourceParams,+ ): Promise<ResolveAgentInterventionBySourceResult> {+ const result = await lambdaClient.aiAgent.resolveAgentInterventionBySource.mutate(params);++ if (!result.success) return { handled: false };++ return {+ execution: 'execution' in result ? result.execution : undefined,+ handled: true,+ state: result.state,+ };+ }++ /** Fetch the authoritative v2 snapshot and view/resolve authorization for an active card. */+ async getAgentInterventionReviewBySource(params: GetAgentInterventionReviewBySourceParams) {+ return await lambdaClient.aiAgent.getAgentInterventionReviewBySource.mutate(params);+ }+/*** Create Thread for client-side task execution (desktop only, single agent mode)*diff --git a/src/store/chat/agents/__tests__/clientRuntimeExecutors/fixtures/mockInstructions.ts b/src/store/chat/agents/__tests__/clientRuntimeExecutors/fixtures/mockInstructions.tsindex a83adc15d4f..e530e907aba 100644--- a/src/store/chat/agents/__tests__/clientRuntimeExecutors/fixtures/mockInstructions.ts+++ b/src/store/chat/agents/__tests__/clientRuntimeExecutors/fixtures/mockInstructions.ts@@ -64,6 +64,7 @@ export const createCallToolInstruction = (export const createRequestHumanApproveInstruction = (pendingTools: ChatToolPayload[] = [],options: {+ parentMessageId?: string;reason?: string;skipCreateToolMessage?: boolean;} = {},@@ -81,6 +82,7 @@ export const createRequestHumanApproveInstruction = (];return {+ ...(options.parentMessageId && { parentMessageId: options.parentMessageId }),pendingToolsCalling,reason: options.reason,skipCreateToolMessage: options.skipCreateToolMessage || false,diff --git a/src/store/chat/agents/__tests__/clientRuntimeExecutors/request-human-approve.test.ts b/src/store/chat/agents/__tests__/clientRuntimeExecutors/request-human-approve.test.tsindex dafb1cadb99..50e1c7bb357 100644--- a/src/store/chat/agents/__tests__/clientRuntimeExecutors/request-human-approve.test.ts+++ b/src/store/chat/agents/__tests__/clientRuntimeExecutors/request-human-approve.test.ts@@ -4,6 +4,7 @@ import { describe, expect, it, vi } from 'vitest';import {createAssistantMessage,createMockStore,+ createPendingToolMessage,createRequestHumanApproveInstruction,} from './fixtures';import { createInitialState, createTestContext, executeWithMockContext } from './helpers';@@ -46,7 +47,7 @@ describe('request_human_approve executor', () => {role: 'tool',content: '',plugin: toolCalls[0],- pluginIntervention: { status: 'pending' },+ pluginIntervention: expect.objectContaining({ status: 'pending' }),tool_call_id: 'tool_1',parentId: 'msg_assistant',groupId: assistantMessage.groupId,@@ -250,8 +251,7 @@ describe('request_human_approve executor', () => {it('should skip message creation when skipCreateToolMessage is true', async () => {// Givenconst mockStore = createMockStore();- const assistantMessage = createAssistantMessage();- mockStore.dbMessagesMap['test-session_test-topic'] = [assistantMessage];+ const assistantMessage = createAssistantMessage({ id: 'msg_assistant' });const context = createTestContext();const toolCalls: ChatToolPayload[] = [@@ -263,8 +263,23 @@ describe('request_human_approve executor', () => {type: 'default',},];+ const durableToolMessage = createPendingToolMessage({+ id: 'msg_tool_1',+ parentId: assistantMessage.id,+ plugin: toolCalls[0],+ pluginIntervention: {+ batchId: 'op_previous:1:msg_assistant',+ itemIndex: 0,+ operationId: 'op_previous',+ status: 'pending',+ stepIndex: 1,+ },+ tool_call_id: 'tool_1',+ });+ mockStore.dbMessagesMap['test-session_test-topic'] = [assistantMessage, durableToolMessage];const instruction = createRequestHumanApproveInstruction(toolCalls, {+ parentMessageId: assistantMessage.id,skipCreateToolMessage: true,});const state = createInitialState();@@ -340,7 +355,7 @@ describe('request_human_approve executor', () => {id: toolCall.id,}),tool_call_id: toolCall.id,- pluginIntervention: { status: 'pending' },+ pluginIntervention: expect.objectContaining({ status: 'pending' }),}),expect.objectContaining({operationId: expect.any(String),diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.tsindex 7264c51ecdf..0be8e93514c 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { lambdaClient } from '@/libs/trpc/client';import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgent';+import { messageService } from '@/services/message';import { useChatStore } from '../../../../store';import { messageMapKey } from '../../../../utils/messageMapKey';@@ -20,6 +21,13 @@ vi.mock('@/libs/trpc/client', () => ({lambdaClient: {aiAgent: {processHumanIntervention: { mutate: vi.fn().mockResolvedValue({ success: true }) },+ resolveAgentInterventionBySource: {+ mutate: vi.fn().mockResolvedValue({+ contractVersion: 2,+ status: 'unavailable',+ success: false,+ }),+ },submitHeteroIntervention: { mutate: vi.fn().mockResolvedValue({ success: true }) },},},@@ -51,6 +59,13 @@ vi.mock('@/utils/localStorage', () => {beforeEach(() => {resetTestEnvironment();+ vi.mocked(lambdaClient.aiAgent.resolveAgentInterventionBySource.mutate)+ .mockReset()+ .mockResolvedValue({+ contractVersion: 2,+ status: 'unavailable',+ success: false,+ });useChatStore.setState({updateTopicStatus: vi.fn().mockResolvedValue(undefined),});@@ -60,6 +75,18 @@ afterEach(() => {vi.restoreAllMocks();});+const captureActError = async (action: () => Promise<void>): Promise<unknown> => {+ let captured: unknown;+ await act(async () => {+ try {+ await action();+ } catch (error) {+ captured = error;+ }+ });+ return captured;+};+describe('ConversationControl actions', () => {describe('stopGenerateMessage', () => {it('should cancel running generateAI operations in current context', () => {@@ -839,6 +866,305 @@ describe('ConversationControl actions', () => {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';+ const topicId = 'server-topic';+ const chatKey = messageMapKey({ agentId, topicId });+ const toolMessage = createMockMessage({+ id: 'tool-msg-durable',+ plugin: {+ apiName: 'editFile',+ arguments: '{"path":"/tmp/a"}',+ identifier: 'lobe-local-system',+ type: 'default',+ },+ pluginIntervention: {+ batchId: 'batch-durable',+ operationId: 'operation-durable',+ status: 'pending',+ },+ role: 'tool',+ tool_call_id: 'call-durable',+ } as any);+ const precreatedResult = {+ autoStarted: true,+ messageId: 'assistant-resumed',+ operationId: 'operation-resumed',+ success: true,+ } as any;++ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ activeTopicId: topicId,+ dbMessagesMap: { [chatKey]: [toolMessage] },+ messagesMap: { [chatKey]: [toolMessage] },+ });+ });+ vi.spyOn(result.current, 'isGatewayModeEnabled').mockReturnValue(true);+ const executeGatewayAgentSpy = vi+ .spyOn(result.current, 'executeGatewayAgent')+ .mockResolvedValue({} as any);+ vi.mocked(+ lambdaClient.aiAgent.resolveAgentInterventionBySource.mutate,+ ).mockResolvedValueOnce({+ contractVersion: 2,+ execution: precreatedResult,+ state: 'claimed',+ status: 'approved',+ success: true,+ });++ await act(async () => {+ await result.current.approveToolCalling('tool-msg-durable', '', undefined, {+ editedArguments: { path: '/tmp/b' },+ });+ });++ expect(lambdaClient.aiAgent.resolveAgentInterventionBySource.mutate).toHaveBeenCalledWith({+ action: {+ edits: { 'tool-msg-durable': { path: '/tmp/b' } },+ scope: 'once',+ type: 'approve_tool',+ },+ batchId: 'batch-durable',+ operationId: 'operation-durable',+ resolutionRequestId: expect.any(String),+ targets: [{ toolCallId: 'call-durable', toolMessageId: 'tool-msg-durable' }],+ });+ expect(result.current.dbMessagesMap[chatKey][0].plugin?.arguments).toBe(+ '{"path":"/tmp/a"}',+ );+ expect(executeGatewayAgentSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ parentMessageId: 'tool-msg-durable',+ precreatedResult,+ }),+ );+ expect(executeGatewayAgentSpy.mock.calls[0]?.[0]).not.toHaveProperty('resumeApproval');+ });++ it('refreshes a durable approval that another surface already resolved', async () => {+ const { result } = renderHook(() => useChatStore());+ const agentId = 'server-agent';+ const topicId = 'server-topic';+ const chatKey = messageMapKey({ agentId, topicId });+ let pausedOperationId!: string;+ const toolMessage = createMockMessage({+ id: 'tool-msg-already-resolved-approval',+ plugin: {+ apiName: 'writeFile',+ arguments: '{}',+ identifier: 'fs',+ type: 'default',+ },+ pluginIntervention: {+ batchId: 'batch-already-resolved-approval',+ operationId: 'operation-already-resolved-approval',+ status: 'pending',+ },+ role: 'tool',+ tool_call_id: 'call-already-resolved-approval',+ } as any);++ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ activeTopicId: topicId,+ dbMessagesMap: { [chatKey]: [toolMessage] },+ messagesMap: { [chatKey]: [toolMessage] },+ });+ pausedOperationId = result.current.startOperation({+ context: { agentId, topicId, threadId: null },+ type: 'execServerAgentRuntime',+ }).operationId;+ });+ vi.spyOn(result.current, 'isGatewayModeEnabled').mockReturnValue(true);+ const executeGatewayAgentSpy = vi+ .spyOn(result.current, 'executeGatewayAgent')+ .mockResolvedValue({} as any);+ const completeOperationSpy = vi.spyOn(result.current, 'completeOperation');+ const refreshSpy = vi.spyOn(result.current, 'refreshMessages').mockResolvedValue(undefined);+ const updateTopicStatusSpy = vi.mocked(result.current.updateTopicStatus);+ updateTopicStatusSpy.mockClear();+ vi.mocked(+ lambdaClient.aiAgent.resolveAgentInterventionBySource.mutate,+ ).mockResolvedValueOnce({+ contractVersion: 2,+ state: 'already_resolved',+ status: 'resolved',+ success: true,+ });++ await act(async () => {+ await result.current.approveToolCalling('tool-msg-already-resolved-approval', '');+ });++ expect(refreshSpy).toHaveBeenCalledWith({ agentId, topicId });+ expect(executeGatewayAgentSpy).not.toHaveBeenCalled();+ expect(updateTopicStatusSpy).not.toHaveBeenCalledWith(+ expect.objectContaining({ status: 'active' }),+ );+ expect(completeOperationSpy).not.toHaveBeenCalled();+ expect(result.current.operations[pausedOperationId].status).toBe('running');+ expect(+ Object.values(result.current.operations).find(+ (operation) => operation.type === 'approveToolCalling',+ ),+ ).toMatchObject({+ metadata: { cancelReason: 'Intervention already resolved' },+ status: 'cancelled',+ });+ });++ it('propagates a generic approval failure, keeps the card pending, and reuses its UUID', async () => {+ const { result } = renderHook(() => useChatStore());+ const agentId = 'server-agent';+ const topicId = 'server-topic';+ const chatKey = messageMapKey({ agentId, topicId });+ const toolMessage = createMockMessage({+ id: 'tool-msg-claim-failure',+ plugin: { apiName: 'writeFile', arguments: '{}', identifier: 'fs', type: 'default' },+ pluginIntervention: {+ batchId: 'batch-claim-failure',+ operationId: 'operation-claim-failure',+ status: 'pending',+ },+ role: 'tool',+ tool_call_id: 'call-claim-failure',+ } as any);+ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ activeTopicId: topicId,+ dbMessagesMap: { [chatKey]: [toolMessage] },+ messagesMap: { [chatKey]: [toolMessage] },+ });+ });+ vi.spyOn(result.current, 'isGatewayModeEnabled').mockReturnValue(true);+ const mutation = vi.mocked(lambdaClient.aiAgent.resolveAgentInterventionBySource.mutate);+ mutation.mockRejectedValue(new Error('claim unavailable'));++ expect(+ await captureActError(() =>+ result.current.approveToolCalling('tool-msg-claim-failure', ''),+ ),+ ).toMatchObject({ message: 'claim unavailable' });+ expect(+ await captureActError(() =>+ result.current.approveToolCalling('tool-msg-claim-failure', ''),+ ),+ ).toMatchObject({ message: 'claim unavailable' });++ expect(result.current.dbMessagesMap[chatKey][0].pluginIntervention?.status).toBe('pending');+ expect(mutation.mock.calls[0]?.[0].resolutionRequestId).toBe(+ mutation.mock.calls[1]?.[0].resolutionRequestId,+ );+ });++ it('falls back to the legacy Gateway resume only when the durable source is absent', async () => {+ const { result } = renderHook(() => useChatStore());+ const agentId = 'server-agent';+ const topicId = 'server-topic';+ const chatKey = messageMapKey({ agentId, topicId });+ const toolMessage = createMockMessage({+ id: 'tool-msg-compat',+ plugin: { apiName: 'search', arguments: '{}', identifier: 'web-search', type: 'default' },+ pluginIntervention: {+ batchId: 'batch-compat',+ operationId: 'operation-compat',+ status: 'pending',+ },+ role: 'tool',+ tool_call_id: 'call-compat',+ } as any);++ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ activeTopicId: topicId,+ dbMessagesMap: { [chatKey]: [toolMessage] },+ messagesMap: { [chatKey]: [toolMessage] },+ });+ });+ vi.spyOn(result.current, 'isGatewayModeEnabled').mockReturnValue(true);+ const executeGatewayAgentSpy = vi+ .spyOn(result.current, 'executeGatewayAgent')+ .mockResolvedValue({} as any);++ await act(async () => {+ await result.current.approveToolCalling('tool-msg-compat', '');+ });++ expect(lambdaClient.aiAgent.resolveAgentInterventionBySource.mutate).toHaveBeenCalledOnce();+ expect(executeGatewayAgentSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ resumeApproval: {+ decision: 'approved',+ parentMessageId: 'tool-msg-compat',+ toolCallId: 'call-compat',+ },+ }),+ );+ });++ it('retains a source idempotency UUID across transport retry and clears it after success', async () => {+ const { result } = renderHook(() => useChatStore());+ const agentId = 'server-agent';+ const topicId = 'server-topic';+ const chatKey = messageMapKey({ agentId, topicId });+ const toolMessage = createMockMessage({+ id: 'tool-msg-retry',+ pluginIntervention: {+ batchId: 'batch-retry',+ operationId: 'operation-retry',+ status: 'pending',+ },+ role: 'tool',+ tool_call_id: 'call-retry',+ } as any);+ act(() => {+ useChatStore.setState({+ dbMessagesMap: { [chatKey]: [toolMessage] },+ messagesMap: { [chatKey]: [toolMessage] },+ });+ });+ const mutation = vi.mocked(lambdaClient.aiAgent.resolveAgentInterventionBySource.mutate);+ mutation+ .mockRejectedValueOnce(new Error('transport failed'))+ .mockResolvedValueOnce({+ contractVersion: 2,+ state: 'claimed',+ status: 'approved',+ success: true,+ })+ .mockResolvedValueOnce({+ contractVersion: 2,+ state: 'claimed',+ status: 'approved',+ success: true,+ });+ const params = {+ action: { scope: 'once', type: 'approve_tool' } as const,+ toolMessageIds: ['tool-msg-retry'],+ };++ await expect(result.current.tryResolveAgentInterventionBySource(params)).rejects.toThrow(+ 'transport failed',+ );+ await expect(result.current.tryResolveAgentInterventionBySource(params)).resolves.toEqual({+ execution: undefined,+ handled: true,+ state: 'claimed',+ });+ await result.current.tryResolveAgentInterventionBySource(params);++ const requestIds = mutation.mock.calls.map(([input]) => input.resolutionRequestId);+ expect(requestIds[0]).toBe(requestIds[1]);+ expect(requestIds[2]).not.toBe(requestIds[1]);+ });+it('should still take the Gateway branch when the server already ended the paused op (post-coordinator-fix state)', async () => {const { result } = renderHook(() => useChatStore());@@ -953,9 +1279,9 @@ describe('ConversationControl actions', () => {const updateTopicStatusMock = vi.mocked(result.current.updateTopicStatus);updateTopicStatusMock.mockClear();- await act(async () => {- await result.current.approveToolCalling('tool-msg-1', 'group-1');- });+ expect(+ await captureActError(() => result.current.approveToolCalling('tool-msg-1', 'group-1')),+ ).toMatchObject({ message: 'network error' });expect(executeGatewayAgentSpy).toHaveBeenCalled();@@ -1089,6 +1415,141 @@ describe('ConversationControl actions', () => {});});+ describe('durable terminal source lifecycle', () => {+ const agentId = 'server-agent';+ const topicId = 'server-topic';+ const chatKey = messageMapKey({ agentId, topicId });++ const seedDurableTerminalCard = (result: {+ current: ReturnType<typeof useChatStore.getState>;+ }) => {+ const toolMessage = createMockMessage({+ id: 'tool-msg-terminal-source',+ pluginIntervention: {+ batchId: 'batch-terminal-source',+ operationId: 'operation-terminal-source',+ status: 'pending',+ },+ role: 'tool',+ tool_call_id: 'call-terminal-source',+ } as any);+ let pausedOperationId!: string;++ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ activeTopicId: topicId,+ dbMessagesMap: { [chatKey]: [toolMessage] },+ messagesMap: { [chatKey]: [toolMessage] },+ });+ pausedOperationId = result.current.startOperation({+ context: { agentId, topicId, threadId: null },+ type: 'execServerAgentRuntime',+ }).operationId;+ });++ vi.spyOn(result.current, 'isGatewayModeEnabled').mockReturnValue(true);+ return pausedOperationId;+ };++ it('does not retire the paused operation when Stop loses the durable claim', async () => {+ const { result } = renderHook(() => useChatStore());+ const pausedOperationId = seedDurableTerminalCard(result);+ const completeOperationSpy = vi.spyOn(result.current, 'completeOperation');+ const executeGatewayAgentSpy = vi+ .spyOn(result.current, 'executeGatewayAgent')+ .mockResolvedValue({} as any);+ const refreshSpy = vi.spyOn(result.current, 'refreshMessages').mockResolvedValue(undefined);+ const updateTopicStatusSpy = vi.mocked(result.current.updateTopicStatus);+ updateTopicStatusSpy.mockClear();+ vi.mocked(lambdaClient.aiAgent.resolveAgentInterventionBySource.mutate).mockResolvedValueOnce(+ {+ contractVersion: 2,+ state: 'already_resolved',+ status: 'resolved',+ success: true,+ },+ );++ await act(async () => {+ await result.current.stopPendingApproval(['tool-msg-terminal-source']);+ });++ expect(refreshSpy).toHaveBeenCalledWith({ agentId, topicId });+ expect(completeOperationSpy).not.toHaveBeenCalled();+ expect(result.current.operations[pausedOperationId].status).toBe('running');+ expect(executeGatewayAgentSpy).not.toHaveBeenCalled();+ expect(updateTopicStatusSpy).not.toHaveBeenCalledWith(+ expect.objectContaining({ status: 'active' }),+ );+ });++ it('retires the paused operation only when Stop wins the durable claim', async () => {+ const { result } = renderHook(() => useChatStore());+ const pausedOperationId = seedDurableTerminalCard(result);+ const executeGatewayAgentSpy = vi+ .spyOn(result.current, 'executeGatewayAgent')+ .mockResolvedValue({} as any);+ const updateTopicStatusSpy = vi.mocked(result.current.updateTopicStatus);+ updateTopicStatusSpy.mockClear();+ 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']);+ });++ expect(result.current.operations[pausedOperationId].status).toBe('completed');+ expect(executeGatewayAgentSpy).not.toHaveBeenCalled();+ expect(updateTopicStatusSpy).not.toHaveBeenCalledWith(+ expect.objectContaining({ status: 'active' }),+ );+ });++ it('completes only the local action when custom cancel wins the durable claim', async () => {+ const { result } = renderHook(() => useChatStore());+ const pausedOperationId = seedDurableTerminalCard(result);+ const legacyFallback = vi.fn().mockResolvedValue(undefined);+ const executeGatewayAgentSpy = vi+ .spyOn(result.current, 'executeGatewayAgent')+ .mockResolvedValue({} as any);+ const updateTopicStatusSpy = vi.mocked(result.current.updateTopicStatus);+ updateTopicStatusSpy.mockClear();+ vi.mocked(lambdaClient.aiAgent.resolveAgentInterventionBySource.mutate).mockResolvedValueOnce(+ {+ contractVersion: 2,+ state: 'claimed',+ status: 'cancelled',+ success: true,+ },+ );++ await act(async () => {+ await result.current.cancelToolInteraction('tool-msg-terminal-source', undefined, {+ onLegacyFallback: legacyFallback,+ });+ });++ expect(legacyFallback).not.toHaveBeenCalled();+ expect(executeGatewayAgentSpy).not.toHaveBeenCalled();+ expect(updateTopicStatusSpy).not.toHaveBeenCalledWith(+ expect.objectContaining({ status: 'active' }),+ );+ expect(result.current.operations[pausedOperationId].status).toBe('running');+ expect(+ Object.values(result.current.operations).find(+ (operation) => operation.type === 'cancelToolInteraction',+ )?.status,+ ).toBe('completed');+ });+ });+describe('rejectToolCalling server-mode branch', () => {it('starts a new Gateway op with resumeApproval.decision=rejected_continue (unified)', async () => {const { result } = renderHook(() => useChatStore());@@ -1596,6 +2057,7 @@ describe('ConversationControl actions', () => {parentMessageId: 'tool-msg-1',resumeToolResult: {content: 'My favorite color is blue',+ outcome: 'submitted',parentMessageId: 'tool-msg-1',toolCallId: 'call_ask',},@@ -1668,6 +2130,67 @@ describe('ConversationControl actions', () => {executeGatewayAgentSpy.mockRestore();});+ it('propagates a generic custom-submit failure without running side effects or settling the card', async () => {+ const { result } = renderHook(() => useChatStore());+ const agentId = 'server-agent';+ const topicId = 'server-topic';+ const chatKey = messageMapKey({ agentId, topicId });+ const toolMessage = createMockMessage({+ id: 'tool-msg-custom-failure',+ plugin: {+ apiName: 'showAgentMarketplace',+ arguments: '{}',+ identifier: 'lobe-web-onboarding',+ type: 'default',+ },+ pluginIntervention: {+ batchId: 'batch-custom-failure',+ operationId: 'operation-custom-failure',+ status: 'pending',+ },+ role: 'tool',+ tool_call_id: 'call-custom-failure',+ } as any);+ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ activeTopicId: topicId,+ dbMessagesMap: { [chatKey]: [toolMessage] },+ messagesMap: { [chatKey]: [toolMessage] },+ });+ });+ vi.spyOn(result.current, 'isGatewayModeEnabled').mockReturnValue(true);+ const legacySideEffect = vi.fn().mockResolvedValue({+ response: { selectedTemplateIds: ['template-1'] },+ });+ const mutation = vi.mocked(lambdaClient.aiAgent.resolveAgentInterventionBySource.mutate);+ mutation.mockRejectedValue(new Error('custom claim unavailable'));+ const submit = () =>+ result.current.submitToolInteraction('tool-msg-custom-failure', {}, undefined, {+ agentInterventionAction: {+ result: {+ kind: 'agent_marketplace',+ selectedTemplateIds: ['template-1'],+ },+ type: 'submit_custom',+ },+ prepareLegacyFallback: legacySideEffect,+ });++ expect(await captureActError(submit)).toMatchObject({+ message: 'custom claim unavailable',+ });+ expect(await captureActError(submit)).toMatchObject({+ message: 'custom claim unavailable',+ });++ expect(legacySideEffect).not.toHaveBeenCalled();+ expect(result.current.dbMessagesMap[chatKey][0].pluginIntervention?.status).toBe('pending');+ expect(mutation.mock.calls[0]?.[0].resolutionRequestId).toBe(+ mutation.mock.calls[1]?.[0].resolutionRequestId,+ );+ });+it('takes the client path (executeClientAgent) when gateway mode is disabled', async () => {const { result } = renderHook(() => useChatStore());@@ -2286,6 +2809,465 @@ describe('ConversationControl actions', () => {});describe('submitHeteroIntervention characterization (lifecycle refactor regression net)', () => {+ it.each([+ {+ actionType: 'submit' as const,+ expectedAction: {+ result: { 'Which color?': 'Blue' },+ type: 'submit_answers' as const,+ },+ interactionKind: 'question',+ payload: { 'Which color?': 'Blue' },+ },+ {+ actionType: 'skip' as const,+ expectedAction: { type: 'skip_interaction' as const },+ interactionKind: 'question',+ payload: {},+ },+ {+ actionType: 'cancel' as const,+ expectedAction: { type: 'cancel_interaction' as const },+ interactionKind: 'question',+ payload: {},+ },+ {+ actionType: 'submit' as const,+ expectedAction: { optionId: 'allow_once', type: 'select_provider_option' as const },+ interactionKind: 'permission',+ payload: { permission: 'allow_once' },+ },+ {+ actionType: 'skip' as const,+ expectedAction: { type: 'skip_interaction' as const },+ interactionKind: 'permission',+ payload: {},+ },+ {+ actionType: 'cancel' as const,+ expectedAction: { type: 'cancel_interaction' as const },+ interactionKind: 'permission',+ payload: {},+ },+ {+ actionType: 'submit' as const,+ expectedAction: { optionId: 'approve_plan', type: 'select_provider_option' as const },+ interactionKind: 'plan',+ payload: { plan: 'approve_plan' },+ },+ {+ actionType: 'skip' as const,+ expectedAction: { type: 'skip_interaction' as const },+ interactionKind: 'plan',+ payload: {},+ },+ {+ actionType: 'cancel' as const,+ expectedAction: { type: 'cancel_interaction' as const },+ interactionKind: 'plan',+ payload: {},+ },+ ])(+ 'resolves a cold-start $interactionKind $actionType through the durable source before consulting operation memory',+ async ({ actionType, expectedAction, interactionKind, payload }) => {+ const { result } = renderHook(() => useChatStore());+ const agentId = 'remote-agent';+ const topicId = 'remote-topic';+ const chatKey = messageMapKey({ agentId, topicId });+ const assistantMessage = createMockMessage({+ id: `assistant-msg-${interactionKind}-${actionType}`,+ role: 'assistant',+ });+ const toolMessage = createMockMessage({+ id: `tool-msg-${interactionKind}-${actionType}`,+ parentId: assistantMessage.id,+ pluginIntervention: {+ batchId: `batch-${interactionKind}`,+ operationId: `server-operation-${interactionKind}`,+ status: 'pending',+ },+ pluginState: { heterogeneousIntervention: { interactionKind } },+ role: 'tool',+ tool_call_id: `call-${interactionKind}`,+ } as any);++ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ activeTopicId: topicId,+ dbMessagesMap: { [chatKey]: [assistantMessage, toolMessage] },+ messageOperationMap: {},+ messagesMap: { [chatKey]: [assistantMessage, toolMessage] },+ operations: {},+ });+ });++ const sourceMutation = vi.mocked(+ lambdaClient.aiAgent.resolveAgentInterventionBySource.mutate,+ );+ sourceMutation.mockResolvedValueOnce({+ contractVersion: 2,+ state: 'claimed',+ status: 'approved',+ success: true,+ });+ const dispatchSpy = vi.spyOn(result.current, 'internal_dispatchMessage');+ const interventionWriteSpy = vi.spyOn(messageService, 'updateMessagePlugin');+ const persistAnswersSpy = vi+ .spyOn(messageService, 'updateMessagePluginState')+ .mockResolvedValue({ messages: [], success: true });+ const legacyRemoteSubmit = vi.mocked(lambdaClient.aiAgent.submitHeteroIntervention.mutate);+ const localSubmit = vi+ .spyOn(heterogeneousAgentService, 'submitIntervention')+ .mockResolvedValue(undefined as any);++ await act(async () => {+ await result.current.submitHeteroIntervention(toolMessage.id, actionType, payload);+ });++ expect(sourceMutation).toHaveBeenCalledWith({+ action: expectedAction,+ batchId: `batch-${interactionKind}`,+ operationId: `server-operation-${interactionKind}`,+ resolutionRequestId: expect.any(String),+ targets: [{ toolCallId: `call-${interactionKind}`, toolMessageId: toolMessage.id }],+ });+ const resolvingIntervention = {+ ...toolMessage.pluginIntervention,+ resolving: true,+ status: 'pending',+ };+ expect(dispatchSpy).toHaveBeenCalledWith(+ {+ id: toolMessage.id,+ type: 'updateMessage',+ value: { pluginIntervention: resolvingIntervention },+ },+ { context: { agentId, topicId } },+ );+ expect(dispatchSpy).toHaveBeenCalledWith(+ {+ id: assistantMessage.id,+ tool_call_id: toolMessage.tool_call_id,+ type: 'updateMessageTools',+ value: { intervention: resolvingIntervention },+ },+ { context: { agentId, topicId } },+ );+ expect(interventionWriteSpy).not.toHaveBeenCalled();+ if (actionType === 'submit') {+ expect(persistAnswersSpy).toHaveBeenCalledWith(+ toolMessage.id,+ { askUserAnswers: payload },+ expect.objectContaining({ agentId, topicId }),+ );+ } else {+ expect(persistAnswersSpy).not.toHaveBeenCalled();+ }+ expect(legacyRemoteSubmit).not.toHaveBeenCalled();+ expect(localSubmit).not.toHaveBeenCalled();+ },+ );++ it('refreshes an already-resolved cold-start card without persisting a losing answer', async () => {+ const { result } = renderHook(() => useChatStore());+ const agentId = 'remote-agent';+ const topicId = 'remote-topic';+ const chatKey = messageMapKey({ agentId, topicId });+ const toolMessage = createMockMessage({+ id: 'tool-msg-already-resolved',+ pluginIntervention: {+ batchId: 'batch-already-resolved',+ operationId: 'server-operation-already-resolved',+ status: 'pending',+ },+ pluginState: { heterogeneousIntervention: { interactionKind: 'question' } },+ role: 'tool',+ tool_call_id: 'call-already-resolved',+ } as any);++ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ activeTopicId: topicId,+ dbMessagesMap: { [chatKey]: [toolMessage] },+ messageOperationMap: {},+ messagesMap: { [chatKey]: [toolMessage] },+ operations: {},+ });+ });++ vi.mocked(lambdaClient.aiAgent.resolveAgentInterventionBySource.mutate).mockResolvedValueOnce(+ {+ contractVersion: 2,+ state: 'already_resolved',+ status: 'resolved',+ success: true,+ },+ );+ const interventionWriteSpy = vi.spyOn(messageService, 'updateMessagePlugin');+ const persistAnswersSpy = vi+ .spyOn(messageService, 'updateMessagePluginState')+ .mockResolvedValue({ messages: [], success: true });+ const refreshSpy = vi.spyOn(result.current, 'refreshMessages').mockResolvedValue(undefined);++ await act(async () => {+ await result.current.submitHeteroIntervention('tool-msg-already-resolved', 'submit', {+ Question: 'Losing answer',+ });+ });++ expect(refreshSpy).toHaveBeenCalledWith({ agentId, topicId });+ expect(interventionWriteSpy).not.toHaveBeenCalled();+ expect(persistAnswersSpy).not.toHaveBeenCalled();+ });++ it('fails closed after an unavailable durable source when operation memory is empty', async () => {+ const { result } = renderHook(() => useChatStore());+ const agentId = 'remote-agent';+ const topicId = 'remote-topic';+ const chatKey = messageMapKey({ agentId, topicId });+ const toolMessage = createMockMessage({+ id: 'tool-msg-source-unavailable',+ pluginIntervention: {+ batchId: 'batch-source-unavailable',+ operationId: 'server-operation-source-unavailable',+ status: 'pending',+ },+ pluginState: { heterogeneousIntervention: { interactionKind: 'question' } },+ role: 'tool',+ tool_call_id: 'call-source-unavailable',+ } as any);++ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ activeTopicId: topicId,+ dbMessagesMap: { [chatKey]: [toolMessage] },+ messageOperationMap: {},+ messagesMap: { [chatKey]: [toolMessage] },+ operations: {},+ });+ });++ const sourceMutation = vi.mocked(+ lambdaClient.aiAgent.resolveAgentInterventionBySource.mutate,+ );+ const pluginSpy = vi+ .spyOn(result.current, 'optimisticUpdateMessagePlugin')+ .mockResolvedValue(undefined);+ const legacyRemoteSubmit = vi.mocked(lambdaClient.aiAgent.submitHeteroIntervention.mutate);+ const localSubmit = vi+ .spyOn(heterogeneousAgentService, 'submitIntervention')+ .mockResolvedValue(undefined as any);++ await act(async () => {+ await result.current.submitHeteroIntervention('tool-msg-source-unavailable', 'submit', {+ Question: 'Answer',+ });+ });++ expect(sourceMutation).toHaveBeenCalledOnce();+ expect(pluginSpy).not.toHaveBeenCalled();+ expect(legacyRemoteSubmit).not.toHaveBeenCalled();+ expect(localSubmit).not.toHaveBeenCalled();+ });++ it('uses the in-memory runtime identity only for the handled-false local desktop fallback', async () => {+ const { result } = renderHook(() => useChatStore());+ const agentId = 'local-agent';+ const topicId = 'local-topic';+ const chatKey = messageMapKey({ agentId, topicId });+ const assistantMessage = createMockMessage({ id: 'assistant-msg-local', role: 'assistant' });+ const toolMessage = createMockMessage({+ id: 'tool-msg-local-fallback',+ parentId: assistantMessage.id,+ pluginIntervention: {+ batchId: 'batch-local-fallback',+ operationId: 'server-operation-local-fallback',+ status: 'pending',+ },+ pluginState: { heterogeneousIntervention: { interactionKind: 'question' } },+ role: 'tool',+ tool_call_id: 'call-local-fallback',+ } as any);+ const clientOperationId = 'client-local-operation';++ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ activeTopicId: topicId,+ dbMessagesMap: { [chatKey]: [assistantMessage, toolMessage] },+ messagesMap: { [chatKey]: [assistantMessage, toolMessage] },+ });+ result.current.startOperation({+ context: { agentId, threadId: null, topicId },+ operationId: clientOperationId,+ type: 'execHeterogeneousAgent',+ });+ useChatStore.setState({+ messageOperationMap: { [assistantMessage.id]: clientOperationId },+ });+ });++ const pluginSpy = vi+ .spyOn(result.current, 'optimisticUpdateMessagePlugin')+ .mockResolvedValue(undefined);+ vi.spyOn(result.current, 'optimisticUpdateMessageContent').mockResolvedValue(undefined);+ vi.spyOn(messageService, 'updateMessagePluginState').mockResolvedValue({+ messages: [],+ success: true,+ });+ const localSubmit = vi+ .spyOn(heterogeneousAgentService, 'submitIntervention')+ .mockResolvedValue(undefined as any);+ const sourceMutation = vi.mocked(+ lambdaClient.aiAgent.resolveAgentInterventionBySource.mutate,+ );++ await act(async () => {+ await result.current.submitHeteroIntervention('tool-msg-local-fallback', 'submit', {+ Question: 'Answer',+ });+ });++ expect(sourceMutation).toHaveBeenCalledWith(+ expect.objectContaining({ operationId: 'server-operation-local-fallback' }),+ );+ expect(pluginSpy).toHaveBeenCalledWith(+ 'tool-msg-local-fallback',+ { intervention: { status: 'approved' } },+ { operationId: clientOperationId },+ );+ expect(localSubmit).toHaveBeenCalledWith({+ operationId: clientOperationId,+ result: { Question: 'Answer' },+ toolCallId: 'call-local-fallback',+ });+ });++ it('uses the in-memory runtime identity only for the handled-false remote legacy fallback', async () => {+ const { result } = renderHook(() => useChatStore());+ const agentId = 'remote-agent';+ const topicId = 'remote-topic';+ const chatKey = messageMapKey({ agentId, topicId });+ const assistantMessage = createMockMessage({ id: 'assistant-msg-remote', role: 'assistant' });+ const toolMessage = createMockMessage({+ id: 'tool-msg-remote-fallback',+ parentId: assistantMessage.id,+ pluginIntervention: {+ batchId: 'batch-remote-fallback',+ operationId: 'server-operation-remote-fallback',+ status: 'pending',+ },+ pluginState: { heterogeneousIntervention: { interactionKind: 'question' } },+ role: 'tool',+ tool_call_id: 'call-remote-fallback',+ } as any);+ const clientOperationId = 'client-remote-operation';++ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ activeTopicId: topicId,+ dbMessagesMap: { [chatKey]: [assistantMessage, toolMessage] },+ messagesMap: { [chatKey]: [assistantMessage, toolMessage] },+ });+ result.current.startOperation({+ context: { agentId, threadId: null, topicId },+ operationId: clientOperationId,+ type: 'execServerAgentRuntime',+ });+ useChatStore.setState({+ messageOperationMap: { [assistantMessage.id]: clientOperationId },+ });+ });++ vi.spyOn(result.current, 'optimisticUpdateMessagePlugin').mockResolvedValue(undefined);+ vi.spyOn(messageService, 'updateMessagePluginState').mockResolvedValue({+ messages: [],+ success: true,+ });+ const sourceMutation = vi.mocked(+ lambdaClient.aiAgent.resolveAgentInterventionBySource.mutate,+ );+ const legacyRemoteSubmit = vi.mocked(lambdaClient.aiAgent.submitHeteroIntervention.mutate);++ await act(async () => {+ await result.current.submitHeteroIntervention('tool-msg-remote-fallback', 'submit', {+ Question: 'Answer',+ });+ });++ expect(sourceMutation).toHaveBeenCalledWith(+ expect.objectContaining({ operationId: 'server-operation-remote-fallback' }),+ );+ expect(legacyRemoteSubmit).toHaveBeenCalledWith({+ operationId: clientOperationId,+ resolutionRequestId: expect.any(String),+ result: { Question: 'Answer' },+ toolCallId: 'call-remote-fallback',+ });+ });++ it('keeps a cold-start durable card unchanged when the source request fails', async () => {+ const { result } = renderHook(() => useChatStore());+ const agentId = 'remote-agent';+ const topicId = 'remote-topic';+ const chatKey = messageMapKey({ agentId, topicId });+ const toolMessage = createMockMessage({+ content: 'Pending question',+ id: 'tool-msg-source-failure',+ pluginIntervention: {+ batchId: 'batch-source-failure',+ operationId: 'server-operation-source-failure',+ status: 'pending',+ },+ pluginState: { heterogeneousIntervention: { interactionKind: 'question' } },+ role: 'tool',+ tool_call_id: 'call-source-failure',+ } as any);++ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ activeTopicId: topicId,+ dbMessagesMap: { [chatKey]: [toolMessage] },+ messageOperationMap: {},+ messagesMap: { [chatKey]: [toolMessage] },+ operations: {},+ });+ });++ const sourceError = new Error('source transport unavailable');+ vi.mocked(lambdaClient.aiAgent.resolveAgentInterventionBySource.mutate).mockRejectedValueOnce(+ sourceError,+ );+ const pluginSpy = vi+ .spyOn(result.current, 'optimisticUpdateMessagePlugin')+ .mockResolvedValue(undefined);+ const contentSpy = vi+ .spyOn(result.current, 'optimisticUpdateMessageContent')+ .mockResolvedValue(undefined);+ const legacyRemoteSubmit = vi.mocked(lambdaClient.aiAgent.submitHeteroIntervention.mutate);++ expect(+ await captureActError(() =>+ result.current.submitHeteroIntervention('tool-msg-source-failure', 'submit', {+ Question: 'Answer',+ }),+ ),+ ).toBe(sourceError);++ expect(pluginSpy).not.toHaveBeenCalled();+ expect(contentSpy).not.toHaveBeenCalled();+ expect(legacyRemoteSubmit).not.toHaveBeenCalled();+ expect(result.current.dbMessagesMap[chatKey][0]).toMatchObject({+ content: 'Pending question',+ pluginIntervention: { status: 'pending' },+ });+ });+it('submits via IPC, persists optimistic intervention, and flips topic status to running (submit)', async () => {const { result } = renderHook(() => useChatStore());@@ -2486,10 +3468,14 @@ describe('ConversationControl actions', () => {.spyOn(result.current, 'optimisticUpdateMessagePlugin').mockResolvedValue(undefined);vi.spyOn(result.current, 'optimisticUpdateMessageContent').mockResolvedValue(undefined);- vi.spyOn(result.current, 'updateTopicStatus').mockResolvedValue(undefined as any);+ const updateTopicStatusSpy = vi+ .spyOn(result.current, 'updateTopicStatus')+ .mockResolvedValue(undefined as any);const submitInterventionSpy = vi.spyOn(heterogeneousAgentService, 'submitIntervention').mockResolvedValue(undefined as any);+ const remoteSubmit = vi.mocked(lambdaClient.aiAgent.submitHeteroIntervention.mutate);+ remoteSubmit.mockClear();await act(async () => {await expect(@@ -2497,12 +3483,14 @@ describe('ConversationControl actions', () => {).resolves.toBeUndefined();});- // Optimistic write uses the empty global-state fallback context.+ // Remote publish is only transport acceptance: keep the form pending,+ // mark it resolving, and use the empty global-state fallback context.expect(pluginSpy).toHaveBeenCalledWith('tool-msg-1',- expect.objectContaining({ intervention: expect.objectContaining({ status: 'rejected' }) }),+ { intervention: { resolving: true, status: 'pending' } },{},);+ expect(updateTopicStatusSpy).not.toHaveBeenCalled();// Remote tRPC submit fires with the (stale) resolved operationId + cancel;// the desktop IPC path is not taken for a GC'd (non-local) op.@@ -2514,6 +3502,39 @@ describe('ConversationControl actions', () => {}),);expect(submitInterventionSpy).not.toHaveBeenCalled();++ const firstCancelRequestId = remoteSubmit.mock.calls[0][0].resolutionRequestId;+ await act(async () => {+ await result.current.submitHeteroIntervention('tool-msg-1', 'cancel');+ });+ expect(remoteSubmit.mock.calls[1][0].resolutionRequestId).toBe(firstCancelRequestId);++ await act(async () => {+ await result.current.submitHeteroIntervention('tool-msg-1', 'skip');+ });+ expect(remoteSubmit.mock.calls[2][0].resolutionRequestId).not.toBe(firstCancelRequestId);++ await act(async () => {+ await result.current.submitHeteroIntervention('tool-msg-1', 'submit', { b: 2, a: 1 });+ await result.current.submitHeteroIntervention('tool-msg-1', 'submit', { a: 1, b: 2 });+ await result.current.submitHeteroIntervention('tool-msg-1', 'submit', { a: 2, b: 2 });+ });+ const firstPayloadRequestId = remoteSubmit.mock.calls[3][0].resolutionRequestId;+ expect(remoteSubmit.mock.calls[4][0].resolutionRequestId).toBe(firstPayloadRequestId);+ expect(remoteSubmit.mock.calls[5][0].resolutionRequestId).not.toBe(firstPayloadRequestId);++ const publishError = new Error('publish failed');+ remoteSubmit.mockRejectedValueOnce(publishError);+ await act(async () => {+ await expect(result.current.submitHeteroIntervention('tool-msg-1', 'cancel')).rejects.toBe(+ publishError,+ );+ });+ expect(pluginSpy).toHaveBeenLastCalledWith(+ 'tool-msg-1',+ { intervention: { status: 'pending' } },+ {},+ );});it('flips topic status on the passed context, NOT the active topic, when submitting from a background conversation', async () => {@@ -2660,7 +3681,7 @@ describe('ConversationControl actions', () => {executeGatewayAgentSpy.mockRestore();});- it('marks every card approved so the bar settles in one paint', async () => {+ it('does not forge approved cards before the server wins the batch claim', async () => {const { result } = renderHook(() => useChatStore());seedPendingBatch(result);@@ -2674,13 +3695,7 @@ describe('ConversationControl actions', () => {await result.current.approveAllToolCalls(['tool-msg-a', 'tool-msg-b', 'tool-msg-c']);});- for (const id of ['tool-msg-a', 'tool-msg-b', 'tool-msg-c']) {- expect(optimisticSpy).toHaveBeenCalledWith(- id,- { intervention: { status: 'approved' } },- expect.anything(),- );- }+ expect(optimisticSpy).not.toHaveBeenCalled();executeGatewayAgentSpy.mockRestore();});diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts b/src/store/chat/slices/agentRun/actions/entries/conversationControl.tsindex bf022deab1d..f9b26b6351c 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts@@ -11,7 +11,11 @@ import { t } from 'i18next';import { type ChatInputEditor } from '@/features/ChatInput';import { lambdaClient } from '@/libs/trpc/client';-import { aiAgentService } from '@/services/aiAgent';+import {+ type AgentInterventionSourceAction,+ aiAgentService,+ type ResolveAgentInterventionBySourceResult,+} from '@/services/aiAgent';import { getAgentStoreState } from '@/store/agent';import { agentSelectors } from '@/store/agent/selectors';import { displayMessageSelectors } from '@/store/chat/selectors';@@ -27,6 +31,7 @@ import { AI_RUNTIME_OPERATION_TYPES } from '@/store/chat/slices/operation/types'import { type ChatStore } from '@/store/chat/store';import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { type StoreSetter } from '@/store/types';+import { useUserStore } from '@/store/user';import { buildRunLifecycle } from '../lifecycle/buildRunLifecycle';import { type RunScope } from '../lifecycle/types';@@ -36,11 +41,71 @@ import { type RunScope } from '../lifecycle/types';*/type Setter = StoreSetter<ChatStore>;++const canonicalizeResolutionPayload = (value: unknown): unknown => {+ if (Array.isArray(value)) return value.map(canonicalizeResolutionPayload);+ if (value && typeof value === 'object') {+ return Object.fromEntries(+ Object.entries(value as Record<string, unknown>)+ .sort(([left], [right]) => left.localeCompare(right))+ .map(([key, child]) => [key, canonicalizeResolutionPayload(child)]),+ );+ }+ return value;+};++const toAgentInterventionAnswerResult = (+ value: Record<string, unknown>,+): Record<string, string | string[]> | undefined => {+ const entries = Object.entries(value);+ if (+ entries.length === 0 ||+ entries.some(+ ([, answer]) =>+ typeof answer !== 'string' &&+ !(Array.isArray(answer) && answer.every((item) => typeof item === 'string')),+ )+ ) {+ return;+ }+ return Object.fromEntries(entries) as Record<string, string | string[]>;+};++const toHeterogeneousSourceAction = (+ actionType: 'submit' | 'skip' | 'cancel',+ interactionKind: unknown,+ payload: Record<string, unknown>,+): AgentInterventionSourceAction | undefined => {+ if (actionType === 'skip') return { type: 'skip_interaction' };+ if (actionType === 'cancel') return { type: 'cancel_interaction' };++ if (interactionKind === 'question') {+ const result = toAgentInterventionAnswerResult(payload);+ return result ? { result, type: 'submit_answers' } : undefined;+ }+ if (interactionKind === 'permission' || interactionKind === 'plan') {+ const selected = Object.values(payload).flatMap((value) =>+ typeof value === 'string'+ ? [value]+ : Array.isArray(value)+ ? value.filter((item): item is string => typeof item === 'string')+ : [],+ );+ return selected.length === 1+ ? { optionId: selected[0], type: 'select_provider_option' }+ : undefined;+ }+};+export const conversationControl = (set: Setter, get: () => ChatStore, _api?: unknown) =>new ConversationControlActionImpl(set, get, _api);export class ConversationControlActionImpl {readonly #get: () => ChatStore;+ /** Stable generic claim key shared by retries of one active Web action. */+ readonly #interventionResolutionRequestIds = new Map<string, string>();+ /** Stable per-intervention idempotency key reused by transport retries. */+ readonly #heteroResolutionRequestIds = new Map<string, string>();constructor(set: Setter, get: () => ChatStore, _api?: unknown) {void _api;@@ -48,6 +113,71 @@ export class ConversationControlActionImpl {this.#get = get;}+ /**+ * Resolve an active Gateway card through the same durable generic claim as+ * Mobile/notifications. Returns false only when the deployment has no+ * generic intervention store, allowing the existing OSS path to continue.+ */+ tryResolveAgentInterventionBySource = async (params: {+ action: AgentInterventionSourceAction;+ context?: ConversationContext;+ toolMessageIds: string[];+ }): Promise<ResolveAgentInterventionBySourceResult> => {+ const targets = params.toolMessageIds.map((toolMessageId) => {+ const message = dbMessageSelectors.getDbMessageById(toolMessageId)(this.#get());+ return {+ batchId: message?.pluginIntervention?.batchId,+ operationId: message?.pluginIntervention?.operationId,+ toolCallId: message?.tool_call_id,+ toolMessageId,+ };+ });+ const first = targets[0];+ if (+ !first?.batchId ||+ !first.operationId ||+ targets.some(+ (target) =>+ !target.toolCallId ||+ target.batchId !== first.batchId ||+ target.operationId !== first.operationId,+ )+ ) {+ return { handled: false };+ }++ const sourceTargets = targets.map(({ toolCallId, toolMessageId }) => ({+ toolCallId: toolCallId!,+ toolMessageId,+ }));+ const resolutionKey = JSON.stringify(+ canonicalizeResolutionPayload({+ action: params.action,+ batchId: first.batchId,+ operationId: first.operationId,+ targets: sourceTargets,+ }),+ );+ const resolutionRequestId =+ this.#interventionResolutionRequestIds.get(resolutionKey) ?? globalThis.crypto.randomUUID();+ this.#interventionResolutionRequestIds.set(resolutionKey, resolutionRequestId);++ const result = await aiAgentService.resolveAgentInterventionBySource({+ action: params.action,+ batchId: first.batchId,+ operationId: first.operationId,+ resolutionRequestId,+ targets: sourceTargets,+ });+ if (result.handled) {+ this.#interventionResolutionRequestIds.delete(resolutionKey);+ if (result.state === 'already_resolved' && params.context) {+ await this.#get().refreshMessages(params.context);+ }+ }+ return result;+ };+/*** Decide whether approve/reject/reject_continue should go through the* Gateway resume path (new op carrying `resumeApproval`) instead of the@@ -206,6 +336,29 @@ export class ConversationControlActionImpl {for (const id of opIds) completeOperation(id);};+ /**+ * A durable source that reports `already_resolved` lost the first-winner+ * claim. `tryResolveAgentInterventionBySource` has already refreshed the+ * authoritative messages, so callers must not publish a resumed lifecycle,+ * execute, mark the topic active, or retire the actual paused operation.+ *+ * Actions that created an interim local operation before probing the source+ * still need to retire that temporary loading marker. Cancel it instead of+ * completing it so the losing action is never represented as a successful+ * resume.+ */+ #discardAlreadyResolvedSource = (+ result: ResolveAgentInterventionBySourceResult,+ interimOperationId?: string,+ ): boolean => {+ if (!result.handled || result.state !== 'already_resolved') return false;++ if (interimOperationId) {+ this.#get().cancelOperation(interimOperationId, 'Intervention already resolved');+ }+ return true;+ };+#writeTopicStatus = (context: ConversationContext, status: ChatTopicStatus): void => {if (!context.topicId) return;@@ -375,6 +528,11 @@ export class ConversationControlActionImpl {toolMessageId: string,_assistantGroupId: string,context?: ConversationContext,+ options?: {+ editedArguments?: Record<string, unknown>;+ onLegacyEditFallback?: () => Promise<void>;+ rememberToolKey?: string;+ },): Promise<void> => {const { executeClientAgent, startOperation, completeOperation } = this.#get();@@ -409,21 +567,26 @@ export class ConversationControlActionImpl {const optimisticContext = { operationId };const shouldUseGatewayResume = this.#shouldUseGatewayResume(effectiveContext);- if (!shouldUseGatewayResume) this.#writeTopicStatus(effectiveContext, 'active');-- // Park → resume: a new op continues the run paused on this tool's approval.- this.#emitRunResumed(effectiveContext, {- operationId,- parentMessageId: toolMessageId,- runtimeType: shouldUseGatewayResume ? 'gateway' : 'client',- });+ if (!shouldUseGatewayResume) {+ this.#writeTopicStatus(effectiveContext, 'active');+ // Park → resume: a new op continues the run paused on this tool's approval.+ this.#emitRunResumed(effectiveContext, {+ operationId,+ parentMessageId: toolMessageId,+ runtimeType: 'client',+ });+ }- // 2. Update intervention status to approved- await this.#get().optimisticUpdateMessagePlugin(- toolMessageId,- { intervention: { status: 'approved' } },- optimisticContext,- );+ // Local runtime owns its message mutation. Gateway resumes claim the+ // still-pending row atomically on the server, so they must not persist an+ // optimistic approved state before calling the claim endpoint.+ if (!shouldUseGatewayResume) {+ await this.#get().optimisticUpdateMessagePlugin(+ toolMessageId,+ { intervention: { status: 'approved' } },+ optimisticContext,+ );+ }// NOTE: intentionally do NOT bail on Stop here. `intervention: approved` is// already persisted above; returning early would leave the tool marked@@ -452,17 +615,56 @@ export class ConversationControlActionImpl {// Gateway mode on retry.const pausedOpIds = this.#getRunningServerOps(effectiveContext).map((op) => op.id);try {- await this.#get().executeGatewayAgent({+ const sourceResolution = await this.tryResolveAgentInterventionBySource({+ action: {+ ...(options?.editedArguments && {+ edits: { [toolMessageId]: options.editedArguments },+ }),+ scope: options?.rememberToolKey ? 'remember' : 'once',+ type: 'approve_tool',+ },context: effectiveContext,- message: '',- metadata: requestMetadata,+ toolMessageIds: [toolMessageId],+ });+ if (this.#discardAlreadyResolvedSource(sourceResolution, operationId)) return;++ this.#emitRunResumed(effectiveContext, {+ operationId,parentMessageId: toolMessageId,- resumeApproval: {- decision: 'approved',- parentMessageId: toolMessageId,- toolCallId,- },+ runtimeType: 'gateway',});+ if (sourceResolution.handled) {+ if (sourceResolution.execution) {+ await this.#get().executeGatewayAgent({+ context: effectiveContext,+ message: '',+ metadata: requestMetadata,+ parentMessageId: toolMessageId,+ precreatedResult: sourceResolution.execution,+ });+ }+ } else {+ // OSS compatibility: no generic durable store. Persist a staged edit+ // only now, after the generic capability probe, then use the existing+ // message-row claim path.+ if (options?.editedArguments) {+ await options.onLegacyEditFallback?.();+ }+ await this.#get().executeGatewayAgent({+ context: effectiveContext,+ message: '',+ metadata: requestMetadata,+ parentMessageId: toolMessageId,+ resumeApproval: {+ decision: 'approved',+ parentMessageId: toolMessageId,+ toolCallId,+ },+ });+ if (options?.rememberToolKey) {+ await useUserStore.getState().addToolToAllowList(options.rememberToolKey);+ }+ }this.#writeTopicStatus(effectiveContext, 'active');this.#completeOpsById(pausedOpIds);completeOperation(operationId);@@ -473,6 +675,7 @@ export class ConversationControlActionImpl {type: 'approveToolCalling',message: err.message || 'Unknown error',});+ throw error;}return;}@@ -520,6 +723,9 @@ export class ConversationControlActionImpl {// This ensures proper cancellation propagationparentOperationId: operationId,});+ if (options?.rememberToolKey) {+ await useUserStore.getState().addToolToAllowList(options.rememberToolKey);+ }completeOperation(operationId);} catch (error) {const err = error as Error;@@ -557,8 +763,9 @@ export class ConversationControlActionImpl {* This cannot go through the ordinary cancel actions: they all filter on* `status === 'running'`, and a parked run's client operation is `completed`* (the server's park is stream-terminal) and pruned ~30s later, so the client- * no longer holds the parked operation id. The server resolves it from the- * topic instead.+ * no longer holds its operation object. The pending tool rows retain the+ * authoritative operationId + sealed batchId, which are the only identities+ * accepted by the server stop path.*/stopPendingApproval = async (toolMessageIds: string[],@@ -583,20 +790,41 @@ export class ConversationControlActionImpl {const addressable = toolMessageIds.filter((id) => !id.startsWith('tmp_'));if (addressable.length === 0) return;- // Clear the cards in one paint rather than letting them wink out one by one- // as the server catches up.- await Promise.all(- addressable.map((toolMessageId) =>- this.#get().optimisticUpdateMessagePlugin(toolMessageId, {- intervention: { status: 'aborted' },- }),- ),- );+ const targets = addressable.map((id) => dbMessageSelectors.getDbMessageById(id)(this.#get()));+ const operationId = targets[0]?.pluginIntervention?.operationId;+ const batchId = targets[0]?.pluginIntervention?.batchId;+ if (+ !operationId ||+ !batchId ||+ targets.some(+ (message) =>+ !message ||+ message.pluginIntervention?.operationId !== operationId ||+ message.pluginIntervention?.batchId !== batchId,+ )+ ) {+ console.warn('[stopPendingApproval] missing or mixed authoritative batch identity; skipping');+ return;+ }const pausedOpIds = this.#getRunningServerOps(effectiveContext).map((op) => op.id);try {- await aiAgentService.stopPendingApproval({ toolMessageIds: addressable, topicId });+ const sourceResolution = await this.tryResolveAgentInterventionBySource({+ action: { scope: 'operation', type: 'stop' },+ context: effectiveContext,+ toolMessageIds: addressable,+ });+ if (this.#discardAlreadyResolvedSource(sourceResolution)) return;++ if (!sourceResolution.handled) {+ await aiAgentService.stopPendingApproval({+ batchId,+ operationId,+ toolMessageIds: addressable,+ topicId,+ });+ }this.#completeOpsById(pausedOpIds);} catch (error) {console.error('[stopPendingApproval] failed:', error);@@ -652,37 +880,41 @@ export class ConversationControlActionImpl {context: { ...effectiveContext, messageId: anchorMessageId },});- const optimisticContext = { operationId };-- this.#emitRunResumed(effectiveContext, {- operationId,- parentMessageId: anchorMessageId,- runtimeType: 'gateway',- });-- // Mark every card approved up front so the whole intervention bar settles in- // one paint instead of clearing card-by-card as the server catches up.- await Promise.all(- decisions.map((decision) =>- this.#get().optimisticUpdateMessagePlugin(- decision.parentMessageId,- { intervention: { status: 'approved' } },- optimisticContext,- ),- ),- );-const requestMetadata = this.#getRequestMetadataFromMessageChain(anchorMessageId);const pausedOpIds = this.#getRunningServerOps(effectiveContext).map((op) => op.id);try {- await this.#get().executeGatewayAgent({+ const sourceResolution = await this.tryResolveAgentInterventionBySource({+ action: { scope: 'once', type: 'approve_tool' },context: effectiveContext,- message: '',- metadata: requestMetadata,+ toolMessageIds: decisions.map(({ parentMessageId }) => parentMessageId),+ });+ if (this.#discardAlreadyResolvedSource(sourceResolution, operationId)) return;++ this.#emitRunResumed(effectiveContext, {+ operationId,parentMessageId: anchorMessageId,- resumeApprovals: decisions,+ runtimeType: 'gateway',});+ if (sourceResolution.handled) {+ if (sourceResolution.execution) {+ await this.#get().executeGatewayAgent({+ context: effectiveContext,+ message: '',+ metadata: requestMetadata,+ parentMessageId: anchorMessageId,+ precreatedResult: sourceResolution.execution,+ });+ }+ } else {+ await this.#get().executeGatewayAgent({+ context: effectiveContext,+ message: '',+ metadata: requestMetadata,+ parentMessageId: anchorMessageId,+ resumeApprovals: decisions,+ });+ }this.#writeTopicStatus(effectiveContext, 'active');this.#completeOpsById(pausedOpIds);completeOperation(operationId);@@ -693,6 +925,7 @@ export class ConversationControlActionImpl {type: 'approveToolCalling',message: err.message || 'Unknown error',});+ throw error;}};@@ -701,7 +934,17 @@ export class ConversationControlActionImpl {response: Record<string, unknown>,context?: ConversationContext,options?: {+ agentInterventionAction?: Extract<+ AgentInterventionSourceAction,+ { type: 'submit_answers' | 'submit_custom' }+ >;createUserMessage?: boolean;+ prepareLegacyFallback?: () => Promise<{+ createUserMessage?: boolean;+ pluginState?: Record<string, unknown>;+ response: Record<string, unknown>;+ toolResultContent?: string;+ }>;pluginState?: Record<string, unknown>;toolResultContent?: string;},@@ -732,46 +975,50 @@ export class ConversationControlActionImpl {});const optimisticContext: OptimisticUpdateContext = { operationId };- const shouldCreateUserMessage = options?.createUserMessage !== false;+ let resolvedOptions = options;+ let resolvedResponse = response;+ const shouldCreateUserMessage = resolvedOptions?.createUserMessage !== false;const shouldUseGatewayResume = this.#shouldUseGatewayResume(effectiveContext);- if (!shouldUseGatewayResume) this.#writeTopicStatus(effectiveContext, 'active');-- // Park → resume: a new op continues the run paused on this tool interaction.- this.#emitRunResumed(effectiveContext, {- operationId,- parentMessageId: toolMessageId,- runtimeType: shouldUseGatewayResume ? 'gateway' : 'client',- });-- // 1. Mark intervention as approved and set tool result to user's response- await this.#get().optimisticUpdateMessagePlugin(- toolMessageId,- { intervention: { status: 'approved' } },- optimisticContext,- );-- const toolContent = options?.toolResultContent ?? `User submitted: ${JSON.stringify(response)}`;- await this.#get().optimisticUpdateMessageContent(- toolMessageId,- toolContent,- undefined,- optimisticContext,- );+ if (!shouldUseGatewayResume) {+ this.#writeTopicStatus(effectiveContext, 'active');+ // Park → resume: a new op continues the run paused on this tool interaction.+ this.#emitRunResumed(effectiveContext, {+ operationId,+ parentMessageId: toolMessageId,+ runtimeType: 'client',+ });+ }- if (options?.pluginState) {- await this.#get().optimisticUpdatePluginState(+ let toolContent =+ resolvedOptions?.toolResultContent ?? `User submitted: ${JSON.stringify(resolvedResponse)}`;+ if (!shouldUseGatewayResume) {+ // Client runtime owns its local pending row. Gateway must leave the DB+ // row pending until resumeToolResult acquires the server-side CAS.+ await this.#get().optimisticUpdateMessagePlugin(+ toolMessageId,+ { intervention: { status: 'approved' } },+ optimisticContext,+ );+ await this.#get().optimisticUpdateMessageContent(toolMessageId,- options.pluginState,+ toolContent,+ undefined,optimisticContext,);++ if (resolvedOptions?.pluginState) {+ await this.#get().optimisticUpdatePluginState(+ toolMessageId,+ resolvedOptions.pluginState,+ optimisticContext,+ );+ }}- // NOTE: intentionally do NOT bail on Stop here. `intervention: approved`- // and the tool result are already persisted above; returning early would- // leave the submission recorded but never resumed — a stuck conversation.- // Same best-effort rationale as approveToolCalling: complete atomically and- // honor the next Stop normally.+ // NOTE: intentionally do NOT bail on Stop here. In client mode the result+ // is already persisted; in Gateway mode the authoritative claim+resume+ // below is the indivisible action. Honor the next Stop after it settles.// 1.5. Server-mode: start a **new** Gateway op carrying the human answer as// the tool result via `resumeToolResult`. The server writes the answer as@@ -794,18 +1041,59 @@ export class ConversationControlActionImpl {// marker intact and `#shouldUseGatewayResume` still flags Gateway mode.const pausedOpIds = this.#getRunningServerOps(effectiveContext).map((op) => op.id);try {- await this.#get().executeGatewayAgent({- context: effectiveContext,- message: '',- metadata: requestMetadata,+ const answerResult = toAgentInterventionAnswerResult(resolvedResponse);+ const sourceAction =+ resolvedOptions?.agentInterventionAction ??+ (answerResult ? ({ result: answerResult, type: 'submit_answers' } as const) : undefined);+ const sourceResolution = sourceAction+ ? await this.tryResolveAgentInterventionBySource({+ action: sourceAction,+ context: effectiveContext,+ toolMessageIds: [toolMessageId],+ })+ : { handled: false as const };++ if (this.#discardAlreadyResolvedSource(sourceResolution, operationId)) return;++ this.#emitRunResumed(effectiveContext, {+ operationId,parentMessageId: toolMessageId,- resumeToolResult: {- content: toolContent,- parentMessageId: toolMessageId,- toolCallId,- ...(options?.pluginState ? { pluginState: options.pluginState } : {}),- },+ runtimeType: 'gateway',});++ if (sourceResolution.handled) {+ if (sourceResolution.execution) {+ await this.#get().executeGatewayAgent({+ context: effectiveContext,+ message: '',+ metadata: requestMetadata,+ parentMessageId: toolMessageId,+ precreatedResult: sourceResolution.execution,+ });+ }+ } else {+ const legacyFallback = await resolvedOptions?.prepareLegacyFallback?.();+ if (legacyFallback) {+ resolvedResponse = legacyFallback.response;+ resolvedOptions = { ...resolvedOptions, ...legacyFallback };+ toolContent =+ resolvedOptions.toolResultContent ??+ `User submitted: ${JSON.stringify(resolvedResponse)}`;+ }+ await this.#get().executeGatewayAgent({+ context: effectiveContext,+ message: '',+ metadata: requestMetadata,+ parentMessageId: toolMessageId,+ resumeToolResult: {+ content: toolContent,+ outcome: 'submitted',+ parentMessageId: toolMessageId,+ toolCallId,+ ...(resolvedOptions?.pluginState ? { pluginState: resolvedOptions.pluginState } : {}),+ },+ });+ }this.#writeTopicStatus(effectiveContext, 'active');this.#completeOpsById(pausedOpIds);completeOperation(operationId);@@ -816,6 +1104,7 @@ export class ConversationControlActionImpl {type: 'submitToolInteraction',message: err.message || 'Unknown error',});+ throw error;}return;}@@ -881,7 +1170,7 @@ export class ConversationControlActionImpl {// 2b. Default path: create a user message summarizing the response, resume from userconst requestMetadata = this.#getRequestMetadataFromMessageChain(toolMessageId);- const userMessageContent = Object.values(response).join(', ');+ const userMessageContent = Object.values(resolvedResponse).join(', ');const groupId = toolMessage.groupId;const userMsg = await this.#get().optimisticCreateMessage({@@ -949,6 +1238,7 @@ export class ConversationControlActionImpl {toolMessageId: string,reason?: string,context?: ConversationContext,+ options?: { onLegacyFallback?: () => Promise<void> },): Promise<void> => {const { executeClientAgent, startOperation, completeOperation } = this.#get();@@ -976,15 +1266,88 @@ export class ConversationControlActionImpl {});const optimisticContext: OptimisticUpdateContext = { operationId };+ const shouldUseGatewayResume = this.#shouldUseGatewayResume(effectiveContext);- this.#writeTopicStatus(effectiveContext, 'active');+ if (!shouldUseGatewayResume) {+ this.#writeTopicStatus(effectiveContext, 'active');+ // Park → resume: a new op continues the run paused on this tool interaction.+ this.#emitRunResumed(effectiveContext, {+ operationId,+ parentMessageId: toolMessageId,+ runtimeType: 'client',+ });+ }- // Park → resume: a new op continues the run paused on this tool interaction.- this.#emitRunResumed(effectiveContext, {- operationId,- parentMessageId: toolMessageId,- runtimeType: 'client',- });+ const toolContent = reason ? `User skipped: ${reason}` : 'User skipped this question.';++ // Gateway owns the pending-row claim. Do not persist an optimistic+ // `rejected` state first: the authoritative resume endpoint deliberately+ // accepts only pending rows, so a client-side write would make its own+ // request lose the first-winner CAS.+ if (shouldUseGatewayResume) {+ const toolCallId = toolMessage.tool_call_id;+ if (!toolCallId) {+ console.warn(+ '[skipToolInteraction][server] tool message missing tool_call_id; skipping resume',+ );+ completeOperation(operationId);+ return;+ }+ const requestMetadata = this.#getRequestMetadataFromMessageChain(toolMessageId);+ const pausedOpIds = this.#getRunningServerOps(effectiveContext).map((op) => op.id);+ try {+ const sourceResolution = await this.tryResolveAgentInterventionBySource({+ action: { type: 'skip_interaction' },+ context: effectiveContext,+ toolMessageIds: [toolMessageId],+ });+ if (this.#discardAlreadyResolvedSource(sourceResolution, operationId)) return;++ this.#emitRunResumed(effectiveContext, {+ operationId,+ parentMessageId: toolMessageId,+ runtimeType: 'gateway',+ });+ if (sourceResolution.handled) {+ if (sourceResolution.execution) {+ await this.#get().executeGatewayAgent({+ context: effectiveContext,+ message: '',+ metadata: requestMetadata,+ parentMessageId: toolMessageId,+ precreatedResult: sourceResolution.execution,+ });+ }+ } else {+ await options?.onLegacyFallback?.();+ await this.#get().executeGatewayAgent({+ context: effectiveContext,+ message: '',+ metadata: requestMetadata,+ parentMessageId: toolMessageId,+ resumeToolResult: {+ content: toolContent,+ outcome: 'skipped',+ parentMessageId: toolMessageId,+ rejectionReason: reason,+ toolCallId,+ },+ });+ }+ this.#writeTopicStatus(effectiveContext, 'active');+ this.#completeOpsById(pausedOpIds);+ completeOperation(operationId);+ } catch (error) {+ const err = error as Error;+ console.error('[skipToolInteraction][server] Gateway resume failed:', err);+ this.#get().failOperation(operationId, {+ type: 'skipToolInteraction',+ message: err.message || 'Unknown error',+ });+ throw error;+ }+ return;+ }// 1. Mark intervention as rejected (skipped) with reasonawait this.#get().optimisticUpdateMessagePlugin(@@ -993,7 +1356,6 @@ export class ConversationControlActionImpl {optimisticContext,);- const toolContent = reason ? `User skipped: ${reason}` : 'User skipped this question.';await this.#get().optimisticUpdateMessageContent(toolMessageId,toolContent,@@ -1077,6 +1439,7 @@ export class ConversationControlActionImpl {cancelToolInteraction = async (toolMessageId: string,context?: ConversationContext,+ options?: { onLegacyFallback?: () => Promise<void> },): Promise<void> => {const { startOperation, completeOperation } = this.#get();@@ -1090,6 +1453,7 @@ export class ConversationControlActionImpl {const toolMessage = dbMessageSelectors.getDbMessageById(toolMessageId)(this.#get());if (!toolMessage) return;+ const shouldUseGatewayStop = this.#shouldUseGatewayResume(effectiveContext);const { operationId } = startOperation({type: 'cancelToolInteraction',@@ -1104,6 +1468,59 @@ export class ConversationControlActionImpl {const optimisticContext = { operationId };+ // A Gateway custom cancel is terminal: recordCustomInteractionResolution+ // has already persisted the custom side effect, then this path stops the+ // authoritative parked operation and its complete sealed batch. It must+ // not merely paint the one card rejected and leave the server op waiting.+ if (shouldUseGatewayStop) {+ const batchId = toolMessage.pluginIntervention?.batchId;+ const parkedOperationId = toolMessage.pluginIntervention?.operationId;+ if (!batchId || !parkedOperationId) {+ console.warn('[cancelToolInteraction][server] missing authoritative batch identity');+ completeOperation(operationId);+ return;+ }++ const batchToolMessageIds = [+ ...new Set(+ Object.values(this.#get().dbMessagesMap)+ .flat()+ .filter(+ (message) =>+ message.role === 'tool' &&+ message.pluginIntervention?.batchId === batchId &&+ message.pluginIntervention?.operationId === parkedOperationId,+ )+ .map(({ id }) => id),+ ),+ ];+ try {+ const sourceResolution = await this.tryResolveAgentInterventionBySource({+ action: { type: 'cancel_interaction' },+ context: effectiveContext,+ toolMessageIds: [toolMessageId],+ });+ if (this.#discardAlreadyResolvedSource(sourceResolution, operationId)) return;++ if (!sourceResolution.handled) {+ await options?.onLegacyFallback?.();+ await this.stopPendingApproval(+ batchToolMessageIds.length > 0 ? batchToolMessageIds : [toolMessageId],+ effectiveContext,+ );+ }+ completeOperation(operationId);+ } catch (error) {+ const err = error as Error;+ this.#get().failOperation(operationId, {+ type: 'cancelToolInteraction',+ message: err.message || 'Unknown error',+ });+ throw error;+ }+ return;+ }+this.#writeTopicStatus(effectiveContext, 'active');await this.#get().optimisticUpdateMessagePlugin(@@ -1134,14 +1551,13 @@ export class ConversationControlActionImpl {* keeps going on its own; no synthetic user message, no new op.** The framework's intervention surface still drives the UI: we just- * stamp `pluginIntervention.status` and the eventual `tool_result`- * content via the same optimistic primitives, so the InterventionBar /- * inline tool body update synchronously and the answered Render takes- * over once `pluginIntervention.status === 'approved' | 'rejected'`.+ * stamp the local terminal state immediately. Remote submits remain+ * `pending + resolving` until the blocked producer echoes its ACK, so the+ * form stays visible and disabled across remounts without claiming success.** `actionType`:- * - `'submit'` → mark approved, ship `payload` as the answer- * - `'skip' | 'cancel'` → mark rejected, ship `cancelled: true` so the+ * - `'submit'` → ship `payload` as the answer+ * - `'skip' | 'cancel'` → ship `cancelled: true` so the* bridge resolves with `cancelReason` and CC sees an isError result* (it'll fall back to plain-text questioning)*/@@ -1160,10 +1576,75 @@ export class ConversationControlActionImpl {return;}+ const effectiveContext: ConversationContext = context ?? {+ agentId: this.#get().activeAgentId,+ topicId: this.#get().activeTopicId,+ threadId: this.#get().activeThreadId,+ };+ const originalIntervention = toolMessage.pluginIntervention;+ const originalContent = toolMessage.content;+ const interventionState = (+ toolMessage.pluginState as+ { heterogeneousIntervention?: { interactionKind?: unknown } } | undefined+ )?.heterogeneousIntervention;+ const sourceAction = toHeterogeneousSourceAction(+ actionType,+ interventionState?.interactionKind,+ payload ?? {},+ );++ // A persisted v2 card carries everything the server needs to locate and+ // authorize the intervention. Resolve it before consulting ephemeral+ // operation memory so refresh/cold-start submissions still reach the+ // durable first-winner claim. The message/runtime ids are locators only;+ // the source endpoint remains responsible for ACL and token authority.+ if (originalIntervention?.batchId && originalIntervention.operationId && sourceAction) {+ const sourceResolution = await this.tryResolveAgentInterventionBySource({+ action: sourceAction,+ context: effectiveContext,+ toolMessageIds: [toolMessageId],+ });+ if (this.#discardAlreadyResolvedSource(sourceResolution)) return;++ if (sourceResolution.handled) {+ const sourceOptimisticContext: OptimisticUpdateContext = { context: effectiveContext };+ const resolvingIntervention = {+ ...originalIntervention,+ resolving: true,+ status: 'pending' as const,+ };+ this.#get().internal_dispatchMessage(+ {+ id: toolMessageId,+ type: 'updateMessage',+ value: { pluginIntervention: resolvingIntervention },+ },+ sourceOptimisticContext,+ );+ if (toolMessage.parentId) {+ this.#get().internal_dispatchMessage(+ {+ id: toolMessage.parentId,+ tool_call_id: toolCallId,+ type: 'updateMessageTools',+ value: { intervention: resolvingIntervention },+ },+ sourceOptimisticContext,+ );+ }+ if (actionType === 'submit') {+ await this.setInterventionAnswers(toolMessageId, payload ?? {}, sourceOptimisticContext);+ }+ return;+ }+ }+// Walk up to the assistant that owns this tool. `messageOperationMap` is a// most-granular pointer, so it may reference a transient child op// (`reasoning`, `toolCalling`, ...), not the runtime execution that owns- // the AskUser bridge.+ // the AskUser bridge. This memory-only lookup is deliberately deferred+ // until the durable path is unavailable or reports `handled: false`; it is+ // provenance for local desktop IPC / legacy fallback, never server auth.const { messageOperationMap } = this.#get();const candidateOperationId =(toolMessage.parentId && messageOperationMap?.[toolMessage.parentId]) ??@@ -1180,11 +1661,6 @@ export class ConversationControlActionImpl {const { operation, operationId } =this.#resolveHeteroInterventionExecutionOperation(candidateOperationId);- const effectiveContext: ConversationContext = context ?? {- agentId: this.#get().activeAgentId,- topicId: this.#get().activeTopicId,- threadId: this.#get().activeThreadId,- };// If the operation has already been garbage-collected (e.g. the bridge// timed out earlier and `runtime_end` rolled the op into `completed`// 30s+ ago), don't pass the stale opId into the optimistic chain — the@@ -1200,8 +1676,21 @@ export class ConversationControlActionImpl {);}const optimisticContext: OptimisticUpdateContext = operationAlive ? { operationId } : {};+ const isLocalDesktopHetero = operation?.type === 'execHeterogeneousAgent';- if (actionType === 'submit') {+ if (!isLocalDesktopHetero) {+ // Publishing the user intent is not completion. Keep the interaction+ // pending but mark its in-flight phase so a remount/retry cannot present+ // an optimistic terminal state before the producer has consumed it.+ await this.#get().optimisticUpdateMessagePlugin(+ toolMessageId,+ { intervention: { resolving: true, status: 'pending' } },+ optimisticContext,+ );+ if (actionType === 'submit') {+ await this.setInterventionAnswers(toolMessageId, payload ?? {}, optimisticContext);+ }+ } else if (actionType === 'submit') {await this.#get().optimisticUpdateMessagePlugin(toolMessageId,{ intervention: { status: 'approved' } },@@ -1257,7 +1746,6 @@ export class ConversationControlActionImpl {// the question, so they are never GC'd out from under this check; that makes// "not an alive execHeterogeneousAgent op" a safe signal for "remote".// Both paths are idempotent on an unknown / already-settled toolCallId.- const isLocalDesktopHetero = operation?.type === 'execHeterogeneousAgent';try {if (isLocalDesktopHetero) {// Dynamic import keeps `@/services/electron/*` out of non-Electron bundles.@@ -1269,21 +1757,48 @@ export class ConversationControlActionImpl {: { cancelReason: 'user_cancelled', cancelled: true, operationId, toolCallId },);} else {+ const resolutionIntent = JSON.stringify(+ canonicalizeResolutionPayload({ actionType, payload: payload ?? {} }),+ );+ const resolutionKey = `${operationId}:${toolCallId}:${resolutionIntent}`;+ const resolutionRequestId =+ this.#heteroResolutionRequestIds.get(resolutionKey) ?? globalThis.crypto.randomUUID();+ this.#heteroResolutionRequestIds.set(resolutionKey, resolutionRequestId);await lambdaClient.aiAgent.submitHeteroIntervention.mutate(actionType === 'submit'- ? { operationId, result: payload ?? {}, toolCallId }- : { cancelReason: 'user_cancelled', cancelled: true, operationId, toolCallId },+ ? { operationId, resolutionRequestId, result: payload ?? {}, toolCallId }+ : {+ cancelReason: 'user_cancelled',+ cancelled: true,+ operationId,+ resolutionRequestId,+ toolCallId,+ },);}} catch (err) {console.error('[submitHeteroIntervention] submitIntervention failed:', err);+ await this.#get().optimisticUpdateMessagePlugin(+ toolMessageId,+ { intervention: originalIntervention ?? { status: 'pending' } },+ optimisticContext,+ );+ if (isLocalDesktopHetero) {+ await this.#get().optimisticUpdateMessageContent(+ toolMessageId,+ originalContent,+ undefined,+ optimisticContext,+ );+ }+ throw err;}// Sidebar topic row was swapped to the `waitingForHuman` hand icon when// the intervention was raised; once the user submits/skips/cancels the// CC stream resumes so flip it back to `running`. The natural completion// (`runtime_end` → `writeTopicStatus('active')`) takes over from there.- if (effectiveContext.topicId) {+ if (isLocalDesktopHetero && effectiveContext.topicId) {void this.#get().updateTopicStatus?.({agentId: effectiveContext.agentId,groupId: effectiveContext.groupId,@@ -1297,7 +1812,7 @@ export class ConversationControlActionImpl {* In-memory draft store for an intervention form. Backs the renderer's* "remember what I'd partially answered" behaviour without paying for a* DB round-trip on every keystroke — drafts only matter while the- * intervention is pending (5 min cap), and the canonical pluginState+ * intervention is pending (10 min cap), and the canonical pluginState* mirror is enough to survive HMR / panel re-mounts.** `askUserDraft` is irrelevant after submit (the form unmounts), so we@@ -1388,27 +1903,22 @@ export class ConversationControlActionImpl {if (!shouldUseGatewayResume) this.#writeTopicStatus(effectiveContext, 'active');- // Optimistic update - update status to rejected and save reason- const intervention = {- rejectedReason: reason,- status: 'rejected',- } as const;- await this.#get().optimisticUpdateMessagePlugin(- toolMessage.id,- { intervention },- optimisticContext,- );-const toolContent = !!reason? `User reject this tool calling with reason: ${reason}`: 'User reject this tool calling without reason';-- await this.#get().optimisticUpdateMessageContent(- messageId,- toolContent,- undefined,- optimisticContext,- );+ if (!shouldUseGatewayResume) {+ await this.#get().optimisticUpdateMessagePlugin(+ toolMessage.id,+ { intervention: { rejectedReason: reason, status: 'rejected' } },+ optimisticContext,+ );+ await this.#get().optimisticUpdateMessageContent(+ messageId,+ toolContent,+ undefined,+ optimisticContext,+ );+ }const requestMetadata = this.#getRequestMetadataFromMessageChain(messageId);// Server-mode: start a **new** Gateway op carrying the rejection.@@ -1426,29 +1936,54 @@ export class ConversationControlActionImpl {return;}const pausedOpIds = this.#getRunningServerOps(effectiveContext).map((op) => op.id);- // Park → resume: the new gateway op continues the run paused on this tool.- this.#emitRunResumed(effectiveContext, {- operationId,- parentMessageId: messageId,- runtimeType: 'gateway',- });try {- await this.#get().executeGatewayAgent({+ const sourceResolution = await this.tryResolveAgentInterventionBySource({+ action: { reason, type: 'reject_continue' },context: effectiveContext,- message: '',- metadata: requestMetadata,+ toolMessageIds: [messageId],+ });+ if (this.#discardAlreadyResolvedSource(sourceResolution, operationId)) return;++ // Park → resume: the new gateway op continues the run paused on this tool.+ this.#emitRunResumed(effectiveContext, {+ operationId,parentMessageId: messageId,- resumeApproval: {- decision: 'rejected_continue',- parentMessageId: messageId,- rejectionReason: reason,- toolCallId,- },+ runtimeType: 'gateway',});+ if (sourceResolution.handled) {+ if (sourceResolution.execution) {+ await this.#get().executeGatewayAgent({+ context: effectiveContext,+ message: '',+ metadata: requestMetadata,+ parentMessageId: messageId,+ precreatedResult: sourceResolution.execution,+ });+ }+ } else {+ await this.#get().executeGatewayAgent({+ context: effectiveContext,+ message: '',+ metadata: requestMetadata,+ parentMessageId: messageId,+ resumeApproval: {+ decision: 'rejected_continue',+ parentMessageId: messageId,+ rejectionReason: reason,+ toolCallId,+ },+ });+ }this.#writeTopicStatus(effectiveContext, 'active');this.#completeOpsById(pausedOpIds);} catch (error) {- console.error('[rejectToolCalling][server] Gateway resume failed:', error);+ const err = error as Error;+ console.error('[rejectToolCalling][server] Gateway resume failed:', err);+ this.#get().failOperation(operationId, {+ type: 'rejectToolCalling',+ message: err.message || 'Unknown error',+ });+ throw error;}}@@ -1502,41 +2037,44 @@ export class ConversationControlActionImpl {},});- const optimisticContext = { operationId };- // Park → resume: the new gateway op continues the run paused on this tool.- this.#emitRunResumed(effectiveContext, {- operationId,- parentMessageId: messageId,- runtimeType: 'gateway',- });- await this.#get().optimisticUpdateMessagePlugin(- messageId,- { intervention: { rejectedReason: reason, status: 'rejected' } as any },- optimisticContext,- );- const toolContent = reason- ? `User reject this tool calling with reason: ${reason}`- : 'User reject this tool calling without reason';- await this.#get().optimisticUpdateMessageContent(- messageId,- toolContent,- undefined,- optimisticContext,- );-try {- await this.#get().executeGatewayAgent({+ const sourceResolution = await this.tryResolveAgentInterventionBySource({+ action: { reason, type: 'reject_continue' },context: effectiveContext,- message: '',- metadata: requestMetadata,+ toolMessageIds: [messageId],+ });+ if (this.#discardAlreadyResolvedSource(sourceResolution, operationId)) return;++ // Park → resume: the new gateway op continues the run paused on this tool.+ this.#emitRunResumed(effectiveContext, {+ operationId,parentMessageId: messageId,- resumeApproval: {- decision: 'rejected_continue',- parentMessageId: messageId,- rejectionReason: reason,- toolCallId,- },+ runtimeType: 'gateway',});+ if (sourceResolution.handled) {+ if (sourceResolution.execution) {+ await this.#get().executeGatewayAgent({+ context: effectiveContext,+ message: '',+ metadata: requestMetadata,+ parentMessageId: messageId,+ precreatedResult: sourceResolution.execution,+ });+ }+ } else {+ await this.#get().executeGatewayAgent({+ context: effectiveContext,+ message: '',+ metadata: requestMetadata,+ parentMessageId: messageId,+ resumeApproval: {+ decision: 'rejected_continue',+ parentMessageId: messageId,+ rejectionReason: reason,+ toolCallId,+ },+ });+ }this.#writeTopicStatus(effectiveContext, 'active');this.#completeOpsById(pausedOpIds);completeOperation(operationId);@@ -1547,6 +2085,7 @@ export class ConversationControlActionImpl {type: 'rejectToolCalling',message: err.message || 'Unknown error',});+ throw error;}return;}diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex e4c58601a03..45d8c2f6902 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -435,6 +435,12 @@ export class GatewayActionImpl {optimisticTopic?: { id: string; metadata?: ChatTopicMetadata; title: string };/** Parent message ID for regeneration/continue (skip user message creation, branch from this message) */parentMessageId?: string;+ /**+ * Operation already created by the generic intervention claim+dispatch+ * endpoint. The client adopts it here so streaming setup stays identical+ * without issuing a second legacy resume request.+ */+ precreatedResult?: ExecAgentResult;/** Server operation whose visible output ended before this fresh turn. */replacesOperationId?: string;/**@@ -503,6 +509,7 @@ export class GatewayActionImpl {optimisticTopic,parentMessageId,parentOperationId,+ precreatedResult,replacesOperationId,resumeApproval,resumeApprovals,@@ -574,67 +581,69 @@ export class GatewayActionImpl {throw abortSignal.reason ?? new DOMException('Aborted', 'AbortError');}- const result = await aiAgentService.execAgentTask(- {- agentId: executionContext.agentId,- // Fresh sends only — resume flows never pass this, and the server drops- // it defensively on resume-like params anyway.- clientIds,- appContext: {- agentDocumentId: executionContext.agentDocumentId,- ...(messageContext.agentId !== executionContext.agentId && {- conversationAgentId: messageContext.agentId,- }),- defaultTaskAssigneeAgentId: executionContext.defaultTaskAssigneeAgentId,- documentId: executionContext.documentId,- // When AgentBuilder runs, context.agentId is the builtin builder agent.- // The actual editing target is chatStore.activeAgentId (kept in sync by- // AgentBuilderProvider). Pass it so the server can route tool calls to- // the correct agent rather than the builder itself.- ...(executionContext.scope === 'agent_builder' && {- editingAgentId: this.#get().activeAgentId ?? undefined,- }),- // Same shape as `editingAgentId`, for the Group Agent Builder panel on- // the group Profile page. The builder conversation is keyed by the- // builtin builder agent (no groupId in its ConversationContext, so the- // message map key and the group's own chat stay separate), which left- // the server runtime with no idea which group it was editing.- // The context value wins, and every surface that opens this scope sets- // it from its own route/group: it is fixed for the run, so a mid-run- // navigation cannot make the server stamp a different group than the- // panel is reading from. The `activeGroupId` fallback is a last resort- // for a caller that forgot — it is sampled here, AFTER the async- // preflight above, so it can already be stale by this point.- ...(executionContext.scope === 'group_agent_builder' && {- editingGroupId: executionContext.editingGroupId ?? this.#get().activeGroupId,- }),- groupId: executionContext.groupId,- ...(initialTopicMetadata && { initialTopicMetadata }),- // Forward the group orchestration role so the server can stamp it onto- // the assistant message metadata. Without this the gateway-created- // supervisor turn loses its role on the step_start snapshot / refetch- // and renders as a generic assistant.- orchestrationRole: executionContext.orchestrationRole,- scope: executionContext.scope,- taskId,- threadId: executionContext.threadId,- topicId: executionContext.topicId,+ const result =+ precreatedResult ??+ (await aiAgentService.execAgentTask(+ {+ agentId: executionContext.agentId,+ // Fresh sends only — resume flows never pass this, and the server drops+ // it defensively on resume-like params anyway.+ clientIds,+ appContext: {+ agentDocumentId: executionContext.agentDocumentId,+ ...(messageContext.agentId !== executionContext.agentId && {+ conversationAgentId: messageContext.agentId,+ }),+ defaultTaskAssigneeAgentId: executionContext.defaultTaskAssigneeAgentId,+ documentId: executionContext.documentId,+ // When AgentBuilder runs, context.agentId is the builtin builder agent.+ // The actual editing target is chatStore.activeAgentId (kept in sync by+ // AgentBuilderProvider). Pass it so the server can route tool calls to+ // the correct agent rather than the builder itself.+ ...(executionContext.scope === 'agent_builder' && {+ editingAgentId: this.#get().activeAgentId ?? undefined,+ }),+ // Same shape as `editingAgentId`, for the Group Agent Builder panel on+ // the group Profile page. The builder conversation is keyed by the+ // builtin builder agent (no groupId in its ConversationContext, so the+ // message map key and the group's own chat stay separate), which left+ // the server runtime with no idea which group it was editing.+ // The context value wins, and every surface that opens this scope sets+ // it from its own route/group: it is fixed for the run, so a mid-run+ // navigation cannot make the server stamp a different group than the+ // panel is reading from. The `activeGroupId` fallback is a last resort+ // for a caller that forgot — it is sampled here, AFTER the async+ // preflight above, so it can already be stale by this point.+ ...(executionContext.scope === 'group_agent_builder' && {+ editingGroupId: executionContext.editingGroupId ?? this.#get().activeGroupId,+ }),+ groupId: executionContext.groupId,+ ...(initialTopicMetadata && { initialTopicMetadata }),+ // Forward the group orchestration role so the server can stamp it onto+ // the assistant message metadata. Without this the gateway-created+ // supervisor turn loses its role on the step_start snapshot / refetch+ // and renders as a generic assistant.+ orchestrationRole: executionContext.orchestrationRole,+ scope: executionContext.scope,+ taskId,+ threadId: executionContext.threadId,+ topicId: executionContext.topicId,+ },+ ...desktopDeviceHints,+ fileIds,+ replacesOperationId,+ mentionedAgents,+ parentMessageId,+ prompt: message,+ resumeApproval,+ resumeApprovals,+ resumeToolResult,+ selectedToolIds,+ trigger: metadata?.trigger,+ userInterventionConfig,},- ...desktopDeviceHints,- fileIds,- replacesOperationId,- mentionedAgents,- parentMessageId,- prompt: message,- resumeApproval,- resumeApprovals,- resumeToolResult,- selectedToolIds,- trigger: metadata?.trigger,- userInterventionConfig,- },- { signal: abortSignal },- );+ { signal: abortSignal },+ ));// 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.diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.test.tsindex 7b999678621..3f5134bf527 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.test.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.test.ts@@ -1026,4 +1026,114 @@ describe('createGatewayEventHandler', () => {expect(lifecycle.afterRunComplete).not.toHaveBeenCalled();});++ it('keeps a modern intervention resolving until the producer ACK arrives', async () => {+ const key = messageMapKey(context);+ const getMessages = vi+ .spyOn(messageService, 'getMessages')+ .mockResolvedValue([] as unknown as UIChatMessage[]);+ const updateMessagePlugin = vi.spyOn(messageService, 'updateMessagePlugin');+ const store = createStore({+ [key]: [+ {+ content: '',+ id: 'permission-message',+ parentId: 'answer-msg',+ pluginIntervention: {+ batchId: 'batch-1',+ operationId: 'op-1',+ status: 'pending',+ },+ role: 'tool',+ tool_call_id: 'permission-1',+ } as UIChatMessage,+ ],+ });+ store.updateTopicStatus = vi.fn().mockResolvedValue(undefined);+ const handler = createGatewayEventHandler(() => store, {+ assistantMessageId: 'answer-msg',+ context,+ operationId: 'op-1',+ runtimeType: 'hetero',+ });+ const resolutionRequestId = '018fbd8e-7baf-7c6d-8000-000000000001';++ handler(+ makeEvent('agent_intervention_request', {+ apiName: 'askUserQuestion',+ arguments: '{"questions":[]}',+ deadline: Date.now() + 60_000,+ identifier: 'claude-code',+ interactionKind: 'permission',+ provider: 'cursor',+ toolCallId: 'permission-1',+ }),+ );+ await flush();+ expect(store.updateTopicStatus).toHaveBeenLastCalledWith(+ expect.objectContaining({ status: 'waitingForHuman', topicId: 'topic-1' }),+ );++ vi.mocked(store.updateTopicStatus!).mockClear();+ getMessages.mockClear();+ handler(+ makeEvent('agent_intervention_response', {+ producerAck: false,+ resolutionRequestId,+ result: { approved: true },+ toolCallId: 'permission-1',+ }),+ );+ await flush();+ expect(store.internal_dispatchMessage).toHaveBeenCalledWith(+ {+ id: 'permission-message',+ type: 'updateMessage',+ value: {+ pluginIntervention: {+ batchId: 'batch-1',+ operationId: 'op-1',+ resolving: true,+ status: 'pending',+ },+ },+ },+ { context },+ );+ expect(store.internal_dispatchMessage).toHaveBeenCalledWith(+ {+ id: 'answer-msg',+ tool_call_id: 'permission-1',+ type: 'updateMessageTools',+ value: {+ intervention: {+ batchId: 'batch-1',+ operationId: 'op-1',+ resolving: true,+ status: 'pending',+ },+ },+ },+ { context },+ );+ expect(store.updateTopicStatus).toHaveBeenLastCalledWith(+ expect.objectContaining({ status: 'waitingForHuman', topicId: 'topic-1' }),+ );+ expect(updateMessagePlugin).not.toHaveBeenCalled();+ expect(getMessages).not.toHaveBeenCalled();++ handler(+ makeEvent('agent_intervention_response', {+ producerAck: true,+ resolutionRequestId,+ result: { approved: true },+ toolCallId: 'permission-1',+ }),+ );+ await flush();+ expect(getMessages).toHaveBeenCalledWith({ ...context, skipWorks: true });+ expect(store.updateTopicStatus).toHaveBeenLastCalledWith(+ expect.objectContaining({ status: 'running', topicId: 'topic-1' }),+ );+ });});diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.tsindex cd50e607e10..e5a67ff6b5c 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts@@ -1,4 +1,6 @@import type {+ AgentInterventionRequestData,+ AgentInterventionResponseData,AgentStreamEvent,StepCompleteData,StreamChunkData,@@ -439,6 +441,7 @@ export const createGatewayEventHandler = (const toolStateBootstrapPromiseByCallId = new Map<string, Promise<void>>();const lastAppliedToolStateSeqByCallId = new Map<string, number>();const completedToolStateCallIds = new Set<string>();+ const pendingInterventionToolCallIds = new Set<string>();// Tracks whether any server-confirmed state has actually arrived// (server-assigned assistant id, streamed text/reasoning/tools, or a SoT@@ -481,6 +484,22 @@ export const createGatewayEventHandler = (return processingChain;};+ const writeTopicStatus = (status: 'running' | 'waitingForHuman') => {+ if (!context.topicId) return;+ const statusWrite = get().updateTopicStatus?.({+ agentId: context.agentId,+ groupId: context.groupId,+ ...(context.scope === 'group' || context.scope === 'group_agent'+ ? { scope: context.scope }+ : {}),+ status,+ topicId: context.topicId,+ });+ void statusWrite?.catch((error) => {+ console.error('[gatewayEventHandler] updateTopicStatus failed:', error);+ });+ };+const getToolMessageByCallId = (toolCallId: string): UIChatMessage | undefined => {const messages = get().dbMessagesMap[messageMapKey(context)] ?? [];// Tool-call ids are operation-scoped, not topic-global. Codex can reuse an@@ -912,6 +931,83 @@ export const createGatewayEventHandler = (break;}+ case 'agent_intervention_request': {+ const data = event.data as AgentInterventionRequestData | undefined;+ if (!data?.toolCallId) break;++ pendingInterventionToolCallIds.add(data.toolCallId);+ writeTopicStatus('waitingForHuman');+ void notifyDesktopHumanApprovalRequired(get, context);++ // Server persistence runs before stream publish. Reconcile from DB so+ // both the inline tool and global InterventionBar see `pending`, even+ // when this request raced ahead of the provider's tools_calling event.+ enqueue(async () => {+ await fetchAndReplaceMessages(get, context, { skipWorks: true }).catch(console.error);+ hasStreamedContent = true;+ });+ break;+ }++ case 'agent_intervention_response': {+ const data = event.data as AgentInterventionResponseData | undefined;+ if (!data?.toolCallId) break;++ // A modern submit response is a producer-delivery leg, not completion.+ // Keep the topic/card waiting until the producer echoes producerAck.+ // Older responses had no request id and remain terminal-compatible.+ if (data.resolutionRequestId && data.producerAck !== true) {+ pendingInterventionToolCallIds.add(data.toolCallId);+ writeTopicStatus('waitingForHuman');+ enqueue(async () => {+ const toolMessage = getToolMessageByCallId(data.toolCallId);+ if (!toolMessage) return;+ const intervention = {+ ...toolMessage.pluginIntervention,+ resolving: true,+ status: 'pending' as const,+ };++ // The inline parent tool reads plugin.intervention, while the+ // global approval collector reads the durable tool row's top-level+ // pluginIntervention. Update both local projections immediately so+ // every subscribed surface becomes non-actionable. Do not persist+ // this subscriber hint: a slow write could overwrite a later+ // producer-ACK terminal state.+ get().internal_dispatchMessage(+ {+ id: toolMessage.id,+ type: 'updateMessage',+ value: { pluginIntervention: intervention },+ },+ { context },+ );+ if (toolMessage.parentId && toolMessage.tool_call_id) {+ get().internal_dispatchMessage(+ {+ id: toolMessage.parentId,+ tool_call_id: toolMessage.tool_call_id,+ type: 'updateMessageTools',+ value: { intervention },+ },+ { context },+ );+ }+ });+ break;+ }++ pendingInterventionToolCallIds.delete(data.toolCallId);+ enqueue(async () => {+ // Successful Web submits, explicit cancellation, producer timeout,+ // and session teardown all converge on the durable tool row before+ // this refresh. Do not infer the terminal state from identifier.+ await fetchAndReplaceMessages(get, context, { skipWorks: true }).catch(console.error);+ if (pendingInterventionToolCallIds.size === 0) writeTopicStatus('running');+ });+ break;+ }+case 'step_start': {const data = event.data as {pendingToolsCalling?: unknown[];@@ -946,20 +1042,7 @@ export const createGatewayEventHandler = (void notifyDesktopHumanApprovalRequired(get, context);// Persist the explicit "needs user input" marker so the sidebar swaps// the running spinner for the hand icon across reloads.- if (context.topicId) {- const statusWrite = get().updateTopicStatus?.({- agentId: context.agentId,- groupId: context.groupId,- ...(context.scope === 'group' || context.scope === 'group_agent'- ? { scope: context.scope }- : {}),- status: 'waitingForHuman',- topicId: context.topicId,- });- void statusWrite?.catch((error) => {- console.error('[gatewayEventHandler] updateTopicStatus failed:', error);- });- }+ writeTopicStatus('waitingForHuman');}break;