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
🔌 feat: Add a Connected Account Setting for Pull Requests (#16990)
Marco Beretta6a1a97adef7f
diff --git a/client/src/components/Nav/Settings/ConnectedAccounts.tsx b/client/src/components/Nav/Settings/ConnectedAccounts.tsxnew file mode 100644index 0000000000..3dc0c953ee--- /dev/null+++ b/client/src/components/Nav/Settings/ConnectedAccounts.tsx@@ -0,0 +1,396 @@+import { useCallback, useEffect, useId, useRef, useState } from 'react';+import { ExternalLink, Gitlab } from 'lucide-react';+import { apiBaseUrl } from 'librechat-data-provider';+import { useQueryClient } from '@tanstack/react-query';+import {+ AlertDialog,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+ AlertDialogTrigger,+ Button,+ Chip,+ GithubIcon,+ Skeleton,+ Spinner,+} from '@librechat/client';+import type { PullRequestProvider } from 'librechat-data-provider';+import type { ComponentType } from 'react';+import type { TranslationKeys } from '~/hooks';+import {+ useGetStartupConfig,+ usePullRequestConnectionQuery,+ useConnectPullRequestAccountMutation,+ useDisconnectPullRequestAccountMutation,+ watchPullRequestSignIn,+ pullRequestSignInSession,+} from '~/data-provider';+import { useLocalize } from '~/hooks';++const PROVIDERS: Record<+ PullRequestProvider,+ { Icon: ComponentType<{ className?: string }>; name: TranslationKeys }+> = {+ github: { Icon: GithubIcon, name: 'com_ui_pr_provider_github' },+ gitlab: { Icon: Gitlab, name: 'com_ui_pr_provider_gitlab' },+ bitbucket: { Icon: ExternalLink, name: 'com_ui_pr_provider_bitbucket' },+};++/** A grant whose app the server no longer has, so no provider is named for it. */+const UNNAMED_PROVIDER: (typeof PROVIDERS)[PullRequestProvider] = {+ Icon: ExternalLink,+ name: 'com_ui_settings_label_pull_request_account',+};++type ConnectError = 'com_ui_pr_account_connect_error' | 'com_ui_pr_account_popup_blocked';++/** How long a started sign-in is watched for when the server does not say how long it lasts. */+const DEFAULT_CONNECT_FLOW_SECONDS = 10 * 60;++/**+ * The user's own account for pull request lookups. One row for the provider the operator+ * configured: the status, and a single action to connect or disconnect it. The action button is+ * swapped as the state changes, so focus is carried over to whichever button replaces it.+ */+export default function ConnectedAccounts() {+ const localize = useLocalize();+ const rowId = useId();+ const { data: startupConfig } = useGetStartupConfig();+ const queryClient = useQueryClient();+ const status = usePullRequestConnectionQuery();+ const connectMutation = useConnectPullRequestAccountMutation();+ const disconnectMutation = useDisconnectPullRequestAccountMutation();+ const [confirmOpen, setConfirmOpen] = useState(false);+ const [connectError, setConnectError] = useState<ConnectError | null>(null);+ const [disconnectFailed, setDisconnectFailed] = useState(false);+ const actionRef = useRef<HTMLButtonElement | null>(null);+ const groupRef = useRef<HTMLDivElement | null>(null);+ /** Where focus goes when a disconnect removes the row along with its trigger. */+ const fallbackRef = useRef<HTMLElement | null>(null);+ const keepFocus = useRef(false);+ /** Whether the row is still shown, so a failure after Settings closed is reported elsewhere. */+ const mounted = useRef(true);+ useEffect(() => {+ mounted.current = true;+ return () => {+ mounted.current = false;+ /** A status that hides the row while a handoff is armed takes the focused button with it. */+ if (keepFocus.current) {+ const fallback = fallbackRef.current;+ setTimeout(() => {+ if (document.activeElement == null || document.activeElement === document.body) {+ fallback?.focus();+ }+ }, 0);+ }+ };+ }, []);++ /**+ * Callback ref, so a replacement button takes focus as it mounts after an action, but only+ * when the button it replaced took focus away with it.+ */+ const bindAction = useCallback((button: HTMLButtonElement | null) => {+ actionRef.current = button;+ if (button == null || !keepFocus.current) {+ return;+ }+ keepFocus.current = false;+ if (document.activeElement == null || document.activeElement === document.body) {+ button.focus();+ }+ }, []);++ /** A disconnect that failed may still have ended the connection: once the status read after it+ * says so, the confirmation closes as on success, and focus moves on the same way. */+ const disconnected = status.data?.connected === false;+ useEffect(() => {+ if (!confirmOpen || !disconnectFailed || !disconnected) {+ return;+ }+ keepFocus.current = true;+ setConfirmOpen(false);+ setDisconnectFailed(false);+ }, [confirmOpen, disconnectFailed, disconnected]);++ /**+ * The server is the authority: an app it no longer has is nothing to connect to, and once the+ * status loads its provider is the one a connection goes to, whatever the cached startup says.+ * A grant still stored stays removable after the app is turned off, or turning it back on would+ * revive it.+ */+ const revocable = status.data?.connected === true;+ /** A grant whose app is turned off: kept until removed, but no lookup uses it. */+ const unused = revocable && status.data?.configured === false;+ /** The startup config only until the status loads: after that a grant whose app is gone may+ * belong to any provider, so the row names it only as an account. */+ const provider = status.data != null ? status.data.provider : startupConfig?.pullRequestsConnect;+ if (!revocable && (provider == null || status.data?.configured === false)) {+ return null;+ }++ const { Icon, name: nameKey } = provider != null ? PROVIDERS[provider] : UNNAMED_PROVIDER;+ const name = localize(nameKey);+ const labelId = `${rowId}-label`;+ const descriptionId = `${rowId}-description`;++ const connect = () => {+ if (connectMutation.isLoading) {+ return;+ }+ setConnectError(null);+ /** Opened inside the click so the browser treats it as user initiated. */+ const popup = window.open('', '_blank');+ if (popup == null) {+ setConnectError('com_ui_pr_account_popup_blocked');+ return;+ }+ popup.opener = null;+ /**+ * The promise, not `mutate` callbacks, so the window opened in the click is still sent to the+ * sign-in page (or closed) when Settings is closed before the server answers. The watch on the+ * sign-in lives outside this row for the same reason.+ */+ const startedIn = pullRequestSignInSession();+ connectMutation.mutateAsync().then(+ ({ url, expiresInSeconds, flowId }) => {+ /** Signed out meanwhile: the sign-in belongs to a session that is over. */+ if (startedIn !== pullRequestSignInSession()) {+ popup.close();+ return;+ }+ /**+ * Closed while the server answered: the user cancelled, and nothing will sign in. Still the+ * blank page this window opened, so unlike after navigating, `closed` can be trusted here.+ */+ if (popup.closed) {+ return;+ }+ popup.location.href = url;+ keepFocus.current = true;+ watchPullRequestSignIn(queryClient, {+ startedIn,+ flowId,+ expiresAt: Date.now() + (expiresInSeconds ?? DEFAULT_CONNECT_FLOW_SECONDS) * 1000,+ });+ },+ () => {+ /** With Settings closed the row cannot explain the failure, so the window it opened does,+ * on the sign-in error page. */+ if (!mounted.current) {+ popup.location.href = `${apiBaseUrl()}/oauth/error?error=connect_failed`;+ return;+ }+ popup.close();+ setConnectError('com_ui_pr_account_connect_error');+ },+ );+ };++ const disconnect = () => {+ setDisconnectFailed(false);+ /** Taken before the request: removing a grant whose app is off removes this row too. */+ fallbackRef.current =+ groupRef.current?.closest<HTMLElement>('[role="tabpanel"], [role="dialog"]') ?? null;+ disconnectMutation.mutate(undefined, {+ onSuccess: () => {+ keepFocus.current = true;+ setConfirmOpen(false);+ },+ onError: () => setDisconnectFailed(true),+ });+ };++ const retry = () => {+ keepFocus.current = true;+ /** Taken before the request: an answer that the app is gone hides this row, Retry with it. */+ const fallback = groupRef.current?.closest<HTMLElement>('[role="tabpanel"], [role="dialog"]');+ status.refetch().then((result) => {+ if (result.isError) {+ keepFocus.current = false;+ }+ /** After React has applied the answer: focus left on nothing goes to the panel. */+ setTimeout(() => {+ const lost = document.activeElement == null || document.activeElement === document.body;+ if (groupRef.current == null && lost) {+ fallback?.focus();+ }+ }, 0);+ });+ };++ let statusContent = <Chip tone="neutral">{localize('com_ui_pr_account_checking')}</Chip>;+ let action = <Skeleton className="h-9 w-24" aria-hidden="true" />;++ const statusError = (+ <span className="text-text-destructive text-xs">+ {localize('com_ui_pr_account_status_error')}+ </span>+ );++ /** A grant known to be removable stays removable while a later status check fails. */+ if (status.isError && !revocable) {+ statusContent = statusError;+ action = (+ <Button+ ref={bindAction}+ type="button"+ variant="outline"+ size="sm"+ aria-label={localize('com_ui_retry')}+ aria-busy={status.isFetching}+ onClick={retry}+ >+ {status.isFetching ? <Spinner className="h-4 w-4" /> : localize('com_ui_retry')}+ </Button>+ );+ } else if (status.data?.connected === true) {+ statusContent = unused ? (+ <Chip tone="neutral">{localize('com_ui_pr_account_not_in_use')}</Chip>+ ) : (+ <Chip tone="success">{localize('com_ui_pr_account_connected')}</Chip>+ );+ action = (+ <AlertDialogTrigger asChild>+ <Button+ ref={bindAction}+ type="button"+ variant="outline"+ size="sm"+ aria-label={localize('com_ui_pr_account_disconnect_aria', { 0: name })}+ >+ {localize('com_ui_pr_account_disconnect')}+ </Button>+ </AlertDialogTrigger>+ );+ } else if (status.data != null) {+ statusContent = <Chip tone="neutral">{localize('com_ui_pr_account_not_connected')}</Chip>;+ action = (+ <Button+ ref={bindAction}+ type="button"+ variant="outline"+ size="sm"+ aria-label={localize('com_ui_pr_account_connect_aria', { 0: name })}+ aria-busy={connectMutation.isLoading}+ aria-disabled={connectMutation.isLoading}+ onClick={connect}+ >+ {connectMutation.isLoading ? (+ <Spinner className="h-4 w-4" />+ ) : (+ localize('com_ui_pr_account_connect')+ )}+ </Button>+ );+ }++ if (status.isError && revocable) {+ statusContent = statusError;+ }++ return (+ <AlertDialog+ open={confirmOpen}+ onOpenChange={(open) => {+ /** A disconnect already sent cannot be taken back, so it is not dismissed mid-request. */+ if (!open && disconnectMutation.isLoading) {+ return;+ }+ /** Dismissed after a failed disconnect whose status read is still out: that read may+ * replace or hide the trigger focus returns to, so the handoff stays armed. */+ if (!open && disconnectFailed) {+ keepFocus.current = true;+ }+ setConfirmOpen(open);+ setDisconnectFailed(false);+ }}+ >+ <div+ ref={groupRef}+ role="group"+ aria-labelledby={labelId}+ aria-describedby={descriptionId}+ className="flex flex-col gap-2"+ >+ <div className="flex items-center gap-3">+ <span className="text-text-secondary shrink-0" aria-hidden="true">+ <Icon className="h-5 w-5" />+ </span>+ <div className="min-w-0 flex-1">+ {/** The status sits beside the name, not in the row, so the description keeps the+ * column's width on a phone. */}+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1">+ <p id={labelId} className="text-text-primary text-sm font-medium">+ {name}+ </p>+ <div role="status">{statusContent}</div>+ </div>+ <p id={descriptionId} className="text-text-secondary text-xs">+ {localize(+ unused ? 'com_ui_pr_account_unused_description' : 'com_ui_pr_account_description',+ )}+ </p>+ </div>+ <div className="shrink-0">{action}</div>+ </div>+ {connectError != null && (+ <p role="alert" className="text-text-destructive text-xs">+ {localize(connectError)}+ </p>+ )}+ </div>++ <AlertDialogContent+ className="w-11/12 max-w-md"+ onCloseAutoFocus={(event) => {+ event.preventDefault();+ const action = actionRef.current;+ if (action?.isConnected === true) {+ action.focus();+ } else {+ fallbackRef.current?.focus();+ }+ }}+ >+ <AlertDialogHeader>+ <AlertDialogTitle>+ {localize('com_ui_pr_account_disconnect_title', { 0: name })}+ </AlertDialogTitle>+ <AlertDialogDescription>+ {localize('com_ui_pr_account_disconnect_description')}+ </AlertDialogDescription>+ </AlertDialogHeader>+ {disconnectFailed && (+ <p role="alert" className="text-text-destructive text-xs">+ {localize('com_ui_pr_account_disconnect_error')}+ </p>+ )}+ <AlertDialogFooter className="mt-2">+ <AlertDialogCancel asChild>+ <Button type="button" variant="outline" disabled={disconnectMutation.isLoading}>+ {localize('com_ui_cancel')}+ </Button>+ </AlertDialogCancel>+ <Button+ type="button"+ variant="destructive"+ aria-label={localize('com_ui_pr_account_disconnect')}+ aria-busy={disconnectMutation.isLoading}+ disabled={disconnectMutation.isLoading}+ onClick={disconnect}+ >+ {disconnectMutation.isLoading ? (+ <Spinner className="h-4 w-4" />+ ) : (+ localize('com_ui_pr_account_disconnect')+ )}+ </Button>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ );+}diff --git a/client/src/components/Nav/Settings/__tests__/ConnectedAccounts.spec.tsx b/client/src/components/Nav/Settings/__tests__/ConnectedAccounts.spec.tsxnew file mode 100644index 0000000000..c2c3f86450--- /dev/null+++ b/client/src/components/Nav/Settings/__tests__/ConnectedAccounts.spec.tsx@@ -0,0 +1,666 @@+import React from 'react';+import '@testing-library/jest-dom';+import userEvent from '@testing-library/user-event';+import { QueryKeys } from 'librechat-data-provider';+import { act, render, screen, waitFor } from '@testing-library/react';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import type { TPullRequestConnection, TStartupConfig } from 'librechat-data-provider';+import { usePullRequestConnectionStatus } from '~/data-provider/PullRequest/connection';+import { stopPullRequestSignIns } from '~/data-provider/PullRequest/signIn';+import { endPullRequestSession } from '~/data-provider/PullRequest/queries';+import ConnectedAccounts from '../ConnectedAccounts';++const mockGetConnection = jest.fn();+const mockConnect = jest.fn();+const mockDisconnect = jest.fn();+const mockStartup: { current: Partial<TStartupConfig> | undefined } = {+ current: { pullRequestsConnect: 'github' },+};++jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string, values?: Record<string, string | number>) =>+ values == null ? key : `${key}:${Object.values(values).join(',')}`,+}));++jest.mock('~/data-provider/Endpoints', () => ({+ ...jest.requireActual('~/data-provider/Endpoints'),+ useGetStartupConfig: () => ({ data: mockStartup.current }),+}));++jest.mock('librechat-data-provider', () => {+ const actual = jest.requireActual('librechat-data-provider');+ return {+ ...actual,+ dataService: {+ ...actual.dataService,+ getPullRequestConnection: (...args: unknown[]) => mockGetConnection(...args),+ connectPullRequestAccount: (...args: unknown[]) => mockConnect(...args),+ disconnectPullRequestAccount: (...args: unknown[]) => mockDisconnect(...args),+ },+ };+});++const connection = (connected: boolean): TPullRequestConnection => ({+ configured: true,+ provider: 'github',+ connected,+});++/** Rejections are part of these tests; keep React Query from logging each one. */+const logger = { log: () => undefined, warn: () => undefined, error: () => undefined };++const renderRow = () => {+ const client = new QueryClient({ logger, defaultOptions: { queries: { retry: false } } });+ const invalidate = jest.spyOn(client, 'invalidateQueries');+ const { unmount } = render(+ <QueryClientProvider client={client}>+ <ConnectedAccounts />+ </QueryClientProvider>,+ );+ return { client, invalidate, unmount };+};++/** Settings as the registry shows the row: inside a tab panel, only while the status allows it. */+function SettingsPanel() {+ const status = usePullRequestConnectionStatus();+ return (+ <div role="tabpanel" tabIndex={-1}>+ {status?.connected === true && <ConnectedAccounts />}+ </div>+ );+}++/** Settings with its own visibility rule (context.tsx): the row shows for a known grant, or while+ * the startup config offers an app and the server has not said there is none. */+function ConfigPanel() {+ const status = usePullRequestConnectionStatus();+ const shown =+ status?.connected === true ||+ (mockStartup.current?.pullRequestsConnect != null && status?.configured !== false);+ return (+ <div role="tabpanel" tabIndex={-1}>+ {shown && <ConnectedAccounts />}+ </div>+ );+}++const renderPanel = () => {+ const client = new QueryClient({ logger, defaultOptions: { queries: { retry: false } } });+ render(+ <QueryClientProvider client={client}>+ <SettingsPanel />+ </QueryClientProvider>,+ );+ return { client };+};++const fakeWindow = () => ({ opener: {} as unknown, location: { href: '' }, close: jest.fn() });++describe('ConnectedAccounts', () => {+ let openSpy: jest.SpyInstance;++ beforeEach(() => {+ mockStartup.current = { pullRequestsConnect: 'github' };+ mockGetConnection.mockReset();+ mockConnect.mockReset();+ mockDisconnect.mockReset();+ openSpy = jest.spyOn(window, 'open');+ });++ afterEach(() => {+ /** A sign-in watch outlives the row, so each test ends the one it started. */+ stopPullRequestSignIns();+ openSpy.mockRestore();+ });++ it('renders nothing and asks nothing when the deployment offers no account to connect', () => {+ mockStartup.current = {};+ const { container } = render(+ <QueryClientProvider client={new QueryClient({ logger })}>+ <ConnectedAccounts />+ </QueryClientProvider>,+ );+ expect(container).toBeEmptyDOMElement();+ expect(mockGetConnection).not.toHaveBeenCalled();+ });++ it('offers Disconnect for a grant whose app is gone from a deployment with pull requests on', async () => {+ mockStartup.current = { pullRequestsEnabled: true };+ mockGetConnection.mockResolvedValue({ configured: false, connected: true });+ renderRow();++ expect(+ await screen.findByRole('button', {+ name: 'com_ui_pr_account_disconnect_aria:com_ui_settings_label_pull_request_account',+ }),+ ).toBeInTheDocument();+ });++ it('renders nothing for a deployment with pull requests on and nothing to disconnect', async () => {+ mockStartup.current = { pullRequestsEnabled: true };+ mockGetConnection.mockResolvedValue({ configured: false, connected: false });+ const { client } = renderRow();+ await waitFor(() => expect(mockGetConnection).toHaveBeenCalled());+ await waitFor(() =>+ expect(client.getQueryData([QueryKeys.pullRequestConnection])).toBeDefined(),+ );+ expect(screen.queryByRole('button')).not.toBeInTheDocument();+ });++ it('renders nothing once the server says no app is configured', async () => {+ mockGetConnection.mockResolvedValue({ configured: false, connected: false });+ renderRow();+ await waitFor(() => expect(mockGetConnection).toHaveBeenCalled());+ await waitFor(() => expect(screen.queryByRole('status')).not.toBeInTheDocument());+ expect(screen.queryByRole('button')).not.toBeInTheDocument();+ });++ it('keeps Disconnect for a grant that outlives a turned-off app', async () => {+ mockGetConnection.mockResolvedValue({ configured: false, connected: true });+ renderRow();++ expect(+ await screen.findByRole('button', {+ name: 'com_ui_pr_account_disconnect_aria:com_ui_settings_label_pull_request_account',+ }),+ ).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: /com_ui_pr_account_connect_aria/ })).toBeNull();+ /** No lookup uses a grant whose app is off, so it is not shown as in use. */+ expect(screen.getByRole('status')).toHaveTextContent('com_ui_pr_account_not_in_use');+ expect(screen.queryByText('com_ui_pr_account_connected')).toBeNull();+ expect(screen.getByText('com_ui_pr_account_unused_description')).toBeInTheDocument();+ expect(screen.queryByText('com_ui_pr_account_description')).toBeNull();+ });++ it('shows the success status and lookup copy for a grant the current app uses', async () => {+ mockGetConnection.mockResolvedValue(connection(true));+ renderRow();+ await screen.findByRole('button', { name: /com_ui_pr_account_disconnect_aria/ });+ expect(screen.getByRole('status')).toHaveTextContent('com_ui_pr_account_connected');+ expect(screen.getByText('com_ui_pr_account_description')).toBeInTheDocument();+ });++ it('shows a checking status and no action while the connection loads', () => {+ mockGetConnection.mockReturnValue(new Promise(() => undefined));+ renderRow();+ expect(screen.getByRole('status')).toHaveTextContent('com_ui_pr_account_checking');+ expect(screen.queryByRole('button')).not.toBeInTheDocument();+ });++ it('connects through a window opened in the click, then sends it to the sign-in page', async () => {+ const popup = fakeWindow();+ openSpy.mockReturnValue(popup as unknown as Window);+ mockGetConnection.mockResolvedValue(connection(false));+ mockConnect.mockResolvedValue({ url: 'https://github.com/login/oauth/authorize?x=1' });+ renderRow();++ const button = await screen.findByRole('button', {+ name: 'com_ui_pr_account_connect_aria:com_ui_pr_provider_github',+ });+ expect(screen.getByRole('status')).toHaveTextContent('com_ui_pr_account_not_connected');+ await userEvent.click(button);++ expect(openSpy).toHaveBeenCalledWith('', '_blank');+ expect(popup.opener).toBeNull();+ expect(mockConnect).toHaveBeenCalledTimes(1);+ await waitFor(() =>+ expect(popup.location.href).toBe('https://github.com/login/oauth/authorize?x=1'),+ );+ expect(popup.close).not.toHaveBeenCalled();+ });++ it('keeps asking while the sign-in is open, so a finish without refocus still shows', async () => {+ const popup = fakeWindow();+ openSpy.mockReturnValue(popup as unknown as Window);+ mockGetConnection.mockResolvedValue(connection(false));+ mockConnect.mockResolvedValue({ url: 'https://github.com/login/oauth/authorize?x=1' });+ const { invalidate } = renderRow();++ await userEvent.click(+ await screen.findByRole('button', { name: /com_ui_pr_account_connect_aria/ }),+ );+ await waitFor(() => expect(popup.location.href).not.toBe(''));+ const before = mockGetConnection.mock.calls.length;+ mockGetConnection.mockResolvedValue(connection(true));++ expect(+ await screen.findByRole(+ 'button',+ { name: /com_ui_pr_account_disconnect_aria/ },+ { timeout: 5000 },+ ),+ ).toBeInTheDocument();+ expect(mockGetConnection.mock.calls.length).toBeGreaterThan(before);+ expect(invalidate).toHaveBeenCalledWith([QueryKeys.conversationPullRequest]);++ const settled = mockGetConnection.mock.calls.length;+ await new Promise((resolve) => setTimeout(resolve, 2500));+ expect(mockGetConnection).toHaveBeenCalledTimes(settled);+ }, 15000);++ it('stops watching when the flow the server started expires', async () => {+ const popup = fakeWindow();+ openSpy.mockReturnValue(popup as unknown as Window);+ mockGetConnection.mockResolvedValue(connection(false));+ mockConnect.mockResolvedValue({+ url: 'https://github.com/login/oauth/authorize?x=1',+ expiresInSeconds: 1,+ });+ renderRow();++ await userEvent.click(+ await screen.findByRole('button', { name: /com_ui_pr_account_connect_aria/ }),+ );+ await waitFor(() => expect(popup.location.href).not.toBe(''));+ const started = mockGetConnection.mock.calls.length;+ /** Past one poll interval: a watch still running would have asked again by now. */+ await new Promise((resolve) => setTimeout(resolve, 2500));+ expect(mockGetConnection).toHaveBeenCalledTimes(started);+ }, 10000);++ it('still sends the window to the sign-in page when Settings closes first', async () => {+ const popup = fakeWindow();+ openSpy.mockReturnValue(popup as unknown as Window);+ mockGetConnection.mockResolvedValue(connection(false));+ let answer: (value: { url: string }) => void = () => undefined;+ mockConnect.mockReturnValueOnce(new Promise((resolve) => (answer = resolve)));+ const { unmount } = renderRow();++ await userEvent.click(+ await screen.findByRole('button', { name: /com_ui_pr_account_connect_aria/ }),+ );+ await waitFor(() => expect(mockConnect).toHaveBeenCalledTimes(1));+ unmount();+ answer({ url: 'https://github.com/login/oauth/authorize?x=1' });++ await waitFor(() =>+ expect(popup.location.href).toBe('https://github.com/login/oauth/authorize?x=1'),+ );+ expect(popup.close).not.toHaveBeenCalled();+ });++ it('starts nothing when the window is closed before the server answers', async () => {+ const popup = { ...fakeWindow(), closed: false };+ openSpy.mockReturnValue(popup as unknown as Window);+ mockGetConnection.mockResolvedValue(connection(false));+ let answer: (value: { url: string }) => void = () => undefined;+ mockConnect.mockReturnValueOnce(new Promise((resolve) => (answer = resolve)));+ renderRow();++ await userEvent.click(+ await screen.findByRole('button', { name: /com_ui_pr_account_connect_aria/ }),+ );+ await waitFor(() => expect(mockConnect).toHaveBeenCalledTimes(1));+ popup.closed = true;+ const asked = mockGetConnection.mock.calls.length;+ answer({ url: 'https://github.com/login/oauth/authorize?x=1' });++ /** Past the first poll: a watch started anyway would have asked by now. */+ await new Promise((resolve) => setTimeout(resolve, 2500));+ expect(popup.location.href).toBe('');+ expect(mockGetConnection).toHaveBeenCalledTimes(asked);+ }, 10000);++ it('closes the window instead of signing in when the session ends first', async () => {+ const popup = fakeWindow();+ openSpy.mockReturnValue(popup as unknown as Window);+ mockGetConnection.mockResolvedValue(connection(false));+ let answer: (value: { url: string }) => void = () => undefined;+ mockConnect.mockReturnValueOnce(new Promise((resolve) => (answer = resolve)));+ const { unmount } = renderRow();++ await userEvent.click(+ await screen.findByRole('button', { name: /com_ui_pr_account_connect_aria/ }),+ );+ await waitFor(() => expect(mockConnect).toHaveBeenCalledTimes(1));+ unmount();+ endPullRequestSession();+ answer({ url: 'https://github.com/login/oauth/authorize?x=1' });++ await waitFor(() => expect(popup.close).toHaveBeenCalledTimes(1));+ expect(popup.location.href).toBe('');+ });++ it('shows the sign-in error page in the window when the connection fails after Settings closed', async () => {+ const popup = fakeWindow();+ openSpy.mockReturnValue(popup as unknown as Window);+ mockGetConnection.mockResolvedValue(connection(false));+ let fail: (error: Error) => void = () => undefined;+ mockConnect.mockReturnValueOnce(new Promise((_resolve, reject) => (fail = reject)));+ const { unmount } = renderRow();++ await userEvent.click(+ await screen.findByRole('button', { name: /com_ui_pr_account_connect_aria/ }),+ );+ await waitFor(() => expect(mockConnect).toHaveBeenCalledTimes(1));+ unmount();+ fail(new Error('500'));++ /** The row is gone, so the window explains the failure instead of vanishing. */+ await waitFor(() => expect(popup.location.href).toBe('/oauth/error?error=connect_failed'));+ expect(popup.close).not.toHaveBeenCalled();+ });++ it('refreshes pull requests when the sign-in finishes after Settings closed', async () => {+ const popup = fakeWindow();+ openSpy.mockReturnValue(popup as unknown as Window);+ mockGetConnection.mockResolvedValue(connection(false));+ mockConnect.mockResolvedValue({ url: 'https://github.com/login/oauth/authorize?x=1' });+ const { client, invalidate, unmount } = renderRow();++ await userEvent.click(+ await screen.findByRole('button', { name: /com_ui_pr_account_connect_aria/ }),+ );+ await waitFor(() => expect(popup.location.href).not.toBe(''));+ unmount();+ const before = invalidate.mock.calls.length;+ mockGetConnection.mockResolvedValue(connection(true));++ await waitFor(+ () =>+ expect(client.getQueryData([QueryKeys.pullRequestConnection])).toEqual(connection(true)),+ { timeout: 5000 },+ );+ expect(invalidate.mock.calls.length).toBeGreaterThan(before);+ expect(invalidate).toHaveBeenLastCalledWith([QueryKeys.conversationPullRequest]);+ }, 10000);++ it('closes the opened window and explains when the connection cannot start', async () => {+ const popup = fakeWindow();+ openSpy.mockReturnValue(popup as unknown as Window);+ mockGetConnection.mockResolvedValue(connection(false));+ mockConnect.mockRejectedValue(new Error('500'));+ renderRow();++ await userEvent.click(+ await screen.findByRole('button', { name: /com_ui_pr_account_connect_aria/ }),+ );++ expect(await screen.findByRole('alert')).toHaveTextContent('com_ui_pr_account_connect_error');+ expect(popup.close).toHaveBeenCalledTimes(1);+ expect(popup.location.href).toBe('');+ });++ it('does not start the flow when the browser blocks the window', async () => {+ openSpy.mockReturnValue(null);+ mockGetConnection.mockResolvedValue(connection(false));+ renderRow();++ await userEvent.click(+ await screen.findByRole('button', { name: /com_ui_pr_account_connect_aria/ }),+ );++ expect(screen.getByRole('alert')).toHaveTextContent('com_ui_pr_account_popup_blocked');+ expect(mockConnect).not.toHaveBeenCalled();+ });++ it('asks before disconnecting, then disconnects and refreshes pull requests', async () => {+ mockGetConnection.mockResolvedValue(connection(true));+ mockDisconnect.mockResolvedValue(undefined);+ const { invalidate } = renderRow();++ const trigger = await screen.findByRole('button', {+ name: 'com_ui_pr_account_disconnect_aria:com_ui_pr_provider_github',+ });+ expect(screen.getByRole('status')).toHaveTextContent('com_ui_pr_account_connected');+ await userEvent.click(trigger);++ const dialog = await screen.findByRole('alertdialog');+ expect(dialog).toHaveTextContent(+ 'com_ui_pr_account_disconnect_title:com_ui_pr_provider_github',+ );+ expect(mockDisconnect).not.toHaveBeenCalled();++ mockGetConnection.mockResolvedValue(connection(false));+ await userEvent.click(screen.getByRole('button', { name: 'com_ui_pr_account_disconnect' }));++ await waitFor(() => expect(mockDisconnect).toHaveBeenCalledTimes(1));+ await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument());+ expect(invalidate).toHaveBeenCalledWith([QueryKeys.pullRequestConnection]);+ expect(invalidate).toHaveBeenCalledWith([QueryKeys.conversationPullRequest]);+ const connect = await screen.findByRole('button', { name: /com_ui_pr_account_connect_aria/ });+ expect(screen.getByRole('status')).toHaveTextContent('com_ui_pr_account_not_connected');+ await waitFor(() => expect(connect).toHaveFocus());+ });++ it('asks for the status once when Settings reveals a grant whose app is off', async () => {+ mockStartup.current = { pullRequestsEnabled: true };+ mockGetConnection.mockResolvedValue({ configured: false, connected: true });+ renderPanel();++ expect(+ await screen.findByRole('button', { name: /com_ui_pr_account_disconnect_aria/ }),+ ).toBeInTheDocument();+ expect(mockGetConnection).toHaveBeenCalledTimes(1);+ });++ it('moves focus to the panel when disconnecting removes the last row', async () => {+ mockStartup.current = { pullRequestsEnabled: true };+ mockGetConnection.mockResolvedValue({ configured: false, connected: true });+ mockDisconnect.mockResolvedValue(undefined);+ renderPanel();++ await userEvent.click(+ await screen.findByRole('button', { name: /com_ui_pr_account_disconnect_aria/ }),+ );+ await screen.findByRole('alertdialog');+ mockGetConnection.mockResolvedValue({ configured: false, connected: false });+ await userEvent.click(screen.getByRole('button', { name: 'com_ui_pr_account_disconnect' }));++ await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument());+ expect(screen.queryByRole('group')).toBeNull();+ await waitFor(() => expect(screen.getByRole('tabpanel')).toHaveFocus());+ });++ it('moves focus to the panel when a retry finds the app gone and hides the row', async () => {+ mockGetConnection.mockRejectedValueOnce(new Error('500'));+ const client = new QueryClient({ logger, defaultOptions: { queries: { retry: false } } });+ render(+ <QueryClientProvider client={client}>+ <ConfigPanel />+ </QueryClientProvider>,+ );++ const retry = await screen.findByRole('button', { name: 'com_ui_retry' });+ mockGetConnection.mockResolvedValue({ configured: false, connected: false });+ await userEvent.click(retry);++ await waitFor(() => expect(screen.queryByRole('group')).toBeNull());+ await waitFor(() => expect(screen.getByRole('tabpanel')).toHaveFocus());+ });++ it('cannot be cancelled or dismissed once the disconnect is sent', async () => {+ mockGetConnection.mockResolvedValue(connection(true));+ let settle: () => void = () => undefined;+ mockDisconnect.mockReturnValueOnce(new Promise<void>((resolve) => (settle = resolve)));+ renderRow();++ await userEvent.click(+ await screen.findByRole('button', { name: /com_ui_pr_account_disconnect_aria/ }),+ );+ await userEvent.click(+ await screen.findByRole('button', { name: 'com_ui_pr_account_disconnect' }),+ );++ const cancel = screen.getByRole('button', { name: 'com_ui_cancel' });+ await waitFor(() => expect(cancel).toBeDisabled());+ await userEvent.keyboard('{Escape}');+ expect(screen.getByRole('alertdialog')).toBeInTheDocument();++ settle();+ await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument());+ });++ it('keeps the confirmation open with an error when disconnecting fails', async () => {+ mockGetConnection.mockResolvedValue(connection(true));+ mockDisconnect.mockRejectedValue(new Error('500'));+ renderRow();++ await userEvent.click(+ await screen.findByRole('button', { name: /com_ui_pr_account_disconnect_aria/ }),+ );+ await userEvent.click(+ await screen.findByRole('button', { name: 'com_ui_pr_account_disconnect' }),+ );++ expect(await screen.findByRole('alert')).toHaveTextContent(+ 'com_ui_pr_account_disconnect_error',+ );+ expect(screen.getByRole('alertdialog')).toBeInTheDocument();+ });++ it('closes the confirmation when a failed disconnect had ended the connection after all', async () => {+ mockGetConnection.mockResolvedValue(connection(true));+ mockDisconnect.mockRejectedValue(new Error('500'));+ const { invalidate } = renderRow();++ await userEvent.click(+ await screen.findByRole('button', { name: /com_ui_pr_account_disconnect_aria/ }),+ );+ const asked = mockGetConnection.mock.calls.length;+ invalidate.mockClear();+ /** The server fenced the grant before the request failed. */+ mockGetConnection.mockResolvedValue(connection(false));+ await userEvent.click(+ await screen.findByRole('button', { name: 'com_ui_pr_account_disconnect' }),+ );++ await waitFor(() => expect(mockGetConnection.mock.calls.length).toBeGreaterThan(asked));+ await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument());+ const connect = await screen.findByRole('button', { name: /com_ui_pr_account_connect_aria/ });+ await waitFor(() => expect(connect).toHaveFocus());+ /** Pull requests follow the server's token now. */+ await waitFor(() =>+ expect(invalidate).toHaveBeenCalledWith([QueryKeys.conversationPullRequest]),+ );+ });++ it('hands focus on when a dismissed failed disconnect turns out to have ended the connection', async () => {+ mockGetConnection.mockResolvedValue(connection(true));+ mockDisconnect.mockRejectedValue(new Error('500'));+ renderRow();++ await userEvent.click(+ await screen.findByRole('button', { name: /com_ui_pr_account_disconnect_aria/ }),+ );+ /** The status read after the failure is slow. */+ let answer: (status: TPullRequestConnection) => void = () => undefined;+ mockGetConnection.mockImplementation(() => new Promise((resolve) => (answer = resolve)));+ await userEvent.click(+ await screen.findByRole('button', { name: 'com_ui_pr_account_disconnect' }),+ );+ expect(await screen.findByRole('alert')).toHaveTextContent(+ 'com_ui_pr_account_disconnect_error',+ );+ await userEvent.click(screen.getByRole('button', { name: 'com_ui_cancel' }));+ await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument());++ act(() => answer(connection(false)));+ const connect = await screen.findByRole('button', { name: /com_ui_pr_account_connect_aria/ });+ await waitFor(() => expect(connect).toHaveFocus());+ });++ it('keeps the error when the status read after a failed disconnect still shows the grant', async () => {+ mockGetConnection.mockResolvedValue(connection(true));+ mockDisconnect.mockRejectedValue(new Error('500'));+ renderRow();++ await userEvent.click(+ await screen.findByRole('button', { name: /com_ui_pr_account_disconnect_aria/ }),+ );+ const asked = mockGetConnection.mock.calls.length;+ await userEvent.click(+ await screen.findByRole('button', { name: 'com_ui_pr_account_disconnect' }),+ );++ await waitFor(() => expect(mockGetConnection.mock.calls.length).toBeGreaterThan(asked));+ expect(await screen.findByRole('alert')).toHaveTextContent(+ 'com_ui_pr_account_disconnect_error',+ );+ expect(screen.getByRole('alertdialog')).toBeInTheDocument();+ });++ it('keeps the confirmation button named while the disconnect is in flight', async () => {+ mockGetConnection.mockResolvedValue(connection(true));+ let settle: () => void = () => undefined;+ mockDisconnect.mockReturnValueOnce(new Promise<void>((resolve) => (settle = resolve)));+ renderRow();++ await userEvent.click(+ await screen.findByRole('button', { name: /com_ui_pr_account_disconnect_aria/ }),+ );+ const confirm = await screen.findByRole('button', { name: 'com_ui_pr_account_disconnect' });+ await userEvent.click(confirm);++ await waitFor(() => expect(confirm).toHaveAttribute('aria-busy', 'true'));+ expect(screen.getByRole('button', { name: 'com_ui_pr_account_disconnect' })).toBe(confirm);+ settle();+ await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument());+ });++ it('names the provider the server reports over a stale startup config', async () => {+ mockGetConnection.mockResolvedValue({ configured: true, provider: 'gitlab', connected: false });+ renderRow();++ expect(+ await screen.findByRole('button', {+ name: 'com_ui_pr_account_connect_aria:com_ui_pr_provider_gitlab',+ }),+ ).toBeInTheDocument();+ expect(screen.getByRole('group')).toHaveAccessibleName('com_ui_pr_provider_gitlab');+ });++ it('explains a failed status check and retries it', async () => {+ mockGetConnection.mockRejectedValueOnce(new Error('500'));+ renderRow();++ const retry = await screen.findByRole('button', { name: 'com_ui_retry' });+ expect(screen.getByRole('status')).toHaveTextContent('com_ui_pr_account_status_error');++ mockGetConnection.mockResolvedValueOnce(connection(true));+ await userEvent.click(retry);++ expect(+ await screen.findByRole('button', { name: /com_ui_pr_account_disconnect_aria/ }),+ ).toBeInTheDocument();+ expect(mockGetConnection).toHaveBeenCalledTimes(2);+ });++ it('keeps Disconnect for a known grant when a later status check fails', async () => {+ mockGetConnection.mockResolvedValueOnce(connection(true));+ const { client } = renderRow();+ await screen.findByRole('button', { name: /com_ui_pr_account_disconnect_aria/ });++ mockGetConnection.mockRejectedValueOnce(new Error('500'));+ await client.refetchQueries([QueryKeys.pullRequestConnection]);++ await waitFor(() =>+ expect(screen.getByRole('status')).toHaveTextContent('com_ui_pr_account_status_error'),+ );+ expect(+ screen.getByRole('button', { name: /com_ui_pr_account_disconnect_aria/ }),+ ).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'com_ui_retry' })).toBeNull();+ });++ it('keeps the retry button named while a failed refresh is retried', async () => {+ mockGetConnection.mockResolvedValueOnce(connection(false));+ const { client } = renderRow();+ await screen.findByRole('button', { name: /com_ui_pr_account_connect_aria/ });++ mockGetConnection.mockRejectedValueOnce(new Error('500'));+ await client.refetchQueries([QueryKeys.pullRequestConnection]);+ const retry = await screen.findByRole('button', { name: 'com_ui_retry' });++ let answer: (value: TPullRequestConnection) => void = () => undefined;+ mockGetConnection.mockReturnValueOnce(new Promise((resolve) => (answer = resolve)));+ await userEvent.click(retry);++ await waitFor(() => expect(retry).toHaveAttribute('aria-busy', 'true'));+ expect(screen.getByRole('button', { name: 'com_ui_retry' })).toBe(retry);+ answer(connection(false));+ expect(+ await screen.findByRole('button', { name: /com_ui_pr_account_connect_aria/ }),+ ).toBeInTheDocument();+ });+});diff --git a/client/src/components/Nav/Settings/__tests__/Sidebar.spec.tsx b/client/src/components/Nav/Settings/__tests__/Sidebar.spec.tsxindex e6b62614a9..0c42e897c0 100644--- a/client/src/components/Nav/Settings/__tests__/Sidebar.spec.tsx+++ b/client/src/components/Nav/Settings/__tests__/Sidebar.spec.tsx@@ -18,6 +18,7 @@ const ctx: SettingsContextValue = {emailEnabled: true,allowEmailChange: true,passkeyLoginEnabled: false,+ hasPullRequestConnect: false,isTwoFactorPolicyProvider: true,twoFactorEnabled: false,allowAccountDeletion: true,diff --git a/client/src/components/Nav/Settings/__tests__/context.spec.tsx b/client/src/components/Nav/Settings/__tests__/context.spec.tsxindex c6add06fe1..08cf15a023 100644--- a/client/src/components/Nav/Settings/__tests__/context.spec.tsx+++ b/client/src/components/Nav/Settings/__tests__/context.spec.tsx@@ -1,12 +1,14 @@import { RecoilRoot } from 'recoil';import { renderHook } from '@testing-library/react';-import type { TUser } from 'librechat-data-provider';+import type { TPullRequestConnection, TStartupConfig, TUser } from 'librechat-data-provider';import type { PropsWithChildren } from 'react';import { useSettingsContext } from '../context';type LegacyProviderUser = Omit<TUser, 'provider'> & { provider?: string | null };let mockUser: LegacyProviderUser | undefined;+let mockStartup: Partial<TStartupConfig> | undefined;+let mockConnection: TPullRequestConnection | undefined;jest.mock('~/hooks', () => ({useAuthContext: () => ({ user: mockUser }),@@ -20,7 +22,8 @@ jest.mock('~/hooks/usePersonalizationAccess', () => () => ({}));jest.mock('~/data-provider', () => ({- useGetStartupConfig: () => ({ data: undefined }),+ useGetStartupConfig: () => ({ data: mockStartup }),+ usePullRequestConnectionStatus: () => mockConnection,}));jest.mock('../../SettingsTabs/ProviderKeys/useProviderKeys', () => () => []);@@ -76,3 +79,41 @@ describe('useSettingsContext two-factor policy scope', () => {expect(policyProviderFor(undefined)).toBe(false);});});++describe('useSettingsContext connected accounts', () => {+ afterEach(() => {+ mockStartup = undefined;+ mockConnection = undefined;+ });++ const hasConnect = () =>+ renderHook(() => useSettingsContext(), { wrapper }).result.current.hasPullRequestConnect;++ it('offers the section when the deployment advertises an app, before the status loads', () => {+ mockStartup = { pullRequestsConnect: 'github' };+ expect(hasConnect()).toBe(true);+ });++ it('hides the section once the server says no app is configured', () => {+ mockStartup = { pullRequestsConnect: 'github' };+ mockConnection = { configured: false, connected: false };+ expect(hasConnect()).toBe(false);+ });++ it('keeps the section while a stored grant outlives its app', () => {+ mockStartup = { pullRequestsConnect: 'github' };+ mockConnection = { configured: false, connected: true };+ expect(hasConnect()).toBe(true);+ });++ it('offers the section for a surviving grant when no app is advertised any more', () => {+ mockStartup = { pullRequestsEnabled: true };+ mockConnection = { configured: false, connected: true };+ expect(hasConnect()).toBe(true);+ });++ it('never offers the section when the deployment advertises no app', () => {+ mockConnection = { configured: true, provider: 'github', connected: false };+ expect(hasConnect()).toBe(false);+ });+});diff --git a/client/src/components/Nav/Settings/__tests__/registry.spec.ts b/client/src/components/Nav/Settings/__tests__/registry.spec.tsindex 22439a9d86..fd7d4d7de4 100644--- a/client/src/components/Nav/Settings/__tests__/registry.spec.ts+++ b/client/src/components/Nav/Settings/__tests__/registry.spec.ts@@ -20,6 +20,7 @@ const settingsContext: SettingsContextValue = {emailEnabled: true,allowEmailChange: true,passkeyLoginEnabled: false,+ hasPullRequestConnect: false,isTwoFactorPolicyProvider: true,twoFactorEnabled: false,allowAccountDeletion: true,diff --git a/client/src/components/Nav/Settings/context.tsx b/client/src/components/Nav/Settings/context.tsxindex 6a2db1bb55..157cc20dd6 100644--- a/client/src/components/Nav/Settings/context.tsx+++ b/client/src/components/Nav/Settings/context.tsx@@ -7,10 +7,10 @@ import {isTwoFactorPolicyProvider,} from 'librechat-data-provider';import type { SettingsContextValue } from './types';+import { useGetStartupConfig, usePullRequestConnectionStatus } from '~/data-provider';import useProviderKeys from '../SettingsTabs/ProviderKeys/useProviderKeys';import { useHasAccess, useAuthContext, useGetAgentsConfig } from '~/hooks';import usePersonalizationAccess from '~/hooks/usePersonalizationAccess';-import { useGetStartupConfig } from '~/data-provider';import { hasAnalyticsGtmId } from '~/store/analytics';import store from '~/store';@@ -18,6 +18,7 @@ export function useSettingsContext(): SettingsContextValue {const { user } = useAuthContext();const { data: startupConfig } = useGetStartupConfig();const { agentsConfig } = useGetAgentsConfig();+ const pullRequestConnection = usePullRequestConnectionStatus();const { hasAnyPersonalizationFeature, hasMemoryOptOut } = usePersonalizationAccess();const hasRemoteAgents = useHasAccess({@@ -40,6 +41,10 @@ export function useSettingsContext(): SettingsContextValue {const emailEnabled = startupConfig?.emailEnabled === true;const allowEmailChange = startupConfig?.allowEmailChange === true;const passkeyLoginEnabled = startupConfig?.passkeyLoginEnabled === true;+ /** Also while a stored grant outlives its app, so it can still be disconnected. */+ const hasPullRequestConnect =+ pullRequestConnection?.connected === true ||+ (startupConfig?.pullRequestsConnect != null && pullRequestConnection?.configured !== false);const twoFactorPolicyProvider = user != null && isTwoFactorPolicyProvider(user.provider);const twoFactorEnabled = user?.twoFactorEnabled === true;const allowAccountDeletion = startupConfig?.allowAccountDeletion !== false;@@ -79,6 +84,7 @@ export function useSettingsContext(): SettingsContextValue {emailEnabled,allowEmailChange,passkeyLoginEnabled,+ hasPullRequestConnect,isTwoFactorPolicyProvider: twoFactorPolicyProvider,twoFactorEnabled,allowAccountDeletion,@@ -105,6 +111,7 @@ export function useSettingsContext(): SettingsContextValue {emailEnabled,allowEmailChange,passkeyLoginEnabled,+ hasPullRequestConnect,twoFactorPolicyProvider,twoFactorEnabled,allowAccountDeletion,diff --git a/client/src/components/Nav/Settings/registry.tsx b/client/src/components/Nav/Settings/registry.tsxindex ff7e713747..e1a0bea798 100644--- a/client/src/components/Nav/Settings/registry.tsx+++ b/client/src/components/Nav/Settings/registry.tsx@@ -59,6 +59,7 @@ import ProviderKeys from '../SettingsTabs/ProviderKeys';import { showLiaAtom } from '~/components/Lia/store';import { autoScrollAtom } from '~/store/autoScroll';import Avatar from '../SettingsTabs/Account/Avatar';+import ConnectedAccounts from './ConnectedAccounts';import CodeEnvironments from './CodeEnvironments';import About from '../SettingsTabs/About/About';import ApiKeys from '../SettingsTabs/ApiKeys';@@ -829,6 +830,16 @@ export const registry: SettingEntry[] = [show: (ctx) => ctx.passkeyLoginEnabled,Component: Passkeys,},+ // Account · Connected accounts+ {+ id: 'pullRequestAccount',+ tab: ACCOUNT,+ section: 'connections',+ labelKey: 'com_ui_settings_label_pull_request_account',+ keywords: ['github', 'gitlab', 'bitbucket', 'pull request', 'oauth', 'connect'],+ show: (ctx) => ctx.hasPullRequestConnect,+ Component: ConnectedAccounts,+ },// Account · Billing{id: 'tokenCredits',diff --git a/client/src/components/Nav/Settings/types.ts b/client/src/components/Nav/Settings/types.tsindex 145bd7b809..098c6851f6 100644--- a/client/src/components/Nav/Settings/types.ts+++ b/client/src/components/Nav/Settings/types.ts@@ -35,6 +35,7 @@ export type SectionId =| 'danger'| 'profile'| 'security'+ | 'connections'| 'billing'| 'about';@@ -51,6 +52,7 @@ export interface SettingsContextValue {emailEnabled: boolean;allowEmailChange: boolean;passkeyLoginEnabled: boolean;+ hasPullRequestConnect: boolean;isTwoFactorPolicyProvider: boolean;twoFactorEnabled: boolean;allowAccountDeletion: boolean;@@ -167,6 +169,7 @@ export const TABS: TabMeta[] = [sections: [{ id: 'profile', labelKey: 'com_ui_settings_section_profile' },{ id: 'security', labelKey: 'com_ui_settings_section_security' },+ { id: 'connections', labelKey: 'com_ui_settings_section_connections' },{ id: 'billing', labelKey: 'com_ui_settings_section_billing' },{ id: 'danger', labelKey: 'com_ui_settings_section_danger_zone', danger: true },],diff --git a/client/src/components/OAuth/OAuthError.tsx b/client/src/components/OAuth/OAuthError.tsxindex 64820dcc21..6d00e4f805 100644--- a/client/src/components/OAuth/OAuthError.tsx+++ b/client/src/components/OAuth/OAuthError.tsx@@ -1,12 +1,19 @@-import React from 'react';+import React, { useEffect } from 'react';import { Button } from '@librechat/client';import { useSearchParams } from 'react-router-dom';+import { announceOAuthSettled } from '~/data-provider';import { useLocalize } from '~/hooks';export default function OAuthError() {const localize = useLocalize();const [searchParams] = useSearchParams();const error = searchParams.get('error') || 'unknown_error';+ const flowId = searchParams.get('flow') ?? undefined;++ useEffect(() => {+ /** Ends the watch on this sign-in in the window that started it, which no longer polls. */+ announceOAuthSettled({ outcome: 'failed', flowId });+ }, [flowId]);const getErrorMessage = (error: string): string => {switch (error) {@@ -36,12 +43,12 @@ export default function OAuthError() {};return (- <div className="flex min-h-screen items-center justify-center bg-surface-secondary p-8">- <div className="w-full max-w-md rounded-lg bg-surface-primary p-8 text-center shadow-lg">+ <div className="bg-surface-secondary flex min-h-screen items-center justify-center p-8">+ <div className="bg-surface-primary w-full max-w-md rounded-lg p-8 text-center shadow-lg"><div className="mb-4 flex justify-center">- <div className="flex h-12 w-12 items-center justify-center rounded-full bg-status-error-subtle">+ <div className="bg-status-error-subtle flex h-12 w-12 items-center justify-center rounded-full"><svg- className="h-6 w-6 text-status-error"+ className="text-status-error h-6 w-6"fill="none"viewBox="0 0 24 24"stroke="currentColor"@@ -56,10 +63,10 @@ export default function OAuthError() {</svg></div></div>- <h1 className="mb-4 text-3xl font-bold text-text-primary">+ <h1 className="text-text-primary mb-4 text-3xl font-bold">{localize('com_ui_oauth_error_title') || 'Authentication Failed'}</h1>- <p className="mb-6 text-sm text-text-secondary">{getErrorMessage(error)}</p>+ <p className="text-text-secondary mb-6 text-sm">{getErrorMessage(error)}</p><Buttonvariant="default"onClick={() => window.close()}diff --git a/client/src/components/OAuth/OAuthSuccess.tsx b/client/src/components/OAuth/OAuthSuccess.tsxindex fdda4f3217..c1d19fd7ca 100644--- a/client/src/components/OAuth/OAuthSuccess.tsx+++ b/client/src/components/OAuth/OAuthSuccess.tsx@@ -1,5 +1,6 @@import React, { useEffect, useState } from 'react';import { useSearchParams } from 'react-router-dom';+import { announceOAuthSettled } from '~/data-provider';import { useLocalize } from '~/hooks';export default function OAuthSuccess() {@@ -7,6 +8,12 @@ export default function OAuthSuccess() {const [searchParams] = useSearchParams();const [secondsLeft, setSecondsLeft] = useState(3);const serverName = searchParams.get('serverName');+ const flowId = searchParams.get('flow') ?? undefined;++ useEffect(() => {+ /** Reaches the window that started the sign-in even when the provider severed the popup. */+ announceOAuthSettled({ outcome: 'succeeded', flowId });+ }, [flowId]);useEffect(() => {const countdown = setInterval(() => {@@ -24,19 +31,19 @@ export default function OAuthSuccess() {}, []);return (- <div className="flex min-h-screen items-center justify-center bg-surface-secondary p-8">- <div className="w-full max-w-md rounded-xl bg-surface-primary p-8 text-center shadow-lg">- <h1 className="mb-4 text-3xl font-bold text-text-primary">+ <div className="bg-surface-secondary flex min-h-screen items-center justify-center p-8">+ <div className="bg-surface-primary w-full max-w-md rounded-xl p-8 text-center shadow-lg">+ <h1 className="text-text-primary mb-4 text-3xl font-bold">{localize('com_ui_oauth_success_title') || 'Authentication Successful'}</h1>- <p className="mb-2 text-sm text-text-secondary">+ <p className="text-text-secondary mb-2 text-sm">{localize('com_ui_oauth_success_description') ||'Your authentication was successful. This window will close in'}{' '}- <span className="font-medium text-accent-primary">{secondsLeft}</span>{' '}+ <span className="text-accent-primary font-medium">{secondsLeft}</span>{' '}{localize('com_ui_seconds') || 'seconds'}.</p>{serverName && (- <p className="mt-4 text-xs text-text-tertiary">+ <p className="text-text-tertiary mt-4 text-xs">{localize('com_ui_oauth_connected_to') || 'Connected to'}:{' '}<span className="font-medium">{serverName}</span></p>diff --git a/client/src/components/OAuth/__tests__/OAuthError.spec.tsx b/client/src/components/OAuth/__tests__/OAuthError.spec.tsxnew file mode 100644index 0000000000..74620c1981--- /dev/null+++ b/client/src/components/OAuth/__tests__/OAuthError.spec.tsx@@ -0,0 +1,36 @@+import React from 'react';+import { render } from '@testing-library/react';+import { MemoryRouter } from 'react-router-dom';+import OAuthError from '../OAuthError';++const mockAnnounce = jest.fn();++jest.mock('~/data-provider', () => ({+ announceOAuthSettled: (settlement: unknown) => mockAnnounce(settlement),+}));++jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string) => key,+}));++const renderAt = (path: string) =>+ render(+ <MemoryRouter initialEntries={[path]}>+ <OAuthError />+ </MemoryRouter>,+ );++describe('OAuthError', () => {+ beforeEach(() => mockAnnounce.mockReset());++ it('announces the failed sign-in with the flow it names', () => {+ renderAt('/oauth/error?error=callback_failed&flow=flow-a');+ expect(mockAnnounce).toHaveBeenCalledTimes(1);+ expect(mockAnnounce).toHaveBeenCalledWith({ outcome: 'failed', flowId: 'flow-a' });+ });++ it('announces a failure without a flow when the redirect names none', () => {+ renderAt('/oauth/error?error=invalid_state');+ expect(mockAnnounce).toHaveBeenCalledWith({ outcome: 'failed', flowId: undefined });+ });+});diff --git a/client/src/components/OAuth/__tests__/OAuthSuccess.spec.tsx b/client/src/components/OAuth/__tests__/OAuthSuccess.spec.tsxnew file mode 100644index 0000000000..0e99b90412--- /dev/null+++ b/client/src/components/OAuth/__tests__/OAuthSuccess.spec.tsx@@ -0,0 +1,31 @@+import React from 'react';+import { render } from '@testing-library/react';+import { MemoryRouter } from 'react-router-dom';+import OAuthSuccess from '../OAuthSuccess';++const mockAnnounce = jest.fn();++jest.mock('~/data-provider', () => ({+ announceOAuthSettled: (settlement: unknown) => mockAnnounce(settlement),+}));++jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string) => key,+}));++describe('OAuthSuccess', () => {+ it('announces the settled sign-in once, for a window the provider severed from this one', () => {+ const { rerender } = render(+ <MemoryRouter initialEntries={['/oauth/success?serverName=GitHub&flow=flow-a']}>+ <OAuthSuccess />+ </MemoryRouter>,+ );+ rerender(+ <MemoryRouter initialEntries={['/oauth/success?serverName=GitHub&flow=flow-a']}>+ <OAuthSuccess />+ </MemoryRouter>,+ );+ expect(mockAnnounce).toHaveBeenCalledTimes(1);+ expect(mockAnnounce).toHaveBeenCalledWith({ outcome: 'succeeded', flowId: 'flow-a' });+ });+});diff --git a/client/src/data-provider/PullRequest/connection.test.tsx b/client/src/data-provider/PullRequest/connection.test.tsxnew file mode 100644index 0000000000..6306da8101--- /dev/null+++ b/client/src/data-provider/PullRequest/connection.test.tsx@@ -0,0 +1,320 @@+import React from 'react';+import { QueryKeys } from 'librechat-data-provider';+import { act, renderHook, waitFor } from '@testing-library/react';+import { QueryClient, QueryObserver, QueryClientProvider } from '@tanstack/react-query';+import type { TPullRequestConnection, TStartupConfig } from 'librechat-data-provider';+import {+ syncPullRequestConnection,+ resetPullRequestCredentials,+ usePullRequestConnectionQuery,+ usePullRequestConnectionStatus,+ useDisconnectPullRequestAccountMutation,+} from './connection';++const mockGetConnection = jest.fn();+const mockDisconnect = jest.fn();+const mockStartup: { current: Partial<TStartupConfig> | undefined } = {+ current: { pullRequestsConnect: 'github' },+};++jest.mock('../Endpoints', () => ({+ useGetStartupConfig: () => ({ data: mockStartup.current }),+}));++jest.mock('librechat-data-provider', () => {+ const actual = jest.requireActual('librechat-data-provider');+ return {+ ...actual,+ dataService: {+ ...actual.dataService,+ getPullRequestConnection: (...args: unknown[]) => mockGetConnection(...args),+ disconnectPullRequestAccount: (...args: unknown[]) => mockDisconnect(...args),+ },+ };+});++const connection = (connected: boolean): TPullRequestConnection => ({+ configured: true,+ provider: 'github',+ connected,+});++const setup = () => {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ const invalidate = jest.spyOn(client, 'invalidateQueries');+ const wrapper = ({ children }: { children: React.ReactNode }) => (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ );+ return { client, invalidate, wrapper };+};++describe('pull request connection hooks', () => {+ beforeEach(() => {+ mockStartup.current = { pullRequestsConnect: 'github' };+ mockGetConnection.mockReset();+ mockDisconnect.mockReset();+ });++ it('never asks a deployment with pull requests off', () => {+ mockStartup.current = {};+ const { wrapper } = setup();+ const { result } = renderHook(() => usePullRequestConnectionQuery(), { wrapper });+ expect(result.current.fetchStatus).toBe('idle');+ expect(mockGetConnection).not.toHaveBeenCalled();+ });++ it('asks a deployment with pull requests on that no longer offers an app', async () => {+ mockStartup.current = { pullRequestsEnabled: true };+ mockGetConnection.mockResolvedValueOnce({ configured: false, connected: true });+ const { wrapper } = setup();+ const { result } = renderHook(() => usePullRequestConnectionQuery(), { wrapper });+ await waitFor(() => expect(result.current.data?.connected).toBe(true));+ expect(mockGetConnection).toHaveBeenCalledTimes(1);+ });++ it('refetches cached pull requests once a connection made elsewhere shows up', async () => {+ mockGetConnection.mockResolvedValueOnce(connection(false));+ const { wrapper, invalidate } = setup();+ const { result } = renderHook(() => usePullRequestConnectionQuery(), { wrapper });+ await waitFor(() => expect(invalidate).toHaveBeenCalledTimes(1));++ mockGetConnection.mockResolvedValueOnce(connection(true));+ await act(async () => {+ await result.current.refetch();+ });++ await waitFor(() => expect(invalidate).toHaveBeenCalledTimes(2));+ expect(invalidate).toHaveBeenLastCalledWith([QueryKeys.conversationPullRequest]);+ });++ it('refetches cached pull requests when the first status shows the user connected', async () => {+ mockGetConnection.mockResolvedValueOnce(connection(true));+ const { wrapper, invalidate } = setup();+ renderHook(() => usePullRequestConnectionQuery(), { wrapper });+ await waitFor(() =>+ expect(invalidate).toHaveBeenCalledWith([QueryKeys.conversationPullRequest]),+ );+ expect(invalidate).toHaveBeenCalledTimes(1);+ });++ it('refetches cached pull requests once on a first status showing the server token', async () => {+ mockGetConnection.mockResolvedValue(connection(false));+ const { wrapper, invalidate } = setup();+ const { result } = renderHook(() => usePullRequestConnectionQuery(), { wrapper });+ await waitFor(() =>+ expect(invalidate).toHaveBeenCalledWith([QueryKeys.conversationPullRequest]),+ );+ expect(invalidate).toHaveBeenCalledTimes(1);++ await act(async () => {+ await result.current.refetch();+ });+ expect(invalidate).toHaveBeenCalledTimes(1);+ });++ it('refetches cached pull requests from the visibility status alone, with the row hidden', async () => {+ mockStartup.current = { pullRequestsEnabled: true };+ mockGetConnection.mockResolvedValue({ configured: false, connected: true });+ const { client, wrapper, invalidate } = setup();+ renderHook(() => usePullRequestConnectionStatus(), { wrapper });+ await waitFor(() => expect(invalidate).toHaveBeenCalledTimes(1));++ /** Disconnected in another tab: the section hides, and only this observer sees it. */+ mockGetConnection.mockResolvedValue({ configured: false, connected: false });+ await act(async () => {+ await client.refetchQueries([QueryKeys.pullRequestConnection]);+ });+ await waitFor(() => expect(invalidate).toHaveBeenCalledTimes(2));+ expect(invalidate).toHaveBeenLastCalledWith([QueryKeys.conversationPullRequest]);+ });++ it('refreshes pull requests once per change, not on every Settings visit', async () => {+ mockGetConnection.mockResolvedValue(connection(true));+ const { wrapper, invalidate } = setup();+ const first = renderHook(() => usePullRequestConnectionQuery(), { wrapper });+ await waitFor(() => expect(invalidate).toHaveBeenCalledTimes(1));+ first.unmount();++ const second = renderHook(() => usePullRequestConnectionQuery(), { wrapper });+ await act(async () => {+ await second.result.current.refetch();+ });+ expect(invalidate).toHaveBeenCalledTimes(1);+ });++ it('refetches cached pull requests when a connection moves to another provider', async () => {+ mockGetConnection.mockResolvedValueOnce(connection(true));+ const { wrapper, invalidate } = setup();+ const { result } = renderHook(() => usePullRequestConnectionQuery(), { wrapper });+ await waitFor(() => expect(invalidate).toHaveBeenCalledTimes(1));++ mockGetConnection.mockResolvedValueOnce({ ...connection(true), provider: 'gitlab' });+ await act(async () => {+ await result.current.refetch();+ });+ await waitFor(() => expect(invalidate).toHaveBeenCalledTimes(2));+ });++ it('refetches cached pull requests when the deployment moves a disconnected user to another provider', async () => {+ mockGetConnection.mockResolvedValueOnce(connection(false));+ const { wrapper, invalidate } = setup();+ const { result } = renderHook(() => usePullRequestConnectionQuery(), { wrapper });+ await waitFor(() => expect(invalidate).toHaveBeenCalledTimes(1));++ mockGetConnection.mockResolvedValueOnce({ ...connection(false), provider: 'gitlab' });+ await act(async () => {+ await result.current.refetch();+ });+ await waitFor(() => expect(invalidate).toHaveBeenCalledTimes(2));+ });++ it('starts over with the next session, so its first status follows the first-status rule', async () => {+ mockGetConnection.mockResolvedValue(connection(true));+ const { wrapper, invalidate } = setup();+ const first = renderHook(() => usePullRequestConnectionQuery(), { wrapper });+ await waitFor(() => expect(invalidate).toHaveBeenCalledTimes(1));+ first.unmount();++ resetPullRequestCredentials();+ const second = renderHook(() => usePullRequestConnectionQuery(), { wrapper });+ await act(async () => {+ await second.result.current.refetch();+ });+ await waitFor(() => expect(invalidate).toHaveBeenCalledTimes(2));+ });++ it('refetches cached pull requests when another sign-in replaces the grant', async () => {+ mockGetConnection.mockResolvedValueOnce({ ...connection(true), flowId: 'flow-a' });+ const { wrapper, invalidate } = setup();+ const { result } = renderHook(() => usePullRequestConnectionQuery(), { wrapper });+ await waitFor(() => expect(invalidate).toHaveBeenCalledTimes(1));++ mockGetConnection.mockResolvedValueOnce({ ...connection(true), flowId: 'flow-b' });+ await act(async () => {+ await result.current.refetch();+ });+ await waitFor(() => expect(invalidate).toHaveBeenCalledTimes(2));+ });++ it('restarts a pull request still on its first load when the credential changes', async () => {+ const { client } = setup();+ syncPullRequestConnection(client, connection(false));+ const loads: Array<(value: unknown) => void> = [];+ const queryFn = jest.fn(() => new Promise((resolve) => loads.push(resolve)));+ const observer = new QueryObserver(client, {+ queryKey: [QueryKeys.conversationPullRequest, 'convo'],+ queryFn,+ });+ const unsubscribe = observer.subscribe(() => undefined);+ try {+ await waitFor(() => expect(queryFn).toHaveBeenCalledTimes(1));+ /** Connected while the first load, under the server's token, is still running. */+ syncPullRequestConnection(client, { ...connection(true), flowId: 'flow-a' });+ await waitFor(() => expect(queryFn).toHaveBeenCalledTimes(2));+ /** The cancelled load answers last, and does not replace the answer under the new token. */+ loads[1]('new');+ await waitFor(() =>+ expect(client.getQueryData([QueryKeys.conversationPullRequest, 'convo'])).toBe('new'),+ );+ loads[0]('old');+ await act(async () => {+ await Promise.resolve();+ });+ expect(client.getQueryData([QueryKeys.conversationPullRequest, 'convo'])).toBe('new');+ } finally {+ unsubscribe();+ }+ });++ it('marks the account disconnected and refetches the status and pull requests', async () => {+ mockDisconnect.mockResolvedValue(undefined);+ const { client, wrapper, invalidate } = setup();+ client.setQueryData([QueryKeys.pullRequestConnection], connection(true));+ const { result } = renderHook(() => useDisconnectPullRequestAccountMutation(), { wrapper });++ await act(async () => {+ await result.current.mutateAsync();+ });++ expect(+ client.getQueryData<TPullRequestConnection>([QueryKeys.pullRequestConnection])?.connected,+ ).toBe(false);+ expect(invalidate).toHaveBeenCalledWith([QueryKeys.pullRequestConnection]);+ expect(invalidate).toHaveBeenCalledWith([QueryKeys.conversationPullRequest]);+ });++ it('reads the status after a failed disconnect even with Settings closed', async () => {+ mockDisconnect.mockRejectedValue(new Error('500'));+ const { client, wrapper, invalidate } = setup();+ /** Pull requests were last refreshed under the user's own grant. */+ syncPullRequestConnection(client, { ...connection(true), flowId: 'flow-a' });+ await waitFor(() => expect(invalidate).toHaveBeenCalledTimes(1));+ /** No status observer is mounted: only the mutation is. */+ const { result } = renderHook(() => useDisconnectPullRequestAccountMutation(), { wrapper });+ mockGetConnection.mockResolvedValue(connection(false));++ await act(async () => {+ await result.current.mutateAsync().catch(() => undefined);+ });++ await waitFor(() => expect(mockGetConnection).toHaveBeenCalledTimes(1));+ await waitFor(() => expect(invalidate).toHaveBeenCalledTimes(2));+ expect(invalidate).toHaveBeenLastCalledWith([QueryKeys.conversationPullRequest]);+ });++ it("resets the leaving account's cached status when the session ends", async () => {+ const { client } = setup();+ client.setQueryData([QueryKeys.pullRequestConnection], connection(true));+ syncPullRequestConnection(client, connection(true));+ resetPullRequestCredentials();+ await waitFor(() =>+ expect(client.getQueryData([QueryKeys.pullRequestConnection])).toBeUndefined(),+ );+ });++ it('resets a status that arrived after Settings closed when the account changes', async () => {+ mockStartup.current = { pullRequestsEnabled: true };+ let answer: (status: TPullRequestConnection) => void = () => undefined;+ mockGetConnection.mockImplementationOnce(() => new Promise((resolve) => (answer = resolve)));+ const { client, wrapper } = setup();+ const { unmount } = renderHook(() => usePullRequestConnectionStatus(), { wrapper });+ await waitFor(() => expect(mockGetConnection).toHaveBeenCalledTimes(1));+ /** Settings closes before the first status arrives; the answer is cached with no observer. */+ unmount();+ await act(async () => {+ answer(connection(true));+ });+ expect(client.getQueryData([QueryKeys.pullRequestConnection])).toEqual(connection(true));++ resetPullRequestCredentials();+ await waitFor(() =>+ expect(client.getQueryData([QueryKeys.pullRequestConnection])).toBeUndefined(),+ );+ });++ it('leaves the next session alone when a disconnect answers after the session ended', async () => {+ let answer: (value?: unknown) => void = () => undefined;+ mockDisconnect.mockImplementation(() => new Promise((resolve) => (answer = resolve)));+ const { client, wrapper, invalidate } = setup();+ const { result } = renderHook(() => useDisconnectPullRequestAccountMutation(), { wrapper });++ let pending: Promise<void> = Promise.resolve();+ act(() => {+ pending = result.current.mutateAsync();+ });+ await waitFor(() => expect(mockDisconnect).toHaveBeenCalledTimes(1));+ /** Signed out, and the next user's status is cached, before the old disconnect answers. */+ resetPullRequestCredentials();+ client.setQueryData([QueryKeys.pullRequestConnection], connection(true));+ invalidate.mockClear();+ await act(async () => {+ answer();+ await pending;+ });++ expect(+ client.getQueryData<TPullRequestConnection>([QueryKeys.pullRequestConnection])?.connected,+ ).toBe(true);+ expect(invalidate).not.toHaveBeenCalled();+ });+});diff --git a/client/src/data-provider/PullRequest/connection.ts b/client/src/data-provider/PullRequest/connection.tsnew file mode 100644index 0000000000..831b8ecb9e--- /dev/null+++ b/client/src/data-provider/PullRequest/connection.ts@@ -0,0 +1,203 @@+import { useEffect } from 'react';+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';+import { MutationKeys, QueryKeys, dataService } from 'librechat-data-provider';+import type {+ TStartupConfig,+ TPullRequestConnectStart,+ TPullRequestConnection,+} from 'librechat-data-provider';+import type { QueryClient } from '@tanstack/react-query';+import { useGetStartupConfig } from '../Endpoints';++/**+ * The credential the server looks this user's pull requests up with, as the status shows it:+ * the user's own account (the grant a given sign-in produced, when the server names it) or the+ * server's token, on the provider the deployment now uses.+ */+const credentialOf = (status: TPullRequestConnection): string =>+ status.connected+ ? `user:${status.provider ?? ''}:${status.flowId ?? ''}`+ : `server:${status.provider ?? ''}`;++/** Per app, the credential its cached pull requests were last refreshed under. */+const refreshedUnder = new Map<QueryClient, string>();++/**+ * Refetches every cached pull request under the credential the server now uses. In-flight loads+ * are cancelled first: an invalidation alone joins a first load that is still running, so one+ * that started with the old credential would land afterwards and stand.+ */+function refetchPullRequests(queryClient: QueryClient): void {+ void queryClient+ .cancelQueries([QueryKeys.conversationPullRequest])+ .then(() => queryClient.invalidateQueries([QueryKeys.conversationPullRequest]));+}++/** Every app that has asked for the status, so the session reset reaches its cache even when no+ * answer was ever synced there (Settings closed before the first status arrived). */+const statusClients = new Set<QueryClient>();++/** Counts sessions, so work a session started does not touch the next one's cache. */+let epoch = 0;++/** Forgets every app's credential with the session, so the next one starts from its own. */+export function resetPullRequestCredentials(): void {+ /** The status cached for the account that is leaving is not the next one's: an account switch+ * without a logout keeps the query cache, so it is reset (and refetched where watched). */+ for (const queryClient of new Set([...statusClients, ...refreshedUnder.keys()])) {+ void queryClient.resetQueries([QueryKeys.pullRequestConnection]);+ }+ refreshedUnder.clear();+ epoch += 1;+}++/**+ * Reads the status afresh and syncs pull requests to it, with or without Settings open: an+ * invalidation alone refetches only a status something is still watching. A request already in+ * flight is cancelled first, since it may have been sent before the change it must observe.+ */+async function reconcileConnection(queryClient: QueryClient, startedIn: number): Promise<void> {+ await queryClient.cancelQueries([QueryKeys.pullRequestConnection]);+ const status = await queryClient.fetchQuery<TPullRequestConnection>(+ [QueryKeys.pullRequestConnection],+ () => dataService.getPullRequestConnection(),+ { staleTime: 0, retry: false },+ );+ if (startedIn === epoch) {+ syncPullRequestConnection(queryClient, status);+ }+}++/**+ * Refetches every cached pull request when a status shows a different credential than the one+ * they were last refreshed under: connecting, disconnecting, or a connection moving to another+ * provider. The first status of a session always refreshes them once, whatever it says, since+ * pull requests fetched before it may have used a grant this app never saw. Every path that+ * learns the status goes through here, so a change refetches pull requests once.+ */+export function syncPullRequestConnection(+ queryClient: QueryClient,+ status: TPullRequestConnection,+): void {+ const credential = credentialOf(status);+ const previous = refreshedUnder.get(queryClient);+ refreshedUnder.set(queryClient, credential);+ if (previous === credential) {+ return;+ }+ refetchPullRequests(queryClient);+}++/**+ * Whether asking for the connection can find anything: on any deployment with pull requests on,+ * not only one advertising an app to connect, because a grant made before the app was turned off+ * must still be found to be disconnected.+ */+const isConnectionKnowable = (startupConfig?: Partial<TStartupConfig>): boolean =>+ startupConfig?.pullRequestsEnabled === true || startupConfig?.pullRequestsConnect != null;++/**+ * Whether the signed-in user has connected their own account. Asked on a deployment with pull+ * requests on, and again when the window regains focus; a sign-in in progress is+ * watched by `watchPullRequestSignIn`, which outlives this hook. A change in either direction+ * swaps the token the server looks pull requests up with, so every cached pull request is+ * refetched.+ */+export const usePullRequestConnectionQuery = () => {+ const queryClient = useQueryClient();+ statusClients.add(queryClient);+ const { data: startupConfig } = useGetStartupConfig();+ const query = useQuery<TPullRequestConnection>(+ [QueryKeys.pullRequestConnection],+ () => dataService.getPullRequestConnection(),+ {+ enabled: isConnectionKnowable(startupConfig),+ retry: false,+ refetchOnWindowFocus: true,+ /** The row renders inside Settings, whose visibility check (`usePullRequestConnectionStatus`)+ * asks as Settings mounts; the row reuses that answer instead of asking again. */+ refetchOnMount: false,+ },+ );++ const { data } = query;+ useEffect(() => {+ if (data != null) {+ syncPullRequestConnection(queryClient, data);+ }+ }, [data, queryClient]);++ return query;+};++/**+ * The same status for what contains the Settings row, so an app the server no longer has hides+ * the whole section, and a later answer that it has one again brings the section back. It shares+ * the row's query.+ */+export const usePullRequestConnectionStatus = () => {+ const queryClient = useQueryClient();+ statusClients.add(queryClient);+ const { data: startupConfig } = useGetStartupConfig();+ const { data } = useQuery<TPullRequestConnection>(+ [QueryKeys.pullRequestConnection],+ () => dataService.getPullRequestConnection(),+ {+ enabled: isConnectionKnowable(startupConfig),+ retry: false,+ refetchOnWindowFocus: true,+ },+ );+ /** Synced here too: a status that hides the row (a grant removed while its app is off) must+ * still refetch pull requests looked up with that grant. A status already synced is a no-op. */+ useEffect(() => {+ if (data != null) {+ syncPullRequestConnection(queryClient, data);+ }+ }, [data, queryClient]);+ return data;+};++/** Starts the provider's sign-in; the caller navigates a window it opened to the returned url. */+export const useConnectPullRequestAccountMutation = () =>+ useMutation<TPullRequestConnectStart, unknown, void>({+ mutationKey: [MutationKeys.connectPullRequestAccount],+ mutationFn: () => dataService.connectPullRequestAccount(),+ });++export const useDisconnectPullRequestAccountMutation = () => {+ const queryClient = useQueryClient();+ return useMutation<void, unknown, void, number>({+ mutationKey: [MutationKeys.disconnectPullRequestAccount],+ mutationFn: () => dataService.disconnectPullRequestAccount(),+ /** The session the disconnect was sent in: an answer after it ended belongs to nobody here. */+ onMutate: () => epoch,+ onSuccess: (_data, _variables, startedIn) => {+ if (startedIn !== epoch) {+ return;+ }+ const status = queryClient.setQueryData<TPullRequestConnection>(+ [QueryKeys.pullRequestConnection],+ (current) => (current == null ? current : { ...current, connected: false }),+ );+ queryClient.invalidateQueries([QueryKeys.pullRequestConnection]);+ /** A disconnect always leaves the server's token, whatever this app saw before. */+ refreshedUnder.set(+ queryClient,+ credentialOf({ configured: true, provider: status?.provider, connected: false }),+ );+ refetchPullRequests(queryClient);+ },+ /** A failed request may still have ended the connection (the server fences the grant before+ * removing it), so the status is asked again and a change refetches pull requests. A status+ * read that fails too leaves the status invalidated for the next look at it. */+ onError: (_error, _variables, startedIn) => {+ if (startedIn == null || startedIn !== epoch) {+ return;+ }+ reconcileConnection(queryClient, startedIn).catch(() =>+ queryClient.invalidateQueries([QueryKeys.pullRequestConnection]),+ );+ },+ });+};diff --git a/client/src/data-provider/PullRequest/index.ts b/client/src/data-provider/PullRequest/index.tsindex a4878becc8..d339cfb35b 100644--- a/client/src/data-provider/PullRequest/index.ts+++ b/client/src/data-provider/PullRequest/index.ts@@ -1,2 +1,4 @@export * from './queries';export * from './batch';+export * from './connection';+export * from './signIn';diff --git a/client/src/data-provider/PullRequest/queries.ts b/client/src/data-provider/PullRequest/queries.tsindex 16e135194c..a8fbee9858 100644--- a/client/src/data-provider/PullRequest/queries.ts+++ b/client/src/data-provider/PullRequest/queries.ts@@ -9,7 +9,9 @@ import {import type { TConversationPullRequestResponse } from 'librechat-data-provider';import type { UseQueryOptions } from '@tanstack/react-query';import { createBatchFetcher, createPullRequestBatcher } from './batch';+import { resetPullRequestCredentials } from './connection';import { useGetStartupConfig } from '../Endpoints';+import { stopPullRequestSignIns } from './signIn';import store from '~/store';const SETTLED_REFRESH_MS = 60_000;@@ -90,13 +92,35 @@ const batcherFor = (userId: string): RowBatcher => {};/**- * Ends the row queue with the session. Called wherever the session's client state is cleared, so+ * Ends the row queue, any account sign-in watch and the record of which credential cached pull+ * requests were fetched with, with the session. Called wherever the session's client state is cleared, so* signing back in as the same account starts a fresh queue and neither waits behind, nor sends,* anything the previous session left.*/+/** The account the pull request session belongs to. */+let sessionOwner: string | undefined;++/**+ * Records who signed in, and ends the pull request session when it is a different account than+ * the last one: an account switch without a logout passes no teardown, and the sign-in watch,+ * credential record and queued lookups would otherwise carry over to the next account.+ */+export const setPullRequestSessionOwner = (userId?: string | null): void => {+ if (!userId) {+ return;+ }+ if (sessionOwner !== undefined && sessionOwner !== userId) {+ endPullRequestSession();+ }+ sessionOwner = userId;+};+export const endPullRequestSession = (): void => {rowBatcher?.batcher.dispose();rowBatcher = undefined;+ /** A sign-in watch left running would ask for, and cache, the next user's connection. */+ stopPullRequestSignIns();+ resetPullRequestCredentials();};/**diff --git a/client/src/data-provider/PullRequest/signIn.test.ts b/client/src/data-provider/PullRequest/signIn.test.tsnew file mode 100644index 0000000000..3ac218dfc7--- /dev/null+++ b/client/src/data-provider/PullRequest/signIn.test.ts@@ -0,0 +1,508 @@+import { QueryKeys } from 'librechat-data-provider';+import { QueryClient } from '@tanstack/react-query';+import type { TPullRequestConnection } from 'librechat-data-provider';+import {+ PULL_REQUEST_CONNECT_POLL_MS,+ PULL_REQUEST_SETTLED_GRACE_MS,+ announceOAuthSettled,+ stopPullRequestSignIns,+ pullRequestSignInSession,+ watchPullRequestSignIn,+} from './signIn';+import { endPullRequestSession, setPullRequestSessionOwner } from './queries';++const mockGetConnection = jest.fn();++jest.mock('librechat-data-provider', () => {+ const actual = jest.requireActual('librechat-data-provider');+ return {+ ...actual,+ dataService: {+ ...actual.dataService,+ getPullRequestConnection: (...args: unknown[]) => mockGetConnection(...args),+ },+ };+});++/** jsdom has no BroadcastChannel; this one delivers between instances of one name, as tabs do. */+class FakeBroadcastChannel {+ static open = new Set<FakeBroadcastChannel>();+ private listeners = new Set<(event: MessageEvent) => void>();+ constructor(readonly name: string) {+ FakeBroadcastChannel.open.add(this);+ }++ addEventListener(_type: 'message', listener: (event: MessageEvent) => void) {+ this.listeners.add(listener);+ }++ postMessage(data: unknown) {+ for (const other of FakeBroadcastChannel.open) {+ if (other !== this && other.name === this.name) {+ other.listeners.forEach((listener) => listener({ data } as MessageEvent));+ }+ }+ }++ close() {+ FakeBroadcastChannel.open.delete(this);+ }+}++const connection = (connected: boolean): TPullRequestConnection => ({+ configured: true,+ provider: 'github',+ connected,+});++const MINUTE = 60_000;++const setup = () => {+ const client = new QueryClient({+ logger: { log: () => undefined, warn: () => undefined, error: () => undefined },+ });+ const invalidate = jest.spyOn(client, 'invalidateQueries');+ return { client, invalidate };+};++const pass = (ms: number) => jest.advanceTimersByTimeAsync(ms);+const focus = async () => {+ window.dispatchEvent(new Event('focus'));+ await pass(0);+};++describe('watchPullRequestSignIn', () => {+ beforeAll(() => {+ (globalThis as { BroadcastChannel?: unknown }).BroadcastChannel = FakeBroadcastChannel;+ });++ afterAll(() => {+ delete (globalThis as { BroadcastChannel?: unknown }).BroadcastChannel;+ });++ beforeEach(() => {+ jest.useFakeTimers();+ mockGetConnection.mockReset();+ mockGetConnection.mockResolvedValue(connection(false));+ });++ afterEach(() => {+ stopPullRequestSignIns();+ jest.useRealTimers();+ });++ it('refreshes pull requests and stops once the account shows connected', async () => {+ const { client, invalidate } = setup();+ watchPullRequestSignIn(client, {+ startedIn: pullRequestSignInSession(),+ expiresAt: Date.now() + 10 * MINUTE,+ });++ await pass(PULL_REQUEST_CONNECT_POLL_MS);+ expect(mockGetConnection).toHaveBeenCalledTimes(1);+ /** The session's first status. */+ expect(invalidate).toHaveBeenCalledTimes(1);++ mockGetConnection.mockResolvedValue(connection(true));+ await focus();+ expect(invalidate).toHaveBeenCalledTimes(2);+ expect(invalidate).toHaveBeenLastCalledWith([QueryKeys.conversationPullRequest]);+ expect(client.getQueryData([QueryKeys.pullRequestConnection])).toEqual(connection(true));++ const asked = mockGetConnection.mock.calls.length;+ await pass(5 * MINUTE);+ await focus();+ expect(mockGetConnection).toHaveBeenCalledTimes(asked);+ });++ it('asks at once when the sign-in page announces it settled, however the popup reads', async () => {+ const { client, invalidate } = setup();+ watchPullRequestSignIn(client, {+ startedIn: pullRequestSignInSession(),+ expiresAt: Date.now() + 10 * MINUTE,+ });+ mockGetConnection.mockResolvedValue(connection(true));++ /** Before any timer is due: only the announcement can explain this ask. */+ announceOAuthSettled({ outcome: 'succeeded' });+ await pass(0);+ expect(mockGetConnection).toHaveBeenCalledTimes(1);+ expect(invalidate).toHaveBeenCalledWith([QueryKeys.conversationPullRequest]);+ });++ it('asks again after the announcement instead of joining a request sent before it', async () => {+ const { client, invalidate } = setup();+ watchPullRequestSignIn(client, {+ startedIn: pullRequestSignInSession(),+ expiresAt: Date.now() + 10 * MINUTE,+ });+ /** A focus asks while the callback has not stored the grant yet; that answer is slow. */+ let answerEarly: (status: TPullRequestConnection) => void = () => undefined;+ mockGetConnection.mockImplementationOnce(+ () => new Promise((resolve) => (answerEarly = resolve)),+ );+ await focus();+ expect(mockGetConnection).toHaveBeenCalledTimes(1);++ mockGetConnection.mockResolvedValue(connection(true));+ invalidate.mockClear();+ announceOAuthSettled({ outcome: 'succeeded' });+ await pass(0);+ answerEarly(connection(false));+ await pass(0);+ expect(mockGetConnection).toHaveBeenCalledTimes(2);+ expect(client.getQueryData([QueryKeys.pullRequestConnection])).toEqual(connection(true));+ expect(invalidate).toHaveBeenCalledWith([QueryKeys.conversationPullRequest]);+ });++ it('backs off asking on a timer, so a sign-in left open costs few requests', async () => {+ const { client } = setup();+ watchPullRequestSignIn(client, {+ startedIn: pullRequestSignInSession(),+ expiresAt: Date.now() + 60 * MINUTE,+ });++ await pass(15_000);+ /** Responsive while a sign-in is likely: 2, 6 and 14 seconds in. */+ expect(mockGetConnection).toHaveBeenCalledTimes(3);+ await pass(60 * MINUTE - 15_000);+ /** At most one ask per 30 seconds after that: about 120 in an hour, not 1,800. */+ expect(mockGetConnection.mock.calls.length).toBeLessThanOrEqual(122);+ });++ it('stops watching, focus and announcements included, when the flow expires', async () => {+ const { client } = setup();+ watchPullRequestSignIn(client, {+ startedIn: pullRequestSignInSession(),+ expiresAt: Date.now() + 1 * MINUTE,+ });+ await pass(1 * MINUTE);+ const asked = mockGetConnection.mock.calls.length;++ await pass(5 * MINUTE);+ await focus();+ announceOAuthSettled({ outcome: 'succeeded' });+ await pass(0);+ expect(mockGetConnection).toHaveBeenCalledTimes(asked);+ });++ it('keeps reading past expiry after its own sign-in settled, until a read succeeds', async () => {+ const { client, invalidate } = setup();+ watchPullRequestSignIn(client, {+ startedIn: pullRequestSignInSession(),+ expiresAt: Date.now() + 1 * MINUTE,+ flowId: 'flow-a',+ });+ await pass(59_000);+ /** Settled just before expiry, and the read it prompts fails. */+ mockGetConnection.mockRejectedValue(new Error('offline'));+ announceOAuthSettled({ outcome: 'succeeded', flowId: 'flow-a' });+ await pass(2_000);++ mockGetConnection.mockResolvedValue({ ...connection(true), flowId: 'flow-a' });+ invalidate.mockClear();+ await focus();+ expect(invalidate).toHaveBeenCalledWith([QueryKeys.conversationPullRequest]);+ const asked = mockGetConnection.mock.calls.length;+ await pass(PULL_REQUEST_SETTLED_GRACE_MS);+ expect(mockGetConnection).toHaveBeenCalledTimes(asked);+ });++ it('still reads a settlement announced just after the flow expired', async () => {+ const { client, invalidate } = setup();+ watchPullRequestSignIn(client, {+ startedIn: pullRequestSignInSession(),+ expiresAt: Date.now() + 1 * MINUTE,+ flowId: 'flow-a',+ });+ await pass(1 * MINUTE + 10_000);+ /** The callback was accepted just before expiry and announces only now. */+ mockGetConnection.mockResolvedValue({ ...connection(true), flowId: 'flow-a' });+ invalidate.mockClear();+ announceOAuthSettled({ outcome: 'succeeded', flowId: 'flow-a' });+ await pass(PULL_REQUEST_CONNECT_POLL_MS);+ expect(invalidate).toHaveBeenCalledWith([QueryKeys.conversationPullRequest]);+ const asked = mockGetConnection.mock.calls.length;+ await pass(10 * MINUTE);+ expect(mockGetConnection).toHaveBeenCalledTimes(asked);+ });++ it('still hears a failure that settles after the grant already showed connected', async () => {+ const { client, invalidate } = setup();+ watchPullRequestSignIn(client, {+ startedIn: pullRequestSignInSession(),+ expiresAt: Date.now() + 60 * MINUTE,+ flowId: 'flow-a',+ });+ /** A poll sees the grant the callback stored before its final check. */+ mockGetConnection.mockResolvedValue({ ...connection(true), flowId: 'flow-a' });+ await focus();+ const polled = mockGetConnection.mock.calls.length;+ await pass(10 * MINUTE);+ expect(mockGetConnection).toHaveBeenCalledTimes(polled);++ /** The callback then removes it and lands on the error page for this flow. */+ mockGetConnection.mockResolvedValue(connection(false));+ invalidate.mockClear();+ announceOAuthSettled({ outcome: 'failed', flowId: 'flow-a' });+ await pass(0);+ expect(mockGetConnection).toHaveBeenCalledTimes(polled + 1);+ expect(invalidate).toHaveBeenCalledWith([QueryKeys.conversationPullRequest]);+ });++ it('gives up a settled sign-in whose status cannot be read once the grace passes', async () => {+ const { client } = setup();+ watchPullRequestSignIn(client, {+ startedIn: pullRequestSignInSession(),+ expiresAt: Date.now() + 1 * MINUTE,+ flowId: 'flow-a',+ });+ mockGetConnection.mockRejectedValue(new Error('offline'));+ announceOAuthSettled({ outcome: 'succeeded', flowId: 'flow-a' });+ await pass(1 * MINUTE + PULL_REQUEST_SETTLED_GRACE_MS);+ const asked = mockGetConnection.mock.calls.length;+ await pass(10 * MINUTE);+ await focus();+ expect(mockGetConnection).toHaveBeenCalledTimes(asked);+ });++ it("drops a replaced watch's late answer, leaving the new watch to speak", async () => {+ const { client, invalidate } = setup();+ let answerA: (status: TPullRequestConnection) => void = () => undefined;+ mockGetConnection.mockImplementationOnce(() => new Promise((resolve) => (answerA = resolve)));+ watchPullRequestSignIn(client, {+ startedIn: pullRequestSignInSession(),+ expiresAt: Date.now() + 60 * MINUTE,+ flowId: 'flow-a',+ });+ await focus();+ /** Flow B replaces A while A's read is still out. */+ watchPullRequestSignIn(client, {+ startedIn: pullRequestSignInSession(),+ expiresAt: Date.now() + 60 * MINUTE,+ flowId: 'flow-b',+ });+ invalidate.mockClear();+ answerA({ ...connection(true), flowId: 'flow-a' });+ await pass(0);+ expect(invalidate).not.toHaveBeenCalledWith([QueryKeys.conversationPullRequest]);+ });++ it('ends the watch when another account signs in without a logout', async () => {+ const { client } = setup();+ setPullRequestSessionOwner('first');+ watchPullRequestSignIn(client, {+ startedIn: pullRequestSignInSession(),+ expiresAt: Date.now() + 60 * MINUTE,+ flowId: 'flow-a',+ });+ setPullRequestSessionOwner('first');+ await focus();+ const asked = mockGetConnection.mock.calls.length;+ expect(asked).toBeGreaterThan(0);++ setPullRequestSessionOwner('second');+ await pass(10 * MINUTE);+ await focus();+ expect(mockGetConnection).toHaveBeenCalledTimes(asked);+ });++ it("keeps watching when another flow's grant shows up, and stops on its own", async () => {+ const { client, invalidate } = setup();+ mockGetConnection.mockResolvedValue({ ...connection(true), flowId: 'flow-a' });+ watchPullRequestSignIn(client, {+ startedIn: pullRequestSignInSession(),+ expiresAt: Date.now() + 10 * MINUTE,+ flowId: 'flow-b',+ });+ announceOAuthSettled({ outcome: 'succeeded' });+ await pass(0);+ expect(invalidate).toHaveBeenCalledTimes(1);++ /** Still watching: the second sign-in replacing the first grant is a change. */+ mockGetConnection.mockResolvedValue({ ...connection(true), flowId: 'flow-b' });+ await focus();+ expect(invalidate).toHaveBeenCalledTimes(2);+ const asked = mockGetConnection.mock.calls.length;+ await pass(5 * MINUTE);+ expect(mockGetConnection).toHaveBeenCalledTimes(asked);+ });++ it('keeps watching through a failed status read', async () => {+ const { client, invalidate } = setup();+ mockGetConnection.mockRejectedValueOnce(new Error('500'));+ watchPullRequestSignIn(client, {+ startedIn: pullRequestSignInSession(),+ expiresAt: Date.now() + 10 * MINUTE,+ });+ await pass(PULL_REQUEST_CONNECT_POLL_MS);++ mockGetConnection.mockResolvedValue(connection(true));+ await focus();+ expect(invalidate).toHaveBeenCalledWith([QueryKeys.conversationPullRequest]);+ });++ it('refreshes pull requests when the account it watches turns out disconnected', async () => {+ const { client, invalidate } = setup();+ mockGetConnection.mockResolvedValueOnce(connection(true));+ watchPullRequestSignIn(client, {+ startedIn: pullRequestSignInSession(),+ expiresAt: Date.now() + 10 * MINUTE,+ });+ await focus();+ expect(invalidate).toHaveBeenCalledTimes(1);++ /** Removed elsewhere while this window still watches a new sign-in. */+ mockGetConnection.mockResolvedValue(connection(false));+ watchPullRequestSignIn(client, {+ startedIn: pullRequestSignInSession(),+ expiresAt: Date.now() + 10 * MINUTE,+ });+ await focus();+ expect(invalidate).toHaveBeenCalledTimes(2);+ });++ it('replaces the watch on an earlier sign-in when another starts', async () => {+ const { client } = setup();+ watchPullRequestSignIn(client, {+ startedIn: pullRequestSignInSession(),+ expiresAt: Date.now() + 10 * MINUTE,+ });+ watchPullRequestSignIn(client, {+ startedIn: pullRequestSignInSession(),+ expiresAt: Date.now() + 10 * MINUTE,+ });++ await focus();+ expect(mockGetConnection).toHaveBeenCalledTimes(1);+ });++ it('ends every watch with the session, so none asks for the next user', async () => {+ const { client } = setup();+ watchPullRequestSignIn(client, {+ startedIn: pullRequestSignInSession(),+ expiresAt: Date.now() + 10 * MINUTE,+ });++ endPullRequestSession();+ await pass(10 * MINUTE);+ await focus();+ announceOAuthSettled({ outcome: 'succeeded' });+ await pass(0);+ expect(mockGetConnection).not.toHaveBeenCalled();+ });++ it('applies an answer asked for just before the flow expired', async () => {+ const { client, invalidate } = setup();+ let answer: (status: TPullRequestConnection) => void = () => undefined;+ mockGetConnection.mockReturnValue(new Promise((resolve) => (answer = resolve)));+ watchPullRequestSignIn(client, {+ startedIn: pullRequestSignInSession(),+ expiresAt: Date.now() + 1 * MINUTE,+ });+ await pass(1 * MINUTE - 1);+ announceOAuthSettled({ outcome: 'succeeded' });+ await pass(1);+ expect(invalidate).not.toHaveBeenCalled();+ answer(connection(true));+ await pass(0);+ expect(invalidate).toHaveBeenCalled();+ });++ it('discards an answer that arrives after the session ended', async () => {+ const { client, invalidate } = setup();+ let answer: (status: TPullRequestConnection) => void = () => undefined;+ mockGetConnection.mockReturnValue(new Promise((resolve) => (answer = resolve)));+ watchPullRequestSignIn(client, {+ startedIn: pullRequestSignInSession(),+ expiresAt: Date.now() + 10 * MINUTE,+ });+ announceOAuthSettled({ outcome: 'succeeded' });+ await pass(0);+ endPullRequestSession();+ invalidate.mockClear();+ answer(connection(true));+ await pass(0);+ expect(invalidate).not.toHaveBeenCalled();+ });++ it('does not start a watch for a sign-in begun in a session that has since ended', async () => {+ const { client } = setup();+ const startedIn = pullRequestSignInSession();+ endPullRequestSession();+ watchPullRequestSignIn(client, { startedIn, expiresAt: Date.now() + 10 * MINUTE });++ await pass(10 * MINUTE);+ await focus();+ expect(mockGetConnection).not.toHaveBeenCalled();+ });++ describe('a failed sign-in', () => {+ const watchFlow = (client: QueryClient, flowId?: string) =>+ watchPullRequestSignIn(client, {+ startedIn: pullRequestSignInSession(),+ expiresAt: Date.now() + 60 * MINUTE,+ flowId,+ });++ const askedAfter = async (ms: number) => {+ const before = mockGetConnection.mock.calls.length;+ await pass(ms);+ return mockGetConnection.mock.calls.length - before;+ };++ it('ends the watch on the flow it names, after one last read', async () => {+ watchFlow(setup().client, 'flow-a');+ announceOAuthSettled({ outcome: 'failed', flowId: 'flow-a' });+ /** The read the failure itself asks for, and none after it. */+ expect(await askedAfter(10 * MINUTE)).toBe(1);+ });++ it('reads the status once before ending, since the grant may have been stored', async () => {+ const { client, invalidate } = setup();+ watchFlow(client, 'flow-a');+ mockGetConnection.mockResolvedValue({ ...connection(true), flowId: 'flow-a' });+ const before = mockGetConnection.mock.calls.length;+ announceOAuthSettled({ outcome: 'failed', flowId: 'flow-a' });+ await pass(0);+ expect(mockGetConnection.mock.calls.length - before).toBe(1);+ expect(invalidate).toHaveBeenCalledWith([QueryKeys.conversationPullRequest]);+ expect(await askedAfter(10 * MINUTE)).toBe(0);+ });++ it('keeps watching when the read after a failure fails, until one succeeds', async () => {+ const { client, invalidate } = setup();+ watchFlow(client, 'flow-a');+ mockGetConnection.mockRejectedValueOnce(new Error('offline'));+ announceOAuthSettled({ outcome: 'failed', flowId: 'flow-a' });+ await pass(0);+ expect(mockGetConnection).toHaveBeenCalledTimes(1);++ /** The server had stored the grant: the next read that succeeds syncs it, then the watch ends. */+ mockGetConnection.mockResolvedValue({ ...connection(true), flowId: 'flow-a' });+ invalidate.mockClear();+ await focus();+ expect(mockGetConnection).toHaveBeenCalledTimes(2);+ expect(invalidate).toHaveBeenCalledWith([QueryKeys.conversationPullRequest]);+ expect(await askedAfter(10 * MINUTE)).toBe(0);+ });++ it('leaves the watch on another flow running', async () => {+ watchFlow(setup().client, 'flow-b');+ announceOAuthSettled({ outcome: 'failed', flowId: 'flow-a' });+ expect(await askedAfter(10 * MINUTE)).toBeGreaterThan(0);+ });++ it('ignores a failure that names no flow, such as another OAuth sign-in', async () => {+ watchFlow(setup().client, 'flow-a');+ announceOAuthSettled({ outcome: 'failed' });+ expect(await askedAfter(10 * MINUTE)).toBeGreaterThan(0);+ });++ it('ignores a failure when its own server names no flow either', async () => {+ watchFlow(setup().client);+ announceOAuthSettled({ outcome: 'failed' });+ expect(await askedAfter(10 * MINUTE)).toBeGreaterThan(0);+ });+ });+});diff --git a/client/src/data-provider/PullRequest/signIn.ts b/client/src/data-provider/PullRequest/signIn.tsnew file mode 100644index 0000000000..c7ebe9774b--- /dev/null+++ b/client/src/data-provider/PullRequest/signIn.ts@@ -0,0 +1,221 @@+import { QueryKeys, dataService } from 'librechat-data-provider';+import type { TPullRequestConnection } from 'librechat-data-provider';+import type { QueryClient } from '@tanstack/react-query';+import { syncPullRequestConnection } from './connection';++/** First wait between status asks while a sign-in is watched; each wait doubles from here. */+export const PULL_REQUEST_CONNECT_POLL_MS = 2000;+/** Longest wait between status asks, so a sign-in left open costs a few requests a minute. */+export const PULL_REQUEST_CONNECT_POLL_MAX_MS = 30_000;+/** How long a settled sign-in keeps retrying its status read after the flow expired. */+export const PULL_REQUEST_SETTLED_GRACE_MS = 2 * 60_000;+/** Same-origin pages that end an OAuth sign-in announce it here. */+export const OAUTH_SETTLED_CHANNEL = 'librechat:oauth-settled';++type Watch = { stop: () => void };++/** What a landing page says about the sign-in it ends, and which one when it knows. */+export type OAuthSettlement = { outcome: 'succeeded' | 'failed'; flowId?: string };++const isSettlement = (value: unknown): value is OAuthSettlement =>+ typeof value === 'object' &&+ value !== null &&+ ((value as OAuthSettlement).outcome === 'succeeded' ||+ (value as OAuthSettlement).outcome === 'failed');++/** One sign-in per app at a time: starting another replaces the watch on the first. */+const watches = new Map<QueryClient, Watch>();+/** Counts ended sessions, so work started in one session can tell it has ended. */+let session = 0;++/** The current session; a sign-in started now is watched only while this stays current. */+export function pullRequestSignInSession(): number {+ return session;+}++/**+ * Announces, from the page an OAuth sign-in lands on, how it settled. The page shares this app's+ * origin, so the announcement reaches the window that started the sign-in even when the+ * provider's pages severed the popup from it (a cross-origin opener policy makes the retained+ * window handle read as closed while the sign-in is still open).+ */+export function announceOAuthSettled(settlement: OAuthSettlement): void {+ if (typeof BroadcastChannel === 'undefined') {+ return;+ }+ const channel = new BroadcastChannel(OAUTH_SETTLED_CHANNEL);+ channel.postMessage(settlement);+ channel.close();+}++/**+ * Watches a sign-in started from this window until the account is connected, outside any+ * component, so closing Settings mid-flow still refreshes what was fetched with the old token.+ *+ * - The landing page's announcement asks the status at once; it is the signal that survives the+ * provider severing the popup, so the popup handle is not consulted at all. A failure ends the+ * watch only when it names this sign-in's flow: the server names it on every failure after the+ * flow is bound, so one naming none belongs to another sign-in or never reached this one.+ * - Without it (an older page, no BroadcastChannel) the status is asked on a timer that starts at+ * 2 seconds and doubles to 30, and whenever this window regains focus.+ * - At `expiresAt` the server's signed state is no longer accepted, so watching ends.+ * - Seeing the grant this sign-in produced ends watching. A server that names grants by the flow+ * behind them lets another flow's grant (a second tab, an earlier click) be told apart, and that+ * one does not end this watch; an older server's connected status does. Every answer goes+ * through the same check a mounted status row uses, so a change of credential, a replaced grant+ * included, refetches cached pull requests once.+ *+ * A failed status read is not an answer, so watching continues; the row shows the failure.+ * Returns a function that ends the watch; ending the session ends every watch.+ */+export function watchPullRequestSignIn(+ queryClient: QueryClient,+ { expiresAt, startedIn, flowId }: { expiresAt: number; startedIn: number; flowId?: string },+): () => void {+ /** Started before the session ended: nothing to watch for whoever signs in next. */+ if (startedIn !== session) {+ return () => undefined;+ }+ watches.get(queryClient)?.stop();+ let timer: ReturnType<typeof setTimeout> | undefined;+ let wait = PULL_REQUEST_CONNECT_POLL_MS;+ let stopped = false;+ /** This flow's sign-in page reported a failure: the next status read that succeeds ends the+ * watch, whatever it says, since the server may have stored the grant before failing. */+ let failed = false;+ /** This flow's sign-in page settled, so the server may hold a new grant: the watch outlives the+ * flow's expiry, for a bounded grace, until a status read after it succeeds. */+ let settled = false;++ /** `fresh` for a check after the sign-in page settled: a request already in flight may have been+ * sent before the callback stored the grant, and asking now would only join it. */+ const check = async (fresh = false): Promise<void> => {+ if (stopped) {+ return;+ }+ let status: TPullRequestConnection;+ try {+ if (fresh) {+ await queryClient.cancelQueries([QueryKeys.pullRequestConnection]);+ }+ status = await queryClient.fetchQuery<TPullRequestConnection>(+ [QueryKeys.pullRequestConnection],+ () => dataService.getPullRequestConnection(),+ { staleTime: 0, retry: false },+ );+ } catch {+ return;+ }+ /** An answer already asked for still counts once the watch expires, since a sign-in that+ * landed just before expiry must refresh pull requests. It is discarded once another sign-in+ * replaced this watch, whose own reads now speak for the connection, or once the session+ * ended, as it would apply to whoever signs in next. */+ const current = watches.get(queryClient);+ if (startedIn !== session || (current != null && current !== watch)) {+ return;+ }+ /** Every answer, so an account removed elsewhere mid-flow also refreshes pull requests. */+ syncPullRequestConnection(queryClient, status);+ const ours = flowId == null || status.flowId == null || status.flowId === flowId;+ if (failed || settled) {+ stop();+ } else if (status.connected && ours) {+ /** Connected, but the sign-in page has not settled: the callback can still fail after+ * storing (a disconnect racing it, say), so polling ends while the channel keeps+ * listening until it settles or the grace passes. */+ quiet();+ }+ };++ const schedule = () => {+ timer = setTimeout(() => {+ void check();+ wait = Math.min(wait * 2, PULL_REQUEST_CONNECT_POLL_MAX_MS);+ schedule();+ }, wait);+ };+ const onSignal = () => void check();+ const onSettled = (event: MessageEvent) => {+ const settlement: unknown = event.data;+ if (!isSettlement(settlement) || settlement.outcome === 'succeeded') {+ if (isSettlement(settlement) && flowId != null && settlement.flowId === flowId) {+ settled = true;+ resume();+ }+ if (lapsed) {+ return;+ }+ void check(true);+ return;+ }+ /** A failure naming no flow is another sign-in's (an MCP server's, say): ours always name it. */+ if (settlement.flowId != null && settlement.flowId === flowId) {+ /** The server can store the grant and still report the flow failed (a check after storing+ * could not finish), so the watch ends only on a status read that succeeds; a failed one+ * leaves it to the timer, focus and expiry like any other. */+ failed = true;+ settled = true;+ resume();+ void check(true);+ }+ };+ const channel =+ typeof BroadcastChannel === 'undefined' ? null : new BroadcastChannel(OAUTH_SETTLED_CHANNEL);+ channel?.addEventListener('message', onSettled);+ /** Past the flow's expiry, unsettled: no more polling, but the sign-in page may still announce+ * a callback the server accepted just before expiry, so the channel stays open for the grace. */+ let lapsed = false;+ let expiry: ReturnType<typeof setTimeout> = setTimeout(+ () => {+ if (!settled) {+ quiet();+ }+ /** Settled but not yet read back, or not settled yet: a bounded grace, then give up. */+ expiry = setTimeout(() => stop(), PULL_REQUEST_SETTLED_GRACE_MS);+ },+ Math.max(0, expiresAt - Date.now()),+ );++ /** Stops polling and focus checks, keeping the announcement channel open. */+ function quiet() {+ lapsed = true;+ clearTimeout(timer);+ window.removeEventListener('focus', onSignal);+ }++ /** A settlement announced during the grace resumes reading until a read succeeds. */+ const resume = () => {+ if (!lapsed || stopped) {+ return;+ }+ lapsed = false;+ wait = PULL_REQUEST_CONNECT_POLL_MS;+ schedule();+ window.addEventListener('focus', onSignal);+ };++ function stop() {+ stopped = true;+ clearTimeout(timer);+ clearTimeout(expiry);+ window.removeEventListener('focus', onSignal);+ channel?.close();+ if (watches.get(queryClient) === watch) {+ watches.delete(queryClient);+ }+ }++ const watch: Watch = { stop };+ watches.set(queryClient, watch);+ schedule();+ window.addEventListener('focus', onSignal);+ return stop;+}++/** Ends every sign-in watch, as the session ending does: none may ask for the next user. */+export function stopPullRequestSignIns(): void {+ session += 1;+ for (const watch of [...watches.values()]) {+ watch.stop();+ }+}diff --git a/client/src/hooks/AuthContext.tsx b/client/src/hooks/AuthContext.tsxindex 640febf32d..5974ab1913 100644--- a/client/src/hooks/AuthContext.tsx+++ b/client/src/hooks/AuthContext.tsx@@ -41,6 +41,7 @@ import {useGetUserQuery,endPullRequestSession,useLoginUserMutation,+ setPullRequestSessionOwner,useLogoutUserMutation,useRefreshTokenMutation,} from '~/data-provider';@@ -124,6 +125,7 @@ const AuthContextProvider = ({setQueriesEnabled(true);/** A different account signing in without a logout must not inherit cached audio. */setTTSCacheOwner(user?.id);+ setPullRequestSessionOwner(user?.id);/*** Any accepted full-auth response supersedes a staged enrollment, whichever path minted* it. The setup endpoints trust the stored bearer independently of the session, so a@@ -265,6 +267,7 @@ const AuthContextProvider = ({setQueriesEnabled(true);openFileDeletionRetention();setTTSCacheOwner(authenticatedUser.id);+ setPullRequestSessionOwner(authenticatedUser.id);navigate(redirect, { replace: true });},[navigate, setQueriesEnabled, setUser],diff --git a/client/src/hooks/__tests__/AuthContext.spec.tsx b/client/src/hooks/__tests__/AuthContext.spec.tsxindex f2d35f7618..05a02bbd37 100644--- a/client/src/hooks/__tests__/AuthContext.spec.tsx+++ b/client/src/hooks/__tests__/AuthContext.spec.tsx@@ -88,6 +88,7 @@ jest.mock('~/data-provider', () => ({})),useGetRole: jest.fn(() => ({ data: null })),endPullRequestSession: jest.fn(() => mockEndPullRequestSession()),+ setPullRequestSessionOwner: jest.fn(),useListRoles: jest.fn(() => ({ data: undefined })),}));diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.jsonindex c8ddc9f4bd..8beb89ebff 100644--- a/client/src/locales/en/translation.json+++ b/client/src/locales/en/translation.json@@ -1,4 +1,20 @@{+ "com_ui_pr_account_checking": "Checking connection",+ "com_ui_pr_account_connect": "Connect",+ "com_ui_pr_account_connect_aria": "Connect {{0}}",+ "com_ui_pr_account_connect_error": "Couldn't start connecting. Try again.",+ "com_ui_pr_account_connected": "Connected",+ "com_ui_pr_account_description": "Look up pull requests with your own account",+ "com_ui_pr_account_disconnect": "Disconnect",+ "com_ui_pr_account_disconnect_aria": "Disconnect {{0}}",+ "com_ui_pr_account_disconnect_description": "Pull requests will no longer be looked up with your account. You can connect it again at any time.",+ "com_ui_pr_account_disconnect_error": "Couldn't disconnect. Try again.",+ "com_ui_pr_account_disconnect_title": "Disconnect {{0}}?",+ "com_ui_pr_account_not_connected": "Not connected",+ "com_ui_pr_account_not_in_use": "Not in use",+ "com_ui_pr_account_popup_blocked": "Your browser blocked the sign-in window. Allow pop-ups and try again.",+ "com_ui_pr_account_status_error": "Couldn't check the connection",+ "com_ui_pr_account_unused_description": "Pull requests no longer use this account. Disconnect it to remove it.","com_ui_pr_additions": "{{0}} lines added","com_ui_pr_checks": "Checks: {{0}}","com_ui_pr_checks_failing": "Failing",@@ -12,6 +28,9 @@"com_ui_pr_open_in_bitbucket": "Open in Bitbucket","com_ui_pr_open_in_github": "Open in GitHub","com_ui_pr_open_in_gitlab": "Open in GitLab",+ "com_ui_pr_provider_bitbucket": "Bitbucket",+ "com_ui_pr_provider_github": "GitHub",+ "com_ui_pr_provider_gitlab": "GitLab","com_ui_pr_refresh_failed": "Couldn't refresh the pull request","com_ui_pr_state": "State: {{0}}","com_ui_pr_state_closed": "Closed",@@ -2842,6 +2861,7 @@"com_ui_settings_label_language_stt": "Speech-to-text language","com_ui_settings_label_playback_rate": "Playback rate","com_ui_settings_label_provider_api_keys": "Provider API keys",+ "com_ui_settings_label_pull_request_account": "Pull request account","com_ui_settings_label_revoke_keys": "Revoke all provider API keys","com_ui_settings_label_shared_links": "Shared chats","com_ui_settings_label_voice": "Voice",@@ -2854,6 +2874,7 @@"com_ui_settings_section_appearance": "Appearance","com_ui_settings_section_billing": "Billing","com_ui_settings_section_commands": "Commands",+ "com_ui_settings_section_connections": "Connected accounts","com_ui_settings_section_conversations": "Conversations","com_ui_settings_section_danger_zone": "Danger zone","com_ui_settings_section_data": "Your data",diff --git a/packages/data-provider/src/api-endpoints.ts b/packages/data-provider/src/api-endpoints.tsindex d98d43370d..a06d908ed3 100644--- a/packages/data-provider/src/api-endpoints.ts+++ b/packages/data-provider/src/api-endpoints.ts@@ -173,6 +173,14 @@ export const conversationPullRequest = (conversationId: string) =>export const conversationPullRequests = () => `${conversationsRoot}/pull-requests`;+const pullRequestOAuthRoot = `${BASE_URL}/api/pull-requests/oauth`;++export const pullRequestConnection = () => `${pullRequestOAuthRoot}/status`;++export const pullRequestConnect = () => `${pullRequestOAuthRoot}/connect`;++export const pullRequestDisconnect = () => pullRequestOAuthRoot;+export const genTitle = (conversationId: string) =>`${conversationsRoot}/gen_title/${encodeURIComponent(conversationId)}`;diff --git a/packages/data-provider/src/data-service.ts b/packages/data-provider/src/data-service.tsindex 12ccf44b8d..2843e72c96 100644--- a/packages/data-provider/src/data-service.ts+++ b/packages/data-provider/src/data-service.ts@@ -1247,6 +1247,18 @@ export function getConversationPullRequests(return request.post(endpoints.conversationPullRequests(), { conversationIds }, options);}+export function getPullRequestConnection(): Promise<t.TPullRequestConnection> {+ return request.get(endpoints.pullRequestConnection());+}++export function connectPullRequestAccount(): Promise<t.TPullRequestConnectStart> {+ return request.get(endpoints.pullRequestConnect());+}++export function disconnectPullRequestAccount(): Promise<void> {+ return request.delete(endpoints.pullRequestDisconnect());+}+export function getPrompt(id: string): Promise<{ prompt: t.TPrompt }> {return request.get(endpoints.getPrompt(id));}diff --git a/packages/data-provider/src/keys.ts b/packages/data-provider/src/keys.tsindex d950178f53..6facec62d3 100644--- a/packages/data-provider/src/keys.ts+++ b/packages/data-provider/src/keys.ts@@ -111,6 +111,7 @@ export enum QueryKeys {subagentThread = 'subagentThread',backgroundTasks = 'backgroundTasks',conversationPullRequest = 'conversationPullRequest',+ pullRequestConnection = 'pullRequestConnection',codeEnvironments = 'codeEnvironments',agentQueuedTurns = 'agentQueuedTurns',/* Combined Pinned-section display order (favorites + pinned chats) */@@ -198,4 +199,6 @@ export enum MutationKeys {moveConversationCodeEnvironment = 'moveConversationCodeEnvironment',convoSeen = 'convoSeen',convoUnread = 'convoUnread',+ connectPullRequestAccount = 'connectPullRequestAccount',+ disconnectPullRequestAccount = 'disconnectPullRequestAccount',}