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-run): preserve wakeup approvals, close resolved interventions, share trusted URL gate (#19713)

Arvin Xu9a4c951fb60e
diff --git a/apps/server/src/services/taskResultBridge/index.test.ts b/apps/server/src/services/taskResultBridge/index.test.ts
index 53ebab8e12a..5ddb8a49a9e 100644
--- a/apps/server/src/services/taskResultBridge/index.test.ts
+++ b/apps/server/src/services/taskResultBridge/index.test.ts
@@ -19,6 +19,7 @@ const {
execAgent,
findMessage,
getLastLeaf,
+ getUserSettings,
release,
settle,
topicFindById,
@@ -32,6 +33,7 @@ const {
execAgent: vi.fn(),
findMessage: vi.fn(),
getLastLeaf: vi.fn(),
+ getUserSettings: vi.fn(),
releaseReservation: vi.fn(),
tryReserve: vi.fn(),
release: vi.fn(),
@@ -77,6 +79,12 @@ vi.mock('../aiAgent', () => ({
}),
}));
+vi.mock('@/database/models/user', () => ({
+ UserModel: vi.fn(function () {
+ return { getUserSettings };
+ }),
+}));
+
const TEST_USER = 'user-1';
const db = {
transaction: vi.fn(async (callback) => callback({ execute: vi.fn() })),
@@ -105,6 +113,7 @@ describe('TaskResultBridgeService.deliver', () => {
let findByTopicId: any;
beforeEach(() => {
+ getUserSettings.mockReset().mockResolvedValue(undefined);
createMsg.mockReset().mockResolvedValue({ id: 'task-cb-task-1-topic-done' } as any);
createPending.mockReset().mockResolvedValue({ id: 'receipt-1' });
claimPending
@@ -143,6 +152,34 @@ describe('TaskResultBridgeService.deliver', () => {
afterEach(() => vi.restoreAllMocks());
+ it.each(['manual', 'auto-run', 'allow-list'] as const)(
+ 'preserves %s preferences so creator questions can wait for user input',
+ async (approvalMode) => {
+ const intervention = { allowList: ['lobe-task/viewTask'], approvalMode };
+ getUserSettings.mockResolvedValue({ tool: { humanIntervention: intervention } });
+
+ await new TaskResultBridgeService(db, TEST_USER).deliver(baseParams);
+
+ expect(execAgent.mock.calls[0][0].userInterventionConfig).toEqual(intervention);
+ },
+ );
+
+ it('defaults a user-facing creator to manual approval', async () => {
+ await new TaskResultBridgeService(db, TEST_USER).deliver(baseParams);
+ expect(execAgent.mock.calls[0][0].userInterventionConfig).toEqual({
+ allowList: [],
+ approvalMode: 'manual',
+ });
+ });
+
+ it('normalizes a legacy headless preference like the foreground client', async () => {
+ getUserSettings.mockResolvedValue({
+ tool: { humanIntervention: { approvalMode: 'headless' } },
+ });
+ await new TaskResultBridgeService(db, TEST_USER).deliver(baseParams);
+ expect(execAgent.mock.calls[0][0].userInterventionConfig.approvalMode).toBe('auto-run');
+ });
+
it('appends a taskCallback card to the origin topic and runs the creator agent off history', async () => {
await new TaskResultBridgeService(db, TEST_USER).deliver(baseParams);
@@ -276,6 +313,32 @@ describe('TaskResultBridgeService.deliver', () => {
}
});
+ it('retains a callback while a question is pending and dispatches it after the topic is free', async () => {
+ vi.useFakeTimers();
+ try {
+ topicFindById.mockResolvedValue({
+ metadata: { runningOperation: { operationId: 'op-question', status: 'waiting_for_human' } },
+ });
+ tryReserve.mockResolvedValue(false);
+ const service = new TaskResultBridgeService(db, TEST_USER);
+ const delivery = service.deliver(baseParams);
+ const rejected = expect(delivery).rejects.toThrow('remained busy');
+ await vi.runAllTimersAsync();
+ await rejected;
+
+ expect(release).toHaveBeenCalledWith(['receipt-1'], expect.stringContaining('remained busy'));
+ expect(settle).not.toHaveBeenCalled();
+ expect(execAgent).not.toHaveBeenCalled();
+
+ tryReserve.mockResolvedValue(true);
+ await service.drain(ORIGIN.agentId, ORIGIN.topicId);
+ expect(execAgent).toHaveBeenCalledTimes(1);
+ expect(attachCreatorOperation).toHaveBeenCalledWith(['receipt-1'], 'op-new');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('restores messenger routing and registers a proactive bot completion hook', async () => {
topicFindById.mockResolvedValue({
agentId: 'agent-creator',
@@ -294,6 +357,8 @@ describe('TaskResultBridgeService.deliver', () => {
await new TaskResultBridgeService(db, TEST_USER).deliver(baseParams);
const hooks = execAgent.mock.calls[0][0].hooks;
+ expect(execAgent.mock.calls[0][0].userInterventionConfig).toEqual({ approvalMode: 'headless' });
+ expect(getUserSettings).not.toHaveBeenCalled();
const botHook = hooks.find((hook: any) => hook.id === 'task-creator-completion');
expect(botHook.webhook).toMatchObject({
delivery: 'qstash',
diff --git a/apps/server/src/services/taskResultBridge/index.ts b/apps/server/src/services/taskResultBridge/index.ts
index b4b298fcb94..56068bcfe6b 100644
--- a/apps/server/src/services/taskResultBridge/index.ts
+++ b/apps/server/src/services/taskResultBridge/index.ts
@@ -1,4 +1,9 @@
-import type { ChatTopicBotContext, TaskContext, TaskTopicHandoff } from '@lobechat/types';
+import type {
+ ChatTopicBotContext,
+ TaskContext,
+ TaskTopicHandoff,
+ UserToolConfig,
+} from '@lobechat/types';
import { RequestTrigger } from '@lobechat/types';
import debug from 'debug';
import { sql } from 'drizzle-orm';
@@ -7,6 +12,7 @@ import { MessageModel } from '@/database/models/message';
import { TaskModel } from '@/database/models/task';
import { TaskTopicModel } from '@/database/models/taskTopic';
import { TopicModel } from '@/database/models/topic';
+import { UserModel } from '@/database/models/user';
import type { LobeChatDatabase } from '@/database/type';
import type { AgentHook } from '@/server/services/agentRuntime/hooks/types';
import type { BotCallbackBody } from '@/server/services/bot/BotCallbackService';
@@ -235,6 +241,18 @@ export class TaskResultBridgeService {
this.workspaceId,
).getLastMainThreadSpineMessageId(originTopicId);
+ // A creator wakeup continues a user-facing conversation. Preserve the
+ // same approval preferences as a foreground send, including its allow
+ // list. Bot channels still lack this UI/resume contract and stay headless.
+ const settings = botContext
+ ? undefined
+ : await new UserModel(this.db, this.userId).getUserSettings();
+ const intervention = (settings?.tool as UserToolConfig | undefined)?.humanIntervention;
+ const approvalMode =
+ intervention?.approvalMode === 'headless'
+ ? 'auto-run'
+ : (intervention?.approvalMode ?? 'manual');
+
const result = await new AiAgentService(this.db, this.userId, {
workspaceId: this.workspaceId,
}).execAgent({
@@ -248,7 +266,9 @@ export class TaskResultBridgeService {
suppressUserMessage: true,
topicStartReservationId: reservationId,
trigger: RequestTrigger.AgentSignal,
- userInterventionConfig: { approvalMode: 'headless' },
+ userInterventionConfig: botContext
+ ? { approvalMode: 'headless' }
+ : { allowList: intervention?.allowList ?? [], approvalMode },
});
await callbackStore.attachCreatorOperation(receiptIds, result.operationId);
} catch (error) {
diff --git a/packages/agent-runtime/src/agents/GeneralChatAgent.ts b/packages/agent-runtime/src/agents/GeneralChatAgent.ts
index cbce339590b..1f288a73c0b 100644
--- a/packages/agent-runtime/src/agents/GeneralChatAgent.ts
+++ b/packages/agent-runtime/src/agents/GeneralChatAgent.ts
@@ -756,6 +756,9 @@ export class GeneralChatAgent implements Agent {
if (state.userInterventionConfig?.approvalMode === 'headless') {
instructions.push({
payload: {
+ blockedContent:
+ 'This run cannot wait for user interaction. Continue in a user-facing conversation to answer questions or approve tools.',
+ blockedReason: 'human_intervention_unavailable',
parentMessageId,
toolsCalling: toolsNeedingIntervention,
},
diff --git a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts
index 2a729e86ca9..9ea14c52268 100644
--- a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts
+++ b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts
@@ -3469,6 +3469,9 @@ describe('GeneralChatAgent', () => {
expect(result).toEqual([
{
payload: {
+ blockedContent:
+ 'This run cannot wait for user interaction. Continue in a user-facing conversation to answer questions or approve tools.',
+ blockedReason: 'human_intervention_unavailable',
parentMessageId: 'msg-1',
toolsCalling: [blockedTool],
},
@@ -3762,6 +3765,51 @@ describe('GeneralChatAgent', () => {
});
describe('headless mode (for async tasks)', () => {
+ it.each(['manual', 'auto-run', 'allow-list'] as const)(
+ 'parks creator questions in %s mode instead of blocking them',
+ async (approvalMode) => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: 'creator-wakeup',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+ const question: ChatToolPayload = {
+ id: 'question-1',
+ identifier: 'lobe-user-interaction',
+ apiName: 'askUserQuestion',
+ arguments: '{}',
+ type: 'builtin',
+ };
+ const result = await agent.runner(
+ createMockContext('llm_result', {
+ hasToolsCalling: true,
+ toolsCalling: [question],
+ parentMessageId: 'creator-message',
+ }),
+ createMockState({
+ toolManifestMap: {
+ 'lobe-user-interaction': {
+ identifier: 'lobe-user-interaction',
+ api: [{ name: 'askUserQuestion', humanIntervention: 'always' }],
+ },
+ },
+ userInterventionConfig: {
+ approvalMode,
+ allowList: ['lobe-user-interaction/askUserQuestion'],
+ },
+ }),
+ );
+ expect(result).toEqual([
+ {
+ parentMessageId: 'creator-message',
+ pendingToolsCalling: [question],
+ reason: 'human_intervention_required',
+ type: 'request_human_approve',
+ },
+ ]);
+ },
+ );
+
it('should execute tool-level required tools in headless mode', async () => {
const agent = new GeneralChatAgent({
agentConfig: { maxSteps: 100 },
@@ -3897,6 +3945,9 @@ describe('GeneralChatAgent', () => {
expect(result).toEqual([
{
payload: {
+ blockedContent:
+ 'This run cannot wait for user interaction. Continue in a user-facing conversation to answer questions or approve tools.',
+ blockedReason: 'human_intervention_unavailable',
parentMessageId: 'msg-1',
toolsCalling: [alwaysTool],
},
@@ -3945,6 +3996,9 @@ describe('GeneralChatAgent', () => {
expect(result).toEqual([
{
payload: {
+ blockedContent:
+ 'This run cannot wait for user interaction. Continue in a user-facing conversation to answer questions or approve tools.',
+ blockedReason: 'human_intervention_unavailable',
parentMessageId: 'msg-1',
toolsCalling: [blacklistedTool],
},
@@ -4024,6 +4078,9 @@ describe('GeneralChatAgent', () => {
},
{
payload: {
+ blockedContent:
+ 'This run cannot wait for user interaction. Continue in a user-facing conversation to answer questions or approve tools.',
+ blockedReason: 'human_intervention_unavailable',
parentMessageId: 'msg-1',
toolsCalling: [blacklistedTool, alwaysTool],
},
@@ -4081,6 +4138,9 @@ describe('GeneralChatAgent', () => {
},
{
payload: {
+ blockedContent:
+ 'This run cannot wait for user interaction. Continue in a user-facing conversation to answer questions or approve tools.',
+ blockedReason: 'human_intervention_unavailable',
parentMessageId: 'msg-1',
toolsCalling: [tool2],
},
diff --git a/packages/agent-runtime/src/core/__tests__/runtime.test.ts b/packages/agent-runtime/src/core/__tests__/runtime.test.ts
index 9fc8bbc9c58..476d4b6564a 100644
--- a/packages/agent-runtime/src/core/__tests__/runtime.test.ts
+++ b/packages/agent-runtime/src/core/__tests__/runtime.test.ts
@@ -1325,12 +1325,19 @@ describe('AgentRuntime', () => {
expect(result.nextContext?.payload).toHaveProperty('toolCount', 3);
});
- it('should resolve blocked tools and continue without waiting for human approval', async () => {
+ it.each([
+ {},
+ {
+ blockedContent: 'This run cannot wait for user interaction.',
+ blockedReason: 'human_intervention_unavailable',
+ },
+ ])('should resolve blocked tools with the supplied rejection %j', async (rejection) => {
class BlockedToolAgent implements Agent {
async runner(context: AgentRuntimeContext, _state: AgentState) {
if (context.phase === 'user_input') {
return {
payload: {
+ ...rejection,
parentMessageId: 'assistant-1',
toolsCalling: [
{
@@ -1363,7 +1370,8 @@ describe('AgentRuntime', () => {
{
id: 'call_blocked',
result: {
- content: 'Blocked by security/privacy.',
+ content: rejection.blockedContent ?? 'Blocked by security/privacy.',
+ ...(rejection.blockedReason && { error: rejection.blockedReason }),
success: false,
},
type: 'tool_result',
diff --git a/packages/agent-runtime/src/core/runtime.ts b/packages/agent-runtime/src/core/runtime.ts
index 702d9dcb742..73f01a26f5a 100644
--- a/packages/agent-runtime/src/core/runtime.ts
+++ b/packages/agent-runtime/src/core/runtime.ts
@@ -640,7 +640,8 @@ export class AgentRuntime {
for (const toolCalling of payload.toolsCalling) {
const result = {
- content: 'Blocked by security/privacy.',
+ content: payload.blockedContent ?? 'Blocked by security/privacy.',
+ ...(payload.blockedReason && { error: payload.blockedReason }),
success: false,
};
diff --git a/src/features/ChatInput/ControlBar/GitStatus.tsx b/src/features/ChatInput/ControlBar/GitStatus.tsx
index 2aba23fda1b..963a07b6445 100644
--- a/src/features/ChatInput/ControlBar/GitStatus.tsx
+++ b/src/features/ChatInput/ControlBar/GitStatus.tsx
@@ -7,7 +7,6 @@ import { memo, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import RingLoadingIcon from '@/components/RingLoading';
-import { electronSystemService } from '@/services/electron/system';
import { gitService } from '@/services/git';
import {
deviceSelectors,
@@ -20,6 +19,7 @@ import {
} from '@/store/device';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
+import { openTrustedExternalUrl } from '@/utils/openTrustedExternalUrl';
import BranchSwitcher from './BranchSwitcher';
import { gitChipStyles } from './gitChipStyles';
@@ -191,7 +191,7 @@ const GitStatus = memo<GitStatusProps>(
const handleOpenPr = useCallback(() => {
if (prData?.pullRequest?.url) {
- void electronSystemService.openExternalLink(prData.pullRequest.url);
+ openTrustedExternalUrl(prData.pullRequest.url);
}
}, [prData?.pullRequest?.url]);
diff --git a/src/features/ChatInput/ControlBar/StaleGitSnapshot.tsx b/src/features/ChatInput/ControlBar/StaleGitSnapshot.tsx
index cef9ded4ab9..cd27260e8a5 100644
--- a/src/features/ChatInput/ControlBar/StaleGitSnapshot.tsx
+++ b/src/features/ChatInput/ControlBar/StaleGitSnapshot.tsx
@@ -13,7 +13,7 @@ import { GitBranchIcon, GitForkIcon, GitPullRequest, RotateCcwIcon } from 'lucid
import { memo, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { electronSystemService } from '@/services/electron/system';
+import { openTrustedExternalUrl } from '@/utils/openTrustedExternalUrl';
import { gitChipStyles } from './gitChipStyles';
import { resolveStaleSnapshot } from './staleSnapshot';
@@ -87,7 +87,7 @@ const StaleGitSnapshot = memo<StaleGitSnapshotProps>(
const handleOpenPr = useCallback(() => {
if (pullRequest?.url) {
- void electronSystemService.openExternalLink(pullRequest.url);
+ openTrustedExternalUrl(pullRequest.url);
}
}, [pullRequest?.url]);
diff --git a/src/features/ChatTerminal/links.test.ts b/src/features/ChatTerminal/links.test.ts
index 7c58691f608..95003c2d628 100644
--- a/src/features/ChatTerminal/links.test.ts
+++ b/src/features/ChatTerminal/links.test.ts
@@ -4,6 +4,15 @@ import { electronSystemService } from '@/services/electron/system';
import { openTerminalLink } from './links';
+// openTerminalLink delegates to openTrustedExternalUrl, which branches on
+// isDesktop β€” pin it to desktop, the only platform with a terminal panel.
+const { isDesktopRef } = vi.hoisted(() => ({ isDesktopRef: { value: true } }));
+
+vi.mock('@/const/version', () => ({
+ get isDesktop() {
+ return isDesktopRef.value;
+ },
+}));
vi.mock('@/services/electron/system', () => ({
electronSystemService: { openExternalLink: vi.fn().mockResolvedValue(undefined) },
}));
diff --git a/src/features/ChatTerminal/links.ts b/src/features/ChatTerminal/links.ts
index dc584ad077c..efd9d0bf9d8 100644
--- a/src/features/ChatTerminal/links.ts
+++ b/src/features/ChatTerminal/links.ts
@@ -1,29 +1,10 @@
-import debug from 'debug';
-
-import { electronSystemService } from '@/services/electron/system';
-
-const log = debug('lobe-desktop:chat-terminal');
-
-// The main process hands this straight to shell.openExternal, and terminal
-// output is attacker-reachable β€” any command can print an escape sequence. So
-// the renderer is the gate: only http(s) ever reaches the OS handler.
-const OPENABLE_PROTOCOLS = new Set(['http:', 'https:']);
+import { openTrustedExternalUrl } from '@/utils/openTrustedExternalUrl';
+/**
+ * Terminal output is attacker-reachable β€” any command can print an escape
+ * sequence β€” so link opening goes through the shared trusted-URL gate
+ * (http(s) only, no current-window navigation). See openTrustedExternalUrl.
+ */
export const openTerminalLink = (uri: string) => {
- let parsed: URL;
- try {
- parsed = new URL(uri);
- } catch {
- log('ignoring unparseable terminal link: %s', uri);
- return;
- }
-
- if (!OPENABLE_PROTOCOLS.has(parsed.protocol)) {
- log('ignoring terminal link with unsupported protocol: %s', parsed.protocol);
- return;
- }
-
- void electronSystemService.openExternalLink(parsed.href).catch((error) => {
- log('failed to open terminal link %s: %O', parsed.href, error);
- });
+ openTrustedExternalUrl(uri);
};
diff --git a/src/features/CommandMenu/useCommandMenu.ts b/src/features/CommandMenu/useCommandMenu.ts
index f51b8044e23..84672de0b0d 100644
--- a/src/features/CommandMenu/useCommandMenu.ts
+++ b/src/features/CommandMenu/useCommandMenu.ts
@@ -3,7 +3,6 @@ import { useTheme as useNextThemesTheme } from 'next-themes';
import { useCallback, useEffect } from 'react';
import useSWR from 'swr';
-import { isDesktop } from '@/const/version';
import type { FtsSearchResult } from '@/database/repositories/ftsSearch';
import { useCreateMenuItems } from '@/features/HomeSidebar/hooks';
import { useCreateNewModal } from '@/features/LibraryModal';
@@ -11,7 +10,6 @@ import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwar
import { usePermission } from '@/hooks/usePermission';
import { useGroupWizard } from '@/layout/GlobalProvider/GroupWizardProvider';
import { lambdaClient } from '@/libs/trpc/client';
-import { electronSystemService } from '@/services/electron/system';
import { useAgentStore } from '@/store/agent';
import { builtinAgentSelectors } from '@/store/agent/selectors/builtinAgentSelectors';
import { useChatStore } from '@/store/chat';
@@ -19,6 +17,7 @@ import { topicSelectors } from '@/store/chat/selectors';
import { useGlobalStore } from '@/store/global';
import { globalHelpers } from '@/store/global/helpers';
import { useHomeStore } from '@/store/home';
+import { openTrustedExternalUrl } from '@/utils/openTrustedExternalUrl';
import { useCommandMenuContext } from './CommandMenuContext';
import { type ThemeMode } from './types';
@@ -113,12 +112,8 @@ export const useCommandMenu = () => {
);
const handleExternalLink = useCallback(
- async (url: string) => {
- if (isDesktop) {
- await electronSystemService.openExternalLink(url);
- } else {
- window.open(url, '_blank', 'noopener,noreferrer');
- }
+ (url: string) => {
+ openTrustedExternalUrl(url);
onClose();
},
[onClose],
diff --git a/src/features/Conversation/WorkingSidebar/Overview/index.tsx b/src/features/Conversation/WorkingSidebar/Overview/index.tsx
index 326b6f2b221..258422a27ea 100644
--- a/src/features/Conversation/WorkingSidebar/Overview/index.tsx
+++ b/src/features/Conversation/WorkingSidebar/Overview/index.tsx
@@ -30,7 +30,6 @@ import BranchSwitcher from '@/features/ChatInput/ControlBar/BranchSwitcher';
import WorktreeSwitcher from '@/features/ChatInput/ControlBar/WorktreeSwitcher';
import { getAllWorkSummaries } from '@/features/Conversation/store/slices/data/workSummaries';
import WorkSummaryCard from '@/features/Work/WorkSummaryCard';
-import { electronSystemService } from '@/services/electron/system';
import { gitService } from '@/services/git';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
@@ -43,6 +42,7 @@ import {
useFetchGitWorktrees,
useReviewPatches,
} from '@/store/device';
+import { openTrustedExternalUrl } from '@/utils/openTrustedExternalUrl';
import ProgressSection from '../ProgressSection';
import { collectChangeStats, isLinkedWorktreeCheckout, shouldShowCiLabel } from './overviewData';
@@ -362,7 +362,7 @@ const Overview = memo<OverviewProps>(
prAvailable
? () => onOpenTab('pr')
: pullRequest.url
- ? () => void electronSystemService.openExternalLink(pullRequest.url)
+ ? () => openTrustedExternalUrl(pullRequest.url)
: undefined
}
/>
diff --git a/src/features/Portal/Acceptance/Header.tsx b/src/features/Portal/Acceptance/Header.tsx
index aa6bebb9957..7eb8ab54691 100644
--- a/src/features/Portal/Acceptance/Header.tsx
+++ b/src/features/Portal/Acceptance/Header.tsx
@@ -1,4 +1,4 @@
-import { DESKTOP_HEADER_ICON_SMALL_SIZE, isDesktop } from '@lobechat/const';
+import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@lobechat/const';
import { copyToClipboard, Flexbox, Icon } from '@lobehub/ui';
import { ActionIcon, type DropdownItem, DropdownMenu, toast } from '@lobehub/ui/base-ui';
import { Copy, ExternalLink, MoreHorizontal, RefreshCw } from 'lucide-react';
@@ -10,9 +10,9 @@ import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath
import { useAppOrigin } from '@/hooks/useAppOrigin';
import { mutate as globalMutate } from '@/libs/swr';
import { verifyKeys } from '@/libs/swr/keys';
-import { electronSystemService } from '@/services/electron/system';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
+import { openTrustedExternalUrl } from '@/utils/openTrustedExternalUrl';
import Header from '../components/Header';
import Title from './Title';
@@ -66,13 +66,7 @@ const AcceptanceHeader = memo(() => {
title={t('report.actions.openInBrowser')}
onClick={() => {
if (!externalUrl) return;
- // In Electron a `window.open` is denied by the window-open handler,
- // so hand the URL to the system browser through the main process.
- if (isDesktop) {
- void electronSystemService.openExternalLink(externalUrl);
- return;
- }
- window.open(externalUrl, '_blank', 'noopener,noreferrer');
+ openTrustedExternalUrl(externalUrl);
}}
/>
}
diff --git a/src/features/Portal/TaskDetail/Header.tsx b/src/features/Portal/TaskDetail/Header.tsx
index d8f67e68512..62d3d8febb7 100644
--- a/src/features/Portal/TaskDetail/Header.tsx
+++ b/src/features/Portal/TaskDetail/Header.tsx
@@ -1,4 +1,4 @@
-import { DESKTOP_HEADER_ICON_SMALL_SIZE, isDesktop } from '@lobechat/const';
+import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@lobechat/const';
import { ActionIcon } from '@lobehub/ui/base-ui';
import { ExternalLink } from 'lucide-react';
import { memo } from 'react';
@@ -6,10 +6,10 @@ import { useTranslation } from 'react-i18next';
import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
import { useAppOrigin } from '@/hooks/useAppOrigin';
-import { electronSystemService } from '@/services/electron/system';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
import { useTaskStore } from '@/store/task';
+import { openTrustedExternalUrl } from '@/utils/openTrustedExternalUrl';
import PortalHeader from '../components/Header';
import Title from './Title';
@@ -45,11 +45,7 @@ const TaskDetailHeader = memo(() => {
title={t('report.actions.openInBrowser')}
onClick={() => {
if (!pageUrl) return;
- if (isDesktop) {
- void electronSystemService.openExternalLink(pageUrl);
- return;
- }
- window.open(pageUrl, '_blank', 'noopener,noreferrer');
+ openTrustedExternalUrl(pageUrl);
}}
/>
}
diff --git a/src/features/Portal/VerifyReport/Header.tsx b/src/features/Portal/VerifyReport/Header.tsx
index 8749ec30aac..e569c341842 100644
--- a/src/features/Portal/VerifyReport/Header.tsx
+++ b/src/features/Portal/VerifyReport/Header.tsx
@@ -1,4 +1,4 @@
-import { DESKTOP_HEADER_ICON_SMALL_SIZE, isDesktop } from '@lobechat/const';
+import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@lobechat/const';
import { copyToClipboard, Flexbox } from '@lobehub/ui';
import { ActionIcon, toast } from '@lobehub/ui/base-ui';
import { Copy, ExternalLink } from 'lucide-react';
@@ -8,9 +8,9 @@ import { useTranslation } from 'react-i18next';
import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';
import { useAppOrigin } from '@/hooks/useAppOrigin';
-import { electronSystemService } from '@/services/electron/system';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
+import { openTrustedExternalUrl } from '@/utils/openTrustedExternalUrl';
import Header from '../components/Header';
import Title from './Title';
@@ -50,13 +50,7 @@ const VerifyReportHeader = memo(() => {
title={t('report.actions.openInBrowser')}
onClick={() => {
if (!externalUrl) return;
- // In Electron a `window.open` is denied by the window-open handler,
- // so hand the URL to the system browser through the main process.
- if (isDesktop) {
- void electronSystemService.openExternalLink(externalUrl);
- return;
- }
- window.open(externalUrl, '_blank', 'noopener,noreferrer');
+ openTrustedExternalUrl(externalUrl);
}}
/>
</Flexbox>
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
index 249f96cf935..142a41612aa 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
@@ -1,8 +1,9 @@
import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
-import { RequestTrigger } from '@lobechat/types';
+import { type ExecAgentResult, RequestTrigger } from '@lobechat/types';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type * as ConstVersion from '@/const/version';
+import { getPendingInterventions } from '@/features/Conversation/store/slices/data/pendingInterventions';
import { aiAgentService } from '@/services/aiAgent';
import { messageService } from '@/services/message';
import { shareChatService } from '@/services/shareChat';
@@ -12,6 +13,7 @@ import * as serverConfigStore from '@/store/serverConfig';
import type { GatewayConnection } from '../transports/gateway/gateway';
import { GatewayActionImpl } from '../transports/gateway/gateway';
+import { createMockMessage } from './fixtures';
vi.mock('@/services/aiAgent', () => ({
aiAgentService: {
@@ -676,6 +678,96 @@ describe('GatewayActionImpl', () => {
expect(connectToGateway).toHaveBeenCalled();
});
+ const precreatedInterventionResult: ExecAgentResult = {
+ agentId: 'agent-1',
+ assistantMessageId: 'ast-resumed',
+ autoStarted: true,
+ createdAt: '2026-09-19T00:00:00.000Z',
+ message: 'ok',
+ operationId: 'server-op-resumed',
+ status: 'created',
+ success: true,
+ timestamp: '2026-09-19T00:00:00.000Z',
+ token: 'test-token',
+ topicId: 'topic-1',
+ userMessageId: 'user-1',
+ };
+
+ it.each(['approved', 'rejected'] as const)(
+ 'removes a %s question from pending interventions before connecting the precreated continuation',
+ async (status) => {
+ const { action, connectToGateway, replaceMessages } = createExecuteTestAction();
+ const context = {
+ agentId: 'agent-1',
+ scope: 'thread' as const,
+ threadId: 'thread-1',
+ topicId: 'topic-1',
+ };
+ const question = createMockMessage({
+ id: 'question-1',
+ plugin: {
+ apiName: 'askUserQuestion',
+ arguments: '{}',
+ identifier: 'lobe-agent',
+ type: 'default',
+ },
+ pluginIntervention: { status: 'pending' },
+ role: 'tool',
+ tool_call_id: 'call-question',
+ });
+ let displayedMessages = [question];
+ const resolvedMessages = [
+ { ...question, pluginIntervention: { status } },
+ createMockMessage({ id: 'ast-resumed', role: 'assistant' }),
+ ];
+ vi.mocked(messageService.getMessages).mockResolvedValueOnce(resolvedMessages);
+ replaceMessages.mockImplementation((messages) => {
+ displayedMessages = messages;
+ });
+ connectToGateway.mockImplementation(() => {
+ // No continuation events have arrived: the answer alone must dismiss the form.
+ expect(getPendingInterventions(displayedMessages)).toEqual([]);
+ });
+ const executionsBefore = vi.mocked(aiAgentService.execAgentTask).mock.calls.length;
+ expect(getPendingInterventions(displayedMessages)).toHaveLength(1);
+
+ await action.executeGatewayAgent({
+ context,
+ message: '',
+ parentMessageId: question.id,
+ precreatedResult: precreatedInterventionResult,
+ });
+
+ expect(connectToGateway).toHaveBeenCalledOnce();
+ expect(messageService.getMessages).toHaveBeenLastCalledWith({
+ ...context,
+ skipWorks: true,
+ });
+ expect(displayedMessages).toEqual(resolvedMessages);
+ expect(aiAgentService.execAgentTask).toHaveBeenCalledTimes(executionsBefore);
+ },
+ );
+
+ it('still connects the accepted continuation when its initial message refresh fails', async () => {
+ const { action, connectToGateway, replaceMessages } = createExecuteTestAction();
+ const error = new Error('message refresh unavailable');
+ const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ vi.mocked(messageService.getMessages).mockRejectedValueOnce(error);
+
+ await action.executeGatewayAgent({
+ context: { agentId: 'agent-1', topicId: 'topic-1' },
+ message: '',
+ precreatedResult: precreatedInterventionResult,
+ });
+
+ expect(connectToGateway).toHaveBeenCalledOnce();
+ expect(replaceMessages).not.toHaveBeenCalled();
+ expect(consoleSpy).toHaveBeenCalledWith(
+ '[Gateway] Failed to refresh messages after intervention resolution:',
+ error,
+ );
+ });
+
it.each([
{
expectedEnabled: true,
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
index f80b0b4712c..e556d77eb14 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -948,6 +948,27 @@ export class GatewayActionImpl {
const resolvedMessageContext = resolveThread({ ...messageContext, topicId: result.topicId });
this.#get().moveVoiceMessages(messageContext, resolvedMessageContext);
+ if (precreatedResult) {
+ // V2 resolves the intervention before returning this continuation. Apply
+ // that persisted state before subscribing, so the answered form closes
+ // even when the next runtime event is delayed. SWR revalidation alone
+ // can be ignored while the previous operation still appears running.
+ try {
+ const messages = await messageService.getMessages({
+ ...resolvedMessageContext,
+ skipWorks: true,
+ });
+ this.#get().replaceMessages(messages, {
+ context: resolvedMessageContext,
+ preserveWorks: true,
+ });
+ } catch (error) {
+ // The continuation already exists; a failed read must not prevent us
+ // from connecting to it and reconciling through subsequent events.
+ console.error('[Gateway] Failed to refresh messages after intervention resolution:', error);
+ }
+ }
+
if (result.createdThreadId) {
// Attachments picked in the subtopic composer were staged under the
// `_new` key; carry them over so the next turn in the thread still sees
diff --git a/src/utils/__tests__/openTrustedExternalUrl.test.ts b/src/utils/__tests__/openTrustedExternalUrl.test.ts
new file mode 100644
index 00000000000..cc04812fe7a
--- /dev/null
+++ b/src/utils/__tests__/openTrustedExternalUrl.test.ts
@@ -0,0 +1,75 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { electronSystemService } from '@/services/electron/system';
+
+import { openTrustedExternalUrl } from '../openTrustedExternalUrl';
+
+// `isDesktop` is read inside the helper on every call, so a getter lets each
+// test flip the platform without re-importing the module.
+const { isDesktopRef } = vi.hoisted(() => ({ isDesktopRef: { value: false } }));
+
+vi.mock('@/const/version', () => ({
+ get isDesktop() {
+ return isDesktopRef.value;
+ },
+}));
+vi.mock('@/services/electron/system', () => ({
+ electronSystemService: { openExternalLink: vi.fn().mockResolvedValue(undefined) },
+}));
+
+const windowOpen = vi.fn();
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ isDesktopRef.value = false;
+ vi.stubGlobal('open', windowOpen);
+});
+
+describe('openTrustedExternalUrl', () => {
+ describe('web', () => {
+ it('opens a new detached tab via window.open', () => {
+ openTrustedExternalUrl('https://github.com/lobehub/lobehub/pull/19676');
+
+ expect(windowOpen).toHaveBeenCalledWith(
+ 'https://github.com/lobehub/lobehub/pull/19676',
+ '_blank',
+ 'noopener,noreferrer',
+ );
+ expect(electronSystemService.openExternalLink).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('desktop', () => {
+ beforeEach(() => {
+ isDesktopRef.value = true;
+ });
+
+ it('hands the URL to the electron main process', () => {
+ openTrustedExternalUrl('https://github.com/lobehub/lobehub/pull/19676');
+
+ expect(electronSystemService.openExternalLink).toHaveBeenCalledWith(
+ 'https://github.com/lobehub/lobehub/pull/19676',
+ );
+ expect(windowOpen).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('protocol gate', () => {
+ it.each(['file:///etc/passwd', 'vscode://x', 'javascript:alert(1)', 'mailto:[email protected]'])(
+ 'refuses %s β€” only http(s) may reach the OS handler',
+ (uri) => {
+ openTrustedExternalUrl(uri);
+
+ expect(windowOpen).not.toHaveBeenCalled();
+ expect(electronSystemService.openExternalLink).not.toHaveBeenCalled();
+ },
+ );
+
+ it('silently ignores text that is not a URL', () => {
+ openTrustedExternalUrl('not a link');
+
+ expect(windowOpen).not.toHaveBeenCalled();
+ expect(electronSystemService.openExternalLink).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/src/utils/openTrustedExternalUrl.ts b/src/utils/openTrustedExternalUrl.ts
new file mode 100644
index 00000000000..1d498e35bd2
--- /dev/null
+++ b/src/utils/openTrustedExternalUrl.ts
@@ -0,0 +1,36 @@
+import { isDesktop } from '@/const/version';
+import { electronSystemService } from '@/services/electron/system';
+
+// The renderer is the final gate before the OS handler β€” the desktop main
+// process hands URLs straight to shell.openExternal, so only http(s) may pass.
+const OPENABLE_PROTOCOLS = new Set(['http:', 'https:']);
+
+/**
+ * Open a URL the caller vouches for in the OS browser (desktop) or a new
+ * browser tab (web).
+ *
+ * Contract: callers pass only URLs from first-party data β€” our API responses,
+ * git service results, or constants β€” never raw user input or parsed
+ * terminal/markdown output unless that content has been vetted upstream.
+ * The helper is the last line of defense regardless of the caller: http(s)
+ * only, never navigates the current window, and the new tab is detached with
+ * noopener/noreferrer so the opened page cannot reach back.
+ */
+export const openTrustedExternalUrl = (rawUrl: string): void => {
+ let parsed: URL;
+ try {
+ parsed = new URL(rawUrl);
+ } catch {
+ return;
+ }
+
+ if (!OPENABLE_PROTOCOLS.has(parsed.protocol)) return;
+
+ if (isDesktop) {
+ void electronSystemService.openExternalLink(parsed.href).catch(() => {});
+ } else {
+ // Synchronous window.open inside the click handler keeps the user gesture
+ // trusted so browser popup blockers don't intervene.
+ window.open(parsed.href, '_blank', 'noopener,noreferrer');
+ }
+};