diff --git a/ui-react/src/__tests__/autocomplete-comboboxes.test.tsx b/ui-react/src/__tests__/autocomplete-comboboxes.test.tsx index d4704309..a55a31d5 100644 --- a/ui-react/src/__tests__/autocomplete-comboboxes.test.tsx +++ b/ui-react/src/__tests__/autocomplete-comboboxes.test.tsx @@ -88,7 +88,7 @@ describe('StandardVariableCombobox', () => { expect(screen.getByRole('combobox')).not.toBeDisabled(); }); - it('shows selected human-readable description when a value is provided', async () => { + it('shows the humanized title when a value is provided', async () => { const selected = { id: 'https://w3id.org/okn/i/mint/sv1', label: 'Precipitation', @@ -99,7 +99,7 @@ describe('StandardVariableCombobox', () => { }); // Wait for loading to complete await waitFor(() => { - expect(screen.getByText('Amount of precipitation')).toBeInTheDocument(); + expect(screen.getByRole('combobox')).toHaveTextContent('Precipitation'); }); }); diff --git a/ui-react/src/components/autocomplete/StandardVariableCombobox.tsx b/ui-react/src/components/autocomplete/StandardVariableCombobox.tsx index 65a491b7..de5d7e27 100644 --- a/ui-react/src/components/autocomplete/StandardVariableCombobox.tsx +++ b/ui-react/src/components/autocomplete/StandardVariableCombobox.tsx @@ -16,11 +16,11 @@ import * as React from 'react'; import { Check, ChevronsUpDown, Plus } from 'lucide-react'; import { cn } from '@/lib/utils'; -import { humanizeStandardVariable } from '@/lib/standard-variable-grammar'; import { + dedupeStandardVariables, isUnlabeledStandardVariable, standardVariableDescription, - standardVariableName, + standardVariableTitle, } from '@/lib/standard-variable-display'; import { useSemanticSearch } from '@/hooks/useSemanticSearch'; import { Button } from '@/components/ui/button'; @@ -127,16 +127,27 @@ export function StandardVariableCombobox({ const options = narrowed && !showAll ? scoped : all; const semanticSearch = useSemanticSearch(search, { target: 'svo', limit: 50 }); - const semanticOptions = React.useMemo( - () => - semanticSearch.results?.map((result) => ({ + const knownById = React.useMemo( + () => new Map([...all, ...scoped].map((o) => [o.id, o])), + [all, scoped], + ); + const semanticOptions = React.useMemo(() => { + if (!semanticSearch.results) return null; + // The service can answer with an empty label (or only a description) for a + // row the catalog names; take the catalog's label so the option has a title. + const mapped = semanticSearch.results.map((result) => { + const known = knownById.get(result.id); + return { id: result.id, - label: result.label ?? '', - description: result.description ?? null, + label: result.label?.trim() || known?.label || '', + description: result.description ?? known?.description ?? null, models: Array.isArray(result.models) ? result.models : [], - })) ?? null, - [semanticSearch.results], - ); + }; + }); + // One row per id, and one per label: the service can return the same + // variable under a catalog id and under an adapter URI. + return dedupeStandardVariables(mapped, { byLabel: true }); + }, [semanticSearch.results, knownById]); /** * Semantic results are ranked over the whole catalog, so the scope has to be @@ -160,7 +171,7 @@ export function StandardVariableCombobox({ * a control that reads as empty. */ const visibleOptions = React.useMemo(() => { - const listed = rankedOptions ?? options; + const listed = dedupeStandardVariables(rankedOptions ?? options); const base = requireLabel ? listed.filter((o) => !isUnlabeledStandardVariable(o)) : listed; // Semantic search results already have a query-specific ranking. Apply the // task/goal ranking only to the unfiltered catalog list. @@ -196,15 +207,7 @@ export function StandardVariableCombobox({ [value, visibleOptions, all, onChange], ); - const triggerLabel = !value - ? placeholder - : (standardVariableDescription(value) ?? - (isUnlabeledStandardVariable(value) - ? standardVariableName(value) - : (() => { - const { phenomenon, property } = humanizeStandardVariable(value.label); - return phenomenon ? `${phenomenon} — ${property}` : property; - })())); + const triggerLabel = !value ? placeholder : standardVariableTitle(value); return ( <> @@ -270,21 +273,12 @@ export function StandardVariableCombobox({ )} />
+ {standardVariableTitle(sv)} {standardVariableDescription(sv) && ( - + {standardVariableDescription(sv)} )} - - {standardVariableName(sv)} - {!!sv.models?.length && ( {sv.models diff --git a/ui-react/src/components/autocomplete/__tests__/StandardVariableCombobox.create.test.tsx b/ui-react/src/components/autocomplete/__tests__/StandardVariableCombobox.create.test.tsx index 4b7bcb59..185b4853 100644 --- a/ui-react/src/components/autocomplete/__tests__/StandardVariableCombobox.create.test.tsx +++ b/ui-react/src/components/autocomplete/__tests__/StandardVariableCombobox.create.test.tsx @@ -94,7 +94,7 @@ describe('StandardVariableCombobox create', () => { description: null, }), ); - expect(screen.getByRole('combobox')).toHaveTextContent(/zzz_new/i); + expect(screen.getByRole('combobox')).toHaveTextContent(/zzz new/i); }); it('does not offer create unless asked to', async () => { diff --git a/ui-react/src/components/autocomplete/__tests__/StandardVariableCombobox.options.test.tsx b/ui-react/src/components/autocomplete/__tests__/StandardVariableCombobox.options.test.tsx new file mode 100644 index 00000000..8f0139eb --- /dev/null +++ b/ui-react/src/components/autocomplete/__tests__/StandardVariableCombobox.options.test.tsx @@ -0,0 +1,144 @@ +/** + * Every option leads with a readable title (the humanized label), shows its + * description as smaller secondary text, and is listed once. + */ +import { MockedProvider } from '@apollo/client/testing'; +import { render, screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { StandardVariableCombobox } from '@/components/autocomplete/StandardVariableCombobox'; +import { IndicatorAdapterInferenceDocument } from '@/components/autocomplete/useScopedStandardVariables'; +import { + GetIndicatorVariableOptionsDocument, + PrefetchReferenceDataDocument, +} from '@/graphql/generated/graphql'; + +const semantic = vi.hoisted(() => ({ + results: null as Array<{ + id: string; + label?: string | null; + description?: string | null; + }> | null, +})); +vi.mock('@/hooks/useSemanticSearch', () => ({ + useSemanticSearch: (query: string) => ({ + results: query.trim() ? semantic.results : null, + loading: false, + error: null, + }), +})); + +const sv = (id: string, label: string | null, description: string | null = null) => ({ + __typename: 'modelcatalog_standard_variable', + id, + label, + description, +}); + +const TERM_COUNT = 'https://w3id.org/okn/i/mint/document_lexicon_group__term_count'; +const DESCRIPTION = "For each document and lexicon group, how often the group's terms occur."; + +const catalogMock = { + request: { query: PrefetchReferenceDataDocument }, + result: { + data: { + modelcatalog_standard_variable: [ + sv(TERM_COUNT, 'document_lexicon_group__term_count', DESCRIPTION), + ], + modelcatalog_unit: [], + }, + }, +}; + +async function open(mocks: unknown[]) { + render( + + {}} scope="all" /> + , + ); + await userEvent.click(await screen.findByRole('combobox')); +} + +describe('StandardVariableCombobox option titles and repeats', () => { + beforeEach(() => { + semantic.results = null; + }); + + it('leads with the humanized label and keeps the description as secondary text', async () => { + await open([catalogMock]); + const title = await screen.findByText('Document lexicon group — Term count'); + expect(title).toHaveClass('font-medium'); + const description = screen.getByText(DESCRIPTION); + expect(description).toHaveClass('text-xs', 'line-clamp-1'); + expect(screen.getAllByRole('option')).toHaveLength(1); + }); + + it('gives a search hit with no label the catalog title, and lists each variable once', async () => { + // The service answers with an empty label, then again under the same id. + semantic.results = [ + { id: TERM_COUNT, label: '', description: DESCRIPTION }, + { id: TERM_COUNT, label: 'document_lexicon_group__term_count', description: null }, + ]; + await open([catalogMock]); + await userEvent.type(screen.getByPlaceholderText(/search standard variables/i), 'term'); + await waitFor(() => expect(screen.getAllByRole('option')).toHaveLength(1)); + expect(screen.getByText('Document lexicon group — Term count')).toBeInTheDocument(); + }); + + it('titles a search hit that has only an id from the id tail', async () => { + semantic.results = [{ id: 'https://w3id.org/okn/i/mint/air__daily_max_of_temperature' }]; + await open([catalogMock]); + await userEvent.type(screen.getByPlaceholderText(/search standard variables/i), 'air'); + expect(await screen.findByText('Air — Daily max of temperature')).toBeInTheDocument(); + }); + + it('lists a variable once when the catalog and an adapter contract both name it', async () => { + const ID = 'https://w3id.org/okn/i/mint/air__daily_max_of_temperature'; + const mocks = [ + { + request: { query: GetIndicatorVariableOptionsDocument }, + result: { + data: { + modelcatalog_dataset_specification_presentation: [ + { + __typename: 'modelcatalog_dataset_specification_presentation', + dataset_specification_id: 'ds', + presentation_id: 'p', + presentation: { + __typename: 'modelcatalog_variable_presentation', + id: 'p', + standard_variable: sv( + 'catalog-uuid-1', + 'air__daily_max_of_temperature', + 'Daily max', + ), + }, + }, + ], + }, + }, + }, + { + request: { query: IndicatorAdapterInferenceDocument }, + result: { + data: { + adapterTransforms: [ + { contracts: [{ role: 'output', standard_variable_uri: ID, format: null }] }, + ], + }, + }, + }, + ]; + render( + + {}} scope="indicator" /> + , + ); + await waitFor(() => expect(screen.getByRole('combobox')).toBeEnabled()); + await userEvent.click(screen.getByRole('combobox')); + expect(await screen.findByText('Air — Daily max of temperature')).toBeInTheDocument(); + expect(screen.getAllByRole('option')).toHaveLength(1); + expect(screen.getByText('Daily max')).toBeInTheDocument(); + }); +}); diff --git a/ui-react/src/components/autocomplete/__tests__/StandardVariableCombobox.scope.test.tsx b/ui-react/src/components/autocomplete/__tests__/StandardVariableCombobox.scope.test.tsx index 017abf45..126cdd83 100644 --- a/ui-react/src/components/autocomplete/__tests__/StandardVariableCombobox.scope.test.tsx +++ b/ui-react/src/components/autocomplete/__tests__/StandardVariableCombobox.scope.test.tsx @@ -310,29 +310,29 @@ describe('StandardVariableCombobox scope', () => { it('offers the whole catalog by default, so registration forms are unchanged', async () => { renderCombobox({}); await openList(); - await waitFor(() => expect(screen.getByText('drawdown')).toBeInTheDocument()); - expect(screen.getByText('100hr_dead_moisture')).toBeInTheDocument(); - expect(screen.getByText('soil__porosity')).toBeInTheDocument(); + await waitFor(() => expect(screen.getByText('Drawdown')).toBeInTheDocument()); + expect(screen.getByText('100hr dead moisture')).toBeInTheDocument(); + expect(screen.getByText('Soil — Porosity')).toBeInTheDocument(); }); it('places preferred variables before the alphabetical catalog order', async () => { renderCombobox({ preferredIds: ['sv-poro', 'sv-draw'] }); await openList(); - await waitFor(() => expect(screen.getByText('soil__porosity')).toBeInTheDocument()); + await waitFor(() => expect(screen.getByText('Soil — Porosity')).toBeInTheDocument()); const labels = screen.getAllByRole('option').map((option) => option.textContent); - expect(labels[0]).toContain('soil__porosity'); - expect(labels[1]).toContain('drawdown'); + expect(labels[0]).toContain('Soil — Porosity'); + expect(labels[1]).toContain('Drawdown'); }); it('offers only producible variables under scope="indicator"', async () => { renderCombobox({ scope: 'indicator' }); await openList(); - await waitFor(() => expect(screen.getByText('drawdown')).toBeInTheDocument()); + await waitFor(() => expect(screen.getByText('Drawdown')).toBeInTheDocument()); // Reaches no model, so it must not be offered. - expect(screen.queryByText('100hr_dead_moisture')).not.toBeInTheDocument(); + expect(screen.queryByText('100hr dead moisture')).not.toBeInTheDocument(); // An input-only variable is not an indicator either. - expect(screen.queryByText('soil__porosity')).not.toBeInTheDocument(); + expect(screen.queryByText('Soil — Porosity')).not.toBeInTheDocument(); }); it('offers SVOs produced by registered adapter transforms as outcomes', async () => { @@ -342,25 +342,25 @@ describe('StandardVariableCombobox scope', () => { , ); await openList(); - await waitFor(() => expect(screen.getByText('spring__volume_flow_rate')).toBeInTheDocument()); + await waitFor(() => expect(screen.getByText('Spring — Volume flow rate')).toBeInTheDocument()); }); it('unions inputs and parameter-adjusted variables under scope="driver"', async () => { renderCombobox({ scope: 'driver' }); await openList(); // soil__porosity arrives through inputs, drawdown through a parameter. - await waitFor(() => expect(screen.getByText('soil__porosity')).toBeInTheDocument()); - expect(screen.getByText('drawdown')).toBeInTheDocument(); - expect(screen.queryByText('100hr_dead_moisture')).not.toBeInTheDocument(); + await waitFor(() => expect(screen.getByText('Soil — Porosity')).toBeInTheDocument()); + expect(screen.getByText('Drawdown')).toBeInTheDocument(); + expect(screen.queryByText('100hr dead moisture')).not.toBeInTheDocument(); }); it('infers drivers from a selected outcome across model and ETL steps', async () => { renderCombobox({ scope: 'driver', driverOutcomeId: 'sv-draw' }); await openList(); - await waitFor(() => expect(screen.getByText('middle')).toBeInTheDocument()); - expect(screen.getByText('sv-forcing')).toBeInTheDocument(); - expect(screen.queryByText('soil__porosity')).not.toBeInTheDocument(); - expect(screen.queryByText('drawdown')).not.toBeInTheDocument(); + await waitFor(() => expect(screen.getByText('Middle')).toBeInTheDocument()); + expect(screen.getByText('Sv-forcing')).toBeInTheDocument(); + expect(screen.queryByText('Soil — Porosity')).not.toBeInTheDocument(); + expect(screen.queryByText('Drawdown')).not.toBeInTheDocument(); }); it('limits outcome inference to the selected model configurations', async () => { @@ -370,8 +370,8 @@ describe('StandardVariableCombobox scope', () => { driverConfigurationIds: ['cfg-outcome'], }); await openList(); - await waitFor(() => expect(screen.getByText('middle')).toBeInTheDocument()); - expect(screen.queryByText('air__temperature')).not.toBeInTheDocument(); + await waitFor(() => expect(screen.getByText('Middle')).toBeInTheDocument()); + expect(screen.queryByText('Air — Temperature')).not.toBeInTheDocument(); }); it('falls back to outcome-producing models when a retained model is incompatible', async () => { @@ -381,9 +381,9 @@ describe('StandardVariableCombobox scope', () => { driverConfigurationIds: ['cfg-incompatible'], }); await openList(); - await waitFor(() => expect(screen.getByText('middle')).toBeInTheDocument()); - expect(screen.getByText('air__temperature')).toBeInTheDocument(); - expect(screen.queryByText('only_incompatible')).not.toBeInTheDocument(); + await waitFor(() => expect(screen.getByText('Middle')).toBeInTheDocument()); + expect(screen.getByText('Air — Temperature')).toBeInTheDocument(); + expect(screen.queryByText('Only incompatible')).not.toBeInTheDocument(); }); it('keeps model inference when the optional adapter registry is unavailable', async () => { @@ -412,20 +412,20 @@ describe('StandardVariableCombobox scope', () => { , ); await openList(); - await waitFor(() => expect(screen.getByText('middle')).toBeInTheDocument()); - expect(screen.queryByText('air__temperature')).not.toBeInTheDocument(); - expect(screen.queryByText('soil__porosity')).not.toBeInTheDocument(); + await waitFor(() => expect(screen.getByText('Middle')).toBeInTheDocument()); + expect(screen.queryByText('Air — Temperature')).not.toBeInTheDocument(); + expect(screen.queryByText('Soil — Porosity')).not.toBeInTheDocument(); }); it('widens to the whole catalog when the escape link is clicked', async () => { renderCombobox({ scope: 'indicator', scopeLabel: 'a model produces' }); const user = await openList(); - await waitFor(() => expect(screen.getByText('drawdown')).toBeInTheDocument()); - expect(screen.queryByText('100hr_dead_moisture')).not.toBeInTheDocument(); + await waitFor(() => expect(screen.getByText('Drawdown')).toBeInTheDocument()); + expect(screen.queryByText('100hr dead moisture')).not.toBeInTheDocument(); await user.click(screen.getByRole('button', { name: /show every standard variable/i })); - await waitFor(() => expect(screen.getByText('100hr_dead_moisture')).toBeInTheDocument()); + await waitFor(() => expect(screen.getByText('100hr dead moisture')).toBeInTheDocument()); }); it('names the scope and its size in the escape link', async () => { @@ -446,9 +446,9 @@ describe('StandardVariableCombobox scope', () => { value: { id: 'sv-dead', label: '100hr_dead_moisture', description: null }, }); await openList(); - await waitFor(() => expect(screen.getByText('drawdown')).toBeInTheDocument()); + await waitFor(() => expect(screen.getByText('Drawdown')).toBeInTheDocument()); // The trigger also prints the stored label, so assert on the option row. const options = screen.getAllByRole('option').map((o) => o.textContent); - expect(options).toContain('100hr_dead_moisture'); + expect(options).toContain('100hr dead moisture'); }); }); diff --git a/ui-react/src/components/autocomplete/__tests__/StandardVariableCombobox.unlabeled.test.tsx b/ui-react/src/components/autocomplete/__tests__/StandardVariableCombobox.unlabeled.test.tsx index fca2d4c7..b32a6893 100644 --- a/ui-react/src/components/autocomplete/__tests__/StandardVariableCombobox.unlabeled.test.tsx +++ b/ui-react/src/components/autocomplete/__tests__/StandardVariableCombobox.unlabeled.test.tsx @@ -44,14 +44,14 @@ describe('StandardVariableCombobox unlabeled rows', () => { it('shows a readable name, never the bare id', async () => { await open(); expect(await screen.findByText('…83d62379 (no label)')).toBeInTheDocument(); - expect(screen.getByText('drawdown')).toBeInTheDocument(); + expect(screen.getByText('Drawdown')).toBeInTheDocument(); expect(screen.queryByText(/Catalog ID/)).not.toBeInTheDocument(); expect(screen.queryByText(UUID)).not.toBeInTheDocument(); }); it('leaves unlabeled rows out when the caller needs a label', async () => { await open({ requireLabel: true }); - expect(await screen.findByText('drawdown')).toBeInTheDocument(); + expect(await screen.findByText('Drawdown')).toBeInTheDocument(); expect(screen.queryByText(/no label/)).not.toBeInTheDocument(); }); }); diff --git a/ui-react/src/components/autocomplete/useScopedStandardVariables.ts b/ui-react/src/components/autocomplete/useScopedStandardVariables.ts index f75f671f..8c49ef6f 100644 --- a/ui-react/src/components/autocomplete/useScopedStandardVariables.ts +++ b/ui-react/src/components/autocomplete/useScopedStandardVariables.ts @@ -46,7 +46,10 @@ import { type InferenceTransformKind, type VariableTransform, } from '@/lib/modeling/outcome-driver-inference'; -import { UNNAMED_STANDARD_VARIABLE } from '@/lib/standard-variable-display'; +import { + UNNAMED_STANDARD_VARIABLE, + standardVariableLabelKey, +} from '@/lib/standard-variable-display'; import { slugFromUri } from '@/lib/uri'; export type StandardVariableScope = 'all' | 'indicator' | 'driver'; @@ -398,7 +401,15 @@ export function useScopedStandardVariables( return { id, label: slugFromUri(id), description: null }; }), ); - return dedupe([...rows.map((r) => r.presentation.standard_variable), ...adapterOutputs]); + const catalog = dedupe(rows.map((r) => r.presentation.standard_variable)); + // An adapter contract names a variable by URI slug, and the catalog holds + // the same variable under its own id. Keep the catalog row, which carries + // the description, and add only the adapter outputs it does not already list. + const listed = new Set(catalog.map((o) => standardVariableLabelKey(o))); + return dedupe([ + ...catalog, + ...adapterOutputs.filter((o) => !listed.has(standardVariableLabelKey(o))), + ]); } if (scope === 'driver') { const inputs = driverQ.data?.inputs ?? []; diff --git a/ui-react/src/lib/standard-variable-display.ts b/ui-react/src/lib/standard-variable-display.ts index 40ec48a5..de397196 100644 --- a/ui-react/src/lib/standard-variable-display.ts +++ b/ui-react/src/lib/standard-variable-display.ts @@ -1,3 +1,5 @@ +import { humanizeStandardVariable } from '@/lib/standard-variable-grammar'; + /** * How a standard variable reads in a list. * @@ -41,3 +43,42 @@ export function standardVariableDescription(sv: VariableLike): string | null { const text = (sv.description ?? '').trim(); return text && !text.startsWith(CATALOG_ID_PREFIX) ? text : null; } + +/** + * The title an option leads with: the label, humanized ("Document lexicon group + * — Term count" from `document_lexicon_group__term_count`). A row with no label + * borrows the id's tail when that is grammar-shaped, else reads as unnamed. + */ +export function standardVariableTitle(sv: VariableLike): string { + const source = isUnlabeledStandardVariable(sv) ? idTail(sv.id) : sv.label!.trim(); + if (isUnlabeledStandardVariable(sv) && !source.includes('__')) return standardVariableName(sv); + const { phenomenon, property } = humanizeStandardVariable(source); + if (phenomenon) return `${phenomenon} — ${property}`; + // Not grammar (no `__`): the label is the whole name, so only spell out its joiners. + const spaced = property.replace(/[~_]+/g, ' ').replace(/\s+/g, ' ').trim(); + return spaced.charAt(0).toUpperCase() + spaced.slice(1); +} + +/** A key that makes two rows naming the same variable collide; null for unlabeled rows. */ +export function standardVariableLabelKey(sv: VariableLike): string | null { + return isUnlabeledStandardVariable(sv) ? null : sv.label!.trim().toLowerCase(); +} + +/** Drop repeats by id, then (for labeled rows) by label, keeping the first seen. */ +export function dedupeStandardVariables( + rows: ReadonlyArray, + { byLabel = false }: { byLabel?: boolean } = {}, +): T[] { + const ids = new Set(); + const labels = new Set(); + const kept: T[] = []; + for (const row of rows) { + if (ids.has(row.id)) continue; + const key = byLabel ? standardVariableLabelKey(row) : null; + if (key !== null && labels.has(key)) continue; + ids.add(row.id); + if (key !== null) labels.add(key); + kept.push(row); + } + return kept; +} diff --git a/ui-react/src/pages/modeling/thread/wizard/ModelsStep.tsx b/ui-react/src/pages/modeling/thread/wizard/ModelsStep.tsx index 1b614b33..2b6c0a46 100644 --- a/ui-react/src/pages/modeling/thread/wizard/ModelsStep.tsx +++ b/ui-react/src/pages/modeling/thread/wizard/ModelsStep.tsx @@ -130,6 +130,31 @@ function rowFromConfig(cfg: ModelConfigInfo | ModelSetupInfo, parent?: ModelConf }; } +type OutcomeMatch = 'produces' | 'transforms'; + +/** The part of a standard-variable id or label that names it, lower-cased. */ +function outcomeName(value: string): string { + return slugFromUri(value.trim()).toLowerCase(); +} + +/** + * True when the row declares the outcome as one of its outputs. The id is + * compared first; the name (the URI slug or the label) bridges a flow whose + * output was registered under another namespace for the same variable. + */ +function rowProducesOutcome( + row: Pick, + outcome: string, + outcomeLabel?: string | null, +): boolean { + if (row.producesIds.includes(outcome)) return true; + const names = new Set([outcomeName(outcome), outcomeLabel ? outcomeName(outcomeLabel) : '']); + names.delete(''); + return [...row.producesIds, ...row.producesLabels].some( + (value) => value && names.has(outcomeName(value)), + ); +} + function flattenToRows( data: ReturnType['data'], ): ModelRow[] { @@ -153,10 +178,15 @@ function ModelCard({ row, checked, onToggle, + outcomeMatch, + outcomeLabel, }: { row: ModelRow; checked: boolean; onToggle: (id: string, checked: boolean) => void; + /** How the row reaches the chosen outcome, when one is chosen. */ + outcomeMatch?: OutcomeMatch | null; + outcomeLabel?: string | null; }) { // Asked only for a flow, and only once per flow per session. An unanswered or // failed check leaves the card pickable: plan and submit still refuse correctly. @@ -185,6 +215,19 @@ function ModelCard({ {row.name} {row.isFlow && }
+ {outcomeMatch && outcomeLabel && ( +
+ {outcomeMatch === 'produces' + ? `Produces ${outcomeLabel}` + : `Can be transformed into ${outcomeLabel}`} +
+ )} {row.takesCollection && (
Takes a set of files as one input
)} @@ -711,9 +754,11 @@ export function ModelsStep({ const indicatorRows = useMemo( () => indicator - ? allRows.filter((r) => r.producesIds.includes(indicator) || inferredModelIds.has(r.id)) + ? allRows.filter( + (r) => rowProducesOutcome(r, indicator, indicatorLabel) || inferredModelIds.has(r.id), + ) : allRows, - [allRows, indicator, inferredModelIds], + [allRows, indicator, indicatorLabel, inferredModelIds], ); const dataFeasibleRows = useMemo(() => { if (!hasRegionGeometry || availabilityLoading || availabilityError) return indicatorRows; @@ -756,23 +801,47 @@ export function ModelsStep({ ); }, [dataFilteredRows, searchText]); - const searchedRows = useMemo(() => { + const matchedRows = useMemo(() => { if (!debouncedSearchText.trim() || !semanticSearch.results) return localSearchedRows; const rankById = new Map(semanticSearch.results.map((result, index) => [result.id, index])); + const semanticRank = (row: ModelRow) => + Math.min( + Infinity, + ...row.searchIds + .map((id) => rankById.get(id)) + .filter((rank): rank is number => rank !== undefined), + ); + // The index may not carry a row (a flow's outputs, for one), so a row the + // plain text filter finds is kept and follows the semantic hits. + const found = new Set(localSearchedRows.map((row) => row.id)); return dataFilteredRows - .map((row) => ({ - row, - rank: Math.min( - ...row.searchIds - .map((id) => rankById.get(id)) - .filter((rank): rank is number => rank !== undefined), - ), - })) - .filter((item) => Number.isFinite(item.rank)) - .sort((a, b) => a.rank - b.rank) + .map((row) => ({ row, rank: semanticRank(row) })) + .filter((item) => Number.isFinite(item.rank) || found.has(item.row.id)) + .sort((a, b) => (a.rank === b.rank ? 0 : a.rank < b.rank ? -1 : 1)) .map((item) => item.row); }, [dataFilteredRows, debouncedSearchText, localSearchedRows, semanticSearch.results]); + // Rows that declare the outcome as an output come first, models and flows + // alike, whatever the search ranked them; then the rows reachable by a + // transform. The sort is stable, so each group keeps its own order. + const outcomeMatchById = useMemo(() => { + const matches = new Map(); + if (!indicator) return matches; + for (const row of allRows) { + if (rowProducesOutcome(row, indicator, indicatorLabel)) matches.set(row.id, 'produces'); + else if (inferredModelIds.has(row.id)) matches.set(row.id, 'transforms'); + } + return matches; + }, [allRows, indicator, indicatorLabel, inferredModelIds]); + const searchedRows = useMemo(() => { + if (outcomeMatchById.size === 0) return matchedRows; + const tier = (row: ModelRow) => { + const match = outcomeMatchById.get(row.id); + return match === 'produces' ? 0 : match === 'transforms' ? 1 : 2; + }; + return [...matchedRows].sort((a, b) => tier(a) - tier(b)); + }, [matchedRows, outcomeMatchById]); + const threadRegionId = thread.region_id ?? null; const { regionRows, otherRows } = useMemo(() => { if (!threadRegionId) return { regionRows: searchedRows, otherRows: [] as ModelRow[] }; @@ -793,10 +862,10 @@ export function ModelsStep({ return allRows.filter( (row) => selected.has(row.id) && - !row.producesIds.includes(indicator) && + !rowProducesOutcome(row, indicator, indicatorLabel) && !inferredModelIds.has(row.id), ); - }, [allRows, indicator, inferredModelIds, selectedIds]); + }, [allRows, indicator, indicatorLabel, inferredModelIds, selectedIds]); const toggleModel = useCallback((id: string, checked: boolean) => { setSelectedIds((prev) => { @@ -1023,6 +1092,8 @@ export function ModelsStep({ row={row} checked={selectedIds.has(row.id)} onToggle={toggleModel} + outcomeMatch={outcomeMatchById.get(row.id) ?? null} + outcomeLabel={indicatorLabel} /> )) )} diff --git a/ui-react/src/pages/modeling/thread/wizard/__tests__/ModelsStepOutcomeRanking.test.tsx b/ui-react/src/pages/modeling/thread/wizard/__tests__/ModelsStepOutcomeRanking.test.tsx new file mode 100644 index 00000000..eac71e6f --- /dev/null +++ b/ui-react/src/pages/modeling/thread/wizard/__tests__/ModelsStepOutcomeRanking.test.tsx @@ -0,0 +1,169 @@ +/** + * Choosing an outcome ranks the rows that produce it first, flows included, + * then the rows that can be transformed into it, and says why on each card. + */ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import type { MockedResponse } from '@apollo/client/testing'; +import userEvent from '@testing-library/user-event'; +import { renderWithProviders, screen, waitFor } from '@/test/utils/render'; +import { GetModelTreeWithRegionsDocument, type Thread } from '@/graphql/generated/modeling'; +import { ModelOutcomeAdapterInferenceDocument, ModelsStep } from '../ModelsStep'; + +vi.mock('@/components/ui/use-toast', () => ({ useToast: () => ({ toast: vi.fn() }) })); +vi.mock('@/hooks/useFlowAvailability', () => ({ useFlowAvailability: () => null })); + +const semantic = vi.hoisted(() => ({ + results: null as Array<{ id: string }> | null, +})); +vi.mock('@/hooks/useSemanticSearch', () => ({ + useSemanticSearch: (query: string) => ({ + results: query.trim() ? semantic.results : null, + loading: false, + error: null, + }), +})); + +const REPORT = 'https://w3id.org/okn/i/mint/document_collection__sensemaking_report'; +const RAW = 'https://w3id.org/okn/i/mint/document_collection__raw_text'; + +function config(id: string, label: string, outId: string, outLabel: string, isFlow = false) { + return { + id, + label, + ...(isFlow ? { flow: { __typename: 'x', configuration_id: id } } : {}), + regions: [], + inputs: [], + outputs: [ + { + configuration_id: id, + output_id: `${id}-out`, + output: { + id: `${id}-out`, + label: outLabel, + has_format: null, + presentations: [ + { + dataset_specification_id: `${id}-out`, + presentation_id: `${id}-vp`, + presentation: { id: `${id}-vp`, standard_variable: { id: outId, label: outLabel } }, + }, + ], + }, + }, + ], + child_configurations: [], + }; +} + +const treeMock: MockedResponse = { + request: { query: GetModelTreeWithRegionsDocument }, + result: { + data: { + modelcatalog_software: [ + { + id: 'sw', + label: 'Sensemaking', + versions: [ + { + id: 'v', + label: '1', + configurations: [ + config('alpha', 'Alpha model', RAW, 'document_collection__raw_text'), + config('mid', 'Mid model', REPORT, 'document_collection__sensemaking_report'), + // Registered under another namespace: only the name matches. + config( + 'zeta', + 'Zeta flow', + 'https://example.org/vocab/document_collection__sensemaking_report', + 'document_collection__sensemaking_report', + true, + ), + ], + }, + ], + }, + ], + }, + }, +}; + +const adapterMock: MockedResponse = { + request: { query: ModelOutcomeAdapterInferenceDocument }, + result: { + data: { + adapterTransforms: [ + { + id: 't1', + name: 'raw-to-report', + description: null, + contracts: [ + { id: 'c1', role: 'input', standard_variable_uri: RAW, format: null, unit: null }, + { id: 'c2', role: 'output', standard_variable_uri: REPORT, format: null, unit: null }, + ], + }, + ], + }, + }, +}; + +const thread = { + __typename: 'thread', + id: 't1', + name: 'Report', + task_id: 'task1', + start_date: '2000-01-01', + end_date: '2026-01-01', + region_id: null, + driving_variable_id: null, + response_variable_id: REPORT, + response_variable: { id: REPORT, label: 'document_collection__sensemaking_report' }, + events: [], + permissions: [{ __typename: 'thread_permission', user_id: 'testuser', read: true, write: true }], + thread_models: [], +} as unknown as Thread; + +function renderStep() { + return renderWithProviders( + , + { apolloMocks: [treeMock, adapterMock] }, + ); +} + +const cardNames = () => + screen + .getAllByRole('checkbox') + .map((box) => box.getAttribute('aria-label')?.replace(/^Select /, '')); + +describe('ModelsStep outcome ranking', () => { + beforeEach(() => { + semantic.results = null; + }); + + it('puts the rows that produce the outcome first, flows included, then transforms', async () => { + renderStep(); + await screen.findByText('Zeta flow'); + // Tree order is alphabetical (Alpha, Mid, Zeta); the producers lead. + await waitFor(() => expect(cardNames()).toEqual(['Mid model', 'Zeta flow', 'Alpha model'])); + }); + + it('says why each row is listed', async () => { + renderStep(); + await screen.findByText('Zeta flow'); + await waitFor(() => expect(screen.getAllByTestId('outcome-reason')).toHaveLength(3)); + const reasons = screen.getAllByTestId('outcome-reason').map((el) => el.textContent); + expect(reasons).toEqual([ + 'Produces document_collection__sensemaking_report', + 'Produces document_collection__sensemaking_report', + 'Can be transformed into document_collection__sensemaking_report', + ]); + }); + + it('keeps exact matches ahead of semantic-only hits, and keeps a row the index lacks', async () => { + // The index ranks the transformed row first and does not carry the flow. + semantic.results = [{ id: 'alpha' }, { id: 'mid' }]; + renderStep(); + await screen.findByText('Zeta flow'); + await userEvent.type(screen.getByPlaceholderText(/filter models/i), 'e'); + await waitFor(() => expect(cardNames()).toEqual(['Mid model', 'Zeta flow', 'Alpha model'])); + }); +});