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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions frontend/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,7 @@ function AppContent({ operatorAlias }: { operatorAlias: string | null }) {

const rerunValues = matchPath('/scanner/launch/:scenarioName', location.pathname)
? new URLSearchParams(location.search).getAll('rerun') : []
const rerunId = rerunValues.length ? rerunValues.length === 1 ? rerunValues[0] : '' : null
const rerunId = rerunValues.length ? (rerunValues.length === 1 ? (rerunValues[0] ?? '') : '') : null
const rerun = useScenarioLaunchSeed(rerunId, generation, ready)
const { updateAttribution: updateRerunAttribution } = rerun
const launchLabels = useMemo<Record<string, string>>(() => rerun.active
Expand Down Expand Up @@ -1089,7 +1089,7 @@ function App() {
const accountKey = account?.homeAccountId
? `${account.tenantId}:${account.homeAccountId}`
: authConfig.clientId ? null : 'local'
const operatorAlias = account?.username ? account.username.split('@')[0].toLowerCase() : null
const operatorAlias = account?.username ? (account.username.split('@')[0]?.toLowerCase() ?? null) : null
return (
<RuntimeProvider>
<RuntimeBanner />
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/auth/AuthProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ export function AuthProvider({ children }: AuthProviderProps) {
instance.setActiveAccount(redirectResult.account)
} else if (!instance.getActiveAccount()) {
const accounts = instance.getAllAccounts()
if (accounts.length > 0) instance.setActiveAccount(accounts[0])
if (accounts.length > 0 && accounts[0]) instance.setActiveAccount(accounts[0])
}

const requestedPath = typeof redirectResult?.state === 'string' ? redirectResult.state : null
Expand Down
11 changes: 6 additions & 5 deletions frontend/src/components/Analytics/AnalyticsFilters.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -375,11 +375,12 @@ export default function AnalyticsFilters({ filters, refreshVersion, onChange, dr
const occurrence = occurrences.get(fingerprint) ?? 0
occurrences.set(fingerprint, occurrence + 1)
const label = `${analyticsDimensionLabel(predicate.dimension)} (${predicate.match_mode.toUpperCase()}): ` +
predicate.values.map((value: AttackAnalyticsValue) =>
labels[analyticsOptionLabelKey(predicate.dimension, value)]
? analyticsOptionLabel({ key: value, label: labels[analyticsOptionLabelKey(predicate.dimension, value)] })
: analyticsValueLabel(value),
).join(', ')
predicate.values.map((value: AttackAnalyticsValue) => {
const optLabel = labels[analyticsOptionLabelKey(predicate.dimension, value)]
return optLabel
? analyticsOptionLabel({ key: value, label: optLabel })
: analyticsValueLabel(value)
}).join(', ')
return (
<div key={`${fingerprint}:${occurrence}`} className={styles.chip}>
<Button appearance="subtle" className={styles.chipLabel}
Expand Down
8 changes: 6 additions & 2 deletions frontend/src/components/Chat/ChatWindow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1864,7 +1864,8 @@ export default function ChatWindow({
setMessages(prev => {
// A pending navigation load may still leave a different conversation in state.
const failedMessages = hasMatchingTranscript ? prev : [...messages, userMessage]
if (failedMessages.length > 0 && failedMessages[failedMessages.length - 1].isLoading) {
const lastFailedMessage = failedMessages[failedMessages.length - 1]
if (failedMessages.length > 0 && lastFailedMessage?.isLoading) {
return [...failedMessages.slice(0, -1), errorMessage]
}
return [...failedMessages, errorMessage]
Expand Down Expand Up @@ -2337,7 +2338,7 @@ export default function ChatWindow({
let promptSnapshot: ChatConverterSnapshot | undefined
if (restoresFirstPrompt && activeTarget) {
const selected = source.messages[messageIndex]
if (!canBranchFirstPrompt(activeTarget, source.messages, messageIndex)
if (!selected || !canBranchFirstPrompt(activeTarget, source.messages, messageIndex)
|| selectedPieceIds.some((id: string) => !selected.message_pieces.some((piece: BackendMessagePiece) => piece.id === id))) {
throw new Error('The selected prompt changed. Reload the conversation before branching.')
}
Expand All @@ -2349,6 +2350,9 @@ export default function ChatWindow({
const restoration = preparePromptRestore(saved?.converters, branchConverterSnapshot)
promptSnapshot = restoration.snapshot
const promptMessage = copiedMessages[copiedMessages.length - 1]
if (!promptMessage) {
throw new Error('No prompt message to branch from.')
}
restoredPrompt = saved ? {
text: saved.originalValue, attachments: saved.attachments, textMetadata: saved.textMetadata, converters: promptSnapshot,
} : draftMessageToComposer(restoration.pipelineChanged ? {
Expand Down
12 changes: 7 additions & 5 deletions frontend/src/components/Chat/ConverterPanel/ConverterPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ export default function ConverterPanel({
// Offer converters that accept whatever the pipeline currently emits, so a
// chain can legally continue past a converter that changes the data type.
const lastSelectedConverter = selectedConverters[selectedConverters.length - 1]
const nextInputType = lastSelectedConverter?.identifier.supported_output_types?.[0] ?? activeDataType
const nextInputType: string = lastSelectedConverter?.identifier.supported_output_types?.[0] ?? activeDataType ?? ''

const filteredConverters = converters.filter((converter: ConverterInstance) => {
const supported = converter.identifier.supported_input_types ?? []
Expand Down Expand Up @@ -332,7 +332,9 @@ export default function ConverterPanel({
setPipeline(effectiveActiveTab, (stages: ConverterPipelineStage[]) => {
const nextPipeline = [...stages]
const [movedConverter] = nextPipeline.splice(sourceIndex, 1)
nextPipeline.splice(targetIndex, 0, movedConverter)
if (movedConverter) {
nextPipeline.splice(targetIndex, 0, movedConverter)
}
return nextPipeline
})
}, [setPipeline, effectiveActiveTab, selectedStages.length])
Expand Down Expand Up @@ -524,7 +526,7 @@ export default function ConverterPanel({
))}
onSave={() => {
const stage = selectedStages[index]
if (stage.temporary) setSaving({
if (stage?.temporary) setSaving({
stage, pieceType: effectiveActiveTab, converterType: converter.identifier.class_name,
source: stage.temporary, generation,
})
Expand Down Expand Up @@ -589,8 +591,8 @@ export default function ConverterPanel({
/>
<ValuePreview
label="Converted message"
dataType={results[input.id].converted_value_data_type}
value={results[input.id].converted_value}
dataType={results[input.id]?.converted_value_data_type ?? 'text'}
value={results[input.id]?.converted_value}
emptyText="This conversion returned an empty value."
testId="converter-final-result"
/>
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/Chat/MessageList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ function ScoreOverflowMenu({ scores, orderedScores, onSelect }: ScoreOverflowMen
<ScoreOverflowMenuItem
key={score.id}
score={score}
label={labels[index]}
label={labels[index] ?? ''}
onSelect={onSelect}
/>
))}
Expand Down
3 changes: 2 additions & 1 deletion frontend/src/components/Chat/converterTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,8 @@ export function applyConvertedValues(
if (Object.keys(conversions).length === 0) return pieces
if (pieces.length !== pieceIds.length) throw new Error('Message pieces do not match the draft identities.')
return pieces.map((piece: MessagePieceRequest, index: number): MessagePieceRequest => {
const conversion = conversions[pieceIds[index]]
const pieceId = pieceIds[index]
const conversion = pieceId !== undefined ? conversions[pieceId] : undefined
return conversion ? {
...piece,
converted_value: conversion.convertedValue,
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/components/Chat/messageViewModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,9 @@ export function formatStructuredMessage(text: string): string | null {
const formatted = JSON.stringify(parsed, null, 2)
// Restore the exact numeric lexemes in place of the placeholders
const restoreRegex = new RegExp(`"${nonce}(\\d+)__"`, 'g')
return formatted.replace(restoreRegex, (match, index) => {
return formatted.replace(restoreRegex, (match: string, index: string) => {
const numIndex = Number(index)
return numIndex in numbers ? numbers[numIndex] : match
return numbers[numIndex] ?? match
})
} catch {
return null
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/components/Config/CreateTargetDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ function defaultSupportsNoKey(targetType: string): boolean {
function getParameterLabel(name: string): string {
return name
.split('_')
.map((word) => word.length === 1 ? word.toUpperCase() : `${word[0].toUpperCase()}${word.slice(1)}`)
.map((word) => word.length === 1 ? word.toUpperCase() : `${word[0]?.toUpperCase() ?? ''}${word.slice(1)}`)
.join(' ')
}

Expand Down Expand Up @@ -483,7 +483,7 @@ export default function CreateTargetDialog({ open, onClose, onCreated, existingT
if (selectedInnerTargets.length === 0) return candidates
// Otherwise, filter to only targets compatible with the first one
const firstSelected = availableTargets.find(
(t) => t.target_registry_name === selectedInnerTargets[0].registryName,
(t) => t.target_registry_name === selectedInnerTargets[0]?.registryName,
)
if (!firstSelected) return candidates
return candidates.filter((t) => isCompatible(firstSelected, t))
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/Configuration/DotenvEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ Prism.languages.dotenv = {
}

function highlightDotenv(value: string): string {
return Prism.highlight(value, Prism.languages.dotenv, 'dotenv')
return Prism.highlight(value, Prism.languages.dotenv ?? {}, 'dotenv')
}

export default function DotenvEditor({ value, disabled, onChange }: DotenvEditorProps) {
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/Configuration/PythonCode.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ interface PythonCodeEditorProps {
}

function highlightPython(source: string): string {
return Prism.highlight(source, Prism.languages.python, 'python')
return Prism.highlight(source, Prism.languages.python ?? {}, 'python')
}

export function PythonCodeBlock({ source, ariaLabel }: PythonCodeBlockProps) {
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/Configuration/YamlEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ interface YamlEditorProps {
}

function highlightYaml(value: string): string {
return Prism.highlight(value, Prism.languages.yaml, 'yaml')
return Prism.highlight(value, Prism.languages.yaml ?? {}, 'yaml')
}

export default function YamlEditor({ value, disabled, onChange }: YamlEditorProps) {
Expand Down
12 changes: 7 additions & 5 deletions frontend/src/components/Converters/ConverterChainField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,11 +70,13 @@ export default function ConverterChainField({
if (index + delta < 0 || index + delta >= value.length) return
const next = [...value]
const [entry] = next.splice(index, 1)
next.splice(index + delta, 0, entry)
const [entryId] = ids.splice(index, 1)
ids.splice(index + delta, 0, entryId)
setEntryIds(ids)
onChange(next)
if (entry !== undefined && entryId !== undefined) {
next.splice(index + delta, 0, entry)
ids.splice(index + delta, 0, entryId)
setEntryIds(ids)
onChange(next)
}
}

return <section className={styles.root} aria-label={label}>
Expand All @@ -98,7 +100,7 @@ export default function ConverterChainField({
} : undefined}
onReset={() => onChange(value.map((entry, position) => position === index ? name : entry))}
onSave={allowTemporary && converter && typeof selection !== 'string' ? () => setSaving({
entryId: ids[index], source: selection, converterType: converter.identifier.class_name, generation,
entryId: ids[index] ?? '', source: selection, converterType: converter.identifier.class_name, generation,
}) : undefined}
onMove={(delta) => move(index, delta)}
onDragStart={(event) => {
Expand Down
6 changes: 3 additions & 3 deletions frontend/src/components/Datasets/seedExampleQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ function oneValue(params: URLSearchParams, key: string): { value: string | null;
const values = params.getAll(key)
if (values.length > 1) return { value: null, repeated: true }
if (values.length === 0 || values[0] === '') return { value: null, repeated: false }
return { value: values[0], repeated: false }
return { value: values[0] ?? null, repeated: false }
}

function pageSize(params: URLSearchParams): number {
Expand Down Expand Up @@ -90,7 +90,7 @@ function seedTypesFrom(params: URLSearchParams): SeedType[] {
*/
export function seedBrowserQueryFromSearchParams(params: URLSearchParams): SeedBrowserQuery {
const searchValues = params.getAll(SEARCH_PARAM)
const search = searchValues.length === 1 ? searchValues[0].slice(0, MAX_SEED_SEARCH_LENGTH) : ''
const search = searchValues.length === 1 ? (searchValues[0]?.slice(0, MAX_SEED_SEARCH_LENGTH) ?? '') : ''
const cursor = oneValue(params, CURSOR_PARAM)
const example = oneValue(params, EXAMPLE_PARAM)
return {
Expand Down Expand Up @@ -222,7 +222,7 @@ export function popSeedCursor(cursors: readonly (string | null)[]): {
} | null {
if (cursors.length === 0) return null
return {
cursor: cursors[cursors.length - 1],
cursor: cursors[cursors.length - 1] ?? null,
seedCursors: cursors.slice(0, -1),
}
}
Expand Down
26 changes: 15 additions & 11 deletions frontend/src/components/History/HistoryFiltersBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -248,17 +248,21 @@ export default function HistoryFiltersBar({
itemSize={LABEL_OPTION_HEIGHT_PX}
containerSizeRef={labelListMeasure.containerSizeRef}
>
{(index: number) => (
<Option
key={filteredLabelOptions[index]}
value={filteredLabelOptions[index]}
aria-posinset={index + 1}
aria-setsize={filteredLabelOptions.length}
{...{ [LABEL_OPTION_INDEX_ATTR]: index }}
>
{filteredLabelOptions[index]}
</Option>
)}
{(index: number) => {
const option = filteredLabelOptions[index]
if (option === undefined) return null
return (
<Option
key={option}
value={option}
aria-posinset={index + 1}
aria-setsize={filteredLabelOptions.length}
{...{ [LABEL_OPTION_INDEX_ATTR]: index }}
>
{option}
</Option>
)
}}
</Virtualizer>
</div>
</Combobox>
Expand Down
18 changes: 14 additions & 4 deletions frontend/src/components/Parameters/ReferenceField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,22 @@ export default function ReferenceField({
const selected = Array.isArray(value) ? value : []

const move = (index: number, delta: number): void => {
const target = index + delta
if (index < 0 || target < 0 || index >= selected.length || target >= selected.length) return
const next = [...selected]
const ids = selected.map((_, position) => entryIds[position] ?? `${id}-initial-${position}`)
;[next[index], next[index + delta]] = [next[index + delta], next[index]]
;[ids[index], ids[index + delta]] = [ids[index + delta], ids[index]]
setEntryIds(ids)
onChange(next)
const itemA = next[index]
const itemB = next[target]
const idA = ids[index]
const idB = ids[target]
if (itemA !== undefined && itemB !== undefined && idA !== undefined && idB !== undefined) {
next[index] = itemB
next[target] = itemA
ids[index] = idB
ids[target] = idA
setEntryIds(ids)
onChange(next)
}
}

return (
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/Parameters/parameterForm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ function elementTypeName(param: Parameter): string {
return param.type_name
}
const match = /^list\[(.+)\]$/.exec(param.type_name)
return match ? match[1] : 'str'
return match?.[1] ?? 'str'
}

function parseListValue(raw: string): string[] {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -493,7 +493,7 @@ function ScenarioPresetEditorContent({ mode, presetName }: ScenarioPresetEditorC
<ParameterField
key={parameter.name}
parameter={parameter}
value={config.scenarioParamValues[parameter.name]}
value={config.scenarioParamValues[parameter.name] ?? ''}
disabled={saving}
onChange={updateScenarioParam}
testIdPrefix="preset-param"
Expand Down
16 changes: 9 additions & 7 deletions frontend/src/components/ScenarioPresets/presetRunSizes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,15 @@ export async function estimatePresetRunSizes(
)))
const outcomes = items.map((item, index) => {
const estimate = estimates[index]
return estimate.status === 'fulfilled'
? { name: item.preset.name, runSize: estimate.value, failure: null }
: {
name: item.preset.name,
runSize: null,
failure: `${item.preset.name}: ${toApiError(estimate.reason).detail}`,
}
if (estimate && estimate.status === 'fulfilled') {
return { name: item.preset.name, runSize: estimate.value, failure: null }
}
const reason = estimate && estimate.status === 'rejected' ? estimate.reason : new Error('Missing estimate')
return {
name: item.preset.name,
runSize: null,
failure: `${item.preset.name}: ${toApiError(reason).detail}`,
}
})
return {
runSizes: new Map<string, ScenarioRunSizeEstimateResponse | null>(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,9 @@ function ScenarioSuiteEditorContent({ mode, suiteName }: ScenarioSuiteEditorCont
}
const reordered = [...current]
const [entry] = reordered.splice(index, 1)
reordered.splice(nextIndex, 0, entry)
if (entry) {
reordered.splice(nextIndex, 0, entry)
}
return reordered
})
}
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/components/Scenarios/ScenarioDetail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ export default function ScenarioDetail(props: ScenarioDetailProps) {
const { scenarioName: encodedScenarioName } = useParams<{ scenarioName: string }>()
const [searchParams] = useSearchParams()
const conversationIds = searchParams.getAll('prepended_conversation_id')
const initialConversationId = conversationIds.length === 1 ? conversationIds[0].trim() : ''
const initialConversationId = conversationIds.length === 1 ? (conversationIds[0]?.trim() ?? '') : ''
const presetName = searchParams.get(PRESET_QUERY_PARAM)?.trim() ?? ''
if (presetName && props.sourceRunId) return <ScenarioDetailStateFrame>
<MessageBar intent="error"><MessageBarBody>Choose a saved run or a preset, not both.</MessageBarBody></MessageBar>
Expand Down Expand Up @@ -751,7 +751,7 @@ function ScenarioLaunchForm({
<div key={parameter.name} className={styles.dynamicParameters}>
<ParameterField
parameter={parameter}
value={scenarioParamValues[parameter.name]}
value={scenarioParamValues[parameter.name] ?? ''}
disabled={submitting || loadingConversation}
onChange={updateScenarioParam}
testIdPrefix="scenario-param"
Expand Down
1 change: 1 addition & 0 deletions frontend/src/components/Scenarios/ScenarioRunPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@ function ScenarioRunContent({ scenarioResultId, attackResultId }: ScenarioRunCon
const groupedAttempts = new Map<string, ScenarioProgressResult[]>()
for (let index = state.results.length - 1; index >= 0; index -= 1) {
const attempt = state.results[index]
if (!attempt) continue
const existing = groupedAttempts.get(attempt.atomic_group_id)
if (existing) {
existing.push(attempt)
Expand Down
5 changes: 4 additions & 1 deletion frontend/src/components/Scenarios/scenarioHierarchy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,10 @@ export function mergeRootPage(
indexById.set(group.atomic_group_id, merged.length)
merged.push({ ...group, roots: [...group.roots] })
} else {
merged[i] = { ...merged[i], counts: group.counts, roots: [...merged[i].roots, ...group.roots] }
const targetGroup = merged[i]
if (targetGroup) {
merged[i] = { ...targetGroup, counts: group.counts, roots: [...targetGroup.roots, ...group.roots] }
}
}
}
return merged
Expand Down
Loading
Loading