diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index d0bfb2e616..829387c4ae 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -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>(() => rerun.active @@ -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 ( diff --git a/frontend/src/auth/AuthProvider.tsx b/frontend/src/auth/AuthProvider.tsx index b800319627..6f9fba9fa5 100644 --- a/frontend/src/auth/AuthProvider.tsx +++ b/frontend/src/auth/AuthProvider.tsx @@ -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 diff --git a/frontend/src/components/Analytics/AnalyticsFilters.tsx b/frontend/src/components/Analytics/AnalyticsFilters.tsx index 3992fc03f8..0b46b4bd18 100644 --- a/frontend/src/components/Analytics/AnalyticsFilters.tsx +++ b/frontend/src/components/Analytics/AnalyticsFilters.tsx @@ -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 (
diff --git a/frontend/src/components/Parameters/ReferenceField.tsx b/frontend/src/components/Parameters/ReferenceField.tsx index 971a696857..cc889e7c8f 100644 --- a/frontend/src/components/Parameters/ReferenceField.tsx +++ b/frontend/src/components/Parameters/ReferenceField.tsx @@ -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 ( diff --git a/frontend/src/components/Parameters/parameterForm.ts b/frontend/src/components/Parameters/parameterForm.ts index 2c0b5d0200..a21c7aef46 100644 --- a/frontend/src/components/Parameters/parameterForm.ts +++ b/frontend/src/components/Parameters/parameterForm.ts @@ -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[] { diff --git a/frontend/src/components/ScenarioPresets/ScenarioPresetEditor.tsx b/frontend/src/components/ScenarioPresets/ScenarioPresetEditor.tsx index 2781b21118..667643b7ab 100644 --- a/frontend/src/components/ScenarioPresets/ScenarioPresetEditor.tsx +++ b/frontend/src/components/ScenarioPresets/ScenarioPresetEditor.tsx @@ -493,7 +493,7 @@ function ScenarioPresetEditorContent({ mode, presetName }: ScenarioPresetEditorC { 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( diff --git a/frontend/src/components/ScenarioSuites/ScenarioSuiteEditor.tsx b/frontend/src/components/ScenarioSuites/ScenarioSuiteEditor.tsx index 3751306d3d..bdd237e77a 100644 --- a/frontend/src/components/ScenarioSuites/ScenarioSuiteEditor.tsx +++ b/frontend/src/components/ScenarioSuites/ScenarioSuiteEditor.tsx @@ -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 }) } diff --git a/frontend/src/components/Scenarios/ScenarioDetail.tsx b/frontend/src/components/Scenarios/ScenarioDetail.tsx index 9ea4101425..317ff016d0 100644 --- a/frontend/src/components/Scenarios/ScenarioDetail.tsx +++ b/frontend/src/components/Scenarios/ScenarioDetail.tsx @@ -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 Choose a saved run or a preset, not both. @@ -751,7 +751,7 @@ function ScenarioLaunchForm({
() 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) diff --git a/frontend/src/components/Scenarios/scenarioHierarchy.ts b/frontend/src/components/Scenarios/scenarioHierarchy.ts index 5c319fa26f..87bfbbe876 100644 --- a/frontend/src/components/Scenarios/scenarioHierarchy.ts +++ b/frontend/src/components/Scenarios/scenarioHierarchy.ts @@ -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 diff --git a/frontend/src/components/Scenarios/scenarioMarkdown.ts b/frontend/src/components/Scenarios/scenarioMarkdown.ts index 0542d0b6bc..c80994f386 100644 --- a/frontend/src/components/Scenarios/scenarioMarkdown.ts +++ b/frontend/src/components/Scenarios/scenarioMarkdown.ts @@ -41,7 +41,7 @@ function normalizeProseLine(line: string): string { while (cursor < line.length) { if (line[cursor] !== '`' || isEscaped(line, cursor)) { - output.push(line[cursor]) + output.push(line[cursor] ?? '') cursor += 1 continue } @@ -82,6 +82,9 @@ function openingFence(line: string): MarkdownFence | null { return null } const run = match[1] + if (!run) { + return null + } return { marker: run[0] === '`' ? '`' : '~', length: run.length, diff --git a/frontend/src/components/Scenarios/scenarioTechniqueSets.ts b/frontend/src/components/Scenarios/scenarioTechniqueSets.ts index 68e3ecb824..26b1c6e894 100644 --- a/frontend/src/components/Scenarios/scenarioTechniqueSets.ts +++ b/frontend/src/components/Scenarios/scenarioTechniqueSets.ts @@ -16,7 +16,7 @@ function humanizeTechniqueSetName(name: string): string { return knownLabel } const words = name.replace(/_/g, ' ') - return words.length > 0 ? `${words[0].toUpperCase()}${words.slice(1)}` : name + return words.length > 0 ? `${words[0]?.toUpperCase() ?? ''}${words.slice(1)}` : name } export function techniqueSetMembers(scenario: RegisteredScenario, name: string): string[] { diff --git a/frontend/src/components/SearchableMultiCombobox.tsx b/frontend/src/components/SearchableMultiCombobox.tsx index 1af044d81a..0bc428b5f3 100644 --- a/frontend/src/components/SearchableMultiCombobox.tsx +++ b/frontend/src/components/SearchableMultiCombobox.tsx @@ -18,7 +18,7 @@ interface SearchableMultiComboboxProps { /** The first selected choice and how many more, e.g. "alice (+2)". */ function formatSummary(selected: string[], options: FilterOption[], prefix?: string): string { if (selected.length === 0) return '' - const first = options.find((option: FilterOption) => option.value === selected[0])?.label ?? selected[0] + const first = (options.find((option: FilterOption) => option.value === selected[0])?.label ?? selected[0]) ?? '' const summary = selected.length === 1 ? first : `${first} (+${selected.length - 1})` return prefix ? `${prefix}: ${summary}` : summary } diff --git a/frontend/src/hooks/useChatConverters.ts b/frontend/src/hooks/useChatConverters.ts index 0ec01ad869..2f260c8c39 100644 --- a/frontend/src/hooks/useChatConverters.ts +++ b/frontend/src/hooks/useChatConverters.ts @@ -100,9 +100,9 @@ function changePipeline(state: ConversionState, pieceType: string, stages: Conve let prefixLength = 0 while ( prefixLength < previous.length && prefixLength < stages.length - && previous[prefixLength].id === stages[prefixLength].id - && previous[prefixLength].converterId === stages[prefixLength].converterId - && previous[prefixLength].temporary === stages[prefixLength].temporary + && previous[prefixLength]?.id === stages[prefixLength]?.id + && previous[prefixLength]?.converterId === stages[prefixLength]?.converterId + && previous[prefixLength]?.temporary === stages[prefixLength]?.temporary ) prefixLength++ if (prefixLength === previous.length && prefixLength === stages.length) return state @@ -142,7 +142,7 @@ function completedResults(state: ConversionState): Record stage.stageId !== pipeline[index].id, + (stage: ConverterStageResult, index: number) => stage.stageId !== pipeline[index]?.id, )) continue results[input.id] = { original_value: input.value, @@ -372,8 +372,9 @@ export function usePieceConverters( ) if (afterStageId !== undefined && boundary < 0) return [] const start = boundary + 1 - const value = boundary < 0 ? state.workingInputs[input.id] ?? input.value : previous[boundary].value - const dataType = boundary < 0 ? input.dataType : previous[boundary].generated.output_data_type + const prevBoundary = boundary >= 0 ? previous[boundary] : undefined + const value = prevBoundary ? prevBoundary.value : (state.workingInputs[input.id] ?? input.value) + const dataType = prevBoundary ? prevBoundary.generated.output_data_type : input.dataType if (start >= pipeline.length || (boundary < 0 && !value.trim() && !input.file)) return [] return [{ input, pipeline, prefix: previous.slice(0, start), start, value, dataType }] }) @@ -418,10 +419,10 @@ export function usePieceConverters( } : {}), }) if (response.steps.length !== remaining.length || response.steps.some( - (step: ConverterPreviewStep, index: number) => step.converter_id !== remaining[index].converterId, + (step: ConverterPreviewStep, index: number) => step.converter_id !== remaining[index]?.converterId, )) throw new Error('The conversion response does not match the requested stages.') const stages: ConverterStageResult[] = response.steps.map((step: ConverterPreviewStep, index: number) => ({ - stageId: remaining[index].id, generated: step, value: step.output_value, + stageId: remaining[index]?.id ?? '', generated: step, value: step.output_value, })) return { input, pipelineRevision, stages: [...prefix, ...stages] } } catch (error) { diff --git a/frontend/src/hooks/useTour.ts b/frontend/src/hooks/useTour.ts index 6c87fb8ed2..f30c7d1e53 100644 --- a/frontend/src/hooks/useTour.ts +++ b/frontend/src/hooks/useTour.ts @@ -178,6 +178,9 @@ export function useTour( } const nextStep = steps[nextIndex] + if (!nextStep) { + return + } if (nextStep.viewRequired !== currentViewRef.current) { // The required view differs from the actual current view. diff --git a/frontend/src/utils/attackAnalytics.ts b/frontend/src/utils/attackAnalytics.ts index bd450f7472..f730af841d 100644 --- a/frontend/src/utils/attackAnalytics.ts +++ b/frontend/src/utils/attackAnalytics.ts @@ -317,7 +317,7 @@ function canonicalTimestamp(value: string): string { if (!match || !Number.isFinite(milliseconds)) { throw new Error('Last updated bounds must be ISO 8601 timestamps with Z or an explicit time-zone offset.') } - const [, year, month, day, hour, minute, second = '0', fraction = '', offset] = match + const [, year, month, day, hour, minute, second = '0', fraction = '', offset = 'Z'] = match const calendar = new Date(`${year}-${month}-${day}T00:00:00Z`) if (Number(year) < 1 || calendar.getUTCMonth() + 1 !== Number(month) || calendar.getUTCDate() !== Number(day) || Number(hour) > 23 || Number(minute) > 59 || diff --git a/frontend/src/utils/conversationDraft.ts b/frontend/src/utils/conversationDraft.ts index 26291c7cab..4f7b29f963 100644 --- a/frontend/src/utils/conversationDraft.ts +++ b/frontend/src/utils/conversationDraft.ts @@ -227,9 +227,12 @@ export function draftMessageToComposer( const applied: ChatConverterSnapshot['applied'] = {} for (const piece of message.pieces) { const id = piece === textPieces[0] ? 'text' : piece.draftId - if (snapshot.workingInputs[piece.draftId] !== undefined) workingInputs[id] = snapshot.workingInputs[piece.draftId] - if (snapshot.stageResults[piece.draftId]) stageResults[id] = snapshot.stageResults[piece.draftId] - if (snapshot.errors[piece.draftId]) errors[id] = snapshot.errors[piece.draftId] + const workingInput = snapshot.workingInputs[piece.draftId] + if (workingInput !== undefined) workingInputs[id] = workingInput + const stageResult = snapshot.stageResults[piece.draftId] + if (stageResult !== undefined) stageResults[id] = stageResult + const err = snapshot.errors[piece.draftId] + if (err !== undefined) errors[id] = err const previous = snapshot.applied[piece.draftId] const convertedType = piece.converted_value_data_type ?? piece.data_type if (piece.converted_value !== undefined && (piece.converted_value !== piece.original_value diff --git a/frontend/src/utils/conversationExport.ts b/frontend/src/utils/conversationExport.ts index 11df6cf861..4b087ae41d 100644 --- a/frontend/src/utils/conversationExport.ts +++ b/frontend/src/utils/conversationExport.ts @@ -224,7 +224,7 @@ export async function conversationToHtml(

CoPyRIT conversation export

${summary}

-${exported.map((message, index) => renderMessage(message, media.perMessage[index])).join('\n')} +${exported.map((message, index) => renderMessage(message, media.perMessage[index] ?? { attachments: [], originalAttachments: [] })).join('\n')} ` diff --git a/frontend/src/utils/findingExportFilename.ts b/frontend/src/utils/findingExportFilename.ts index 704d318633..7d71dd5861 100644 --- a/frontend/src/utils/findingExportFilename.ts +++ b/frontend/src/utils/findingExportFilename.ts @@ -17,7 +17,7 @@ export function findingExportFilename(operation: Pick, end = NAME_LIMIT if (name[end] !== '-' && name.slice(0, end).includes('-')) end = name.lastIndexOf('-', end - 1) // A word longer than the limit is cut between letters, never between a letter and its marks. - while (end > 0 && MARK.test(name[end])) end -= 1 + while (end > 0 && MARK.test(name[end] ?? '')) end -= 1 } const slug = name.slice(0, end).join('').replace(/-+$/, '') const pad = (value: number) => String(value).padStart(2, '0') diff --git a/frontend/src/utils/media.ts b/frontend/src/utils/media.ts index b03fa39000..0fd3eed3b5 100644 --- a/frontend/src/utils/media.ts +++ b/frontend/src/utils/media.ts @@ -21,9 +21,10 @@ export function basenameFromValue(value: string, fallback: string): string { if (!value) return fallback if (value.startsWith('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/api/media')) { const match = /[?&]path=([^&]+)/.exec(value) - if (match) { + const matchPath = match?.[1] + if (matchPath) { try { - const decoded = decodeURIComponent(match[1]) + const decoded = decodeURIComponent(matchPath) const parts = decoded.split(/[/\\]/) return parts[parts.length - 1] || fallback } catch { @@ -32,7 +33,7 @@ export function basenameFromValue(value: string, fallback: string): string { } return fallback } - const cleaned = value.split('?')[0] + const cleaned = value.split('?')[0] ?? '' const parts = cleaned.split(/[/\\]/) return parts[parts.length - 1] || fallback } @@ -211,7 +212,7 @@ export function mapMediaUrl({ dataType, value, valueUrl }: MapMediaUrlInput): Ma if (isBinary) return { status: 'unsupported', url: supportedDownloadUrl(url) } const classified = dataUriKind(url) ?? kindForExtension(extensionOf(url)) - if (classified === 'unsupported') return { status: 'unsupported', url: supportedDownloadUrl(url) } + if (classified === 'unsupported' || !previewKind) return { status: 'unsupported', url: supportedDownloadUrl(url) } if (classified !== 'unknown' && classified !== previewKind) { return { status: 'unsupported', url: supportedDownloadUrl(url) } } diff --git a/frontend/src/utils/routeParams.ts b/frontend/src/utils/routeParams.ts index 19eddd0339..ad84cf5e55 100644 --- a/frontend/src/utils/routeParams.ts +++ b/frontend/src/utils/routeParams.ts @@ -17,17 +17,19 @@ export function routerPathParamValue(value: string | undefined): string { /** Returns one validated scenario-run provenance UUID from a route query. */ export function scenarioRunProvenance(searchParams: URLSearchParams): string | null { const values = searchParams.getAll(SCENARIO_RESULT_ID_QUERY_KEY) - if (values.length !== 1 || !UUID_PATTERN.test(values[0])) { + const first = values[0] + if (values.length !== 1 || !first || !UUID_PATTERN.test(first)) { return null } - return values[0] + return first } /** Returns one validated evidence id. Never returns a caller-supplied return URL. */ export function findingEvidenceOrigin(searchParams: URLSearchParams): string | null { const values = searchParams.getAll(FINDING_EVIDENCE_ID_QUERY_KEY) - return values.length === 1 && UUID_PATTERN.test(values[0]) ? values[0] : null + const first = values[0] + return values.length === 1 && first && UUID_PATTERN.test(first) ? first : null } /** Builds an attack-detail route with optional bounded scenario-run provenance. */ @@ -100,7 +102,7 @@ const SELECTION_KEY_PARAM = 'selection_key' export function selectionKeyFromSearchParams(params: URLSearchParams): string | null { const values = params.getAll(SELECTION_KEY_PARAM) if (values.length !== 1) return null - return values[0] + return values[0] ?? null } /** @@ -154,41 +156,44 @@ function isCatalogReturnPath(value: string): boolean { /** Returns true if the pathname or path belongs to the dataset catalog or dataset detail view. */ export function isDatasetsPath(pathOrUrl: string): boolean { if (!pathOrUrl) return false - const cleanPath = pathOrUrl.split('?')[0].split('#')[0] + const cleanPath = pathOrUrl.split('?')[0]?.split('#')[0] ?? '' return cleanPath === DATASETS_PATH || cleanPath === DATASET_DETAIL_PATH || cleanPath.startsWith(`${DATASETS_PATH}/`) } /** Returns true if the pathname or path belongs to the chat view or an attack view. */ export function isChatPath(pathOrUrl: string): boolean { if (!pathOrUrl) return false - const cleanPath = pathOrUrl.split('?')[0].split('#')[0] + const cleanPath = pathOrUrl.split('?')[0]?.split('#')[0] ?? '' return cleanPath === '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/attack/chat' || cleanPath.startsWith('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/attack/chat/') } /** Parses attackId and conversationId from a chat or attack route path. */ export function parseChatRoute(path: string): { attackId: string | null; conversationId: string | null } { if (!path) return { attackId: null, conversationId: null } - const clean = path.split('?')[0].split('#')[0] + const clean = path.split('?')[0]?.split('#')[0] ?? '' const matchWithConv = /^\/attacks\/([^/]+)\/conversations\/([^/]+)/.exec(clean) if (matchWithConv) { + const rawAttackId = matchWithConv[1] ?? '' + const rawConversationId = matchWithConv[2] ?? '' try { return { - attackId: decodeURIComponent(matchWithConv[1]), - conversationId: decodeURIComponent(matchWithConv[2]), + attackId: decodeURIComponent(rawAttackId), + conversationId: decodeURIComponent(rawConversationId), } } catch { - return { attackId: matchWithConv[1], conversationId: matchWithConv[2] } + return { attackId: rawAttackId, conversationId: rawConversationId } } } const matchAttack = /^\/attacks\/([^/]+)/.exec(clean) if (matchAttack) { + const rawAttackId = matchAttack[1] ?? '' try { return { - attackId: decodeURIComponent(matchAttack[1]), + attackId: decodeURIComponent(rawAttackId), conversationId: null, } } catch { - return { attackId: matchAttack[1], conversationId: null } + return { attackId: rawAttackId, conversationId: null } } } return { attackId: null, conversationId: null } diff --git a/frontend/src/utils/seedImport.ts b/frontend/src/utils/seedImport.ts index 1c84a8661a..51712c46f0 100644 --- a/frontend/src/utils/seedImport.ts +++ b/frontend/src/utils/seedImport.ts @@ -238,6 +238,12 @@ export function buildSeedImport(members: readonly SeedRecord[]): SeedImportOutco // No sequence numbers stored on records if (promptRecords.length === 1) { const record = promptRecords[0] + if (!record) { + return { + type: 'unsupported', + reason: 'Prompt record is missing.', + } + } const mappedRole = mapToDraftRole(record.role) ?? 'user' turns.push({ role: mappedRole, @@ -250,9 +256,10 @@ export function buildSeedImport(members: readonly SeedRecord[]): SeedImportOutco // combine them into a single turn at sequence 0. const allRoles = promptRecords.map((r) => mapToDraftRole(r.role) ?? 'user') const distinctRoles = new Set(allRoles) - if (distinctRoles.size === 1) { + const firstRole = allRoles[0] + if (distinctRoles.size === 1 && firstRole !== undefined) { turns.push({ - role: allRoles[0], + role: firstRole, sequence: 0, pieces: promptRecords.map(recordToDraftPiece), }) @@ -274,10 +281,10 @@ export function buildSeedImport(members: readonly SeedRecord[]): SeedImportOutco // 6. Differentiate Single Prompt vs. Multi-turn Conversation with Final User Turn Split // If exactly 1 turn and role is 'user', import as single prompt to editable composer. - if (turns.length === 1 && turns[0].role === 'user') { - const turn = turns[0] - const textPieces = turn.pieces.filter((p) => !isPathDataType(p.data_type)) - const mediaPieces = turn.pieces.filter((p) => isPathDataType(p.data_type)) + const firstTurn = turns[0] + if (turns.length === 1 && firstTurn && firstTurn.role === 'user') { + const textPieces = firstTurn.pieces.filter((p) => !isPathDataType(p.data_type)) + const mediaPieces = firstTurn.pieces.filter((p) => isPathDataType(p.data_type)) const text = textPieces.map((p) => p.original_value).join('\n\n') const attachments: MessageAttachment[] = mediaPieces.map(draftAttachment) @@ -295,8 +302,8 @@ export function buildSeedImport(members: readonly SeedRecord[]): SeedImportOutco // Multi-turn or single non-user turn -> Conversation // Extract system prompt if first turn is system or developer let systemPrompt: string | undefined - if (turns[0].role === 'system' || turns[0].role === 'developer') { - const sysPieces = turns[0].pieces.filter((p) => !isPathDataType(p.data_type)) + if (firstTurn && (firstTurn.role === 'system' || firstTurn.role === 'developer')) { + const sysPieces = firstTurn.pieces.filter((p) => !isPathDataType(p.data_type)) if (sysPieces.length > 0) { systemPrompt = sysPieces.map((p) => p.original_value).join('\n\n') } @@ -310,7 +317,7 @@ export function buildSeedImport(members: readonly SeedRecord[]): SeedImportOutco let historyTurns = turns let composerDraft: ConversationImport['composerDraft'] | undefined - if (lastTurn.role === 'user' && turns.length > 1) { + if (lastTurn && lastTurn.role === 'user' && turns.length > 1) { historyTurns = turns.slice(0, -1) const textPieces = lastTurn.pieces.filter((p) => !isPathDataType(p.data_type)) const mediaPieces = lastTurn.pieces.filter((p) => isPathDataType(p.data_type)) diff --git a/frontend/src/utils/targetIdentity.ts b/frontend/src/utils/targetIdentity.ts index 07c437733b..13162bb135 100644 --- a/frontend/src/utils/targetIdentity.ts +++ b/frontend/src/utils/targetIdentity.ts @@ -20,7 +20,7 @@ function hoistFromInner( const inners = target.inner_targets ?? [] if (inners.length > 0) { const values = new Set(inners.map(pick).filter((value): value is string => Boolean(value))) - if (values.size === 1) return [...values][0] + if (values.size === 1) return [...values][0] ?? null } return null } @@ -110,8 +110,9 @@ export function resolveTargetByIdentifierHash( (target) => targetIdentifierHash(target) === identifierHash, ) - if (matches.length === 1) { - return { status: 'resolved', target: matches[0] } + const first = matches[0] + if (matches.length === 1 && first) { + return { status: 'resolved', target: first } } return { status: matches.length === 0 ? 'unavailable' : 'ambiguous' } } diff --git a/frontend/tsconfig.json b/frontend/tsconfig.json index 38d4561207..279a48a2dd 100644 --- a/frontend/tsconfig.json +++ b/frontend/tsconfig.json @@ -17,6 +17,7 @@ /* Linting */ "strict": true, + "noUncheckedIndexedAccess": true, "noUnusedLocals": true, "noUnusedParameters": true, "noFallthroughCasesInSwitch": true,