-
+
Seed examples used by this scan. Limits and filters control which examples are selected.
@@ -1044,8 +1038,7 @@ function ScenarioLaunchForm({
&& !confirmedDatasetSettings.sources.some((source) => source.fetch === 'always'
&& !datasetMetadata.items.some((item) => item.name === source.name && item.loaded))}
onLoad={() => { if (estimateRequest) void datasetMetadata.loadSelected(scenario.scenario_name, estimateRequest) }}
- required={datasetRequired} showCatalogLink={false}
- selectionError={validationError !== null ? datasetSelectionProblem : null} pickerRef={datasetPickerRef}
+ required={datasetRequired}
onReload={datasetMetadata.reload} onChange={setDatasetEdits} onValidationChange={setDatasetError}
/>
diff --git a/frontend/src/components/Scenarios/datasetPresentation.test.ts b/frontend/src/components/Scenarios/datasetPresentation.test.ts
index 925d612b6d..5d18733750 100644
--- a/frontend/src/components/Scenarios/datasetPresentation.test.ts
+++ b/frontend/src/components/Scenarios/datasetPresentation.test.ts
@@ -26,15 +26,17 @@ describe('datasetTotalLimit', () => {
})
describe('datasetNameWithOrigin', () => {
- it.each(['local', 'remote', 'generated', 'user'])('displays recorded %s origin', (origin) => {
+ it.each([
+ ['local', 'Local files'], ['remote', 'Remote provider'], ['generated', 'Generated'], ['user', 'User'],
+ ])('displays recorded %s origin with the catalog label', (origin, label) => {
expect(datasetNameWithOrigin('sample', {
name: 'sample', selection_key: 'dataset:named:sample', loaded: true, provider_available: false,
origins: [origin], logical_examples: 1, seed_pieces: 1, objectives: 1, modalities: [], harm_categories: [],
has_unlabeled_harm_categories: false,
- })).toBe(`sample (${origin})`)
+ })).toBe(`sample (${label})`)
})
it('does not guess the origin of an unloaded dataset', () => {
- expect(datasetNameWithOrigin('sample', undefined)).toBe('sample (unknown)')
+ expect(datasetNameWithOrigin('sample', undefined)).toBe('sample (Unknown)')
})
})
diff --git a/frontend/src/components/Scenarios/datasetPresentation.ts b/frontend/src/components/Scenarios/datasetPresentation.ts
index 5e689e58d7..6b51829fa4 100644
--- a/frontend/src/components/Scenarios/datasetPresentation.ts
+++ b/frontend/src/components/Scenarios/datasetPresentation.ts
@@ -100,9 +100,22 @@ export function datasetChoices(
return [...names].filter((name) => options.mode === 'any' || options.allowed_names.includes(name)).sort()
}
+const ORIGIN_LABELS: Readonly> = {
+ generated: 'Generated',
+ local: 'Local files',
+ remote: 'Remote provider',
+ user: 'User',
+ unknown: 'Unknown',
+}
+
+/** The display name of a seed origin, shared by the dataset catalog and the scanner. */
+export function datasetOriginLabel(origin: string): string {
+ return ORIGIN_LABELS[origin] ?? origin
+}
+
export function datasetNameWithOrigin(name: string, dataset: DatasetInfo | undefined): string {
const origins = [...new Set(dataset?.origins ?? [])]
- return `${name} (${origins.length > 0 ? origins.join(', ') : 'unknown'})`
+ return `${name} (${(origins.length > 0 ? origins : ['unknown']).map(datasetOriginLabel).join(', ')})`
}
export function datasetFacts(datasets: DatasetInfo[], names: string[]) {
diff --git a/frontend/src/components/Scenarios/scenarioLaunchRequest.test.ts b/frontend/src/components/Scenarios/scenarioLaunchRequest.test.ts
index a7bc31f660..811009d3e5 100644
--- a/frontend/src/components/Scenarios/scenarioLaunchRequest.test.ts
+++ b/frontend/src/components/Scenarios/scenarioLaunchRequest.test.ts
@@ -120,27 +120,6 @@ describe('scenario launch requests', () => {
'Wait for valid technique settings before launch.'],
['invalid datasets', { datasetError: 'Bad dataset limit.' }, 'Bad dataset limit.'],
['linked datasets that cannot launch', { linkedDatasetError: 'Linked problem.' }, 'Linked problem.'],
- ['a launch without the datasets the scenario requires', {
- scenario: makeScenario({
- scenario_name: 'any.renamed_policy', default_datasets: [],
- dataset_defaults: { sources: [], max_per_dataset: 'all', max_total: 'all', fetch: 'if_missing', filters: {} },
- dataset_options: {
- mode: 'any', allowed_names: [], min_selected: 1, per_dataset_limit: true, total_limit: true,
- supports_overrides: true, filters: true,
- },
- }),
- }, 'Select a dataset.'],
- ['fewer datasets than the scenario requires', {
- scenario: makeScenario({
- default_datasets: [],
- dataset_defaults: { sources: [], max_per_dataset: 'all', max_total: 'all', fetch: 'if_missing', filters: {} },
- dataset_options: {
- mode: 'any', allowed_names: [], min_selected: 2, per_dataset_limit: true, total_limit: true,
- supports_overrides: true, filters: true,
- },
- }),
- datasetEdits: { sources: [{ name: 'ds_a' }] },
- }, 'Select at least 2 datasets.'],
['an unsupported conversation', {
supportsPrependedConversation: false,
scenarioParamValues: { objective: '', prepended_conversation_id: 'saved' },
@@ -164,7 +143,7 @@ describe('scenario launch requests', () => {
expect(linkedDatasetProblem([], false)).toBeNull()
expect(linkedDatasetProblem([' returns ', 'returns ', 'missing'], true)).toBeNull()
expect(linkedDatasetProblem(['ds_a', ' returns ', ''], false)).toBe(
- 'This scenario does not take datasets, so it can\'t launch with the linked datasets: ds_a, " returns ", "".',
+ 'This scenario can\'t take the linked datasets: ds_a, " returns ", "".',
)
expect(linkedDatasetProblem(['ds_a', ' '], true)).toBeNull()
})
diff --git a/frontend/src/components/Scenarios/scenarioLaunchRequest.ts b/frontend/src/components/Scenarios/scenarioLaunchRequest.ts
index 95f686bcfd..ca60345ca5 100644
--- a/frontend/src/components/Scenarios/scenarioLaunchRequest.ts
+++ b/frontend/src/components/Scenarios/scenarioLaunchRequest.ts
@@ -9,8 +9,6 @@ import type {
TechniqueOverride,
} from '@/types'
-import { scenarioDatasetDefaults } from './datasetPresentation'
-
/**
* Common/opaque parameters the base scenario declares via
* `Scenario._common_scenario_parameters` — the launch form exposes a
@@ -51,28 +49,18 @@ export function requiresDatasetSelection(scenario: RegisteredScenario): boolean
return (scenario.dataset_options?.min_selected ?? 0) > 0
}
-/** Why the selected datasets are too few for the scenario's declared minimum, or null. */
-export function datasetSelectionError(scenario: RegisteredScenario, datasetEdits: ScenarioDatasetRequest): string | null {
- const minimum = scenario.dataset_options?.min_selected ?? 0
- if (minimum === 0) return null
- const selected = (datasetEdits.sources ?? scenarioDatasetDefaults(scenario).sources).length
- if (selected >= minimum) return null
- return minimum === 1 ? 'Select a dataset.' : `Select at least ${minimum} datasets.`
-}
-
function linkedDatasetLabel(name: string): string {
return name !== '' && name === name.trim() ? name : JSON.stringify(name)
}
/**
- * Why a link's dataset names can't launch, or null. A scenario without dataset input would drop
- * them silently; other names, including blank ones, are left for the server to validate.
+ * Why a link's dataset names can't launch, or null. A scenario without dataset input, or with fixed
+ * sources, can't take them; other names, including blank ones, are left for the server to validate.
*/
-export function linkedDatasetProblem(names: readonly string[], supportsDatasets: boolean): string | null {
+export function linkedDatasetProblem(names: readonly string[], takesLinkedDatasets: boolean): string | null {
if (names.length === 0) return null
- if (!supportsDatasets) {
- return "This scenario does not take datasets, so it can't launch with the linked datasets: "
- + `${names.map(linkedDatasetLabel).join(', ')}.`
+ if (!takesLinkedDatasets) {
+ return `This scenario can't take the linked datasets: ${names.map(linkedDatasetLabel).join(', ')}.`
}
return null
}
@@ -218,8 +206,6 @@ export function buildRunRequest(input: ScenarioLaunchInput): BuildRunRequestResu
if (supportsParameter(input.scenario, 'objective_target') && !input.targetName) {
return { ok: false, error: 'Select a target.' }
}
- const datasetProblem = datasetSelectionError(input.scenario, input.datasetEdits)
- if (datasetProblem) return { ok: false, error: datasetProblem }
const estimateResult = buildEstimateRequest(input)
if (!estimateResult.ok) {
return estimateResult
diff --git a/frontend/src/hooks/useScenarioLaunch.test.tsx b/frontend/src/hooks/useScenarioLaunch.test.tsx
index c6d4855e20..d0f267eafe 100644
--- a/frontend/src/hooks/useScenarioLaunch.test.tsx
+++ b/frontend/src/hooks/useScenarioLaunch.test.tsx
@@ -121,7 +121,8 @@ describe('useScenarioLaunch', () => {
await act(async () => { await view.result.current.confirmLaunch() })
- expect(view.result.current.apiError).toBe('Request validation failed: Dataset names must be non-empty.')
+ expect(view.result.current.apiError)
+ .toBe('Request validation failed: datasets.sources.0.name: Dataset names must be non-empty.')
})
it('does not start a run while launching is blocked', async () => {
diff --git a/frontend/src/services/errors.test.ts b/frontend/src/services/errors.test.ts
index 4befdd7f5b..299407f23a 100644
--- a/frontend/src/services/errors.test.ts
+++ b/frontend/src/services/errors.test.ts
@@ -374,18 +374,21 @@ describe('notSaveableReason', () => {
})
describe('apiErrorMessage', () => {
- it('adds distinct field messages to the detail, without the pydantic prefix', () => {
+ it('adds each distinct field message with its field to the detail, without the pydantic prefixes', () => {
const error = toApiError(makeAxiosError({
status: 422,
data: {
detail: 'Request validation failed',
errors: [
- { field: 'body.datasets.sources.0.name', message: 'Value error, Dataset names must be non-empty.' },
+ { field: 'body.datasets.sources.0.name', message: 'String should have at least 1 character' },
+ { field: 'body.datasets.sources.0.name', message: 'String should have at least 1 character' },
{ field: 'body.datasets.sources.1.name', message: 'Value error, Dataset names must be non-empty.' },
],
},
}))
- expect(apiErrorMessage(error)).toBe('Request validation failed: Dataset names must be non-empty.')
+ expect(apiErrorMessage(error)).toBe('Request validation failed: '
+ + 'datasets.sources.0.name: String should have at least 1 character; '
+ + 'datasets.sources.1.name: Dataset names must be non-empty.')
expect(apiErrorMessage(toApiError(new Error('Plain failure.')))).toBe('Plain failure.')
})
})
diff --git a/frontend/src/services/errors.ts b/frontend/src/services/errors.ts
index 59dc105c30..b25a27413b 100644
--- a/frontend/src/services/errors.ts
+++ b/frontend/src/services/errors.ts
@@ -139,16 +139,18 @@ export function toApiError(err: unknown): ApiError {
}
}
-/** Pydantic's prefix on validator messages, which says nothing to the user. */
+/** Pydantic's prefixes on validator messages and request body fields, which say nothing to the user. */
const VALUE_ERROR_PREFIX = /^Value error, /
+const BODY_FIELD_PREFIX = /^body\./
/**
- * The error's detail followed by its distinct field messages, so a 422's generic
- * "Request validation failed" says what failed.
+ * The error's detail followed by its distinct field messages, each with its field, so a 422's
+ * generic "Request validation failed" says what failed and where.
*/
export function apiErrorMessage(error: ApiError): string {
- const messages = [...new Set(error.fieldErrors.map((item) => item.message.replace(VALUE_ERROR_PREFIX, '')))]
- return messages.length > 0 ? `${error.detail}: ${messages.join(' ')}` : error.detail
+ const messages = [...new Set(error.fieldErrors.map((item) =>
+ `${item.field.replace(BODY_FIELD_PREFIX, '')}: ${item.message.replace(VALUE_ERROR_PREFIX, '')}`))]
+ return messages.length > 0 ? `${error.detail}: ${messages.join('; ')}` : error.detail
}
/** Problem type the backend gives a target it refused to save, which can still be created without saving it. */
diff --git a/pyrit/cli/_output.py b/pyrit/cli/_output.py
index 5a5d87ee56..2f19ee18a8 100644
--- a/pyrit/cli/_output.py
+++ b/pyrit/cli/_output.py
@@ -137,7 +137,8 @@ def print_scenario_list(*, items: list[RegisteredScenario]) -> None:
print(f" Default Datasets ({len(sc.default_datasets)}):")
print(_wrap(text=", ".join(sc.default_datasets), indent=" "))
options = sc.dataset_options
- print(f" Dataset selection: {options.mode.value}; overrides: {options.supports_overrides}")
+ minimum = f"; at least {options.min_selected} required" if options.min_selected else ""
+ print(f" Dataset selection: {options.mode.value}; overrides: {options.supports_overrides}{minimum}")
if options.allowed_names:
print(_wrap(text="Options: " + ", ".join(options.allowed_names), indent=" "))
defaults = sc.dataset_defaults
diff --git a/pyrit/scenario/core/dataset_overrides.py b/pyrit/scenario/core/dataset_overrides.py
index c3d2f78733..f65b524da1 100644
--- a/pyrit/scenario/core/dataset_overrides.py
+++ b/pyrit/scenario/core/dataset_overrides.py
@@ -93,14 +93,24 @@ def validate_dataset_selection(
raise DatasetConstraintError(f"Dataset sources are fixed: {', '.join(defaults.dataset_names)}.")
if options.mode is DatasetSelectionMode.SUBSET and (not names or set(names) - set(options.allowed_names)):
raise DatasetConstraintError(f"Select datasets from: {', '.join(options.allowed_names)}.")
- if options.min_selected is not None and len(names) < options.min_selected:
- # Clients show the same wording for the same rule.
- minimum = options.min_selected
- raise DatasetConstraintError("Select a dataset." if minimum == 1 else f"Select at least {minimum} datasets.")
+ validate_minimum_selection(config=config, options=options)
if options.max_selected is not None and len(names) > options.max_selected:
raise DatasetConstraintError(f"Select at most {options.max_selected} dataset(s).")
+def validate_minimum_selection(*, config: DatasetAttackConfiguration, options: ScenarioDatasetOptions) -> None:
+ """
+ Require the declared minimum of named datasets, with or without overrides. Inline seeds need none.
+
+ Raises:
+ DatasetConstraintError: If fewer datasets are selected than the scenario requires.
+ """
+ minimum = options.min_selected
+ if minimum is None or config.source_kind is DatasetSourceKind.INLINE or len(config.dataset_names) >= minimum:
+ return
+ raise DatasetConstraintError("Select a dataset." if minimum == 1 else f"Select at least {minimum} datasets.")
+
+
def project_dataset_settings(
config: DatasetAttackConfiguration, *, required_data: ScenarioRequiredData | None = None
) -> ScenarioDatasetSettings:
diff --git a/pyrit/scenario/core/scenario.py b/pyrit/scenario/core/scenario.py
index 5671b2282a..c899bbbbc4 100644
--- a/pyrit/scenario/core/scenario.py
+++ b/pyrit/scenario/core/scenario.py
@@ -88,7 +88,11 @@
DatasetSource,
DatasetSourceKind,
)
-from pyrit.scenario.core.dataset_overrides import apply_dataset_overrides, project_dataset_settings
+from pyrit.scenario.core.dataset_overrides import (
+ apply_dataset_overrides,
+ project_dataset_settings,
+ validate_minimum_selection,
+)
from pyrit.scenario.core.dataset_sampling import sample_with_coverage
from pyrit.scenario.core.required_data import ScenarioRequiredData
from pyrit.scenario.core.scenario_context import ScenarioContext
@@ -1082,6 +1086,7 @@ def _resolve_runtime_configuration(
)
self._load_required_data_like_dataset_config()
self._validate_runtime_configuration()
+ validate_minimum_selection(config=self._dataset_config, options=options)
def _validate_dataset_scorer_requirements(self) -> None:
"""
diff --git a/pyrit/scenario/scenarios/foundry/assert_policy.py b/pyrit/scenario/scenarios/foundry/assert_policy.py
index 097ebbe117..39b13dea56 100644
--- a/pyrit/scenario/scenarios/foundry/assert_policy.py
+++ b/pyrit/scenario/scenarios/foundry/assert_policy.py
@@ -36,7 +36,7 @@
from pyrit.scenario.core.atomic_attack import AtomicAttack
from pyrit.scenario.core.attack_technique import AttackTechnique
from pyrit.scenario.core.attack_technique_factory import AttackTechniqueFactory
-from pyrit.scenario.core.dataset_configuration import DatasetAttackConfiguration, DatasetSourceKind
+from pyrit.scenario.core.dataset_configuration import DatasetAttackConfiguration
from pyrit.scenario.core.scenario import BaselineAttackPolicy, Scenario
from pyrit.scenario.core.technique_requirements import (
IncompatibleTechniqueError,
@@ -51,7 +51,6 @@
from collections.abc import Sequence
from pathlib import Path
- from pyrit.models import ScenarioDatasetSizeEstimate
from pyrit.prompt_target import PromptTarget
from pyrit.scenario.core.scenario_context import ScenarioContext
from pyrit.scenario.core.scenario_technique import ScenarioTechnique
@@ -249,12 +248,6 @@ def _validate_runtime_configuration(self) -> None:
if prompt is not None and not prompt.strip():
raise ValueError("target_system_prompt must not be blank.")
- def _has_no_datasets(self) -> bool:
- return self._dataset_config.source_kind is DatasetSourceKind.MEMORY and not self._dataset_config.dataset_names
-
- def _get_run_size_budget(self) -> ScenarioDatasetSizeEstimate:
- return BoundedDatasetSize(value=1) if self._has_no_datasets() else super()._get_run_size_budget()
-
async def _estimate_run_size_async(self, *, budget: BoundedDatasetSize) -> ScenarioRunSizeEstimate:
count, datasets = await self._get_dataset_size_for_estimate_async(budget=budget)
components = [
@@ -267,9 +260,6 @@ async def _estimate_run_size_async(self, *, budget: BoundedDatasetSize) -> Scena
"At most one unit per selected group for each technique; groups a technique can't use are skipped. "
f"Techniques that take a turn count make up to {self.params['max_turns']} target turns."
)
- if self._has_no_datasets():
- datasets = []
- note = "No ASSERT dataset is selected; pass stored dataset names with --datasets. " + note
return ScenarioRunSizeEstimate(
status=ScenarioRunSizeEstimateStatus.Approximate,
total_attack_count=sum(component.count for component in components),
@@ -288,16 +278,10 @@ async def _resolve_seed_groups_by_dataset_async(
dict[str, list[AttackSeedGroup]]: Selected groups keyed by dataset.
Raises:
- ValueError: If no dataset is selected, a group lacks ASSERT metadata or conflicts with
- ``target_system_prompt``, or a stored objective seed appears more than once.
+ ValueError: If a group lacks ASSERT metadata or conflicts with ``target_system_prompt``,
+ or a stored objective seed appears more than once.
DatasetConstraintError: If the selected datasets contain no groups.
"""
- if self._has_no_datasets():
- raise ValueError(
- "Select a dataset. foundry.assert_policy needs stored ASSERT seed groups. Pass their dataset "
- "names with --datasets (or the deprecated --dataset-names), or supply dataset_config in Python. "
- "Generate groups with AssertGenerator and store them with AssertProvider."
- )
selection = await self._dataset_config._resolve_attack_groups_async()
population = selection.select(apply_sampling=False)
if not any(population.values()):
diff --git a/tests/unit/cli/test_output.py b/tests/unit/cli/test_output.py
index e2799dfc33..4854b31c93 100644
--- a/tests/unit/cli/test_output.py
+++ b/tests/unit/cli/test_output.py
@@ -23,6 +23,7 @@
AttackOutcome,
Parameter,
RetryEvent,
+ ScenarioDatasetOptions,
ScenarioRunListItem,
ScenarioRunState,
TargetCapabilities,
@@ -248,6 +249,13 @@ def test_print_scenario_list_minimal_fields(capsys):
assert "MinScenario" in captured.out
+@pytest.mark.parametrize(("min_selected", "suffix"), [(None, ""), (1, "; at least 1 required")])
+def test_print_scenario_list_shows_the_dataset_minimum(capsys, min_selected, suffix):
+ options = ScenarioDatasetOptions(min_selected=min_selected)
+ _output.print_scenario_list(items=[_make_scenario(dataset_options=options)])
+ assert f"Dataset selection: any; overrides: True{suffix}\n" in capsys.readouterr().out
+
+
def test_print_scenario_list_no_max_dataset_size(capsys):
items = [
_make_scenario(
diff --git a/tests/unit/scenario/core/test_scenario_dataset_overrides.py b/tests/unit/scenario/core/test_scenario_dataset_overrides.py
index e4c1d079a0..92ac42ed5b 100644
--- a/tests/unit/scenario/core/test_scenario_dataset_overrides.py
+++ b/tests/unit/scenario/core/test_scenario_dataset_overrides.py
@@ -270,13 +270,14 @@ class _RequiredInlineScenario(_InlineScenario):
@pytest.mark.usefixtures("patch_central_database")
-async def test_declared_minimum_selection_names_the_count() -> None:
+@pytest.mark.parametrize("args", [{}, {"dataset_overrides": {"sources": [{"name": "a"}]}}])
+async def test_declared_minimum_selection_applies_with_or_without_overrides(args: dict[str, object]) -> None:
class _RequiredScenario(_Scenario):
- DATASET_OPTIONS = ScenarioDatasetOptions(min_selected=2)
+ DATASET_OPTIONS = ScenarioDatasetOptions(min_selected=3)
scenario = _RequiredScenario()
- scenario.set_params_from_args(args={"dataset_overrides": {"sources": [{"name": "a"}]}})
- with pytest.raises(ValueError, match=r"^Select at least 2 datasets\.$"):
+ scenario.set_params_from_args(args=args)
+ with pytest.raises(ValueError, match=r"^Select at least 3 datasets\.$"):
await scenario.get_run_size_estimate_async()
diff --git a/tests/unit/scenario/foundry/test_assert_policy.py b/tests/unit/scenario/foundry/test_assert_policy.py
index 702cd46747..6b1fb2f9c4 100644
--- a/tests/unit/scenario/foundry/test_assert_policy.py
+++ b/tests/unit/scenario/foundry/test_assert_policy.py
@@ -27,11 +27,9 @@
AssertSkipReason,
AssertTaxonomy,
AttackOutcome,
- BoundedDatasetSize,
Message,
PromptResponseError,
ScenarioEvaluationIdentifier,
- ScenarioRunSizeEstimateStatus,
SeedObjective,
ViolatesAssertPolicy,
construct_response_from_request,
@@ -250,19 +248,11 @@ def test_registry_name_and_argument_free_construction() -> None:
}
-async def test_default_estimate_is_bounded_without_datasets_async() -> None:
- estimate = await AssertPolicy().get_default_run_size_estimate_async()
- assert estimate.status is ScenarioRunSizeEstimateStatus.Approximate
- assert estimate.dataset_size == BoundedDatasetSize(value=1)
- assert estimate.total_attack_count == 2
- assert estimate.datasets == []
- assert "--datasets" in (estimate.note or "")
-
-
-async def test_dataset_overrides_must_select_a_dataset_async() -> None:
+@pytest.mark.parametrize("args", [{}, {"dataset_overrides": {"max_total": 3}}])
+async def test_estimate_without_datasets_asks_for_one_async(args: dict[str, Any]) -> None:
scenario = AssertPolicy()
assert scenario.get_dataset_options().min_selected == 1
- scenario.set_params_from_args(args={"dataset_overrides": {"max_total": 3}})
+ scenario.set_params_from_args(args=args)
with pytest.raises(ValueError, match=r"^Select a dataset\.$"):
await scenario.get_run_size_estimate_async()
@@ -281,8 +271,8 @@ async def test_invalid_parameters_are_rejected_before_reading_data_async(args: d
await scenario.get_run_size_estimate_async()
-async def test_run_without_datasets_names_the_dataset_flag_async(harness: _Harness) -> None:
- with pytest.raises(ValueError, match=r"^Select a dataset\..*--datasets"):
+async def test_run_without_datasets_asks_for_one_async(harness: _Harness) -> None:
+ with pytest.raises(ValueError, match=r"^Select a dataset\.$"):
await harness.initialize_async(harness.scenario())
@@ -966,6 +956,7 @@ def test_readiness_uses_the_execution_history_requirements(harness: _Harness, te
"objective_target": harness.objective,
"scenario_techniques": [_technique(technique)],
"incompatible_technique_policy": policy,
+ **_datasets("assert_a"),
}
scenario = harness.scenario()
scenario.set_params_from_args(args=args)
@@ -1003,6 +994,7 @@ async def test_incompatible_scoring_config_uses_scenario_policy_async(harness: _
"objective_target": harness.objective,
"scoring_target": harness.judge,
"scenario_techniques": [_technique("tap")],
+ **_datasets("assert_a"),
}
)
assert any(issue.role == "objective_scorer" for issue in scenario.get_readiness().issues)
@@ -1012,6 +1004,7 @@ async def test_incompatible_scoring_config_uses_scenario_policy_async(harness: _
"scoring_target": harness.judge,
"scenario_techniques": [_technique("prompt_sending"), _technique("tap")],
"incompatible_technique_policy": policy,
+ **_datasets("assert_a"),
}
)
assert any(issue.role == "objective_scorer" for issue in scenario.get_readiness().issues) == (policy == "raise")
@@ -1115,7 +1108,7 @@ async def test_selected_scoring_target_is_the_default_judge_async(harness: _Harn
def test_readiness_reports_a_missing_default_judge_target(harness: _Harness) -> None:
scenario = AssertPolicy(adversarial_chat=harness.adversarial)
- scenario.set_params_from_args(args={"objective_target": harness.objective})
+ scenario.set_params_from_args(args={"objective_target": harness.objective, **_datasets("assert_a")})
with patch(
"pyrit.scenario.core.scenario.get_default_scorer_target",
side_effect=TargetRoleConfigurationError(role="objective_scorer_chat"),
@@ -1132,7 +1125,7 @@ async def test_supplied_scorer_needs_no_default_judge_target_async(harness: _Har
"pyrit.scenario.core.scenario.get_default_scorer_target",
side_effect=TargetRoleConfigurationError(role="objective_scorer_chat"),
):
- scenario.set_params_from_args(args={"objective_target": harness.objective})
+ scenario.set_params_from_args(args={"objective_target": harness.objective, **_datasets("assert_a")})
readiness = scenario.get_readiness()
await harness.initialize_async(scenario, **_prompt_case(), **_datasets("assert_a"))
diff --git a/tests/unit/scenario/test_default_run_size_estimates.py b/tests/unit/scenario/test_default_run_size_estimates.py
index 3a1f80ca9a..5357d3205f 100644
--- a/tests/unit/scenario/test_default_run_size_estimates.py
+++ b/tests/unit/scenario/test_default_run_size_estimates.py
@@ -32,6 +32,7 @@
AtomicAttack,
CompoundDatasetAttackConfiguration,
DatasetAttackConfiguration,
+ DatasetConstraintError,
DatasetSource,
Scenario,
ScenarioTechnique,
@@ -365,6 +366,11 @@ async def test_all_builtin_default_size_contracts_are_bounded_async() -> None:
if not scenario_class.__module__.startswith("pyrit.scenario.scenarios."):
continue
scenario = registry.create_instance(name)
+ if scenario.get_dataset_options().min_selected and not scenario.get_default_dataset_names():
+ # A scenario that needs a dataset and has no default has no default run to size.
+ with pytest.raises(DatasetConstraintError, match=r"^Select "):
+ await scenario.get_default_run_size_estimate_async()
+ continue
estimate = await scenario.get_default_run_size_estimate_async()
assert isinstance(estimate.dataset_size, BoundedDatasetSize), name
assert estimate.status is not ScenarioRunSizeEstimateStatus.Unavailable, name
From caa9d1a101eb9cef60795a47feee3dd6923f00cc Mon Sep 17 00:00:00 2001
From: Richard Lundeen
Date: Fri, 20 Nov 2026 11:57:00 -0800
Subject: [PATCH 3/8] FIX: Report an unavailable default estimate when a
dataset is required
A scenario that declares min_selected and has no default datasets has no
default run to size. Return an unavailable default estimate with the
selection message instead of raising, so the catalog shows the reason
without logging a failure on every load. Configured estimates and runs
still reject the selection.
Co-Authored-By: Claude Opus 5.5
---
pyrit/scenario/core/scenario.py | 8 ++++++++
tests/unit/scenario/test_default_run_size_estimates.py | 7 +++----
2 files changed, 11 insertions(+), 4 deletions(-)
diff --git a/pyrit/scenario/core/scenario.py b/pyrit/scenario/core/scenario.py
index c899bbbbc4..4abeffd2b9 100644
--- a/pyrit/scenario/core/scenario.py
+++ b/pyrit/scenario/core/scenario.py
@@ -85,6 +85,7 @@
from pyrit.scenario.core.atomic_attack import AtomicAttack, compute_atomic_group_id
from pyrit.scenario.core.dataset_configuration import (
DatasetAttackConfiguration,
+ DatasetConstraintError,
DatasetSource,
DatasetSourceKind,
)
@@ -819,6 +820,13 @@ async def get_default_run_size_estimate_async(self) -> ScenarioRunSizeEstimate:
allow_missing_required=True,
)
self._params_resolved = True
+ try:
+ validate_minimum_selection(
+ config=self._resolve_default_dataset_config(), options=self.get_dataset_options()
+ )
+ except DatasetConstraintError as error:
+ # A scenario that needs a dataset and has no default has no default run to size.
+ return ScenarioRunSizeEstimate.unavailable(note=str(error))
return await self.get_run_size_estimate_async(target_is_configured=False)
USES_DATASET_SIZE_LIMIT: ClassVar[bool] = True
diff --git a/tests/unit/scenario/test_default_run_size_estimates.py b/tests/unit/scenario/test_default_run_size_estimates.py
index 5357d3205f..fbe37469ec 100644
--- a/tests/unit/scenario/test_default_run_size_estimates.py
+++ b/tests/unit/scenario/test_default_run_size_estimates.py
@@ -32,7 +32,6 @@
AtomicAttack,
CompoundDatasetAttackConfiguration,
DatasetAttackConfiguration,
- DatasetConstraintError,
DatasetSource,
Scenario,
ScenarioTechnique,
@@ -366,12 +365,12 @@ async def test_all_builtin_default_size_contracts_are_bounded_async() -> None:
if not scenario_class.__module__.startswith("pyrit.scenario.scenarios."):
continue
scenario = registry.create_instance(name)
+ estimate = await scenario.get_default_run_size_estimate_async()
if scenario.get_dataset_options().min_selected and not scenario.get_default_dataset_names():
# A scenario that needs a dataset and has no default has no default run to size.
- with pytest.raises(DatasetConstraintError, match=r"^Select "):
- await scenario.get_default_run_size_estimate_async()
+ assert estimate.status is ScenarioRunSizeEstimateStatus.Unavailable, name
+ assert estimate.note == "Select a dataset.", name
continue
- estimate = await scenario.get_default_run_size_estimate_async()
assert isinstance(estimate.dataset_size, BoundedDatasetSize), name
assert estimate.status is not ScenarioRunSizeEstimateStatus.Unavailable, name
finite_count = estimate.total_attack_count or estimate.maximum_attack_count
From 274c36f76b469ad8197abd5a6440a4670b0b8f07 Mon Sep 17 00:00:00 2001
From: Richard Lundeen
Date: Fri, 20 Nov 2026 12:42:44 -0800
Subject: [PATCH 4/8] FIX: Report dataset requirement clearly in the scanner
estimate and launch
- Size the default run against the default configuration's dataset options, so a reused scenario instance returns the unavailable estimate instead of raising.
- Label a 400/422 estimate as a configuration to complete, not a backend failure.
- Focus the launch error banner after a rejected launch so its reason scrolls into view.
Co-Authored-By: Claude Opus 5.5
---
.../Scenarios/ScenarioDetail.test.tsx | 8 ++++++-
.../components/Scenarios/ScenarioDetail.tsx | 3 ++-
frontend/src/hooks/useScenarioLaunch.test.tsx | 20 +++++++++++++++-
frontend/src/hooks/useScenarioLaunch.ts | 8 +++++--
.../src/hooks/useScenarioRunEstimate.test.tsx | 12 ++++++++++
frontend/src/hooks/useScenarioRunEstimate.ts | 13 ++++++----
pyrit/scenario/core/scenario.py | 6 ++---
.../core/test_scenario_dataset_overrides.py | 24 +++++++++++++++++++
8 files changed, 82 insertions(+), 12 deletions(-)
diff --git a/frontend/src/components/Scenarios/ScenarioDetail.test.tsx b/frontend/src/components/Scenarios/ScenarioDetail.test.tsx
index 4c8eb307bd..c8de4a52e6 100644
--- a/frontend/src/components/Scenarios/ScenarioDetail.test.tsx
+++ b/frontend/src/components/Scenarios/ScenarioDetail.test.tsx
@@ -2811,7 +2811,9 @@ describe('ScenarioDetail', () => {
await screen.findByText('boom')
await waitFor(() => expect(screen.queryByRole('dialog', { name: 'Run preview' })).not.toBeInTheDocument())
expect(screen.getByRole('alert')).toHaveTextContent('boom')
- await waitFor(() => expect(screen.getByTestId('launch-scenario-btn')).toHaveFocus())
+ // Focus moves to the banner at the top of the form so the browser scrolls the reason into view.
+ await waitFor(() => expect(screen.getByRole('alert').closest('[tabindex="-1"]')).toHaveFocus())
+ expect(screen.getByTestId('launch-scenario-btn')).not.toHaveFocus()
expect(screen.getByTestId('scenario-target-select')).toHaveValue('target-b')
expect(screen.getByTestId('technique-crescendo')).toBeChecked()
expect(screen.getByTestId('technique-default_technique')).not.toBeChecked()
@@ -3382,6 +3384,10 @@ describe('ScenarioDetail', () => {
const estimate = await screen.findByTestId('run-estimate')
await waitFor(() => expect(within(estimate).getByRole('status')).toHaveTextContent('Select a dataset.'))
+ // The 400 rejects the configuration, not the backend.
+ expect(within(estimate).getByRole('status'))
+ .toHaveTextContent('Complete the required configuration to request an estimate.')
+ expect(estimate).not.toHaveTextContent('The backend estimate could not be refreshed.')
await waitFor(() => expect(screen.getByRole('button', { name: 'Launch scan' })).toBeEnabled())
await confirmRunPreview(user)
diff --git a/frontend/src/components/Scenarios/ScenarioDetail.tsx b/frontend/src/components/Scenarios/ScenarioDetail.tsx
index faf9e3abcf..5279e82f97 100644
--- a/frontend/src/components/Scenarios/ScenarioDetail.tsx
+++ b/frontend/src/components/Scenarios/ScenarioDetail.tsx
@@ -666,6 +666,7 @@ function ScenarioLaunchForm({
clearValidationError,
isSubmitting,
launchButtonRef,
+ apiErrorRef,
submitForm,
dismissPreview,
changePreviewOpen,
@@ -900,7 +901,7 @@ function ScenarioLaunchForm({
)}
{apiError && (
-
+
{apiError}
)}
diff --git a/frontend/src/hooks/useScenarioLaunch.test.tsx b/frontend/src/hooks/useScenarioLaunch.test.tsx
index d0f267eafe..5951ae8f30 100644
--- a/frontend/src/hooks/useScenarioLaunch.test.tsx
+++ b/frontend/src/hooks/useScenarioLaunch.test.tsx
@@ -1,6 +1,6 @@
import type { FormEvent } from 'react'
-import { act, renderHook } from '@testing-library/react'
+import { act, renderHook, waitFor } from '@testing-library/react'
import type { BuildRunRequestResult } from '@/components/Scenarios/scenarioLaunchRequest'
import { scenariosApi } from '@/services/api'
@@ -114,6 +114,24 @@ describe('useScenarioLaunch', () => {
expect(view.result.current.submitting).toBe(false)
})
+ it('focuses the error banner, not Launch scan, when the launch is rejected', async () => {
+ startRun.mockRejectedValue({ isAxiosError: true, response: { status: 400, data: { detail: 'Select a dataset.' } } })
+ const { view } = renderLaunch()
+ const banner = document.createElement('div')
+ banner.tabIndex = -1
+ const button = document.createElement('button')
+ document.body.append(banner, button)
+ view.result.current.apiErrorRef.current = banner
+ view.result.current.launchButtonRef.current = button
+ act(() => view.result.current.submitForm(submitEvent()))
+
+ await act(async () => { await view.result.current.confirmLaunch() })
+
+ await waitFor(() => expect(banner).toHaveFocus())
+ banner.remove()
+ button.remove()
+ })
+
it('shows the field messages of a rejected request', async () => {
startRun.mockRejectedValue(BLANK_DATASET_NAME)
const { view } = renderLaunch()
diff --git a/frontend/src/hooks/useScenarioLaunch.ts b/frontend/src/hooks/useScenarioLaunch.ts
index e4d0ee3525..096e90bee3 100644
--- a/frontend/src/hooks/useScenarioLaunch.ts
+++ b/frontend/src/hooks/useScenarioLaunch.ts
@@ -24,13 +24,15 @@ export interface ScenarioLaunch {
/** Synchronous submit state, for guards that run before React re-renders. */
isSubmitting: () => boolean
launchButtonRef: RefObject
+ /** The banner for a rejected launch; it takes focus so the reason scrolls into view. */
+ apiErrorRef: RefObject
submitForm: (event: FormEvent) => void
dismissPreview: () => void
changePreviewOpen: (open: boolean) => void
confirmLaunch: () => Promise
}
-function focusSoon(ref: RefObject): void {
+function focusSoon(ref: RefObject): void {
const focus = () => {
ref.current?.focus()
}
@@ -55,6 +57,7 @@ export function useScenarioLaunch({
// Synchronous guard against a double-submit racing ahead of the state update.
const isSubmittingRef = useRef(false)
const launchButtonRef = useRef(null)
+ const apiErrorRef = useRef(null)
const submitForm = (event: FormEvent): void => {
event.preventDefault()
@@ -107,7 +110,7 @@ export function useScenarioLaunch({
} catch (err) {
setApiError(apiErrorMessage(toApiError(err)))
setPreviewOpen(false)
- focusSoon(launchButtonRef)
+ focusSoon(apiErrorRef)
} finally {
isSubmittingRef.current = false
setSubmitting(false)
@@ -122,6 +125,7 @@ export function useScenarioLaunch({
clearValidationError: () => setValidationError(null),
isSubmitting: () => isSubmittingRef.current,
launchButtonRef,
+ apiErrorRef,
submitForm,
dismissPreview,
changePreviewOpen,
diff --git a/frontend/src/hooks/useScenarioRunEstimate.test.tsx b/frontend/src/hooks/useScenarioRunEstimate.test.tsx
index 9b4614dbd4..f3e4cdfeeb 100644
--- a/frontend/src/hooks/useScenarioRunEstimate.test.tsx
+++ b/frontend/src/hooks/useScenarioRunEstimate.test.tsx
@@ -143,6 +143,18 @@ describe('useScenarioRunEstimate', () => {
expect(view.result.current.datasetProjection?.effective_datasets?.max_total).toBe(7)
})
+ it.each([
+ [400, 'Complete the required configuration to request an estimate.'],
+ [422, 'Complete the required configuration to request an estimate.'],
+ [503, 'The backend estimate could not be refreshed.'],
+ ])('labels a %i without an earlier estimate as %s', async (status, label) => {
+ estimateRun.mockRejectedValueOnce({ isAxiosError: true, response: { status, data: { detail: 'Select a dataset.' } } })
+ const view = renderEstimate({ request: { techniques: ['a'] } })
+ await settle()
+
+ expect(view.result.current.state).toMatchObject({ status: 'unavailable', label, note: 'Select a dataset.' })
+ })
+
it('reports why no request could be built instead of calling the backend', async () => {
const view = renderEstimate({ request: null, invalidReason: 'Select a target.' })
await settle()
diff --git a/frontend/src/hooks/useScenarioRunEstimate.ts b/frontend/src/hooks/useScenarioRunEstimate.ts
index d34c72a757..605ca23622 100644
--- a/frontend/src/hooks/useScenarioRunEstimate.ts
+++ b/frontend/src/hooks/useScenarioRunEstimate.ts
@@ -13,12 +13,14 @@ import type {
export const ESTIMATE_DEBOUNCE_MS = 300
+const REQUIRED_CONFIGURATION_LABEL = 'Complete the required configuration to request an estimate.'
+
type SuccessfulEstimateResult = Extract
/** The backend answer for one request key. */
export type EstimateRequestState =
| { status: 'resolved', requestKey: string, result: ScenarioRunEstimateResult, datasetSettings?: ScenarioDatasetSettings }
- | { status: 'error', requestKey: string, error: string }
+ | { status: 'error', requestKey: string, error: string, httpStatus: number | null }
interface UseScenarioRunEstimateInput {
scenarioName: string
@@ -88,7 +90,7 @@ export function useScenarioRunEstimate({
.catch((err: unknown) => {
if (isStale()) return
const error = toApiError(err)
- setRequestState({ status: 'error', requestKey, error: apiErrorMessage(error) })
+ setRequestState({ status: 'error', requestKey, error: apiErrorMessage(error), httpStatus: error.status })
if (request.datasets && (error.status === 400 || error.status === 422)) {
const { datasets, ...defaultRequest } = request
void datasets
@@ -133,7 +135,7 @@ function estimateState({
return {
status: 'unavailable',
scope: 'request',
- label: 'Complete the required configuration to request an estimate.',
+ label: REQUIRED_CONFIGURATION_LABEL,
note: invalidReason,
}
}
@@ -151,7 +153,10 @@ function estimateState({
: {
status: 'unavailable',
scope: 'request',
- label: 'The backend estimate could not be refreshed.',
+ // A 400 or 422 rejects the configuration itself; the backend is working.
+ label: current.httpStatus === 400 || current.httpStatus === 422
+ ? REQUIRED_CONFIGURATION_LABEL
+ : 'The backend estimate could not be refreshed.',
note: current.error,
}
}
diff --git a/pyrit/scenario/core/scenario.py b/pyrit/scenario/core/scenario.py
index 4abeffd2b9..a1445332ad 100644
--- a/pyrit/scenario/core/scenario.py
+++ b/pyrit/scenario/core/scenario.py
@@ -820,10 +820,10 @@ async def get_default_run_size_estimate_async(self) -> ScenarioRunSizeEstimate:
allow_missing_required=True,
)
self._params_resolved = True
+ # Options depend on the current configuration, so drop any left by an earlier call on this instance.
+ self._dataset_config = self._resolve_default_dataset_config()
try:
- validate_minimum_selection(
- config=self._resolve_default_dataset_config(), options=self.get_dataset_options()
- )
+ validate_minimum_selection(config=self._dataset_config, options=self.get_dataset_options())
except DatasetConstraintError as error:
# A scenario that needs a dataset and has no default has no default run to size.
return ScenarioRunSizeEstimate.unavailable(note=str(error))
diff --git a/tests/unit/scenario/core/test_scenario_dataset_overrides.py b/tests/unit/scenario/core/test_scenario_dataset_overrides.py
index 92ac42ed5b..1bfc93b3a9 100644
--- a/tests/unit/scenario/core/test_scenario_dataset_overrides.py
+++ b/tests/unit/scenario/core/test_scenario_dataset_overrides.py
@@ -269,6 +269,30 @@ class _RequiredInlineScenario(_InlineScenario):
assert options.min_selected is None
+@pytest.mark.usefixtures("patch_central_database")
+async def test_default_estimate_ignores_an_earlier_inline_configuration() -> None:
+ class _RequiredScenario(_Scenario):
+ DATASET_OPTIONS = ScenarioDatasetOptions(min_selected=1)
+
+ def __init__(self) -> None:
+ Scenario.__init__(
+ self,
+ version=1,
+ technique_class=_Technique,
+ default_dataset_config=DatasetAttackConfiguration(max_per_dataset="all", max_total="all"),
+ objective_scorer=SubStringScorer(substring="yes"),
+ )
+
+ scenario = _RequiredScenario()
+ inline = DatasetAttackConfiguration(seeds=[SeedObjective(value="x")], max_total=1)
+ scenario.set_params_from_args(args={"dataset_config": inline})
+ await scenario.get_run_size_estimate_async()
+
+ estimate = await scenario.get_default_run_size_estimate_async()
+ assert estimate.status.value == "unavailable"
+ assert estimate.note == "Select a dataset."
+
+
@pytest.mark.usefixtures("patch_central_database")
@pytest.mark.parametrize("args", [{}, {"dataset_overrides": {"sources": [{"name": "a"}]}}])
async def test_declared_minimum_selection_applies_with_or_without_overrides(args: dict[str, object]) -> None:
From df2e9e361f7b3ece3f942d664b209af7250bdafb Mon Sep 17 00:00:00 2001
From: Richard Lundeen
Date: Fri, 20 Nov 2026 13:58:41 -0800
Subject: [PATCH 5/8] FIX: Show the dataset requirement on the picker before
the run preview
Launch scan with fewer datasets than the scenario declares in min_selected
now keeps the form open and shows the server's wording on the focused,
required Add dataset picker instead of opening the Run preview. The text is
the server's estimate rejection for this request when there is one, else
the library's validate_minimum_selection wording; the library stays the
only enforcer. The message clears once enough datasets are selected.
The Run preview disables Launch scan while the server rejected the current
request's estimate (HTTP 400 or 422), and those rejections are labelled
"Fix the configuration to request an estimate." The missing-input label
stays for configurations the form can't build.
Co-Authored-By: Claude Opus 5.5
---
.../Scenarios/ScenarioDatasetTable.tsx | 12 ++--
.../Scenarios/ScenarioDetail.test.tsx | 65 ++++++++++++++++---
.../components/Scenarios/ScenarioDetail.tsx | 15 ++++-
.../Scenarios/scenarioLaunchRequest.test.ts | 8 +++
.../Scenarios/scenarioLaunchRequest.ts | 9 +++
frontend/src/hooks/useScenarioLaunch.test.tsx | 27 +++++++-
frontend/src/hooks/useScenarioLaunch.ts | 25 +++++++
.../src/hooks/useScenarioRunEstimate.test.tsx | 31 +++++++--
frontend/src/hooks/useScenarioRunEstimate.ts | 14 ++--
9 files changed, 180 insertions(+), 26 deletions(-)
diff --git a/frontend/src/components/Scenarios/ScenarioDatasetTable.tsx b/frontend/src/components/Scenarios/ScenarioDatasetTable.tsx
index 268efb1630..47f8983f0f 100644
--- a/frontend/src/components/Scenarios/ScenarioDatasetTable.tsx
+++ b/frontend/src/components/Scenarios/ScenarioDatasetTable.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useId, useState } from 'react'
+import { type Ref, useEffect, useId, useState } from 'react'
import {
Badge, Button, Combobox, Divider, mergeClasses, MessageBar, MessageBarBody, Option, Radio, RadioGroup,
@@ -32,6 +32,9 @@ interface ScenarioDatasetTableProps {
onLoad?: () => void
/** Marks the picker required until the first dataset is chosen. */
required?: boolean
+ /** The server's reason the required picker has too few datasets, shown as its validation message. */
+ selectionError?: string | null
+ pickerRef?: Ref
onReload: () => void
onChange: (request: ScenarioDatasetRequest) => void
onValidationChange: (error: string | null) => void
@@ -39,7 +42,7 @@ interface ScenarioDatasetTableProps {
export default function ScenarioDatasetTable({
request, defaults, effective, options, datasets, disabled, loading, metadataError,
- preparing = false, loadError, loadEnabled = false, onLoad, required = false,
+ preparing = false, loadError, loadEnabled = false, onLoad, required = false, selectionError = null, pickerRef,
onReload, onChange, onValidationChange,
}: ScenarioDatasetTableProps) {
const styles = useScenarioDatasetTableStyles()
@@ -142,7 +145,7 @@ export default function ScenarioDatasetTable({
: policies[0] === 'always' ? 'Refresh datasets for each new scan'
: policies[0] === 'never' ? 'Only use datasets already in memory'
: 'Load missing datasets'
- const picker = { if (data.open) onReload() }}
onChange={(event) => setSearch(event.target.value)}
@@ -242,7 +245,8 @@ export default function ScenarioDatasetTable({
}
{canSelect &&
{(canAdd || replaceSingleSource) && (required ?
+ label={replaceSingleSource ? 'Choose dataset' : 'Add dataset'} required={selected.length === 0}
+ validationMessage={selectionError ?? undefined} validationState={selectionError ? 'error' : 'none'}>
{picker}
: picker)}
{/* Reset clears source and per-dataset edits, so it shows only when there are some. Saved presets
diff --git a/frontend/src/components/Scenarios/ScenarioDetail.test.tsx b/frontend/src/components/Scenarios/ScenarioDetail.test.tsx
index c8de4a52e6..4f6c142519 100644
--- a/frontend/src/components/Scenarios/ScenarioDetail.test.tsx
+++ b/frontend/src/components/Scenarios/ScenarioDetail.test.tsx
@@ -3373,27 +3373,76 @@ describe('ScenarioDetail', () => {
expect(screen.getByRole('combobox', { name: 'Add dataset' })).not.toBeRequired()
})
- it('should show the server message for a missing required dataset in the estimate and on launch', async () => {
+ it('should show the server message for a missing required dataset on the focused picker before any preview', async () => {
const user = userEvent.setup()
// The library rejects a selection below the scenario's declared minimum with this 400.
const missingDataset = { isAxiosError: true, response: { status: 400, data: { detail: 'Select a dataset.' } } }
mockGetScenario.mockResolvedValue(policyScenario())
mockEstimateRun.mockRejectedValue(missingDataset)
- mockStartRun.mockRejectedValue(missingDataset)
renderDetail(POLICY_PATH)
const estimate = await screen.findByTestId('run-estimate')
await waitFor(() => expect(within(estimate).getByRole('status')).toHaveTextContent('Select a dataset.'))
// The 400 rejects the configuration, not the backend.
- expect(within(estimate).getByRole('status'))
- .toHaveTextContent('Complete the required configuration to request an estimate.')
+ expect(within(estimate).getByRole('status')).toHaveTextContent('Fix the configuration to request an estimate.')
expect(estimate).not.toHaveTextContent('The backend estimate could not be refreshed.')
+ const picker = screen.getByRole('combobox', { name: 'Add dataset' })
+ expect(picker).toBeRequired()
+ expect(picker).not.toHaveAttribute('aria-invalid', 'true')
+ jest.mocked(Element.prototype.scrollIntoView).mockClear()
+
await waitFor(() => expect(screen.getByRole('button', { name: 'Launch scan' })).toBeEnabled())
- await confirmRunPreview(user)
+ await user.click(screen.getByRole('button', { name: 'Launch scan' }))
- await waitFor(() => expect(mockStartRun).toHaveBeenCalledTimes(1))
- await waitFor(() => expect(screen.getAllByRole('alert').map((alert) => alert.textContent))
- .toContain('Select a dataset.'))
+ await waitFor(() => expect(picker).toHaveFocus())
+ expect(picker).toHaveAttribute('aria-invalid', 'true')
+ expect(picker).toHaveAccessibleDescription('Select a dataset.')
+ // Focus scrolls the form to the picker; scrollIntoView would also scroll the app shell.
+ expect(Element.prototype.scrollIntoView).not.toHaveBeenCalled()
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+ // The picker carries the error, so the banner at the top of the form stays empty.
+ expect(screen.getAllByRole('alert').map((alert) => alert.textContent)).toEqual(['Select a dataset.'])
+ expect(mockStartRun).not.toHaveBeenCalled()
+
+ mockEstimateRun.mockResolvedValue(makeEstimate(25))
+ await user.click(picker)
+ await user.click(screen.getByRole('option', { name: 'ds_a (Unknown)', exact: true }))
+ expect(picker).not.toHaveAttribute('aria-invalid', 'true')
+ expect(screen.getByRole('combobox', { name: 'Add dataset' })).not.toHaveAccessibleDescription('Select a dataset.')
+ })
+
+ it('should word a shortfall as the library does while the server has not rejected the selection', async () => {
+ const user = userEvent.setup()
+ mockGetScenario.mockResolvedValue(makeScenario({
+ ...policyScenario(),
+ dataset_options: { ...policyScenario().dataset_options!, min_selected: 2 },
+ }))
+ mockEstimateRun.mockResolvedValue(makeEstimate(25))
+ renderDetail(`${POLICY_PATH}?dataset=ds_a`)
+
+ expect(await screen.findByText('ds_a (Unknown)')).toBeInTheDocument()
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Launch scan' })).toBeEnabled())
+ await user.click(screen.getByRole('button', { name: 'Launch scan' }))
+
+ const picker = screen.getByRole('combobox', { name: 'Add dataset' })
+ await waitFor(() => expect(picker).toHaveFocus())
+ expect(picker).toHaveAccessibleDescription('Select at least 2 datasets.')
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+ })
+
+ it('should not offer Launch scan in the preview for a request the server rejected', async () => {
+ const user = userEvent.setup()
+ mockGetScenario.mockResolvedValue(policyScenario())
+ mockEstimateRun.mockRejectedValue({
+ isAxiosError: true, response: { status: 400, data: { detail: 'max_turns must be at least 1.' } },
+ })
+ renderDetail(`${POLICY_PATH}?dataset=ds_a`)
+
+ const dialog = await openRunPreview(user)
+ await waitFor(() => expect(dialog).toHaveTextContent('max_turns must be at least 1.'))
+ expect(dialog).toHaveTextContent('Fix the configuration to request an estimate.')
+ expect(screen.getByTestId('confirm-launch-scenario-btn')).toBeDisabled()
+ expect(within(dialog).getByRole('button', { name: 'Cancel' })).toBeEnabled()
})
it('should open Browse datasets from the Datasets header in a new tab', async () => {
diff --git a/frontend/src/components/Scenarios/ScenarioDetail.tsx b/frontend/src/components/Scenarios/ScenarioDetail.tsx
index 5279e82f97..681932372a 100644
--- a/frontend/src/components/Scenarios/ScenarioDetail.tsx
+++ b/frontend/src/components/Scenarios/ScenarioDetail.tsx
@@ -99,6 +99,7 @@ import {
type ScenarioLaunchInput,
scenarioDynamicParameters,
linkedDatasetProblem,
+ minimumSelectionMessage,
requiresDatasetSelection,
supportsParameter,
} from './scenarioLaunchRequest'
@@ -616,6 +617,13 @@ function ScenarioLaunchForm({
const datasetOptions: ScenarioDatasetOptions = datasetProjection?.dataset_options
?? scenarioDatasetOptions(scenario)
const selectedDatasetNames = (datasetEdits.sources ?? datasetDefaults.sources).map((source) => source.name)
+ // The server enforces the scenario's declared minimum. Launch scan presents it on the required picker,
+ // preferring the server's own rejection of this request over the library's wording for the minimum.
+ const minimumDatasets = scenario.dataset_options?.min_selected ?? 0
+ const datasetPickerShown = supportsDatasets && datasetOptions.supports_overrides && datasetOptions.mode !== 'fixed'
+ const datasetSelectionMessage = datasetPickerShown && selectedDatasetNames.length < minimumDatasets
+ ? runEstimate.rejection ?? minimumSelectionMessage(minimumDatasets)
+ : null
const datasetSelectionKey = JSON.stringify(selectedDatasetNames)
const reloadDatasetMetadata = datasetMetadata.reload
const previousDatasetSelection = useRef(datasetSelectionKey)
@@ -663,16 +671,19 @@ function ScenarioLaunchForm({
submitting,
apiError,
validationError,
+ datasetSelectionError,
clearValidationError,
isSubmitting,
launchButtonRef,
apiErrorRef,
+ datasetPickerRef,
submitForm,
dismissPreview,
changePreviewOpen,
confirmLaunch,
} = useScenarioLaunch({
requestResult,
+ datasetSelectionMessage,
submitBlocked: conversationBusy || Boolean(techniqueEditError),
launchBlocked: conversationBusy || Boolean(techniqueEditError) || !runtime.ready || !defaultsReady
|| staleSelection || unavailableSelection || checkingRefreshPolicies,
@@ -1039,7 +1050,7 @@ function ScenarioLaunchForm({
&& !confirmedDatasetSettings.sources.some((source) => source.fetch === 'always'
&& !datasetMetadata.items.some((item) => item.name === source.name && item.loaded))}
onLoad={() => { if (estimateRequest) void datasetMetadata.loadSelected(scenario.scenario_name, estimateRequest) }}
- required={datasetRequired}
+ required={datasetRequired} selectionError={datasetSelectionError} pickerRef={datasetPickerRef}
onReload={datasetMetadata.reload} onChange={setDatasetEdits} onValidationChange={setDatasetError}
/>
@@ -1158,7 +1169,7 @@ function ScenarioLaunchForm({
open={previewOpen}
submitting={submitting}
confirmDisabled={submitting || conversationBusy || !runtime.ready || !defaultsReady || !requestResult.ok
- || checkingRefreshPolicies}
+ || checkingRefreshPolicies || runEstimate.rejection !== null}
onOpenChange={changePreviewOpen}
onCancel={dismissPreview}
onConfirm={() => void confirmLaunch()}
diff --git a/frontend/src/components/Scenarios/scenarioLaunchRequest.test.ts b/frontend/src/components/Scenarios/scenarioLaunchRequest.test.ts
index 811009d3e5..5d443d317f 100644
--- a/frontend/src/components/Scenarios/scenarioLaunchRequest.test.ts
+++ b/frontend/src/components/Scenarios/scenarioLaunchRequest.test.ts
@@ -4,6 +4,7 @@ import {
buildEstimateRequest,
buildRunRequest,
linkedDatasetProblem,
+ minimumSelectionMessage,
scenarioDynamicParameters,
type ScenarioLaunchInput,
} from './scenarioLaunchRequest'
@@ -156,4 +157,11 @@ describe('scenario launch requests', () => {
// An identical payload keeps the estimate key, so editing launch-only fields sends no new estimate.
expect(after).toEqual(before)
})
+
+ it.each([[1, 'Select a dataset.'], [2, 'Select at least 2 datasets.']])(
+ 'words a minimum of %i datasets as validate_minimum_selection does',
+ (minimum, message) => {
+ expect(minimumSelectionMessage(minimum)).toBe(message)
+ },
+ )
})
diff --git a/frontend/src/components/Scenarios/scenarioLaunchRequest.ts b/frontend/src/components/Scenarios/scenarioLaunchRequest.ts
index ca60345ca5..45f7c19c30 100644
--- a/frontend/src/components/Scenarios/scenarioLaunchRequest.ts
+++ b/frontend/src/components/Scenarios/scenarioLaunchRequest.ts
@@ -49,6 +49,15 @@ export function requiresDatasetSelection(scenario: RegisteredScenario): boolean
return (scenario.dataset_options?.min_selected ?? 0) > 0
}
+/**
+ * The library's message for fewer datasets than a declared minimum, worded as ``validate_minimum_selection``
+ * in pyrit/scenario/core/dataset_overrides.py words it. The server enforces the minimum; the form shows this
+ * only while it has no estimate rejection of its own to show.
+ */
+export function minimumSelectionMessage(minimum: number): string {
+ return minimum === 1 ? 'Select a dataset.' : `Select at least ${minimum} datasets.`
+}
+
function linkedDatasetLabel(name: string): string {
return name !== '' && name === name.trim() ? name : JSON.stringify(name)
}
diff --git a/frontend/src/hooks/useScenarioLaunch.test.tsx b/frontend/src/hooks/useScenarioLaunch.test.tsx
index 5951ae8f30..cde12cfeb3 100644
--- a/frontend/src/hooks/useScenarioLaunch.test.tsx
+++ b/frontend/src/hooks/useScenarioLaunch.test.tsx
@@ -35,6 +35,7 @@ const BLANK_DATASET_NAME = {
interface Props {
requestResult?: BuildRunRequestResult
+ datasetSelectionMessage?: string | null
submitBlocked?: boolean
launchBlocked?: boolean
}
@@ -42,9 +43,8 @@ interface Props {
function renderLaunch(initial: Props = {}) {
const onLaunched = jest.fn()
const view = renderHook(
- ({ requestResult = VALID, submitBlocked = false, launchBlocked = false }: Props) => useScenarioLaunch({
- requestResult, submitBlocked, launchBlocked, onLaunched,
- }),
+ ({ requestResult = VALID, datasetSelectionMessage = null, submitBlocked = false, launchBlocked = false }: Props) =>
+ useScenarioLaunch({ requestResult, datasetSelectionMessage, submitBlocked, launchBlocked, onLaunched }),
{ initialProps: initial },
)
return { view, onLaunched }
@@ -69,6 +69,27 @@ describe('useScenarioLaunch', () => {
expect(view.result.current.validationError).toBeNull()
})
+ it('shows too few datasets on the focused picker instead of opening the confirmation', async () => {
+ const { view } = renderLaunch({ datasetSelectionMessage: 'Select a dataset.' })
+ const picker = document.createElement('input')
+ document.body.append(picker)
+ view.result.current.datasetPickerRef.current = picker
+ expect(view.result.current.datasetSelectionError).toBeNull()
+
+ act(() => view.result.current.submitForm(submitEvent()))
+
+ expect(view.result.current.previewOpen).toBe(false)
+ expect(view.result.current.datasetSelectionError).toBe('Select a dataset.')
+ await waitFor(() => expect(picker).toHaveFocus())
+
+ // Enough datasets clear the message; a later shortfall waits for the next Launch scan.
+ view.rerender({ datasetSelectionMessage: null })
+ expect(view.result.current.datasetSelectionError).toBeNull()
+ view.rerender({ datasetSelectionMessage: 'Select a dataset.' })
+ expect(view.result.current.datasetSelectionError).toBeNull()
+ picker.remove()
+ })
+
it('does not open the confirmation while submitting is blocked', () => {
const { view } = renderLaunch({ submitBlocked: true })
act(() => view.result.current.submitForm(submitEvent()))
diff --git a/frontend/src/hooks/useScenarioLaunch.ts b/frontend/src/hooks/useScenarioLaunch.ts
index 096e90bee3..755ad2e6a8 100644
--- a/frontend/src/hooks/useScenarioLaunch.ts
+++ b/frontend/src/hooks/useScenarioLaunch.ts
@@ -8,6 +8,11 @@ import type { ScenarioRunSummary } from '@/types'
interface UseScenarioLaunchInput {
/** The run request built from the current form, or why it can't be built. */
requestResult: BuildRunRequestResult
+ /**
+ * The server's reason the selected datasets are fewer than the scenario's declared minimum, or null when
+ * there are enough. Launch scan shows it on the dataset picker instead of opening the confirmation.
+ */
+ datasetSelectionMessage: string | null
/** True when the form can't open the confirmation, for example while a conversation is being edited. */
submitBlocked: boolean
/** True when a confirmed launch must not start, for example while the runtime is not ready. */
@@ -20,12 +25,16 @@ export interface ScenarioLaunch {
submitting: boolean
apiError: string | null
validationError: string | null
+ /** The dataset picker's message after Launch scan with too few datasets; it clears once there are enough. */
+ datasetSelectionError: string | null
clearValidationError: () => void
/** Synchronous submit state, for guards that run before React re-renders. */
isSubmitting: () => boolean
launchButtonRef: RefObject
/** The banner for a rejected launch; it takes focus so the reason scrolls into view. */
apiErrorRef: RefObject
+ /** The dataset picker; it takes focus when it reports too few datasets. */
+ datasetPickerRef: RefObject
submitForm: (event: FormEvent) => void
dismissPreview: () => void
changePreviewOpen: (open: boolean) => void
@@ -46,6 +55,7 @@ function focusSoon(ref: RefObject): void {
/** Own the confirmation dialog and the single in-flight launch for a scenario run. */
export function useScenarioLaunch({
requestResult,
+ datasetSelectionMessage,
submitBlocked,
launchBlocked,
onLaunched,
@@ -54,10 +64,17 @@ export function useScenarioLaunch({
const [submitting, setSubmitting] = useState(false)
const [apiError, setApiError] = useState(null)
const [validationError, setValidationError] = useState(null)
+ const [showDatasetSelectionError, setShowDatasetSelectionError] = useState(false)
// Synchronous guard against a double-submit racing ahead of the state update.
const isSubmittingRef = useRef(false)
const launchButtonRef = useRef(null)
const apiErrorRef = useRef(null)
+ const datasetPickerRef = useRef(null)
+
+ // Enough datasets clear the message, so a later shortfall waits for the next Launch scan.
+ if (showDatasetSelectionError && datasetSelectionMessage === null) {
+ setShowDatasetSelectionError(false)
+ }
const submitForm = (event: FormEvent): void => {
event.preventDefault()
@@ -68,6 +85,12 @@ export function useScenarioLaunch({
return
}
setValidationError(null)
+ if (datasetSelectionMessage !== null) {
+ setShowDatasetSelectionError(true)
+ // Focus scrolls the form to the picker; scrollIntoView would also scroll the app shell.
+ focusSoon(datasetPickerRef)
+ return
+ }
setPreviewOpen(true)
}
@@ -122,10 +145,12 @@ export function useScenarioLaunch({
submitting,
apiError,
validationError,
+ datasetSelectionError: showDatasetSelectionError ? datasetSelectionMessage : null,
clearValidationError: () => setValidationError(null),
isSubmitting: () => isSubmittingRef.current,
launchButtonRef,
apiErrorRef,
+ datasetPickerRef,
submitForm,
dismissPreview,
changePreviewOpen,
diff --git a/frontend/src/hooks/useScenarioRunEstimate.test.tsx b/frontend/src/hooks/useScenarioRunEstimate.test.tsx
index f3e4cdfeeb..040aafa790 100644
--- a/frontend/src/hooks/useScenarioRunEstimate.test.tsx
+++ b/frontend/src/hooks/useScenarioRunEstimate.test.tsx
@@ -144,15 +144,31 @@ describe('useScenarioRunEstimate', () => {
})
it.each([
- [400, 'Complete the required configuration to request an estimate.'],
- [422, 'Complete the required configuration to request an estimate.'],
- [503, 'The backend estimate could not be refreshed.'],
- ])('labels a %i without an earlier estimate as %s', async (status, label) => {
+ [400, 'Fix the configuration to request an estimate.', 'Select a dataset.'],
+ [422, 'Fix the configuration to request an estimate.', 'Select a dataset.'],
+ [503, 'The backend estimate could not be refreshed.', null],
+ ])('labels a %i without an earlier estimate as %s', async (status, label, rejection) => {
estimateRun.mockRejectedValueOnce({ isAxiosError: true, response: { status, data: { detail: 'Select a dataset.' } } })
const view = renderEstimate({ request: { techniques: ['a'] } })
await settle()
expect(view.result.current.state).toMatchObject({ status: 'unavailable', label, note: 'Select a dataset.' })
+ // Only a rejected configuration, not an unavailable backend, reports the server's rejection.
+ expect(view.result.current.rejection).toBe(rejection)
+ })
+
+ it('reports a rejection only for the request the server rejected', async () => {
+ estimateRun
+ .mockRejectedValueOnce({ isAxiosError: true, response: { status: 400, data: { detail: 'Select a dataset.' } } })
+ .mockResolvedValueOnce(response(3))
+ const view = renderEstimate({ request: { techniques: ['a'] } })
+ await settle()
+ expect(view.result.current.rejection).toBe('Select a dataset.')
+
+ view.rerender({ request: { techniques: ['a'], datasets: { sources: [{ name: 'ds_a' }] } } })
+ expect(view.result.current.rejection).toBeNull()
+ await settle()
+ expect(view.result.current.rejection).toBeNull()
})
it('reports why no request could be built instead of calling the backend', async () => {
@@ -160,7 +176,12 @@ describe('useScenarioRunEstimate', () => {
await settle()
expect(estimateRun).not.toHaveBeenCalled()
- expect(view.result.current.state).toMatchObject({ status: 'unavailable', note: 'Select a target.' })
+ expect(view.result.current.state).toMatchObject({
+ status: 'unavailable',
+ label: 'Complete the required configuration to request an estimate.',
+ note: 'Select a target.',
+ })
+ expect(view.result.current.rejection).toBeNull()
})
it.each([
diff --git a/frontend/src/hooks/useScenarioRunEstimate.ts b/frontend/src/hooks/useScenarioRunEstimate.ts
index 605ca23622..f58dd5c6d6 100644
--- a/frontend/src/hooks/useScenarioRunEstimate.ts
+++ b/frontend/src/hooks/useScenarioRunEstimate.ts
@@ -14,6 +14,7 @@ import type {
export const ESTIMATE_DEBOUNCE_MS = 300
const REQUIRED_CONFIGURATION_LABEL = 'Complete the required configuration to request an estimate.'
+const REJECTED_CONFIGURATION_LABEL = 'Fix the configuration to request an estimate.'
type SuccessfulEstimateResult = Extract
@@ -41,6 +42,13 @@ export interface ScenarioRunEstimate {
datasetProjection: ScenarioRunSizeEstimateResponse | null
/** The backend answer for the current request, or null while it's pending. */
current: EstimateRequestState | null
+ /** The server's message when it rejected the current request's configuration (HTTP 400 or 422), else null. */
+ rejection: string | null
+}
+
+function isRejection(state: EstimateRequestState | null): state is Extract {
+ // A 400 or 422 rejects the configuration itself; the backend is working.
+ return state?.status === 'error' && (state.httpStatus === 400 || state.httpStatus === 422)
}
/**
@@ -119,6 +127,7 @@ export function useScenarioRunEstimate({
state: estimateState({ invalidReason: request === null ? invalidReason : null, current, lastGoodEstimate }),
datasetProjection,
current,
+ rejection: isRejection(current) ? current.error : null,
}
}
@@ -153,10 +162,7 @@ function estimateState({
: {
status: 'unavailable',
scope: 'request',
- // A 400 or 422 rejects the configuration itself; the backend is working.
- label: current.httpStatus === 400 || current.httpStatus === 422
- ? REQUIRED_CONFIGURATION_LABEL
- : 'The backend estimate could not be refreshed.',
+ label: isRejection(current) ? REJECTED_CONFIGURATION_LABEL : 'The backend estimate could not be refreshed.',
note: current.error,
}
}
From 150ff74b8f679931d0c40805d5dc422ebe321448 Mon Sep 17 00:00:00 2001
From: Richard Lundeen
Date: Fri, 20 Nov 2026 14:10:15 -0800
Subject: [PATCH 6/8] FIX: Keep other estimate rejections off the dataset
picker
The server checks parameters and techniques before the dataset count, so its
estimate rejection can be about another field. The picker now always shows
the library's wording for the declared minimum; other rejections stay in the
run estimate and disable the preview's Launch scan.
Co-Authored-By: Claude Opus 5.5
---
.../Scenarios/ScenarioDatasetTable.tsx | 2 +-
.../Scenarios/ScenarioDetail.test.tsx | 21 +++++++++++++++++++
.../components/Scenarios/ScenarioDetail.tsx | 6 +++---
.../Scenarios/scenarioLaunchRequest.ts | 2 +-
frontend/src/hooks/useScenarioLaunch.ts | 4 ++--
5 files changed, 28 insertions(+), 7 deletions(-)
diff --git a/frontend/src/components/Scenarios/ScenarioDatasetTable.tsx b/frontend/src/components/Scenarios/ScenarioDatasetTable.tsx
index 47f8983f0f..2189d17127 100644
--- a/frontend/src/components/Scenarios/ScenarioDatasetTable.tsx
+++ b/frontend/src/components/Scenarios/ScenarioDatasetTable.tsx
@@ -32,7 +32,7 @@ interface ScenarioDatasetTableProps {
onLoad?: () => void
/** Marks the picker required until the first dataset is chosen. */
required?: boolean
- /** The server's reason the required picker has too few datasets, shown as its validation message. */
+ /** Why the required picker has too few datasets, shown as its validation message. */
selectionError?: string | null
pickerRef?: Ref
onReload: () => void
diff --git a/frontend/src/components/Scenarios/ScenarioDetail.test.tsx b/frontend/src/components/Scenarios/ScenarioDetail.test.tsx
index 4f6c142519..a28ed41033 100644
--- a/frontend/src/components/Scenarios/ScenarioDetail.test.tsx
+++ b/frontend/src/components/Scenarios/ScenarioDetail.test.tsx
@@ -3430,6 +3430,27 @@ describe('ScenarioDetail', () => {
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
})
+ it('should keep another field\'s estimate rejection off the dataset picker', async () => {
+ const user = userEvent.setup()
+ mockGetScenario.mockResolvedValue(policyScenario())
+ // The server checks parameters before the dataset count, so this rejection is not about datasets.
+ mockEstimateRun.mockRejectedValue({
+ isAxiosError: true, response: { status: 400, data: { detail: 'max_turns must be at least 1.' } },
+ })
+ renderDetail(POLICY_PATH)
+
+ const estimate = await screen.findByTestId('run-estimate')
+ await waitFor(() => expect(estimate).toHaveTextContent('max_turns must be at least 1.'))
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Launch scan' })).toBeEnabled())
+ await user.click(screen.getByRole('button', { name: 'Launch scan' }))
+
+ const picker = screen.getByRole('combobox', { name: 'Add dataset' })
+ await waitFor(() => expect(picker).toHaveFocus())
+ expect(picker).toHaveAccessibleDescription('Select a dataset.')
+ expect(picker).not.toHaveAccessibleDescription(expect.stringContaining('max_turns'))
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+ })
+
it('should not offer Launch scan in the preview for a request the server rejected', async () => {
const user = userEvent.setup()
mockGetScenario.mockResolvedValue(policyScenario())
diff --git a/frontend/src/components/Scenarios/ScenarioDetail.tsx b/frontend/src/components/Scenarios/ScenarioDetail.tsx
index 681932372a..47593627fd 100644
--- a/frontend/src/components/Scenarios/ScenarioDetail.tsx
+++ b/frontend/src/components/Scenarios/ScenarioDetail.tsx
@@ -617,12 +617,12 @@ function ScenarioLaunchForm({
const datasetOptions: ScenarioDatasetOptions = datasetProjection?.dataset_options
?? scenarioDatasetOptions(scenario)
const selectedDatasetNames = (datasetEdits.sources ?? datasetDefaults.sources).map((source) => source.name)
- // The server enforces the scenario's declared minimum. Launch scan presents it on the required picker,
- // preferring the server's own rejection of this request over the library's wording for the minimum.
+ // The server enforces the scenario's declared minimum. Launch scan presents it on the required picker in the
+ // library's wording; the estimate's own rejection can be about another field, so it stays in the run estimate.
const minimumDatasets = scenario.dataset_options?.min_selected ?? 0
const datasetPickerShown = supportsDatasets && datasetOptions.supports_overrides && datasetOptions.mode !== 'fixed'
const datasetSelectionMessage = datasetPickerShown && selectedDatasetNames.length < minimumDatasets
- ? runEstimate.rejection ?? minimumSelectionMessage(minimumDatasets)
+ ? minimumSelectionMessage(minimumDatasets)
: null
const datasetSelectionKey = JSON.stringify(selectedDatasetNames)
const reloadDatasetMetadata = datasetMetadata.reload
diff --git a/frontend/src/components/Scenarios/scenarioLaunchRequest.ts b/frontend/src/components/Scenarios/scenarioLaunchRequest.ts
index 45f7c19c30..9d5ec9feac 100644
--- a/frontend/src/components/Scenarios/scenarioLaunchRequest.ts
+++ b/frontend/src/components/Scenarios/scenarioLaunchRequest.ts
@@ -52,7 +52,7 @@ export function requiresDatasetSelection(scenario: RegisteredScenario): boolean
/**
* The library's message for fewer datasets than a declared minimum, worded as ``validate_minimum_selection``
* in pyrit/scenario/core/dataset_overrides.py words it. The server enforces the minimum; the form shows this
- * only while it has no estimate rejection of its own to show.
+ * on the dataset picker, since the server checks other fields first and its rejection can be about one of them.
*/
export function minimumSelectionMessage(minimum: number): string {
return minimum === 1 ? 'Select a dataset.' : `Select at least ${minimum} datasets.`
diff --git a/frontend/src/hooks/useScenarioLaunch.ts b/frontend/src/hooks/useScenarioLaunch.ts
index 755ad2e6a8..1d3844432e 100644
--- a/frontend/src/hooks/useScenarioLaunch.ts
+++ b/frontend/src/hooks/useScenarioLaunch.ts
@@ -9,8 +9,8 @@ interface UseScenarioLaunchInput {
/** The run request built from the current form, or why it can't be built. */
requestResult: BuildRunRequestResult
/**
- * The server's reason the selected datasets are fewer than the scenario's declared minimum, or null when
- * there are enough. Launch scan shows it on the dataset picker instead of opening the confirmation.
+ * The library's message for fewer datasets than the scenario's declared minimum, or null when there are
+ * enough. Launch scan shows it on the dataset picker instead of opening the confirmation.
*/
datasetSelectionMessage: string | null
/** True when the form can't open the confirmation, for example while a conversation is being edited. */
From db15b2fcdd7173353f2e414ef54d1f3e28e5344a Mon Sep 17 00:00:00 2001
From: Richard Lundeen
Date: Fri, 20 Nov 2026 14:46:29 -0800
Subject: [PATCH 7/8] FIX: Drop the refresh warning from the preview of a
rejected request
Co-Authored-By: Claude Opus 5.5
---
frontend/src/components/Scenarios/ScenarioDetail.test.tsx | 1 +
frontend/src/components/Scenarios/ScenarioDetail.tsx | 3 ++-
2 files changed, 3 insertions(+), 1 deletion(-)
diff --git a/frontend/src/components/Scenarios/ScenarioDetail.test.tsx b/frontend/src/components/Scenarios/ScenarioDetail.test.tsx
index a28ed41033..dbe3a67a7b 100644
--- a/frontend/src/components/Scenarios/ScenarioDetail.test.tsx
+++ b/frontend/src/components/Scenarios/ScenarioDetail.test.tsx
@@ -3462,6 +3462,7 @@ describe('ScenarioDetail', () => {
const dialog = await openRunPreview(user)
await waitFor(() => expect(dialog).toHaveTextContent('max_turns must be at least 1.'))
expect(dialog).toHaveTextContent('Fix the configuration to request an estimate.')
+ expect(dialog).not.toHaveTextContent('Cannot confirm which datasets will refresh')
expect(screen.getByTestId('confirm-launch-scenario-btn')).toBeDisabled()
expect(within(dialog).getByRole('button', { name: 'Cancel' })).toBeEnabled()
})
diff --git a/frontend/src/components/Scenarios/ScenarioDetail.tsx b/frontend/src/components/Scenarios/ScenarioDetail.tsx
index 47593627fd..58263b66c6 100644
--- a/frontend/src/components/Scenarios/ScenarioDetail.tsx
+++ b/frontend/src/components/Scenarios/ScenarioDetail.tsx
@@ -1175,7 +1175,8 @@ function ScenarioLaunchForm({
onConfirm={() => void confirmLaunch()}
refresh={{
checking: checkingRefreshPolicies,
- unconfirmed: unconfirmedRefreshPolicies,
+ // A rejected request cannot launch, so its refresh effects do not apply.
+ unconfirmed: unconfirmedRefreshPolicies && runEstimate.rejection === null,
refreshed: refreshDatasets,
edited: editedRefreshDatasets,
unchecked: uncheckedRefreshDatasets,
From a77d58b50daf3708d553d6187b2315f44273ecca Mon Sep 17 00:00:00 2001
From: Richard Lundeen
Date: Fri, 20 Nov 2026 15:29:04 -0800
Subject: [PATCH 8/8] DOC: Explain ASSERT dataset selection from the CLI
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
---
doc/scanner/0_scanner.md | 6 ++++++
1 file changed, 6 insertions(+)
diff --git a/doc/scanner/0_scanner.md b/doc/scanner/0_scanner.md
index 4de563f5f5..043af06bf0 100644
--- a/doc/scanner/0_scanner.md
+++ b/doc/scanner/0_scanner.md
@@ -41,6 +41,12 @@ from ambient environment variables. A configured deterministic objective scorer
needs no scoring model; techniques without generation need no adversarial model.
See [scan targets](../code/setup/0_setup.md#scan-targets) for setup options.
+Select named datasets with `--datasets [ ...]`. For example,
+`foundry.assert_policy` has no default datasets: if it reports "Select a dataset.",
+pass the names of stored ASSERT datasets with `--datasets`. Create groups with
+`AssertGenerator` and store them with `AssertProvider` as shown in the
+[ASSERT generation guide](../code/executor/7_promptgen.ipynb).
+
### Connecting to CoPyRIT
Point a local configuration file at the remote backend: