diff --git a/frontend/src/hooks/useChatConverters.test.tsx b/frontend/src/hooks/useChatConverters.test.tsx
index 2bd093d8c8..df7916ba9d 100644
--- a/frontend/src/hooks/useChatConverters.test.tsx
+++ b/frontend/src/hooks/useChatConverters.test.tsx
@@ -51,6 +51,95 @@ function makePreviewResponse() {
}
describe('useChatConverters across runtime generation changes', () => {
+ it('restores exact working inputs, stage IDs, middle edits, and applied values after a send clears them', async () => {
+ mockedPreview.mockImplementation(async (request) => {
+ let value = request.original_value
+ const steps = request.converter_ids.map((converterId: string) => {
+ const input = value
+ value = `${input}|${converterId}`
+ return {
+ converter_id: converterId, converter_type: 'TestConverter',
+ input_value: input, input_data_type: 'text', output_value: value, output_data_type: 'text',
+ }
+ })
+ return { steps }
+ })
+ const { result, rerender } = renderHook(
+ ({ text }: { text: string }) => useChatConverters(text, NO_ATTACHMENTS),
+ { initialProps: { text: 'original text' } },
+ )
+ act(() => {
+ result.current.setPipeline('text', () => [
+ { id: 'first-stage', converterId: 'first' }, { id: 'second-stage', converterId: 'second' },
+ ])
+ result.current.editInput('text', 'working input')
+ })
+ await act(async () => { await result.current.convert('text') })
+ act(() => { result.current.editStageOutput('text', 'first-stage', 'Edited middle') })
+ await act(async () => { await result.current.convertRemaining('text', 'first-stage') })
+ act(() => { result.current.editConvertedValue('text', 'Exact sendable result') })
+ const saved = result.current.snapshot()
+ act(() => { result.current.clearAll() })
+ rerender({ text: '' })
+ expect(result.current.stageResults).toEqual({})
+ rerender({ text: 'original text' })
+ act(() => { result.current.restoreSnapshot(saved, 'original text', NO_ATTACHMENTS) })
+ expect(result.current.workingInputs).toEqual(saved.workingInputs)
+ expect(result.current.pipelines).toEqual(saved.pipelines)
+ expect(result.current.stageResults).toEqual(saved.stageResults)
+ expect(result.current.stageResults.text[0].value).toBe('Edited middle')
+ expect(result.current.applied.text.convertedValue).toBe('Exact sendable result')
+ expect(result.current.repeatDisabledReason).toBeDefined()
+ expect(mockedPreview).toHaveBeenCalledTimes(2)
+ runtime.generation = 'replacement'
+ rerender({ text: 'original text' })
+ expect(() => result.current.restoreSnapshot(saved, 'original text', NO_ATTACHMENTS)).toThrow(/runtime changed/)
+ expect(result.current.stageResults).toEqual({})
+ })
+
+ it('applies completed conversions and final-stage edits without a separate action', async () => {
+ mockedPreview.mockResolvedValue(makePreviewResponse())
+ const { result } = renderHook(() => useChatConverters('original text', NO_ATTACHMENTS))
+ act(() => {
+ result.current.setPipeline('text', () => [{ id: 'stage-1', converterId: 'base64-default' }])
+ })
+ await act(async () => { await result.current.convert('text') })
+ expect(result.current.applied.text.convertedValue).toBe('b3JpZ2luYWwgdGV4dA==')
+ expect(result.current.repeatDisabledReason).toBeUndefined()
+ act(() => { result.current.editStageOutput('text', 'stage-1', 'Edited final output') })
+ expect(result.current.applied.text.convertedValue).toBe('Edited final output')
+ expect(result.current.repeatDisabledReason).toMatch(/editing a conversion/)
+ act(() => { result.current.clearAll() })
+ expect(result.current.repeatDisabledReason).toBeUndefined()
+ })
+
+ it('disables repetitions for partial-region conversion even after the markers are consumed', async () => {
+ mockedPreview.mockResolvedValue({
+ ...makePreviewResponse(),
+ steps: [{ ...makePreviewResponse().steps[0], input_value: 'before \u27eapart\u27eb after' }],
+ })
+ const { result } = renderHook(() => useChatConverters('before part after', NO_ATTACHMENTS))
+ act(() => {
+ result.current.setPipeline('text', () => [{ id: 'stage-1', converterId: 'base64-default' }])
+ result.current.editInput('text', 'before \u27eapart\u27eb after')
+ })
+ await act(async () => { await result.current.convert('text') })
+ expect(result.current.applied.text).toBeDefined()
+ expect(result.current.repeatDisabledReason).toMatch(/part of a prompt/)
+ })
+
+ it('disables repetitions after the sendable converted value is manually edited', async () => {
+ mockedPreview.mockResolvedValue(makePreviewResponse())
+ const { result } = renderHook(() => useChatConverters('original text', NO_ATTACHMENTS))
+ act(() => {
+ result.current.setPipeline('text', () => [{ id: 'stage-1', converterId: 'base64-default' }])
+ })
+ await act(async () => { await result.current.convert('text') })
+ act(() => { result.current.editConvertedValue('text', 'Changed in composer') })
+ expect(result.current.applied.text.convertedValue).toBe('Changed in composer')
+ expect(result.current.repeatDisabledReason).toBeDefined()
+ })
+
it('restores repeat pipelines and exact applied values without retaining unrelated selections', () => {
const { result } = renderHook(() => useChatConverters('original text', NO_ATTACHMENTS))
const pipelines = {
@@ -248,7 +337,7 @@ describe('useChatConverters concurrent conversion runs', () => {
expect(result.current.stageResults['text']!.length).toBe(1)
expect(result.current.isConverting).toBe(true)
act(() => { result.current.apply() })
- expect(result.current.applied['att-1']).toBeUndefined()
+ expect(result.current.applied['att-1']?.convertedValue).toBe('rerun-image')
await act(async () => {
textRun.respond('rerun-text')
diff --git a/frontend/src/hooks/useChatConverters.ts b/frontend/src/hooks/useChatConverters.ts
index 90bfb5fef9..1b0f7f0ef2 100644
--- a/frontend/src/hooks/useChatConverters.ts
+++ b/frontend/src/hooks/useChatConverters.ts
@@ -1,4 +1,4 @@
-import { useCallback, useMemo, useRef, useState } from 'react'
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import { buildAppliedConversions } from '@/utils/conversionResults'
import { buildConverterInputs } from '@/components/Chat/converterTypes'
@@ -7,6 +7,7 @@ import { convertersApi } from '@/services/api'
import { toApiError } from '@/services/errors'
import type {
ChatConverterController,
+ ChatConverterSnapshot,
ConverterInputPiece,
ConverterPipelineStage,
ConverterPreviewResponse,
@@ -14,6 +15,7 @@ import type {
ConverterStageResult,
MessageAttachment,
PieceConversion,
+ PieceConversionUpdates,
} from '@/types'
import { generateClientId } from '@/utils/clientId'
import { fileToBase64 } from '@/utils/messageMapper'
@@ -56,6 +58,11 @@ interface ConversionScope {
includeIncomplete?: boolean
}
+interface PieceConverterOptions {
+ initialSnapshot?: ChatConverterSnapshot
+ selectedIds?: ReadonlySet
+}
+
function omitPieces(values: Record, ids: Set): Record {
return Object.fromEntries(Object.entries(values).filter(([id]: [string, T]) => !ids.has(id)))
}
@@ -162,7 +169,9 @@ export function useChatConverters(text: string, attachments: MessageAttachment[]
return usePieceConverters(inputs)
}
-export function usePieceConverters(inputs: ConverterInputPiece[], scopeKey?: string): ChatConverterController {
+export function usePieceConverters(
+ inputs: ConverterInputPiece[], scopeKey?: string, options: PieceConverterOptions = {},
+): ChatConverterController {
const { generation } = useRuntime()
const [state, setState] = useState(() => ({
generation,
@@ -180,8 +189,12 @@ export function usePieceConverters(inputs: ConverterInputPiece[], scopeKey?: str
isConverting: false,
runOwners: {},
activeRuns: [],
+ ...(options.initialSnapshot?.generation === generation ? options.initialSnapshot : {}),
}))
const nextRunId = useRef(0)
+ const currentState = useRef(state)
+ useLayoutEffect(() => { currentState.current = state }, [state])
+ useEffect(() => () => { currentState.current = null }, [])
if (state.scopeKey !== scopeKey) {
setState({
@@ -235,32 +248,57 @@ export function usePieceConverters(inputs: ConverterInputPiece[], scopeKey?: str
})
}, [])
- const editInput = useCallback((pieceId: string, value: string): void => {
- setState((current: ConversionState) => {
+ const editInput = useCallback((pieceId: string, value: string): PieceConversionUpdates | void => {
+ const update = (current: ConversionState): ConversionState => {
const input = current.inputs.find((candidate: VersionedInput) => candidate.id === pieceId)
if (!input || input.dataType !== 'text' || (current.workingInputs[pieceId] ?? input.value) === value) return current
- return {
+ const next = {
...invalidatePiece(current, pieceId),
workingInputs: { ...current.workingInputs, [pieceId]: value },
stageResults: { ...current.stageResults, [pieceId]: [] },
}
- })
+ return {
+ ...next, applied: {
+ ...next.applied,
+ ...buildAppliedConversions(next.inputs.filter((piece: VersionedInput) => piece.id === pieceId), completedResults(next)),
+ },
+ }
+ }
+ if (!currentState.current) return
+ const next = update(currentState.current)
+ if (next === currentState.current) return
+ setState(update)
+ return { [pieceId]: next.applied[pieceId] ?? null }
}, [])
- const editStageOutput = useCallback((pieceId: string, stageId: string, value: string): void => {
- setState((current: ConversionState) => {
+ const editStageOutput = useCallback((
+ pieceId: string, stageId: string, value: string,
+ ): PieceConversionUpdates | void => {
+ const update = (current: ConversionState): ConversionState => {
const stages = current.stageResults[pieceId] ?? []
const index = stages.findIndex((stage: ConverterStageResult) => stage.stageId === stageId)
const stage = stages[index]
if (!stage || stage.generated.output_data_type !== 'text' || stage.value === value) return current
- return {
+ const next = {
...invalidatePiece(current, pieceId),
stageResults: {
...current.stageResults,
[pieceId]: [...stages.slice(0, index), { ...stage, value }],
},
}
- })
+ return {
+ ...next,
+ applied: {
+ ...next.applied,
+ ...buildAppliedConversions(next.inputs.filter((input: VersionedInput) => input.id === pieceId), completedResults(next)),
+ },
+ }
+ }
+ if (!currentState.current) return
+ const next = update(currentState.current)
+ if (next === currentState.current) return
+ setState(update)
+ return { [pieceId]: next.applied[pieceId] ?? null }
}, [])
const runConversion = async ({
@@ -268,10 +306,11 @@ export function usePieceConverters(inputs: ConverterInputPiece[], scopeKey?: str
pieceId,
afterStageId,
includeIncomplete = false,
- }: ConversionScope): Promise => {
+ }: ConversionScope): Promise => {
if (state.activeRuns.length > 0 && state.activeRuns[state.activeRuns.length - 1] === state.runId) return
const completed = completedResults(state)
const selected = state.inputs.flatMap((input: VersionedInput): ConversionJob[] => {
+ if (options.selectedIds && !options.selectedIds.has(input.id)) return []
if (
pieceType !== undefined
&& pieceType !== input.pieceType
@@ -335,10 +374,14 @@ export function usePieceConverters(inputs: ConverterInputPiece[], scopeKey?: str
return { input, pipelineRevision, error: `Conversion from stage ${start + 1} failed: ${toApiError(error).detail}` }
}
}))
- setState((current: ConversionState) => {
+ const completeRun = (current: ConversionState): {
+ state: ConversionState; updates: PieceConversionUpdates
+ } => {
const activeRuns = current.activeRuns.filter((active: number) => active !== runId)
const stageResults = { ...current.stageResults }
const errors = { ...current.errors }
+ const accepted = new Set()
+ const updates: PieceConversionUpdates = {}
for (const outcome of outcomes) {
// A newer run that selected this input owns its outcome slot now.
if (current.runOwners[outcome.input.id] !== runId) continue
@@ -347,11 +390,26 @@ export function usePieceConverters(inputs: ConverterInputPiece[], scopeKey?: str
!input || input.revision !== outcome.input.revision
|| current.pipelineRevisions[input.pieceType] !== outcome.pipelineRevision
) continue
- if (outcome.stages) stageResults[input.id] = outcome.stages
+ updates[input.id] = null
+ if (outcome.stages) {
+ stageResults[input.id] = outcome.stages
+ accepted.add(input.id)
+ }
else if (outcome.error) errors[input.id] = outcome.error
}
- return { ...current, stageResults, errors, activeRuns, isConverting: activeRuns.length > 0 }
- })
+ const next = { ...current, stageResults, errors, activeRuns, isConverting: activeRuns.length > 0 }
+ const applied = buildAppliedConversions(
+ next.inputs.filter((input: VersionedInput) => accepted.has(input.id)), completedResults(next),
+ )
+ return {
+ state: { ...next, applied: { ...next.applied, ...applied } },
+ updates: { ...updates, ...applied },
+ }
+ }
+ if (!currentState.current) return
+ const completion = completeRun(currentState.current)
+ setState((current: ConversionState) => completeRun(current).state)
+ return Object.keys(completion.updates).length ? completion.updates : undefined
}
const apply = useCallback((): void => {
@@ -377,7 +435,10 @@ export function usePieceConverters(inputs: ConverterInputPiece[], scopeKey?: str
setState((current: ConversionState) => {
const conversion = current.applied[pieceId]
if (!conversion) return current
- return { ...current, applied: { ...current.applied, [pieceId]: { ...conversion, convertedValue: value } } }
+ return {
+ ...current,
+ applied: { ...current.applied, [pieceId]: { ...conversion, convertedValue: value, manuallyEdited: true } },
+ }
})
}, [])
@@ -415,13 +476,64 @@ export function usePieceConverters(inputs: ConverterInputPiece[], scopeKey?: str
})
}, [])
+ const snapshot = (): ChatConverterSnapshot => ({
+ generation: state.generation,
+ workingInputs: state.workingInputs,
+ pipelines: state.pipelines,
+ stageResults: state.stageResults,
+ errors: state.errors,
+ applied: state.applied,
+ })
+ const restoreSnapshot = (
+ saved: ChatConverterSnapshot, text: string, attachments: MessageAttachment[],
+ ): void => {
+ if (saved.generation !== generation) {
+ throw new Error('The converter runtime changed. The previous converter state cannot be restored.')
+ }
+ const runId = ++nextRunId.current
+ setState((current: ConversionState) => ({
+ ...reconcileInputs(current, buildConverterInputs(text, attachments)),
+ ...saved,
+ pipelineRevisions: Object.fromEntries(
+ Object.keys({ ...current.pipelines, ...saved.pipelines }).map((pieceType: string) => (
+ [pieceType, (current.pipelineRevisions[pieceType] ?? 0) + 1]
+ )),
+ ),
+ runId,
+ isConverting: false,
+ runOwners: {},
+ activeRuns: [],
+ }))
+ }
+
+ const hasEditedConversion = state.inputs.some((input: VersionedInput) => (
+ state.workingInputs[input.id] !== undefined && state.workingInputs[input.id] !== input.value
+ )) || Object.values(state.stageResults).some((stages: ConverterStageResult[]) => stages.some(
+ (stage: ConverterStageResult) => stage.value !== stage.generated.output_value,
+ )) || Object.values(state.applied).some((conversion: PieceConversion) => conversion.manuallyEdited)
+ const hasPartialConversion = state.inputs.some((input: VersionedInput) => input.value.includes('\u27ea'))
+ || Object.values(state.stageResults).some((stages: ConverterStageResult[]) => stages.some(
+ (stage: ConverterStageResult) => stage.generated.input_value.includes('\u27ea'),
+ ))
+ || (Object.keys(state.applied).length > 0 && state.inputs.some(
+ (input: VersionedInput) => !state.applied[input.id] && Boolean(input.value || input.file),
+ ))
+ || state.inputs.some((input: VersionedInput) => {
+ const stages = state.stageResults[input.id] ?? []
+ return stages.length > 0 && stages.length !== (state.pipelines[input.pieceType]?.length ?? 0)
+ })
return {
+ repeatDisabledReason: hasEditedConversion || hasPartialConversion
+ ? 'Repeated sends are unavailable after editing a conversion or converting only part of a prompt. Send once or reset conversions.'
+ : undefined,
editRevision: state.nextRevision,
- inputs: state.inputs,
+ inputs: state.inputs.filter((input: VersionedInput) => !options.selectedIds || options.selectedIds.has(input.id)),
workingInputs: state.workingInputs,
pipelines: state.pipelines,
stageResults: state.stageResults,
- results: completedResults(state),
+ results: Object.fromEntries(Object.entries(completedResults(state)).filter(
+ ([id]: [string, ConverterPreviewResponse]) => !options.selectedIds || options.selectedIds.has(id),
+ )),
errors: state.errors,
applied: state.applied,
isConverting: state.isConverting,
@@ -437,5 +549,7 @@ export function usePieceConverters(inputs: ConverterInputPiece[], scopeKey?: str
clearAll,
editConvertedValue,
restore,
+ snapshot,
+ restoreSnapshot,
}
}
diff --git a/frontend/src/hooks/useConversationDraft.ts b/frontend/src/hooks/useConversationDraft.ts
index 31a770de74..132c689ca5 100644
--- a/frontend/src/hooks/useConversationDraft.ts
+++ b/frontend/src/hooks/useConversationDraft.ts
@@ -25,7 +25,9 @@ interface DraftState extends ConversationSaveInput {
baselineTarget: string | undefined
}
-export function useConversationDraft(newAttackContext?: NewAttackContext) {
+export function useConversationDraft(
+ newAttackContext?: NewAttackContext, options: { pendingUserMessage?: boolean } = {},
+) {
const [draft, setDraft] = useState(null)
const [error, setError] = useState(null)
const activeId = useRef(null)
@@ -37,8 +39,11 @@ export function useConversationDraft(newAttackContext?: NewAttackContext) {
|| targetKey(draft.target) !== draft.baselineTarget
)
const validationError = draft ? validateDraft(draft.messages) : null
+ const messages = draft?.messages ?? []
+ const history = options.pendingUserMessage && messages[messages.length - 1]?.role === 'user'
+ ? messages.slice(0, -1) : messages
const targetError = draft?.target
- ? editorTargetDisabledReason(draft.target, draftDataTypes(draft.messages)) : undefined
+ ? editorTargetDisabledReason(draft.target, draftDataTypes(messages), history) : undefined
const releaseUrls = useCallback((): void => {
for (const url of urls.current) URL.revokeObjectURL(url)
@@ -52,7 +57,12 @@ export function useConversationDraft(newAttackContext?: NewAttackContext) {
activeId.current = id
saved.current = false
setError(null)
- setDraft({ ...input, id, baselineMessages: input.messages, baselineTarget: targetKey(input.target) })
+ setDraft({
+ ...input, id, baselineMessages: input.messages, baselineTarget: targetKey(input.target),
+ sourcePieceIds: input.messages.flatMap((message: ConversationDraftMessage) => message.pieces.flatMap(
+ (piece: ConversationDraftPiece) => piece.source_piece_id ? [piece.source_piece_id] : [],
+ )),
+ })
}, [releaseUrls])
const discard = useCallback((): void => {
activeId.current = null
@@ -134,18 +144,21 @@ export function useConversationDraft(newAttackContext?: NewAttackContext) {
const save = async (
destination: SaveConversationRequest['destination'], onSaved: (response: AddMessageResponse) => void,
messages: ConversationDraftMessage[] = draft?.messages ?? [],
- ): Promise => {
- if (!draft || workflow.saving) return
+ reuseUnsentConversation = false,
+ ): Promise => {
+ if (!draft || workflow.saving) return false
const id = draft.id
setError(null)
try {
if (validationError || targetError) throw new Error(validationError ?? targetError)
- const response = await workflow.save({ ...draft, messages }, destination)
- if (activeId.current !== id) return
+ const response = await workflow.save({ ...draft, messages }, destination, reuseUnsentConversation)
+ if (activeId.current !== id) return false
saved.current = true
onSaved(response)
+ return true
} catch (cause) {
if (activeId.current === id) setError(toApiError(cause).detail)
+ return false
}
}
@@ -154,7 +167,7 @@ export function useConversationDraft(newAttackContext?: NewAttackContext) {
}, [])
return {
- draft, dirty, error, validationError, targetError, saving: workflow.saving,
+ draft, dirty, error, validationError, targetError, history, saving: workflow.saving,
begin, discard, save, changeMessages, changePiece, changeAttachments, addPiece, applyConversions,
shouldBlock: (): boolean => !saved.current && (dirty || workflow.saving),
changeObjective,
diff --git a/frontend/src/hooks/useConversationSave.ts b/frontend/src/hooks/useConversationSave.ts
index e1626cff37..4054cc060d 100644
--- a/frontend/src/hooks/useConversationSave.ts
+++ b/frontend/src/hooks/useConversationSave.ts
@@ -20,6 +20,7 @@ export function useConversationSave(newAttackContext?: NewAttackContext) {
const save = useCallback(async (
input: ConversationSaveInput,
destination: SaveConversationRequest['destination'],
+ reuseUnsentConversation = false,
): Promise => {
if (pending.current) throw new Error('A conversation save is already in progress.')
pending.current = true
@@ -50,6 +51,10 @@ export function useConversationSave(newAttackContext?: NewAttackContext) {
operation_id: operationId,
labels,
messages,
+ ...(reuseUnsentConversation ? {
+ reuse_unsent_conversation: true,
+ expected_source_piece_ids: input.sourcePieceIds ?? [],
+ } : {}),
}
const signature = JSON.stringify(payload)
if (attempt.current?.signature !== signature) attempt.current = { signature, id: generateClientId() }
diff --git a/frontend/src/hooks/usePieceConverters.test.tsx b/frontend/src/hooks/usePieceConverters.test.tsx
index fe3826f81f..d233b9256e 100644
--- a/frontend/src/hooks/usePieceConverters.test.tsx
+++ b/frontend/src/hooks/usePieceConverters.test.tsx
@@ -1,7 +1,7 @@
import { act, renderHook, waitFor } from '@testing-library/react'
import { convertersApi } from '@/services/api'
-import type { ConverterInputPiece, ConverterPreviewResponse } from '@/types'
+import type { ConverterInputPiece, ConverterPreviewResponse, PieceConversionUpdates } from '@/types'
import { buildAppliedConversions } from '@/utils/conversionResults'
import { usePieceConverters } from './useChatConverters'
@@ -27,6 +27,26 @@ const second: ConverterInputPiece[] = [{ id: 'two', pieceType: 'text', name: 'Se
describe('usePieceConverters', () => {
beforeEach(() => jest.resetAllMocks())
+ it('keeps stage edits when editor selection changes and converts only selected pieces', async () => {
+ jest.mocked(convertersApi.previewConversion).mockResolvedValue(response('converted'))
+ const inputs = [...first, ...second]
+ const { result, rerender } = renderHook(({ selected }: { selected: string }) => usePieceConverters(
+ inputs, undefined, { selectedIds: new Set([selected]) },
+ ), { initialProps: { selected: 'one' } })
+ act(() => result.current.addConverter('text', 'converter'))
+ await act(async () => { await result.current.convert('text') })
+ const stageId = result.current.stageResults.one[0].stageId
+ act(() => { result.current.editStageOutput('one', stageId, 'Edited first') })
+ rerender({ selected: 'two' })
+ expect(result.current.inputs.map((input) => input.id)).toEqual(['two'])
+ expect(result.current.results).toEqual({})
+ await act(async () => { await result.current.convert('text') })
+ rerender({ selected: 'one' })
+ expect(result.current.results.one.converted_value).toBe('Edited first')
+ expect(result.current.snapshot().stageResults.two[0].value).toBe('converted')
+ expect(convertersApi.previewConversion).toHaveBeenCalledTimes(2)
+ })
+
it('starts the new selection immediately and ignores a late result from the old selection', async () => {
let resolveOld: (value: ConverterPreviewResponse) => void = () => {}
jest.mocked(convertersApi.previewConversion)
@@ -37,7 +57,7 @@ describe('usePieceConverters', () => {
{ initialProps: { inputs: first, scope: 'first-message' } },
)
act(() => result.current.addConverter('text', 'converter'))
- let pending: Promise
+ let pending: Promise
act(() => { pending = result.current.convert('text') })
await waitFor(() => expect(convertersApi.previewConversion).toHaveBeenCalledTimes(1))
rerender({ inputs: second, scope: 'second-message' })
@@ -95,7 +115,9 @@ describe('usePieceConverters', () => {
})
await act(async () => { await result.current.convert('text') })
const stageId = result.current.stageResults.one[0].stageId
- act(() => { result.current.editStageOutput('one', stageId, 'manual middle') })
+ let updates: PieceConversionUpdates | void = undefined
+ act(() => { updates = result.current.editStageOutput('one', stageId, 'manual middle') })
+ expect(updates).toEqual({ one: null })
expect(result.current.stageResults.one).toHaveLength(1)
expect(result.current.results.one).toBeUndefined()
await act(async () => { await result.current.convertRemaining('one', stageId) })
diff --git a/frontend/src/test-utils/targetFixtures.ts b/frontend/src/test-utils/targetFixtures.ts
index 540ae1e4bc..199eac6e25 100644
--- a/frontend/src/test-utils/targetFixtures.ts
+++ b/frontend/src/test-utils/targetFixtures.ts
@@ -18,6 +18,7 @@ export interface FlatTargetInput {
identifier_hash?: string | null
identifier?: Partial
capabilities?: TargetCapabilities | null
+ supports_history_replay?: boolean
target_specific_params?: Record | null
inner_targets?: FlatTargetInput[] | null
}
@@ -38,6 +39,7 @@ export function makeTarget(flat: FlatTargetInput): TargetInstance {
target_registry_name: flat.target_registry_name,
identifier,
capabilities: flat.capabilities ?? null,
+ ...(flat.supports_history_replay !== undefined ? { supports_history_replay: flat.supports_history_replay } : {}),
target_specific_params: flat.target_specific_params ?? null,
inner_targets: flat.inner_targets ? flat.inner_targets.map(makeTarget) : null,
}
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index 0f998b4bd5..1c77be967e 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -63,6 +63,7 @@ export interface ConverterInputPiece {
}
export interface PieceConversion {
+ manuallyEdited?: boolean
pieceId: string
pieceType: string
converterInstanceIds: string[]
@@ -71,6 +72,9 @@ export interface PieceConversion {
convertedDataType: string
}
+/** Only touched pieces are present; null explicitly clears a stale conversion. */
+export type PieceConversionUpdates = Record
+
export interface ConverterPipelineStage {
readonly id: string
readonly converterId: string
@@ -82,7 +86,23 @@ export interface ConverterStageResult {
value: string
}
+export interface ChatConverterSnapshot {
+ generation: string
+ workingInputs: Record
+ pipelines: Record
+ stageResults: Record
+ errors: Record
+ applied: Record
+}
+
+export interface UndoLastSendAction {
+ readonly disabledReason?: string
+ readonly isUndoing: boolean
+ readonly onUndo: () => void
+}
+
export interface ChatConverterController {
+ readonly repeatDisabledReason?: string
readonly editRevision: number
inputs: ConverterInputPiece[]
workingInputs: Record
@@ -95,10 +115,10 @@ export interface ChatConverterController {
addConverter: (pieceType: string, converterId: string) => void
setPipeline: (pieceType: string, update: (stages: ConverterPipelineStage[]) => ConverterPipelineStage[]) => void
retainConverters: (availableIds: Set) => void
- convert: (pieceType: string) => Promise
- convertRemaining: (pieceId: string, stageId: string) => Promise
- editInput: (pieceId: string, value: string) => void
- editStageOutput: (pieceId: string, stageId: string, value: string) => void
+ convert: (pieceType: string) => Promise
+ convertRemaining: (pieceId: string, stageId: string) => Promise
+ editInput: (pieceId: string, value: string) => PieceConversionUpdates | void
+ editStageOutput: (pieceId: string, stageId: string, value: string) => PieceConversionUpdates | void
apply: () => void
clear: (pieceId: string) => void
clearAll: () => void
@@ -107,6 +127,8 @@ export interface ChatConverterController {
text: string, attachments: MessageAttachment[], conversions: Record,
pipelines?: Record,
) => void
+ snapshot: () => ChatConverterSnapshot
+ restoreSnapshot: (snapshot: ChatConverterSnapshot, text: string, attachments: MessageAttachment[]) => void
}
export interface MessageTextDisplayPiece {
@@ -281,6 +303,8 @@ export interface TargetInstance {
/** Typed identity: class name, endpoint, model name, generation params, content hash. */
identifier: TargetIdentifier
capabilities?: TargetCapabilities | null
+ /** Effective replay support, including configured adapters and provider restoration. */
+ supports_history_replay?: boolean
/** Non-promoted constructor params, curated for display (e.g., RoundRobin weights). */
target_specific_params?: Record | null
/** Inner targets for composite targets like RoundRobinTarget. */
@@ -750,6 +774,7 @@ export interface ConversationDraftPiece extends MessagePieceRequest {
}
export interface ConversationSaveInput {
+ sourcePieceIds?: string[]
messages: ConversationDraftMessage[]
objective: string
initialObjective: string
@@ -791,6 +816,8 @@ export interface SaveConversationRequest {
operation_id?: string
labels?: Record
messages: MessageRequest[]
+ reuse_unsent_conversation?: boolean
+ expected_source_piece_ids?: string[]
}
export interface CreateAttackResponse {
diff --git a/frontend/src/utils/conversationDraft.test.ts b/frontend/src/utils/conversationDraft.test.ts
index 37645d0b80..eed8697b10 100644
--- a/frontend/src/utils/conversationDraft.test.ts
+++ b/frontend/src/utils/conversationDraft.test.ts
@@ -1,10 +1,136 @@
-import type { ConversationDraftMessage, TargetCapabilities } from '@/types'
+import type { ChatConverterSnapshot, ConversationDraftMessage, TargetCapabilities } from '@/types'
import { makeTarget } from '@/test-utils/targetFixtures'
import { buildMessagePieces } from './messageMapper'
-import { draftConverterInputs, draftDataTypes, draftMessageToInput, editorTargetDisabledReason, serializeDraft, toConversationDraft, unansweredToolCallId, validateDraft } from './conversationDraft'
+import {
+ draftConverterInputs, draftDataTypes, draftMessageToComposer, draftMessageToInput, editorTargetDisabledReason,
+ historyReplayDisabledReason, serializeDraft, toConversationDraft, unansweredToolCallId, validateDraft,
+} from './conversationDraft'
describe('conversation drafts', () => {
+ it('returns original text and media with separate conversions and remapped converter stages', () => {
+ const stage = { id: 'stage', converterId: 'base64' }
+ const snapshot: ChatConverterSnapshot = {
+ generation: 'runtime', pipelines: { text: [stage], image: [{ id: 'image-stage', converterId: 'image' }] },
+ workingInputs: { 'pending-text': 'Working text', unrelated: 'Other message' },
+ stageResults: { 'pending-text': [{
+ stageId: stage.id, value: 'Edited output', generated: {
+ converter_id: 'base64', converter_type: 'Base64Converter', input_value: 'Working text',
+ input_data_type: 'text', output_value: 'Generated output', output_data_type: 'text',
+ },
+ }] },
+ errors: { unrelated: 'Other error' }, applied: {},
+ }
+ const file = new File(['image'], 'original.png', { type: 'image/png' })
+ const prompt = draftMessageToComposer({
+ id: 'pending', role: 'user', pieces: [{
+ draftId: 'pending-text', data_type: 'text', original_value: 'Original text',
+ converted_value: 'Edited output', converted_value_data_type: 'text', applied_converter_ids: ['base64'],
+ prompt_metadata: { video_id: 'video' },
+ }, {
+ draftId: 'image', data_type: 'image_path', original_value: '', file, previewUrl: 'blob:original',
+ converted_value: 'converted.png', converted_value_data_type: 'image_path', applied_converter_ids: ['image'],
+ }],
+ }, snapshot)
+ expect(prompt.text).toBe('Original text')
+ expect(prompt.textMetadata).toEqual({ video_id: 'video' })
+ expect(prompt.attachments[0]).toMatchObject({ draftId: 'image', file, url: 'blob:original' })
+ expect(prompt.converters.applied.text).toMatchObject({
+ pieceId: 'text', originalValue: 'Original text', convertedValue: 'Edited output', converterInstanceIds: ['base64'],
+ })
+ expect(prompt.converters.applied.image).toMatchObject({
+ pieceId: 'image', convertedValue: 'converted.png', converterInstanceIds: ['image'],
+ })
+ expect(prompt.converters.stageResults.text).toEqual(snapshot.stageResults['pending-text'])
+ expect(prompt.converters.workingInputs).toEqual({ text: 'Working text' })
+ expect(prompt.converters.errors).toEqual({})
+ expect(prompt.converters.pipelines).toEqual(snapshot.pipelines)
+ })
+
+ it('keeps a text-to-file conversion separate from its original prompt', () => {
+ const prompt = draftMessageToComposer({
+ id: 'pending', role: 'user', pieces: [{
+ draftId: 'pending-text', data_type: 'text', original_value: 'Make an image',
+ converted_value: 'output.png', converted_value_data_type: 'image_path', applied_converter_ids: ['draw'],
+ }],
+ }, { generation: 'runtime', pipelines: {}, stageResults: {}, workingInputs: {}, errors: {}, applied: {} })
+ expect(prompt.text).toBe('Make an image')
+ expect(prompt.attachments).toEqual([])
+ expect(prompt.converters.applied.text).toMatchObject({
+ convertedValue: 'output.png', convertedDataType: 'image_path', originalValue: 'Make an image',
+ })
+ })
+
+ it('combines text pieces without replacing their originals with converted text or clearing pipelines', () => {
+ const pipelines = { text: [{ id: 'stage', converterId: 'base64' }] }
+ const prompt = draftMessageToComposer({
+ id: 'pending', role: 'user', pieces: [{
+ draftId: 'one', data_type: 'text', original_value: 'First', converted_value: 'Converted first',
+ }, { draftId: 'two', data_type: 'text', original_value: 'Second' }],
+ }, { generation: 'runtime', pipelines, stageResults: {}, workingInputs: {}, errors: {}, applied: {} })
+ expect(prompt.text).toBe('First\nSecond')
+ expect(prompt.converters.applied.text.convertedValue).toBe('Converted first\nSecond')
+ expect(prompt.converters.applied.text.manuallyEdited).toBe(true)
+ expect(prompt.converters.pipelines).toEqual(pipelines)
+ expect(prompt.notice).toContain('Multiple text pieces')
+ })
+
+ it.each([
+ [false, false], [true, false], [true, true],
+ ])('allows a fresh request for multi-turn=%s and editable=%s', (multiTurn: boolean, editable: boolean) => {
+ const target = makeTarget({
+ target_registry_name: 'fresh',
+ capabilities: { supports_multi_turn: multiTurn, supports_editable_history: editable, supported_input_modalities: ['text'] },
+ })
+ expect(historyReplayDisabledReason(target, [])).toBeUndefined()
+ expect(editorTargetDisabledReason(target, ['text'], [])).toBeUndefined()
+ expect(editorTargetDisabledReason(target, ['image_path'], [])).toMatch(/image_path/)
+ })
+
+ it.each(['user', 'assistant', 'simulated_assistant', 'tool', 'simulated_tool'])(
+ 'rejects replayed %s history without editable history, but allows an editable target', (role: string) => {
+ const target = makeTarget({
+ target_registry_name: 'immutable',
+ capabilities: { supports_multi_turn: true, supports_editable_history: false, supported_input_modalities: ['text'] },
+ })
+ expect(historyReplayDisabledReason(target, [{ role }])).toMatch(/editable history/)
+ const editable = makeTarget({
+ target_registry_name: 'editable',
+ capabilities: { supports_multi_turn: true, supports_editable_history: true, supported_input_modalities: ['text'] },
+ })
+ expect(historyReplayDisabledReason(editable, [{ role }])).toBeUndefined()
+ },
+ )
+
+ it.each([false, true])('uses effective replay support for an adapted single-turn=%s target', (singleTurn: boolean) => {
+ const target = makeTarget({
+ target_registry_name: 'adapted',
+ supports_history_replay: true,
+ capabilities: {
+ supports_multi_turn: !singleTurn, supports_editable_history: false, supported_input_modalities: ['text'],
+ },
+ })
+ const history = [{ role: 'user' }, { role: 'assistant' }]
+ expect(historyReplayDisabledReason(target, history)).toBeUndefined()
+ expect(editorTargetDisabledReason(target, ['text'], history)).toBeUndefined()
+ expect(historyReplayDisabledReason({ ...target, supports_history_replay: false }, history)).toBeDefined()
+ expect(editorTargetDisabledReason(target, ['image_path'], history)).toMatch(/image_path/)
+ })
+
+ it('allows initial system setup only with system-prompt and multi-turn support', () => {
+ const history = [{ role: 'system' }, { role: 'developer' }]
+ const target = makeTarget({
+ target_registry_name: 'system-bootstrap',
+ capabilities: { supports_multi_turn: true, supports_editable_history: false, supports_system_prompt: true },
+ })
+ expect(historyReplayDisabledReason(target, history)).toBeUndefined()
+ expect(historyReplayDisabledReason(target, [...history, { role: 'simulated_assistant' }])).toBeDefined()
+ expect(historyReplayDisabledReason(makeTarget({
+ target_registry_name: 'no-system',
+ capabilities: { supports_multi_turn: true, supports_editable_history: false, supports_system_prompt: false },
+ }), history)).toBeDefined()
+ })
+
it('preserves text-only remix metadata through composer restoration and request construction', async () => {
const prompt = draftMessageToInput({
id: 'user', role: 'user', pieces: [{
diff --git a/frontend/src/utils/conversationDraft.ts b/frontend/src/utils/conversationDraft.ts
index 9d1efb809f..39df93d338 100644
--- a/frontend/src/utils/conversationDraft.ts
+++ b/frontend/src/utils/conversationDraft.ts
@@ -1,6 +1,6 @@
import type {
- BackendMessage, ConversationDraftMessage, ConversationDraftPiece, ConversationDraftRole,
- ConverterInputPiece, MessageAttachment, SaveConversationRequest, TargetInstance,
+ BackendMessage, ChatConverterSnapshot, ConversationDraftMessage, ConversationDraftPiece, ConversationDraftRole,
+ ConverterInputPiece, MessageAttachment, PieceConversion, SaveConversationRequest, TargetInstance,
} from '@/types'
import { generateClientId } from './clientId'
import { dataTypeToAttachmentType, fileToBase64, mimeTypeToDataType } from './messageMapper'
@@ -14,10 +14,26 @@ export function draftDataTypes(messages: ConversationDraftMessage[]): string[] {
.map((piece: ConversationDraftPiece) => piece.converted_value_data_type ?? piece.data_type)))]
}
-export function editorTargetDisabledReason(target: TargetInstance, dataTypes: string[]): string | undefined {
- if (!target.capabilities?.supports_editable_history || !target.capabilities.supports_multi_turn) {
+export function historyReplayDisabledReason(
+ target: TargetInstance, history?: ReadonlyArray<{ readonly role: string }>,
+): string | undefined {
+ if (history?.length === 0) return undefined
+ const capabilities = target.capabilities
+ const systemSetup = history !== undefined && capabilities?.supports_multi_turn && capabilities.supports_system_prompt
+ && history.every((message: { readonly role: string }) => message.role === 'system' || message.role === 'developer')
+ const supportsReplay = target.supports_history_replay
+ ?? Boolean(capabilities?.supports_editable_history && capabilities.supports_multi_turn)
+ if (!systemSetup && !supportsReplay) {
return 'This target does not support editable history.'
}
+ return undefined
+}
+
+export function editorTargetDisabledReason(
+ target: TargetInstance, dataTypes: string[], history?: ReadonlyArray<{ readonly role: string }>,
+): string | undefined {
+ const replayError = historyReplayDisabledReason(target, history)
+ if (replayError) return replayError
const unsupported = dataTypes.filter((type: string) => !target.capabilities?.supported_input_modalities.includes(type))
if (unsupported.length) return `This target does not support these history data types: ${unsupported.join(', ')}.`
return undefined
@@ -159,6 +175,70 @@ export function draftMessageToInput(message: ConversationDraftMessage): {
}
}
+export function draftMessageToComposer(
+ message: ConversationDraftMessage, snapshot: ChatConverterSnapshot,
+): ReturnType & { converters: ChatConverterSnapshot; notice?: string } {
+ const textPieces = message.pieces.filter((piece: ConversationDraftPiece) => !isPathDataType(piece.data_type))
+ if (textPieces.length > 1) {
+ if (textPieces.every((piece: ConversationDraftPiece) => piece.data_type === 'text'
+ && (piece.converted_value_data_type ?? piece.data_type) === 'text')) {
+ const combined: ConversationDraftPiece = {
+ draftId: generateClientId(), data_type: 'text',
+ original_value: textPieces.map((piece: ConversationDraftPiece) => piece.original_value).join('\n'),
+ converted_value: textPieces.some((piece: ConversationDraftPiece) => piece.converted_value !== undefined)
+ ? textPieces.map((piece: ConversationDraftPiece) => piece.converted_value ?? piece.original_value).join('\n')
+ : undefined,
+ converted_value_data_type: 'text',
+ prompt_metadata: Object.assign({}, ...textPieces.map((piece: ConversationDraftPiece) => piece.prompt_metadata)),
+ }
+ const prompt = draftMessageToComposer({
+ ...message, pieces: [combined, ...message.pieces.filter((piece: ConversationDraftPiece) => isPathDataType(piece.data_type))],
+ }, snapshot)
+ if (prompt.converters.applied.text) prompt.converters.applied.text.manuallyEdited = true
+ return {
+ ...prompt,
+ notice: 'Multiple text pieces were combined. Original and converted text are retained; their separate text-stage edits cannot be combined.',
+ }
+ }
+ return {
+ ...draftMessageToInput(message),
+ converters: { ...snapshot, workingInputs: {}, stageResults: {}, errors: {}, applied: {} },
+ notice: 'Multiple text pieces were combined into one prompt. Their separate original/converted values and stage edits cannot be shown in one text input.',
+ }
+ }
+ const text = textPieces[0]?.original_value ?? ''
+ const attachments = message.pieces.filter((piece: ConversationDraftPiece) => isPathDataType(piece.data_type))
+ .map(draftAttachment)
+ const textMetadata = textPieces[0]?.prompt_metadata
+ const workingInputs: ChatConverterSnapshot['workingInputs'] = {}
+ const stageResults: ChatConverterSnapshot['stageResults'] = {}
+ const errors: ChatConverterSnapshot['errors'] = {}
+ 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 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
+ || convertedType !== piece.data_type || piece.applied_converter_ids?.length || previous)) {
+ const conversion: PieceConversion = {
+ pieceId: id,
+ pieceType: isPathDataType(piece.data_type) ? dataTypeToAttachmentType(piece.data_type) : 'text',
+ originalValue: piece.original_value,
+ convertedValue: piece.converted_value,
+ convertedDataType: convertedType,
+ converterInstanceIds: piece.applied_converter_ids ?? previous?.converterInstanceIds ?? [],
+ ...(previous?.manuallyEdited || (previous && previous.convertedValue !== piece.converted_value)
+ ? { manuallyEdited: true } : {}),
+ }
+ applied[id] = conversion
+ }
+ }
+ return { text, attachments, textMetadata, converters: { ...snapshot, workingInputs, stageResults, errors, applied } }
+}
+
export function attachmentDraft(attachment: MessageAttachment): ConversationDraftPiece {
return {
draftId: attachment.draftId ?? generateClientId(),
diff --git a/frontend/src/utils/conversionResults.ts b/frontend/src/utils/conversionResults.ts
index e87807ccad..06b34bc003 100644
--- a/frontend/src/utils/conversionResults.ts
+++ b/frontend/src/utils/conversionResults.ts
@@ -16,6 +16,8 @@ export function buildAppliedConversions(
originalValue: input.value,
convertedValue: result.converted_value,
convertedDataType: result.converted_value_data_type,
+ ...(result.converted_value !== (result.steps[result.steps.length - 1]?.output_value ?? input.value)
+ ? { manuallyEdited: true } : {}),
}
}
return applied
diff --git a/pyrit/backend/mappers/target_mappers.py b/pyrit/backend/mappers/target_mappers.py
index c3b78792a4..a02b018a51 100644
--- a/pyrit/backend/mappers/target_mappers.py
+++ b/pyrit/backend/mappers/target_mappers.py
@@ -69,11 +69,18 @@ def target_object_to_instance(target_registry_name: str, target_obj: PromptTarge
TargetInstance DTO with metadata derived from the object.
"""
target_identifier = TargetIdentifier.from_component_identifier(target_obj.get_identifier())
+ try:
+ target_obj.validate_history_replay()
+ except ValueError:
+ supports_history_replay = False
+ else:
+ supports_history_replay = True
return TargetInstance(
target_registry_name=target_registry_name,
identifier=target_identifier,
capabilities=target_obj.capabilities,
+ supports_history_replay=supports_history_replay,
target_specific_params=_target_specific_params(target_identifier),
inner_targets=_build_inner_targets(target_obj),
)
diff --git a/pyrit/backend/models/attacks.py b/pyrit/backend/models/attacks.py
index 5201b94278..b1b646cd28 100644
--- a/pyrit/backend/models/attacks.py
+++ b/pyrit/backend/models/attacks.py
@@ -597,7 +597,7 @@ class CreateConversationResponse(BaseModel):
class SaveConversationRequest(_AttackAttributionInput):
- """Save a complete draft as a new conversation, without sending it."""
+ """Save a complete draft without sending it, optionally reusing unsent history."""
save_id: uuid.UUID
destination: Literal["same_attack", "new_attack"]
@@ -608,6 +608,8 @@ class SaveConversationRequest(_AttackAttributionInput):
objective: str | None = Field(None, description="Omit to keep the destination's objective unchanged")
target_registry_name: IdentifierStr | None = None
messages: list[MessageRequest] = Field(default_factory=list)
+ reuse_unsent_conversation: bool = False
+ expected_source_piece_ids: list[uuid.UUID] | None = None
@model_validator(mode="after")
def _validate_destination(self) -> "SaveConversationRequest":
@@ -621,6 +623,13 @@ def _validate_destination(self) -> "SaveConversationRequest":
raise ValueError("Same attack requires attack_result_id; New attack must not supply it")
if (self.source_attack_result_id is None) != (self.source_conversation_id is None):
raise ValueError("Both source attack and source conversation are required together")
+ if self.reuse_unsent_conversation and (
+ self.destination != "same_attack"
+ or self.source_attack_result_id != self.attack_result_id
+ or self.source_conversation_id is None
+ or self.expected_source_piece_ids is None
+ ):
+ raise ValueError("Reusing unsent history requires the same source attack and an expected piece snapshot")
if self.objective is not None:
self.objective = self.objective.strip()
for message in self.messages:
diff --git a/pyrit/backend/routes/attacks.py b/pyrit/backend/routes/attacks.py
index 36ab5812eb..4af5b210ae 100644
--- a/pyrit/backend/routes/attacks.py
+++ b/pyrit/backend/routes/attacks.py
@@ -43,6 +43,7 @@
)
from pyrit.backend.routes.common import parse_label_query_params
from pyrit.backend.services.attack_service import AttackObjectiveConflictError, get_attack_service
+from pyrit.backend.services.history_replay import HistoryReplayError
from pyrit.backend.services.manual_send_scheduler import ManualSendConflictError, ManualSendQueueFullError
from pyrit.backend.services.media_persistence import MediaAccessDeniedError
from pyrit.common.deprecation import print_deprecation_message
@@ -68,8 +69,10 @@ async def save_conversation_async(*, body: SaveConversationRequest, request: Req
return await get_attack_service().save_conversation_async(request=body)
except PermissionError as exc:
raise HTTPException(status_code=403, detail=str(exc)) from exc
- except AttackStateConflictError as exc:
+ except (AttackStateConflictError, ManualSendConflictError) as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
+ except ManualSendQueueFullError as exc:
+ raise HTTPException(status_code=429, detail=str(exc)) from exc
except LookupError as exc:
raise FileNotFoundError(str(exc)) from exc
except ValueError as exc:
@@ -277,6 +280,8 @@ async def create_attack(request: CreateAttackRequest) -> CreateAttackResponse:
raise FileNotFoundError(str(e)) from e
except MediaAccessDeniedError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
+ except HistoryReplayError as exc:
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
except ValueError as e:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
diff --git a/pyrit/backend/services/attack_service.py b/pyrit/backend/services/attack_service.py
index a972bc7ab1..6399291408 100644
--- a/pyrit/backend/services/attack_service.py
+++ b/pyrit/backend/services/attack_service.py
@@ -54,6 +54,7 @@
)
from pyrit.backend.models.common import PaginationInfo
from pyrit.backend.models.message_sends import MessageSendRequest, MessageSendStatus
+from pyrit.backend.services.history_replay import validate_history_replay
from pyrit.backend.services.media_persistence import persist_message_pieces_async
from pyrit.backend.services.message_send_service import (
MessageSendService,
@@ -88,8 +89,10 @@
Message,
MessagePiece,
TargetIdentifier,
+ group_conversation_message_pieces_by_sequence,
)
from pyrit.models.messages.tool_content import validate_tool_conversation
+from pyrit.models.target.request_trace_context import RequestTraceContext
from pyrit.prompt_target import PromptTarget
logger = logging.getLogger(__name__)
@@ -499,6 +502,15 @@ async def create_attack_async(self, *, request: CreateAttackRequest) -> CreateAt
persisted_paths=persisted_paths,
start_sequence=max((piece.sequence for piece in copied), default=-1) + 1,
)
+ if copied or pieces:
+ target_object = await self._validate_editor_target_async(
+ target_identifier=target_identifier, registry_name=request.target_registry_name
+ )
+ if target_object:
+ validate_history_replay(
+ target=target_object,
+ messages=group_conversation_message_pieces_by_sequence([*copied, *pieces]),
+ )
task = asyncio.create_task(
self._memory.add_conversation_branches_to_attack_async(
attack_result_id=attack_result.attack_result_id,
@@ -613,7 +625,19 @@ async def update_attack_async(self, *, attack_result_id: str, request: UpdateAtt
async def save_conversation_async(self, *, request: SaveConversationRequest) -> AddMessageResponse:
"""
- Save a complete draft without changing source pieces or invoking a target.
+ Save a complete draft without invoking a target or replacing sent evidence.
+
+ Returns:
+ The stored attack and conversation.
+ """
+ if not request.reuse_unsent_conversation:
+ return await self._save_conversation_async(request=request)
+ with self._message_send_service.reserve_conversation(str(request.source_conversation_id)):
+ return await self._save_conversation_async(request=request)
+
+ async def _save_conversation_async(self, *, request: SaveConversationRequest) -> AddMessageResponse:
+ """
+ Prepare and persist a conversation while the caller holds any required source reservation.
Returns:
The stored attack and conversation.
@@ -637,13 +661,41 @@ async def save_conversation_async(self, *, request: SaveConversationRequest) ->
else str(uuid.uuid5(request.save_id, "attack"))
)
existing = await self._memory.get_attack_results_async(attack_result_ids=[attack_result_id])
- if existing and existing[0].metadata.get(f"conversation_save:{conversation_id}") == fingerprint:
+ if existing and (
+ existing[0].metadata.get(f"conversation_save:{conversation_id}") == fingerprint
+ or existing[0].metadata.get(f"conversation_save:{conversation_id}:{fingerprint}")
+ ):
return await self._saved_conversation_response_async(
attack_result_id=attack_result_id,
conversation_id=conversation_id,
)
+ if (
+ request.reuse_unsent_conversation
+ and existing
+ and (
+ existing[0].metadata.get(f"conversation_save:{request.source_conversation_id}") == fingerprint
+ or existing[0].metadata.get(f"conversation_save:{request.source_conversation_id}:{fingerprint}")
+ )
+ ):
+ return await self._saved_conversation_response_async(
+ attack_result_id=attack_result_id,
+ conversation_id=str(request.source_conversation_id),
+ )
source_pieces = await self._get_save_source_async(request=request)
+ replacements: dict[str, Sequence[MessagePiece]] | None = None
+ if request.reuse_unsent_conversation:
+ if set(source_pieces) != set(request.expected_source_piece_ids or []):
+ raise AttackStateConflictError("The conversation changed. Reload before leaving edit mode.")
+ if not any(
+ piece.role in ("assistant", "tool")
+ or piece.prompt_metadata.get(RequestTraceContext.REQUEST_METADATA_KEY)
+ or piece.prompt_metadata.get(RequestTraceContext.METADATA_KEY)
+ for piece in source_pieces.values()
+ ):
+ conversation_id = str(request.source_conversation_id)
+ replacements = {conversation_id: list(source_pieces.values())}
same_attack = request.destination == "same_attack"
+ replay_registry_name = request.target_registry_name
new_attack: AttackResult | None = None
expected_fields: dict[str, Any] = {}
update_fields: dict[str, Any] = {}
@@ -655,6 +707,9 @@ async def save_conversation_async(self, *, request: SaveConversationRequest) ->
attack = results[0]
if request.operation_id is not None and request.operation_id != attack.operation_id:
raise ValueError("Operation attribution is immutable on continuation")
+ original_registry_name = attack.metadata.get("target_registry_name")
+ if isinstance(original_registry_name, str):
+ replay_registry_name = original_registry_name
if attack.operator and attack.operator != request.operator:
raise PermissionError("Cannot save to an attack owned by another operator")
identifier = attack.get_attack_strategy_identifier()
@@ -686,7 +741,7 @@ async def save_conversation_async(self, *, request: SaveConversationRequest) ->
)
target = await self._validate_editor_target_async(
target_identifier=target_identifier,
- registry_name=request.target_registry_name,
+ registry_name=replay_registry_name,
)
persisted_paths: list[str] = []
inserted = False
@@ -713,7 +768,9 @@ async def save_conversation_async(self, *, request: SaveConversationRequest) ->
if same_attack
and request.source_conversation_id
and request.source_attack_result_id == request.attack_result_id
+ and replacements is None
else None,
+ replace_conversation_pieces=replacements,
)
)
try:
@@ -859,7 +916,7 @@ async def _prepare_message_pieces_async(
prepared_pieces.append((saved, request_piece))
prepared_messages.append(Message(message_pieces=prepared))
if target:
- target.validate_history(prepared_messages)
+ validate_history_replay(target=target, messages=prepared_messages)
elif source_pieces is not None:
validate_tool_conversation(prepared_messages)
for saved, request_piece in prepared_pieces:
@@ -877,13 +934,13 @@ async def _validate_editor_target_async(
registry_name: str | None,
) -> PromptTarget | None:
"""
- Resolve a registered target that supports editable, multi-turn history.
+ Resolve a registered target; check replay capabilities against the actual history separately.
Returns:
The resolved target for provider preflight, or None for an unbound draft.
Raises:
- ValueError: If a bound target is unavailable or cannot replay the draft.
+ ValueError: If a bound target is unavailable or its identity no longer matches.
"""
if target_identifier is None:
return None
@@ -899,9 +956,6 @@ async def _validate_editor_target_async(
break
if target is None or target.identifier.hash != target_identifier.hash:
raise ValueError("The attack target is not registered. Choose New attack without a target.")
- capabilities = target.capabilities
- if not capabilities.supports_editable_history or not capabilities.supports_multi_turn:
- raise ValueError("The selected target does not support editable history. Select a different target.")
target_object = service.get_target_object(target_registry_name=target.target_registry_name)
if target_object is None:
raise ValueError("The selected target is no longer registered")
@@ -1074,6 +1128,17 @@ async def create_related_conversation_async(
target_identifier=objective_target,
)
+ if all_pieces and conversation.target_identifier is not None:
+ target = await self._validate_editor_target_async(
+ target_identifier=conversation.target_identifier,
+ registry_name=ar.metadata.get("target_registry_name")
+ if isinstance(ar.metadata.get("target_registry_name"), str)
+ else None,
+ )
+ if target:
+ validate_history_replay(
+ target=target, messages=group_conversation_message_pieces_by_sequence(all_pieces)
+ )
stored = await self._memory.add_conversation_branches_to_attack_async(
attack_result_id=attack_result_id,
conversations=[conversation],
@@ -1189,7 +1254,7 @@ async def _bind_manual_target_async(self, *, attack: AttackResult, registry_name
)
if target_object:
for conversation in conversations.values():
- target_object.validate_history(conversation)
+ validate_history_replay(target=target_object, messages=conversation)
atomic = AtomicAttackIdentifier.build(
attack_identifier=AttackIdentifier(
class_name="ManualAttack",
diff --git a/pyrit/backend/services/history_replay.py b/pyrit/backend/services/history_replay.py
new file mode 100644
index 0000000000..b49d9b72b2
--- /dev/null
+++ b/pyrit/backend/services/history_replay.py
@@ -0,0 +1,43 @@
+# Copyright (c) Microsoft Corporation.
+# Licensed under the MIT license.
+
+"""Capability checks for history copied into a fresh target conversation."""
+
+from collections.abc import Sequence
+
+from pyrit.models import Message
+from pyrit.prompt_target import PromptTarget
+
+
+class HistoryReplayError(ValueError):
+ """The selected target cannot replay the supplied conversation history."""
+
+
+def validate_history_replay(*, target: PromptTarget, messages: Sequence[Message]) -> None:
+ """
+ Check replay permission separately from ordinary live continuation.
+
+ Empty history needs no replay capability. Initial system/developer setup is
+ also allowed when the target supports system prompts and multiple turns.
+
+ Raises:
+ ValueError: The target cannot replay the history or accept its pieces.
+ """
+ capabilities = target.capabilities
+ system_setup = (
+ capabilities.supports_multi_turn
+ and capabilities.supports_system_prompt
+ and all(message.api_role in ("system", "developer") for message in messages)
+ )
+ if messages and not system_setup:
+ try:
+ target.validate_history_replay()
+ except ValueError as error:
+ raise HistoryReplayError(
+ "The selected target cannot initialize copies of this conversation because it does not support "
+ "editable history. Select a different target or configure a supported history adapter."
+ ) from error
+ try:
+ target.validate_history(messages)
+ except ValueError as error:
+ raise HistoryReplayError(str(error)) from error
diff --git a/pyrit/backend/services/message_send_service.py b/pyrit/backend/services/message_send_service.py
index 5351370600..fee546cc1d 100644
--- a/pyrit/backend/services/message_send_service.py
+++ b/pyrit/backend/services/message_send_service.py
@@ -11,7 +11,7 @@
import uuid
from collections import OrderedDict
from collections.abc import AsyncGenerator, Callable, Coroutine
-from contextlib import ExitStack, asynccontextmanager
+from contextlib import AbstractContextManager, ExitStack, asynccontextmanager
from dataclasses import dataclass, replace
from datetime import UTC, datetime
from functools import lru_cache, partial
@@ -28,6 +28,7 @@
RequestConverterMode,
)
from pyrit.backend.services.converter_service import get_converter_service
+from pyrit.backend.services.history_replay import validate_history_replay
from pyrit.backend.services.manual_send_scheduler import (
ManualSendConflictError,
ManualSendQueueFullError,
@@ -66,6 +67,7 @@ class _ValidatedMessage:
request_configurations: list[ConverterConfiguration]
response_configurations: list[ConverterConfiguration]
applied_identifiers: dict[int, list[ConverterIdentifier]]
+ replay_target: PromptTarget | None = None
@dataclass(kw_only=True)
@@ -154,6 +156,15 @@ def __init__(
self._closing = False
self._shutdown_task: asyncio.Task[None] | None = None
+ def reserve_conversation(self, conversation_id: str) -> AbstractContextManager[None]:
+ """
+ Reserve a conversation so a caller can replace unsent history without overlapping a send.
+
+ Returns:
+ The conversation's exclusive manual-operation reservation.
+ """
+ return self._scheduler.reserve(conversation_id=conversation_id)
+
async def submit_async(self, *, attack_result_id: str, request: MessageSendRequest) -> MessageSendStatus:
"""
Validate and admit one background send, deduplicating only retained worker-local submissions.
@@ -305,12 +316,25 @@ async def _validate_message_async(self, *, attack_result_id: str, request: AddMe
)
if request.send and target is None:
raise ValueError(f"Target object for '{target_registry_name}' not found")
+ replay_target = None
+ original_registry_name = ar.metadata.get("target_registry_name")
+ if isinstance(request, MessageSendRequest) and request.count > 1 and isinstance(original_registry_name, str):
+ replay_target = get_target_service().get_target_object(target_registry_name=original_registry_name)
+ if replay_target is None:
+ raise ValueError("The original attack target is unavailable. Choose a new attack.")
+ self._validate_target_match(attack_identifier=ar.get_attack_strategy_identifier(), target=replay_target)
+ if isinstance(request, MessageSendRequest) and request.count > 1 and target is not None:
+ history = await self._memory.get_conversation_messages_async(conversation_id=msg_conversation_id)
+ if replay_target is not None and replay_target is not target:
+ validate_history_replay(target=replay_target, messages=history)
+ validate_history_replay(target=target, messages=history)
return _ValidatedMessage(
target=target,
request_configurations=request_converter_configs,
response_configurations=response_converter_configs,
applied_identifiers=resolve_applied_converter_identifiers(request.pieces),
+ replay_target=replay_target,
)
async def _validate_repeat_history_async(self, *, request: MessageSendRequest, target: PromptTarget | None) -> None:
@@ -441,6 +465,10 @@ async def _prepare_repeated_send_async(
if source.target_identifier is None:
source.target_identifier = validated.target.get_identifier()
history = list(await self._memory.get_conversation_messages_async(conversation_id=source.conversation_id))
+ # Recheck after queueing: the source history may have changed since admission.
+ if validated.replay_target is not None and validated.replay_target is not validated.target:
+ validate_history_replay(target=validated.replay_target, messages=history)
+ validate_history_replay(target=validated.target, messages=history)
sequence = max((message.sequence for message in history), default=-1) + 1
operation.status.request_turn_number = sequence
message = await self._prepare_message_async(
diff --git a/pyrit/memory/memory_interface.py b/pyrit/memory/memory_interface.py
index 3a8cd03d53..5ff88f15fd 100644
--- a/pyrit/memory/memory_interface.py
+++ b/pyrit/memory/memory_interface.py
@@ -5410,6 +5410,7 @@ def _execute_add_conversation_branches_to_attack(
expected_fields: Mapping[str, Any] | None = None,
update_fields: Mapping[str, Any] | None = None,
request_fingerprint: str | None = None,
+ replace_conversation_pieces: Mapping[str, Sequence[MessagePiece]] | None = None,
) -> bool:
"""
Atomically store initial or related conversations, pieces, and attack references.
@@ -5431,6 +5432,9 @@ def _execute_add_conversation_branches_to_attack(
conversation_ids = [conversation.conversation_id for conversation in conversations]
if len(set(conversation_ids)) != len(conversation_ids):
raise ValueError("Prepared branch conversation IDs must be unique")
+ replacements = replace_conversation_pieces or {}
+ if not set(replacements).issubset(conversation_ids):
+ raise ValueError("Replacement snapshots must belong to the prepared conversations")
if source_conversation and source_conversation.conversation_id in conversation_ids:
raise ValueError("A prepared branch cannot replace the source conversation")
if any(not piece.not_in_memory and piece.conversation_id not in conversation_ids for piece in message_pieces):
@@ -5450,7 +5454,10 @@ def _execute_add_conversation_branches_to_attack(
if (
request_fingerprint
and entry is not None
- and (entry.attack_metadata or {}).get(receipt_key) == request_fingerprint
+ and (
+ (entry.attack_metadata or {}).get(receipt_key) == request_fingerprint
+ or (entry.attack_metadata or {}).get(f"{receipt_key}:{request_fingerprint}")
+ )
):
return False
if new_attack is not None:
@@ -5460,6 +5467,27 @@ def _execute_add_conversation_branches_to_attack(
elif entry is None:
return False
self._check_attack_fields(entry=entry, expected_fields=expected_fields or {})
+ if replacements:
+ active_ids = {entry.conversation_id, *(entry.pruned_conversation_ids or [])}
+ if not set(replacements).issubset(active_ids):
+ raise ValueError("Replacement conversations must belong to the destination attack")
+ self._check_conversation_history(session=session, expected=replacements)
+ piece_ids = [piece.id for pieces in replacements.values() for piece in pieces]
+ if piece_ids:
+ if (
+ session.query(ScoreEntry.id)
+ .filter(ScoreEntry.prompt_request_response_id.in_(piece_ids))
+ .first()
+ ):
+ raise AttackStateConflictError(
+ "Scored history cannot be replaced. Save a new conversation."
+ )
+ session.query(EmbeddingDataEntry).filter(EmbeddingDataEntry.id.in_(piece_ids)).delete(
+ synchronize_session=False
+ )
+ session.query(PromptMemoryEntry).filter(PromptMemoryEntry.id.in_(piece_ids)).delete(
+ synchronize_session=False
+ )
if source_conversation is not None:
active_ids = {entry.conversation_id, *(entry.pruned_conversation_ids or [])}
if source_conversation.conversation_id not in active_ids:
@@ -5469,7 +5497,11 @@ def _execute_add_conversation_branches_to_attack(
conversation=source_conversation.model_copy(update={"attack_result_id": attack_result_id}),
)
for conversation in conversations:
- if request_fingerprint and session.get(ConversationEntry, conversation.conversation_id) is not None:
+ if (
+ request_fingerprint
+ and conversation.conversation_id not in replacements
+ and session.get(ConversationEntry, conversation.conversation_id) is not None
+ ):
raise AttackStateConflictError("The creation identity is already in use")
self._insert_conversation_in_session(
session=session,
@@ -5483,7 +5515,11 @@ def _execute_add_conversation_branches_to_attack(
entry.pruned_conversation_ids = pruned_ids or None
self._apply_attack_fields_in_session(session=session, entry=entry, update_fields=update_fields or {})
if request_fingerprint:
- entry.attack_metadata = {**(entry.attack_metadata or {}), receipt_key: request_fingerprint}
+ entry.attack_metadata = {
+ **(entry.attack_metadata or {}),
+ receipt_key: request_fingerprint,
+ f"{receipt_key}:{request_fingerprint}": True,
+ }
entry.timestamp = datetime.now(UTC)
return True
except IntegrityError:
@@ -5493,7 +5529,10 @@ def _execute_add_conversation_branches_to_attack(
if (
request_fingerprint
and existing is not None
- and (existing.attack_metadata or {}).get(receipt_key) == request_fingerprint
+ and (
+ (existing.attack_metadata or {}).get(receipt_key) == request_fingerprint
+ or (existing.attack_metadata or {}).get(f"{receipt_key}:{request_fingerprint}")
+ )
):
return False
raise
@@ -9725,6 +9764,7 @@ def add_conversation_branches_to_attack(
expected_fields: Mapping[str, Any] | None = None,
update_fields: Mapping[str, Any] | None = None,
request_fingerprint: str | None = None,
+ replace_conversation_pieces: Mapping[str, Sequence[MessagePiece]] | None = None,
) -> bool:
"""
Use ``add_conversation_branches_to_attack_async``.
@@ -9748,6 +9788,7 @@ def add_conversation_branches_to_attack(
expected_fields=expected_fields,
update_fields=update_fields,
request_fingerprint=request_fingerprint,
+ replace_conversation_pieces=replace_conversation_pieces,
)
@legacy_sync_override(lambda: MemoryInterface.add_conversation_branches_to_attack)
@@ -9762,6 +9803,7 @@ async def add_conversation_branches_to_attack_async(
expected_fields: Mapping[str, Any] | None = None,
update_fields: Mapping[str, Any] | None = None,
request_fingerprint: str | None = None,
+ replace_conversation_pieces: Mapping[str, Sequence[MessagePiece]] | None = None,
) -> bool:
"""
Atomically store initial or related conversations, pieces, and attack references.
@@ -9790,6 +9832,7 @@ async def add_conversation_branches_to_attack_async(
expected_fields=expected_fields,
update_fields=update_fields,
request_fingerprint=request_fingerprint,
+ replace_conversation_pieces=replace_conversation_pieces,
)
async def update_attack_result_conditionally_async(
diff --git a/pyrit/models/catalog/target.py b/pyrit/models/catalog/target.py
index 6fad8fe073..ccc73e8357 100644
--- a/pyrit/models/catalog/target.py
+++ b/pyrit/models/catalog/target.py
@@ -53,6 +53,10 @@ class TargetInstance(BaseModel):
),
)
capabilities: TargetCapabilities = Field(..., description="Structured snapshot of target capabilities")
+ supports_history_replay: bool = Field(
+ False,
+ description="Effective history replay support, including configured adapters and provider restoration",
+ )
target_specific_params: dict[str, JSONValue] | None = Field(
None,
description="Non-promoted constructor parameters, curated for display (e.g., RoundRobin weights)",
diff --git a/tests/unit/backend/test_attack_service.py b/tests/unit/backend/test_attack_service.py
index f54b6e2908..062b6d12ff 100644
--- a/tests/unit/backend/test_attack_service.py
+++ b/tests/unit/backend/test_attack_service.py
@@ -23,6 +23,7 @@
import pyrit
import pyrit.backend.services.pagination as backend_pagination
import pyrit.common.pagination as common_pagination
+from pyrit.backend.mappers.target_mappers import target_object_to_instance
from pyrit.backend.models.attacks import (
AddMessageRequest,
AttackSummary,
@@ -1008,7 +1009,7 @@ async def test_manual_creation_registers_ownership_async(
request=MessagePiece(role="user", original_value="history", conversation_id=source_id).to_message()
)
with patch("pyrit.backend.services.attack_service.get_target_service") as targets:
- targets.return_value.get_target_async = AsyncMock(return_value=object())
+ targets.return_value.get_target_async = AsyncMock(return_value=target_object_to_instance("target", target))
targets.return_value.get_target_object.return_value = target
created = await AttackService().create_attack_async(
request=CreateAttackRequest(
@@ -1073,12 +1074,11 @@ async def test_create_attack_stores_attack_result(self, attack_service, mock_mem
async def test_create_attack_stores_prepended_conversation(self, attack_service, mock_memory) -> None:
"""Test that create_attack stores prepended conversation messages."""
with patch("pyrit.backend.services.attack_service.get_target_service") as mock_get_target_service:
- mock_target_obj = MagicMock()
- mock_target_obj.get_identifier.return_value = ComponentIdentifier(
- class_name="TextTarget", class_module="pyrit.prompt_target"
- )
+ mock_target_obj = MockPromptTarget()
mock_target_service = MagicMock()
- mock_target_service.get_target_async = AsyncMock(return_value=MagicMock(type="TextTarget"))
+ mock_target_service.get_target_async = AsyncMock(
+ return_value=target_object_to_instance("target-1", mock_target_obj)
+ )
mock_target_service.get_target_object.return_value = mock_target_obj
mock_get_target_service.return_value = mock_target_service
@@ -1100,12 +1100,11 @@ async def test_create_attack_stores_prepended_conversation(self, attack_service,
async def test_create_attack_lowers_system_prompt_to_system_message(self, attack_service, mock_memory) -> None:
"""Test that system_prompt is lowered to a single system-role message at sequence 0."""
with patch("pyrit.backend.services.attack_service.get_target_service") as mock_get_target_service:
- mock_target_obj = MagicMock()
- mock_target_obj.get_identifier.return_value = ComponentIdentifier(
- class_name="TextTarget", class_module="pyrit.prompt_target"
- )
+ mock_target_obj = MockPromptTarget()
mock_target_service = MagicMock()
- mock_target_service.get_target_async = AsyncMock(return_value=MagicMock(type="TextTarget"))
+ mock_target_service.get_target_async = AsyncMock(
+ return_value=target_object_to_instance("target-1", mock_target_obj)
+ )
mock_target_service.get_target_object.return_value = mock_target_obj
mock_get_target_service.return_value = mock_target_service
@@ -1143,12 +1142,11 @@ async def test_create_attack_system_prompt_prepends_before_prepended_conversatio
) -> None:
"""Test that system_prompt is inserted at sequence 0, ahead of prepended_conversation messages."""
with patch("pyrit.backend.services.attack_service.get_target_service") as mock_get_target_service:
- mock_target_obj = MagicMock()
- mock_target_obj.get_identifier.return_value = ComponentIdentifier(
- class_name="TextTarget", class_module="pyrit.prompt_target"
- )
+ mock_target_obj = MockPromptTarget()
mock_target_service = MagicMock()
- mock_target_service.get_target_async = AsyncMock(return_value=MagicMock(type="TextTarget"))
+ mock_target_service.get_target_async = AsyncMock(
+ return_value=target_object_to_instance("target-1", mock_target_obj)
+ )
mock_target_service.get_target_object.return_value = mock_target_obj
mock_get_target_service.return_value = mock_target_service
@@ -1221,12 +1219,11 @@ async def test_create_attack_prepended_messages_have_incrementing_sequences(
) -> None:
"""Test that multiple prepended messages get incrementing sequence numbers and preserve lineage."""
with patch("pyrit.backend.services.attack_service.get_target_service") as mock_get_target_service:
- mock_target_obj = MagicMock()
- mock_target_obj.get_identifier.return_value = ComponentIdentifier(
- class_name="TextTarget", class_module="pyrit.prompt_target"
- )
+ mock_target_obj = MockPromptTarget()
mock_target_service = MagicMock()
- mock_target_service.get_target_async = AsyncMock(return_value=MagicMock(type="TextTarget"))
+ mock_target_service.get_target_async = AsyncMock(
+ return_value=target_object_to_instance("target-1", mock_target_obj)
+ )
mock_target_service.get_target_object.return_value = mock_target_obj
mock_get_target_service.return_value = mock_target_service
@@ -2888,10 +2885,11 @@ async def test_nested_branching_preserves_target_after_version_change_async(
source_id = source.conversation_id
for _ in range(2):
- branch = await service.create_related_conversation_async(
- attack_result_id=attack.attack_result_id,
- request=CreateConversationRequest(source_conversation_id=source_id, cutoff_index=0),
- )
+ with patch.object(service, "_validate_editor_target_async", return_value=MockPromptTarget()):
+ branch = await service.create_related_conversation_async(
+ attack_result_id=attack.attack_result_id,
+ request=CreateConversationRequest(source_conversation_id=source_id, cutoff_index=0),
+ )
assert branch is not None
async with await sqlite_instance.get_session_async() as session:
rows = (
@@ -3019,7 +3017,10 @@ async def test_branch_persistence_failure_does_not_commit_copies_async(
mock_memory.duplicate_messages_async.return_value = ("branch", [copied])
mock_memory.add_conversation_branches_to_attack_async.side_effect = RuntimeError("branch insertion failed")
- with pytest.raises(RuntimeError, match="branch insertion failed"):
+ with (
+ patch.object(attack_service, "_validate_editor_target_async", return_value=MockPromptTarget()),
+ pytest.raises(RuntimeError, match="branch insertion failed"),
+ ):
await attack_service.create_related_conversation_async(
attack_result_id="ar-attack-1",
request=CreateConversationRequest(source_conversation_id="attack-1", cutoff_index=0),
@@ -3396,9 +3397,14 @@ async def test_create_related_conversation_uses_duplicate_branch(
prepared = Conversation(conversation_id="branch-dup", target_identifier=expected_target)
pieces = [MessagePiece(conversation_id="branch-dup", role="user", original_value="copy")] if has_pieces else []
- with patch.object(
- attack_service, "_prepare_conversation_up_to_async", return_value=(prepared, pieces)
- ) as mock_dup:
+ with (
+ patch.object(
+ attack_service, "_prepare_conversation_up_to_async", return_value=(prepared, pieces)
+ ) as mock_dup,
+ patch.object(
+ attack_service, "_validate_editor_target_async", return_value=MockPromptTarget()
+ ) as resolve_target,
+ ):
result = await attack_service.create_related_conversation_async(
attack_result_id="attack-1",
request=CreateConversationRequest(source_conversation_id="attack-1", cutoff_index=2),
@@ -3406,6 +3412,7 @@ async def test_create_related_conversation_uses_duplicate_branch(
assert result is not None
assert result.conversation_id == "branch-dup"
+ assert resolve_target.await_count == int(bool(pieces) and expected_target is not None)
mock_dup.assert_called_once()
assert mock_dup.call_args.kwargs == {
"source_conversation_id": "attack-1",
diff --git a/tests/unit/backend/test_conversation_editor.py b/tests/unit/backend/test_conversation_editor.py
index 14db53dacc..21d7bd60f6 100644
--- a/tests/unit/backend/test_conversation_editor.py
+++ b/tests/unit/backend/test_conversation_editor.py
@@ -20,6 +20,7 @@
ConversationMessageRequest,
ConversationPieceRequest,
CreateAttackRequest,
+ CreateConversationRequest,
SaveConversationRequest,
UpdateAttackRequest,
)
@@ -28,6 +29,7 @@
from pyrit.backend.models.targets import TargetListResponse
from pyrit.backend.routes.attacks import get_saved_conversation_async as get_saved_conversation_route_async
from pyrit.backend.services.attack_service import AttackService
+from pyrit.backend.services.manual_send_scheduler import ManualSendConflictError
from pyrit.backend.services.target_service import TargetService
from pyrit.memory import SQLiteMemory
from pyrit.memory.memory_interface import AttackStateConflictError
@@ -37,6 +39,7 @@
Conversation,
ConversationReference,
ConversationType,
+ Message,
MessagePiece,
PromptDataType,
Score,
@@ -107,6 +110,287 @@ def response_target(patch_central_database: None) -> Iterator[OpenAIResponseTarg
@pytest.mark.usefixtures("patch_central_database")
class TestConversationEditor:
+ async def test_edit_exit_does_not_replace_history_already_read_by_an_inflight_send_async(
+ self, *, editor_target: MockPromptTarget, sqlite_instance: SQLiteMemory
+ ) -> None:
+ service = AttackService()
+ request = draft(value="Context seen by provider")
+ request.messages[0].role = "system"
+ request.target_registry_name = "selected"
+ saved = await service.save_conversation_async(request=request)
+ conversation_id = saved.messages.conversation_id
+ piece = saved.messages.messages[0].message_pieces[0]
+ edit = SaveConversationRequest(
+ save_id=uuid.uuid4(),
+ destination="same_attack",
+ attack_result_id=saved.attack.attack_result_id,
+ source_attack_result_id=saved.attack.attack_result_id,
+ source_conversation_id=conversation_id,
+ operator="owner",
+ target_registry_name="selected",
+ reuse_unsent_conversation=True,
+ expected_source_piece_ids=[piece.id],
+ messages=[
+ ConversationMessageRequest(
+ role="system",
+ pieces=[ConversationPieceRequest(original_value="Changed context")],
+ )
+ ],
+ )
+ entered, release = asyncio.Event(), asyncio.Event()
+ original_send = editor_target._send_prompt_to_target_async
+
+ async def blocked_send_async(*, normalized_conversation: list[Message]) -> list[Message]:
+ assert normalized_conversation[0].get_piece().converted_value == "Context seen by provider"
+ entered.set()
+ await release.wait()
+ return await original_send(normalized_conversation=normalized_conversation)
+
+ sends = service._message_send_service
+ async with message_send_lifecycle_async(sends):
+ with patch.object(editor_target, "_send_prompt_to_target_async", side_effect=blocked_send_async):
+ status = await sends.submit_async(
+ attack_result_id=saved.attack.attack_result_id,
+ request=MessageSendRequest(
+ submission_id="inflight-edit",
+ target_conversation_id=conversation_id,
+ target_registry_name="selected",
+ pieces=[ConversationPieceRequest(original_value="Next prompt")],
+ ),
+ )
+ try:
+ await asyncio.wait_for(entered.wait(), timeout=5)
+ with pytest.raises(ManualSendConflictError, match="already in progress"):
+ await service.save_conversation_async(request=edit)
+ history = await sqlite_instance.get_message_pieces_async(conversation_id=conversation_id)
+ assert [item.id for item in history] == [piece.id]
+ assert history[0].converted_value == "Context seen by provider"
+ finally:
+ release.set()
+ assert (await _settle_send_async(service=sends, status=status)).state == MessageSendState.COMPLETED
+ with pytest.raises(AttackStateConflictError, match="conversation changed"):
+ await service.save_conversation_async(request=edit)
+ with sends.reserve_conversation(conversation_id):
+ pass
+
+ async def test_same_attack_uses_original_target_capabilities_not_an_alias_async(
+ self, sqlite_instance: SQLiteMemory
+ ) -> None:
+ original = MockPromptTarget()
+ alias = MockPromptTarget()
+ targets = {"origin": original, "alias": alias}
+ target_service = MagicMock(spec=TargetService)
+ target_service.get_target_object.side_effect = lambda target_registry_name: targets[target_registry_name]
+
+ async def get_target_async(*, target_registry_name: str) -> TargetInstance:
+ return target_object_to_instance(target_registry_name, targets[target_registry_name])
+
+ target_service.get_target_async.side_effect = get_target_async
+ with patch("pyrit.backend.services.attack_service.get_target_service", return_value=target_service):
+ service = AttackService()
+ request = draft()
+ request.target_registry_name = "origin"
+ source = await service.save_conversation_async(request=request)
+ original.apply_capabilities(capabilities=TargetCapabilities(supports_multi_turn=True))
+ assert original.get_identifier().hash == alias.get_identifier().hash
+ request = draft(value="Copied context")
+ request.destination = "same_attack"
+ request.attack_result_id = source.attack.attack_result_id
+ request.target_registry_name = "alias"
+ with pytest.raises(ValueError, match="editable history"):
+ await service.save_conversation_async(request=request)
+ request.destination = "new_attack"
+ request.attack_result_id = None
+ saved = await service.save_conversation_async(request=request)
+ assert saved.attack.attack_result_id != source.attack.attack_result_id
+ assert saved.messages.messages[0].message_pieces[0].original_value == "Copied context"
+ assert len(await sqlite_instance.get_attack_results_async()) == 2
+
+ @pytest.mark.parametrize("role", ["user", "simulated_assistant"])
+ async def test_replay_rules_cover_same_attack_new_attack_and_copy_routes_async(
+ self, *, editor_target: MockPromptTarget, sqlite_instance: SQLiteMemory, role: str
+ ) -> None:
+ service = AttackService()
+ request = draft()
+ request.target_registry_name = "selected"
+ request.messages[0].role = role
+ source = await service.save_conversation_async(request=request)
+ editor_target.apply_capabilities(capabilities=TargetCapabilities(supports_multi_turn=True))
+ copy = draft(value="Copied history")
+ copy.target_registry_name = "selected"
+ copy.source_attack_result_id = source.attack.attack_result_id
+ copy.source_conversation_id = uuid.UUID(source.messages.conversation_id)
+ copy.messages[0].role = role
+ with pytest.raises(ValueError, match="editable history"):
+ await service.save_conversation_async(request=copy)
+ copy.destination = "same_attack"
+ copy.attack_result_id = source.attack.attack_result_id
+ with pytest.raises(ValueError, match="editable history"):
+ await service.save_conversation_async(request=copy)
+ with pytest.raises(ValueError, match="editable history"):
+ await service.create_related_conversation_async(
+ attack_result_id=source.attack.attack_result_id,
+ request=CreateConversationRequest(
+ source_conversation_id=source.messages.conversation_id, cutoff_index=0
+ ),
+ )
+ with pytest.raises(ValueError, match="editable history"):
+ await service.create_attack_async(
+ request=CreateAttackRequest(
+ target_registry_name="selected",
+ source_conversation_id=source.messages.conversation_id,
+ cutoff_index=0,
+ )
+ )
+ copy.destination = "new_attack"
+ copy.attack_result_id = None
+ copy.target_registry_name = None
+ unbound = await service.save_conversation_async(request=copy)
+ assert unbound.attack.target_unbound
+ assert unbound.messages.messages[0].message_pieces[0].original_value == "Copied history"
+ assert editor_target.prompt_sent == []
+ assert len(await sqlite_instance.get_attack_results_async()) == 2
+
+ async def test_fresh_drafts_bind_and_send_without_editable_history_async(
+ self, *, editor_target: MockPromptTarget
+ ) -> None:
+ editor_target.apply_capabilities(capabilities=TargetCapabilities())
+ service = AttackService()
+ request = draft()
+ request.messages = []
+ request.target_registry_name = "selected"
+ bound = await service.save_conversation_async(request=request)
+ assert not bound.attack.target_unbound
+ request.save_id = uuid.uuid4()
+ request.target_registry_name = None
+ unbound = await service.save_conversation_async(request=request)
+ await service.add_message_async(
+ attack_result_id=unbound.attack.attack_result_id,
+ request=AddMessageRequest(
+ target_registry_name="selected",
+ target_conversation_id=unbound.messages.conversation_id,
+ pieces=[ConversationPieceRequest(original_value="First live request")],
+ ),
+ )
+ assert editor_target.prompt_sent == ["First live request"]
+
+ async def test_repeated_edit_exit_reuses_unsent_conversation_async(self, sqlite_instance: SQLiteMemory) -> None:
+ service = AttackService()
+ original_request = draft()
+ saved = await service.save_conversation_async(request=original_request)
+ conversation_id = saved.messages.conversation_id
+ for value in ("First edit", "Second edit"):
+ request = SaveConversationRequest(
+ save_id=uuid.uuid4(),
+ destination="same_attack",
+ attack_result_id=saved.attack.attack_result_id,
+ source_attack_result_id=saved.attack.attack_result_id,
+ source_conversation_id=conversation_id,
+ operator="owner",
+ reuse_unsent_conversation=True,
+ expected_source_piece_ids=[
+ piece.id for message in saved.messages.messages for piece in message.message_pieces
+ ],
+ messages=[
+ ConversationMessageRequest(role="user", pieces=[ConversationPieceRequest(original_value=value)])
+ ],
+ )
+ saved = await service.save_conversation_async(request=request)
+ assert saved.messages.conversation_id == conversation_id
+ assert saved.messages.messages[0].message_pieces[0].original_value == value
+ assert len(await sqlite_instance.get_message_pieces_async(conversation_id=conversation_id)) == 1
+ assert await service.save_conversation_async(request=request) == saved
+ assert not saved.attack.related_conversation_ids
+ assert await service.save_conversation_async(request=original_request) == saved
+
+ async def test_explicit_save_still_forks_unsent_conversation_async(self, sqlite_instance: SQLiteMemory) -> None:
+ service = AttackService()
+ source = await service.save_conversation_async(request=draft())
+ request = draft(value="Explicit saved copy")
+ request.destination = "same_attack"
+ request.attack_result_id = source.attack.attack_result_id
+ request.source_attack_result_id = source.attack.attack_result_id
+ request.source_conversation_id = uuid.UUID(source.messages.conversation_id)
+ saved = await service.save_conversation_async(request=request)
+ assert saved.messages.conversation_id != source.messages.conversation_id
+ original = await sqlite_instance.get_message_pieces_async(conversation_id=source.messages.conversation_id)
+ assert original[0].original_value == "Original prompt"
+
+ @pytest.mark.parametrize("evidence", ["assistant", "request"])
+ async def test_edit_exit_preserves_sent_conversation_async(
+ self, *, sqlite_instance: SQLiteMemory, evidence: str
+ ) -> None:
+ service = AttackService()
+ source = await service.save_conversation_async(request=draft())
+ conversation_id = source.messages.conversation_id
+ await sqlite_instance.add_message_pieces_to_memory_async(
+ message_pieces=[
+ MessagePiece(
+ role="assistant" if evidence == "assistant" else "user",
+ original_value="Recorded target exchange",
+ conversation_id=conversation_id,
+ prompt_metadata={RequestTraceContext.REQUEST_METADATA_KEY: 1} if evidence == "request" else {},
+ ),
+ ]
+ )
+ pieces = await sqlite_instance.get_message_pieces_async(conversation_id=conversation_id)
+ request = draft(value="Edited history")
+ request.destination = "same_attack"
+ request.attack_result_id = source.attack.attack_result_id
+ request.source_attack_result_id = source.attack.attack_result_id
+ request.source_conversation_id = uuid.UUID(conversation_id)
+ request.reuse_unsent_conversation = True
+ request.expected_source_piece_ids = [piece.id for piece in pieces]
+ saved = await service.save_conversation_async(request=request)
+ assert saved.messages.conversation_id != conversation_id
+ assert list(await sqlite_instance.get_message_pieces_async(conversation_id=conversation_id)) == list(pieces)
+
+ async def test_edit_exit_rejects_stale_source_async(self, sqlite_instance: SQLiteMemory) -> None:
+ service = AttackService()
+ source = await service.save_conversation_async(request=draft())
+ request = draft(value="Stale edit")
+ request.destination = "same_attack"
+ request.attack_result_id = source.attack.attack_result_id
+ request.source_attack_result_id = source.attack.attack_result_id
+ request.source_conversation_id = uuid.UUID(source.messages.conversation_id)
+ request.reuse_unsent_conversation = True
+ request.expected_source_piece_ids = []
+ with pytest.raises(AttackStateConflictError, match="conversation changed"):
+ await service.save_conversation_async(request=request)
+ pieces = await sqlite_instance.get_message_pieces_async(conversation_id=source.messages.conversation_id)
+ assert pieces[0].original_value == "Original prompt"
+
+ async def test_edit_exit_detects_concurrent_message_before_commit_async(
+ self, sqlite_instance: SQLiteMemory
+ ) -> None:
+ service = AttackService()
+ source = await service.save_conversation_async(request=draft())
+ conversation_id = source.messages.conversation_id
+ pieces = await sqlite_instance.get_message_pieces_async(conversation_id=conversation_id)
+ request = draft(value="Concurrent edit")
+ request.destination = "same_attack"
+ request.attack_result_id = source.attack.attack_result_id
+ request.source_attack_result_id = source.attack.attack_result_id
+ request.source_conversation_id = uuid.UUID(conversation_id)
+ request.reuse_unsent_conversation = True
+ request.expected_source_piece_ids = [piece.id for piece in pieces]
+ prepare = service._prepare_message_pieces_async
+
+ async def concurrent_append_async(**kwargs: Any) -> list[MessagePiece]:
+ prepared = await prepare(**kwargs)
+ await sqlite_instance.add_message_pieces_to_memory_async(
+ message_pieces=[
+ MessagePiece(role="user", original_value="Newer message", conversation_id=conversation_id),
+ ]
+ )
+ return prepared
+
+ with patch.object(service, "_prepare_message_pieces_async", side_effect=concurrent_append_async):
+ with pytest.raises(AttackStateConflictError, match="history changed"):
+ await service.save_conversation_async(request=request)
+ pieces = await sqlite_instance.get_message_pieces_async(conversation_id=conversation_id)
+ assert {piece.original_value for piece in pieces} == {"Original prompt", "Newer message"}
+
@pytest.mark.parametrize("related", [False, True])
async def test_lookup_upgraded_history_without_attack_link_async(
self, *, sqlite_instance: SQLiteMemory, related: bool
@@ -675,7 +959,6 @@ async def test_provider_tool_extensions_round_trip_without_execution_async(
[
TargetCapabilities(),
TargetCapabilities(supports_multi_turn=True),
- TargetCapabilities(supports_editable_history=True),
],
)
async def test_save_requires_editable_history_async(
@@ -707,8 +990,9 @@ async def test_save_requires_each_tool_input_async(
await AttackService().save_conversation_async(request=request)
assert (await sqlite_instance.get_attack_results_async()) == []
+ @pytest.mark.parametrize("has_history", [False, True])
async def test_same_attack_checks_target_without_registry_name_async(
- self, *, editor_target: MockPromptTarget, sqlite_instance: SQLiteMemory
+ self, *, editor_target: MockPromptTarget, sqlite_instance: SQLiteMemory, has_history: bool
) -> None:
service = AttackService()
request = draft()
@@ -722,10 +1006,16 @@ async def test_same_attack_checks_target_without_registry_name_async(
objective=first.attack.objective,
expected_objective=first.attack.objective,
operator="owner",
+ messages=draft().messages if has_history else [],
)
- with pytest.raises(ValueError, match="editable history"):
- await service.save_conversation_async(request=request)
- assert (await sqlite_instance.get_conversation_metadata_async(conversation_id=str(request.save_id))) is None
+ if has_history:
+ with pytest.raises(ValueError, match="editable history"):
+ await service.save_conversation_async(request=request)
+ assert (await sqlite_instance.get_conversation_metadata_async(conversation_id=str(request.save_id))) is None
+ else:
+ saved = await service.save_conversation_async(request=request)
+ assert saved.messages.conversation_id == str(request.save_id)
+ assert saved.messages.messages == []
async def test_tool_removal_allows_text_target_save_async(self, editor_target: MockPromptTarget) -> None:
editor_target.apply_capabilities(
diff --git a/tests/unit/backend/test_conversation_save_route.py b/tests/unit/backend/test_conversation_save_route.py
index 9aec9ad406..ab40330198 100644
--- a/tests/unit/backend/test_conversation_save_route.py
+++ b/tests/unit/backend/test_conversation_save_route.py
@@ -15,6 +15,7 @@
from pyrit.backend.models.attacks import AddMessageResponse, AttackSummary, ConversationMessagesResponse
from pyrit.backend.routes.attacks import router
from pyrit.backend.services.attack_service import AttackService
+from pyrit.backend.services.manual_send_scheduler import ManualSendConflictError, ManualSendQueueFullError
from pyrit.memory.memory_interface import AttackStateConflictError
@@ -79,6 +80,8 @@ async def identity_async(request: Request, call_next: RequestResponseEndpoint) -
[
(PermissionError("Only the owner can save to this attack"), 403),
(AttackStateConflictError("History changed"), 409),
+ (ManualSendConflictError("A send owns this conversation"), 409),
+ (ManualSendQueueFullError("The manual-send queue is full"), 429),
(ValueError("The target does not support audio_path"), 422),
],
)
diff --git a/tests/unit/backend/test_history_replay.py b/tests/unit/backend/test_history_replay.py
new file mode 100644
index 0000000000..6167334094
--- /dev/null
+++ b/tests/unit/backend/test_history_replay.py
@@ -0,0 +1,87 @@
+# Copyright (c) Microsoft Corporation.
+# Licensed under the MIT license.
+
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+from fastapi import HTTPException
+
+from pyrit.backend.models.attacks import CreateAttackRequest
+from pyrit.backend.routes.attacks import create_attack
+from pyrit.backend.services.attack_service import AttackService
+from pyrit.backend.services.history_replay import HistoryReplayError, validate_history_replay
+from pyrit.models import Message, MessagePiece
+from pyrit.models.target.target_capabilities import TargetCapabilities
+from pyrit.prompt_target import PromptTarget, TargetConfiguration
+from unit.mocks import MockPromptTarget
+
+pytestmark = pytest.mark.usefixtures("patch_central_database")
+
+
+def _mock_target(capabilities: TargetCapabilities) -> MagicMock:
+ real_target = MockPromptTarget(custom_configuration=TargetConfiguration(capabilities=capabilities))
+ target = MagicMock(spec=PromptTarget)
+ target.capabilities = capabilities
+ target.validate_history_replay.side_effect = real_target.validate_history_replay
+ return target
+
+
+@pytest.mark.parametrize(
+ "error,status_code",
+ [(HistoryReplayError("Cannot replay this history"), 400), (ValueError("Target not found"), 404)],
+)
+async def test_creation_distinguishes_unsupported_history_from_missing_targets_async(
+ *, error: ValueError, status_code: int
+) -> None:
+ service = MagicMock(spec=AttackService)
+ service.create_attack_async = AsyncMock(side_effect=error)
+ with patch("pyrit.backend.routes.attacks.get_attack_service", return_value=service):
+ with pytest.raises(HTTPException) as raised:
+ await create_attack(request=CreateAttackRequest(target_registry_name="target"))
+ assert raised.value.status_code == status_code
+ assert raised.value.detail == str(error)
+
+
+@pytest.mark.parametrize("multi_turn,editable", [(False, False), (True, False), (True, True)])
+def test_empty_history_needs_no_replay_capability(*, multi_turn: bool, editable: bool) -> None:
+ target = _mock_target(TargetCapabilities(supports_multi_turn=multi_turn, supports_editable_history=editable))
+ validate_history_replay(target=target, messages=[])
+ target.validate_history.assert_called_once_with([])
+
+
+@pytest.mark.parametrize("role", ["user", "assistant", "simulated_assistant", "tool", "simulated_tool"])
+def test_history_requires_target_replay_support(role: str) -> None:
+ messages = [Message(message_pieces=[MessagePiece(role=role, original_value="History")])]
+ for multi_turn in (False, True):
+ target = _mock_target(TargetCapabilities(supports_multi_turn=multi_turn))
+ with pytest.raises(ValueError, match="does not support editable history"):
+ validate_history_replay(target=target, messages=messages)
+ target.validate_history.assert_not_called()
+ target = _mock_target(TargetCapabilities(supports_multi_turn=True, supports_editable_history=True))
+ validate_history_replay(target=target, messages=messages)
+ target.validate_history.assert_called_once_with(messages)
+
+
+def test_initial_system_setup_is_not_assistant_history() -> None:
+ messages = [
+ Message(message_pieces=[MessagePiece(role="system", original_value="System setup")]),
+ Message(message_pieces=[MessagePiece(role="developer", original_value="Developer setup")]),
+ ]
+ target = _mock_target(
+ TargetCapabilities(supports_multi_turn=True, supports_system_prompt=True, supports_editable_history=False)
+ )
+ validate_history_replay(target=target, messages=messages)
+ target.validate_history.assert_called_once_with(messages)
+ messages.append(Message(message_pieces=[MessagePiece(role="simulated_assistant", original_value="Reply")]))
+ with pytest.raises(ValueError, match="editable history"):
+ validate_history_replay(target=target, messages=messages)
+
+
+def test_replay_still_validates_native_input_and_tool_history() -> None:
+ target = _mock_target(TargetCapabilities(supports_multi_turn=True, supports_editable_history=True))
+ target.validate_history.side_effect = ValueError("Unsupported history piece")
+ with pytest.raises(ValueError, match="Unsupported history piece"):
+ validate_history_replay(
+ target=target,
+ messages=[Message(message_pieces=[MessagePiece(role="user", original_value="History")])],
+ )
diff --git a/tests/unit/backend/test_mappers.py b/tests/unit/backend/test_mappers.py
index 7726434682..ea37d30077 100644
--- a/tests/unit/backend/test_mappers.py
+++ b/tests/unit/backend/test_mappers.py
@@ -29,6 +29,7 @@
from pyrit.backend.mappers.target_mappers import target_object_to_instance
from pyrit.backend.models._media import build_filename, infer_mime_type
from pyrit.backend.models.attacks import AddMessageRequest, MessagePieceRequest, ScoreView
+from pyrit.message_normalizer import HistorySquashNormalizer
from pyrit.models import (
AtomicAttackIdentifier,
AttackOutcome,
@@ -40,7 +41,9 @@
Score,
)
from pyrit.models.conversation_stats import ConversationStats
-from pyrit.prompt_target import PromptTarget, TargetCapabilities
+from pyrit.prompt_target import PromptTarget, TargetCapabilities, TargetConfiguration, TextTarget, WebsocketTarget
+from pyrit.prompt_target.common.target_capabilities import CapabilityName
+from unit.mocks import MockPromptTarget
# ============================================================================
# Helpers
@@ -1486,6 +1489,42 @@ def test_blob_url_extension(self) -> None:
# ============================================================================
+@pytest.mark.usefixtures("patch_central_database")
+@pytest.mark.parametrize(
+ "mode", ["native", "unsupported", "editable_adapter", "multi_turn_adapter", "restore_callback"]
+)
+def test_target_instance_reports_effective_history_replay(mode: str) -> None:
+ if mode == "native":
+ target: PromptTarget = MockPromptTarget()
+ elif mode == "unsupported":
+ target = TextTarget()
+ elif mode == "restore_callback":
+ target = WebsocketTarget(
+ endpoint="ws://localhost:9999",
+ protocol_identifier="offline-replay",
+ initialization_strings=[],
+ response_parser=str,
+ message_builder=str,
+ conversation_restore_callback=AsyncMock(),
+ )
+ else:
+ capability = CapabilityName.EDITABLE_HISTORY if mode == "editable_adapter" else CapabilityName.MULTI_TURN
+ target = MockPromptTarget(
+ custom_configuration=TargetConfiguration(
+ capabilities=TargetCapabilities(supports_multi_turn=mode == "editable_adapter"),
+ normalizer_overrides={capability: HistorySquashNormalizer()},
+ )
+ )
+ with patch.object(target, "validate_history_replay", wraps=target.validate_history_replay) as validate:
+ result = target_object_to_instance("replay-target", target)
+ validate.assert_called_once()
+ assert result.supports_history_replay is (mode != "unsupported")
+ assert result.model_dump()["supports_history_replay"] is (mode != "unsupported")
+ assert result.capabilities == target.capabilities
+ if mode not in ("native", "unsupported"):
+ assert not result.capabilities.supports_editable_history
+
+
class TestTargetObjectToInstance:
"""Tests for target_object_to_instance function."""
diff --git a/tests/unit/backend/test_message_send_service.py b/tests/unit/backend/test_message_send_service.py
index a60f3757df..40dc447eb0 100644
--- a/tests/unit/backend/test_message_send_service.py
+++ b/tests/unit/backend/test_message_send_service.py
@@ -60,6 +60,7 @@
MessagePiece,
PromptDataType,
)
+from pyrit.models.target.target_capabilities import TargetCapabilities
from pyrit.prompt_normalizer import ConverterConfiguration, PromptNormalizer
from pyrit.prompt_target.common.target_capabilities import CapabilityName, TargetCapabilities
from pyrit.prompt_target.common.target_configuration import TargetConfiguration
@@ -2773,6 +2774,81 @@ def _submission(
@pytest.mark.timeout(20)
@pytest.mark.usefixtures("patch_central_database")
class TestAsyncMessageSend:
+ async def test_repetitions_cannot_bypass_original_capabilities_through_an_alias_async(
+ self,
+ *,
+ real_send_context: tuple[MessageSendService, AttackResult, MockPromptTarget, Base64Converter],
+ sqlite_instance: SQLiteMemory,
+ ) -> None:
+ service, attack, original, _ = real_send_context
+ alias = MockPromptTarget()
+ original.apply_capabilities(capabilities=TargetCapabilities(supports_multi_turn=True))
+ assert original.get_identifier().hash == alias.get_identifier().hash
+ await sqlite_instance.update_attack_result_by_id_async(
+ attack_result_id=attack.attack_result_id,
+ update_fields={"attack_metadata": {"target_registry_name": "origin"}},
+ )
+ await sqlite_instance.add_message_to_memory_async(
+ request=MessagePiece(
+ role="assistant", original_value="Existing response", conversation_id=attack.conversation_id
+ ).to_message()
+ )
+ target_service = MagicMock(spec=TargetService)
+ target_service.get_target_object.side_effect = lambda target_registry_name: (
+ original if target_registry_name == "origin" else alias
+ )
+ with patch("pyrit.backend.services.message_send_service.get_target_service", return_value=target_service):
+ with pytest.raises(ValueError, match="editable history"):
+ await service.submit_async(
+ attack_result_id=attack.attack_result_id,
+ request=_submission(conversation_id=attack.conversation_id, count=2),
+ )
+ assert original.prompt_sent == alias.prompt_sent == []
+ [stored] = await sqlite_instance.get_attack_results_async(attack_result_ids=[attack.attack_result_id])
+ assert stored.get_active_conversation_ids() == {attack.conversation_id}
+
+ @pytest.mark.parametrize("with_history,count", [(False, 2), (True, 2), (True, 1)])
+ async def test_repetitions_require_replay_but_live_continuation_does_not_async(
+ self,
+ *,
+ real_send_context: tuple[MessageSendService, AttackResult, MockPromptTarget, Base64Converter],
+ sqlite_instance: SQLiteMemory,
+ with_history: bool,
+ count: int,
+ ) -> None:
+ service, attack, target, _ = real_send_context
+ target.apply_capabilities(capabilities=TargetCapabilities(supports_multi_turn=True))
+ if with_history:
+ for role in ("user", "assistant"):
+ await sqlite_instance.add_message_to_memory_async(
+ request=MessagePiece(
+ role=role,
+ original_value="Previous turn",
+ conversation_id=attack.conversation_id,
+ ).to_message()
+ )
+ before = list(await sqlite_instance.get_message_pieces_async(conversation_id=attack.conversation_id))
+ if with_history and count > 1:
+ with pytest.raises(ValueError, match="editable history"):
+ await service.submit_async(
+ attack_result_id=attack.attack_result_id,
+ request=_submission(conversation_id=attack.conversation_id, count=count),
+ )
+ assert target.prompt_sent == []
+ assert (
+ list(await sqlite_instance.get_message_pieces_async(conversation_id=attack.conversation_id)) == before
+ )
+ else:
+ status = await service.submit_async(
+ attack_result_id=attack.attack_result_id,
+ request=_submission(conversation_id=attack.conversation_id, count=count),
+ )
+ status = await _settle_send_async(service=service, status=status)
+ assert status.state == MessageSendState.COMPLETED
+ assert target.prompt_sent == ["Hello"] * count
+ [stored] = await sqlite_instance.get_attack_results_async(attack_result_ids=[attack.attack_result_id])
+ assert len(stored.get_active_conversation_ids()) == (1 if with_history and count > 1 else count)
+
@pytest.mark.parametrize(
"terminal_state", [MessageSendState.COMPLETED, MessageSendState.FAILED, MessageSendState.INTERRUPTED]
)