mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-18 22:14:27 +00:00
🪁 fix: Keep Workspace Discovery Reactive (#16296)
* 🪁 fix: Keep Workspace Discovery Reactive
* fix: Observe Agent Endpoints Without Recoil
---------
Co-authored-by: Lia <lia@librechat.ai>
This commit is contained in:
parent
8fb4056e8a
commit
d0850e7389
10 changed files with 485 additions and 42 deletions
|
|
@ -1,6 +1,6 @@
|
|||
import { useState } from 'react';
|
||||
import * as Ariakit from '@ariakit/react';
|
||||
import { Check, ChevronDown, Folder, FolderSync, FolderX } from 'lucide-react';
|
||||
import { Check, ChevronDown, Folder, FolderSync, FolderX, RefreshCw } from 'lucide-react';
|
||||
import { TooltipAnchor, composerControlClasses, useToastContext } from '@librechat/client';
|
||||
import type { CodeWorkspaceSelection, TConversation } from 'librechat-data-provider';
|
||||
import type { SetterOrUpdater } from 'recoil';
|
||||
|
|
@ -10,13 +10,16 @@ import type {
|
|||
CodeWorkspaceResult,
|
||||
TranslationKeys,
|
||||
} from '~/hooks';
|
||||
import {
|
||||
useCodeWorkspaceRefresh,
|
||||
useMoveConversationCodeEnvironmentMutation,
|
||||
} from '~/data-provider';
|
||||
import {
|
||||
cn,
|
||||
codeWorkspaceErrorKeys,
|
||||
getCodeWorkspaceErrorReason,
|
||||
getResponseStatus,
|
||||
} from '~/utils';
|
||||
import { useMoveConversationCodeEnvironmentMutation } from '~/data-provider';
|
||||
import { useLocalize } from '~/hooks';
|
||||
|
||||
const stateLabels: Partial<Record<CodeWorkspaceResult['state'], TranslationKeys>> = {
|
||||
|
|
@ -174,6 +177,7 @@ export default function CodeWorkspaceMenu({
|
|||
const menuStore = Ariakit.useMenuStore({ focusLoop: true, placement: 'top-start' });
|
||||
const isOpen = menuStore.useState('open');
|
||||
const moveMutation = useMoveConversationCodeEnvironmentMutation();
|
||||
const { refresh, isRefreshing } = useCodeWorkspaceRefresh();
|
||||
const [moveDraft, setMoveDraft] = useState<{
|
||||
conversationId: string;
|
||||
workspaces: Record<string, string>;
|
||||
|
|
@ -217,7 +221,7 @@ export default function CodeWorkspaceMenu({
|
|||
);
|
||||
const labelKey = stateLabels[workspace.state];
|
||||
let label =
|
||||
workspace.mode === 'without_attached'
|
||||
workspace.state === 'without_attached'
|
||||
? localize('com_ui_code_workspace_without_attached')
|
||||
: (onlyDescriptor?.name ?? onlyDescriptor?.id);
|
||||
if (label == null && workspace.state === 'ready') {
|
||||
|
|
@ -241,16 +245,22 @@ export default function CodeWorkspaceMenu({
|
|||
<TooltipAnchor
|
||||
description={recovery}
|
||||
render={
|
||||
<div
|
||||
<button
|
||||
type="button"
|
||||
data-testid="code-workspace-locked-status"
|
||||
role="status"
|
||||
aria-label={`${label}. ${recovery}`}
|
||||
className={cn(composerControlClasses(), 'min-w-0 max-w-full cursor-default px-2.5')}
|
||||
disabled={disabled || isRefreshing}
|
||||
onClick={() => void refresh()}
|
||||
aria-label={`${label}. ${recovery}. ${localize('com_ui_retry')}`}
|
||||
aria-busy={isRefreshing}
|
||||
className={cn(composerControlClasses(), 'min-w-0 max-w-full px-2.5')}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<Icon className="size-4 shrink-0 text-text-secondary" aria-hidden="true" />
|
||||
<span className="min-w-0 max-w-[16rem] truncate">{label}</span>
|
||||
<span role="status" className="min-w-0 max-w-[16rem] truncate">
|
||||
{label}
|
||||
</span>
|
||||
<RefreshCw className="size-3 shrink-0 text-text-secondary" aria-hidden="true" />
|
||||
</TooltipAnchor>
|
||||
);
|
||||
}
|
||||
|
|
@ -424,6 +434,22 @@ export default function CodeWorkspaceMenu({
|
|||
))}
|
||||
</>
|
||||
)}
|
||||
<Ariakit.MenuSeparator className="my-1 h-0 w-full border-t border-border-light" />
|
||||
<Ariakit.MenuItem
|
||||
disabled={buttonDisabled || isRefreshing}
|
||||
hideOnClick={false}
|
||||
onClick={() => void refresh()}
|
||||
aria-busy={isRefreshing}
|
||||
className={cn(
|
||||
menuItemClasses(),
|
||||
'items-center aria-disabled:cursor-not-allowed aria-disabled:opacity-50',
|
||||
)}
|
||||
>
|
||||
<RefreshCw className="size-4 shrink-0 text-text-secondary" aria-hidden="true" />
|
||||
<span className="text-sm font-medium text-text-primary">
|
||||
{localize('com_ui_refresh')}
|
||||
</span>
|
||||
</Ariakit.MenuItem>
|
||||
</Ariakit.Menu>
|
||||
</Ariakit.MenuProvider>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -88,6 +88,37 @@ function renderMenu(ui: React.ReactElement) {
|
|||
}
|
||||
|
||||
describe('CodeWorkspaceMenu', () => {
|
||||
test('shows loading rather than the inferred no-workspace fallback on first load', () => {
|
||||
renderMenu(
|
||||
<CodeWorkspaceMenu
|
||||
setConversation={jest.fn()}
|
||||
workspace={workspace({
|
||||
mode: 'without_attached',
|
||||
state: 'loading',
|
||||
selections: undefined,
|
||||
environments: [{ environment, state: 'loading', workspaces: [] }],
|
||||
})}
|
||||
disabled={false}
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByTestId('code-workspace')).toHaveTextContent('com_ui_code_workspace_loading');
|
||||
});
|
||||
|
||||
test('can retry a locked unavailable workspace without changing its saved decision', async () => {
|
||||
const invalidate = jest.spyOn(QueryClient.prototype, 'invalidateQueries');
|
||||
const setConversation = jest.fn();
|
||||
renderMenu(
|
||||
<CodeWorkspaceMenu
|
||||
setConversation={setConversation}
|
||||
workspace={workspace({ locked: true, state: 'unavailable', canSubmit: false })}
|
||||
disabled={false}
|
||||
/>,
|
||||
);
|
||||
await userEvent.click(screen.getByRole('button', { name: /com_ui_retry/ }));
|
||||
expect(invalidate).toHaveBeenCalled();
|
||||
expect(setConversation).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('shows the instruction file and truncation reported by the worker', async () => {
|
||||
const state = workspace();
|
||||
state.environments[0].workspaces[0].instructions = [
|
||||
|
|
@ -260,7 +291,7 @@ describe('CodeWorkspaceMenu', () => {
|
|||
);
|
||||
|
||||
expect(screen.getByTestId('code-workspace-locked-status')).toHaveAccessibleName(
|
||||
'com_ui_code_workspace_unavailable. com_ui_code_workspace_locked_recovery',
|
||||
'com_ui_code_workspace_unavailable. com_ui_code_workspace_locked_recovery. com_ui_retry',
|
||||
);
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import type {
|
|||
UseInfiniteQueryOptions,
|
||||
} from '@tanstack/react-query';
|
||||
import type t from 'librechat-data-provider';
|
||||
import { retryTransientQuery } from '../retry';
|
||||
import { isEphemeralAgent } from '~/common';
|
||||
|
||||
/**
|
||||
|
|
@ -74,8 +75,13 @@ export const useListAgentsQuery = <TData = t.AgentListResponse>(
|
|||
params: t.AgentListParams = defaultAgentParams,
|
||||
config?: UseQueryOptions<t.AgentListResponse, unknown, TData>,
|
||||
): QueryObserverResult<TData> => {
|
||||
const queryClient = useQueryClient();
|
||||
const endpointsConfig = queryClient.getQueryData<t.TEndpointsConfig>([QueryKeys.endpoints]);
|
||||
/** The shell owns fetching endpoints. Observe its query, but do not start a second
|
||||
* request or couple this shared agent hook to the shell's Recoil gate. */
|
||||
const { data: endpointsConfig } = useQuery<t.TEndpointsConfig>(
|
||||
[QueryKeys.endpoints],
|
||||
() => dataService.getAIEndpoints(),
|
||||
{ enabled: false },
|
||||
);
|
||||
|
||||
const enabled = !!endpointsConfig?.[EModelEndpoint.agents];
|
||||
return useQuery<t.AgentListResponse, unknown, TData>(
|
||||
|
|
@ -83,10 +89,10 @@ export const useListAgentsQuery = <TData = t.AgentListResponse>(
|
|||
() => fetchAllAgentPages(params),
|
||||
{
|
||||
staleTime: 1000 * 5,
|
||||
refetchOnWindowFocus: false,
|
||||
refetchOnReconnect: false,
|
||||
refetchOnMount: false,
|
||||
retry: false,
|
||||
refetchOnWindowFocus: true,
|
||||
refetchOnReconnect: true,
|
||||
refetchOnMount: true,
|
||||
retry: retryTransientQuery,
|
||||
...config,
|
||||
enabled: config?.enabled !== undefined ? config.enabled && enabled : enabled,
|
||||
},
|
||||
|
|
@ -109,10 +115,11 @@ export const useGetAgentByIdQuery = (
|
|||
agent_id: agent_id as string,
|
||||
}),
|
||||
{
|
||||
refetchOnWindowFocus: false,
|
||||
refetchOnReconnect: false,
|
||||
refetchOnMount: false,
|
||||
retry: false,
|
||||
staleTime: 1000 * 5,
|
||||
refetchOnWindowFocus: true,
|
||||
refetchOnReconnect: true,
|
||||
refetchOnMount: true,
|
||||
retry: retryTransientQuery,
|
||||
...config,
|
||||
enabled: isValidAgentId && (config?.enabled ?? true),
|
||||
},
|
||||
|
|
|
|||
|
|
@ -1,5 +1,11 @@
|
|||
import { useMutation, useQueries, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { DynamicQueryKeys, MutationKeys, QueryKeys, dataService } from 'librechat-data-provider';
|
||||
import {
|
||||
useIsFetching,
|
||||
useMutation,
|
||||
useQueries,
|
||||
useQuery,
|
||||
useQueryClient,
|
||||
} from '@tanstack/react-query';
|
||||
import type {
|
||||
TConversation,
|
||||
CodeEnvironmentUserSettings,
|
||||
|
|
@ -9,7 +15,9 @@ import type {
|
|||
TCodeEnvironmentStatusResponse,
|
||||
TCodeEnvironmentsResponse,
|
||||
} from 'librechat-data-provider';
|
||||
import type { QueryFilters } from '@tanstack/react-query';
|
||||
import { CONVERSATION_LIST_KEYS, updateConvoInAllQueries } from '~/utils';
|
||||
import { retryTransientQuery } from './retry';
|
||||
|
||||
export type CodeEnvironmentPairingResponse = TCodeEnvironmentPairingResponse;
|
||||
|
||||
|
|
@ -21,30 +29,41 @@ export function useCodeEnvironmentsQuery(enabled = true) {
|
|||
);
|
||||
}
|
||||
|
||||
function codeEnvironmentStatusOptions(id: string, enabled: boolean) {
|
||||
return {
|
||||
queryKey: DynamicQueryKeys.codeEnvironmentStatus(id),
|
||||
queryFn: (): Promise<TCodeEnvironmentStatusResponse> =>
|
||||
dataService.getCodeEnvironmentStatus(id),
|
||||
enabled: enabled && id.length > 0,
|
||||
staleTime: 10_000,
|
||||
refetchInterval: 10_000,
|
||||
refetchIntervalInBackground: false,
|
||||
retry: retryTransientQuery,
|
||||
};
|
||||
}
|
||||
|
||||
export function useCodeEnvironmentStatusQuery(id: string, enabled = true) {
|
||||
return useQuery<TCodeEnvironmentStatusResponse>(
|
||||
DynamicQueryKeys.codeEnvironmentStatus(id),
|
||||
() => dataService.getCodeEnvironmentStatus(id),
|
||||
{
|
||||
enabled: enabled && id.length > 0,
|
||||
refetchInterval: 10_000,
|
||||
refetchIntervalInBackground: false,
|
||||
retry: false,
|
||||
},
|
||||
);
|
||||
return useQuery(codeEnvironmentStatusOptions(id, enabled));
|
||||
}
|
||||
|
||||
export function useCodeEnvironmentStatusQueries(ids: string[], enabled = true) {
|
||||
return useQueries({
|
||||
queries: ids.map((id) => ({
|
||||
queryKey: DynamicQueryKeys.codeEnvironmentStatus(id),
|
||||
queryFn: () => dataService.getCodeEnvironmentStatus(id),
|
||||
enabled: enabled && id.length > 0,
|
||||
refetchInterval: 10_000,
|
||||
refetchIntervalInBackground: false,
|
||||
retry: false,
|
||||
})),
|
||||
});
|
||||
return useQueries({ queries: ids.map((id) => codeEnvironmentStatusOptions(id, enabled)) });
|
||||
}
|
||||
|
||||
/** Refresh discovery, not the conversation draft or expanded agent editor records. */
|
||||
const isWorkspaceDiscovery: NonNullable<QueryFilters['predicate']> = ({ queryKey }) =>
|
||||
queryKey[0] === QueryKeys.endpoints ||
|
||||
queryKey[0] === QueryKeys.agents ||
|
||||
queryKey[0] === QueryKeys.codeEnvironments ||
|
||||
(queryKey[0] === QueryKeys.agent && queryKey.length === 2);
|
||||
|
||||
export function useCodeWorkspaceRefresh() {
|
||||
const queryClient = useQueryClient();
|
||||
const isRefreshing = useIsFetching({ predicate: isWorkspaceDiscovery }) > 0;
|
||||
return {
|
||||
isRefreshing,
|
||||
refresh: () => queryClient.invalidateQueries({ predicate: isWorkspaceDiscovery }),
|
||||
};
|
||||
}
|
||||
|
||||
export function usePairCodeEnvironmentMutation() {
|
||||
|
|
|
|||
220
client/src/data-provider/__tests__/workspaceFreshness.spec.tsx
Normal file
220
client/src/data-provider/__tests__/workspaceFreshness.spec.tsx
Normal file
|
|
@ -0,0 +1,220 @@
|
|||
import { createElement } from 'react';
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { QueryClient, QueryClientProvider, focusManager, useQueries } from '@tanstack/react-query';
|
||||
import {
|
||||
dataService,
|
||||
DynamicQueryKeys,
|
||||
EModelEndpoint,
|
||||
PermissionBits,
|
||||
QueryKeys,
|
||||
} from 'librechat-data-provider';
|
||||
import type {
|
||||
Agent,
|
||||
AgentListResponse,
|
||||
TCodeEnvironmentStatusResponse,
|
||||
} from 'librechat-data-provider';
|
||||
import type { ReactNode } from 'react';
|
||||
import {
|
||||
useCodeWorkspaceRefresh,
|
||||
useCodeEnvironmentStatusQueries,
|
||||
useCodeEnvironmentStatusQuery,
|
||||
} from '../CodeEnvironments';
|
||||
import { useGetAgentByIdQuery, useListAgentsQuery } from '../Agents/queries';
|
||||
|
||||
jest.mock('librechat-data-provider', () => {
|
||||
const actual =
|
||||
jest.requireActual<typeof import('librechat-data-provider')>('librechat-data-provider');
|
||||
return { ...actual, dataService: { ...actual.dataService } };
|
||||
});
|
||||
|
||||
const ready: TCodeEnvironmentStatusResponse = {
|
||||
environmentId: 'vm',
|
||||
status: 'ready',
|
||||
workspaces: [{ id: 'project' }],
|
||||
};
|
||||
const agent = {
|
||||
id: 'agent_primary',
|
||||
code_environment_id: 'vm',
|
||||
code_workspace_id: 'project',
|
||||
} as Agent;
|
||||
const agentList = { object: 'list', data: [agent], has_more: false } as AgentListResponse;
|
||||
|
||||
function setup() {
|
||||
const client = new QueryClient({
|
||||
defaultOptions: { queries: { retryDelay: 0, cacheTime: Infinity } },
|
||||
});
|
||||
client.setQueryData([QueryKeys.endpoints], { [EModelEndpoint.agents]: {} });
|
||||
const wrapper = ({ children }: { children: ReactNode }) =>
|
||||
createElement(QueryClientProvider, { client }, children);
|
||||
return { client, wrapper };
|
||||
}
|
||||
|
||||
describe('workspace query lifecycle', () => {
|
||||
afterEach(() => focusManager.setFocused(undefined));
|
||||
|
||||
it.each(['single', 'multiple'] as const)(
|
||||
'retries a transient %s status request without a reload',
|
||||
async (kind) => {
|
||||
const request = jest
|
||||
.spyOn(dataService, 'getCodeEnvironmentStatus')
|
||||
.mockRejectedValueOnce({ status: 503 })
|
||||
.mockResolvedValue(ready);
|
||||
const { client, wrapper } = setup();
|
||||
const { result, unmount } = renderHook(
|
||||
() =>
|
||||
kind === 'single'
|
||||
? useCodeEnvironmentStatusQuery('vm')
|
||||
: useCodeEnvironmentStatusQueries(['vm'])[0],
|
||||
{ wrapper },
|
||||
);
|
||||
await waitFor(() => expect(result.current.data).toEqual(ready));
|
||||
expect(request).toHaveBeenCalledTimes(2);
|
||||
unmount();
|
||||
client.clear();
|
||||
},
|
||||
);
|
||||
|
||||
it.each([401, 403, 404, 429])('does not retry status HTTP %s', async (status) => {
|
||||
const request = jest
|
||||
.spyOn(dataService, 'getCodeEnvironmentStatus')
|
||||
.mockRejectedValue({ status });
|
||||
const { client, wrapper } = setup();
|
||||
const { result, unmount } = renderHook(() => useCodeEnvironmentStatusQuery('vm'), { wrapper });
|
||||
await waitFor(() => expect(result.current.isError).toBe(true));
|
||||
expect(request).toHaveBeenCalledTimes(1);
|
||||
unmount();
|
||||
client.clear();
|
||||
});
|
||||
|
||||
it('bounds transient retries instead of fetching indefinitely', async () => {
|
||||
const request = jest
|
||||
.spyOn(dataService, 'getCodeEnvironmentStatus')
|
||||
.mockRejectedValue({ status: 503 });
|
||||
const { client, wrapper } = setup();
|
||||
const { result, unmount } = renderHook(() => useCodeEnvironmentStatusQuery('vm'), { wrapper });
|
||||
await waitFor(() => expect(result.current.isError).toBe(true));
|
||||
expect(request).toHaveBeenCalledTimes(3);
|
||||
unmount();
|
||||
client.clear();
|
||||
});
|
||||
|
||||
it('refreshes discovery but not saved conversation or expanded editor snapshots', async () => {
|
||||
const { client, wrapper } = setup();
|
||||
const keys = [
|
||||
[QueryKeys.endpoints],
|
||||
[QueryKeys.agents],
|
||||
[QueryKeys.agent, agent.id],
|
||||
DynamicQueryKeys.codeEnvironmentStatus('vm'),
|
||||
[QueryKeys.agent, agent.id, 'expanded'],
|
||||
[QueryKeys.conversation, 'saved-chat'],
|
||||
];
|
||||
const requests = keys.map(() => jest.fn().mockResolvedValue({ loaded: true }));
|
||||
const { result, unmount } = renderHook(
|
||||
() => {
|
||||
useQueries({
|
||||
queries: keys.map((queryKey, i) => ({
|
||||
queryKey,
|
||||
queryFn: requests[i],
|
||||
staleTime: Infinity,
|
||||
})),
|
||||
});
|
||||
return useCodeWorkspaceRefresh();
|
||||
},
|
||||
{ wrapper },
|
||||
);
|
||||
await waitFor(() => expect(result.current.isRefreshing).toBe(false));
|
||||
const before = requests.map((request) => request.mock.calls.length);
|
||||
await act(async () => {
|
||||
await result.current.refresh();
|
||||
});
|
||||
requests.forEach((request, i) => {
|
||||
expect(request).toHaveBeenCalledTimes(before[i] + (i < 4 ? 1 : 0));
|
||||
});
|
||||
unmount();
|
||||
client.clear();
|
||||
});
|
||||
|
||||
it('shares a fresh status between composer, submit hook and settings observers', async () => {
|
||||
const request = jest.spyOn(dataService, 'getCodeEnvironmentStatus').mockResolvedValue(ready);
|
||||
const { client, wrapper } = setup();
|
||||
const first = renderHook(() => useCodeEnvironmentStatusQuery('vm'), { wrapper });
|
||||
await waitFor(() => expect(first.result.current.isSuccess).toBe(true));
|
||||
const second = renderHook(() => useCodeEnvironmentStatusQueries(['vm']), { wrapper });
|
||||
await act(async () => {});
|
||||
expect(second.result.current[0].data).toEqual(ready);
|
||||
expect(request).toHaveBeenCalledTimes(1);
|
||||
first.unmount();
|
||||
second.unmount();
|
||||
client.clear();
|
||||
});
|
||||
|
||||
it('revalidates stale agent defaults on mount and focus', async () => {
|
||||
const request = jest.spyOn(dataService, 'getAgentById').mockResolvedValue(agent);
|
||||
const { client, wrapper } = setup();
|
||||
client.setQueryData(
|
||||
[QueryKeys.agent, agent.id],
|
||||
{ ...agent, code_workspace_id: 'old' },
|
||||
{ updatedAt: 1 },
|
||||
);
|
||||
const { result, unmount } = renderHook(() => useGetAgentByIdQuery(agent.id), { wrapper });
|
||||
await waitFor(() => expect(result.current.data?.code_workspace_id).toBe('project'));
|
||||
act(() => {
|
||||
client.setQueryData(
|
||||
[QueryKeys.agent, agent.id],
|
||||
{ ...agent, code_workspace_id: 'old' },
|
||||
{ updatedAt: 1 },
|
||||
);
|
||||
focusManager.setFocused(false);
|
||||
focusManager.setFocused(true);
|
||||
});
|
||||
await waitFor(() => expect(request).toHaveBeenCalledTimes(2));
|
||||
unmount();
|
||||
client.clear();
|
||||
});
|
||||
|
||||
it('starts agent discovery from cached endpoint configuration without Recoil or a duplicate request', async () => {
|
||||
const request = jest.spyOn(dataService, 'listAgents').mockResolvedValue(agentList);
|
||||
const getEndpoints = jest.spyOn(dataService, 'getAIEndpoints');
|
||||
const { client, wrapper } = setup();
|
||||
client.removeQueries([QueryKeys.endpoints]);
|
||||
const { result, unmount } = renderHook(() => useListAgentsQuery(), { wrapper });
|
||||
expect(request).not.toHaveBeenCalled();
|
||||
act(() => {
|
||||
client.setQueryData([QueryKeys.endpoints], { [EModelEndpoint.agents]: {} });
|
||||
});
|
||||
await waitFor(() => expect(result.current.data?.data).toEqual([agent]));
|
||||
expect(request).toHaveBeenCalledTimes(1);
|
||||
expect(getEndpoints).not.toHaveBeenCalled();
|
||||
unmount();
|
||||
client.clear();
|
||||
});
|
||||
|
||||
it('revalidates stale reachable-agent metadata on mount', async () => {
|
||||
const request = jest.spyOn(dataService, 'listAgents').mockResolvedValue(agentList);
|
||||
const { client, wrapper } = setup();
|
||||
const params = { requiredPermission: PermissionBits.VIEW, limit: 100 };
|
||||
client.setQueryData([QueryKeys.agents, params], { ...agentList, data: [] }, { updatedAt: 1 });
|
||||
const { result, unmount } = renderHook(() => useListAgentsQuery(params), { wrapper });
|
||||
await waitFor(() => expect(result.current.data?.data).toEqual([agent]));
|
||||
expect(request).toHaveBeenCalledTimes(1);
|
||||
unmount();
|
||||
client.clear();
|
||||
});
|
||||
|
||||
it('retains a previous status while a background request retries', async () => {
|
||||
const request = jest
|
||||
.spyOn(dataService, 'getCodeEnvironmentStatus')
|
||||
.mockRejectedValueOnce(new Error('Network interrupted'))
|
||||
.mockResolvedValue(ready);
|
||||
const { client, wrapper } = setup();
|
||||
client.setQueryData(DynamicQueryKeys.codeEnvironmentStatus('vm'), ready, { updatedAt: 1 });
|
||||
const { result, unmount } = renderHook(() => useCodeEnvironmentStatusQuery('vm'), { wrapper });
|
||||
expect(result.current.data).toEqual(ready);
|
||||
expect(result.current.isFetching).toBe(true);
|
||||
await waitFor(() => expect(request).toHaveBeenCalledTimes(2));
|
||||
await waitFor(() => expect(result.current.isFetching).toBe(false));
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
unmount();
|
||||
client.clear();
|
||||
});
|
||||
});
|
||||
7
client/src/data-provider/retry.ts
Normal file
7
client/src/data-provider/retry.ts
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
import { getResponseStatus } from '~/utils/errors';
|
||||
|
||||
/** Retry transport and server failures, never an authorization or resource decision. */
|
||||
export function retryTransientQuery(failureCount: number, error: unknown): boolean {
|
||||
const status = getResponseStatus(error);
|
||||
return failureCount < 2 && (status == null || status >= 500);
|
||||
}
|
||||
|
|
@ -99,6 +99,14 @@ describe('useCodeWorkspace', () => {
|
|||
},
|
||||
);
|
||||
|
||||
it('reports unavailable when a ready worker advertises no workspaces', () => {
|
||||
mockStatus()[0].data.workspaces = [];
|
||||
const { result } = renderHook(() => useCodeWorkspace(conversation()));
|
||||
expect(result.current.state).toBe('unavailable');
|
||||
expect(result.current.canSubmit).toBe(true);
|
||||
expect(result.current.resolveSubmission(undefined, 'attached')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('selects one unambiguous initial workspace', () => {
|
||||
const { result } = renderHook(() => useCodeWorkspace(conversation()));
|
||||
|
||||
|
|
|
|||
124
client/src/hooks/Agents/__tests__/workspaceLifecycle.spec.tsx
Normal file
124
client/src/hooks/Agents/__tests__/workspaceLifecycle.spec.tsx
Normal file
|
|
@ -0,0 +1,124 @@
|
|||
import { createElement } from 'react';
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { dataService, DynamicQueryKeys } from 'librechat-data-provider';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import type { TCodeEnvironmentStatusResponse, TConversation } from 'librechat-data-provider';
|
||||
import type { ReactNode } from 'react';
|
||||
import useCodeWorkspace from '../useCodeWorkspace';
|
||||
|
||||
jest.mock('librechat-data-provider', () => {
|
||||
const actual =
|
||||
jest.requireActual<typeof import('librechat-data-provider')>('librechat-data-provider');
|
||||
return { ...actual, dataService: { ...actual.dataService } };
|
||||
});
|
||||
jest.mock('~/data-provider', () => ({
|
||||
useCodeEnvironmentStatusQueries: jest.requireActual('~/data-provider/CodeEnvironments')
|
||||
.useCodeEnvironmentStatusQueries,
|
||||
useGetStartupConfig: () => ({ data: { codeEnvironmentDecisionVersion: 1 } }),
|
||||
}));
|
||||
jest.mock('../workspacePreferences', () => ({
|
||||
useWorkspacePreferences: () => ({ get: () => undefined, remember: jest.fn() }),
|
||||
}));
|
||||
jest.mock('~/hooks/Roles/useHasAccess', () => () => true);
|
||||
jest.mock('~/Providers', () => ({ useAgentsMapContext: () => ({}) }));
|
||||
jest.mock('../useAgentToolPermissions', () => (id: string) => ({
|
||||
agent: id
|
||||
? { id, stateful_code_sessions: true, code_environment_id: 'vm', tools: ['execute_code'] }
|
||||
: undefined,
|
||||
}));
|
||||
jest.mock('../useGetAgentsConfig', () => () => ({
|
||||
agentsConfig: {
|
||||
capabilities: ['execute_code', 'stateful_code_sessions'],
|
||||
statefulCodeSessions: { environments: [{ id: 'vm', name: 'VM', type: 'attached' }] },
|
||||
},
|
||||
}));
|
||||
|
||||
const selected = { environmentId: 'vm', workspaceId: 'project' };
|
||||
const ready: TCodeEnvironmentStatusResponse = {
|
||||
environmentId: 'vm',
|
||||
status: 'ready',
|
||||
workspaces: [{ id: 'project' }],
|
||||
};
|
||||
const saved = {
|
||||
conversationId: 'saved-chat',
|
||||
endpoint: 'agents',
|
||||
agent_id: 'agent_primary',
|
||||
codeEnvironmentMode: 'attached',
|
||||
codeWorkspaces: [selected],
|
||||
} as TConversation;
|
||||
|
||||
function setup(conversation: TConversation = saved) {
|
||||
const client = new QueryClient({
|
||||
defaultOptions: { queries: { retryDelay: 0, cacheTime: Infinity } },
|
||||
});
|
||||
const wrapper = ({ children }: { children: ReactNode }) =>
|
||||
createElement(QueryClientProvider, { client }, children);
|
||||
return { client, ...renderHook(() => useCodeWorkspace(conversation), { wrapper }) };
|
||||
}
|
||||
|
||||
describe('workspace status recovery', () => {
|
||||
it('restores the saved selection when a delayed initial status request resolves', async () => {
|
||||
let resolve = (_status: TCodeEnvironmentStatusResponse) => {};
|
||||
jest.spyOn(dataService, 'getCodeEnvironmentStatus').mockReturnValue(
|
||||
new Promise((done) => {
|
||||
resolve = done;
|
||||
}),
|
||||
);
|
||||
const { result, client, unmount } = setup();
|
||||
expect(result.current.state).toBe('loading');
|
||||
expect(result.current.canSubmit).toBe(false);
|
||||
await act(async () => resolve(ready));
|
||||
await waitFor(() => expect(result.current.state).toBe('ready'));
|
||||
expect(result.current.selections).toEqual([selected]);
|
||||
expect(result.current.locked).toBe(true);
|
||||
expect(result.current.resolveSubmission(saved.codeWorkspaces, 'attached')).toEqual({
|
||||
codeEnvironmentMode: 'attached',
|
||||
codeWorkspaces: [selected],
|
||||
});
|
||||
unmount();
|
||||
client.clear();
|
||||
});
|
||||
|
||||
it('recovers an exhausted background failure without replacing the saved selection', async () => {
|
||||
const request = jest.spyOn(dataService, 'getCodeEnvironmentStatus').mockResolvedValue(ready);
|
||||
const { result, client, unmount } = setup();
|
||||
await waitFor(() => expect(result.current.state).toBe('ready'));
|
||||
request.mockRejectedValue(new Error('offline'));
|
||||
await act(async () => {
|
||||
await client.invalidateQueries(DynamicQueryKeys.codeEnvironmentStatus('vm'));
|
||||
});
|
||||
await waitFor(() => expect(result.current.state).toBe('unavailable'));
|
||||
expect(result.current.canSubmit).toBe(false);
|
||||
expect(result.current.environments[0].selected).toEqual(selected);
|
||||
request.mockResolvedValue(ready);
|
||||
await act(async () => {
|
||||
await client.invalidateQueries(DynamicQueryKeys.codeEnvironmentStatus('vm'));
|
||||
});
|
||||
await waitFor(() => expect(result.current.state).toBe('ready'));
|
||||
expect(result.current.selections).toEqual([selected]);
|
||||
unmount();
|
||||
client.clear();
|
||||
});
|
||||
|
||||
it('recovers an empty first response into the sole workspace without a reload', async () => {
|
||||
const request = jest
|
||||
.spyOn(dataService, 'getCodeEnvironmentStatus')
|
||||
.mockResolvedValue({ ...ready, workspaces: [] });
|
||||
const { result, client, unmount } = setup({
|
||||
...saved,
|
||||
conversationId: 'new',
|
||||
codeEnvironmentMode: undefined,
|
||||
codeWorkspaces: undefined,
|
||||
});
|
||||
await waitFor(() => expect(result.current.state).toBe('unavailable'));
|
||||
expect(result.current.resolveSubmission(undefined, 'attached')).toBeUndefined();
|
||||
request.mockResolvedValue(ready);
|
||||
await act(async () => {
|
||||
await client.invalidateQueries(DynamicQueryKeys.codeEnvironmentStatus('vm'));
|
||||
});
|
||||
await waitFor(() => expect(result.current.state).toBe('ready'));
|
||||
expect(result.current.selections).toEqual([selected]);
|
||||
unmount();
|
||||
client.clear();
|
||||
});
|
||||
});
|
||||
|
|
@ -308,6 +308,7 @@ export default function useCodeWorkspace(
|
|||
} else if (status.data.workspaces == null) state = 'unsupported';
|
||||
else if (selected != null) state = 'ready';
|
||||
else if (stored != null) state = 'missing';
|
||||
else if (workspaces.length === 0) state = 'unavailable';
|
||||
return { environment, state, workspaces, selected };
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -142,8 +142,8 @@ export default function ChatRoute() {
|
|||
const assistantListMap = useAssistantListMap();
|
||||
/** The map comes from Root's shared context (one mapping pass app-wide); the
|
||||
* select-less observer only tracks settle state. Only a loaded list may
|
||||
* invalidate a stored agent pick: on a transient catalog failure (retries are
|
||||
* disabled) the map stays unknown, the pick stays trusted, and the gate below
|
||||
* invalidate a stored agent pick: on a transient catalog failure after retries,
|
||||
* the map stays unknown, the pick stays trusted, and the gate below
|
||||
* releases so the landing never hangs on the error. */
|
||||
const agentsMap: TAgentsMap | undefined = useAgentsMapContext();
|
||||
const agentsQuery = useListAgentsQuery(
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue