🤯 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(intervention): switch to auto approve from the approval card (#22122)
Arvin Xu51247c915261
diff --git a/apps/server/src/routers/lambda/aiAgent/continuationInterventionConfig.test.ts b/apps/server/src/routers/lambda/aiAgent/continuationInterventionConfig.test.tsnew file mode 100644index 00000000000..66647617405--- /dev/null+++ b/apps/server/src/routers/lambda/aiAgent/continuationInterventionConfig.test.ts@@ -0,0 +1,56 @@+import { describe, expect, it } from 'vitest';++import { mergeContinuationUserInterventionConfig } from './continuationInterventionConfig';++describe('mergeContinuationUserInterventionConfig', () => {+ it('keeps the parked run snapshot when nothing changed since it parked', () => {+ const inherited = { allowList: ['a/b'], approvalMode: 'manual' as const };++ expect(+ mergeContinuationUserInterventionConfig({+ inherited,+ persisted: { allowList: ['a/b'], approvalMode: 'manual' },+ }),+ ).toBe(inherited);+ });++ it('merges a just-remembered tool into the allow list', () => {+ expect(+ mergeContinuationUserInterventionConfig({+ inherited: { allowList: ['a/b'], approvalMode: 'allow-list' },+ persisted: { allowList: ['a/b', 'c/d'], approvalMode: 'allow-list' },+ }),+ ).toEqual({ allowList: ['a/b', 'c/d'], approvalMode: 'allow-list' });+ });++ it.each(['manual', 'allow-list'] as const)(+ 'lifts a %s run to auto-run after the owner switched to auto approve',+ (approvalMode) => {+ expect(+ mergeContinuationUserInterventionConfig({+ inherited: { allowList: [], approvalMode },+ persisted: { allowList: [], approvalMode: 'auto-run' },+ }),+ ).toEqual({ allowList: [], approvalMode: 'auto-run' });+ },+ );++ it('never turns a headless run back into an interactive one', () => {+ expect(+ mergeContinuationUserInterventionConfig({+ inherited: { approvalMode: 'headless' },+ persisted: { approvalMode: 'auto-run' },+ }),+ ).toEqual({ approvalMode: 'headless' });+ });++ it("falls back to the owner's foreground preference when the snapshot is gone", () => {+ expect(mergeContinuationUserInterventionConfig({})).toEqual({+ allowList: [],+ approvalMode: 'manual',+ });+ expect(+ mergeContinuationUserInterventionConfig({ persisted: { approvalMode: 'headless' } }),+ ).toEqual({ allowList: [], approvalMode: 'auto-run' });+ });+});diff --git a/apps/server/src/routers/lambda/aiAgent/continuationInterventionConfig.ts b/apps/server/src/routers/lambda/aiAgent/continuationInterventionConfig.tsnew file mode 100644index 00000000000..737b5b23022--- /dev/null+++ b/apps/server/src/routers/lambda/aiAgent/continuationInterventionConfig.ts@@ -0,0 +1,51 @@+import type { UserInterventionConfig, UserToolConfig } from '@lobechat/types';++type PersistedIntervention = NonNullable<UserToolConfig['humanIntervention']>;++/**+ * The owner's intervention config for a continuation, given the parked run's+ * snapshot (`inherited`) and the owner's persisted preference (`persisted`).+ *+ * The continuation inherits the parked run's policy, with two answers the user+ * may have given on the approval card itself, both persisted before dispatch:+ * - "Approve, and don't ask again" appended a tool key to the allow list;+ * - "Switch to auto approve" moved the preference to `auto-run`, which lifts a+ * manual / allow-list run (never a headless one, which cannot park anyway).+ *+ * Without a snapshot (expired state) the owner's foreground preference applies:+ * only a run that could wait for a human parks, so it was never headless.+ */+export const mergeContinuationUserInterventionConfig = ({+ inherited,+ persisted,+}: {+ inherited?: UserInterventionConfig;+ persisted?: PersistedIntervention;+}): UserInterventionConfig => {+ const persistedAllowList = persisted?.allowList ?? [];+ const persistedAutoRun =+ persisted?.approvalMode === 'auto-run' || persisted?.approvalMode === 'headless';++ if (!inherited) {+ return {+ allowList: persistedAllowList,+ approvalMode: persistedAutoRun ? 'auto-run' : (persisted?.approvalMode ?? 'manual'),+ };+ }++ let config = inherited;++ const inheritedAllowList = inherited.allowList ?? [];+ const remembered = persistedAllowList.filter((key) => !inheritedAllowList.includes(key));+ if (remembered.length > 0) {+ config = { ...config, allowList: [...inheritedAllowList, ...remembered] };+ }++ const interactive =+ !inherited.approvalMode ||+ inherited.approvalMode === 'manual' ||+ inherited.approvalMode === 'allow-list';+ if (persistedAutoRun && interactive) config = { ...config, approvalMode: 'auto-run' };++ return config;+};diff --git a/apps/server/src/routers/lambda/aiAgent/interventionDispatch.ts b/apps/server/src/routers/lambda/aiAgent/interventionDispatch.tsindex 7a5561298ab..bb86b9dbacd 100644--- a/apps/server/src/routers/lambda/aiAgent/interventionDispatch.ts+++ b/apps/server/src/routers/lambda/aiAgent/interventionDispatch.ts@@ -25,6 +25,8 @@ import { createStreamEventManager } from '@/server/modules/AgentRuntime/factory'import type { AiAgentService } from '@/server/services/aiAgent';import type { AgentShareGate } from '@/server/services/aiAgent/shareGate';+import { mergeContinuationUserInterventionConfig } from './continuationInterventionConfig';+const log = debug('lobe-server:ai-agent-router');/** Each expected claim is a separate plugin read; a large batch must not open them all at once. */@@ -421,9 +423,9 @@ const repairRuntimeActionContinuationAnchor = async (* 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.+ * The owner's answers on the approval card itself ("don't ask again", "switch+ * to auto approve") are persisted before this dispatch and the parked run's+ * snapshot predates them — see `mergeContinuationUserInterventionConfig`.** A share visitor's continuation uses neither owner fallback: the parked run* carries the VISITOR's approval mode, a visitor can never "remember" into@@ -445,24 +447,13 @@ const resolveContinuationUserInterventionConfig = async (return undefined;}),]);- const intervention = (settings?.tool as UserToolConfig | undefined)?.humanIntervention;- const persistedAllowList = intervention?.allowList ?? [];-const inherited = sourceState ? selectUserInterventionConfig(sourceState) : undefined;if (ctx.shareGate) return inherited ?? { approvalMode: 'manual' };- 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 };+ return mergeContinuationUserInterventionConfig({+ inherited,+ persisted: (settings?.tool as UserToolConfig | undefined)?.humanIntervention,+ });};/**diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 44bf5a283eb..b03f26c3e3c 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -2930,6 +2930,8 @@"tool.intervention.stop": "Stop","tool.intervention.stopTooltip": "Stop here — nothing pending runs and the agent does not continue","tool.intervention.submit": "Submit",+ "tool.intervention.switchToAutoRun": "Switch to auto approve",+ "tool.intervention.switchToAutoRunDesc": "Approve this call and stop asking from now on. Calls that must always ask still ask.","tool.intervention.toolAbort": "You canceled this Skill call","tool.intervention.toolEnded": "This tool call has ended","tool.intervention.toolRejected": "This Skill call was rejected",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 3c6a21f7da9..f12d227565f 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -2930,6 +2930,8 @@"tool.intervention.stop": "停止","tool.intervention.stopTooltip": "就停在这一步——待审批的工具都不会执行,Agent 也不会继续","tool.intervention.submit": "提交",+ "tool.intervention.switchToAutoRun": "切换到自动批准",+ "tool.intervention.switchToAutoRunDesc": "批准本次调用,之后不再询问。必须确认的高风险操作仍会询问。","tool.intervention.toolAbort": "你已取消本次技能调用","tool.intervention.toolEnded": "本次工具调用已结束","tool.intervention.toolRejected": "本次技能调用已被拒绝",diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 9a3f4836968..9bd7f6db651 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -3342,6 +3342,9 @@ export default {'tool.intervention.stop': 'Stop','tool.intervention.stopTooltip':'Stop here — nothing pending runs and the agent does not continue',+ 'tool.intervention.switchToAutoRun': 'Switch to auto approve',+ 'tool.intervention.switchToAutoRunDesc':+ 'Approve this call and stop asking from now on. Calls that must always ask still ask.','tool.intervention.renderFallback.description':'This display was downgraded to raw JSON because the current model was not capable enough to generate a stable interactive payload. Switch to a stronger model and try again.','tool.intervention.renderFallback.rawJson': 'Raw JSON',diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/ApprovalActions.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/ApprovalActions.tsxindex 132bd2da406..def7c2319c9 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/ApprovalActions.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/ApprovalActions.tsx@@ -1,10 +1,10 @@import { registerPendingHotkeyCard } from '@lobechat/shared-tool-ui/pending-hotkeys';import type { BuiltinRememberApproval, DynamicInterventionResolver } from '@lobechat/types';import { safeParseJSON } from '@lobechat/utils';-import { Button, Flexbox } from '@lobehub/ui';+import { Button, Flexbox, Tooltip } from '@lobehub/ui';import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';import * as stylex from '@stylexjs/stylex';-import { CircleStop, CornerDownLeft } from 'lucide-react';+import { CircleStop, CornerDownLeft, Zap } from 'lucide-react';import type { KeyboardEvent as ReactKeyboardEvent } from 'react';import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -12,6 +12,7 @@ import { useTranslation } from 'react-i18next';import { clientInterventionAudits } from '@/store/chat/slices/agentRun/actions/transports/client/interventionAudits';import { useToolStore } from '@/store/tool';import { toolSelectors } from '@/store/tool/selectors';+import { useUserStore } from '@/store/user';import { useConversationResourceAccess } from '../../../../../hooks/useConversationResourceAccess';import { useConversationStore } from '../../../../../store';@@ -19,6 +20,7 @@ import {type ApprovalChoice,approveChoiceLabelKeys,canRememberViaAllowList,+ canSwitchToAutoRun,dynamicAuditType,getApprovalChoices,isChoiceSubmitBlocked,@@ -200,6 +202,13 @@ const ApprovalActions = memo<ApprovalActionsProps>(s.stopPendingApprovalForCard,]);const [stopping, setStopping] = useState(false);+ const isShare = useConversationStore((s) => !!s.context.agentShareId);+ const updateHumanIntervention = useUserStore((s) => s.updateHumanIntervention);+ const showSwitchToAutoRun = canSwitchToAutoRun({+ allowListRememberable,+ approvalMode,+ isShare,+ });/*** "Stop here — don't continue." Sits beside Submit because it answers the@@ -280,6 +289,43 @@ const ApprovalActions = memo<ApprovalActionsProps>(submitBlocked,]);+ /**+ * "Switch to auto approve": the one-click way out of being asked call after+ * call. Approves this call (and the same tool's covered siblings in its+ * batch) and moves the approval mode to auto-run, so the rest of this run+ * and later runs stop asking — except for calls that must always ask.+ * The mode is persisted first: the server continuation reads it.+ */+ const handleSwitchToAutoRun = useCallback(async () => {+ if (loading || isMessageCreating || !canUseResource || approveDisabled) return;+ setLoading(true);+ try {+ await updateHumanIntervention({ approvalMode: 'auto-run' });+ const editedArguments = await onBeforeApprove?.();+ await approveToolCallAndCovered(messageId, assistantGroupId ?? '', {+ editedArguments,+ isCovered: async (sibling) =>+ canRememberViaAllowList({+ config: interventionConfig,+ toolArgs: safeParseJSON(sibling.requestArgs) ?? {},+ }),+ });+ } finally {+ setLoading(false);+ }+ }, [+ approveDisabled,+ approveToolCallAndCovered,+ assistantGroupId,+ canUseResource,+ interventionConfig,+ isMessageCreating,+ loading,+ messageId,+ onBeforeApprove,+ updateHumanIntervention,+ ]);+// When choice flips to reject (via click on row, '2', or arrow), pull focus// into the inline input so the user can start typing the reason immediately.useEffect(() => {@@ -443,6 +489,19 @@ const ApprovalActions = memo<ApprovalActionsProps>(>{t('tool.intervention.stop')}</Button>+ {showSwitchToAutoRun && (+ <Tooltip title={t('tool.intervention.switchToAutoRunDesc')}>+ <Button+ disabled={loading || isMessageCreating || approveDisabled}+ icon={Zap}+ size={'middle'}+ type={'default'}+ onClick={handleSwitchToAutoRun}+ >+ {t('tool.intervention.switchToAutoRun')}+ </Button>+ </Tooltip>+ )}<ButtonclassName={stylex.props(styles.submitButton).className}disabled={isMessageCreating || submitBlocked}diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/approvalGate.test.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/approvalGate.test.tsindex 0ec16153785..7871bc496a3 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/approvalGate.test.ts+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/approvalGate.test.ts@@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest';import {approveChoiceLabelKeys,canRememberViaAllowList,+ canSwitchToAutoRun,dynamicAuditType,getApprovalChoices,isChoiceSubmitBlocked,@@ -165,3 +166,29 @@ describe('isCoveredByRemember', () => {).resolves.toBe(false);});});++describe('canSwitchToAutoRun', () => {+ it.each(['manual', 'allow-list'])(+ 'is offered for a call that can skip approval in %s mode',+ (mode) => {+ expect(+ canSwitchToAutoRun({ allowListRememberable: true, approvalMode: mode, isShare: false }),+ ).toBe(true);+ },+ );++ it('is hidden when auto approve would not skip this call', () => {+ expect(+ canSwitchToAutoRun({ allowListRememberable: false, approvalMode: 'manual', isShare: false }),+ ).toBe(false);+ });++ it('is hidden for a share visitor and when already auto approving', () => {+ expect(+ canSwitchToAutoRun({ allowListRememberable: true, approvalMode: 'manual', isShare: true }),+ ).toBe(false);+ expect(+ canSwitchToAutoRun({ allowListRememberable: true, approvalMode: 'auto-run', isShare: false }),+ ).toBe(false);+ });+});diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/approvalGate.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/approvalGate.tsindex 30e5f2cb700..6739bd6d148 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/approvalGate.ts+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/approvalGate.ts@@ -135,3 +135,20 @@ export const isCoveredByRemember = async ({return false;}};++/**+ * Whether the card offers "switch to auto approve" (approve this call and+ * stop asking from now on). Auto approve never skips a call that must always+ * ask, so the switch is hidden on those — it would not keep its promise. A+ * share visitor's run is gated by the share, not by the visitor's own mode.+ */+export const canSwitchToAutoRun = ({+ allowListRememberable,+ approvalMode,+ isShare,+}: {+ allowListRememberable: boolean;+ approvalMode: string;+ isShare: boolean;+}) =>+ !isShare && allowListRememberable && (approvalMode === 'manual' || approvalMode === 'allow-list');diff --git a/src/features/Conversation/store/slices/message/action/crud.test.ts b/src/features/Conversation/store/slices/message/action/crud.test.tsindex bf9e2cc9b2c..fc3cf9189ef 100644--- a/src/features/Conversation/store/slices/message/action/crud.test.ts+++ b/src/features/Conversation/store/slices/message/action/crud.test.ts@@ -842,6 +842,46 @@ describe('Message CRUD Actions', () => {);});+ it('keeps the local rows when the caller opts out of the refresh', async () => {+ // The server's rows still carry the call as `pending`: loading them would+ // bring back an approval card the user already answered.+ vi.spyOn(messageServiceModule.messageService, 'updateToolArguments').mockResolvedValue({+ success: true,+ messages: [{ id: 'tool-msg-1', role: 'tool' }],+ } as any);+ const store = createTestStore();+ act(() => {+ store.getState().internal_dispatchMessage({+ type: 'createMessage',+ id: 'tool-msg-1',+ value: {+ content: '',+ role: 'tool',+ sessionId: 'test-session',+ tool_call_id: 'tool-call-1',+ plugin: {+ apiName: 'test',+ arguments: '{"key":"old"}',+ identifier: 'p',+ type: 'default',+ },+ },+ });+ });+ const replaceSpy = vi.spyOn(store.getState(), 'replaceMessages');++ await act(async () => {+ await store+ .getState()+ .updatePluginArguments('tool-call-1', { key: 'new' }, true, { refresh: false });+ });++ expect(replaceSpy).not.toHaveBeenCalled();+ expect(+ store.getState().dbMessages.find((m) => m.id === 'tool-msg-1')?.plugin?.arguments,+ ).toBe('{"key":"new"}');+ });+it('should update using toolCallId even when tool message not persisted (intervention pending)', async () => {const updateToolArgsSpy = vi.spyOn(messageServiceModule.messageService, 'updateToolArguments')diff --git a/src/features/Conversation/store/slices/message/action/crud.ts b/src/features/Conversation/store/slices/message/action/crud.tsindex ae907c3b746..8147b093e7c 100644--- a/src/features/Conversation/store/slices/message/action/crud.ts+++ b/src/features/Conversation/store/slices/message/action/crud.ts@@ -151,11 +151,14 @@ export interface MessageCRUDAction {* @param toolCallId - The tool call ID (stable identifier from AI response)* @param value - The new arguments value* @param replace - If true, replace arguments entirely; if false, merge with existing+ * @param options.refresh - Set false to keep the local rows instead of loading the server's+ * after the write (they would carry back a decision the server has not claimed yet)*/updatePluginArguments: <T = any>(toolCallId: string,value: T,replace?: boolean,+ options?: { refresh?: boolean },) => Promise<void>;/**@@ -552,7 +555,7 @@ export const messageCRUDSlice: StateCreator<}},- updatePluginArguments: async (toolCallId, value, replace = false) => {+ updatePluginArguments: async (toolCallId, value, replace = false, options) => {const { internal_dispatchMessage, replaceMessages, context } = get();// Find previous arguments from either tool message or parent's tools array@@ -617,7 +620,7 @@ export const messageCRUDSlice: StateCreator<// Create the update promise - backend handles all cases using toolCallIdconst updatePromise = (async () => {const result = await messageService.updateToolArguments(toolCallId, nextValue, context);- if (result?.success && result.messages) {+ if (options?.refresh !== false && result?.success && result.messages) {replaceMessages(result.messages, { expectedContext: context });}})();diff --git a/src/features/Conversation/store/slices/tool/action.test.ts b/src/features/Conversation/store/slices/tool/action.test.tsindex 806da99f7af..bfbb9adf95b 100644--- a/src/features/Conversation/store/slices/tool/action.test.ts+++ b/src/features/Conversation/store/slices/tool/action.test.ts@@ -172,6 +172,30 @@ describe('Tool Actions', () => {});});+ it('writes legacy-fallback edits without loading the still-pending server rows', async () => {+ const context: ConversationContext = { agentId: 'session-1', topicId: null, threadId: null };+ const store = createStore({ context });+ const updatePluginArguments = vi.fn().mockResolvedValue(undefined);+ act(() => {+ store.setState({+ dbMessages: [{ id: 'tool-msg-1', role: 'tool', tool_call_id: 'call-1' } as any],+ updatePluginArguments,+ });+ });++ await act(async () => {+ await store+ .getState()+ .approveToolCall('tool-msg-1', 'group-1', { editedArguments: { path: 'edited' } });+ });+ const [, , , options] = mockApproveToolCalling.mock.calls[0];+ await options.onLegacyEditFallback();++ expect(updatePluginArguments).toHaveBeenCalledWith('call-1', { path: 'edited' }, true, {+ refresh: false,+ });+ });+describe('submitHeteroIntervention', () => {it('should pass this conversation context to ChatStore, not fall back to global activeTopicId', async () => {// Regression: the hetero path used to call the chat store directly with nodiff --git a/src/features/Conversation/store/slices/tool/action.ts b/src/features/Conversation/store/slices/tool/action.tsindex ee32d025e0a..6a1cd947e8f 100644--- a/src/features/Conversation/store/slices/tool/action.ts+++ b/src/features/Conversation/store/slices/tool/action.ts@@ -50,8 +50,13 @@ export class ToolActionImpl {editedArguments && toolCallId? {...options,+ // The card already shows the approval; the server's rows would bring+ // it back as `pending` until the resume claims it, and a second+ // approval on that card fails the claim and ends the resumed run.onLegacyEditFallback: () =>- this.#get().updatePluginArguments(toolCallId, editedArguments, true),+ this.#get().updatePluginArguments(toolCallId, editedArguments, true, {+ refresh: false,+ }),}: options;if (chatOptions) {