mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-17 21:43:06 +00:00
🔀 feat: Show the Conversation Pull Request in the Sidebar List (#16815)
* feat: Show the Conversation Pull Request in the Sidebar List Add a batch lookup route and a sidebar row mark: the state icon with the CI dot, opening the same card beside the row on hover. The row keeps the conversation's own title. * fix: Address Review Findings on the Sidebar Pull Request Batch and Row Mark Cap the whole batch with a configurable deadline, make the row mark a keyboard-reachable button that opens the card on focus, refresh rows when the window regains focus through the shared batch, and show a retryable failure state instead of treating a failed first lookup as no pull request. * fix: Send Sidebar Pull Request Batches One at a Time Queue every batch request behind the one before it, so an oversized list or an overlapping flush cannot multiply the server's configured lookup concurrency, and bound how long one request may hold the queue so a request that never answers cannot stop the rest. * fix: Keep the Batch Request Timeout Above the Server Deadline Default the client's request timeout to just past the longest batchTimeoutSeconds a deployment may configure, so a queued request never starts while the previous request's server-side lookups are still running. * fix: Keep Batch Lookups Inside the Concurrency Limit and Per-Entry Failures Per Entry Share one lookup limiter across every batch request so lookups that outlive a request's deadline keep their slot, answer a missing token only for the conversations that needed it, and point the row at its pull request description only while that text is in the page. * fix: Bound Batch Reads, Scope Concurrency Per Credential, and Gate the Sidebar on the Batch Version Start the batch deadline when the request arrives and bound the config and lane reads, count lookup slots per credential, advertise a batch route version and ask only a server that has it, take no row space for an absent mark, show a failed refresh over a cached empty answer, keep a malformed response from stalling the request queue, and repair the lane recording tests that still used a mock removed on dev. * fix: Move Capability Resolution Into the Package and Harden the Batch Route and Queue Resolve the pull request startup capabilities in packages/api so the route stays wiring only, bound the config and lane reads by the configured deadline, merge identical lanes before taking limiter slots, fall back to the single route when a replica has no batch route, and dispose the batch queue when the signed-in user changes. * fix: Abort the Batch Fallback With Its Request So the Queue Never Overlaps It Give the batch fetcher the request's abort signal and pass it to every single-route call, abort a request that times out or is disposed, and stop the fallback workers from starting more calls once it has. * fix: Forward the Abort Signal to the Batch POST Pass the request's abort signal through the batch fetcher, the data-provider call and Axios, so a batch request that times out or is disposed is cancelled instead of continuing beside the next one, and settle a request promptly when it is aborted. * fix: Close the Pull Request Lookup Follow-Ups and Cancel Abandoned Sidebar Rows
This commit is contained in:
parent
cdf2e94dcf
commit
caeb786e97
47 changed files with 4260 additions and 128 deletions
|
|
@ -5,31 +5,10 @@ import { useAgentsMapContext, useChatContext } from '~/Providers';
|
|||
import { TONE_DOT_CLASS, presentPullRequest } from './status';
|
||||
import { URLIcon } from '~/components/Endpoints/URLIcon';
|
||||
import { summarizePullRequest } from './summary';
|
||||
import PullRequestPanel from './Panel';
|
||||
import { useLocalize } from '~/hooks';
|
||||
import PullRequestIcon from './Icon';
|
||||
import PullRequestCard from './Card';
|
||||
import { cn } from '~/utils';
|
||||
|
||||
/** Slides in from the chip's side, left to right, and fades; reduced motion only fades. */
|
||||
const cardClass = cn(
|
||||
'border-border-light bg-surface-secondary text-text-primary z-[200] w-80 max-w-[calc(100vw-2rem)] rounded-xl border shadow-lg focus:outline-none',
|
||||
'origin-left -translate-x-3 opacity-0 transition duration-200 ease-out',
|
||||
'data-[enter]:translate-x-0 data-[enter]:opacity-100',
|
||||
'data-[leave]:-translate-x-3 data-[leave]:opacity-0',
|
||||
'motion-reduce:translate-x-0 motion-reduce:transition-opacity',
|
||||
);
|
||||
|
||||
function CiDot({ dotClass }: { dotClass: string }) {
|
||||
return (
|
||||
<span
|
||||
data-testid="pull-request-ci-dot"
|
||||
className={cn(
|
||||
'ring-presentation absolute -right-0.5 -bottom-0.5 size-2 rounded-full ring-2',
|
||||
dotClass,
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
import CiDot from './CiDot';
|
||||
|
||||
/** The agent's picture with the CI dot on its corner. */
|
||||
function AgentAvatar({
|
||||
|
|
@ -72,7 +51,6 @@ function PullRequestChip({ conversationId }: { conversationId: string }) {
|
|||
hideTimeout: 150,
|
||||
});
|
||||
const open = Ariakit.useStoreState(hovercard, 'open');
|
||||
const cardElement = Ariakit.useStoreState(hovercard, 'contentElement');
|
||||
const { data, isError, refetch } = useConversationPullRequestQuery(conversationId);
|
||||
const pullRequest = data?.pullRequest;
|
||||
|
||||
|
|
@ -108,21 +86,12 @@ function PullRequestChip({ conversationId }: { conversationId: string }) {
|
|||
</Ariakit.Button>
|
||||
}
|
||||
/>
|
||||
<Ariakit.Hovercard
|
||||
gutter={8}
|
||||
portal
|
||||
unmountOnHide
|
||||
autoFocusOnShow={false}
|
||||
aria-label={localize('com_ui_pull_request')}
|
||||
className={cardClass}
|
||||
>
|
||||
<PullRequestCard
|
||||
pullRequest={pullRequest}
|
||||
refreshFailed={isError}
|
||||
onRetry={() => void refetch()}
|
||||
portalElement={cardElement}
|
||||
/>
|
||||
</Ariakit.Hovercard>
|
||||
<PullRequestPanel
|
||||
store={hovercard}
|
||||
pullRequest={pullRequest}
|
||||
refreshFailed={isError}
|
||||
onRetry={() => void refetch()}
|
||||
/>
|
||||
</Ariakit.HovercardProvider>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
25
client/src/components/Chat/PullRequest/CiDot.tsx
Normal file
25
client/src/components/Chat/PullRequest/CiDot.tsx
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
import { cn } from '~/utils';
|
||||
|
||||
/**
|
||||
* The CI status dot that sits on the corner of the picture or icon it describes. The ring is
|
||||
* painted in the surface the dot sits on, so the caller names that surface.
|
||||
*/
|
||||
export default function CiDot({
|
||||
dotClass,
|
||||
ringClassName = 'ring-presentation',
|
||||
}: {
|
||||
dotClass: string;
|
||||
ringClassName?: string;
|
||||
}) {
|
||||
return (
|
||||
<span
|
||||
data-testid="pull-request-ci-dot"
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
'pointer-events-none absolute -right-0.5 -bottom-0.5 size-2 rounded-full ring-2',
|
||||
ringClassName,
|
||||
dotClass,
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
58
client/src/components/Chat/PullRequest/Panel.tsx
Normal file
58
client/src/components/Chat/PullRequest/Panel.tsx
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
import * as Ariakit from '@ariakit/react';
|
||||
import type { TConversationPullRequest } from 'librechat-data-provider';
|
||||
import { useLocalize } from '~/hooks';
|
||||
import PullRequestCard from './Card';
|
||||
import { cn } from '~/utils';
|
||||
|
||||
/** Slides in from the anchor's side, left to right, and fades; reduced motion only fades. */
|
||||
export const panelClass = cn(
|
||||
'border-border-light bg-surface-secondary text-text-primary z-[200] w-80 max-w-[calc(100vw-2rem)] rounded-xl border shadow-lg focus:outline-none',
|
||||
'origin-left -translate-x-3 opacity-0 transition duration-200 ease-out',
|
||||
'data-[enter]:translate-x-0 data-[enter]:opacity-100',
|
||||
'data-[leave]:-translate-x-3 data-[leave]:opacity-0',
|
||||
'motion-reduce:translate-x-0 motion-reduce:transition-opacity',
|
||||
);
|
||||
|
||||
/**
|
||||
* The card as a hovercard beside its anchor. It is portaled, and a portal's events still bubble
|
||||
* to the React tree that rendered it, so anything that sits inside a clickable row stops them
|
||||
* here: a click on the card must not open the row it hangs from.
|
||||
*/
|
||||
export default function PullRequestPanel({
|
||||
store,
|
||||
pullRequest,
|
||||
refreshFailed,
|
||||
onRetry,
|
||||
}: {
|
||||
store: Ariakit.HovercardStore;
|
||||
pullRequest: TConversationPullRequest;
|
||||
refreshFailed: boolean;
|
||||
onRetry: () => void;
|
||||
}) {
|
||||
const localize = useLocalize();
|
||||
const panelElement = Ariakit.useStoreState(store, 'contentElement');
|
||||
const stop = (event: { stopPropagation: () => void }) => event.stopPropagation();
|
||||
|
||||
return (
|
||||
<Ariakit.Hovercard
|
||||
store={store}
|
||||
gutter={8}
|
||||
portal
|
||||
unmountOnHide
|
||||
autoFocusOnShow={false}
|
||||
aria-label={localize('com_ui_pull_request')}
|
||||
className={panelClass}
|
||||
onClick={stop}
|
||||
onDoubleClick={stop}
|
||||
onContextMenu={stop}
|
||||
onKeyDown={stop}
|
||||
>
|
||||
<PullRequestCard
|
||||
pullRequest={pullRequest}
|
||||
refreshFailed={refreshFailed}
|
||||
onRetry={onRetry}
|
||||
portalElement={panelElement}
|
||||
/>
|
||||
</Ariakit.Hovercard>
|
||||
);
|
||||
}
|
||||
150
client/src/components/Chat/PullRequest/RowMark.tsx
Normal file
150
client/src/components/Chat/PullRequest/RowMark.tsx
Normal file
|
|
@ -0,0 +1,150 @@
|
|||
import { memo, useEffect } from 'react';
|
||||
import * as Ariakit from '@ariakit/react';
|
||||
import { Button } from '@librechat/client';
|
||||
import { TriangleAlert } from 'lucide-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 { useLocalize } from '~/hooks';
|
||||
import PullRequestIcon from './Icon';
|
||||
import { cn } from '~/utils';
|
||||
import CiDot from './CiDot';
|
||||
|
||||
/** The row's own surface at each state, so the dot's ring blends into it. */
|
||||
const RING_SELECTED = 'ring-surface-nav-selected';
|
||||
const RING_IDLE = 'ring-surface-primary-alt group-hover:ring-surface-nav-hover';
|
||||
|
||||
/**
|
||||
* The pull request a conversation opened, as a mark in its sidebar row: the state icon with the
|
||||
* CI dot on its corner. It renders nothing until a pull request is known, so a row without one
|
||||
* is exactly what it was. The row's title stays the conversation's own title; this only adds
|
||||
* the icon. The mark is a button beside the row's own, so Tab reaches it: focusing it opens the
|
||||
* card, which holds the GitHub link, and activating it must not also open the row.
|
||||
*/
|
||||
function PullRequestRowMark({
|
||||
conversationId,
|
||||
labelId,
|
||||
selected,
|
||||
onDescribed,
|
||||
}: {
|
||||
conversationId: string;
|
||||
/** The id the row lists in `aria-describedby`, so a screen reader hears what the colors say. */
|
||||
labelId: string;
|
||||
selected: boolean;
|
||||
/** Tells the row whether `labelId` is in the page, so it never points at text that is not. */
|
||||
onDescribed?: (described: boolean) => void;
|
||||
}) {
|
||||
const localize = useLocalize();
|
||||
const store = Ariakit.useHovercardStore({
|
||||
placement: 'right-start',
|
||||
showTimeout: 100,
|
||||
hideTimeout: 150,
|
||||
});
|
||||
const open = Ariakit.useStoreState(store, 'open');
|
||||
const { data, isError, refetch } = useRowPullRequestQuery(conversationId);
|
||||
const pullRequest = data?.pullRequest;
|
||||
const described = pullRequest != null || isError;
|
||||
|
||||
useEffect(() => {
|
||||
onDescribed?.(described);
|
||||
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 />}
|
||||
aria-label={failed}
|
||||
aria-expanded={open}
|
||||
data-testid="convo-pull-request-failed"
|
||||
onFocus={() => store.show()}
|
||||
onClick={(event: React.MouseEvent) => {
|
||||
event.stopPropagation();
|
||||
store.show();
|
||||
}}
|
||||
onKeyDown={(event: React.KeyboardEvent) => {
|
||||
if (event.key === 'Enter' || event.key === ' ') event.stopPropagation();
|
||||
}}
|
||||
className="focus-visible:ring-text-primary text-status-warning relative mr-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}
|
||||
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>
|
||||
);
|
||||
}
|
||||
|
||||
if (pullRequest == null) return null;
|
||||
|
||||
const view = presentPullRequest(pullRequest);
|
||||
const dotClass = view.dotTone == null ? null : TONE_DOT_CLASS[view.dotTone];
|
||||
const summary = summarizePullRequest(pullRequest, localize);
|
||||
|
||||
return (
|
||||
<Ariakit.HovercardProvider store={store}>
|
||||
<Ariakit.HovercardAnchor
|
||||
render={<Ariakit.Button />}
|
||||
aria-label={summary}
|
||||
aria-expanded={open}
|
||||
data-testid="convo-pull-request"
|
||||
onFocus={() => store.show()}
|
||||
onClick={(event: React.MouseEvent) => {
|
||||
/* The row itself opens the conversation on click; this opens the card instead. */
|
||||
event.stopPropagation();
|
||||
store.show();
|
||||
}}
|
||||
onKeyDown={(event: React.KeyboardEvent) => {
|
||||
/* Enter and Space belong to this button, not to the row's own shortcuts. */
|
||||
if (event.key === 'Enter' || event.key === ' ') event.stopPropagation();
|
||||
}}
|
||||
className={cn(
|
||||
'focus-visible:ring-text-primary relative mr-1 flex size-4 shrink-0 items-center justify-center rounded-sm outline-hidden focus-visible:ring-2',
|
||||
)}
|
||||
>
|
||||
<PullRequestIcon icon={view.icon} tone={view.iconTone} className="size-4 shrink-0" />
|
||||
{dotClass != null && (
|
||||
<CiDot dotClass={dotClass} ringClassName={selected ? RING_SELECTED : RING_IDLE} />
|
||||
)}
|
||||
</Ariakit.HovercardAnchor>
|
||||
<span id={labelId} className="sr-only">
|
||||
{summary}
|
||||
</span>
|
||||
<PullRequestPanel
|
||||
store={store}
|
||||
pullRequest={pullRequest}
|
||||
refreshFailed={isError}
|
||||
onRetry={() => void refetch()}
|
||||
/>
|
||||
</Ariakit.HovercardProvider>
|
||||
);
|
||||
}
|
||||
|
||||
export default memo(PullRequestRowMark);
|
||||
|
|
@ -0,0 +1,438 @@
|
|||
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 type { TConversationPullRequest } from 'librechat-data-provider';
|
||||
import PullRequestRowMark from '../RowMark';
|
||||
|
||||
const mockGetMany = jest.fn();
|
||||
const mockGetOne = jest.fn();
|
||||
const mockStartup: {
|
||||
current: { pullRequestsEnabled?: boolean; pullRequestsBatchVersion?: number } | undefined;
|
||||
} = {
|
||||
current: { pullRequestsEnabled: true, pullRequestsBatchVersion: 1 },
|
||||
};
|
||||
|
||||
const mockUser: { current: { id: string } | undefined } = { current: { id: 'user-a' } };
|
||||
jest.mock('recoil', () => ({
|
||||
...jest.requireActual('recoil'),
|
||||
useRecoilValue: () => mockUser.current,
|
||||
}));
|
||||
jest.mock('~/data-provider/Endpoints', () => ({
|
||||
useGetStartupConfig: () => ({ data: mockStartup.current }),
|
||||
}));
|
||||
jest.mock('librechat-data-provider', () => {
|
||||
const actual = jest.requireActual('librechat-data-provider');
|
||||
return {
|
||||
...actual,
|
||||
dataService: {
|
||||
...actual.dataService,
|
||||
getConversationPullRequests: (...args: unknown[]) => mockGetMany(...args),
|
||||
getConversationPullRequest: (...args: unknown[]) => mockGetOne(...args),
|
||||
},
|
||||
};
|
||||
});
|
||||
jest.mock('~/hooks', () => ({
|
||||
useLocalize: () => (key: string, values?: Record<string, string | number>) =>
|
||||
values == null ? key : `${key}:${Object.values(values).join(',')}`,
|
||||
}));
|
||||
|
||||
const pr: TConversationPullRequest = {
|
||||
number: 1234,
|
||||
title: 'Simplify Single Tool Execution Path',
|
||||
url: 'https://github.com/LibreChat-AI/LibreChat/pull/1234',
|
||||
additions: 1234,
|
||||
deletions: 56,
|
||||
state: 'open',
|
||||
isDraft: false,
|
||||
mergeable: 'clean',
|
||||
checks: 'passing',
|
||||
};
|
||||
|
||||
const answer = (conversationId: string, value: TConversationPullRequest | null) => ({
|
||||
results: [{ conversationId, pullRequest: value }],
|
||||
});
|
||||
|
||||
let pointerX = 100;
|
||||
const movePointerOver = (element: HTMLElement) => {
|
||||
pointerX += 7;
|
||||
fireEvent.mouseMove(element, {
|
||||
screenX: pointerX,
|
||||
screenY: pointerX,
|
||||
movementX: 7,
|
||||
movementY: 7,
|
||||
});
|
||||
};
|
||||
|
||||
const renderMark = (props: Partial<React.ComponentProps<typeof PullRequestRowMark>> = {}) => {
|
||||
const rowClick = jest.fn();
|
||||
const rowKey = jest.fn();
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
const view = render(
|
||||
<QueryClientProvider client={client}>
|
||||
<div data-testid="row" onClick={rowClick} onKeyDown={rowKey}>
|
||||
<PullRequestRowMark
|
||||
conversationId="convo-1"
|
||||
labelId="pr-label"
|
||||
selected={false}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
return { ...view, rowClick, rowKey, client };
|
||||
};
|
||||
|
||||
describe('PullRequestRowMark', () => {
|
||||
beforeEach(() => {
|
||||
mockGetMany.mockReset();
|
||||
mockGetOne.mockReset();
|
||||
mockStartup.current = { pullRequestsEnabled: true, pullRequestsBatchVersion: 1 };
|
||||
mockUser.current = { id: 'user-a' };
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
'while loading',
|
||||
() => new Promise((resolve) => setTimeout(() => resolve(answer('convo-1', null)), 40)),
|
||||
],
|
||||
['without a pull request', () => Promise.resolve(answer('convo-1', null))],
|
||||
])('renders nothing %s, so the row is unchanged', async (_label, respond) => {
|
||||
mockGetMany.mockImplementation(respond);
|
||||
const { container } = renderMark();
|
||||
await waitFor(() => expect(mockGetMany).toHaveBeenCalled());
|
||||
await new Promise((resolve) => setTimeout(resolve, 30));
|
||||
expect(container.querySelector('[data-testid="convo-pull-request"]')).toBeNull();
|
||||
expect(container.querySelector('[data-testid="convo-pull-request-failed"]')).toBeNull();
|
||||
});
|
||||
|
||||
it.each([
|
||||
['the request fails', () => Promise.reject(new Error('503'))],
|
||||
[
|
||||
'that conversation failed on the server',
|
||||
() =>
|
||||
Promise.resolve({
|
||||
results: [{ conversationId: 'convo-1', error: { code: 'RATE_LIMITED' } }],
|
||||
}),
|
||||
],
|
||||
])('says the lookup failed, with a retry, 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);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['an older server that has the flag but not the batch route', { pullRequestsEnabled: true }],
|
||||
[
|
||||
'a batch version this client does not know',
|
||||
{ pullRequestsEnabled: true, pullRequestsBatchVersion: 2 },
|
||||
],
|
||||
['the version without the flag', { pullRequestsBatchVersion: 1 }],
|
||||
])('does not ask %s, so a rolling upgrade shows no failure marks', async (_label, startup) => {
|
||||
mockStartup.current = startup;
|
||||
const { container } = renderMark();
|
||||
await new Promise((resolve) => setTimeout(resolve, 80));
|
||||
expect(mockGetMany).not.toHaveBeenCalled();
|
||||
expect(container.querySelector('[data-testid="convo-pull-request"]')).toBeNull();
|
||||
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 () => {
|
||||
jest.useFakeTimers();
|
||||
try {
|
||||
mockGetMany
|
||||
.mockResolvedValueOnce(answer('convo-1', null))
|
||||
.mockRejectedValue(new Error('503'));
|
||||
renderMark();
|
||||
await jest.advanceTimersByTimeAsync(100);
|
||||
expect(screen.queryByTestId('convo-pull-request-failed')).toBeNull();
|
||||
await jest.advanceTimersByTimeAsync(61_000);
|
||||
window.dispatchEvent(new Event('focus'));
|
||||
await jest.advanceTimersByTimeAsync(100);
|
||||
expect(screen.getByTestId('convo-pull-request-failed')).toBeInTheDocument();
|
||||
} finally {
|
||||
jest.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
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('mr-1');
|
||||
first.unmount();
|
||||
mockGetMany.mockRejectedValueOnce(new Error('503'));
|
||||
renderMark();
|
||||
expect(await screen.findByTestId('convo-pull-request-failed')).toHaveClass('mr-1');
|
||||
});
|
||||
|
||||
it('falls back to the single route when the replica that answered has no batch route', async () => {
|
||||
mockGetMany.mockRejectedValue(
|
||||
Object.assign(new Error('Not Found'), { response: { status: 404 } }),
|
||||
);
|
||||
mockGetOne.mockResolvedValue({ pullRequest: pr });
|
||||
renderMark();
|
||||
expect(await screen.findByTestId('convo-pull-request')).toBeInTheDocument();
|
||||
expect(mockGetOne).toHaveBeenCalledWith('convo-1', { signal: expect.any(AbortSignal) });
|
||||
expect(screen.queryByTestId('convo-pull-request-failed')).toBeNull();
|
||||
});
|
||||
|
||||
it('shows no failure for a conversation without a pull request when only the batch route is missing', async () => {
|
||||
mockGetMany.mockRejectedValue(
|
||||
Object.assign(new Error('Not Found'), { response: { status: 404 } }),
|
||||
);
|
||||
mockGetOne.mockResolvedValue({ pullRequest: null });
|
||||
const { container } = renderMark();
|
||||
await waitFor(() => expect(mockGetOne).toHaveBeenCalled());
|
||||
await new Promise((resolve) => setTimeout(resolve, 30));
|
||||
expect(container.querySelector('[data-testid="convo-pull-request-failed"]')).toBeNull();
|
||||
expect(container.querySelector('[data-testid="convo-pull-request"]')).toBeNull();
|
||||
});
|
||||
|
||||
it('does not ask for a user it cannot name, so a batch is never sent for no one', async () => {
|
||||
mockUser.current = undefined;
|
||||
const { container } = renderMark();
|
||||
await new Promise((resolve) => setTimeout(resolve, 80));
|
||||
expect(mockGetMany).not.toHaveBeenCalled();
|
||||
expect(container.querySelector('[data-testid="convo-pull-request"]')).toBeNull();
|
||||
});
|
||||
|
||||
it('asks again for the next account, in a queue of its own, once the user changes', async () => {
|
||||
mockGetMany.mockResolvedValue(answer('convo-1', pr));
|
||||
const first = renderMark({ conversationId: 'convo-1' });
|
||||
await screen.findByTestId('convo-pull-request');
|
||||
first.unmount();
|
||||
|
||||
/** The next account's row is not held up by anything the previous account left queued. */
|
||||
mockUser.current = { id: 'user-b' };
|
||||
mockGetMany.mockResolvedValue(answer('convo-2', { ...pr, number: 2 }));
|
||||
renderMark({ conversationId: 'convo-2' });
|
||||
await screen.findByTestId('convo-pull-request');
|
||||
expect(mockGetMany).toHaveBeenLastCalledWith(['convo-2'], { signal: expect.any(AbortSignal) });
|
||||
});
|
||||
|
||||
it('does not hold the next account behind work the previous account left in flight', async () => {
|
||||
/** The first account's request never answers, as a stalled upstream would leave it. */
|
||||
mockGetMany.mockImplementationOnce(() => new Promise(() => undefined));
|
||||
const stalled = renderMark({ conversationId: 'convo-1' });
|
||||
await waitFor(() => expect(mockGetMany).toHaveBeenCalledTimes(1));
|
||||
stalled.unmount();
|
||||
|
||||
mockUser.current = { id: 'user-b' };
|
||||
mockGetMany.mockResolvedValue(answer('convo-2', { ...pr, number: 2 }));
|
||||
renderMark({ conversationId: 'convo-2' });
|
||||
/** Without a queue of its own it would wait out the other account's request, which never ends. */
|
||||
expect(await screen.findByTestId('convo-pull-request')).toBeInTheDocument();
|
||||
expect(mockGetMany).toHaveBeenLastCalledWith(['convo-2'], { signal: expect.any(AbortSignal) });
|
||||
});
|
||||
|
||||
it('does not ask when the deployment does not advertise the feature', async () => {
|
||||
mockStartup.current = { pullRequestsEnabled: false };
|
||||
const { container } = renderMark();
|
||||
await new Promise((resolve) => setTimeout(resolve, 80));
|
||||
expect(mockGetMany).not.toHaveBeenCalled();
|
||||
expect(container.querySelector('[data-testid="convo-pull-request"]')).toBeNull();
|
||||
});
|
||||
|
||||
it('asks through the batch endpoint with the conversation id', async () => {
|
||||
mockGetMany.mockResolvedValue(answer('convo-1', pr));
|
||||
renderMark();
|
||||
await screen.findByTestId('convo-pull-request');
|
||||
expect(mockGetMany).toHaveBeenCalledWith(['convo-1'], { signal: expect.any(AbortSignal) });
|
||||
});
|
||||
|
||||
it('shows the state icon with the CI dot, in the row surface colors', async () => {
|
||||
mockGetMany.mockResolvedValue(answer('convo-1', pr));
|
||||
renderMark({ selected: false });
|
||||
const dot = await screen.findByTestId('pull-request-ci-dot');
|
||||
expect(dot).toHaveClass('bg-status-success', 'ring-surface-primary-alt');
|
||||
expect(screen.getByTestId('convo-pull-request').querySelector('svg')).toHaveClass(
|
||||
'text-status-success',
|
||||
);
|
||||
});
|
||||
|
||||
it('paints the dot ring in the selected surface for the open conversation', async () => {
|
||||
mockGetMany.mockResolvedValue(answer('convo-1', pr));
|
||||
renderMark({ selected: true });
|
||||
expect(await screen.findByTestId('pull-request-ci-dot')).toHaveClass(
|
||||
'ring-surface-nav-selected',
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['failing', { checks: 'failing' as const }, 'bg-status-error', 'text-status-success'],
|
||||
['running', { checks: 'running' as const }, 'bg-status-warning', 'text-status-success'],
|
||||
['conflicts', { mergeable: 'conflicting' as const }, 'bg-status-success', 'text-status-error'],
|
||||
])('colors the dot and icon for %s', async (_label, patch, dotClass, iconClass) => {
|
||||
mockGetMany.mockResolvedValue(answer('convo-1', { ...pr, ...patch }));
|
||||
renderMark();
|
||||
expect(await screen.findByTestId('pull-request-ci-dot')).toHaveClass(dotClass);
|
||||
expect(screen.getByTestId('convo-pull-request').querySelector('svg')).toHaveClass(iconClass);
|
||||
});
|
||||
|
||||
it('shows no dot when there are no checks, or the pull request is finished', async () => {
|
||||
mockGetMany.mockResolvedValue(answer('convo-1', { ...pr, checks: 'none' }));
|
||||
const first = renderMark();
|
||||
await screen.findByTestId('convo-pull-request');
|
||||
expect(screen.queryByTestId('pull-request-ci-dot')).not.toBeInTheDocument();
|
||||
first.unmount();
|
||||
mockGetMany.mockResolvedValue(answer('convo-1', { ...pr, state: 'merged' }));
|
||||
renderMark();
|
||||
await screen.findByTestId('convo-pull-request');
|
||||
expect(screen.queryByTestId('pull-request-ci-dot')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('tells the row when its description exists, and when it stops existing', async () => {
|
||||
const onDescribed = jest.fn();
|
||||
mockGetMany.mockResolvedValue(answer('convo-1', pr));
|
||||
const { unmount } = renderMark({ onDescribed });
|
||||
await screen.findByTestId('convo-pull-request');
|
||||
expect(onDescribed).toHaveBeenLastCalledWith(true);
|
||||
unmount();
|
||||
expect(onDescribed).toHaveBeenLastCalledWith(false);
|
||||
});
|
||||
|
||||
it('reports no description while loading or without a pull request', async () => {
|
||||
const onDescribed = jest.fn();
|
||||
mockGetMany.mockResolvedValue(answer('convo-1', null));
|
||||
renderMark({ onDescribed });
|
||||
await waitFor(() => expect(mockGetMany).toHaveBeenCalled());
|
||||
await new Promise((resolve) => setTimeout(resolve, 30));
|
||||
expect(onDescribed).not.toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it('reports a description for a failed lookup too, since it renders the failure text', async () => {
|
||||
const onDescribed = jest.fn();
|
||||
mockGetMany.mockRejectedValueOnce(new Error('503'));
|
||||
renderMark({ onDescribed });
|
||||
await screen.findByTestId('convo-pull-request-failed');
|
||||
expect(onDescribed).toHaveBeenLastCalledWith(true);
|
||||
});
|
||||
|
||||
it('writes what the colors say into text the row can announce', async () => {
|
||||
mockGetMany.mockResolvedValue(answer('convo-1', pr));
|
||||
renderMark({ labelId: 'row-pr' });
|
||||
await screen.findByTestId('convo-pull-request');
|
||||
const text = document.getElementById('row-pr');
|
||||
expect(text).toHaveTextContent(pr.title);
|
||||
expect(text).toHaveTextContent('com_ui_pr_state_open');
|
||||
expect(text).toHaveTextContent('com_ui_pr_checks_passing');
|
||||
});
|
||||
|
||||
it('is a button with an accessible name that says what the colors say', async () => {
|
||||
mockGetMany.mockResolvedValue(answer('convo-1', pr));
|
||||
renderMark();
|
||||
const mark = await screen.findByTestId('convo-pull-request');
|
||||
expect(mark.tagName).toBe('BUTTON');
|
||||
expect(mark).toHaveAccessibleName(expect.stringContaining(pr.title));
|
||||
expect(mark).toHaveAccessibleName(expect.stringContaining('com_ui_pr_checks_passing'));
|
||||
expect(mark).toHaveAttribute('aria-expanded', 'false');
|
||||
});
|
||||
|
||||
it('opens the card for keyboard focus, so its GitHub link is reachable', async () => {
|
||||
mockGetMany.mockResolvedValue(answer('convo-1', pr));
|
||||
renderMark();
|
||||
const mark = await screen.findByTestId('convo-pull-request');
|
||||
await userEvent.tab();
|
||||
expect(mark).toHaveFocus();
|
||||
expect(await screen.findByTestId('pull-request-card')).toBeInTheDocument();
|
||||
expect(mark).toHaveAttribute('aria-expanded', 'true');
|
||||
});
|
||||
|
||||
it('opens the card on click without opening the row, and keeps Enter and Space off the row', async () => {
|
||||
mockGetMany.mockResolvedValue(answer('convo-1', pr));
|
||||
const { rowClick, rowKey } = renderMark();
|
||||
const mark = await screen.findByTestId('convo-pull-request');
|
||||
fireEvent.click(mark);
|
||||
expect(await screen.findByTestId('pull-request-card')).toBeInTheDocument();
|
||||
fireEvent.keyDown(mark, { key: 'Enter' });
|
||||
fireEvent.keyDown(mark, { key: ' ' });
|
||||
expect(rowClick).not.toHaveBeenCalled();
|
||||
expect(rowKey).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('opens the card to the side on hover, and closes it when the pointer leaves', async () => {
|
||||
mockGetMany.mockResolvedValue(answer('convo-1', pr));
|
||||
renderMark();
|
||||
const mark = await screen.findByTestId('convo-pull-request');
|
||||
expect(screen.queryByTestId('pull-request-card')).not.toBeInTheDocument();
|
||||
movePointerOver(mark);
|
||||
const card = await screen.findByTestId('pull-request-card');
|
||||
expect(card).toHaveTextContent(pr.title);
|
||||
expect(screen.getByTestId('pull-request-github-link')).toHaveAttribute('href', pr.url);
|
||||
fireEvent.mouseLeave(mark);
|
||||
fireEvent.mouseMove(document.body, { screenX: 900, screenY: 900, movementX: 7, movementY: 7 });
|
||||
await waitFor(() => expect(screen.queryByTestId('pull-request-card')).not.toBeInTheDocument());
|
||||
});
|
||||
|
||||
it('does not open the row when the card is clicked', async () => {
|
||||
mockGetMany.mockResolvedValue(answer('convo-1', pr));
|
||||
const { rowClick } = renderMark();
|
||||
movePointerOver(await screen.findByTestId('convo-pull-request'));
|
||||
const card = await screen.findByTestId('pull-request-card');
|
||||
fireEvent.click(card);
|
||||
fireEvent.click(screen.getByTestId('pull-request-github-link'));
|
||||
expect(rowClick).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('refreshes every row in one request when the window regains focus, once its answer is stale', async () => {
|
||||
jest.useFakeTimers();
|
||||
try {
|
||||
mockGetMany.mockResolvedValue(answer('convo-1', pr));
|
||||
renderMark();
|
||||
await jest.advanceTimersByTimeAsync(100);
|
||||
expect(mockGetMany).toHaveBeenCalledTimes(1);
|
||||
await jest.advanceTimersByTimeAsync(61_000);
|
||||
window.dispatchEvent(new Event('focus'));
|
||||
await jest.advanceTimersByTimeAsync(100);
|
||||
expect(mockGetMany).toHaveBeenCalledTimes(2);
|
||||
} finally {
|
||||
jest.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('does not refresh on focus while its answer is still fresh', async () => {
|
||||
jest.useFakeTimers();
|
||||
try {
|
||||
mockGetMany.mockResolvedValue(answer('convo-1', pr));
|
||||
renderMark();
|
||||
await jest.advanceTimersByTimeAsync(100);
|
||||
window.dispatchEvent(new Event('focus'));
|
||||
await jest.advanceTimersByTimeAsync(100);
|
||||
expect(mockGetMany).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
jest.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('never polls, so a list of rows does not poll GitHub once per row', async () => {
|
||||
jest.useFakeTimers();
|
||||
try {
|
||||
mockGetMany.mockResolvedValue(answer('convo-1', { ...pr, checks: 'running' }));
|
||||
renderMark();
|
||||
await jest.advanceTimersByTimeAsync(100);
|
||||
expect(mockGetMany).toHaveBeenCalledTimes(1);
|
||||
await jest.advanceTimersByTimeAsync(10 * 60_000);
|
||||
expect(mockGetMany).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
jest.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('shares its cache entry with the header, so one conversation is fetched once', async () => {
|
||||
mockGetMany.mockResolvedValue(answer('convo-1', pr));
|
||||
const { client } = renderMark();
|
||||
await screen.findByTestId('convo-pull-request');
|
||||
expect(client.getQueryData(['conversationPullRequest', 'convo-1'])).toEqual({
|
||||
pullRequest: pr,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -1,2 +1,3 @@
|
|||
export { default as PullRequestChip } from './Chip';
|
||||
export { default as usePullRequestMenu } from './menu';
|
||||
export { default as PullRequestRowMark } from './RowMark';
|
||||
|
|
|
|||
|
|
@ -4,7 +4,11 @@ import { Link2 } from 'lucide-react';
|
|||
import { useRecoilValue } from 'recoil';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import { Spinner, useToastContext, useMediaQuery } from '@librechat/client';
|
||||
import { Constants, supportsConversationTitleOwnership } from 'librechat-data-provider';
|
||||
import {
|
||||
Constants,
|
||||
PULL_REQUEST_BATCH_VERSION,
|
||||
supportsConversationTitleOwnership,
|
||||
} from 'librechat-data-provider';
|
||||
import type { TConversation } from 'librechat-data-provider';
|
||||
import type { ConversationDragItem } from './dnd';
|
||||
import {
|
||||
|
|
@ -13,6 +17,7 @@ import {
|
|||
useUpdateConversationMutation,
|
||||
} from '~/data-provider';
|
||||
import { cn, logger, setDocumentTitle, isConversationUnseen, hasRealTitle } from '~/utils';
|
||||
import PullRequestRowMark from '~/components/Chat/PullRequest/RowMark';
|
||||
import { useNavigateToConvo, useLocalize, useShiftKey } from '~/hooks';
|
||||
import ConversationEndpointIcon from './ConversationEndpointIcon';
|
||||
import useDrawerViewport from '~/hooks/Nav/useDrawerViewport';
|
||||
|
|
@ -70,6 +75,13 @@ function Conversation({
|
|||
const sharedLinksEnabled = startupConfig?.sharedLinksEnabled === true;
|
||||
const isSharedBadgeVisible = conversation.isShared === true && sharedLinksEnabled;
|
||||
const projectLabelId = useId();
|
||||
const pullRequestLabelId = useId();
|
||||
/** The mark owns the description text; the row points at it only while it is in the page. */
|
||||
const [pullRequestDescribed, setPullRequestDescribed] = useState(false);
|
||||
const showPullRequest =
|
||||
startupConfig?.pullRequestsEnabled === true &&
|
||||
startupConfig.pullRequestsBatchVersion === PULL_REQUEST_BATCH_VERSION &&
|
||||
!isGenerating;
|
||||
const projectBadgeProjectId = showProjectBadge ? conversation.chatProjectId : undefined;
|
||||
const isUnseen = isConversationUnseen(conversation);
|
||||
const isShiftHeld = useShiftKey();
|
||||
|
|
@ -387,7 +399,14 @@ function Conversation({
|
|||
isSmallScreen={isSmallScreen}
|
||||
localize={localize}
|
||||
keyShortcuts={keyShortcuts}
|
||||
describedBy={projectBadgeProjectId ? projectLabelId : undefined}
|
||||
describedBy={
|
||||
[
|
||||
projectBadgeProjectId ? projectLabelId : null,
|
||||
showPullRequest && pullRequestDescribed ? pullRequestLabelId : null,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' ') || undefined
|
||||
}
|
||||
>
|
||||
{/* Status sits on the avatar so the row's trailing edge stays free for its badges
|
||||
and menu. The ring is 2.125rem around the 1.25rem icon: offset by half the
|
||||
|
|
@ -447,6 +466,19 @@ function Conversation({
|
|||
{/* Only render ConvoOptions when user interacts (hover/focus) or for active conversation */}
|
||||
{actionContent}
|
||||
</div>
|
||||
{/* After the action slot on purpose: that slot grows from zero on hover, and anything before
|
||||
it slides left under the pointer, so the mark would move out from under the cursor that
|
||||
is trying to reach it. The title is the only thing that gives way. */}
|
||||
{showPullRequest && (
|
||||
<span className="flex shrink-0 items-center">
|
||||
<PullRequestRowMark
|
||||
conversationId={conversationId ?? ''}
|
||||
labelId={pullRequestLabelId}
|
||||
onDescribed={setPullRequestDescribed}
|
||||
selected={isActiveConvo || isPopoverActive}
|
||||
/>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,176 @@
|
|||
import React, { useEffect } from 'react';
|
||||
import { DndProvider } from 'react-dnd';
|
||||
import { HTML5Backend } from 'react-dnd-html5-backend';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import type { TConversation } from 'librechat-data-provider';
|
||||
|
||||
const mockStartup: {
|
||||
current: { pullRequestsEnabled?: boolean; pullRequestsBatchVersion?: number };
|
||||
} = {
|
||||
current: { pullRequestsEnabled: true, pullRequestsBatchVersion: 1 },
|
||||
};
|
||||
const mockMarkProps: Array<Record<string, unknown>> = [];
|
||||
/** What the mock mark reports to the row, as the real one does once it has text to show. */
|
||||
const mockMarkState = { described: true };
|
||||
|
||||
jest.mock('@librechat/client', () => ({
|
||||
useMediaQuery: () => false,
|
||||
useRemScale: () => 1,
|
||||
useToastContext: () => ({ showToast: jest.fn() }),
|
||||
Spinner: () => <svg data-testid="status-ring" />,
|
||||
Button: ({ children, ...props }: React.ComponentProps<'button'>) => (
|
||||
<button {...props}>{children}</button>
|
||||
),
|
||||
}));
|
||||
jest.mock('~/hooks', () => ({
|
||||
useLocalize: () => (key: string) => key,
|
||||
useNavigateToConvo: () => ({ navigateToConvo: jest.fn() }),
|
||||
useShiftKey: () => false,
|
||||
}));
|
||||
jest.mock('~/data-provider', () => ({
|
||||
useGetStartupConfig: () => ({ data: mockStartup.current }),
|
||||
useUpdateConversationMutation: () => ({ mutateAsync: jest.fn() }),
|
||||
usePinConversationMutation: () => ({ mutate: jest.fn() }),
|
||||
useProjectName: () => 'Scheduling',
|
||||
}));
|
||||
jest.mock('react-router-dom', () => ({ useParams: () => ({ conversationId: 'convo-1' }) }));
|
||||
jest.mock('recoil', () => ({ useRecoilValue: () => [] }));
|
||||
jest.mock('~/store', () => ({
|
||||
__esModule: true,
|
||||
default: {
|
||||
allConversationsSelector: 'allConversationsSelector',
|
||||
conversationIdByIndex: () => 'conversationIdByIndex',
|
||||
},
|
||||
}));
|
||||
jest.mock('~/utils', () => ({
|
||||
cn: (...classes: unknown[]) => classes.filter(Boolean).join(' '),
|
||||
logger: { error: jest.fn() },
|
||||
setDocumentTitle: jest.fn(),
|
||||
isConversationUnseen: () => false,
|
||||
hasRealTitle: (title: string) => !!title && title !== 'New Chat',
|
||||
}));
|
||||
jest.mock('../ConvoOptions', () => ({ ConvoOptions: () => <div data-testid="convo-options" /> }));
|
||||
jest.mock('../ConversationEndpointIcon', () => ({
|
||||
__esModule: true,
|
||||
default: () => <div data-testid="convo-icon" />,
|
||||
}));
|
||||
jest.mock('../RenameForm', () => ({ __esModule: true, default: () => <form /> }));
|
||||
/** Named with the `mock` prefix so the factory below may reference it, and a real component so
|
||||
* its hook is legal. It reports its description to the row the way the real mark does. */
|
||||
function MockRowMark({
|
||||
labelId,
|
||||
onDescribed,
|
||||
...rest
|
||||
}: Record<string, unknown> & { labelId: string; onDescribed?: (described: boolean) => void }) {
|
||||
mockMarkProps.push({ labelId, ...rest });
|
||||
useEffect(() => {
|
||||
onDescribed?.(mockMarkState.described);
|
||||
return () => onDescribed?.(false);
|
||||
}, [onDescribed]);
|
||||
if (!mockMarkState.described) return null;
|
||||
return (
|
||||
<button type="button" data-testid="convo-pull-request">
|
||||
<span id={labelId} data-testid="mark-description" />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
const mockRowMark = MockRowMark;
|
||||
|
||||
jest.mock('~/components/Chat/PullRequest/RowMark', () => ({
|
||||
__esModule: true,
|
||||
default: (props: Record<string, unknown>) => mockRowMark(props as never),
|
||||
}));
|
||||
|
||||
import Conversation from '../Convo';
|
||||
|
||||
const conversation = {
|
||||
conversationId: 'convo-1',
|
||||
title: 'Tool Approval UI',
|
||||
} as TConversation;
|
||||
|
||||
const renderRow = (props: { isGenerating?: boolean } = {}) =>
|
||||
render(
|
||||
<DndProvider backend={HTML5Backend}>
|
||||
<Conversation
|
||||
conversation={conversation}
|
||||
retainView={jest.fn()}
|
||||
toggleNav={jest.fn()}
|
||||
isGenerating={props.isGenerating}
|
||||
/>
|
||||
</DndProvider>,
|
||||
);
|
||||
|
||||
const rowButton = () => screen.getByRole('button', { name: /^com_ui_conversation_label/ });
|
||||
|
||||
describe('Conversation row pull request', () => {
|
||||
beforeEach(() => {
|
||||
mockMarkProps.length = 0;
|
||||
mockMarkState.described = true;
|
||||
mockStartup.current = { pullRequestsEnabled: true, pullRequestsBatchVersion: 1 };
|
||||
});
|
||||
|
||||
it("keeps the title the conversation's own and puts the pull request beside it, outside the row button", () => {
|
||||
renderRow();
|
||||
expect(screen.getByText('Tool Approval UI')).toBeInTheDocument();
|
||||
const mark = screen.getByTestId('convo-pull-request');
|
||||
expect(rowButton()).not.toContainElement(mark);
|
||||
expect(screen.getByTestId('convo-item')).toContainElement(mark);
|
||||
expect(mark.parentElement?.parentElement).toBe(screen.getByTestId('convo-item'));
|
||||
});
|
||||
|
||||
it('sits after the row menu, which grows on hover, so it does not slide out from under the pointer', () => {
|
||||
renderRow();
|
||||
const row = screen.getByTestId('convo-item');
|
||||
const mark = screen.getByTestId('convo-pull-request');
|
||||
const menuSlot = screen.getByTestId('convo-options').parentElement as HTMLElement;
|
||||
expect(row).toContainElement(menuSlot);
|
||||
expect(menuSlot.compareDocumentPosition(mark) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
expect(row.lastElementChild).toBe(mark.parentElement);
|
||||
});
|
||||
|
||||
it("names the pull request in the row's description so a screen reader hears what the colors say", () => {
|
||||
renderRow();
|
||||
const labelId = String(mockMarkProps[0].labelId);
|
||||
expect(rowButton().getAttribute('aria-describedby')).toContain(labelId);
|
||||
expect(document.getElementById(labelId)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('tells the mark which conversation it is for and that this row is the open one', () => {
|
||||
renderRow();
|
||||
expect(mockMarkProps[0]).toMatchObject({ conversationId: 'convo-1', selected: true });
|
||||
});
|
||||
|
||||
it('reserves no space around the mark, since an absent mark must leave the row unchanged', () => {
|
||||
renderRow();
|
||||
const wrapper = screen.getByTestId('convo-pull-request').parentElement as HTMLElement;
|
||||
expect(wrapper.className).not.toMatch(/\bm[rlxy]?-\d/);
|
||||
expect(wrapper.className).not.toMatch(/\bp[rlxy]?-\d/);
|
||||
});
|
||||
|
||||
it('does not point the row at a description that is not in the page', () => {
|
||||
mockMarkState.described = false;
|
||||
renderRow();
|
||||
expect(screen.queryByTestId('convo-pull-request')).not.toBeInTheDocument();
|
||||
expect(rowButton().getAttribute('aria-describedby')).toBeNull();
|
||||
const ids = (rowButton().getAttribute('aria-describedby') ?? '').split(' ').filter(Boolean);
|
||||
expect(ids.every((id) => document.getElementById(id) != null)).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['not advertised', {}],
|
||||
['advertised off', { pullRequestsEnabled: false }],
|
||||
['advertised without the batch route', { pullRequestsEnabled: true }],
|
||||
])('draws nothing and describes nothing when the feature is %s', (_label, startup) => {
|
||||
mockStartup.current = startup;
|
||||
renderRow();
|
||||
expect(screen.queryByTestId('convo-pull-request')).not.toBeInTheDocument();
|
||||
expect(mockMarkProps).toHaveLength(0);
|
||||
expect(rowButton().getAttribute('aria-describedby')).toBeNull();
|
||||
});
|
||||
|
||||
it('leaves the mark out while the chat runs, so the ring is the only status', () => {
|
||||
renderRow({ isGenerating: true });
|
||||
expect(screen.queryByTestId('convo-pull-request')).not.toBeInTheDocument();
|
||||
expect(screen.getByTestId('status-ring')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
758
client/src/data-provider/PullRequest/batch.test.ts
Normal file
758
client/src/data-provider/PullRequest/batch.test.ts
Normal file
|
|
@ -0,0 +1,758 @@
|
|||
import type { TConversationPullRequest } from 'librechat-data-provider';
|
||||
import { PullRequestBatchError, createBatchFetcher, createPullRequestBatcher } from './batch';
|
||||
|
||||
const pr: TConversationPullRequest = {
|
||||
number: 1,
|
||||
title: 't',
|
||||
url: 'https://github.com/o/r/pull/1',
|
||||
additions: 1,
|
||||
deletions: 0,
|
||||
state: 'open',
|
||||
isDraft: false,
|
||||
mergeable: 'clean',
|
||||
checks: 'passing',
|
||||
};
|
||||
|
||||
describe('createPullRequestBatcher', () => {
|
||||
beforeEach(() => jest.useFakeTimers());
|
||||
afterEach(() => jest.useRealTimers());
|
||||
|
||||
it('asks once for every conversation requested in the same moment', async () => {
|
||||
const fetchMany = jest.fn().mockResolvedValue({
|
||||
results: [
|
||||
{ conversationId: 'a', pullRequest: pr },
|
||||
{ conversationId: 'b', pullRequest: null },
|
||||
],
|
||||
});
|
||||
const { load } = createPullRequestBatcher({ fetchMany });
|
||||
const first = load('a');
|
||||
const second = load('b');
|
||||
await jest.advanceTimersByTimeAsync(50);
|
||||
expect(fetchMany).toHaveBeenCalledTimes(1);
|
||||
expect(fetchMany).toHaveBeenCalledWith(['a', 'b'], expect.any(AbortSignal));
|
||||
await expect(first).resolves.toEqual({ pullRequest: pr });
|
||||
await expect(second).resolves.toEqual({ pullRequest: null });
|
||||
});
|
||||
|
||||
it('shares one entry between callers asking for the same conversation', async () => {
|
||||
const fetchMany = jest
|
||||
.fn()
|
||||
.mockResolvedValue({ results: [{ conversationId: 'a', pullRequest: pr }] });
|
||||
const { load } = createPullRequestBatcher({ fetchMany });
|
||||
const calls = [load('a'), load('a')];
|
||||
await jest.advanceTimersByTimeAsync(50);
|
||||
expect(fetchMany).toHaveBeenCalledWith(['a'], expect.any(AbortSignal));
|
||||
await expect(Promise.all(calls)).resolves.toEqual([{ pullRequest: pr }, { pullRequest: pr }]);
|
||||
});
|
||||
|
||||
it('answers no pull request for a conversation the server left out', async () => {
|
||||
const fetchMany = jest.fn().mockResolvedValue({ results: [] });
|
||||
const { load } = createPullRequestBatcher({ fetchMany });
|
||||
const answer = load('a');
|
||||
await jest.advanceTimersByTimeAsync(50);
|
||||
await expect(answer).resolves.toEqual({ pullRequest: null });
|
||||
});
|
||||
|
||||
it('splits a crowd into requests the server accepts', async () => {
|
||||
const fetchMany = jest.fn(async (ids: string[]) => ({
|
||||
results: ids.map((conversationId) => ({ conversationId, pullRequest: null })),
|
||||
}));
|
||||
const { load } = createPullRequestBatcher({ fetchMany, maxBatch: 2 });
|
||||
const all = ['a', 'b', 'c', 'd', 'e'].map((id) => load(id));
|
||||
await jest.advanceTimersByTimeAsync(50);
|
||||
await Promise.all(all);
|
||||
expect(fetchMany.mock.calls.map(([ids]) => ids)).toEqual([['a', 'b'], ['c', 'd'], ['e']]);
|
||||
});
|
||||
|
||||
describe('requests in flight', () => {
|
||||
/** A server that answers only when told to, so overlap is visible. */
|
||||
const slowServer = () => {
|
||||
let active = 0;
|
||||
let peak = 0;
|
||||
const releases: Array<() => void> = [];
|
||||
const fetchMany = jest.fn(
|
||||
(ids: string[]) =>
|
||||
new Promise<{ results: Array<{ conversationId: string; pullRequest: null }> }>(
|
||||
(resolve) => {
|
||||
active += 1;
|
||||
peak = Math.max(peak, active);
|
||||
releases.push(() => {
|
||||
active -= 1;
|
||||
resolve({
|
||||
results: ids.map((conversationId) => ({ conversationId, pullRequest: null })),
|
||||
});
|
||||
});
|
||||
},
|
||||
),
|
||||
);
|
||||
return { fetchMany, releases, peak: () => peak };
|
||||
};
|
||||
|
||||
it('sends the chunks of a crowd one at a time, so the server limit is not multiplied', async () => {
|
||||
const { fetchMany, releases, peak } = slowServer();
|
||||
const { load } = createPullRequestBatcher({ fetchMany, maxBatch: 2 });
|
||||
const all = ['a', 'b', 'c', 'd', 'e'].map((id) => load(id));
|
||||
await jest.advanceTimersByTimeAsync(50);
|
||||
expect(fetchMany).toHaveBeenCalledTimes(1);
|
||||
releases.shift()?.();
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
expect(fetchMany).toHaveBeenCalledTimes(2);
|
||||
releases.shift()?.();
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
expect(fetchMany).toHaveBeenCalledTimes(3);
|
||||
releases.shift()?.();
|
||||
await Promise.all(all);
|
||||
expect(peak()).toBe(1);
|
||||
expect(fetchMany.mock.calls.map(([ids]) => ids)).toEqual([['a', 'b'], ['c', 'd'], ['e']]);
|
||||
});
|
||||
|
||||
it('does not start a later flush while an earlier request is still out', async () => {
|
||||
const { fetchMany, releases, peak } = slowServer();
|
||||
const { load } = createPullRequestBatcher({ fetchMany });
|
||||
const first = load('a');
|
||||
await jest.advanceTimersByTimeAsync(50);
|
||||
const second = load('b');
|
||||
await jest.advanceTimersByTimeAsync(50);
|
||||
expect(fetchMany).toHaveBeenCalledTimes(1);
|
||||
releases.shift()?.();
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
expect(fetchMany).toHaveBeenCalledTimes(2);
|
||||
releases.shift()?.();
|
||||
await Promise.all([first, second]);
|
||||
expect(peak()).toBe(1);
|
||||
});
|
||||
|
||||
it('moves on when a request never answers, failing only the callers it carried', async () => {
|
||||
const fetchMany = jest
|
||||
.fn()
|
||||
.mockImplementationOnce(() => new Promise(() => undefined))
|
||||
.mockResolvedValue({ results: [{ conversationId: 'b', pullRequest: null }] });
|
||||
const { load } = createPullRequestBatcher({ fetchMany, requestTimeoutMs: 1000 });
|
||||
const hung = load('a').catch((error) => error);
|
||||
await jest.advanceTimersByTimeAsync(50);
|
||||
const later = load('b');
|
||||
await jest.advanceTimersByTimeAsync(50);
|
||||
expect(fetchMany).toHaveBeenCalledTimes(1);
|
||||
await jest.advanceTimersByTimeAsync(1000);
|
||||
const error = await hung;
|
||||
expect(error).toBeInstanceOf(PullRequestBatchError);
|
||||
expect(error.code).toBe('TIMEOUT');
|
||||
await jest.advanceTimersByTimeAsync(50);
|
||||
await expect(later).resolves.toEqual({ pullRequest: null });
|
||||
});
|
||||
|
||||
it('waits longer than the longest server deadline a deployment can configure by default', async () => {
|
||||
const fetchMany = jest
|
||||
.fn()
|
||||
.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise((resolve) =>
|
||||
setTimeout(
|
||||
() => resolve({ results: [{ conversationId: 'a', pullRequest: null }] }),
|
||||
125_000,
|
||||
),
|
||||
),
|
||||
)
|
||||
.mockResolvedValue({ results: [{ conversationId: 'b', pullRequest: null }] });
|
||||
const { load } = createPullRequestBatcher({ fetchMany });
|
||||
const slow = load('a');
|
||||
await jest.advanceTimersByTimeAsync(50);
|
||||
const queued = load('b');
|
||||
await jest.advanceTimersByTimeAsync(124_000);
|
||||
/** A 120 s server batch has not finished at 124 s of waiting, and the next must not have started. */
|
||||
expect(fetchMany).toHaveBeenCalledTimes(1);
|
||||
await jest.advanceTimersByTimeAsync(2_000);
|
||||
await expect(slow).resolves.toEqual({ pullRequest: null });
|
||||
await jest.advanceTimersByTimeAsync(50);
|
||||
await expect(queued).resolves.toEqual({ pullRequest: null });
|
||||
expect(fetchMany).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('does not time out a request that answers in time', async () => {
|
||||
const fetchMany = jest
|
||||
.fn()
|
||||
.mockResolvedValue({ results: [{ conversationId: 'a', pullRequest: null }] });
|
||||
const { load } = createPullRequestBatcher({ fetchMany, requestTimeoutMs: 1000 });
|
||||
const answer = load('a');
|
||||
await jest.advanceTimersByTimeAsync(50);
|
||||
await expect(answer).resolves.toEqual({ pullRequest: null });
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['no body', undefined],
|
||||
['a body without results', {}],
|
||||
['results that are not a list', { results: 'nope' }],
|
||||
['a result that is not an entry', { results: [null] }],
|
||||
])(
|
||||
'fails its callers, and not the queue, when the server answers with %s',
|
||||
async (_label, body) => {
|
||||
const fetchMany = jest
|
||||
.fn()
|
||||
.mockResolvedValueOnce(body)
|
||||
.mockResolvedValue({ results: [{ conversationId: 'b', pullRequest: null }] });
|
||||
const { load } = createPullRequestBatcher({ fetchMany, maxBatch: 1 });
|
||||
const bad = load('a').then(
|
||||
() => 'resolved',
|
||||
() => 'rejected',
|
||||
);
|
||||
const good = load('b');
|
||||
await jest.advanceTimersByTimeAsync(50);
|
||||
await expect(bad).resolves.toBe('rejected');
|
||||
await expect(good).resolves.toEqual({ pullRequest: null });
|
||||
expect(fetchMany).toHaveBeenCalledTimes(2);
|
||||
},
|
||||
);
|
||||
|
||||
it('keeps sending after a request fails', async () => {
|
||||
const fetchMany = jest
|
||||
.fn()
|
||||
.mockRejectedValueOnce(new Error('503'))
|
||||
.mockResolvedValue({ results: [{ conversationId: 'c', pullRequest: null }] });
|
||||
const { load } = createPullRequestBatcher({ fetchMany, maxBatch: 1 });
|
||||
const failed = load('a').catch((error) => error.message);
|
||||
const fine = load('c');
|
||||
await jest.advanceTimersByTimeAsync(50);
|
||||
await expect(failed).resolves.toBe('503');
|
||||
await expect(fine).resolves.toEqual({ pullRequest: null });
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects only the conversation whose entry failed, carrying its code', async () => {
|
||||
const fetchMany = jest.fn().mockResolvedValue({
|
||||
results: [
|
||||
{ conversationId: 'a', error: { code: 'RATE_LIMITED' } },
|
||||
{ conversationId: 'b', pullRequest: pr },
|
||||
],
|
||||
});
|
||||
const { load } = createPullRequestBatcher({ fetchMany });
|
||||
const failed = load('a');
|
||||
const fine = load('b');
|
||||
const outcome = failed.catch((error) => error);
|
||||
await jest.advanceTimersByTimeAsync(50);
|
||||
const error = await outcome;
|
||||
expect(error).toBeInstanceOf(PullRequestBatchError);
|
||||
expect(error.code).toBe('RATE_LIMITED');
|
||||
await expect(fine).resolves.toEqual({ pullRequest: pr });
|
||||
});
|
||||
|
||||
it('rejects every caller of a request that fails outright', async () => {
|
||||
const fetchMany = jest.fn().mockRejectedValue(new Error('503'));
|
||||
const { load } = createPullRequestBatcher({ fetchMany });
|
||||
const outcomes = [load('a'), load('b')].map((promise) =>
|
||||
promise.catch((error) => error.message),
|
||||
);
|
||||
await jest.advanceTimersByTimeAsync(50);
|
||||
await expect(Promise.all(outcomes)).resolves.toEqual(['503', '503']);
|
||||
});
|
||||
|
||||
it('starts a new request for a conversation asked for after the last went out', async () => {
|
||||
const fetchMany = jest.fn(async (ids: string[]) => ({
|
||||
results: ids.map((conversationId) => ({ conversationId, pullRequest: null })),
|
||||
}));
|
||||
const { load } = createPullRequestBatcher({ fetchMany });
|
||||
const first = load('a');
|
||||
await jest.advanceTimersByTimeAsync(50);
|
||||
await first;
|
||||
const second = load('b');
|
||||
await jest.advanceTimersByTimeAsync(50);
|
||||
await second;
|
||||
expect(fetchMany.mock.calls.map(([ids]) => ids)).toEqual([['a'], ['b']]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('createPullRequestBatcher dispose', () => {
|
||||
beforeEach(() => jest.useFakeTimers());
|
||||
afterEach(() => jest.useRealTimers());
|
||||
|
||||
it('rejects ids that have not gone out, and sends nothing for them', async () => {
|
||||
const fetchMany = jest.fn();
|
||||
const batcher = createPullRequestBatcher({ fetchMany });
|
||||
const waiting = batcher.load('a').catch((error) => error);
|
||||
batcher.dispose();
|
||||
await jest.advanceTimersByTimeAsync(100);
|
||||
const error = await waiting;
|
||||
expect(error).toBeInstanceOf(PullRequestBatchError);
|
||||
expect(error.code).toBe('DISPOSED');
|
||||
expect(fetchMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not send chunks that were still queued behind a request in flight', async () => {
|
||||
const releases: Array<() => void> = [];
|
||||
const fetchMany = jest.fn(
|
||||
(ids: string[]) =>
|
||||
new Promise<{ results: Array<{ conversationId: string; pullRequest: null }> }>((resolve) =>
|
||||
releases.push(() =>
|
||||
resolve({
|
||||
results: ids.map((conversationId) => ({ conversationId, pullRequest: null })),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const batcher = createPullRequestBatcher({ fetchMany, maxBatch: 1 });
|
||||
const outcomes = ['a', 'b', 'c'].map((id) =>
|
||||
batcher.load(id).then(
|
||||
() => 'sent',
|
||||
(error) => error.code,
|
||||
),
|
||||
);
|
||||
await jest.advanceTimersByTimeAsync(50);
|
||||
expect(fetchMany).toHaveBeenCalledTimes(1);
|
||||
batcher.dispose();
|
||||
releases.shift()?.();
|
||||
await jest.advanceTimersByTimeAsync(50);
|
||||
/** The request on the wire is aborted with the batcher, and the queued chunks never go out. */
|
||||
expect(await Promise.all(outcomes)).toEqual(['ABORTED', 'DISPOSED', 'DISPOSED']);
|
||||
expect(fetchMany).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('refuses new work once disposed', async () => {
|
||||
const batcher = createPullRequestBatcher({ fetchMany: jest.fn() });
|
||||
batcher.dispose();
|
||||
await expect(batcher.load('a')).rejects.toMatchObject({ code: 'DISPOSED' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('createBatchFetcher', () => {
|
||||
const entry = (conversationId: string) => ({ conversationId, pullRequest: null });
|
||||
const notFound = () => Object.assign(new Error('Not Found'), { response: { status: 404 } });
|
||||
|
||||
it('uses the batch route when the server has it', async () => {
|
||||
const fetchMany = jest.fn().mockResolvedValue({ results: [entry('a')] });
|
||||
const fetchOne = jest.fn();
|
||||
await expect(
|
||||
createBatchFetcher({ fetchMany, fetchOne })(['a'], new AbortController().signal),
|
||||
).resolves.toEqual({
|
||||
results: [entry('a')],
|
||||
});
|
||||
expect(fetchOne).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('asks the single route for each conversation when the replica has no batch route', async () => {
|
||||
const fetchMany = jest.fn().mockRejectedValue(notFound());
|
||||
const fetchOne = jest.fn(async (id: string) => ({ pullRequest: id === 'a' ? pr : null }));
|
||||
const results = await createBatchFetcher({ fetchMany, fetchOne })(
|
||||
['a', 'b'],
|
||||
new AbortController().signal,
|
||||
);
|
||||
expect(results).toEqual({
|
||||
results: [
|
||||
{ conversationId: 'a', pullRequest: pr },
|
||||
{ conversationId: 'b', pullRequest: null },
|
||||
],
|
||||
});
|
||||
expect(fetchOne.mock.calls.map(([id]) => id)).toEqual(['a', 'b']);
|
||||
});
|
||||
|
||||
it("keeps one conversation's failure to itself and reports its code", async () => {
|
||||
const fetchMany = jest.fn().mockRejectedValue(notFound());
|
||||
const fetchOne = jest.fn(async (id: string) => {
|
||||
if (id === 'a') {
|
||||
throw Object.assign(new Error('x'), {
|
||||
response: { status: 503, data: { code: 'RATE_LIMITED' } },
|
||||
});
|
||||
}
|
||||
return { pullRequest: pr };
|
||||
});
|
||||
const { results } = await createBatchFetcher({ fetchMany, fetchOne })(
|
||||
['a', 'b'],
|
||||
new AbortController().signal,
|
||||
);
|
||||
expect(results).toEqual([
|
||||
{ conversationId: 'a', error: { code: 'RATE_LIMITED' } },
|
||||
{ conversationId: 'b', pullRequest: pr },
|
||||
]);
|
||||
});
|
||||
|
||||
it('answers a failure with no code as an upstream error, never with its text', async () => {
|
||||
const fetchMany = jest.fn().mockRejectedValue(notFound());
|
||||
const fetchOne = jest.fn().mockRejectedValue(new Error('secret host name'));
|
||||
const { results } = await createBatchFetcher({ fetchMany, fetchOne })(
|
||||
['a'],
|
||||
new AbortController().signal,
|
||||
);
|
||||
expect(results).toEqual([{ conversationId: 'a', error: { code: 'UPSTREAM_ERROR' } }]);
|
||||
expect(JSON.stringify(results)).not.toContain('secret');
|
||||
});
|
||||
|
||||
it.each([
|
||||
['a server error', { response: { status: 503 } }],
|
||||
['a rate limit', { response: { status: 429 } }],
|
||||
['an expired session', { response: { status: 401 } }],
|
||||
['a network failure', new Error('Network Error')],
|
||||
])(
|
||||
'does not fall back on %s, since the route exists and really failed',
|
||||
async (_label, failure) => {
|
||||
const error = failure instanceof Error ? failure : Object.assign(new Error('x'), failure);
|
||||
const fetchMany = jest.fn().mockRejectedValue(error);
|
||||
const fetchOne = jest.fn();
|
||||
await expect(
|
||||
createBatchFetcher({ fetchMany, fetchOne })(['a'], new AbortController().signal),
|
||||
).rejects.toBe(error);
|
||||
expect(fetchOne).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
const measuredFallback = async (concurrency?: () => number | undefined) => {
|
||||
let active = 0;
|
||||
let peak = 0;
|
||||
const fetchMany = jest.fn().mockRejectedValue(notFound());
|
||||
const fetchOne = jest.fn(async () => {
|
||||
active += 1;
|
||||
peak = Math.max(peak, active);
|
||||
await new Promise((resolve) => setTimeout(resolve, 5));
|
||||
active -= 1;
|
||||
return { pullRequest: null };
|
||||
});
|
||||
jest.useRealTimers();
|
||||
const ids = Array.from({ length: 12 }, (_, i) => `c${i}`);
|
||||
const { results } = await createBatchFetcher({ fetchMany, fetchOne, concurrency })(
|
||||
ids,
|
||||
new AbortController().signal,
|
||||
);
|
||||
expect(results.map((r) => r.conversationId)).toEqual(ids);
|
||||
return peak;
|
||||
};
|
||||
|
||||
it('runs the single-route calls one at a time when the server never said how many it allows', async () => {
|
||||
expect(await measuredFallback()).toBe(1);
|
||||
expect(await measuredFallback(() => undefined)).toBe(1);
|
||||
});
|
||||
|
||||
it('runs the single-route calls at the limit the server advertised, no more', async () => {
|
||||
expect(await measuredFallback(() => 3)).toBe(3);
|
||||
expect(await measuredFallback(() => 1)).toBe(1);
|
||||
});
|
||||
|
||||
it.each([0, -2, 1.5, Number.NaN])(
|
||||
'treats an unusable advertised limit of %s as one',
|
||||
async (limit) => {
|
||||
expect(await measuredFallback(() => limit)).toBe(1);
|
||||
},
|
||||
);
|
||||
|
||||
it('reads the advertised limit when the fallback runs, not when the fetcher was made', async () => {
|
||||
let limit = 1;
|
||||
const fetchMany = jest.fn().mockRejectedValue(notFound());
|
||||
let active = 0;
|
||||
let peak = 0;
|
||||
const fetchOne = jest.fn(async () => {
|
||||
active += 1;
|
||||
peak = Math.max(peak, active);
|
||||
await new Promise((resolve) => setTimeout(resolve, 5));
|
||||
active -= 1;
|
||||
return { pullRequest: null };
|
||||
});
|
||||
const fetcher = createBatchFetcher({ fetchMany, fetchOne, concurrency: () => limit });
|
||||
/** The startup config arrives after the fetcher exists, as it does for the module-level one. */
|
||||
limit = 3;
|
||||
jest.useRealTimers();
|
||||
const ids = Array.from({ length: 9 }, (_, i) => `c${i}`);
|
||||
await fetcher(ids, new AbortController().signal);
|
||||
expect(peak).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the single-route fallback and the queue', () => {
|
||||
const notFound = () => Object.assign(new Error('Not Found'), { response: { status: 404 } });
|
||||
|
||||
/** A single-route call that ends only when released or aborted, like a stalled GET. */
|
||||
const stalledSingleRoute = () => {
|
||||
const calls: string[] = [];
|
||||
const aborted: string[] = [];
|
||||
const fetchOne = jest.fn(
|
||||
(id: string, signal: AbortSignal) =>
|
||||
new Promise<{ pullRequest: null }>((_, reject) => {
|
||||
calls.push(id);
|
||||
signal.addEventListener('abort', () => {
|
||||
aborted.push(id);
|
||||
reject(new Error('aborted'));
|
||||
});
|
||||
}),
|
||||
);
|
||||
return { fetchOne, calls, aborted };
|
||||
};
|
||||
|
||||
it('stops its calls when the signal aborts, and starts no more', async () => {
|
||||
const { fetchOne, calls, aborted } = stalledSingleRoute();
|
||||
const controller = new AbortController();
|
||||
const ids = Array.from({ length: 12 }, (_, i) => `c${i}`);
|
||||
const fetcher = createBatchFetcher({
|
||||
fetchMany: jest.fn().mockRejectedValue(notFound()),
|
||||
fetchOne,
|
||||
concurrency: () => 4,
|
||||
});
|
||||
const settled = fetcher(ids, controller.signal).catch((error) => error);
|
||||
await Promise.resolve();
|
||||
await new Promise((resolve) => setTimeout(resolve, 5));
|
||||
expect(calls).toHaveLength(4);
|
||||
controller.abort();
|
||||
const error = await settled;
|
||||
expect(error).toBeInstanceOf(PullRequestBatchError);
|
||||
expect(error.code).toBe('ABORTED');
|
||||
expect(aborted).toHaveLength(4);
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
expect(calls).toHaveLength(4);
|
||||
});
|
||||
|
||||
it('starts nothing when the signal is already aborted', async () => {
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
const fetchOne = jest.fn();
|
||||
const fetcher = createBatchFetcher({
|
||||
fetchMany: jest.fn().mockRejectedValue(notFound()),
|
||||
fetchOne,
|
||||
});
|
||||
await expect(fetcher(['a', 'b'], controller.signal)).rejects.toMatchObject({ code: 'ABORTED' });
|
||||
expect(fetchOne).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not report an aborted call as one conversation's failure", async () => {
|
||||
const controller = new AbortController();
|
||||
const fetchOne = jest.fn(
|
||||
(_id: string, signal: AbortSignal) =>
|
||||
new Promise<never>((_, reject) =>
|
||||
signal.addEventListener('abort', () => reject(new Error('x'))),
|
||||
),
|
||||
);
|
||||
const fetcher = createBatchFetcher({
|
||||
fetchMany: jest.fn().mockRejectedValue(notFound()),
|
||||
fetchOne,
|
||||
});
|
||||
const settled = fetcher(['a'], controller.signal).catch((error) => error);
|
||||
await new Promise((resolve) => setTimeout(resolve, 5));
|
||||
controller.abort();
|
||||
expect(await settled).toMatchObject({ code: 'ABORTED' });
|
||||
});
|
||||
|
||||
it('aborts a request that runs past its timeout, so its fallback stops before the next request starts', async () => {
|
||||
jest.useFakeTimers();
|
||||
try {
|
||||
const { fetchOne, calls, aborted } = stalledSingleRoute();
|
||||
const fetchMany = jest
|
||||
.fn()
|
||||
.mockRejectedValueOnce(notFound())
|
||||
.mockResolvedValue({ results: [{ conversationId: 'z', pullRequest: null }] });
|
||||
const fetcher = createBatchFetcher({ fetchMany, fetchOne });
|
||||
const batcher = createPullRequestBatcher({
|
||||
fetchMany: fetcher,
|
||||
maxBatch: 1,
|
||||
requestTimeoutMs: 1000,
|
||||
});
|
||||
const first = batcher.load('a').catch((error) => error.code);
|
||||
const second = batcher.load('z');
|
||||
await jest.advanceTimersByTimeAsync(50);
|
||||
expect(calls).toEqual(['a']);
|
||||
expect(fetchMany).toHaveBeenCalledTimes(1);
|
||||
await jest.advanceTimersByTimeAsync(1000);
|
||||
expect(await first).toBe('TIMEOUT');
|
||||
/** The stalled call was aborted before the queue handed the next request its turn. */
|
||||
expect(aborted).toEqual(['a']);
|
||||
await jest.advanceTimersByTimeAsync(50);
|
||||
await expect(second).resolves.toEqual({ pullRequest: null });
|
||||
expect(fetchMany).toHaveBeenCalledTimes(2);
|
||||
} finally {
|
||||
jest.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('aborts the request on the wire when the batcher is disposed', async () => {
|
||||
const { fetchOne, calls, aborted } = stalledSingleRoute();
|
||||
const fetcher = createBatchFetcher({
|
||||
fetchMany: jest.fn().mockRejectedValue(notFound()),
|
||||
fetchOne,
|
||||
});
|
||||
const batcher = createPullRequestBatcher({ fetchMany: fetcher, delayMs: 1 });
|
||||
const outcome = batcher.load('a').catch((error) => error.code);
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
expect(calls).toEqual(['a']);
|
||||
batcher.dispose();
|
||||
expect(aborted).toEqual(['a']);
|
||||
expect(await outcome).toBe('ABORTED');
|
||||
});
|
||||
|
||||
it("hands the batcher's own signal to the fetcher, live while the request runs", async () => {
|
||||
let seen: AbortSignal | undefined;
|
||||
const fetchMany = jest.fn(async (_ids: string[], signal: AbortSignal) => {
|
||||
seen = signal;
|
||||
return { results: [{ conversationId: 'a', pullRequest: null }] };
|
||||
});
|
||||
const batcher = createPullRequestBatcher({ fetchMany, delayMs: 1 });
|
||||
await batcher.load('a');
|
||||
expect(seen).toBeDefined();
|
||||
expect(seen?.aborted).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the batch POST receives the request signal', () => {
|
||||
it("hands the batcher's signal to the primary batch call, and aborts it on timeout", async () => {
|
||||
jest.useFakeTimers();
|
||||
try {
|
||||
const seen: AbortSignal[] = [];
|
||||
const fetchMany = jest.fn(
|
||||
(_ids: string[], signal: AbortSignal) =>
|
||||
new Promise<never>(() => {
|
||||
seen.push(signal);
|
||||
}),
|
||||
);
|
||||
const fetcher = createBatchFetcher({ fetchMany, fetchOne: jest.fn() });
|
||||
const batcher = createPullRequestBatcher({ fetchMany: fetcher, requestTimeoutMs: 1000 });
|
||||
const outcome = batcher.load('a').catch((error) => error.code);
|
||||
await jest.advanceTimersByTimeAsync(50);
|
||||
expect(seen).toHaveLength(1);
|
||||
expect(seen[0].aborted).toBe(false);
|
||||
await jest.advanceTimersByTimeAsync(1000);
|
||||
expect(await outcome).toBe('TIMEOUT');
|
||||
expect(seen[0].aborted).toBe(true);
|
||||
} finally {
|
||||
jest.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('aborts the batch call on the wire when the batcher is disposed', async () => {
|
||||
jest.useFakeTimers();
|
||||
try {
|
||||
let seen: AbortSignal | undefined;
|
||||
const fetchMany = jest.fn(
|
||||
(_ids: string[], signal: AbortSignal) =>
|
||||
new Promise<never>(() => {
|
||||
seen = signal;
|
||||
}),
|
||||
);
|
||||
const batcher = createPullRequestBatcher({
|
||||
fetchMany: createBatchFetcher({ fetchMany, fetchOne: jest.fn() }),
|
||||
});
|
||||
const outcome = batcher.load('a').catch(() => 'rejected');
|
||||
await jest.advanceTimersByTimeAsync(50);
|
||||
batcher.dispose();
|
||||
expect(seen?.aborted).toBe(true);
|
||||
expect(await outcome).toBe('rejected');
|
||||
} finally {
|
||||
jest.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('withdrawing a caller that stopped waiting', () => {
|
||||
beforeEach(() => jest.useFakeTimers());
|
||||
afterEach(() => jest.useRealTimers());
|
||||
|
||||
const answer = (ids: string[]) => ({
|
||||
results: ids.map((conversationId) => ({ conversationId, pullRequest: null })),
|
||||
});
|
||||
|
||||
it('rejects the caller at once', async () => {
|
||||
const fetchMany = jest.fn(async (ids: string[]) => answer(ids));
|
||||
const { load } = createPullRequestBatcher({ fetchMany });
|
||||
const controller = new AbortController();
|
||||
const waiting = load('a', controller.signal).catch((error) => error);
|
||||
controller.abort();
|
||||
const error = await waiting;
|
||||
expect(error).toBeInstanceOf(PullRequestBatchError);
|
||||
expect(error.code).toBe('ABORTED');
|
||||
});
|
||||
|
||||
it('never asks for an id whose only caller left before the request went out', async () => {
|
||||
const fetchMany = jest.fn(async (ids: string[]) => answer(ids));
|
||||
const { load } = createPullRequestBatcher({ fetchMany });
|
||||
const controller = new AbortController();
|
||||
void load('gone', controller.signal).catch(() => undefined);
|
||||
const kept = load('kept');
|
||||
controller.abort();
|
||||
await jest.advanceTimersByTimeAsync(50);
|
||||
await kept;
|
||||
expect(fetchMany).toHaveBeenCalledTimes(1);
|
||||
expect(fetchMany.mock.calls[0][0]).toEqual(['kept']);
|
||||
});
|
||||
|
||||
it('sends nothing at all when every caller left', async () => {
|
||||
const fetchMany = jest.fn(async (ids: string[]) => answer(ids));
|
||||
const { load } = createPullRequestBatcher({ fetchMany });
|
||||
const controller = new AbortController();
|
||||
void load('a', controller.signal).catch(() => undefined);
|
||||
void load('b', controller.signal).catch(() => undefined);
|
||||
controller.abort();
|
||||
await jest.advanceTimersByTimeAsync(100);
|
||||
expect(fetchMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps an id that another caller still waits for', async () => {
|
||||
const fetchMany = jest.fn(async (ids: string[]) => answer(ids));
|
||||
const { load } = createPullRequestBatcher({ fetchMany });
|
||||
const controller = new AbortController();
|
||||
void load('shared', controller.signal).catch(() => undefined);
|
||||
const stayed = load('shared');
|
||||
controller.abort();
|
||||
await jest.advanceTimersByTimeAsync(50);
|
||||
await expect(stayed).resolves.toEqual({ pullRequest: null });
|
||||
expect(fetchMany.mock.calls[0][0]).toEqual(['shared']);
|
||||
});
|
||||
|
||||
it('skips a queued request nobody waits for any more, so the next one is not held behind it', async () => {
|
||||
const releases: Array<() => void> = [];
|
||||
const fetchMany = jest.fn(
|
||||
(ids: string[]) =>
|
||||
new Promise<ReturnType<typeof answer>>((resolve) => {
|
||||
releases.push(() => resolve(answer(ids)));
|
||||
}),
|
||||
);
|
||||
const { load } = createPullRequestBatcher({ fetchMany, maxBatch: 1 });
|
||||
const first = load('first');
|
||||
const controller = new AbortController();
|
||||
void load('queued', controller.signal).catch(() => undefined);
|
||||
const last = load('last');
|
||||
await jest.advanceTimersByTimeAsync(50);
|
||||
expect(fetchMany).toHaveBeenCalledTimes(1);
|
||||
controller.abort();
|
||||
releases.shift()?.();
|
||||
await first;
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
expect(fetchMany.mock.calls.map(([ids]) => ids)).toEqual([['first'], ['last']]);
|
||||
releases.shift()?.();
|
||||
await last;
|
||||
});
|
||||
|
||||
it('aborts the request on the wire once nobody waits for it', async () => {
|
||||
let seen: AbortSignal | undefined;
|
||||
const fetchMany = jest.fn(
|
||||
(_ids: string[], signal: AbortSignal) =>
|
||||
new Promise<never>(() => {
|
||||
seen = signal;
|
||||
}),
|
||||
);
|
||||
const { load } = createPullRequestBatcher({ fetchMany });
|
||||
const controller = new AbortController();
|
||||
void load('a', controller.signal).catch(() => undefined);
|
||||
await jest.advanceTimersByTimeAsync(50);
|
||||
expect(seen?.aborted).toBe(false);
|
||||
controller.abort();
|
||||
expect(seen?.aborted).toBe(true);
|
||||
});
|
||||
|
||||
it('leaves the request on the wire running while another caller still waits for it', async () => {
|
||||
let seen: AbortSignal | undefined;
|
||||
const fetchMany = jest.fn(
|
||||
(_ids: string[], signal: AbortSignal) =>
|
||||
new Promise<never>(() => {
|
||||
seen = signal;
|
||||
}),
|
||||
);
|
||||
const { load } = createPullRequestBatcher({ fetchMany });
|
||||
const controller = new AbortController();
|
||||
void load('a', controller.signal).catch(() => undefined);
|
||||
void load('b').catch(() => undefined);
|
||||
await jest.advanceTimersByTimeAsync(50);
|
||||
controller.abort();
|
||||
expect(seen?.aborted).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects a caller whose signal had already aborted, without queueing it', async () => {
|
||||
const fetchMany = jest.fn(async (ids: string[]) => answer(ids));
|
||||
const { load } = createPullRequestBatcher({ fetchMany });
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
await expect(load('a', controller.signal)).rejects.toMatchObject({ code: 'ABORTED' });
|
||||
await jest.advanceTimersByTimeAsync(100);
|
||||
expect(fetchMany).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
300
client/src/data-provider/PullRequest/batch.ts
Normal file
300
client/src/data-provider/PullRequest/batch.ts
Normal file
|
|
@ -0,0 +1,300 @@
|
|||
import {
|
||||
PULL_REQUEST_BATCH_MAX,
|
||||
PULL_REQUEST_BATCH_TIMEOUT_MAX_SECONDS,
|
||||
} from 'librechat-data-provider';
|
||||
import type {
|
||||
TConversationPullRequestResponse,
|
||||
TConversationPullRequestsResponse,
|
||||
} from 'librechat-data-provider';
|
||||
|
||||
/** A failed entry keeps its stable server code, so a caller can tell a rate limit from an outage. */
|
||||
export class PullRequestBatchError extends Error {
|
||||
constructor(public readonly code: string) {
|
||||
super(`Pull request lookup failed: ${code}`);
|
||||
this.name = 'PullRequestBatchError';
|
||||
}
|
||||
}
|
||||
|
||||
type Waiter = {
|
||||
resolve: (value: TConversationPullRequestResponse) => void;
|
||||
reject: (reason: unknown) => void;
|
||||
/** Set when its caller stopped waiting; nothing is sent, or kept running, only for such waiters. */
|
||||
cancelled?: boolean;
|
||||
};
|
||||
|
||||
/** A request that has been queued or sent and not yet settled. */
|
||||
type Dispatch = { waiters: Map<string, Waiter[]>; controller?: AbortController };
|
||||
|
||||
const hasLiveWaiter = (list: Waiter[] | undefined): boolean =>
|
||||
list?.some((waiter) => !waiter.cancelled) === true;
|
||||
|
||||
type BatcherOptions = {
|
||||
/**
|
||||
* `signal` aborts when the request has run out of time or the batcher was disposed. A fetcher
|
||||
* that starts work of its own must stop it on abort: the queue moves on the moment the request
|
||||
* is settled, so work left running would overlap the next request.
|
||||
*/
|
||||
fetchMany: (
|
||||
conversationIds: string[],
|
||||
signal: AbortSignal,
|
||||
) => Promise<TConversationPullRequestsResponse>;
|
||||
/** How long to gather more ids before asking, so rows mounted together share one request. */
|
||||
delayMs?: number;
|
||||
/** Ids per request; the server refuses more than its own bound. */
|
||||
maxBatch?: number;
|
||||
/**
|
||||
* Longest a request may hold the queue. Requests go out one at a time, so one that never
|
||||
* answers would otherwise stop every later one. It defaults to just past the longest deadline a
|
||||
* deployment may configure for the server's own batch, so the server always answers first and
|
||||
* the next request never starts while the previous one's lookups are still running.
|
||||
*/
|
||||
requestTimeoutMs?: number;
|
||||
};
|
||||
|
||||
const DEFAULT_DELAY_MS = 30;
|
||||
const DEFAULT_REQUEST_TIMEOUT_MS = (PULL_REQUEST_BATCH_TIMEOUT_MAX_SECONDS + 10) * 1000;
|
||||
|
||||
/**
|
||||
* Collects the conversation ids asked for within a short window and fetches them in one request.
|
||||
* Each caller gets its own conversation's answer, and callers asking for the same conversation
|
||||
* share one entry. A request that fails rejects only the callers it carried.
|
||||
*/
|
||||
export function createPullRequestBatcher({
|
||||
fetchMany,
|
||||
delayMs = DEFAULT_DELAY_MS,
|
||||
maxBatch = PULL_REQUEST_BATCH_MAX,
|
||||
requestTimeoutMs = DEFAULT_REQUEST_TIMEOUT_MS,
|
||||
}: BatcherOptions) {
|
||||
const pending = new Map<string, Waiter[]>();
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
let disposed = false;
|
||||
|
||||
/**
|
||||
* Requests go out one at a time. Each request lets the server run its own number of lookups at
|
||||
* once, so requests in flight together would multiply the limit the operator configured: a long
|
||||
* pinned list, or a second flush while one is still out, would otherwise put several times that
|
||||
* many lookups on GitHub at once. The tail never rejects, so one failed request cannot stall
|
||||
* the ones queued behind it.
|
||||
*/
|
||||
let tail: Promise<void> = Promise.resolve();
|
||||
/** Aborts whatever request is on the wire, so disposal does not leave its work running. */
|
||||
let active: AbortController | undefined;
|
||||
/** Requests queued or on the wire, so a cancel can tell when one has nobody left waiting. */
|
||||
const dispatches = new Set<Dispatch>();
|
||||
|
||||
const send = (dispatch: Dispatch): Promise<void> => {
|
||||
const { waiters } = dispatch;
|
||||
/** Ids nobody waits for any more (their rows unmounted while queued) are never asked for. */
|
||||
const ids = [...waiters.keys()].filter((id) => hasLiveWaiter(waiters.get(id)));
|
||||
if (!disposed && ids.length === 0) {
|
||||
dispatches.delete(dispatch);
|
||||
return Promise.resolve();
|
||||
}
|
||||
/** Work that was still waiting its turn when the batcher was disposed never goes out. */
|
||||
if (disposed) {
|
||||
for (const list of waiters.values()) {
|
||||
list.forEach((waiter) => waiter.reject(new PullRequestBatchError('DISPOSED')));
|
||||
}
|
||||
return Promise.resolve();
|
||||
}
|
||||
const settle = ({ results }: TConversationPullRequestsResponse) => {
|
||||
const byId = new Map(results.map((entry) => [entry.conversationId, entry]));
|
||||
for (const [id, list] of waiters) {
|
||||
const entry = byId.get(id);
|
||||
for (const waiter of list) {
|
||||
if (entry != null && 'error' in entry) {
|
||||
waiter.reject(new PullRequestBatchError(entry.error.code));
|
||||
} else {
|
||||
waiter.resolve({ pullRequest: entry?.pullRequest ?? null });
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
const fail = (error: unknown) => {
|
||||
for (const list of waiters.values()) list.forEach((waiter) => waiter.reject(error));
|
||||
};
|
||||
const controller = new AbortController();
|
||||
dispatch.controller = controller;
|
||||
active = controller;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
/**
|
||||
* Settles the request on its timeout, and on an abort from disposal, so callers never wait on
|
||||
* a fetcher that ignores its signal. The timeout aborts first, so the code it reports stays
|
||||
* `TIMEOUT` and the abort listener only ever fires for disposal.
|
||||
*/
|
||||
const timedOut = new Promise<never>((_, reject) => {
|
||||
timer = setTimeout(() => {
|
||||
reject(new PullRequestBatchError('TIMEOUT'));
|
||||
controller.abort();
|
||||
}, requestTimeoutMs);
|
||||
controller.signal.addEventListener('abort', () =>
|
||||
reject(new PullRequestBatchError('ABORTED')),
|
||||
);
|
||||
});
|
||||
/**
|
||||
* `settle` is inside the guarded chain: a response that is not the shape it should be would
|
||||
* otherwise throw out of it, leave these callers waiting forever and, because the queue chains
|
||||
* on this promise, stop every later request. Anything that goes wrong here fails the callers
|
||||
* this request carried and nothing else.
|
||||
*/
|
||||
return Promise.race([fetchMany(ids, controller.signal), timedOut])
|
||||
.then(settle)
|
||||
.catch(fail)
|
||||
.finally(() => {
|
||||
clearTimeout(timer);
|
||||
dispatches.delete(dispatch);
|
||||
if (active === controller) active = undefined;
|
||||
});
|
||||
};
|
||||
|
||||
const flush = () => {
|
||||
timer = undefined;
|
||||
const ids = [...pending.keys()];
|
||||
for (let start = 0; start < ids.length; start += maxBatch) {
|
||||
const chunk = ids.slice(start, start + maxBatch);
|
||||
const waiters = new Map<string, Waiter[]>();
|
||||
for (const id of chunk) {
|
||||
waiters.set(id, pending.get(id) ?? []);
|
||||
pending.delete(id);
|
||||
}
|
||||
const dispatch: Dispatch = { waiters };
|
||||
dispatches.add(dispatch);
|
||||
tail = tail.then(() => send(dispatch));
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
/**
|
||||
* Ends this batcher's life, for the identity it was made for. What has not gone out yet is
|
||||
* rejected instead of being sent under whoever is signed in next, and nothing queued behind a
|
||||
* request still in flight waits on it for the next session. A request already on the wire
|
||||
* finishes on its own.
|
||||
*/
|
||||
dispose(): void {
|
||||
disposed = true;
|
||||
active?.abort();
|
||||
clearTimeout(timer);
|
||||
timer = undefined;
|
||||
for (const list of pending.values()) {
|
||||
list.forEach((waiter) => waiter.reject(new PullRequestBatchError('DISPOSED')));
|
||||
}
|
||||
pending.clear();
|
||||
},
|
||||
/**
|
||||
* `signal` withdraws this caller: it is rejected at once, its id leaves the queue if it has not
|
||||
* gone out, and a request nobody is waiting for any more is not started, or is aborted if it
|
||||
* is already on the wire, so rows that scrolled away never hold up the ones now visible.
|
||||
*/
|
||||
load(conversationId: string, signal?: AbortSignal): Promise<TConversationPullRequestResponse> {
|
||||
if (disposed) return Promise.reject(new PullRequestBatchError('DISPOSED'));
|
||||
if (signal?.aborted) return Promise.reject(new PullRequestBatchError('ABORTED'));
|
||||
return new Promise((resolve, reject) => {
|
||||
const waiter: Waiter = { resolve, reject };
|
||||
const waiters = pending.get(conversationId) ?? [];
|
||||
waiters.push(waiter);
|
||||
pending.set(conversationId, waiters);
|
||||
timer ??= setTimeout(flush, delayMs);
|
||||
signal?.addEventListener(
|
||||
'abort',
|
||||
() => {
|
||||
waiter.cancelled = true;
|
||||
reject(new PullRequestBatchError('ABORTED'));
|
||||
const queued = pending.get(conversationId);
|
||||
if (queued != null) {
|
||||
const rest = queued.filter((candidate) => candidate !== waiter);
|
||||
if (rest.length > 0) pending.set(conversationId, rest);
|
||||
else pending.delete(conversationId);
|
||||
if (pending.size === 0) {
|
||||
clearTimeout(timer);
|
||||
timer = undefined;
|
||||
}
|
||||
}
|
||||
for (const dispatch of dispatches) {
|
||||
const ids = [...dispatch.waiters.values()];
|
||||
if (ids.every((list) => !hasLiveWaiter(list))) dispatch.controller?.abort();
|
||||
}
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** An unknown or unusable limit is one call at a time, never more than the operator allowed. */
|
||||
const usableConcurrency = (value: number | undefined): number =>
|
||||
value != null && Number.isInteger(value) && value >= 1 ? value : 1;
|
||||
|
||||
const statusOf = (error: unknown): number | undefined => {
|
||||
if (error == null || typeof error !== 'object') return undefined;
|
||||
const candidate = error as { status?: number; response?: { status?: number } };
|
||||
return candidate.response?.status ?? candidate.status;
|
||||
};
|
||||
|
||||
const codeOf = (error: unknown): string => {
|
||||
const code = (error as { response?: { data?: { code?: unknown } } } | null)?.response?.data?.code;
|
||||
return typeof code === 'string' ? code : 'UPSTREAM_ERROR';
|
||||
};
|
||||
|
||||
/**
|
||||
* Asks the batch route, and when the server that answered does not have it (a replica that has
|
||||
* not been upgraded yet answers 404, whatever the startup config of another replica advertised),
|
||||
* asks the single route for each conversation instead, at the limit the server advertised (one at
|
||||
* a time when it did not say), since the single route has no limiter. Anything but a 404 is a
|
||||
* real failure and is passed on untouched.
|
||||
*/
|
||||
export function createBatchFetcher({
|
||||
fetchMany,
|
||||
fetchOne,
|
||||
concurrency,
|
||||
}: {
|
||||
/** The limit the server advertised, read when the fallback runs; one call at a time without it. */
|
||||
concurrency?: () => number | undefined;
|
||||
fetchMany: (
|
||||
conversationIds: string[],
|
||||
signal: AbortSignal,
|
||||
) => Promise<TConversationPullRequestsResponse>;
|
||||
fetchOne: (
|
||||
conversationId: string,
|
||||
signal: AbortSignal,
|
||||
) => Promise<TConversationPullRequestResponse>;
|
||||
}) {
|
||||
return async (
|
||||
conversationIds: string[],
|
||||
signal: AbortSignal,
|
||||
): Promise<TConversationPullRequestsResponse> => {
|
||||
try {
|
||||
return await fetchMany(conversationIds, signal);
|
||||
} catch (error) {
|
||||
if (statusOf(error) !== 404) throw error;
|
||||
}
|
||||
const results: TConversationPullRequestsResponse['results'] = new Array(conversationIds.length);
|
||||
let next = 0;
|
||||
/**
|
||||
* The fallback is many requests, and the batcher moves on the moment this one is settled, so
|
||||
* it stops itself: once the signal aborts no worker starts another call, and the call each
|
||||
* has in flight is aborted with it, so nothing carries on beside the next request.
|
||||
*/
|
||||
const worker = async (): Promise<void> => {
|
||||
for (let index = next++; index < conversationIds.length; index = next++) {
|
||||
if (signal.aborted) return;
|
||||
const conversationId = conversationIds[index];
|
||||
try {
|
||||
const { pullRequest } = await fetchOne(conversationId, signal);
|
||||
results[index] = { conversationId, pullRequest };
|
||||
} catch (error) {
|
||||
/** After an abort the whole fetch throws below, so a result written here is never read. */
|
||||
results[index] = { conversationId, error: { code: codeOf(error) } };
|
||||
}
|
||||
}
|
||||
};
|
||||
await Promise.all(
|
||||
Array.from(
|
||||
{ length: Math.min(usableConcurrency(concurrency?.()), conversationIds.length) },
|
||||
worker,
|
||||
),
|
||||
);
|
||||
if (signal.aborted) throw new PullRequestBatchError('ABORTED');
|
||||
return { results };
|
||||
};
|
||||
}
|
||||
|
|
@ -1 +1,2 @@
|
|||
export * from './queries';
|
||||
export * from './batch';
|
||||
|
|
|
|||
|
|
@ -1,11 +1,20 @@
|
|||
import React from 'react';
|
||||
import { renderHook, waitFor } from '@testing-library/react';
|
||||
import { RecoilRoot } from 'recoil';
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import type { TConversationPullRequest } from 'librechat-data-provider';
|
||||
import { pullRequestRefetchInterval, useConversationPullRequestQuery } from './queries';
|
||||
import type { TStartupConfig } from 'librechat-data-provider';
|
||||
import {
|
||||
endPullRequestSession,
|
||||
pullRequestRefetchInterval,
|
||||
useRowPullRequestQuery,
|
||||
useConversationPullRequestQuery,
|
||||
} from './queries';
|
||||
import store from '~/store';
|
||||
|
||||
const mockGet = jest.fn();
|
||||
const mockStartup: { current: { pullRequestsEnabled?: boolean } | undefined } = {
|
||||
const mockGetMany = jest.fn();
|
||||
const mockStartup: { current: Partial<TStartupConfig> | undefined } = {
|
||||
current: { pullRequestsEnabled: true },
|
||||
};
|
||||
|
||||
|
|
@ -20,6 +29,7 @@ jest.mock('librechat-data-provider', () => {
|
|||
dataService: {
|
||||
...actual.dataService,
|
||||
getConversationPullRequest: (...args: unknown[]) => mockGet(...args),
|
||||
getConversationPullRequests: (...args: unknown[]) => mockGetMany(...args),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
|
@ -116,3 +126,134 @@ describe('useConversationPullRequestQuery', () => {
|
|||
expect(mockGet).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('useRowPullRequestQuery', () => {
|
||||
const rowStartup = {
|
||||
pullRequestsEnabled: true,
|
||||
pullRequestsBatchVersion: 1,
|
||||
pullRequestsMaxConcurrentLookups: 2,
|
||||
} as const;
|
||||
const answerFor = (ids: string[]) => ({
|
||||
results: ids.map((conversationId) => ({ conversationId, pullRequest: pr })),
|
||||
});
|
||||
|
||||
const wrapRows = (userId = 'user-1') => {
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
const Wrapper = ({ children }: { children: React.ReactNode }) => (
|
||||
<QueryClientProvider client={client}>
|
||||
<RecoilRoot initializeState={({ set }) => set(store.user, { id: userId } as never)}>
|
||||
{children}
|
||||
</RecoilRoot>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
return { Wrapper, client };
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
endPullRequestSession();
|
||||
mockGet.mockReset().mockResolvedValue({ pullRequest: null });
|
||||
mockGetMany.mockReset().mockImplementation(async (ids: string[]) => answerFor(ids));
|
||||
mockStartup.current = { ...rowStartup };
|
||||
});
|
||||
afterEach(() => endPullRequestSession());
|
||||
|
||||
it('asks the batch route once for rows mounted together', async () => {
|
||||
const { Wrapper } = wrapRows();
|
||||
const a = renderHook(() => useRowPullRequestQuery('a'), { wrapper: Wrapper });
|
||||
const b = renderHook(() => useRowPullRequestQuery('b'), { wrapper: Wrapper });
|
||||
await waitFor(() => expect(a.result.current.data).toEqual({ pullRequest: pr }));
|
||||
await waitFor(() => expect(b.result.current.data).toEqual({ pullRequest: pr }));
|
||||
expect(mockGetMany).toHaveBeenCalledTimes(1);
|
||||
expect(mockGetMany.mock.calls[0][0]).toEqual(['a', 'b']);
|
||||
});
|
||||
|
||||
it('does not ask for a row that unmounted before its request went out', async () => {
|
||||
const { Wrapper } = wrapRows();
|
||||
const gone = renderHook(() => useRowPullRequestQuery('gone'), { wrapper: Wrapper });
|
||||
const kept = renderHook(() => useRowPullRequestQuery('kept'), { wrapper: Wrapper });
|
||||
gone.unmount();
|
||||
await waitFor(() => expect(kept.result.current.data).toEqual({ pullRequest: pr }));
|
||||
expect(mockGetMany).toHaveBeenCalledTimes(1);
|
||||
expect(mockGetMany.mock.calls[0][0]).toEqual(['kept']);
|
||||
});
|
||||
|
||||
it('aborts a request on the wire once the last row waiting for it unmounts', async () => {
|
||||
let seen: AbortSignal | undefined;
|
||||
mockGetMany.mockReset().mockImplementation(
|
||||
(_ids: string[], options?: { signal?: AbortSignal }) =>
|
||||
new Promise(() => {
|
||||
seen = options?.signal;
|
||||
}),
|
||||
);
|
||||
const { Wrapper } = wrapRows();
|
||||
const row = renderHook(() => useRowPullRequestQuery('a'), { wrapper: Wrapper });
|
||||
await waitFor(() => expect(seen).toBeDefined());
|
||||
expect(seen?.aborted).toBe(false);
|
||||
row.unmount();
|
||||
await waitFor(() => expect(seen?.aborted).toBe(true));
|
||||
});
|
||||
|
||||
it('starts a fresh queue after the session ends, even for the same account', async () => {
|
||||
const stalled: Array<AbortSignal | undefined> = [];
|
||||
mockGetMany
|
||||
.mockReset()
|
||||
.mockImplementationOnce(
|
||||
(_ids: string[], options?: { signal?: AbortSignal }) =>
|
||||
new Promise(() => {
|
||||
stalled.push(options?.signal);
|
||||
}),
|
||||
)
|
||||
.mockImplementation(async (ids: string[]) => answerFor(ids));
|
||||
const first = wrapRows();
|
||||
renderHook(() => useRowPullRequestQuery('a'), { wrapper: first.Wrapper });
|
||||
await waitFor(() => expect(stalled).toHaveLength(1));
|
||||
act(() => endPullRequestSession());
|
||||
expect(stalled[0]?.aborted).toBe(true);
|
||||
const second = wrapRows();
|
||||
const row = renderHook(() => useRowPullRequestQuery('b'), { wrapper: second.Wrapper });
|
||||
await waitFor(() => expect(row.result.current.data).toEqual({ pullRequest: pr }));
|
||||
expect(mockGetMany.mock.calls.at(-1)?.[0]).toEqual(['b']);
|
||||
});
|
||||
|
||||
it('falls back to the single route no faster than the limit the server advertised', async () => {
|
||||
const notFound = Object.assign(new Error('Not Found'), { response: { status: 404 } });
|
||||
mockGetMany.mockReset().mockRejectedValue(notFound);
|
||||
let active = 0;
|
||||
let peak = 0;
|
||||
mockGet.mockReset().mockImplementation(async () => {
|
||||
active += 1;
|
||||
peak = Math.max(peak, active);
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
active -= 1;
|
||||
return { pullRequest: null };
|
||||
});
|
||||
const { Wrapper } = wrapRows();
|
||||
const rows = ['a', 'b', 'c', 'd', 'e', 'f'].map((id) =>
|
||||
renderHook(() => useRowPullRequestQuery(id), { wrapper: Wrapper }),
|
||||
);
|
||||
await waitFor(() => rows.forEach((row) => expect(row.result.current.isSuccess).toBe(true)));
|
||||
expect(mockGet).toHaveBeenCalledTimes(6);
|
||||
expect(peak).toBe(2);
|
||||
});
|
||||
|
||||
it('falls back one call at a time when the server advertised no limit', async () => {
|
||||
mockStartup.current = { pullRequestsEnabled: true, pullRequestsBatchVersion: 1 };
|
||||
const notFound = Object.assign(new Error('Not Found'), { response: { status: 404 } });
|
||||
mockGetMany.mockReset().mockRejectedValue(notFound);
|
||||
let active = 0;
|
||||
let peak = 0;
|
||||
mockGet.mockReset().mockImplementation(async () => {
|
||||
active += 1;
|
||||
peak = Math.max(peak, active);
|
||||
await new Promise((resolve) => setTimeout(resolve, 5));
|
||||
active -= 1;
|
||||
return { pullRequest: null };
|
||||
});
|
||||
const { Wrapper } = wrapRows();
|
||||
const rows = ['a', 'b', 'c'].map((id) =>
|
||||
renderHook(() => useRowPullRequestQuery(id), { wrapper: Wrapper }),
|
||||
);
|
||||
await waitFor(() => rows.forEach((row) => expect(row.result.current.isSuccess).toBe(true)));
|
||||
expect(peak).toBe(1);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,8 +1,16 @@
|
|||
import { useRecoilValue } from 'recoil';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Constants, QueryKeys, dataService } from 'librechat-data-provider';
|
||||
import {
|
||||
Constants,
|
||||
QueryKeys,
|
||||
dataService,
|
||||
PULL_REQUEST_BATCH_VERSION,
|
||||
} from 'librechat-data-provider';
|
||||
import type { TConversationPullRequestResponse } from 'librechat-data-provider';
|
||||
import type { UseQueryOptions } from '@tanstack/react-query';
|
||||
import { createBatchFetcher, createPullRequestBatcher } from './batch';
|
||||
import { useGetStartupConfig } from '../Endpoints';
|
||||
import store from '~/store';
|
||||
|
||||
const SETTLED_REFRESH_MS = 60_000;
|
||||
/** Checks and conflict state change while a pull request is being worked on. */
|
||||
|
|
@ -23,6 +31,11 @@ export const pullRequestRefetchInterval = (
|
|||
return pr.mergeable === 'unknown' ? ACTIVE_REFRESH_MS : SETTLED_REFRESH_MS;
|
||||
};
|
||||
|
||||
const isSavedConversation = (conversationId: string) =>
|
||||
conversationId !== '' &&
|
||||
conversationId !== Constants.NEW_CONVO &&
|
||||
conversationId !== Constants.PENDING_CONVO;
|
||||
|
||||
/**
|
||||
* Asks only when the deployment advertises the feature and the conversation is a saved one, so a
|
||||
* default installation never calls the endpoint. The server answers no pull request for a chat
|
||||
|
|
@ -37,11 +50,7 @@ export const useConversationPullRequestQuery = (
|
|||
[QueryKeys.conversationPullRequest, conversationId],
|
||||
() => dataService.getConversationPullRequest(conversationId),
|
||||
{
|
||||
enabled:
|
||||
startupConfig?.pullRequestsEnabled === true &&
|
||||
conversationId !== '' &&
|
||||
conversationId !== Constants.NEW_CONVO &&
|
||||
conversationId !== Constants.PENDING_CONVO,
|
||||
enabled: startupConfig?.pullRequestsEnabled === true && isSavedConversation(conversationId),
|
||||
staleTime: 15_000,
|
||||
retry: false,
|
||||
refetchOnWindowFocus: true,
|
||||
|
|
@ -51,3 +60,71 @@ export const useConversationPullRequestQuery = (
|
|||
},
|
||||
);
|
||||
};
|
||||
|
||||
/** What the server last advertised, for a fallback that has no batch limiter to lean on. */
|
||||
let advertisedConcurrency: number | undefined;
|
||||
|
||||
const fetchRows = createBatchFetcher({
|
||||
fetchMany: (conversationIds, signal) =>
|
||||
dataService.getConversationPullRequests(conversationIds, { signal }),
|
||||
fetchOne: (conversationId, signal) =>
|
||||
dataService.getConversationPullRequest(conversationId, { signal }),
|
||||
concurrency: () => advertisedConcurrency,
|
||||
});
|
||||
|
||||
type RowBatcher = ReturnType<typeof createPullRequestBatcher>;
|
||||
let rowBatcher: { userId: string; batcher: RowBatcher } | undefined;
|
||||
|
||||
/**
|
||||
* The batcher for the signed-in user: every sidebar row mounted in the same moment shares one
|
||||
* request. It belongs to one identity, so when the user changes the old one is disposed, and ids
|
||||
* it still held are neither sent under the next account's authorization nor made to wait ahead
|
||||
* of that account's own rows.
|
||||
*/
|
||||
const batcherFor = (userId: string): RowBatcher => {
|
||||
if (rowBatcher?.userId === userId) return rowBatcher.batcher;
|
||||
rowBatcher?.batcher.dispose();
|
||||
const batcher = createPullRequestBatcher({ fetchMany: fetchRows });
|
||||
rowBatcher = { userId, batcher };
|
||||
return batcher;
|
||||
};
|
||||
|
||||
/**
|
||||
* Ends the row queue 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.
|
||||
*/
|
||||
export const endPullRequestSession = (): void => {
|
||||
rowBatcher?.batcher.dispose();
|
||||
rowBatcher = undefined;
|
||||
};
|
||||
|
||||
/**
|
||||
* The pull request of a sidebar row. It shares its cache entry with the header's query, so the
|
||||
* open conversation is never fetched twice, but it never polls: a list of rows would otherwise
|
||||
* poll GitHub once per row. It refreshes when the window regains focus and a row's answer is
|
||||
* older than a minute; every mounted row asks in the same moment, so the batcher turns that
|
||||
* into one request for the whole list rather than one per row.
|
||||
*/
|
||||
export const useRowPullRequestQuery = (conversationId: string) => {
|
||||
const { data: startupConfig } = useGetStartupConfig();
|
||||
const userId = useRecoilValue(store.user)?.id ?? '';
|
||||
return useQuery<TConversationPullRequestResponse>(
|
||||
[QueryKeys.conversationPullRequest, conversationId],
|
||||
({ signal }) => {
|
||||
advertisedConcurrency = startupConfig?.pullRequestsMaxConcurrentLookups;
|
||||
return batcherFor(userId).load(conversationId, signal);
|
||||
},
|
||||
{
|
||||
/** The batch route is newer than the flag: ask only a server that says it has it. */
|
||||
enabled:
|
||||
startupConfig?.pullRequestsEnabled === true &&
|
||||
startupConfig.pullRequestsBatchVersion === PULL_REQUEST_BATCH_VERSION &&
|
||||
userId !== '' &&
|
||||
isSavedConversation(conversationId),
|
||||
staleTime: SETTLED_REFRESH_MS,
|
||||
retry: false,
|
||||
refetchOnWindowFocus: true,
|
||||
},
|
||||
);
|
||||
};
|
||||
|
|
|
|||
|
|
@ -37,6 +37,7 @@ import {
|
|||
import {
|
||||
useGetRole,
|
||||
useGetUserQuery,
|
||||
endPullRequestSession,
|
||||
useLoginUserMutation,
|
||||
useLogoutUserMutation,
|
||||
useRefreshTokenMutation,
|
||||
|
|
@ -64,6 +65,7 @@ const endSessionClientState = (): void => {
|
|||
getDefaultStore().set(resetFacetsAtom);
|
||||
clearRetainedFileDeletions();
|
||||
clearComposerDraftStorage();
|
||||
endPullRequestSession();
|
||||
};
|
||||
/**
|
||||
* Only recognized codes override the HTTP status used by the login error translation.
|
||||
|
|
|
|||
|
|
@ -52,6 +52,7 @@ let mockCapturedLogoutOptions: {
|
|||
onError: (...args: unknown[]) => void;
|
||||
};
|
||||
|
||||
const mockEndPullRequestSession = jest.fn();
|
||||
const mockRefreshMutate = jest.fn();
|
||||
const mockLoginMutate = jest.fn();
|
||||
const mockLogoutMutate = jest.fn();
|
||||
|
|
@ -83,6 +84,7 @@ jest.mock('~/data-provider', () => ({
|
|||
error: null,
|
||||
})),
|
||||
useGetRole: jest.fn(() => ({ data: null })),
|
||||
endPullRequestSession: jest.fn(() => mockEndPullRequestSession()),
|
||||
useListRoles: jest.fn(() => ({ data: undefined })),
|
||||
}));
|
||||
|
||||
|
|
@ -508,6 +510,28 @@ describe('AuthContextProvider — logout onSuccess/onError handling', () => {
|
|||
jotaiStore.set(resetChatFilterSessionAtom);
|
||||
});
|
||||
|
||||
it('ends the sidebar pull request queue at the logout session boundary', () => {
|
||||
mockEndPullRequestSession.mockClear();
|
||||
renderProvider();
|
||||
|
||||
act(() => {
|
||||
mockCapturedLogoutOptions.onSuccess({ message: 'Logout successful' });
|
||||
});
|
||||
|
||||
expect(mockEndPullRequestSession).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not end the sidebar pull request queue while a session is being established', () => {
|
||||
mockEndPullRequestSession.mockClear();
|
||||
renderProvider();
|
||||
|
||||
act(() => {
|
||||
capturedAuthContext?.completeAuthentication('auth-token', { id: 'user-1' } as never);
|
||||
});
|
||||
|
||||
expect(mockEndPullRequestSession).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not call window.location.replace when redirect is absent', async () => {
|
||||
const replaceSpy = jest.spyOn(window.location, 'replace').mockImplementation(() => {});
|
||||
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@
|
|||
"com_ui_pr_checks_running": "Running",
|
||||
"com_ui_pr_deletions": "{{0}} lines removed",
|
||||
"com_ui_pr_label": "PR #{{0}}",
|
||||
"com_ui_pr_load_failed": "Couldn't load the pull request",
|
||||
"com_ui_pr_open_in_github": "Open in GitHub",
|
||||
"com_ui_pr_refresh_failed": "Couldn't refresh the pull request",
|
||||
"com_ui_pr_state": "State: {{0}}",
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue