Skip to content
Open
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
171 changes: 171 additions & 0 deletions src/Exceptionless.Web/ClientApp/e2e/tests/tag-suggestions.e2e.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
import { expect, type Page, type Route, test } from '@playwright/test';

const ORGANIZATION_ID = '000000000000000000000001';

test('complete tag suggestions filter locally without changing selected tags', async ({ page }) => {
const requests: string[] = [];
const input = page.getByPlaceholder('Tag', { exact: true });
await test.step('arrange complete suggestions and an existing selection', async () => {
await page.clock.install();
await setup(page, async (route, aggregation) => {
requests.push(aggregation);
await route.fulfill({ json: tags(['Alpha', 'Beta']) });
});
});
await test.step('filter a complete cache locally while preserving the selection', async () => {
await page.goto('/next/event?tag=Selected&time=%5Bnow-24h%20TO%20now%5D&project=000000000000000000000003');
await page.getByRole('button', { name: /^Tag\s+Selected/ }).click();
await expect(page.getByRole('option', { exact: true, name: 'Alpha' })).toBeVisible();
await input.fill('Be');
await expect(page.getByRole('option', { exact: true, name: 'Beta' })).toBeVisible();
await expect(page.getByRole('option', { exact: true, name: 'Alpha' })).toHaveCount(0);
await page.clock.fastForward(450);
expect(requests).toEqual(['terms:(tags~251)']);
await expect(page).toHaveURL(/[?&]tag=Selected/);
});
await test.step('reopen with an empty search and cached options', async () => {
await input.press('Escape');
await page.getByRole('button', { name: /^Tag\s+Selected/ }).click();
await expect(input).toHaveValue('');
await expect(page.getByRole('option', { exact: true, name: 'Alpha' })).toBeVisible();
expect(requests).toHaveLength(1);
await input.press('Escape');
});
await test.step('reuse suggestions after date and project filters change', async () => {
await page.getByRole('button', { exact: true, name: 'Date Last 24 hours' }).click();
await page.getByRole('button', { exact: true, name: 'Last 7 days' }).click();
await expect(page.getByRole('button', { exact: true, name: 'Date Last 7 days' })).toBeVisible();
await expect(page).not.toHaveURL(/[?&]time=/);
await page
.getByRole('button', { name: /^Project/ })
.first()
.click();
const projectSearch = page.getByPlaceholder('Project', { exact: true });
await projectSearch.fill('One');
await projectSearch.press('Escape');
await page
.getByRole('button', { name: /^Project/ })
.first()
.click();
await expect(projectSearch).toHaveValue('');
await page.getByRole('option', { exact: true, name: 'Project One' }).click();
await expect(page).not.toHaveURL(/[?&]project=/);
await page.keyboard.press('Escape');
await page.getByRole('button', { name: /^Tag\s+Selected/ }).click();
await page.clock.fastForward(450);
expect(requests).toHaveLength(1);
});
});

