Skip to content

🀯 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.

πŸ› fix(agent-runtime): keep the answered run's approval mode in intervention continuations (#19991)

Arvin Xu9e752d45fecc
diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIntervention.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIntervention.test.ts
index 8fbf7a2d24e..5beec551a78 100644
--- a/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIntervention.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIntervention.test.ts
@@ -1,6 +1,6 @@
// @vitest-environment node
import { type LobeChatDatabase } from '@lobechat/database';
-import { agents, messagePlugins, messages, topics } from '@lobechat/database/schemas';
+import { agents, messagePlugins, messages, topics, userSettings } from '@lobechat/database/schemas';
import { getTestDB } from '@lobechat/database/test-utils';
import { AskUserBridge } from '@lobechat/heterogeneous-agents/askUser';
import { eq } from 'drizzle-orm';
@@ -884,6 +884,199 @@ describe('aiAgentRouter β€” remote Human-in-the-loop', () => {
expect(businessV2.rollbackAgentInterventionResolution).not.toHaveBeenCalled();
});
+ describe('continuation approval mode', () => {
+ const execution = {
+ autoStarted: true,
+ messageId: 'assistant-continuation',
+ operationId: 'operation-continuation',
+ success: true,
+ };
+
+ const resolveToolResult = async (params: {
+ resolutionRequestId: string;
+ sourceOperationId: string;
+ }) => {
+ await insertPendingTool({
+ batchId: `batch-${params.sourceOperationId}`,
+ messageId: 'assistant-runtime',
+ operationId: params.sourceOperationId,
+ toolCallId: 'tool-runtime',
+ });
+ businessV2.resolveAgentIntervention.mockResolvedValueOnce({
+ claimId: `claim-${params.sourceOperationId}`,
+ contractVersion: 2,
+ handled: true,
+ ownerUserId: userId,
+ resolutionRequestId: params.resolutionRequestId,
+ runtimeAction: {
+ agentId: 'agent-runtime',
+ appContext: { topicId: 'topic-runtime' },
+ content: '{"answer":"A"}',
+ operationId: params.sourceOperationId,
+ outcome: 'submitted',
+ parentMessageId: 'assistant-runtime',
+ toolCallId: 'tool-runtime',
+ type: 'resume_tool_result',
+ },
+ state: 'claimed',
+ });
+ aiAgentService.execAgent.mockResolvedValueOnce(execution);
+
+ await userCaller().resolveAgentIntervention({
+ action: { itemId: 'item-runtime', type: 'skip_interaction' },
+ expectedBatchVersion: 1,
+ expectedRequestRevisions: {
+ 'item-runtime': { hash: 'c'.repeat(64), version: 1 },
+ },
+ resolutionRequestId: params.resolutionRequestId,
+ reviewToken: 'g'.repeat(43),
+ });
+ };
+
+ const stateFor = (sourceOperationId: string, state: unknown) =>
+ aiAgentService.loadInterventionContinuationState.mockImplementation(async (id: string) =>
+ id === sourceOperationId ? state : null,
+ );
+
+ it('inherits the interactive approval mode of the answered run for a tool-result continuation', async () => {
+ const sourceOperationId = 'operation-interactive-source';
+ stateFor(sourceOperationId, {
+ operationId: sourceOperationId,
+ principal: {
+ policy: {
+ userIntervention: { allowList: ['lobe-web-browsing'], approvalMode: 'manual' },
+ },
+ },
+ status: 'waiting_for_human',
+ });
+
+ await resolveToolResult({
+ resolutionRequestId: '018fbd8e-7baf-7c6d-8000-000000000041',
+ sourceOperationId,
+ });
+
+ // A follow-up askUserQuestion in the continuation must be able to wait for
+ // the user again instead of being blocked as a headless run.
+ expect(aiAgentService.execAgent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ userInterventionConfig: { allowList: ['lobe-web-browsing'], approvalMode: 'manual' },
+ }),
+ );
+ });
+
+ it('carries a just-remembered tool approval into the continuation allow list', async () => {
+ const sourceOperationId = 'operation-remember-source';
+ stateFor(sourceOperationId, {
+ operationId: sourceOperationId,
+ principal: {
+ policy: {
+ userIntervention: { allowList: ['lobe-web-browsing'], approvalMode: 'allow-list' },
+ },
+ },
+ status: 'waiting_for_human',
+ });
+ // "Approve, and don't ask again" persisted this key before dispatch; the
+ // parked run's snapshot does not have it yet.
+ await serverDB
+ .insert(userSettings)
+ .values({
+ id: userId,
+ tool: {
+ humanIntervention: {
+ allowList: ['lobe-web-browsing', 'lobe-local-system____runCommand'],
+ approvalMode: 'allow-list',
+ },
+ },
+ })
+ .onConflictDoUpdate({
+ set: {
+ tool: {
+ humanIntervention: {
+ allowList: ['lobe-web-browsing', 'lobe-local-system____runCommand'],
+ approvalMode: 'allow-list',
+ },
+ },
+ },
+ target: userSettings.id,
+ });
+
+ await resolveToolResult({
+ resolutionRequestId: '018fbd8e-7baf-7c6d-8000-000000000044',
+ sourceOperationId,
+ });
+
+ expect(aiAgentService.execAgent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ userInterventionConfig: {
+ allowList: ['lobe-web-browsing', 'lobe-local-system____runCommand'],
+ approvalMode: 'allow-list',
+ },
+ }),
+ );
+ });
+
+ it("falls back to the owner's interactive preference when the answered run state is gone", async () => {
+ const reviewToken = 'h'.repeat(43);
+ const resolutionRequestId = '018fbd8e-7baf-7c6d-8000-000000000042';
+ await insertPendingTool({
+ batchId: 'batch-expired-source',
+ messageId: 'assistant-runtime',
+ operationId: 'operation-expired-source',
+ toolCallId: 'tool-1',
+ });
+ businessV2.resolveAgentIntervention.mockResolvedValueOnce({
+ claimId: 'claim-expired-source',
+ contractVersion: 2,
+ handled: true,
+ ownerUserId: userId,
+ resolutionRequestId,
+ runtimeAction: {
+ agentId: 'agent-runtime',
+ appContext: { topicId: 'topic-runtime' },
+ decisions: [
+ { decision: 'approved', parentMessageId: 'assistant-runtime', toolCallId: 'tool-1' },
+ ],
+ operationId: 'operation-expired-source',
+ parentMessageId: 'assistant-runtime',
+ type: 'resume_approval',
+ },
+ state: 'claimed',
+ });
+ aiAgentService.execAgent.mockResolvedValueOnce(execution);
+
+ await userCaller().resolveAgentIntervention({
+ action: { itemIds: ['item-runtime'], scope: 'once', type: 'approve_tool' },
+ expectedBatchVersion: 1,
+ expectedRequestRevisions: {
+ 'item-runtime': { hash: 'b'.repeat(64), version: 1 },
+ },
+ resolutionRequestId,
+ reviewToken,
+ });
+
+ const [params] = aiAgentService.execAgent.mock.calls[0];
+ expect(params.userInterventionConfig).toEqual({ allowList: [], approvalMode: 'manual' });
+ });
+
+ it('keeps a continuation headless when the answered run was headless', async () => {
+ const sourceOperationId = 'operation-headless-source';
+ stateFor(sourceOperationId, {
+ operationId: sourceOperationId,
+ principal: { policy: { userIntervention: { approvalMode: 'headless' } } },
+ status: 'waiting_for_human',
+ });
+
+ await resolveToolResult({
+ resolutionRequestId: '018fbd8e-7baf-7c6d-8000-000000000043',
+ sourceOperationId,
+ });
+
+ expect(aiAgentService.execAgent).toHaveBeenCalledWith(
+ expect.objectContaining({ userInterventionConfig: { approvalMode: 'headless' } }),
+ );
+ });
+ });
+
it('retries only the published transition after runtime dispatch already settled the source', async () => {
const reviewToken = 'f'.repeat(43);
const messageId = 'message-published-retry';
diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.ts
index d07a4a4e79c..ffc96d53262 100644
--- a/apps/server/src/routers/lambda/aiAgent.ts
+++ b/apps/server/src/routers/lambda/aiAgent.ts
@@ -1,11 +1,18 @@
import { randomUUID } from 'node:crypto';
import { type AgentStreamEvent } from '@lobechat/agent-gateway-client';
+import { selectUserInterventionConfig } from '@lobechat/agent-runtime';
import { LOADING_FLAT } from '@lobechat/const';
import { isFullAccessApiKey } from '@lobechat/const/apiKeyScope';
import { parse } from '@lobechat/conversation-flow';
import { getServerDefaultHeterogeneousAgentConfig } from '@lobechat/heterogeneous-agents';
-import type { ExecAgentResult, TaskCurrentActivity, TaskStatusResult } from '@lobechat/types';
+import type {
+ ExecAgentResult,
+ TaskCurrentActivity,
+ TaskStatusResult,
+ UserInterventionConfig,
+ UserToolConfig,
+} from '@lobechat/types';
import {
CreateThreadWithMessageSchema,
entityIdPattern,
@@ -460,6 +467,54 @@ const repairRuntimeActionContinuationAnchor = async (
});
};
+/**
+ * The approval mode a continuation runs under. A continuation carries on the
+ * run the user just answered, so it inherits that run's intervention policy β€”
+ * otherwise `execAgent` falls back to `headless` and the next question or
+ * approval in the continuation is blocked instead of waiting for the user.
+ *
+ * When the parked run's state has already expired, fall back to the owner's
+ * foreground approval preference: only a run that could wait for a human can
+ * park on an intervention, so the answered run was never headless.
+ *
+ * The owner's persisted allow list is merged in either way: an "Approve, and
+ * don't ask again" answer writes the tool key there before this dispatch, and
+ * the snapshot in the parked run predates it.
+ */
+const resolveContinuationUserInterventionConfig = async (
+ resolution: ClaimedAgentInterventionResolution,
+ sourceOperationId: string,
+ ctx: AgentInterventionDispatchContext,
+): Promise<UserInterventionConfig> => {
+ const [sourceState, settings] = await Promise.all([
+ ctx.aiAgentService.loadInterventionContinuationState(sourceOperationId).catch((error) => {
+ log('failed to load source state for %s: %O', sourceOperationId, error);
+ return null;
+ }),
+ new UserModel(ctx.serverDB, resolution.ownerUserId).getUserSettings().catch((error) => {
+ log('failed to load intervention settings for %s: %O', resolution.ownerUserId, error);
+ return undefined;
+ }),
+ ]);
+ const intervention = (settings?.tool as UserToolConfig | undefined)?.humanIntervention;
+ const persistedAllowList = intervention?.allowList ?? [];
+
+ const inherited = sourceState ? selectUserInterventionConfig(sourceState) : undefined;
+ if (inherited) {
+ const inheritedAllowList = inherited.allowList ?? [];
+ const remembered = persistedAllowList.filter((key) => !inheritedAllowList.includes(key));
+ if (remembered.length === 0) return inherited;
+ return { ...inherited, allowList: [...inheritedAllowList, ...remembered] };
+ }
+
+ const approvalMode =
+ intervention?.approvalMode === 'headless'
+ ? 'auto-run'
+ : (intervention?.approvalMode ?? 'manual');
+
+ return { allowList: persistedAllowList, approvalMode };
+};
+
/**
* 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
@@ -520,6 +575,10 @@ const dispatchClaimedAgentIntervention = async (
* continuation lands in route attempt logs with an unknown source.
*/
const continuationTrigger = RequestTrigger.Chat;
+ const continuation = continuationRuntimeAction(runtimeAction);
+ const userInterventionConfig = continuation
+ ? await resolveContinuationUserInterventionConfig(resolution, continuation.operationId, ctx)
+ : undefined;
switch (runtimeAction.type) {
case 'execute_custom_interaction': {
@@ -564,6 +623,7 @@ const dispatchClaimedAgentIntervention = async (
},
topicStartReservationId: deterministicContinuationOperationId,
trigger: continuationTrigger,
+ userInterventionConfig,
});
}
break;
@@ -593,6 +653,7 @@ const dispatchClaimedAgentIntervention = async (
: { resumeApprovals: runtimeAction.decisions }),
topicStartReservationId: deterministicContinuationOperationId,
trigger: continuationTrigger,
+ userInterventionConfig,
});
break;
}
@@ -617,6 +678,7 @@ const dispatchClaimedAgentIntervention = async (
},
topicStartReservationId: deterministicContinuationOperationId,
trigger: continuationTrigger,
+ userInterventionConfig,
});
break;
}