diff --git a/client/src/components/Chat/Messages/Content/ToolCall.tsx b/client/src/components/Chat/Messages/Content/ToolCall.tsx index ee14b6971e..6bd9e52230 100644 --- a/client/src/components/Chat/Messages/Content/ToolCall.tsx +++ b/client/src/components/Chat/Messages/Content/ToolCall.tsx @@ -10,10 +10,10 @@ import { } from 'librechat-data-provider'; import type { TAttachment, PartMetadata } from 'librechat-data-provider'; import { useLocalize, useProgress, useExpandCollapse, useLazyCollapseBody } from '~/hooks'; +import { cn, getToolDisplayLabel, logger, openInNewTab } from '~/utils'; import { ToolIcon, getToolIconType, isError } from './ToolOutput'; import { useMCPIconMap, useMCPServerNames } from '~/hooks/MCP'; import { resolveToolCallPhase } from '~/utils/toolCallPhase'; -import { cn, getToolDisplayLabel, logger } from '~/utils'; import { toolPanelSpacingClassName } from './disclosure'; import { useToolCallIntent } from './Parts/intent'; import { AttachmentGroup } from './Parts'; @@ -54,6 +54,7 @@ export default function ToolCall({ }) { const localize = useLocalize(); const [oauthError, setOAuthError] = useState(null); + const [oauthBinding, setOAuthBinding] = useState<'pending' | 'bound' | 'failed'>('pending'); const autoExpand = useRecoilValue(store.autoExpandTools); const hasOutput = (output?.length ?? 0) > 0; const [showInfo, setShowInfo] = useState(() => autoExpand && hasOutput); @@ -139,24 +140,23 @@ export default function ToolCall({ return match?.[1] || ''; }, [parsedAuthUrl, isMCPToolCall]); - const handleOAuthClick = useCallback(async () => { - if (!auth) { - return; + /** + * Sets the CSRF cookie the OAuth callback checks when the provider redirects back, or returns + * null when this prompt has nothing to bind. + */ + const bindOAuth = useCallback((): Promise | null => { + const bindsMCP = isMCPToolCall && mcpServerName.length > 0; + if (!bindsMCP && !actionId) { + return null; } - setOAuthError(null); - try { - if (isMCPToolCall && mcpServerName) { + return (async () => { + if (bindsMCP) { await dataService.bindMCPOAuth(mcpServerName); - } else if (actionId) { + } else { await dataService.bindActionOAuth(actionId); } - } catch (e) { - logger.error('Failed to bind OAuth CSRF cookie', e); - setOAuthError(localize('com_ui_oauth_error_generic')); - return; - } - window.open(auth, '_blank', 'noopener,noreferrer'); - }, [auth, isMCPToolCall, mcpServerName, actionId, localize]); + })(); + }, [isMCPToolCall, mcpServerName, actionId]); const hasError = (typeof output === 'string' && isError(output)) || runStepStatus === 'failed'; /** @@ -216,6 +216,72 @@ export default function ToolCall({ isSubmitting, hasError, }); + const showOAuth = Boolean(auth) && phase === 'running'; + + /** + * Binds when the sign-in prompt appears instead of on tap, so the tap opens the provider + * synchronously: an iOS home-screen app drops a tab opened after an awaited request. The button + * stays disabled until the bind lands, so the provider cannot redirect back before its cookie. + */ + useEffect(() => { + if (!showOAuth) { + return; + } + const binding = bindOAuth(); + if (binding == null) { + setOAuthBinding('bound'); + return; + } + let active = true; + setOAuthBinding('pending'); + binding.then( + () => { + if (active) { + setOAuthBinding('bound'); + } + }, + (error: unknown) => { + logger.error('Failed to bind OAuth CSRF cookie', error); + if (active) { + setOAuthBinding('failed'); + } + }, + ); + return () => { + active = false; + }; + }, [showOAuth, auth, bindOAuth]); + + const handleOAuthClick = useCallback(() => { + if (!auth || oauthBinding === 'pending') { + return; + } + if (oauthBinding === 'bound') { + setOAuthError(null); + openInNewTab(auth); + /** + * Live prompts share one CSRF cookie per callback path, so the last prompt to bind owns it. + * The tapped prompt claims it again after opening; the provider cannot redirect back before + * the user signs in, and the session cookie from the earlier bind covers a faster callback. + */ + bindOAuth()?.catch((error: unknown) => { + logger.error('Failed to bind OAuth CSRF cookie', error); + }); + return; + } + setOAuthError(localize('com_ui_oauth_error_generic')); + setOAuthBinding('pending'); + (bindOAuth() ?? Promise.resolve()).then( + () => { + setOAuthBinding('bound'); + setOAuthError(null); + }, + (error: unknown) => { + logger.error('Failed to bind OAuth CSRF cookie', error); + setOAuthBinding('failed'); + }, + ); + }, [auth, oauthBinding, bindOAuth, localize]); const handleToggleInfo = useCallback(() => { mountBody(); @@ -329,13 +395,15 @@ export default function ToolCall({ )} - {auth != null && auth && phase === 'running' && ( + {showOAuth && (
-
diff --git a/client/src/components/MCP/__tests__/McpOAuthDialog.spec.tsx b/client/src/components/MCP/__tests__/McpOAuthDialog.spec.tsx index 1a747ca32f..d0cbdccb25 100644 --- a/client/src/components/MCP/__tests__/McpOAuthDialog.spec.tsx +++ b/client/src/components/MCP/__tests__/McpOAuthDialog.spec.tsx @@ -87,9 +87,19 @@ describe('McpOAuthDialog', () => { test('Continue opens the OAuth URL in a new tab', () => { const openSpy = jest.spyOn(window, 'open').mockImplementation(() => null); + const clickSpy = jest + .spyOn(HTMLAnchorElement.prototype, 'click') + .mockImplementation(() => undefined); render(); fireEvent.click(screen.getByText('com_ui_continue_oauth')); - expect(openSpy).toHaveBeenCalledWith(baseProps.oauthUrl, '_blank', 'noopener,noreferrer'); + expect(clickSpy).toHaveBeenCalledTimes(1); + const link = clickSpy.mock.instances[0] as unknown as HTMLAnchorElement; + expect(link.href).toBe(baseProps.oauthUrl); + expect(link.target).toBe('_blank'); + expect(link.rel).toBe('noopener noreferrer'); + /** A features string makes WebKit request a popup window, which iOS web apps cannot open. */ + expect(openSpy).not.toHaveBeenCalled(); + clickSpy.mockRestore(); openSpy.mockRestore(); }); diff --git a/client/src/components/Nav/AccountSettings.tsx b/client/src/components/Nav/AccountSettings.tsx index bb17bdcefa..be97547701 100644 --- a/client/src/components/Nav/AccountSettings.tsx +++ b/client/src/components/Nav/AccountSettings.tsx @@ -15,6 +15,7 @@ import { import { ArchivedChatsModal } from '~/components/Nav/SettingsTabs/General/ArchivedChatsModal'; import { useGetStartupConfig, useGetUserBalance } from '~/data-provider'; import { useAuthContext } from '~/hooks/AuthContext'; +import { openInNewTab } from '~/utils'; import { useLocalize } from '~/hooks'; import Settings from './Settings'; import store from '~/store'; @@ -55,7 +56,7 @@ function HelpSubmenu({ > {hasHelpFaq && ( window.open(helpAndFaqURL, '_blank', 'noopener,noreferrer')} + onClick={() => openInNewTab(helpAndFaqURL)} className="select-item text-sm" >