test('incomplete suggestions debounce remote search, reuse cache and preserve selections through failure', async ({ page }) => {
const requests: string[] = [];
const input = page.getByPlaceholder('Tag', { exact: true });
let searchFailed = false;
await test.step('arrange truncated suggestions and one transient search failure', async () => {
await page.clock.install();
await setup(page, async (route, aggregation) => {
requests.push(aggregation);
if (aggregation === 'terms:(tags~251)') {
await route.fulfill({ json: tags(['Common'], 1) });
} else if (aggregation.includes('[fF][aA][iI][lL]')) {
if (!searchFailed) {
searchFailed = true;
await route.fulfill({ json: { status: 503, title: 'Unavailable' }, status: 503 });
} else {
await route.fulfill({ json: tags(['Failover']) });
}
} else {
await route.fulfill({ json: tags(['RareTag']) });
}
});
});
await test.step('debounce searches and add a tag without dropping the selection', async () => {
await page.goto('/next/event?tag=Selected');
await page.getByRole('button', { name: /^Tag\s+Selected/ }).click();
await expect(page.getByRole('option', { exact: true, name: 'Common' })).toBeVisible();
await input.fill('R');
await page.clock.fastForward(350);
expect(requests).toHaveLength(1);
await input.fill('Ra');
await input.fill('Rar');
await input.fill('Rare');
await page.clock.fastForward(350);
await expect(page.getByRole('option', { exact: true, name: 'RareTag' })).toBeVisible();
expect(requests).toHaveLength(2);
await page.getByRole('option', { exact: true, name: 'RareTag' }).click();
await expect(page).toHaveURL(/RareTag/);
expect(requests).toHaveLength(2);
});
await test.step('preserve selections through failure and explicit retry', async () => {
await input.fill('fail');
await page.clock.fastForward(350);
await expect(page.getByText('Could not load tags.')).toBeVisible();
await expect(page.getByRole('button', { exact: true, name: 'Retry' })).toBeVisible();
await expect(page).toHaveURL(/Selected/);
await expect(page).toHaveURL(/RareTag/);
await page.getByRole('button', { exact: true, name: 'Retry' }).click();
await expect(page.getByRole('option', { exact: true, name: 'Failover' })).toBeVisible();
});
await test.step('reuse the previously fetched search', async () => {
await input.fill('Rare');
await page.clock.fastForward(350);
await expect(page.getByRole('option', { exact: true, name: 'RareTag' })).toBeVisible();
await page.clock.fastForward(350);
expect(requests).toHaveLength(4);
});
});

async function setup(page: Page, handleTags: (route: Route, aggregation: string) => Promise<void>) {
page.setDefaultTimeout(10000);
await page.addInitScript((organizationId) => {
localStorage.setItem('satellizer_token', 'synthetic-tag-test-token');
localStorage.setItem('organization', JSON.stringify(organizationId));
}, ORGANIZATION_ID);
await page.route('**/health', (route) => route.fulfill({ body: 'OK' }));
await page.route('**/api/v2/**', async (route) => {
const url = new URL(route.request().url());
const aggregation = url.searchParams.get('aggregations');
if (aggregation?.startsWith('terms:(tags~')) {
expect(url.pathname).toBe(`/api/v2/organizations/${ORGANIZATION_ID}/events/count`);
expect(url.searchParams.get('filter')).toBeNull();
expect(url.searchParams.get('time')).toBe('all');
await handleTags(route, aggregation);
} else if (url.pathname === '/api/v2/users/me') {
await route.fulfill({
json: {
email_address: 'tags@example.test',
full_name: 'Test User',
id: '000000000000000000000002',
is_active: true,
is_email_address_verified: true,
organization_ids: [ORGANIZATION_ID],
organization_preferences: [],
roles: []
}
});
} else if (url.pathname === '/api/v2/organizations' || url.pathname === `/api/v2/organizations/${ORGANIZATION_ID}`) {
const organization = { features: [], id: ORGANIZATION_ID, name: 'Test Organization', plan_id: 'EX_UNLIMITED', plan_name: 'Unlimited' };
await route.fulfill({ json: url.pathname === '/api/v2/organizations' ? [organization] : organization });
} else if (url.pathname.endsWith('/projects')) {
await route.fulfill({ json: [{ id: '000000000000000000000003', name: 'Project One', organization_id: ORGANIZATION_ID }] });
} else if (url.pathname === '/api/v2/assistant/access') {
await route.fulfill({ json: { enabled: false, has_access: false } });
} else if (url.pathname.endsWith('/count')) {
await route.fulfill({ json: { aggregations: {}, total: 0 } });
} else {
await route.fulfill({ json: [] });
}
});
}

