🔎 fix: Quiet Initial PR Discovery Failures and Add Safe Diagnostics (#17436)

* fix: Quiet Initial PR Discovery Failures and Add Safe Diagnostics

* fix: Resolve PR Discovery Static Check Failures
This commit is contained in:
Marco Beretta 2026-10-25 23:18:10 +01:00 • committed by GitHub
parent 7e036380f2
commit 1bbef4a71e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
9 changed files with 230 additions and 90 deletions

View file

@ -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 (
<Ariakit.HovercardProvider store={store}>
<Ariakit.HovercardAnchor
render={<Ariakit.Button ref={markRef} />}
aria-label={failed}
aria-expanded={open}
showOnHover={rowRef == null}
data-testid="convo-pull-request-failed"
onFocus={(event: React.FocusEvent<HTMLElement>) => {
anchorToMark(event);
store.show();
}}
onClick={(event: React.MouseEvent<HTMLElement>) => {
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"
>
<TriangleAlert aria-hidden="true" className="size-4 shrink-0" />
</Ariakit.HovercardAnchor>
<span id={labelId} className="sr-only">
{failed}
</span>
<Ariakit.Hovercard
store={store}
gutter={8}
portal
unmountOnHide
autoFocusOnShow={false}
finalFocus={finalFocus}
aria-label={localize('com_ui_pull_request')}
className={cn(panelClass, 'w-auto')}
onClick={(event) => event.stopPropagation()}
onDoubleClick={(event) => event.stopPropagation()}
onContextMenu={(event) => event.stopPropagation()}
onKeyDown={(event) => event.stopPropagation()}
>
<div role="status" className="text-status-warning flex items-center gap-2 p-3 text-xs">
<span>{failed}</span>
<Button type="button" variant="outline" size="sm" onClick={() => void refetch()}>
{localize('com_ui_retry')}
</Button>
</div>
</Ariakit.Hovercard>
</Ariakit.HovercardProvider>
);
}
/* Discovery is automatic: only a known pull request can have a refresh warning. */
if (pullRequest == null) return null;
const view = presentPullRequest(pullRequest);

View file

@ -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 () => {

View file

@ -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",

View file

@ -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<boolean> => {
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');
}

View file

@ -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',
});
});
});

View file

@ -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 });
}

View file

@ -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<boolean> => {
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');
}

View file

@ -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<boolean> => {
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');
}

View file

@ -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,