Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,14 +1,29 @@
// @vitest-environment jsdom
import '@testing-library/jest-dom/vitest';
import { screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import { QueryClient, useMutation } from '@tanstack/react-query';
import { act, fireEvent, screen, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import deMessages from '@/messages/de.yml';
import enMessages from '@/messages/en.yml';
import frMessages from '@/messages/fr.yml';
import { checkAccessibility } from '@/tests/utils/a11y';
import { render } from '@/tests/utils/render';

const { locale } = vi.hoisted(() => ({
locale: { value: 'en' as 'en' | 'de' | 'fr' },
}));
const catalogs = { en: enMessages, de: deMessages, fr: frMessages };

vi.mock('@tale/ui/i18n/client', () => ({
useT: (ns: string) => ({
t: (key: string, params?: Record<string, string>) => {
if (ns === 'websites') {
const copy = catalogs[locale.value].websites.syncError;
if (key === 'syncError.title') return copy.title;
if (key === 'syncError.description') return copy.description;
if (key === 'syncError.retry') return copy.retry;
}
if (params) {
return Object.entries(params).reduce(
(acc, [k, v]) => acc.replace(`{${k}}`, v),
Expand All @@ -34,8 +49,15 @@ vi.mock('@tanstack/react-router', () => ({
useLocation: () => ({ pathname: '/dashboard/test-org/websites' }),
}));

const { syncStatuses } = vi.hoisted(() => ({
syncStatuses: vi.fn<(args: { organizationId: string }) => Promise<void>>(),
}));

let queryClient: QueryClient;

vi.mock('../hooks/mutations', () => ({
useSyncWebsiteStatuses: () => ({ mutate: vi.fn() }),
useSyncWebsiteStatuses: () =>
useMutation({ mutationFn: syncStatuses }, queryClient),
useCreateWebsite: () => ({ mutate: vi.fn(), isPending: false }),
useDeleteWebsite: () => ({ mutateAsync: vi.fn() }),
}));
Expand Down Expand Up @@ -73,6 +95,110 @@ vi.mock('./website-search-notice', () => ({
import { WebsitesTable } from './websites-table';

describe('WebsitesTable', () => {
beforeEach(() => {
queryClient = new QueryClient();
locale.value = 'en';
sessionStorage.clear();
syncStatuses.mockReset().mockResolvedValue(undefined);
vi.spyOn(Date, 'now').mockReturnValue(1_800_000_000_000);
});

afterEach(() => {
vi.restoreAllMocks();
});

it('retries on remount within five minutes after the first sync rejects', async () => {
syncStatuses.mockRejectedValueOnce(new Error('Unavailable'));
const first = render(<WebsitesTable organizationId="org-sync" />);
await waitFor(() => expect(syncStatuses).toHaveBeenCalledTimes(1));
await act(async () => {});
first.unmount();

render(<WebsitesTable organizationId="org-sync" />);
await waitFor(() => expect(syncStatuses).toHaveBeenCalledTimes(2));
await waitFor(() =>
expect(sessionStorage.getItem('websites-sync-org-sync')).toBe(
String(Date.now()),
),
);
});

it('records completion time only after success and throttles successful remounts', async () => {
let finishSync: (() => void) | undefined;
syncStatuses.mockImplementationOnce(
() =>
new Promise<void>((resolve) => {
finishSync = resolve;
}),
);
const first = render(<WebsitesTable organizationId="org-sync" />);
await waitFor(() => expect(syncStatuses).toHaveBeenCalledTimes(1));
expect(sessionStorage.getItem('websites-sync-org-sync')).toBeNull();
first.unmount();
vi.mocked(Date.now).mockReturnValue(1_800_000_010_000);
await act(async () => finishSync?.());
expect(sessionStorage.getItem('websites-sync-org-sync')).toBe(
String(Date.now()),
);

const second = render(<WebsitesTable organizationId="org-sync" />);
await act(async () => {});
expect(syncStatuses).toHaveBeenCalledTimes(1);
second.unmount();

vi.mocked(Date.now).mockReturnValue(1_800_000_310_000);
render(<WebsitesTable organizationId="org-sync" />);
await waitFor(() => expect(syncStatuses).toHaveBeenCalledTimes(2));
});

it('keeps a retryable alert until Retry succeeds and prevents duplicate retries', async () => {
syncStatuses.mockRejectedValueOnce(new Error('Unavailable'));
render(<WebsitesTable organizationId="org-sync" />);
const alert = await screen.findByRole('alert');
expect(alert).toHaveTextContent(enMessages.websites.syncError.description);
let finishRetry: (() => void) | undefined;
syncStatuses.mockImplementationOnce(
() =>
new Promise<void>((resolve) => {
finishRetry = resolve;
}),
);
const retry = screen.getByRole('button', {
name: enMessages.websites.syncError.retry,
});
fireEvent.click(retry);
await waitFor(() => expect(retry).toBeDisabled());
fireEvent.click(retry);
expect(syncStatuses).toHaveBeenCalledTimes(2);
expect(alert).toBeInTheDocument();
expect(sessionStorage.getItem('websites-sync-org-sync')).toBeNull();
await act(async () => finishRetry?.());
await waitFor(() =>
expect(screen.queryByRole('alert')).not.toBeInTheDocument(),
);
expect(sessionStorage.getItem('websites-sync-org-sync')).toBe(
String(Date.now()),
);
});

it('clears an expired timestamp on failure without touching another organization', async () => {
sessionStorage.setItem(
'websites-sync-org-sync',
String(Date.now() - 300_000),
);
sessionStorage.setItem('websites-sync-other-org', String(Date.now()));
syncStatuses.mockRejectedValueOnce(new Error('Unavailable'));
const view = render(<WebsitesTable organizationId="org-sync" />);
await screen.findByRole('alert');
expect(sessionStorage.getItem('websites-sync-org-sync')).toBeNull();
expect(sessionStorage.getItem('websites-sync-other-org')).toBe(
String(Date.now()),
);
view.rerender(<WebsitesTable organizationId="other-org" />);
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
expect(syncStatuses).toHaveBeenCalledTimes(1);
});

it('stacks the search notice above the table inside the list frame', () => {
render(<WebsitesTable organizationId="test-org-id" />);
const notice = screen.getByTestId('website-search-notice');
Expand All @@ -86,6 +212,31 @@ describe('WebsitesTable', () => {
});

describe('accessibility', () => {
it.each(['en', 'de', 'fr'] as const)(
'shows an accessible, localized retry error in %s',
async (language) => {
locale.value = language;
syncStatuses.mockRejectedValueOnce(new Error('Unavailable'));
const { container, user } = render(
<WebsitesTable organizationId="org-sync" />,
);
const alert = await screen.findByRole('alert');
const copy = catalogs[language].websites.syncError;
expect(alert).toHaveTextContent(copy.title);
expect(alert).toHaveTextContent(copy.description);
const retry = screen.getByRole('button', { name: copy.retry });
await checkAccessibility(container, {
rules: { 'aria-allowed-attr': { enabled: false } },
});
retry.focus();
await user.keyboard('{Enter}');
await waitFor(() =>
expect(screen.queryByRole('alert')).not.toBeInTheDocument(),
);
expect(syncStatuses).toHaveBeenCalledTimes(2);
},
);

it('passes axe audit', async () => {
const { container } = render(
<WebsitesTable organizationId="test-org-id" />,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
'use client';

import { Alert } from '@tale/ui/alert';
import { Button } from '@tale/ui/button';
import { DataTable } from '@tale/ui/data-table/data-table';
import { BulkDeleteBar } from '@tale/ui/data-table/data-table-bulk-actions';
import { useListPage } from '@tale/ui/use-list-page';
Expand Down Expand Up @@ -41,18 +43,33 @@ export function WebsitesTable({
const { t: tEmpty } = useT('emptyStates');
const { t: tWebsites } = useT('websites');
const [createOpen, setCreateOpen] = useState(false);
const [syncErrors, setSyncErrors] = useState<Record<string, boolean>>({});

const { data: count } = useApproxWebsiteCount(organizationId);
const { mutate: syncStatuses } = useSyncWebsiteStatuses();
const { mutateAsync: syncStatuses, isPending: isSyncPending } =
useSyncWebsiteStatuses();

const handleSync = useCallback(() => {
const key = `websites-sync-${organizationId}`;
void syncStatuses({ organizationId }).then(
() => {
sessionStorage.setItem(key, String(Date.now()));
setSyncErrors((previous) => ({ ...previous, [organizationId]: false }));
},
() => {
sessionStorage.removeItem(key);
setSyncErrors((previous) => ({ ...previous, [organizationId]: true }));
},
);
}, [organizationId, syncStatuses]);

useEffect(() => {
const key = `websites-sync-${organizationId}`;
const lastSync = sessionStorage.getItem(key);
const fiveMinutes = 5 * 60 * 1000;
if (lastSync && Date.now() - Number(lastSync) < fiveMinutes) return;
sessionStorage.setItem(key, String(Date.now()));
syncStatuses({ organizationId });
}, [organizationId, syncStatuses]);
handleSync();
}, [organizationId, handleSync]);
const { columns, searchPlaceholder, pageSize } = useWebsitesTableConfig();
const paginatedResult = useListWebsitesPaginated({
organizationId,
Expand Down Expand Up @@ -193,6 +210,24 @@ export function WebsitesTable({
keeps the page inset and the table keeps the remaining height. */}
<div className="flex min-h-0 flex-1 flex-col gap-6">
<WebsiteSearchNotice organizationId={organizationId} />
{syncErrors[organizationId] && (
<Alert
variant="destructive"
title={tWebsites('syncError.title')}
description={tWebsites('syncError.description')}
>
<Button
type="button"
variant="secondary"
size="sm"
isLoading={isSyncPending}
onClick={handleSync}
className="mt-3"
>
{tWebsites('syncError.retry')}
</Button>
</Alert>
)}
<DataTable
columns={columns}
stickyLayout
Expand Down
4 changes: 4 additions & 0 deletions services/platform/messages/de.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8251,6 +8251,10 @@ websites:
resumeScanning: Scans fortsetzen
scanNow: Jetzt scannen
indexed: Indexiert
syncError:
title: Die Website-Status konnten nicht aktualisiert werden
description: Status und Anzahl indexierter Seiten sind möglicherweise veraltet. Versuch erneut, sie zu aktualisieren.
retry: Erneut versuchen
searchNotice:
title: Der Chat kann diese Websites noch nicht durchsuchen
description: Die Seiten werden gecrawlt und gespeichert. Die Wissenssuche braucht aber ein funktionierendes Embedding-Modell, und diese Organisation hat noch keines.
Expand Down
4 changes: 4 additions & 0 deletions services/platform/messages/en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8378,6 +8378,10 @@ websites:
resumeScanning: Resume scanning
scanNow: Scan now
indexed: Indexed
syncError:
title: Website statuses couldn't be refreshed
description: Statuses and indexed page counts may be out of date. Try refreshing them again.
retry: Retry
searchNotice:
title: Chat can't search these websites yet
description: Pages are crawled and stored, but knowledge search needs a working embedding model, and this organization doesn't have one yet.
Expand Down
4 changes: 4 additions & 0 deletions services/platform/messages/fr.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8352,6 +8352,10 @@ websites:
resumeScanning: Reprendre l'analyse
scanNow: Analyser maintenant
indexed: Indexé
syncError:
title: Les statuts des sites web n'ont pas pu être actualisés
description: Les statuts et le nombre de pages indexées sont peut-être obsolètes. Essaie de les actualiser à nouveau.
retry: Réessayer
searchNotice:
title: Le chat ne peut pas encore chercher dans ces sites web
description: Les pages sont explorées et enregistrées, mais la recherche de connaissances a besoin d'un modèle d'embedding qui fonctionne, et cette organisation n'en a pas encore.
Expand Down
7 changes: 7 additions & 0 deletions services/platform/tests/manual/reference/automation.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,13 @@ in EN/DE/FR that clear after correction:
covers the component boundary and axe audit; real API persistence and browser
layout remain manual.

Website status sync records the five-minute throttle only after success. Failed
syncs retry on remount, clear expired timestamps and expose an accessible Retry
alert that stays visible during retry and clears on success. Organization-scoped
storage and errors, completion after unmount and successful throttle expiry are
covered by `app/features/websites/components/websites-table.test.tsx`.
Real-browser layout, focus and screen-reader announcements remain manual.

Failed single-notification and bulk reads restore unread rows and retry controls
in both organization and personal streams, including body activation and a
fresh unread response. Bulk failures restore only the failed stream's captured
Expand Down