function tags(values: string[], omitted = 0) {
return {
aggregations: {
terms_tags: {
data: { '@type': 'bucket', ...(omitted ? { SumOtherDocCount: omitted } : {}) },
items: values.map((key) => ({ key, total: 1 }))
}
},
total: values.length
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import { SvelteSet } from 'svelte/reactivity';
import type { EventSummaryModel, SummaryTemplateKeys } from './components/summary/index';
import type { PersistentEvent } from './models';

import { TAG_SUGGESTION_STALE_TIME, tagSuggestionAggregation, tagSuggestionSession } from './tag-suggestions';

export interface OrganizationEventNotificationRefresher {
cancel: () => void;
schedule: (organizationId?: string, refreshImmediately?: boolean) => void;
Expand Down Expand Up @@ -114,6 +116,7 @@ export const queryKeys = {
stackEvents: (id: string | undefined, params?: GetStackEventsRequest['params']) => [...queryKeys.stacks(id), 'events', params] as const,
stacks: (id: string | undefined) => [...queryKeys.type, 'stacks', id] as const,
stacksCount: (id: string | undefined, params?: GetStackCountRequest['params']) => [...queryKeys.stacks(id), 'count', params] as const,
tagSuggestions: (organizationId: string | undefined, search: string, session: number) => ['EventTagSuggestions', organizationId, search, session] as const,
type: ['PersistentEvent'] as const
};

Expand Down Expand Up @@ -283,6 +286,12 @@ export interface GetStackEventsRequest {
};
}

export interface GetTagSuggestionsRequest {
enabled?: () => boolean;
params: { search: string };
route: { organizationId: string | undefined };
}

export function createEventWithNavigationQueryOptions(request: GetEventRequest, queryClient: QueryClient) {
const eventId = request.route.id;
const params = request.params
Expand Down Expand Up @@ -647,6 +656,32 @@ export function getStackEventsQuery(request: GetStackEventsRequest) {
}));
}

export function getTagSuggestionsQuery(request: GetTagSuggestionsRequest) {
return createQuery<CountResult, ProblemDetails>(() => {
const organizationId = request.route.organizationId;
const search = request.params.search;
const session = tagSuggestionSession(accessToken.current);

return {
enabled: !!accessToken.current && !!organizationId && (request.enabled?.() ?? true),
queryFn: async ({ signal }) => {
const response = await useFetchClient().getJSON<CountResult>(`/organizations/${organizationId}/events/count`, {
params: {
aggregations: tagSuggestionAggregation(search),
time: 'all'
},
signal
});
return response.data!;
},
queryKey: queryKeys.tagSuggestions(organizationId, search, session),
refetchOnWindowFocus: false,
retry: false,
staleTime: TAG_SUGGESTION_STALE_TIME
};
});
}

