From 1bbef4a71e17a9d9498c0edfeea1c68daf751cbc Mon Sep 17 00:00:00 2001 From: Marco Beretta <81851188+berry-13@users.noreply.github.com> Date: Sun, 25 Oct 2026 23:18:10 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=8E=20fix:=20Quiet=20Initial=20PR=20Di?= =?UTF-8?q?scovery=20Failures=20and=20Add=20Safe=20Diagnostics=20(#17436)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix: Quiet Initial PR Discovery Failures and Add Safe Diagnostics * fix: Resolve PR Discovery Static Check Failures --- .../components/Chat/PullRequest/RowMark.tsx | 63 +------- .../PullRequest/__tests__/RowMark.test.tsx | 59 ++++--- client/src/locales/en/translation.json | 1 - packages/api/src/pulls/bitbucket.ts | 11 +- packages/api/src/pulls/diagnostics.spec.ts | 148 ++++++++++++++++++ packages/api/src/pulls/diagnostics.ts | 14 ++ packages/api/src/pulls/github.ts | 11 +- packages/api/src/pulls/gitlab.ts | 11 +- packages/api/src/pulls/lookup.ts | 2 + 9 files changed, 230 insertions(+), 90 deletions(-) create mode 100644 packages/api/src/pulls/diagnostics.spec.ts create mode 100644 packages/api/src/pulls/diagnostics.ts diff --git a/client/src/components/Chat/PullRequest/RowMark.tsx b/client/src/components/Chat/PullRequest/RowMark.tsx index 5dde27ad74..feb50d54af 100644 --- a/client/src/components/Chat/PullRequest/RowMark.tsx +++ b/client/src/components/Chat/PullRequest/RowMark.tsx @@ -1,14 +1,12 @@ import { memo, useRef, useEffect } from 'react'; import * as Ariakit from '@ariakit/react'; -import { Button } from '@librechat/client'; -import { TriangleAlert } from 'lucide-react'; import type { RefObject } from 'react'; import type React from 'react'; import { useRowPullRequestQuery } from '~/data-provider/PullRequest'; import { TONE_DOT_CLASS, presentPullRequest } from './status'; -import PullRequestPanel, { panelClass } from './Panel'; import { summarizePullRequest } from './summary'; import useRowHover from './useRowHover'; +import PullRequestPanel from './Panel'; import { useLocalize } from '~/hooks'; import PullRequestIcon from './Icon'; import { cn } from '~/utils'; @@ -50,7 +48,7 @@ function PullRequestRowMark({ const open = Ariakit.useStoreState(store, 'open'); const { data, isError, refetch } = useRowPullRequestQuery(conversationId); const pullRequest = data?.pullRequest; - const described = pullRequest != null || isError; + const described = pullRequest != null; /* The row is not focusable, so a card it opened hands focus back to the icon on close, and focus or a click on the icon makes the icon the anchor again. */ @@ -65,62 +63,7 @@ function PullRequestRowMark({ return () => onDescribed?.(false); }, [described, onDescribed]); - /* A first lookup that failed is not the same as a chat with no pull request: say so, and - offer a retry, instead of leaving the row looking like there is nothing to find. */ - if (pullRequest == null && isError) { - const failed = localize('com_ui_pr_load_failed'); - return ( - - } - aria-label={failed} - aria-expanded={open} - showOnHover={rowRef == null} - data-testid="convo-pull-request-failed" - onFocus={(event: React.FocusEvent) => { - anchorToMark(event); - store.show(); - }} - onClick={(event: React.MouseEvent) => { - event.stopPropagation(); - anchorToMark(event); - store.show(); - }} - onKeyDown={(event: React.KeyboardEvent) => { - if (event.key === 'Enter' || event.key === ' ') event.stopPropagation(); - }} - className="focus-visible:ring-text-primary text-status-warning relative me-1 flex size-4 shrink-0 items-center justify-center rounded-sm outline-hidden focus-visible:ring-2" - > - - - - {failed} - - event.stopPropagation()} - onDoubleClick={(event) => event.stopPropagation()} - onContextMenu={(event) => event.stopPropagation()} - onKeyDown={(event) => event.stopPropagation()} - > - - {failed} - void refetch()}> - {localize('com_ui_retry')} - - - - - ); - } - + /* Discovery is automatic: only a known pull request can have a refresh warning. */ if (pullRequest == null) return null; const view = presentPullRequest(pullRequest); diff --git a/client/src/components/Chat/PullRequest/__tests__/RowMark.test.tsx b/client/src/components/Chat/PullRequest/__tests__/RowMark.test.tsx index ad84527ac4..5d13457194 100644 --- a/client/src/components/Chat/PullRequest/__tests__/RowMark.test.tsx +++ b/client/src/components/Chat/PullRequest/__tests__/RowMark.test.tsx @@ -2,7 +2,7 @@ import React from 'react'; import '@testing-library/jest-dom'; import userEvent from '@testing-library/user-event'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; -import { render, screen, waitFor, fireEvent } from '@testing-library/react'; +import { render, screen, waitFor, fireEvent, act } from '@testing-library/react'; import type { TConversationPullRequest } from 'librechat-data-provider'; import PullRequestRowMark from '../RowMark'; @@ -122,18 +122,15 @@ describe('PullRequestRowMark', () => { results: [{ conversationId: 'convo-1', error: { code: 'RATE_LIMITED' } }], }), ], - ])('says the lookup failed, with a retry, when %s', async (_label, respond) => { + ])('stays quiet before a pull request is known when %s', async (_label, respond) => { mockGetMany.mockImplementationOnce(respond); - renderMark(); - const failed = await screen.findByTestId('convo-pull-request-failed'); - expect(failed).toHaveAccessibleName('com_ui_pr_load_failed'); - expect(screen.queryByTestId('convo-pull-request')).toBeNull(); - mockGetMany.mockResolvedValue(answer('convo-1', pr)); - fireEvent.focus(failed); - const retry = await screen.findByRole('button', { name: 'com_ui_retry' }); - fireEvent.click(retry); - expect(await screen.findByTestId('convo-pull-request')).toBeInTheDocument(); - expect(mockGetMany).toHaveBeenCalledTimes(2); + const { client } = renderMark(); + await waitFor(() => + expect(client.getQueryState(['conversationPullRequest', 'convo-1'])?.status).toBe('error'), + ); + await waitFor(() => + expect(screen.queryByTestId('convo-pull-request-failed')).not.toBeInTheDocument(), + ); }); it.each([ @@ -152,7 +149,7 @@ describe('PullRequestRowMark', () => { expect(container.querySelector('[data-testid="convo-pull-request-failed"]')).toBeNull(); }); - it('shows the failure when a refresh fails after an empty answer was cached', async () => { + it('stays quiet when a refresh fails after an empty answer was cached', async () => { jest.useFakeTimers(); try { mockGetMany @@ -164,7 +161,7 @@ describe('PullRequestRowMark', () => { await jest.advanceTimersByTimeAsync(61_000); window.dispatchEvent(new Event('focus')); await jest.advanceTimersByTimeAsync(100); - expect(screen.getByTestId('convo-pull-request-failed')).toBeInTheDocument(); + expect(screen.queryByTestId('convo-pull-request-failed')).not.toBeInTheDocument(); } finally { jest.useRealTimers(); } @@ -172,12 +169,26 @@ describe('PullRequestRowMark', () => { it('keeps its spacing on the rendered mark, so an absent mark takes no room', async () => { mockGetMany.mockResolvedValue(answer('convo-1', pr)); - const first = renderMark(); - expect(await screen.findByTestId('convo-pull-request')).toHaveClass('me-1'); - first.unmount(); - mockGetMany.mockRejectedValueOnce(new Error('503')); renderMark(); - expect(await screen.findByTestId('convo-pull-request-failed')).toHaveClass('me-1'); + expect(await screen.findByTestId('convo-pull-request')).toHaveClass('me-1'); + }); + + it('keeps a known pull request and offers a retry when its refresh fails', async () => { + mockGetMany.mockResolvedValueOnce(answer('convo-1', pr)); + const { client } = renderMark(); + fireEvent.click(await screen.findByTestId('convo-pull-request')); + await screen.findByTestId('pull-request-card'); + mockGetMany.mockRejectedValueOnce(new Error('503')); + await act(async () => { + await client.refetchQueries(); + }); + expect(await screen.findByText('com_ui_pr_refresh_failed')).toBeInTheDocument(); + expect(screen.getByTestId('pull-request-card')).toHaveTextContent(pr.title); + mockGetMany.mockResolvedValue(answer('convo-1', pr)); + fireEvent.click(screen.getByRole('button', { name: 'com_ui_retry' })); + await waitFor(() => + expect(screen.queryByText('com_ui_pr_refresh_failed')).not.toBeInTheDocument(), + ); }); it('falls back to the single route when the replica that answered has no batch route', async () => { @@ -315,12 +326,14 @@ describe('PullRequestRowMark', () => { expect(onDescribed).not.toHaveBeenCalledWith(true); }); - it('reports a description for a failed lookup too, since it renders the failure text', async () => { + it('does not describe a pull request that has never been discovered', async () => { const onDescribed = jest.fn(); mockGetMany.mockRejectedValueOnce(new Error('503')); - renderMark({ onDescribed }); - await screen.findByTestId('convo-pull-request-failed'); - expect(onDescribed).toHaveBeenLastCalledWith(true); + const { client } = renderMark({ onDescribed }); + await waitFor(() => + expect(client.getQueryState(['conversationPullRequest', 'convo-1'])?.status).toBe('error'), + ); + expect(onDescribed).not.toHaveBeenCalledWith(true); }); it('writes what the colors say into text the row can announce', async () => { diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json index 5f0c51b3b6..84c3168972 100644 --- a/client/src/locales/en/translation.json +++ b/client/src/locales/en/translation.json @@ -24,7 +24,6 @@ "com_ui_pr_deletions": "{{0}} lines removed", "com_ui_pr_label": "PR #{{0}}", "com_ui_pr_label_gitlab": "MR !{{0}}", - "com_ui_pr_load_failed": "Couldn't load the pull request", "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", diff --git a/packages/api/src/pulls/bitbucket.ts b/packages/api/src/pulls/bitbucket.ts index bca611cc10..78f7e6bd17 100644 --- a/packages/api/src/pulls/bitbucket.ts +++ b/packages/api/src/pulls/bitbucket.ts @@ -19,6 +19,7 @@ import { DEFAULT_MAX_HEAD_COMPARISONS, DEFAULT_MAX_CANDIDATE_PULL_REQUESTS, } from './shared'; +import { logDiscoveryDiagnostic } from './diagnostics'; import { PullRequestSourceError } from './types'; export const BITBUCKET_HOST = 'bitbucket.org'; @@ -277,10 +278,16 @@ export function createBitbucketPullRequestSource({ */ const contains = async (hash: string): Promise => { if (recorded == null || recorded.startsWith(hash)) return true; - if (comparisons >= lookup.maxHeadComparisons) return false; + if (comparisons >= lookup.maxHeadComparisons) { + logDiscoveryDiagnostic('bitbucket', 'COMPARISON_LIMIT'); + return false; + } comparisons += 1; const merged = await getJson(`/merge-base/${recorded}..${hash}`, [400]); - if (merged == null) return false; + if (merged == null) { + logDiscoveryDiagnostic('bitbucket', 'COMPARISON_UNAVAILABLE'); + return false; + } if (!isRecord(merged) || typeof merged.hash !== 'string') { throw new PullRequestSourceError('UPSTREAM_ERROR'); } diff --git a/packages/api/src/pulls/diagnostics.spec.ts b/packages/api/src/pulls/diagnostics.spec.ts new file mode 100644 index 0000000000..c40ca0f18e --- /dev/null +++ b/packages/api/src/pulls/diagnostics.spec.ts @@ -0,0 +1,148 @@ +import { logger } from '@librechat/data-schemas'; +import { createBitbucketPullRequestSource } from './bitbucket'; +import { createGitHubPullRequestSource } from './github'; +import { createGitLabPullRequestSource } from './gitlab'; +import { createPullRequestLookup } from './lookup'; +import { PullRequestSourceError } from './types'; + +const recorded = 'a'.repeat(40); +const candidate = 'b'.repeat(40); +const input = { + repo: 'o/r', + branch: 'private-branch', + head: recorded, + token: 'secret-token', + ttlMs: 30_000, +}; + +describe('pull request discovery diagnostics', () => { + let debug: jest.SpyInstance; + + beforeEach(() => { + debug = jest.spyOn(logger, 'debug').mockImplementation(); + }); + afterAll(() => debug.mockRestore()); + + it.each(['CREDENTIAL_REJECTED', 'RATE_LIMITED', 'UPSTREAM_ERROR'] as const)( + 'logs a safe reason for %s without changing the lookup result', + async (code) => { + const lookup = createPullRequestLookup({ + source: { find: jest.fn().mockRejectedValue(new PullRequestSourceError(code)) }, + }); + await expect(lookup(input)).resolves.toEqual({ ok: false, error: { code } }); + expect(debug).toHaveBeenCalledWith('[PullRequests] Discovery diagnostic', { + provider: 'github', + reason: code, + }); + }, + ); + + it('does not log raw unexpected exceptions or lookup identity', async () => { + const lookup = createPullRequestLookup({ + source: { find: jest.fn().mockRejectedValue(new Error('secret-provider-payload')) }, + }); + await lookup(input); + expect(debug.mock.calls).toEqual([ + ['[PullRequests] Discovery diagnostic', { provider: 'github', reason: 'UPSTREAM_ERROR' }], + ]); + }); + + it('does not log a cached failure again', async () => { + const lookup = createPullRequestLookup({ + source: { + find: jest.fn().mockRejectedValue(new PullRequestSourceError('CREDENTIAL_REJECTED')), + }, + }); + await lookup(input); + await lookup(input); + expect(debug).toHaveBeenCalledTimes(1); + }); + + it.each([ + ['github', createGitHubPullRequestSource], + ['gitlab', createGitLabPullRequestSource], + ['bitbucket', createBitbucketPullRequestSource], + ] as const)('%s explains an inconclusive ancestry check', async (provider, create) => { + const fetchFn = jest.fn(async (url: string) => { + if ( + url.includes('/compare/') || + url.includes('/merge_base?') || + url.includes('/merge-base/') + ) { + return new Response(null, { status: 404 }); + } + if (url.includes('state=open&')) { + return Response.json([{ number: 7, state: 'open', head: { sha: candidate } }]); + } + if (url.includes('state=opened')) { + return Response.json([ + { iid: 7, state: 'opened', sha: candidate, source_project_id: 1, target_project_id: 1 }, + ]); + } + if (url.includes('state=OPEN')) { + return Response.json({ + values: [ + { + id: 7, + state: 'OPEN', + source: { + branch: { name: input.branch }, + commit: { hash: candidate }, + repository: { full_name: input.repo }, + }, + }, + ], + }); + } + return Response.json(provider === 'bitbucket' ? { values: [] } : []); + }); + await expect(create({ fetchFn }).find(input)).resolves.toBeNull(); + expect(debug).toHaveBeenCalledWith('[PullRequests] Discovery diagnostic', { + provider, + reason: 'COMPARISON_UNAVAILABLE', + }); + }); + + it.each([ + ['github', createGitHubPullRequestSource], + ['gitlab', createGitLabPullRequestSource], + ['bitbucket', createBitbucketPullRequestSource], + ] as const)('%s explains an exhausted comparison budget', async (provider, create) => { + const fetchFn = jest.fn(async (url: string) => { + if (url.includes('state=open&')) { + return Response.json([{ number: 7, state: 'open', head: { sha: candidate } }]); + } + if (url.includes('state=opened')) { + return Response.json([ + { iid: 7, state: 'opened', sha: candidate, source_project_id: 1, target_project_id: 1 }, + ]); + } + if (url.includes('state=OPEN')) { + return Response.json({ + values: [ + { + id: 7, + state: 'OPEN', + source: { + branch: { name: input.branch }, + commit: { hash: candidate }, + repository: { full_name: input.repo }, + }, + }, + ], + }); + } + return Response.json(provider === 'bitbucket' ? { values: [] } : []); + }); + await expect( + create({ fetchFn }).find({ + ...input, + limits: { maxHeadComparisons: 0 }, + }), + ).resolves.toBeNull(); + expect(debug).toHaveBeenCalledWith('[PullRequests] Discovery diagnostic', { + provider, + reason: 'COMPARISON_LIMIT', + }); + }); +}); diff --git a/packages/api/src/pulls/diagnostics.ts b/packages/api/src/pulls/diagnostics.ts new file mode 100644 index 0000000000..5c8e5da2f1 --- /dev/null +++ b/packages/api/src/pulls/diagnostics.ts @@ -0,0 +1,14 @@ +import { logger } from '@librechat/data-schemas'; +import type { PullRequestProvider } from 'librechat-data-provider'; +import type { PullRequestErrorCode } from './types'; + +/** Provider responses cannot prove whether a comparison failed due to access or missing commits. */ +type DiscoveryReason = PullRequestErrorCode | 'COMPARISON_UNAVAILABLE' | 'COMPARISON_LIMIT'; + +/** Only bounded codes leave discovery here, never credentials, repository identity or payloads. */ +export function logDiscoveryDiagnostic( + provider: PullRequestProvider, + reason: DiscoveryReason, +): void { + logger.debug('[PullRequests] Discovery diagnostic', { provider, reason }); +} diff --git a/packages/api/src/pulls/github.ts b/packages/api/src/pulls/github.ts index 51d1f7ddee..ad554f0da9 100644 --- a/packages/api/src/pulls/github.ts +++ b/packages/api/src/pulls/github.ts @@ -20,6 +20,7 @@ import { DEFAULT_MAX_HEAD_COMPARISONS, DEFAULT_MAX_CANDIDATE_PULL_REQUESTS, } from './shared'; +import { logDiscoveryDiagnostic } from './diagnostics'; import { isAllowedRepository } from './repository'; import { PullRequestSourceError } from './types'; @@ -395,10 +396,16 @@ export function createGitHubPullRequestSource({ * same configured budget. */ const contains = async (headSha: string): Promise => { if (recorded == null || headSha === recorded) return true; - if (comparisons >= lookup.maxHeadComparisons) return false; + if (comparisons >= lookup.maxHeadComparisons) { + logDiscoveryDiagnostic('github', 'COMPARISON_LIMIT'); + return false; + } comparisons += 1; const comparison = await getJson(`${base}/compare/${recorded}...${headSha}`, lookup); - if (comparison == null) return false; + if (comparison == null) { + logDiscoveryDiagnostic('github', 'COMPARISON_UNAVAILABLE'); + return false; + } if (!isRecord(comparison) || typeof comparison.status !== 'string') { throw new PullRequestSourceError('UPSTREAM_ERROR'); } diff --git a/packages/api/src/pulls/gitlab.ts b/packages/api/src/pulls/gitlab.ts index 06cce5a00d..5c396dd09a 100644 --- a/packages/api/src/pulls/gitlab.ts +++ b/packages/api/src/pulls/gitlab.ts @@ -20,6 +20,7 @@ import { DEFAULT_MAX_HEAD_COMPARISONS, DEFAULT_MAX_CANDIDATE_PULL_REQUESTS, } from './shared'; +import { logDiscoveryDiagnostic } from './diagnostics'; import { PullRequestSourceError } from './types'; export const DEFAULT_GITLAB_HOST = 'gitlab.com'; @@ -242,13 +243,19 @@ export function createGitLabPullRequestSource({ */ const contains = async (sha: string): Promise => { if (recorded == null || sha === recorded) return true; - if (comparisons >= lookup.maxHeadComparisons) return false; + if (comparisons >= lookup.maxHeadComparisons) { + logDiscoveryDiagnostic('gitlab', 'COMPARISON_LIMIT'); + return false; + } comparisons += 1; const base = await getJson( `/repository/merge_base?refs[]=${recorded}&refs[]=${encodeURIComponent(sha)}`, [400], ); - if (base == null) return false; + if (base == null) { + logDiscoveryDiagnostic('gitlab', 'COMPARISON_UNAVAILABLE'); + return false; + } if (!isRecord(base) || typeof base.id !== 'string') { throw new PullRequestSourceError('UPSTREAM_ERROR'); } diff --git a/packages/api/src/pulls/lookup.ts b/packages/api/src/pulls/lookup.ts index d0a1266782..9471465dfb 100644 --- a/packages/api/src/pulls/lookup.ts +++ b/packages/api/src/pulls/lookup.ts @@ -14,6 +14,7 @@ import type { PullRequestLookupStore, PullRequestLookupResult, } from './types'; +import { logDiscoveryDiagnostic } from './diagnostics'; import { PullRequestSourceError } from './types'; import { getSafeErrorMetadata } from '~/utils'; @@ -319,6 +320,7 @@ export function createPullRequestLookup({ logger.warn('[PullRequests] Lookup failed', getSafeErrorMetadata(error)); } const code = error instanceof PullRequestSourceError ? error.code : 'UPSTREAM_ERROR'; + logDiscoveryDiagnostic(provider ?? 'github', code); if (error instanceof PullRequestSourceError && error.code === 'RATE_LIMITED') { const wait = Math.min( MAX_COOLDOWN_MS,