Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
📱 fix: Open Sign-In and External Links From iOS Home-Screen Apps (#16077)
Danny Avila038903abc0c1
diff --git a/client/src/components/Chat/Messages/Content/ToolCall.tsx b/client/src/components/Chat/Messages/Content/ToolCall.tsxindex 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<string | null>(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<void> | 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({)}</div></div>- {auth != null && auth && phase === 'running' && (+ {showOAuth && (<div className="flex w-full flex-col gap-2.5"><div className="mb-1 mt-2"><ButtonclassName="inline-flex items-center justify-center rounded-xl px-4 py-2 text-sm font-medium"variant="default"rel="noopener noreferrer"+ disabled={oauthBinding === 'pending'}+ aria-busy={oauthBinding === 'pending'}onClick={handleOAuthClick}>{localize('com_ui_sign_in_to_domain', { 0: authDomain })}diff --git a/client/src/components/Chat/Messages/Content/__tests__/ToolCall.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ToolCall.test.tsxindex ea68deae29..aa60aedfd2 100644--- a/client/src/components/Chat/Messages/Content/__tests__/ToolCall.test.tsx+++ b/client/src/components/Chat/Messages/Content/__tests__/ToolCall.test.tsx@@ -1,9 +1,10 @@import React from 'react';import { RecoilRoot } from 'recoil';-import { Tools, Constants } from 'librechat-data-provider';-import { render, screen, fireEvent } from '@testing-library/react';+import { Tools, Constants, dataService } from 'librechat-data-provider';+import { render, screen, waitFor, fireEvent } from '@testing-library/react';import { ToolAuthWarningContext } from '../auth';import ToolCall from '../ToolCall';+import { logger } from '~/utils';// Mock dependenciesjest.mock('~/hooks', () => ({@@ -105,8 +106,21 @@ jest.mock('~/utils', () => ({cn: (...classes: any[]) => classes.filter(Boolean).join(' '),getToolDisplayLabel: (name: string, localize: (key: string) => string) =>name === 'set_memory' ? localize('com_ui_tool_name_set_memory') : name,+ openInNewTab: jest.requireActual('~/utils/links').openInNewTab,}));+jest.mock('librechat-data-provider', () => {+ const actual = jest.requireActual('librechat-data-provider');+ return {+ ...actual,+ dataService: {+ ...actual.dataService,+ bindMCPOAuth: jest.fn(),+ bindActionOAuth: jest.fn(),+ },+ };+});+describe('ToolCall', () => {const mockProps = {args: '{"test": "input"}',@@ -335,8 +349,10 @@ describe('ToolCall', () => {describe('authentication flow', () => {it('should show sign-in button when auth URL is provided', () => {- const originalOpen = window.open;- window.open = jest.fn();+ const open = jest.spyOn(window, 'open').mockImplementation(() => null);+ const click = jest+ .spyOn(HTMLAnchorElement.prototype, 'click')+ .mockImplementation(() => undefined);renderWithRecoil(<ToolCall@@ -351,13 +367,122 @@ describe('ToolCall', () => {expect(signInButton).toBeInTheDocument();fireEvent.click(signInButton);- expect(window.open).toHaveBeenCalledWith(- 'https://auth.example.com',- '_blank',- 'noopener,noreferrer',- );+ expect(click).toHaveBeenCalledTimes(1);+ const link = click.mock.instances[0] as unknown as HTMLAnchorElement;+ expect(link.href).toBe('https://auth.example.com/');+ 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(open).not.toHaveBeenCalled();++ click.mockRestore();+ open.mockRestore();+ });- window.open = originalOpen;+ describe('MCP sign-in', () => {+ const callbackUrl = 'https://chat.example.com/api/mcp/clickhouse/oauth/callback';+ const mcpAuth = `https://mcp.example.com/authorize?redirect_uri=${encodeURIComponent(callbackUrl)}`;+ const mcpProps = {+ ...mockProps,+ name: `oauth${Constants.mcp_delimiter}clickhouse`,+ auth: mcpAuth,+ initialProgress: 0.5,+ isSubmitting: true,+ };+ let click: jest.SpyInstance;++ beforeEach(() => {+ click = jest+ .spyOn(HTMLAnchorElement.prototype, 'click')+ .mockImplementation(() => undefined);+ });++ afterEach(() => {+ click.mockRestore();+ });++ const signInButton = () => screen.getByRole('button', { name: 'Sign in to mcp.example.com' });++ it('binds when the prompt appears and opens the provider within the tap', async () => {+ (dataService.bindMCPOAuth as jest.Mock).mockResolvedValue({ success: true });+ renderWithRecoil(<ToolCall {...mcpProps} />);+ expect(dataService.bindMCPOAuth).toHaveBeenCalledWith('clickhouse');+ await waitFor(() => expect(signInButton()).toBeEnabled());++ fireEvent.click(signInButton());++ expect(click).toHaveBeenCalledTimes(1);+ expect((click.mock.instances[0] as unknown as HTMLAnchorElement).href).toBe(mcpAuth);+ expect(dataService.bindMCPOAuth).toHaveBeenCalledTimes(2);+ expect(dataService.bindMCPOAuth).toHaveBeenLastCalledWith('clickhouse');+ });++ it('claims the shared CSRF binding for the prompt the user taps', async () => {+ (dataService.bindMCPOAuth as jest.Mock).mockResolvedValue({ success: true });+ const notionCallback = 'https://chat.example.com/api/mcp/notion/oauth/callback';+ const notionAuth = `https://notion.example.com/authorize?redirect_uri=${encodeURIComponent(notionCallback)}`;+ const notionButton = () =>+ screen.getByRole('button', { name: 'Sign in to notion.example.com' });+ renderWithRecoil(+ <>+ <ToolCall {...mcpProps} />+ <ToolCall+ {...mcpProps}+ name={`oauth${Constants.mcp_delimiter}notion`}+ auth={notionAuth}+ />+ </>,+ );+ await waitFor(() => expect(signInButton()).toBeEnabled());+ await waitFor(() => expect(notionButton()).toBeEnabled());+ expect(dataService.bindMCPOAuth).toHaveBeenLastCalledWith('notion');++ fireEvent.click(signInButton());++ expect(click).toHaveBeenCalledTimes(1);+ expect((click.mock.instances[0] as unknown as HTMLAnchorElement).href).toBe(mcpAuth);+ expect(dataService.bindMCPOAuth).toHaveBeenLastCalledWith('clickhouse');+ });++ it('keeps sign-in disabled until the bind lands', async () => {+ let finishBind: (() => void) | undefined;+ (dataService.bindMCPOAuth as jest.Mock).mockReturnValue(+ new Promise((resolve) => {+ finishBind = () => resolve({ success: true });+ }),+ );+ renderWithRecoil(<ToolCall {...mcpProps} />);++ expect(signInButton()).toBeDisabled();+ expect(signInButton()).toHaveAttribute('aria-busy', 'true');+ fireEvent.click(signInButton());+ expect(click).not.toHaveBeenCalled();++ finishBind!();+ await waitFor(() => expect(signInButton()).toBeEnabled());+ fireEvent.click(signInButton());+ expect(click).toHaveBeenCalledTimes(1);+ });++ it('retries a failed bind on tap instead of opening the provider', async () => {+ (dataService.bindMCPOAuth as jest.Mock)+ .mockRejectedValueOnce(new Error('bind failed'))+ .mockResolvedValue({ success: true });+ renderWithRecoil(<ToolCall {...mcpProps} />);+ await waitFor(() => expect(logger.error).toHaveBeenCalled());+ await waitFor(() => expect(signInButton()).toBeEnabled());++ fireEvent.click(signInButton());++ expect(click).not.toHaveBeenCalled();+ expect(screen.getByRole('alert')).toHaveTextContent('com_ui_oauth_error_generic');+ await waitFor(() => expect(screen.queryByRole('alert')).not.toBeInTheDocument());+ expect(dataService.bindMCPOAuth).toHaveBeenCalledTimes(2);+ await waitFor(() => expect(signInButton()).toBeEnabled());++ fireEvent.click(signInButton());+ expect(click).toHaveBeenCalledTimes(1);+ });});it('should not show auth section when cancelled', () => {diff --git a/client/src/components/MCP/McpOAuthDialog.tsx b/client/src/components/MCP/McpOAuthDialog.tsxindex 873478b184..8b9007c32f 100644--- a/client/src/components/MCP/McpOAuthDialog.tsx+++ b/client/src/components/MCP/McpOAuthDialog.tsx@@ -11,7 +11,7 @@ import {} from '@librechat/client';import CopyButton from '~/components/Messages/Content/CopyButton';import { useLocalize, useCopyToClipboard } from '~/hooks';-import { cn } from '~/utils';+import { cn, openInNewTab } from '~/utils';interface McpOAuthDialogProps {open: boolean;@@ -143,7 +143,7 @@ export default function McpOAuthDialog({type="button"variant="submit"className="flex-1"- onClick={() => window.open(oauthUrl, '_blank', 'noopener,noreferrer')}+ onClick={() => openInNewTab(oauthUrl)}>{localize('com_ui_continue_oauth')}<ExternalLink className="size-4" aria-hidden="true" />diff --git a/client/src/components/MCP/ServerInitializationSection.tsx b/client/src/components/MCP/ServerInitializationSection.tsxindex 9890d901f4..5adf98b306 100644--- a/client/src/components/MCP/ServerInitializationSection.tsx+++ b/client/src/components/MCP/ServerInitializationSection.tsx@@ -3,6 +3,7 @@ import { RefreshCw, Trash2 } from 'lucide-react';import { Button, Spinner } from '@librechat/client';import { useLocalize, useMCPServerManager } from '~/hooks';import { useMCPRefresh } from '~/hooks/MCP/useMCPRefresh';+import { openInNewTab } from '~/utils';interface ServerInitializationSectionProps {sidePanel?: boolean;@@ -97,11 +98,7 @@ export default function ServerInitializationSection({>{localize('com_ui_cancel')}</Button>- <Button- variant="submit"- onClick={() => window.open(serverOAuthUrl, '_blank', 'noopener,noreferrer')}- className="flex-1"- >+ <Button variant="submit" onClick={() => openInNewTab(serverOAuthUrl)} className="flex-1">{localize('com_ui_continue_oauth')}</Button></div>diff --git a/client/src/components/MCP/__tests__/McpOAuthDialog.spec.tsx b/client/src/components/MCP/__tests__/McpOAuthDialog.spec.tsxindex 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(<McpOAuthDialog {...baseProps} />);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.tsxindex 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 && (<Menu.MenuItem- onClick={() => window.open(helpAndFaqURL, '_blank', 'noopener,noreferrer')}+ onClick={() => openInNewTab(helpAndFaqURL)}className="select-item text-sm"><LifeBuoy className="icon-md" aria-hidden="true" />@@ -69,7 +70,7 @@ function HelpSubmenu({{showLegalDivider && (hasTos || hasPrivacy) && <DropdownMenuSeparator />}{hasTos && (<Menu.MenuItem- onClick={() => window.open(termsOfServiceURL, '_blank', 'noopener,noreferrer')}+ onClick={() => openInNewTab(termsOfServiceURL)}className="select-item text-sm"><Scale className="icon-md" aria-hidden="true" />@@ -78,7 +79,7 @@ function HelpSubmenu({)}{hasPrivacy && (<Menu.MenuItem- onClick={() => window.open(privacyPolicyURL, '_blank', 'noopener,noreferrer')}+ onClick={() => openInNewTab(privacyPolicyURL)}className="select-item text-sm"><ShieldCheck className="icon-md" aria-hidden="true" />diff --git a/client/src/components/SidePanel/MCPBuilder/MCPServerCard.spec.tsx b/client/src/components/SidePanel/MCPBuilder/MCPServerCard.spec.tsxnew file mode 100644index 0000000000..617377fba8--- /dev/null+++ b/client/src/components/SidePanel/MCPBuilder/MCPServerCard.spec.tsx@@ -0,0 +1,151 @@+import React from 'react';+import '@testing-library/jest-dom/extend-expect';+import { render, screen, waitFor, fireEvent } from '@testing-library/react';+import type { MCPServerStatusIconProps } from '~/components/MCP/MCPServerStatusIcon';+import type { MCPServerDefinition } from '~/hooks';+import MCPServerCard from './MCPServerCard';++const mockInitializeServer = jest.fn();+const mockGetOAuthUrl = jest.fn();++jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string) => key,+ useMCPServerManager: () => ({+ initializeServer: mockInitializeServer,+ revokeOAuthForServer: jest.fn(),+ getOAuthUrl: mockGetOAuthUrl,+ }),+}));++jest.mock('@librechat/client', () => ({+ MCPIcon: () => <span />,+}));++jest.mock('./MCPCardActions', () => ({+ __esModule: true,+ default: ({ onInitialize }: { onInitialize: () => void }) => (+ <button type="button" onClick={onInitialize}>+ {'com_nav_mcp_connect'}+ </button>+ ),+}));++jest.mock('./MCPServerDialog', () => ({ __esModule: true, default: () => null }));+jest.mock('./MCPStatusBadge', () => ({ getStatusDotColor: () => '' }));+jest.mock('~/components/ui/CustomIcon', () => ({ __esModule: true, default: () => null }));+jest.mock('~/components/MCP/McpOAuthDialog', () => ({+ __esModule: true,+ default: ({ open, oauthUrl }: { open: boolean; oauthUrl: string }) =>+ open ? <div role="dialog">{oauthUrl}</div> : null,+}));++const server = {+ serverName: 'clickhouse',+ config: {},+ effectivePermissions: 0,+} as unknown as MCPServerDefinition;++/** Mirrors the manager's shared state: the flow URL exists only while initializing. */+const renderCard = (isInitializing: boolean, sharedOAuthUrl: string | null = null) => {+ mockGetOAuthUrl.mockReturnValue(sharedOAuthUrl);+ const statusProps = {+ serverName: 'clickhouse',+ serverStatus: { connectionState: 'disconnected', requiresOAuth: true },+ onConfigClick: jest.fn(),+ isInitializing,+ canCancel: true,+ onCancel: jest.fn(),+ hasCustomUserVars: false,+ } as unknown as MCPServerStatusIconProps;+ return (+ <MCPServerCard+ server={server}+ getServerStatusIconProps={() => statusProps}+ canCreateEditMCPs={false}+ />+ );+};++const firstUrl = 'https://auth.example/authorize?flow=1';++describe('MCPServerCard', () => {+ afterEach(() => {+ jest.clearAllMocks();+ });++ test('surfaces the authorization URL in the OAuth dialog instead of opening a tab', async () => {+ const open = jest.spyOn(window, 'open').mockImplementation(() => null);+ mockInitializeServer.mockResolvedValue({+ success: true,+ oauthRequired: true,+ oauthUrl: firstUrl,+ });+ const { rerender } = render(renderCard(false));++ fireEvent.click(screen.getByText('com_nav_mcp_connect'));+ await waitFor(() => expect(mockInitializeServer).toHaveBeenCalledWith('clickhouse', false));+ rerender(renderCard(true, firstUrl));++ expect(await screen.findByRole('dialog')).toHaveTextContent(firstUrl);+ expect(open).not.toHaveBeenCalled();++ rerender(renderCard(false));+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();+ open.mockRestore();+ });++ test('keeps the OAuth dialog closed when connecting needs no authorization', async () => {+ mockInitializeServer.mockResolvedValue({ success: true, oauthRequired: false });+ const { rerender } = render(renderCard(false));++ fireEvent.click(screen.getByText('com_nav_mcp_connect'));+ await waitFor(() => expect(mockInitializeServer).toHaveBeenCalled());+ rerender(renderCard(true));++ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();+ });++ test('stays closed for flows it did not start once its own flow ended', async () => {+ mockInitializeServer.mockResolvedValueOnce({+ success: true,+ oauthRequired: true,+ oauthUrl: firstUrl,+ });+ const { rerender } = render(renderCard(false));+ fireEvent.click(screen.getByText('com_nav_mcp_connect'));+ rerender(renderCard(true, firstUrl));+ expect(await screen.findByRole('dialog')).toBeInTheDocument();+ rerender(renderCard(false));++ /** Another surface, such as the chat's MCP menu, initializes the same server. */+ rerender(renderCard(true, 'https://auth.example/authorize?flow=2'));+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();+ });++ test('does not reopen a previous flow while the next connect is pending', async () => {+ mockInitializeServer.mockResolvedValueOnce({+ success: true,+ oauthRequired: true,+ oauthUrl: firstUrl,+ });+ const { rerender } = render(renderCard(false));+ fireEvent.click(screen.getByText('com_nav_mcp_connect'));+ rerender(renderCard(true, firstUrl));+ expect(await screen.findByRole('dialog')).toBeInTheDocument();+ rerender(renderCard(false));++ let finishSecond: ((value: { success: boolean; oauthRequired: boolean }) => void) | undefined;+ mockInitializeServer.mockReturnValueOnce(+ new Promise((resolve) => {+ finishSecond = resolve;+ }),+ );+ fireEvent.click(screen.getByText('com_nav_mcp_connect'));+ rerender(renderCard(true));+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();++ finishSecond!({ success: true, oauthRequired: false });+ await waitFor(() => expect(mockInitializeServer).toHaveBeenCalledTimes(2));+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();+ });+});diff --git a/client/src/components/SidePanel/MCPBuilder/MCPServerCard.tsx b/client/src/components/SidePanel/MCPBuilder/MCPServerCard.tsxindex e93c9781b6..2ba0e0ec6c 100644--- a/client/src/components/SidePanel/MCPBuilder/MCPServerCard.tsx+++ b/client/src/components/SidePanel/MCPBuilder/MCPServerCard.tsx@@ -1,8 +1,9 @@-import { useState, useRef } from 'react';+import { useState, useRef, useEffect } from 'react';import { MCPIcon } from '@librechat/client';import { PermissionBits, hasPermissions } from 'librechat-data-provider';import type { MCPServerStatusIconProps } from '~/components/MCP/MCPServerStatusIcon';import type { MCPServerDefinition } from '~/hooks';+import McpOAuthDialog from '~/components/MCP/McpOAuthDialog';import { useMCPServerManager, useLocalize } from '~/hooks';import { getStatusDotColor } from './MCPStatusBadge';import CustomIcon from '~/components/ui/CustomIcon';@@ -31,8 +32,9 @@ export default function MCPServerCard({}: MCPServerCardProps) {const localize = useLocalize();const triggerRef = useRef<HTMLDivElement>(null);- const { initializeServer, revokeOAuthForServer } = useMCPServerManager();+ const { initializeServer, revokeOAuthForServer, getOAuthUrl } = useMCPServerManager();const [dialogOpen, setDialogOpen] = useState(false);+ const [awaitingOAuth, setAwaitingOAuth] = useState(false);const statusIconProps = getServerStatusIconProps(server.serverName);const {@@ -49,8 +51,20 @@ export default function MCPServerCard({const description = server.config?.description;const statusDotColor = getStatusDotColor(serverStatus, isInitializing);const canEdit = canCreateEditMCPs && canEditThisServer;+ /** The shared flow URL is cleared when its initialization ends, so it can never be stale. */+ const sharedOAuthUrl = getOAuthUrl(server.serverName);- const handleInitialize = () => {+ useEffect(() => {+ if (!isInitializing) {+ setAwaitingOAuth(false);+ }+ }, [isInitializing]);++ /**+ * `autoOpenOAuth=false` surfaces the authorization URL in the OAuth dialog, whose Continue opens+ * it inside the tap. A tab opened after the initialize request is blocked on iOS home-screen apps.+ */+ const handleInitialize = async () => {/** If server has custom user vars and is not already connected, show config dialog first* This ensures users can enter credentials before initialization attempts*/@@ -58,7 +72,11 @@ export default function MCPServerCard({onConfigClick({ stopPropagation: () => {}, preventDefault: () => {} } as React.MouseEvent);return;}- initializeServer(server.serverName);+ setAwaitingOAuth(false);+ const response = await initializeServer(server.serverName, false);+ if (response?.oauthRequired && response.oauthUrl) {+ setAwaitingOAuth(true);+ }};const handleRevoke = () => {@@ -156,6 +174,17 @@ export default function MCPServerCard({server={server}/>)}+ <McpOAuthDialog+ open={awaitingOAuth && isInitializing && sharedOAuthUrl != null}+ onOpenChange={(open) => {+ if (!open) {+ setAwaitingOAuth(false);+ }+ }}+ serverName={server.serverName}+ oauthUrl={sharedOAuthUrl ?? ''}+ iconUrl={server.config?.iconPath}+ /></>);}diff --git a/client/src/hooks/MCP/useMCPServerManager.ts b/client/src/hooks/MCP/useMCPServerManager.tsindex 682fef7a4d..160ea9ec1e 100644--- a/client/src/hooks/MCP/useMCPServerManager.ts+++ b/client/src/hooks/MCP/useMCPServerManager.ts@@ -45,6 +45,7 @@ import {import { useGetStartupConfig, useMCPServersQuery, useMCPToolsQuery } from '~/data-provider';import { mcpServerInitStatesAtom, getServerInitState } from '~/store/mcp';import { getMCPReinitializeErrorMessage } from './errors';+import { openInNewTab } from '~/utils';export interface MCPServerDefinition {serverName: string;@@ -514,7 +515,7 @@ export function useMCPServerManager({});if (autoOpenOAuth) {- window.open(response.oauthUrl, '_blank', 'noopener,noreferrer');+ openInNewTab(response.oauthUrl);}startServerPolling(serverName, response.flowId, response.oauthTimeout);diff --git a/client/src/utils/index.ts b/client/src/utils/index.tsindex 30e13a2994..34addf5e1c 100644--- a/client/src/utils/index.ts+++ b/client/src/utils/index.ts@@ -31,6 +31,7 @@ export * from './messages';export * from './focus';export * from './tokens';export * from './redirect';+export * from './links';export * from './languages';export * from './conversation';export * from './endpoints';diff --git a/client/src/utils/links.ts b/client/src/utils/links.tsnew file mode 100644index 0000000000..a514fddba4--- /dev/null+++ b/client/src/utils/links.ts@@ -0,0 +1,15 @@+/**+ * Opens `url` in a new tab the way a `target="_blank"` link does, without giving the new page an+ * opener or a referrer. Call it synchronously inside the user's click: `window.open` with a+ * `noopener,noreferrer` features string asks WebKit for a popup window, which Safari opens as a+ * separate window and an iOS home-screen web app does not open at all.+ */+export function openInNewTab(url: string): void {+ const link = document.createElement('a');+ link.href = url;+ link.target = '_blank';+ link.rel = 'noopener noreferrer';+ document.body.appendChild(link);+ link.click();+ link.remove();+}