export function retainPreviousOrganizationQueryData<T>(
previousData: T | undefined,
previousQueryKey: readonly unknown[] | undefined,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,63 +2,104 @@
import type { FacetedFilterProps } from '$comp/faceted-filter';

import * as FacetedFilter from '$comp/faceted-filter';
import { getOrganizationCountQuery } from '$features/events/api.svelte';
import { Button } from '$comp/ui/button';
import { getTagSuggestionsQuery } from '$features/events/api.svelte';
import { TAG_SUGGESTION_LIMIT, tagSuggestions } from '$features/events/tag-suggestions';
import { organization } from '$features/organizations/context.svelte';
import { terms } from '$features/shared/api/aggregations';

import { TagFilter } from './models.svelte';

let { filter, filterChanged, filterRemoved, open = $bindable(false), title = 'Tag', ...props }: FacetedFilterProps<TagFilter> = $props();
let search = $state('');
let debouncedSearch = $state('');
const normalizedSearch = $derived(search.trim().toLowerCase());

function toggleHidden() {
filter.hidden = !filter.hidden;
filterChanged(filter);
}

// Store the organizationId to prevent loading when switching organizations.
const organizationId = organization.current;

// Create query with conditional enabled - only fetch when dropdown is open
const countQuery = getOrganizationCountQuery({
const initialQuery = getTagSuggestionsQuery({
enabled: () => open,
params: {
aggregations: 'terms:tags'
search: ''
},
route: {
get organizationId() {
return organizationId;
return organization.current;
}
}
});

const tags = $derived(Array.from(new Set(['Critical', ...(terms(countQuery.data?.aggregations, 'terms_tags')?.buckets?.map((tag) => tag.key) ?? [])])));
const initial = $derived(tagSuggestions(initialQuery.data));
const searchQuery = getTagSuggestionsQuery({
enabled: () => open && initialQuery.isSuccess && !initial.complete && debouncedSearch.length >= 2 && debouncedSearch === normalizedSearch,
params: {
get search() {
return debouncedSearch;
}
},
route: {
get organizationId() {
return organization.current;
}
}
});
const remoteSearch = $derived(!initial.complete && normalizedSearch.length >= 2);
const currentSearch = $derived(debouncedSearch === normalizedSearch);
const result = $derived(remoteSearch && currentSearch && searchQuery.isSuccess ? tagSuggestions(searchQuery.data) : initial);
const options = $derived(
tags.map((tag) => ({
label: tag,
value: tag
})) ?? []
Array.from(new Set(['Critical', ...filter.value, ...result.tags]))
.filter((tag) => tag.toLowerCase().includes(normalizedSearch))
.slice(0, TAG_SUGGESTION_LIMIT)
.map((tag) => ({
label: tag,
value: tag
}))
);
const loading = $derived(open && (initialQuery.isFetching || (remoteSearch && (!currentSearch || searchQuery.isFetching))));
const failed = $derived(initialQuery.isError || (remoteSearch && currentSearch && searchQuery.isError));

$effect(() => {
if (!countQuery.isSuccess || filter.value.length === 0) {
return;
const statusMessage = $derived.by(() => {
if (loading) {
return 'Searching tags…';
}

if (!initial.complete && normalizedSearch.length < 2) {
return 'Showing up to 250 tags. Type at least two characters to search all tags.';
}

if (options.length === 0) {
return 'No matching tags found.';
}

const selectedTags = tags.filter((tag) => filter.value.includes(tag));
if (filter.value.length !== selectedTags.length) {
filter.value = selectedTags.map((tag) => tag);
filterChanged(filter);
if (remoteSearch && result.tags.length === TAG_SUGGESTION_LIMIT) {
return 'Showing up to 250 tags. Type more to narrow.';
}
return undefined;
});

$effect(() => {
const value = normalizedSearch;
if (!open) {
debouncedSearch = '';
return;
Comment on lines +78 to +80

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Clear the search text when closing the tag picker

When a user types a query and closes the picker, this branch clears only debouncedSearch; the bound search state retains the query. Reopening the picker therefore immediately filters the suggestions by the previous text and may launch another remote lookup instead of showing the full tag list as it did previously. Reset search when open becomes false.

Useful? React with 👍 / 👎.

}
const timer = setTimeout(() => {
debouncedSearch = value;
}, 300);
return () => clearTimeout(timer);
});

function toggleHidden() {
filter.hidden = !filter.hidden;
filterChanged(filter);
}
</script>

<FacetedFilter.MultiSelect
bind:open
bind:search
shouldFilter={false}
changed={(values: string[]) => {
filter.value = values;
filterChanged(filter);
}}
loading={countQuery.isLoading}
{loading}
{options}
remove={() => {
filter.value = [];
Expand All @@ -69,4 +110,23 @@
{toggleHidden}
values={filter.value}
{...props}
></FacetedFilter.MultiSelect>
>
{#snippet status()}
{#if failed || statusMessage}
<div class="text-muted-foreground px-3 py-2 text-xs" role="status">
{#if failed}
Could not load tags.
<Button
size="sm"
variant="link"
onclick={() => {
void (initialQuery.isError ? initialQuery.refetch() : searchQuery.refetch());
}}>Retry</Button
>
{:else}
{statusMessage}
{/if}
</div>
{/if}
{/snippet}
</FacetedFilter.MultiSelect>
Loading
Loading