From 4157cce392b74e5d54eeac96c5c17d00ead7d774 Mon Sep 17 00:00:00 2001 From: juliosuas Date: Tue, 10 Nov 2026 09:01:16 -0600 Subject: [PATCH 1/2] MAINT: Extract ChatWindow send workflow into a reducer (#2652) Final step of #2652, after #3310 (loading), #3369 (score, objective and export) and #3812 (copy and branch). The send workflow's rendered state (per-conversation send and scoring locks, send issues, failed-send recoveries, repeated-send progress and the undoable last send) now moves through an explicit reducer with typed actions in utils/chatSendState.ts. useChatSendState owns that reducer plus the synchronous locks the conversation loader reads; useChatSend owns the commands: optimistic messages, attachment and conversion capture, lazy attack creation, progress tracking, refresh after unknown delivery and preparation-draft restore. Its input is grouped by seam (route, readiness, request, composer, loader, callbacks), and ChatWindow passes the conversation loader through unchanged. No prop, UI, accessibility, request payload or navigation changes. Reducer transitions and the hook's regression cases (duplicate sends, two conversations sending independently, optimistic prompts on return to an in-flight conversation, first-send conversation creation, unknown delivery, pre-submission failures, converted pieces) have focused tests. Refs #2652 --- frontend/src/components/Chat/ChatWindow.tsx | 1075 ++----------------- frontend/src/hooks/useChatSend.test.ts | 376 +++++++ frontend/src/hooks/useChatSend.ts | 986 +++++++++++++++++ frontend/src/utils/chatSendState.test.ts | 234 ++++ frontend/src/utils/chatSendState.ts | 328 ++++++ 5 files changed, 2043 insertions(+), 956 deletions(-) create mode 100644 frontend/src/hooks/useChatSend.test.ts create mode 100644 frontend/src/hooks/useChatSend.ts create mode 100644 frontend/src/utils/chatSendState.test.ts create mode 100644 frontend/src/utils/chatSendState.ts diff --git a/frontend/src/components/Chat/ChatWindow.tsx b/frontend/src/components/Chat/ChatWindow.tsx index 7133d6f2ad..60dda1f69c 100644 --- a/frontend/src/components/Chat/ChatWindow.tsx +++ b/frontend/src/components/Chat/ChatWindow.tsx @@ -48,6 +48,9 @@ import { useConversationMessages } from '@/hooks/useConversationMessages' import { useAttackMutations } from '@/hooks/useAttackMutations' import { useConversationExport } from '@/hooks/useConversationExport' import { useConversationCopy } from '@/hooks/useConversationCopy' +import { useChatSend, useChatSendState } from '@/hooks/useChatSend' +import { PENDING_SEND_CONVERSATION_ID } from '@/utils/chatSendState' +import type { RepeatSendView } from '@/utils/chatSendState' import { conversationPieceSignature, preparePromptRestore } from '@/utils/promptRestore' import { useChatDraftHandoff } from '@/hooks/useChatDraftHandoff' import { @@ -61,20 +64,14 @@ import { import { resolveTargetReference, targetReference } from '@/utils/targetIdentity' import { mergeImportedHistory } from '@/utils/seedImport' import { resolveChatScorerReference } from '@/utils/scorerPresentation' -import type { PieceConversion } from './converterTypes' import { useChatConverters } from '@/hooks/useChatConverters' import { useMediaQuery } from '@/hooks/useMediaQuery' import { useRuntime } from '@/hooks/useRuntime' import { useUserPreferences } from '@/hooks/useUserPreferences' -import { buildTemperatureTarget } from '@/services/targetRegistry' import { NARROW_SCREEN_QUERY } from '@/styles/touchTargets' import { basenameFromValue, - applyConvertedValues, buildMediaUrl, - buildDraftPieceIds, - buildConverterInputs, - buildRequestConverterConfigurations, dataTypeToAttachmentKind, isPathDataType, withDraftIdentity, @@ -82,11 +79,7 @@ import { import type { ChatInputAreaHandle } from './ChatInputArea' import { attacksApi } from '../../services/api' import { toApiError } from '../../services/errors' -import { - buildMessagePieces, - backendMessageToOriginalDraft, - backendMessagesToFrontend, -} from '../../utils/messageMapper' +import { backendMessagesToFrontend } from '../../utils/messageMapper' import type { AddMessageResponse, AttackOutcome, @@ -95,7 +88,6 @@ import type { BackendMessage, BackendMessagePiece, BackendScore, - ChatSendOutcome, ChatConverterSnapshot, ChatDraftContent, ChatDraftContextState, @@ -104,15 +96,9 @@ import type { ConversationDraftPiece, ConverterInputPiece, ConverterPipelineStage, - CreateAttackRequest, CreateConversationRequest, Message, MessageAttachment, - MessageSendConversation, - MessageSendRequest, - MessageSendStatus, - MessageSendObservation, - MultiSendOptions, NewAttackContext, TargetInstance, TargetInfo, @@ -123,7 +109,6 @@ import { attackConversationRoutePath, scenarioRunRoutePath } from '../../utils/r import type { ViewName } from '../Sidebar/Navigation' import { CHAT_NOTICE_FADE_DURATION_MS, useChatWindowStyles } from './ChatWindow.styles' -const RETRYABLE_TARGET_RESPONSE_ERROR = 'processing' const CHAT_NOTICE_VISIBLE_DURATION_MS = 5_000 const SAVED_MESSAGE_PAGE_SIZE = 100 const SAVED_REFERENCE_PAGE_SIZE = 50 @@ -135,79 +120,6 @@ interface ChatInfoNotice { readonly fading: boolean } -interface RecoverableSendDraft { - history: Array> - conversationId: string - failedRequestTurnNumber: number - failedResponseTurnNumber: number - historyCutoffIndex: number - failedRequestMessageIndex: number - originalValue: string - textMetadata?: Record - attachments: MessageAttachment[] - conversions: Record - source: 'live' | 'persisted' - converterGeneration?: string - pipelines?: Record -} - -interface PendingSend { - readonly submissionId: string - readonly controller: AbortController - readonly draftRevision: number | undefined - readonly originalValue: string - readonly textMetadata?: Record - readonly attachments: MessageAttachment[] - readonly conversions: Record - readonly priorUserPieceIds: Set - readonly initialMessages: Message[] - readonly navigationRevision: number - readonly converterGeneration: string - readonly target: TargetReference - readonly chatScorerExplicit: boolean - chatScorerChoice?: RegisteredComponentReference | null - observation?: MessageSendObservation - readonly converterSnapshot?: ChatConverterSnapshot - readonly pipelines?: Record - attackResultId: string | null - conversationId: string - needsRefresh: boolean - responseReadId?: number - progress?: MessageSendStatus - repeatGroup?: RepeatSendGroup - preservedDraft?: Pick -} - -interface UndoableSend { - attackResultId: string - conversationId: string - historySignature: string - cutoffIndex: number - originalValue: string - textMetadata?: Record - attachments: MessageAttachment[] - converters: ChatConverterSnapshot - history: Array> -} - -interface RepeatSendGroup { - source: PendingSend - progress: MessageSendStatus - conversations: Map - read?: Promise -} - -interface RepeatSendView { - progress: MessageSendStatus - needsRefresh: boolean -} - -interface SendIssue { - description: string - blocking: boolean - draft?: PendingSend -} - /** The backend's scoring projection for a conversation's latest response. */ interface ConversationScoring { readonly conversationId: string @@ -235,79 +147,6 @@ function conversationScoringOf(conversationId: string, response: ConversationMes } } -function isSendFinished(progress: MessageSendConversation): boolean { - return ['completed', 'failed', 'interrupted'].includes(progress.state) -} - -function userPieceIds(response: ConversationMessagesResponse): Set { - return new Set(response.messages.filter((message) => message.role === 'user') - .flatMap((message) => message.message_pieces.map((piece) => piece.id))) -} - -function getRecoveryHistoryCutoff(messages: BackendMessage[], failedRequestTurnNumber: number): number { - let precedingUserTurnNumber: number | undefined - for (const message of messages) { - if (message.turn_number >= failedRequestTurnNumber) { - break - } - if (message.role === 'user') { - precedingUserTurnNumber = message.turn_number - } - for (const piece of message.message_pieces) { - if (piece.response_error === RETRYABLE_TARGET_RESPONSE_ERROR) { - // Later replies can depend on the failed turn, so retain only its preceding history. - return (precedingUserTurnNumber ?? message.turn_number) - 1 - } - } - } - return failedRequestTurnNumber - 1 -} - -function getPersistedProcessingRecovery( - conversationId: string, - response: ConversationMessagesResponse, -): RecoverableSendDraft | undefined { - const responseStatus = response.target_response_status - if (responseStatus?.response_error !== RETRYABLE_TARGET_RESPONSE_ERROR) { - return undefined - } - - const failedRequest = response.messages.find( - (message) => ( - message.role === 'user' - && message.turn_number === responseStatus.request_turn_number - ), - ) - const errorMessageIndex = response.messages.findIndex( - (message) => ( - message.role === 'assistant' - && message.turn_number === responseStatus.response_turn_number - ), - ) - if (!failedRequest || errorMessageIndex < 0) { - return undefined - } - - const originalDraft = backendMessageToOriginalDraft(failedRequest) - const textMetadata = failedRequest.message_pieces.filter((piece) => piece.original_value_data_type === 'text') - .reduce>((metadata: Record, piece) => ({ ...metadata, ...piece.prompt_metadata }), {}) - const cutoffIndex = getRecoveryHistoryCutoff(response.messages, responseStatus.request_turn_number) - return { - conversationId, - failedRequestTurnNumber: responseStatus.request_turn_number, - failedResponseTurnNumber: responseStatus.response_turn_number, - historyCutoffIndex: cutoffIndex, - history: response.messages.filter((message: BackendMessage) => message.turn_number <= cutoffIndex) - .map((message: BackendMessage) => ({ role: message.role })), - failedRequestMessageIndex: response.messages.indexOf(failedRequest), - originalValue: originalDraft.content, - textMetadata: Object.keys(textMetadata).length ? textMetadata : undefined, - attachments: (originalDraft.attachments ?? []).map((attachment) => ({ ...attachment })), - conversions: {}, - source: 'persisted', - } -} - interface ChatWindowProps { /** Shared layout slot; standalone chat renders its toolbar inline. */ toolbarContainer?: HTMLElement | null @@ -458,7 +297,6 @@ export default function ChatWindow({ ) const scorerSelectionReady = scorerDefaultsReady || draftScorer !== undefined const [scoringNotice, setScoringNotice] = useState<{ id: string; message: string; conversationId: string } | null>(null) - const [scoringConversations, setScoringConversations] = useState>(new Set()) const scoringNoticeId = scoringNotice?.id useEffect(() => { if (!scoringNoticeId) return @@ -503,9 +341,6 @@ export default function ChatWindow({ const [importSystemConflict, setImportSystemConflict] = useState(null) const [importSystemChoice, setImportSystemChoice] = useState<{ id: string; choice: 'destination' | 'imported' } | null>(null) const exitSaveRef = useRef | null>(null) - // Track sending state per conversation so parallel conversations can send independently - const [sendingConversations, setSendingConversations] = useState>(new Set()) - const isSending = activeConversationId ? sendingConversations.has(activeConversationId) : Boolean(sendingConversations.size) const [isPanelOpen, setIsPanelOpen] = useState(false) const isNarrowScreen = useMediaQuery(NARROW_SCREEN_QUERY) const [isConverterPanelOpen, setIsConverterPanelOpen] = useState(false) @@ -572,7 +407,6 @@ export default function ChatWindow({ const convertersRef = useRef(converters) useLayoutEffect(() => { convertersRef.current = converters }, [converters]) const { applied: activePieceConversions, restore: restoreConversions } = converters - const [undoableSend, setUndoableSend] = useState(null) const [isUndoingSend, setIsUndoingSend] = useState(false) const undoInFlight = useRef(false) @@ -598,7 +432,6 @@ export default function ChatWindow({ const ownsDraftRef = useRef(false) const preserveOnUnmountRef = useRef<(() => void) | null>(null) useEffect(() => () => { preserveOnUnmountRef.current?.() }, []) - const [recoverableSends, setRecoverableSends] = useState>({}) const [isRecoveringProcessingError, setIsRecoveringProcessingError] = useState(false) const [panelRefreshKey, setPanelRefreshKey] = useState(0) const inputBoxRef = useRef(null) @@ -608,80 +441,31 @@ export default function ChatWindow({ discardEditor() } }, [editDraft, viewedConversationId, attackResultId, discardEditor]) - // Synchronous ref tracking which conversations have an in-flight send. - const sendingConvIdsRef = useRef>(new Set()) - // Pending user messages per conversation that may not be stored server-side yet. - // Used to restore the user's input when switching back to an in-flight conversation. - const pendingUserMessagesRef = useRef>(new Map()) - const pendingSendsRef = useRef>(new Map()) - const loadedUserPieceIdsRef = useRef>>(new Map()) - const loadedBackendMessagesRef = useRef>(new Map()) - const isSendInFlight = useCallback( - (convId: string): boolean => sendingConvIdsRef.current.has(convId), - [], - ) + const sendState = useChatSendState({ activeConversationId, viewedConversationId, runtimeGeneration: runtime.generation }) + const { + isSending, recoverableSend, isSendInFlight, reconcileLoadedConversation, getPendingSend, + getLoadedBackendMessages, rememberBackendMessages, clearUndoableSend, clearRecoveries, + } = sendState + const undoableSend = sendState.state.undoable const handleConversationLoaded = useCallback(( convId: string, response: ConversationMessagesResponse, frontendMessages: Message[], ): Message[] => { setConversationScoring(conversationScoringOf(convId, response)) - const savedUserIds = userPieceIds(response) - loadedUserPieceIdsRef.current.set(convId, savedUserIds) - if (response.messages) { - loadedBackendMessagesRef.current.set(convId, response.messages) - } - const persistedRecovery = getPersistedProcessingRecovery(convId, response) - setRecoverableSends((currentRecoveries) => { - const currentRecovery = currentRecoveries[convId] - if (persistedRecovery) { - if ( - currentRecovery?.source === 'live' - && currentRecovery.failedRequestTurnNumber === persistedRecovery.failedRequestTurnNumber - && currentRecovery.failedResponseTurnNumber === persistedRecovery.failedResponseTurnNumber - ) { - return { - ...currentRecoveries, - [convId]: { - ...currentRecovery, - failedRequestMessageIndex: persistedRecovery.failedRequestMessageIndex, - historyCutoffIndex: persistedRecovery.historyCutoffIndex, - }, - } - } - return { ...currentRecoveries, [convId]: persistedRecovery } - } - if (!currentRecovery) { - return currentRecoveries - } - const nextRecoveries = { ...currentRecoveries } - delete nextRecoveries[convId] - return nextRecoveries - }) - // If this conversation has an in-flight send, append any pending user - // messages (that the server may not have stored yet) and a loading indicator. - if (sendingConvIdsRef.current.has(convId)) { - const operation = pendingSendsRef.current.get(convId) - const pending = pendingUserMessagesRef.current.get(convId) ?? [] - const requestStored = operation?.progress?.request_turn_number != null - ? response.messages.some((message: BackendMessage) => ( - message.role === 'user' && message.turn_number === operation.progress?.request_turn_number - )) - : operation && [...savedUserIds].some((id) => !operation.priorUserPieceIds.has(id)) - if (!operation?.progress || !isSendFinished(operation.progress)) { - if (!requestStored) { frontendMessages.push(...pending) } - frontendMessages.push({ - role: 'assistant', - content: '...', - timestamp: new Date().toISOString(), - isLoading: true, - }) - } - } - return frontendMessages - }, []) + return reconcileLoadedConversation(convId, response, frontendMessages) + }, [reconcileLoadedConversation]) + const conversationLoad = useConversationMessages({ + attackResultId, + conversationId, + activeConversationId, + findingEvidenceId, + messagePageSize: executionReadOnly ? SAVED_MESSAGE_PAGE_SIZE : undefined, + sendingConversations: sendState.state.sending, + isSendInFlight, + onConversationLoaded: handleConversationLoaded, + }) const { messages, setMessages, - loadedConversationId, isLoadingMessages, awaitingConversationLoad, conversationLoadIssue, @@ -698,38 +482,10 @@ export default function ChatWindow({ markConversationLoaded, resetConversationMessages, invalidateConversationLoads, - claimConversationRead, - isLatestConversationRead, getViewedConversationId, - setViewedConversationId, - getLoadedConversationId, - } = useConversationMessages({ - attackResultId, - conversationId, - activeConversationId, - findingEvidenceId, - messagePageSize: executionReadOnly ? SAVED_MESSAGE_PAGE_SIZE : undefined, - sendingConversations, - isSendInFlight, - onConversationLoaded: handleConversationLoaded, - }) + } = conversationLoad const incompleteTranscriptReason = isTranscriptIncomplete ? INCOMPLETE_TRANSCRIPT_REASON : undefined const loadedPieceSummary = `${loadedPieceCount} message ${loadedPieceCount === 1 ? 'piece' : 'pieces'} loaded.` - const savedRecovery = viewedConversationId - ? recoverableSends[viewedConversationId] - : undefined - const recoverableSend = useMemo(() => ( - savedRecovery?.converterGeneration !== undefined && savedRecovery.converterGeneration !== runtime.generation - ? { - ...savedRecovery, conversions: {}, pipelines: undefined, source: 'persisted', - } - : savedRecovery - ), [savedRecovery, runtime.generation]) - const [sendIssues, setSendIssues] = useState>({}) - const sendIssueConversationId = attackResultId ? viewedConversationId : loadedConversationId ?? viewedConversationId - const sendIssue = sendIssues[sendIssueConversationId ?? '__pending__'] - const [repeatSends, setRepeatSends] = useState([]) - const latestSendRef = useRef(null) const viewedAttackRef = useRef(attackResultId) const navigationRevisionRef = useRef(0) @@ -738,16 +494,6 @@ export default function ChatWindow({ navigationRevisionRef.current += 1 }, [attackResultId, activeConversationId, conversationId]) - useEffect(() => { - const pendingSends = pendingSendsRef.current - return () => { - for (const operation of pendingSends.values()) { - operation.controller.abort() - } - pendingSends.clear() - } - }, []) - const handleMarkdownChange = useCallback(( _event: ChangeEvent, data: SwitchOnChangeData, @@ -896,7 +642,7 @@ export default function ChatWindow({ const reset = !isRetainedComposer && !isResolvingConversation if (reset) { preserveOnUnmountRef.current?.() - const operation = pendingSendsRef.current.get(composerIdentity.conversationId ?? '__pending__') + const operation = getPendingSend(composerIdentity.conversationId ?? PENDING_SEND_CONVERSATION_ID) if (operation && inputBoxRef.current?.getDraftRevision() === operation.draftRevision) { operation.preservedDraft = draftHandoff.getPreservedDraft( composerIdentity.attackId, composerIdentity.conversationId, @@ -906,7 +652,7 @@ export default function ChatWindow({ activateComposerIdentity(reset) }, [ composerIdentityMatches, composerIdentity, draftAttackId, draftConversationId, draftHandoff, - activateComposerIdentity, + activateComposerIdentity, getPendingSend, ]) useLayoutEffect(() => { if (!composerIdentityMatches) return @@ -961,7 +707,7 @@ export default function ChatWindow({ if (attackResultId !== prevAttackResultId) { setPrevAttackResultId(attackResultId) if (!attackResultId) { - setRecoverableSends({}) + clearRecoveries() resetConversationMessages() setSystemPrompt('') resetPendingObjective() @@ -1063,7 +809,7 @@ export default function ChatWindow({ let existingTurns: ConversationDraftMessage[] = [] let backendMsgs: BackendMessage[] = [] if (pending.conversation && pending.destinationType === 'current_conversation' && draftConversationId && draftAttackId) { - backendMsgs = loadedBackendMessagesRef.current.get(draftConversationId) ?? [] + backendMsgs = getLoadedBackendMessages(draftConversationId) ?? [] if (backendMsgs.length === 0) { try { const res = await attacksApi.getMessages(draftAttackId, draftConversationId) @@ -1127,7 +873,7 @@ export default function ChatWindow({ } if (pending.conversation && pending.destinationType === 'current_conversation' && draftConversationId && draftAttackId) { - if (backendMsgs.length > 0) loadedBackendMessagesRef.current.set(draftConversationId, backendMsgs) + if (backendMsgs.length > 0) rememberBackendMessages(draftConversationId, backendMsgs) if (backendMsgs.some((message: BackendMessage) => message.role === 'assistant' || message.role === 'tool' || message.message_pieces.some((piece: BackendMessagePiece) => piece.prompt_metadata?.pyrit_request_trace || piece.prompt_metadata?.pyrit_target_request))) { @@ -1245,6 +991,7 @@ export default function ChatWindow({ isDraftDestinationReady, composerIdentityMatches, matchingPreservedDraft, isActiveDraftDirty, runtime.ready, runtime.generation, restoreComposerDraft, restoreConverterSnapshot, restoreConversions, activeTarget, currentObjective, editor, labels, setEditorNotice, systemPrompt, availableTargets, importSystemChoice, + getLoadedBackendMessages, rememberBackendMessages, ]) // Handle conversation selection from the panel @@ -1264,662 +1011,88 @@ export default function ChatWindow({ } }, [attackResultId, activeConversationId, getViewedConversationId, isNarrowScreen, onSelectConversation, loadConversation, requestForcedLoad]) - const isCurrentSend = (operation: PendingSend): boolean => ( - !operation.controller.signal.aborted - && pendingSendsRef.current.get(operation.conversationId) === operation - ) - const checkSendPreparation = (operation: PendingSend, requireDefaults: boolean): void => { - const current = launchStateRef.current - if (current.generation !== operation.converterGeneration || !current.ready - || (requireDefaults && (!current.defaultsReady || !current.scorerSelectionReady))) { - throw new Error('Runtime or default labels changed while preparing this message. Your draft is preserved. Retry after default labels finish loading.') - } - } - const isViewingSend = (operation: PendingSend): boolean => ( - viewedAttackRef.current === operation.attackResultId - && ( - getViewedConversationId() === operation.conversationId - || (getViewedConversationId() === null && operation.conversationId === '__pending__' - && navigationRevisionRef.current === operation.navigationRevision) - ) - ) - const setSendIssue = (conversation: string, issue?: SendIssue): void => { - setSendIssues((previous) => { - const next = { ...previous } - if (issue) { next[conversation] = issue } else { delete next[conversation] } - return next - }) - } - const finishTracking = (operation: PendingSend): void => { - if (!isCurrentSend(operation) || !sendingConvIdsRef.current.has(operation.conversationId)) { return } - if (operation.responseReadId === undefined - || isLatestConversationRead(operation.conversationId, operation.responseReadId)) { - invalidateConversationLoads(operation.conversationId) - } - if (isViewingSend(operation)) { - setMessages((previous) => previous.filter((message) => !message.isLoading)) - } - sendingConvIdsRef.current.delete(operation.conversationId) - const finishedConversationId = operation.conversationId - setScoringConversations((previous) => { - const next = new Set(previous) - next.delete(finishedConversationId) - return next - }) - pendingUserMessagesRef.current.delete(operation.conversationId) - setSendingConversations((previous) => { - const next = new Set(previous) - next.delete(operation.conversationId) - return next - }) - setPanelRefreshKey((key) => key + 1) - } - const retireSend = (operation: PendingSend): void => { - if (isCurrentSend(operation) && !operation.needsRefresh - && operation.progress?.failure_stage !== 'preparation') { - pendingSendsRef.current.delete(operation.conversationId) - } - } - const stopSendSpinner = (operation: PendingSend): void => { - if (!isViewingSend(operation)) { return } - const hasMatchingTranscript = getLoadedConversationId() === operation.conversationId - const pending = pendingUserMessagesRef.current.get(operation.conversationId) ?? [] - setMessages((previous) => (hasMatchingTranscript - ? previous - : [...operation.initialMessages, ...pending] - ).filter((message) => !message.isLoading)) - markConversationLoaded(operation.conversationId) - } - - const applySendResponse = ( - operation: PendingSend, response: AddMessageResponse, isLatestRead: boolean, - ): ChatSendOutcome => { - const effectiveConvId = operation.conversationId - const targetResponseStatus = response.messages.target_response_status - const recovery = operation.progress - && !['interrupted', 'finalization'].includes(operation.progress.failure_stage ?? '') - ? getPersistedProcessingRecovery(effectiveConvId, response.messages) - : undefined - const processingFailure = recovery?.failedRequestTurnNumber === operation.progress?.request_turn_number - && recovery !== undefined - const status: ChatSendOutcome['status'] = operation.progress?.failure_stage === 'preparation' - || processingFailure - ? 'retryable_failure' - : operation.progress?.failure_stage - || (targetResponseStatus?.response_error && targetResponseStatus.response_error !== 'none') - ? 'non_retryable_failure' - : 'sent' - const backendMessages = backendMessagesToFrontend(response.messages.messages) - const recoveredDraft: RecoverableSendDraft | undefined = processingFailure && recovery ? { - ...recovery, - originalValue: operation.originalValue, - textMetadata: operation.textMetadata, - attachments: operation.attachments, - conversions: operation.conversions, - converterGeneration: operation.converterGeneration, - pipelines: operation.pipelines, - source: 'live', - } : recovery - if (isLatestRead) { - loadedUserPieceIdsRef.current.set(effectiveConvId, userPieceIds(response.messages)) - if (response.messages?.messages) { - loadedBackendMessagesRef.current.set(effectiveConvId, response.messages.messages) - } - setRecoverableSends((currentRecoveries) => { - const next = { ...currentRecoveries } - if (recoveredDraft) { next[effectiveConvId] = recoveredDraft } else { delete next[effectiveConvId] } - return next - }) - } - if (isLatestRead && isViewingSend(operation)) { - invalidateConversationLoads(effectiveConvId) - setMessages(backendMessages) - setConversationScoring(conversationScoringOf(effectiveConvId, response.messages)) - markConversationLoaded(effectiveConvId) - onAttackChange?.(response.attack) - const scoringError = operation.progress?.scoring_error - const result = response.messages.scoring_failure - if (scoringError && result && result.conversation_id === effectiveConvId) { - setScoringNotice({ - id: operation.submissionId, conversationId: effectiveConvId, - message: 'A scoring error occurred. Open the score above for details.', - }) - } - const lastMessage = response.messages.messages[response.messages.messages.length - 1] - if ( - status === 'sent' && operation.progress?.state === 'completed' - && latestSendRef.current === operation.submissionId - && !operation.repeatGroup && operation.converterSnapshot && operation.attackResultId - && typeof targetResponseStatus?.request_turn_number === 'number' - && targetResponseStatus.request_turn_number === operation.progress.request_turn_number - && lastMessage?.role === 'assistant' && lastMessage.message_pieces.length > 0 - ) { - setUndoableSend({ - attackResultId: operation.attackResultId, - conversationId: effectiveConvId, - historySignature: conversationPieceSignature(response.messages), - cutoffIndex: targetResponseStatus.request_turn_number - 1, - originalValue: operation.originalValue, - textMetadata: operation.textMetadata, - attachments: operation.attachments, - converters: operation.converterSnapshot, - history: response.messages.messages.filter( - (message: BackendMessage) => message.turn_number < targetResponseStatus.request_turn_number, - ).map((message: BackendMessage) => ({ role: message.role })), - }) - } - } - return { - status, - clearDraft: status !== 'retryable_failure' && latestSendRef.current === operation.submissionId - && (!operation.repeatGroup || operation.repeatGroup.source === operation), - } - } - - const updateRepeatView = (group: RepeatSendGroup): void => { - if (group.source.controller.signal.aborted) return - const needsRefresh = [...group.conversations.values()].some( - (operation: PendingSend) => isCurrentSend(operation) && operation.needsRefresh, - ) - setRepeatSends((previous: RepeatSendView[]) => previous.map((view: RepeatSendView) => ( - view.progress.send_id === group.progress.send_id ? { progress: group.progress, needsRefresh } : view - ))) - } - - const receiveRepeatProgress = (group: RepeatSendGroup, progress: MessageSendStatus): void => { - if (group.source.controller.signal.aborted) return - group.progress = progress - let addedConversations = false - for (const conversation of progress.conversations ?? []) { - if (group.conversations.has(conversation.conversation_id)) continue - addedConversations = true - const operation: PendingSend = { - ...group.source, - conversationId: conversation.conversation_id, - draftRevision: undefined, - responseReadId: undefined, - needsRefresh: false, - progress: { ...progress, ...conversation }, - } - group.conversations.set(operation.conversationId, operation) - // A finished sibling may already have a newer send by the time this snapshot arrives. - if (pendingSendsRef.current.has(operation.conversationId)) continue - pendingSendsRef.current.set(operation.conversationId, operation) - sendingConvIdsRef.current.add(operation.conversationId) - const pending = pendingUserMessagesRef.current.get(group.source.conversationId) - if (pending) pendingUserMessagesRef.current.set(operation.conversationId, [...pending]) - setSendingConversations((previous: Set) => new Set(previous).add(operation.conversationId)) - void trackSend(operation).then(() => { retireSend(operation) }) - } - if (addedConversations) setPanelRefreshKey((key: number) => key + 1) - updateRepeatView(group) - } - - const readSendProgress = async (operation: PendingSend): Promise => { - const { attackResultId: sendAttackId, progress: previousProgress } = operation - if (!sendAttackId || !previousProgress) throw new Error('The send has no progress handle.') - const group = operation.repeatGroup - const read = (): Promise => operation.observation - ? operation.observation.readProgress(operation.needsRefresh) - : attacksApi.getMessageSend(sendAttackId, previousProgress.send_id, operation.controller.signal) - if (!group) return read() - // Every conversation uses the same in-flight GET, but settles its own evidence reads and ownership. - group.read ??= read().then((progress: MessageSendStatus) => { - receiveRepeatProgress(group, progress) - return progress - }).finally(() => { group.read = undefined }) - const progress = await group.read - const conversation = progress.conversations?.find( - (candidate: MessageSendConversation) => candidate.conversation_id === operation.conversationId, - ) - return conversation ? { ...progress, ...conversation } : progress - } - - const trackSend = async (operation: PendingSend): Promise => { - try { - if (!operation.attackResultId) { throw new Error('The send has no attack ID.') } - while (operation.progress) { - const repeatProgress = operation.repeatGroup?.progress - // The last conversation can release ownership before the operation publishes its final summary. - const awaitingSummary = repeatProgress && !isSendFinished(repeatProgress) - && repeatProgress.conversations?.length && repeatProgress.conversations.every(isSendFinished) - if (isSendFinished(operation.progress) && !awaitingSummary) break - let progress: MessageSendStatus | undefined - try { - progress = await readSendProgress(operation) - } catch (err) { - if (toApiError(err).status !== 404) { throw err } - // Lost handles permit evidence reads, never a new submission or a claim of delivery. - } - if (!isCurrentSend(operation)) { return { status: 'non_retryable_failure', clearDraft: false } } - operation.progress = progress - const scoringConversationId = operation.conversationId - const isScoring = progress?.is_scoring === true - setScoringConversations((previous) => { - const next = new Set(previous) - if (isScoring) next.add(scoringConversationId) - else next.delete(scoringConversationId) - return next - }) - } - operation.responseReadId = claimConversationRead(operation.conversationId) - const [attack, conversation] = await Promise.all([ - operation.observation?.readAttack(operation.needsRefresh) ?? attacksApi.getAttack(operation.attackResultId), - attacksApi.getMessages(operation.attackResultId, operation.conversationId), - ]) - if (!isCurrentSend(operation)) { return { status: 'non_retryable_failure', clearDraft: false } } - const isLatestRead = isLatestConversationRead(operation.conversationId, operation.responseReadId) - const outcome = applySendResponse(operation, { attack, messages: conversation }, isLatestRead) - const progress = operation.progress - const hasProcessingRecovery = conversation.target_response_status?.response_error === 'processing' - && conversation.target_response_status.request_turn_number === progress?.request_turn_number - if (!progress || progress.failure_stage === 'interrupted' || progress.failure_stage === 'finalization' - || (progress.failure_stage === 'sending' && !hasProcessingRecovery)) { - operation.needsRefresh = true - setSendIssue(operation.conversationId, { - description: `${progress?.error ?? 'Send acceptance is unknown.'} Refresh saved messages only; do not resend.`, - blocking: true, - }) - return { status: 'non_retryable_failure', clearDraft: false } - } - setSendIssue(operation.conversationId, progress.failure_stage === 'preparation' - ? { - description: progress.error ?? 'Message preparation failed before target dispatch.', - blocking: false, - draft: operation, - } - : undefined) - operation.needsRefresh = false - if (outcome.status !== 'retryable_failure' && operation.preservedDraft) { - const preserved = operation.preservedDraft - draftHandoff.clearPreservedDraft( - preserved.sequence, preserved.originatingAttackId, preserved.originatingConversationId, - ) - operation.preservedDraft = undefined - } - return outcome - } catch (err) { - if (isCurrentSend(operation)) { - operation.needsRefresh = true - const error = toApiError(err) - const detail = error.isTimeout ? 'The read timed out.' - : error.isNetworkError ? 'The backend could not be reached.' : error.detail - const phase = operation.progress && isSendFinished(operation.progress) - ? `${operation.progress.error ?? 'Sending finished.'} Saved messages or attack details could not be loaded.` - : 'Send status is unavailable. Delivery may be unknown.' - setSendIssue(operation.conversationId, { - description: `${phase} ${detail} Refresh only; do not resend.`, - blocking: true, - }) - stopSendSpinner(operation) - } - return { status: 'non_retryable_failure', clearDraft: false } - } finally { - finishTracking(operation) - if (operation.repeatGroup) updateRepeatView(operation.repeatGroup) - } - } - - const refreshSend = async (conversationIdToRefresh = sendIssueConversationId ?? '__pending__'): Promise => { - const operation = pendingSendsRef.current.get(conversationIdToRefresh) - if (!operation || sendingConvIdsRef.current.has(operation.conversationId)) { return } - sendingConvIdsRef.current.add(operation.conversationId) - setSendingConversations((previous) => new Set(previous).add(operation.conversationId)) - const outcome = await trackSend(operation) - if (isCurrentSend(operation) && isViewingSend(operation) && outcome.clearDraft - && inputBoxRef.current - && inputBoxRef.current?.getDraftRevision() === operation.draftRevision) { - lastTextRef.current = '' - lastAttachmentsSignatureRef.current = '' - inputBoxRef.current.restoreDraft('', []) - setChatInputText('') - setDraftAttachments([]) - converters.clearAll() - draftHandoff.clearPreservedDraft(undefined, draftAttackId, draftConversationId) - } - retireSend(operation) - } - - const restorePreparationDraft = (): void => { - const operation = sendIssue?.draft - if (!operation || !isCurrentSend(operation) || !isViewingSend(operation)) return - const sameGeneration = operation.converterGeneration === runtime.generation - const attachments = operation.attachments.map(withDraftIdentity) - lastTextRef.current = operation.originalValue - lastAttachmentsSignatureRef.current = computeAttachmentSignature(attachments) - setChatInputText(operation.originalValue) - setDraftAttachments(attachments) - inputBoxRef.current?.restoreDraft(operation.originalValue, attachments, operation.textMetadata) - restoreConversions( - operation.originalValue, attachments, sameGeneration ? operation.conversions : {}, - sameGeneration ? operation.pipelines : undefined, - ) - if (!sameGeneration) setSendIssue(operation.conversationId, { - ...sendIssue, - description: 'Prompt restored after the runtime changed. Review converters before sending.', - }) - } - - const handleSend = async ( - originalValue: string, - convertedValue: string | undefined, - attachments: MessageAttachment[], - options?: MultiSendOptions, - ): Promise => { - if ( - !runtime.ready - || (!attackResultId && (!defaultsReady || !scorerSelectionReady)) - || !activeTarget - || editDraft !== null - || isLoadingAttack - || isLoadingMessages - || awaitingConversationLoad - || isMutationLocked - || sendIssue?.blocking - || isUndoingSend - || unboundHistoryError - ) { - return { status: 'retryable_failure', clearDraft: false } - } - - const initialSendConvId = activeConversationId ?? conversationId ?? '__pending__' - if (sendingConvIdsRef.current.has(initialSendConvId)) { - return { status: 'retryable_failure', clearDraft: false } - } - - setEditorNotice(null) - setUndoableSend(null) - invalidateConversationLoads(initialSendConvId) - setRecoverableSends((currentRecoveries) => { - if (!currentRecoveries[initialSendConvId]) { - return currentRecoveries - } - const nextRecoveries = { ...currentRecoveries } - delete nextRecoveries[initialSendConvId] - return nextRecoveries - }) - - // Capture all piece conversions upfront before any async work or state clears - const conversions = { ...activePieceConversions } - const count = options?.count ?? 1 - const converterMode = options?.requestConverterMode ?? 'shared' - const pipelines = count > 1 ? { ...converters.pipelines } : undefined - const operation: PendingSend = { - submissionId: generateClientId(), - controller: new AbortController(), - draftRevision: inputBoxRef.current?.getDraftRevision(), - originalValue, - textMetadata: inputBoxRef.current?.getTextMetadata(), - attachments: attachments.map((attachment) => ({ ...attachment })), - conversions, - priorUserPieceIds: new Set(loadedUserPieceIdsRef.current.get(initialSendConvId)), - initialMessages: [...messages], - navigationRevision: navigationRevisionRef.current, - converterGeneration: runtime.generation, - target: targetReference(activeTarget), - chatScorerExplicit: draftScorer !== undefined, - chatScorerChoice: attackResultId ? chatScorer : draftScorer === undefined ? defaultChatScorer : draftScorer, - converterSnapshot: count === 1 ? converters.snapshot() : undefined, - pipelines, + const unboundHistoryError = targetResolutionStatus === 'unbound' && activeTarget + ? historyReplayDisabledReason(activeTarget, messages) : undefined + const { + sendIssue, + repeatSends, + send: handleSend, + refreshSend, + refreshRepeatSend, + dismissRepeatSend, + restorePreparationDraft, + } = useChatSend({ + tracking: sendState, + route: { attackResultId, - conversationId: initialSendConvId, - needsRefresh: false, - } - pendingSendsRef.current.set(initialSendConvId, operation) - latestSendRef.current = operation.submissionId - setSendIssue(initialSendConvId) - const submittedNavigationRevision = navigationRevisionRef.current - let submissionAttempted = false - const textConversion = conversions['text'] - const isTextTextConversion = textConversion?.convertedDataType === 'text' - const isTextFileConversion = Boolean(textConversion) && !isTextTextConversion - - // Mark synchronously so the useEffect guard sees it immediately - sendingConvIdsRef.current.add(initialSendConvId) - - // When a text→text converter is active, show the converted text as the bubble's - // primary content. When a text→file converter is active, keep the typed text - // as content and synthesize a file attachment so the bubble shows both. - const displayContent = isTextTextConversion && convertedValue != null ? convertedValue : originalValue - const optimisticAttachments: MessageAttachment[] = [...attachments] - if (isTextFileConversion && textConversion) { - const url = buildMediaUrl(textConversion.convertedValue) - const kind = dataTypeToAttachmentKind(textConversion.convertedDataType) - optimisticAttachments.push({ - type: kind, - name: basenameFromValue(textConversion.convertedValue, `output.${kind}`), - url, - mimeType: 'application/octet-stream', - }) - } - - // Add user message with attachments for display - const userMessage: Message = { - role: 'user', - content: displayContent, - timestamp: new Date().toISOString(), - attachments: optimisticAttachments.length > 0 ? optimisticAttachments : undefined, - originalContent: isTextTextConversion ? originalValue : undefined, - } - setMessages(prev => [...prev, userMessage]) - - // Track as pending so switching back before the server stores it still shows it - const pending = pendingUserMessagesRef.current.get(initialSendConvId) ?? [] - pending.push(userMessage) - pendingUserMessagesRef.current.set(initialSendConvId, pending) - - // Show loading indicator - setSendingConversations(prev => new Set(prev).add(initialSendConvId)) - const loadingMessage: Message = { - role: 'assistant', - content: '...', - timestamp: new Date().toISOString(), - isLoading: true, - } - setMessages(prev => [...prev, loadingMessage]) - - try { - // Build message pieces from text + attachments — always use original text - const pieceIds = buildDraftPieceIds(originalValue, attachments, conversions) - const originalPieces = await buildMessagePieces(originalValue, attachments, operation.textMetadata) - if (textConversion && !originalValue.trim()) { - originalPieces.unshift({ data_type: 'text', original_value: originalValue }) - } - const pieces = applyConvertedValues( - originalPieces, - pieceIds, - conversions, - ) - const requestConfigurations = count > 1 && converterMode === 'per_branch' ? buildRequestConverterConfigurations( - buildConverterInputs(originalValue, attachments), pieceIds, pipelines ?? {}, conversions, - ) : [] - if (!isCurrentSend(operation)) { return { status: 'non_retryable_failure', clearDraft: false } } - - // Create attack lazily on first message - let currentAttackResultId = attackResultId - let currentConversationId = conversationId - let currentActiveConversationId = activeConversationId - if (!currentAttackResultId) { - checkSendPreparation(operation, true) - let selectedTarget = activeTarget - if (temperature.trim()) { - selectedTarget = await buildTemperatureTarget(activeTarget, Number(temperature)) - if (!isCurrentSend(operation)) { return { status: 'non_retryable_failure', clearDraft: false } } - } - checkSendPreparation(operation, true) - const createRequest: CreateAttackRequest = { - target_registry_name: activeTarget.target_registry_name, - ...(selectedTarget.binding ? { target_binding: selectedTarget.binding } : {}), - objective: pendingObjective || undefined, - // TODO(PyRIT 1.4): Pass only dedicated attribution after legacy label aliases are removed. - // The create-attack API normalizes these aliases through _AttackAttributionInput. - labels, - operation_id: operationId ?? undefined, - system_prompt: supportsSystemPrompt ? systemPrompt.trim() || undefined : undefined, - ...(draftScorer !== undefined ? { chat_scorer: draftScorer } - : defaultChatScorer === null || pendingObjective.trim() && defaultChatScorer - ? { chat_scorer: defaultChatScorer } : {}), - } - const createResponse = await attacksApi.createAttack(createRequest) - operation.chatScorerChoice = createRequest.chat_scorer - if (!isCurrentSend(operation)) { return { status: 'non_retryable_failure', clearDraft: false } } - currentAttackResultId = createResponse.attack_result_id - currentConversationId = createResponse.conversation_id - currentActiveConversationId = currentConversationId - // Mark new ID in synchronous ref *before* triggering the state - // update that changes activeConversationId (and fires the useEffect) - sendingConvIdsRef.current.delete('__pending__') - sendingConvIdsRef.current.add(currentConversationId!) - // Move pending messages to the real conversation ID - const pendingMsgs = pendingUserMessagesRef.current.get('__pending__') - if (pendingMsgs) { - pendingUserMessagesRef.current.delete('__pending__') - pendingUserMessagesRef.current.set(currentConversationId!, pendingMsgs) - } - pendingSendsRef.current.delete('__pending__') - operation.attackResultId = currentAttackResultId - operation.conversationId = currentConversationId - pendingSendsRef.current.set(currentConversationId, operation) - if (navigationRevisionRef.current === submittedNavigationRevision) { - retainedComposerIdentityRef.current = JSON.stringify([currentAttackResultId, currentConversationId]) - if (selectedTarget.binding) { - onConversationCreated(currentAttackResultId, currentConversationId, pendingObjective || undefined, selectedTarget) - } else { - onConversationCreated(currentAttackResultId, currentConversationId, pendingObjective || undefined) - } - viewedAttackRef.current = currentAttackResultId - setViewedConversationId(currentConversationId) - } - // Update sending tracker to use real ID instead of __pending__ - setSendingConversations(prev => { - const next = new Set(prev) - next.delete('__pending__') - next.add(currentConversationId!) - return next - }) - } - - // The effective conversation we're sending for - const effectiveConvId = currentActiveConversationId ?? currentConversationId - - // Send message to target - if (!currentAttackResultId || !effectiveConvId) { - throw new Error('Message send is missing an attack or conversation ID.') - } - const addMessageRequest: MessageSendRequest = { - role: 'user', - pieces, - send: true, - target_registry_name: activeTarget.target_registry_name, - target_conversation_id: effectiveConvId, - submission_id: operation.submissionId, - ...(count > 1 ? { - count, - request_converter_mode: converterMode, - } : {}), - ...(requestConfigurations.length ? { request_converter_configurations: requestConfigurations } : {}), - } - if (targetResolutionStatus === 'unbound' && temperature.trim()) { - const selectedTarget = await buildTemperatureTarget(activeTarget, Number(temperature)) - if (!isCurrentSend(operation)) { return { status: 'non_retryable_failure', clearDraft: false } } - addMessageRequest.target_binding = selectedTarget.binding - } - checkSendPreparation(operation, false) - submissionAttempted = true - const acceptance = attacksApi.submitMessageSend(currentAttackResultId, addMessageRequest) - operation.observation = observeChatSend( - currentAttackResultId, acceptance, operation.target, - operation.chatScorerChoice, operation.chatScorerExplicit, availableScorers, - ) - operation.progress = await acceptance - if (!isCurrentSend(operation)) { return { status: 'non_retryable_failure', clearDraft: false } } - if (count > 1) { - const group: RepeatSendGroup = { - source: operation, - progress: operation.progress, - conversations: new Map([[operation.conversationId, operation]]), - } - operation.repeatGroup = group - setRepeatSends((previous: RepeatSendView[]) => [ - ...previous.filter((view: RepeatSendView) => !isSendFinished(view.progress)), - { progress: group.progress, needsRefresh: false }, - ]) - receiveRepeatProgress(group, group.progress) - const sourceProgress = group.progress.conversations?.find( - (conversation: MessageSendConversation) => conversation.conversation_id === operation.conversationId, - ) - if (sourceProgress) operation.progress = { ...group.progress, ...sourceProgress } - if (isViewingSend(operation) && !isNarrowScreen) setIsPanelOpen(true) - setPanelRefreshKey((key: number) => key + 1) - } - return await trackSend(operation) - } catch (err) { - if (!isCurrentSend(operation)) { return { status: 'non_retryable_failure', clearDraft: false } } - const sendConvId = operation.conversationId - const apiError = toApiError(err) - if (submissionAttempted && ![400, 401, 403, 404, 409, 422, 429].includes(apiError.status ?? 0)) { - operation.needsRefresh = true - const detail = apiError.isTimeout ? 'Request timed out.' - : apiError.isNetworkError ? 'Network error. The backend could not be reached.' : apiError.detail - setSendIssue(sendConvId, { - description: `${detail} Send acceptance is unknown. Refresh saved messages only; do not resend.`, - blocking: true, - }) - stopSendSpinner(operation) - return { status: 'non_retryable_failure', clearDraft: false } - } - const viewedConversationId = getViewedConversationId() - const isViewingFailedConversation = isViewingSend(operation) - - // Only show error in UI if user is still on this conversation - if (isViewingFailedConversation) { - const hasMatchingTranscript = getLoadedConversationId() === sendConvId - // Mark the viewed conversation as loaded so first-send failures do not - // get stuck behind the "Loading conversation..." placeholder. - if (viewedConversationId) { - markConversationLoaded(viewedConversationId) - } else if (sendConvId !== '__pending__') { - markConversationLoaded(sendConvId) - } - - let description: string - if (apiError.isNetworkError) { - description = 'Network error — check that the backend is running and reachable.' - } else if (apiError.isTimeout) { - description = 'Request timed out. The server may be busy — please try again.' - } else { - description = apiError.detail - } - - const errorMessage: Message = { - role: 'assistant', - content: '', - timestamp: new Date().toISOString(), - error: { - type: apiError.isNetworkError ? 'network' : apiError.isTimeout ? 'timeout' : 'unknown', - description, - }, - } - setMessages(prev => { - // A pending navigation load may still leave a different conversation in state. - const failedMessages = hasMatchingTranscript ? prev : [...messages, userMessage] - const lastFailedMessage = failedMessages[failedMessages.length - 1] - if (failedMessages.length > 0 && lastFailedMessage?.isLoading) { - return [...failedMessages.slice(0, -1), errorMessage] - } - return [...failedMessages, errorMessage] - }) - - } - return { - status: 'retryable_failure', - clearDraft: false, - } - } finally { - finishTracking(operation) - retireSend(operation) - } - } + conversationId, + activeConversationId, + viewedConversationId, + getViewedAttackId: () => viewedAttackRef.current, + setViewedAttackId: (attackId: string) => { viewedAttackRef.current = attackId }, + getNavigationRevision: () => navigationRevisionRef.current, + }, + readiness: { + runtimeReady: runtime.ready, + runtimeGeneration: runtime.generation, + defaultsReady, + scorerSelectionReady, + isSendBlocked: editDraft !== null || Boolean(isLoadingAttack) || isLoadingMessages || awaitingConversationLoad + || isMutationLocked || isUndoingSend || Boolean(unboundHistoryError), + getLaunchState: () => launchStateRef.current, + }, + request: { + activeTarget, + targetResolutionStatus, + newAttack: { + objective: pendingObjective, temperature, systemPrompt, supportsSystemPrompt, labels, operationId, + draftScorer, defaultChatScorer, + }, + chatScorer, + availableScorers, + }, + composer: { + converters, + getDraftRevision: () => inputBoxRef.current?.getDraftRevision(), + getTextMetadata: () => inputBoxRef.current?.getTextMetadata(), + clearSentDraft: (draftRevision: number | undefined) => { + const inputBox = inputBoxRef.current + if (!inputBox || inputBox.getDraftRevision() !== draftRevision) return + lastTextRef.current = '' + lastAttachmentsSignatureRef.current = '' + inputBox.restoreDraft('', []) + setChatInputText('') + setDraftAttachments([]) + converters.clearAll() + draftHandoff.clearPreservedDraft(undefined, draftAttackId, draftConversationId) + }, + restoreSendDraft: (text, attachments, textMetadata, conversions, pipelines) => { + lastTextRef.current = text + lastAttachmentsSignatureRef.current = computeAttachmentSignature(attachments) + setChatInputText(text) + setDraftAttachments(attachments) + inputBoxRef.current?.restoreDraft(text, attachments, textMetadata) + restoreConversions(text, attachments, conversions, pipelines) + }, + clearPreservedDraft: draftHandoff.clearPreservedDraft, + }, + loader: conversationLoad, + callbacks: { + observeChatSend, + showConversationScoring: (convId: string, response: ConversationMessagesResponse) => { + setConversationScoring(conversationScoringOf(convId, response)) + }, + showScoringNotice: setScoringNotice, + setEditorNotice, + revealRepeatConversations: () => { if (!isNarrowScreen) setIsPanelOpen(true) }, + refreshPanel: () => { setPanelRefreshKey((key: number) => key + 1) }, + onConversationCreated, + onCreatedDestination: (attackId: string, convId: string) => { + retainedComposerIdentityRef.current = JSON.stringify([attackId, convId]) + }, + onAttackChange, + }, + }) const appendConversationCreationError = useCallback((error: unknown): void => { const apiError = toApiError(error) @@ -2364,7 +1537,7 @@ export default function ChatWindow({ recoverProcessingError: handleRecoverProcessingError, restoreRecoverableDraft, restoreEditorPrompt, - clearUndoableSend: () => { setUndoableSend(null) }, + clearUndoableSend, showConversation: (response: ConversationMessagesResponse) => { setMessages(handleConversationLoaded( response.conversation_id, response, backendMessagesToFrontend(response.messages), @@ -2404,8 +1577,6 @@ export default function ChatWindow({ ? temperatureTarget.reconstruction_error ?? 'This target does not support a separate temperature setting.' : temperatureReadOnly ? 'Temperature can only be modified in a new attack' : '' const temperatureExplanationContext = attackResultId ?? temperatureTarget?.identifier.hash - const unboundHistoryError = targetResolutionStatus === 'unbound' && activeTarget - ? historyReplayDisabledReason(activeTarget, messages) : undefined const repeatDisabledReason = converters.repeatDisabledReason ?? (activeTarget ? historyReplayDisabledReason(activeTarget, messages) : undefined) const undoHistory = undoableSend?.attackResultId === attackResultId @@ -2416,7 +1587,7 @@ export default function ChatWindow({ ? 'Undo is available after a single successful send from this tab, with its converters still in memory.' : !runtime.ready || undoableSend.converters.generation !== runtime.generation ? 'The runtime changed. The previous converter state is no longer available.' - : isUndoingSend || sendingConversations.size > 0 || converters.isConverting + : isUndoingSend || sendState.state.sending.size > 0 || converters.isConverting ? 'Wait for the current operation to finish before undoing a send.' : editDraft !== null || isLoadingEdit || isLoadingAttack || isLoadingMessages || awaitingConversationLoad ? 'Finish loading or editing the conversation before undoing a send.' @@ -2451,7 +1622,7 @@ export default function ChatWindow({ try { const source = await attacksApi.getMessages(saved.attackResultId, saved.conversationId) if (conversationPieceSignature(source) !== saved.historySignature) { - setUndoableSend(null) + clearUndoableSend() throw new Error('The conversation changed after this send. Undo is no longer available.') } if (!draftUnchanged()) { @@ -2465,7 +1636,7 @@ export default function ChatWindow({ attacksApi.getMessages(saved.attackResultId, branch.conversation_id), attacksApi.getAttack(saved.attackResultId), ]) - setUndoableSend(null) + clearUndoableSend() if (!draftUnchanged()) { setEditorNotice(`Undo created conversation ${branch.conversation_id} without replacing your current draft.`) return @@ -2481,7 +1652,7 @@ export default function ChatWindow({ }, restoredConverters) setEditorNotice('Last send undone. The original sent conversation remains in history.') } catch (error) { - if (branchAttempted) setUndoableSend(null) + if (branchAttempted) clearUndoableSend() const detail = toApiError(error).detail setEditorError(branchAttempted ? `Undo could not finish. Check the conversation list before trying again. ${detail}` @@ -2796,7 +1967,7 @@ export default function ChatWindow({ attackResultId={isEvidenceUnavailable ? '' : attackResultId ?? ''} defaultOperationId={operationId} disabled={isFindingActionDisabled} open={isFindingDialogOpen} onOpenChange={setIsFindingDialogOpen} returnFocusRef={outcomeButtonRef} /> - {scoringConversations.has(viewedConversationId ?? '__pending__') && Scoring response…} + {sendState.state.scoring.has(viewedConversationId ?? PENDING_SEND_CONVERSATION_ID) && Scoring response…} {scoringNotice && scoringNotice.conversationId === viewedConversationId && {scoringNotice.message} } @@ -2911,23 +2082,15 @@ export default function ChatWindow({ )} - {repeatSends.filter((view: RepeatSendView) => view.progress.attack_result_id === attackResultId).map( + {repeatSends.map( (view: RepeatSendView) => ( setRepeatSends((previous: RepeatSendView[]) => previous.filter( - (candidate: RepeatSendView) => candidate.progress.send_id !== view.progress.send_id, - ))} - onRefresh={() => { - for (const operation of pendingSendsRef.current.values()) { - if (operation.repeatGroup?.progress.send_id === view.progress.send_id && operation.needsRefresh) { - void refreshSend(operation.conversationId) - } - } - }} + onDismiss={() => { dismissRepeatSend(view.progress.send_id) }} + onRefresh={() => { refreshRepeatSend(view.progress.send_id) }} /> ), )} diff --git a/frontend/src/hooks/useChatSend.test.ts b/frontend/src/hooks/useChatSend.test.ts new file mode 100644 index 0000000000..f115e86782 --- /dev/null +++ b/frontend/src/hooks/useChatSend.test.ts @@ -0,0 +1,376 @@ +import { act, renderHook } from '@testing-library/react' +import { useState } from 'react' + +import { attacksApi } from '@/services/api' +import { deferred } from '@/test-utils/deferred' +import { makeTarget } from '@/test-utils/targetFixtures' +import type { + AttackSummary, ChatConverterController, ConversationMessagesResponse, Message, MessageSendStatus, PieceConversion, +} from '@/types' +import { PENDING_SEND_CONVERSATION_ID } from '@/utils/chatSendState' + +import { useChatSend, useChatSendState } from './useChatSend' +import type { UseChatSendOptions } from './useChatSend' + +jest.mock('@/services/api', () => ({ + attacksApi: { + createAttack: jest.fn(), + submitMessageSend: jest.fn(), + getMessageSend: jest.fn(), + getAttack: jest.fn(), + getMessages: jest.fn(), + }, +})) + +const api = attacksApi as jest.Mocked +const target = makeTarget({ target_registry_name: 'chat_target', target_type: 'OpenAIChatTarget' }) +const attack = { + attack_result_id: 'attack', conversation_id: 'a', attack_type: 'ManualAttack', objective: '', converters: [], + message_count: 2, related_conversation_ids: [], labels: {}, created_at: '', updated_at: '', +} as AttackSummary + +function accepted(conversationId: string, state: MessageSendStatus['state'] = 'completed'): MessageSendStatus { + return { + send_id: `send-${conversationId}`, attack_result_id: 'attack', conversation_id: conversationId, + request_turn_number: 1, state, error: null, failure_stage: null, + } +} + +function transcript(conversationId: string, messages: ConversationMessagesResponse['messages'] = []): ConversationMessagesResponse { + return { conversation_id: conversationId, messages, target_response_status: null } +} + +function convertersWith(applied: Record = {}): ChatConverterController { + return { + applied, + pipelines: {}, + snapshot: () => ({ generation: 'g1', pipelines: {}, workingInputs: {}, stageResults: {}, errors: {}, applied }), + } as unknown as ChatConverterController +} + +interface HarnessOptions { + attackResultId?: string | null + conversationId?: string | null + activeConversationId?: string | null + converters?: ChatConverterController +} + +function renderSend(initial: HarnessOptions = {}) { + const viewed = { attackId: initial.attackResultId === undefined ? 'attack' : initial.attackResultId, conversationId: null as string | null } + const options = { + attackResultId: 'attack' as string | null, + conversationId: 'a' as string | null, + activeConversationId: 'a' as string | null, + converters: convertersWith(), + ...initial, + } + viewed.conversationId = options.activeConversationId ?? options.conversationId + const callbacks = { + onConversationCreated: jest.fn(), + onCreatedDestination: jest.fn(), + clearSentDraft: jest.fn(), + restoreSendDraft: jest.fn(), + refreshPanel: jest.fn(), + revealRepeatConversations: jest.fn(), + observeChatSend: jest.fn((_attackId: string, acceptance: Promise) => ({ + readProgress: () => acceptance, + readAttack: () => api.getAttack('attack'), + })), + } + const hook = renderHook((props: HarnessOptions) => { + const [messages, setMessages] = useState([]) + const merged = { ...options, ...props } + const viewedConversationId = merged.activeConversationId ?? merged.conversationId ?? null + const tracking = useChatSendState({ + activeConversationId: merged.activeConversationId ?? null, + viewedConversationId, + runtimeGeneration: 'g1', + }) + const sendOptions: UseChatSendOptions = { + tracking, + route: { + attackResultId: merged.attackResultId, + conversationId: merged.conversationId, + activeConversationId: merged.activeConversationId, + viewedConversationId, + getViewedAttackId: () => viewed.attackId, + setViewedAttackId: (id: string) => { viewed.attackId = id }, + getNavigationRevision: () => 0, + }, + readiness: { + runtimeReady: true, + runtimeGeneration: 'g1', + defaultsReady: true, + scorerSelectionReady: true, + isSendBlocked: false, + getLaunchState: () => ({ generation: 'g1', ready: true, defaultsReady: true, scorerSelectionReady: true }), + }, + request: { + activeTarget: target, + targetResolutionStatus: 'resolved', + newAttack: { + objective: 'Objective', temperature: '', systemPrompt: '', supportsSystemPrompt: false, + labels: { operator: 'me' }, operationId: null, draftScorer: undefined, defaultChatScorer: undefined, + }, + chatScorer: null, + availableScorers: [], + }, + composer: { + converters: merged.converters, + getDraftRevision: () => 1, + getTextMetadata: () => undefined, + clearSentDraft: callbacks.clearSentDraft, + restoreSendDraft: callbacks.restoreSendDraft, + clearPreservedDraft: jest.fn(), + }, + loader: { + messages, + setMessages, + loadedConversationId: merged.activeConversationId ?? null, + invalidateConversationLoads: jest.fn(), + claimConversationRead: () => 1, + isLatestConversationRead: () => true, + markConversationLoaded: jest.fn(), + getViewedConversationId: () => viewed.conversationId, + setViewedConversationId: (id: string | null) => { viewed.conversationId = id }, + getLoadedConversationId: () => viewed.conversationId, + }, + callbacks: { + observeChatSend: callbacks.observeChatSend, + showConversationScoring: jest.fn(), + showScoringNotice: jest.fn(), + setEditorNotice: jest.fn(), + revealRepeatConversations: callbacks.revealRepeatConversations, + refreshPanel: callbacks.refreshPanel, + onConversationCreated: callbacks.onConversationCreated, + onCreatedDestination: callbacks.onCreatedDestination, + }, + } + const send = useChatSend(sendOptions) + return { tracking, send, messages } + }, { initialProps: {} }) + const view = (props: HarnessOptions): void => { + viewed.conversationId = props.activeConversationId ?? viewed.conversationId + hook.rerender(props) + } + return { ...hook, callbacks, view } +} + +beforeEach(() => { + jest.clearAllMocks() + api.getAttack.mockResolvedValue(attack) + api.getMessages.mockImplementation(async (_attackId: string, conversationId: string) => transcript(conversationId)) +}) + +describe('useChatSend', () => { + it('shows the prompt optimistically and locks the conversation until the send settles', async () => { + const acceptance = deferred() + api.submitMessageSend.mockReturnValue(acceptance.promise) + const { result } = renderSend() + + let sent!: Promise + await act(async () => { sent = result.current.send.send('hello', undefined, []) }) + + expect(result.current.messages).toEqual([ + expect.objectContaining({ role: 'user', content: 'hello' }), + expect.objectContaining({ role: 'assistant', isLoading: true }), + ]) + expect(result.current.tracking.isSending).toBe(true) + expect(result.current.tracking.isSendInFlight('a')).toBe(true) + + await act(async () => { + acceptance.resolve(accepted('a')) + await sent + }) + + expect(await sent).toEqual({ status: 'sent', clearDraft: true }) + expect(result.current.tracking.isSending).toBe(false) + expect(result.current.tracking.isSendInFlight('a')).toBe(false) + expect(result.current.messages.some((message: Message) => message.isLoading)).toBe(false) + }) + + it('rejects a duplicate send while the conversation is locked', async () => { + api.submitMessageSend.mockReturnValue(deferred().promise) + const { result } = renderSend() + + await act(async () => { void result.current.send.send('first', undefined, []) }) + let duplicate: unknown + await act(async () => { duplicate = await result.current.send.send('second', undefined, []) }) + + expect(duplicate).toEqual({ status: 'retryable_failure', clearDraft: false }) + expect(api.submitMessageSend).toHaveBeenCalledTimes(1) + }) + + it('sends independently in two conversations', async () => { + const first = deferred() + const second = deferred() + api.submitMessageSend.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise) + const { result, view } = renderSend() + + let firstSend!: Promise + await act(async () => { firstSend = result.current.send.send('to a', undefined, []) }) + view({ activeConversationId: 'b', conversationId: 'b' }) + await act(async () => { void result.current.send.send('to b', undefined, []) }) + + expect(api.submitMessageSend).toHaveBeenCalledTimes(2) + expect([...result.current.tracking.state.sending].sort()).toEqual(['a', 'b']) + + await act(async () => { + first.resolve(accepted('a')) + await firstSend + }) + + expect([...result.current.tracking.state.sending]).toEqual(['b']) + expect(result.current.tracking.isSending).toBe(true) + }) + + it('restores the optimistic prompt when the user returns to a conversation that is still sending', async () => { + api.submitMessageSend.mockReturnValue(deferred().promise) + const { result, view } = renderSend() + + await act(async () => { void result.current.send.send('pending prompt', undefined, []) }) + view({ activeConversationId: 'b', conversationId: 'b' }) + + let reloaded: Message[] = [] + let other: Message[] = [] + act(() => { + reloaded = result.current.tracking.reconcileLoadedConversation('a', transcript('a'), []) + other = result.current.tracking.reconcileLoadedConversation('b', transcript('b'), []) + }) + expect(reloaded).toEqual([ + expect.objectContaining({ role: 'user', content: 'pending prompt' }), + expect.objectContaining({ role: 'assistant', isLoading: true }), + ]) + expect(other).toEqual([]) + }) + + it('moves the first send to the created conversation before routing to it', async () => { + api.createAttack.mockResolvedValue({ attack_result_id: 'created-attack', conversation_id: 'created' } as never) + const acceptance = deferred() + api.submitMessageSend.mockReturnValue(acceptance.promise) + const { result, callbacks } = renderSend({ attackResultId: null, conversationId: null, activeConversationId: null }) + + await act(async () => { void result.current.send.send('first prompt', undefined, []) }) + + expect(api.createAttack).toHaveBeenCalledWith(expect.objectContaining({ + target_registry_name: 'chat_target', objective: 'Objective', labels: { operator: 'me' }, + })) + expect(callbacks.onCreatedDestination).toHaveBeenCalledWith('created-attack', 'created') + expect(callbacks.onConversationCreated).toHaveBeenCalledWith('created-attack', 'created', 'Objective') + expect(api.submitMessageSend).toHaveBeenCalledWith('created-attack', expect.objectContaining({ + target_conversation_id: 'created', send: true, + })) + expect(result.current.tracking.isSendInFlight(PENDING_SEND_CONVERSATION_ID)).toBe(false) + expect(result.current.tracking.isSendInFlight('created')).toBe(true) + expect([...result.current.tracking.state.sending]).toEqual(['created']) + }) + + it('blocks resending after unknown delivery and refreshes without resubmitting', async () => { + api.submitMessageSend.mockRejectedValue(new Error('socket closed')) + const { result } = renderSend() + + let outcome: unknown + await act(async () => { outcome = await result.current.send.send('hello', undefined, []) }) + + expect(outcome).toEqual({ status: 'non_retryable_failure', clearDraft: false }) + expect(result.current.send.sendIssue).toEqual(expect.objectContaining({ + blocking: true, + description: 'socket closed Send acceptance is unknown. Refresh saved messages only; do not resend.', + })) + let resend: unknown + await act(async () => { resend = await result.current.send.send('hello', undefined, []) }) + expect(resend).toEqual({ status: 'retryable_failure', clearDraft: false }) + + await act(async () => { await result.current.send.refreshSend() }) + + expect(api.submitMessageSend).toHaveBeenCalledTimes(1) + expect(api.getMessages).toHaveBeenCalledWith('attack', 'a') + expect(result.current.send.sendIssue?.blocking).toBe(true) + expect(result.current.tracking.isSending).toBe(false) + }) + + it('shows a retryable error when the send fails before submission', async () => { + api.createAttack.mockRejectedValue(new Error('labels changed')) + const { result } = renderSend({ attackResultId: null, conversationId: null, activeConversationId: null }) + + let outcome: unknown + await act(async () => { outcome = await result.current.send.send('hello', undefined, []) }) + + expect(outcome).toEqual({ status: 'retryable_failure', clearDraft: false }) + expect(api.submitMessageSend).not.toHaveBeenCalled() + expect(result.current.messages).toEqual([ + expect.objectContaining({ role: 'user', content: 'hello' }), + expect.objectContaining({ role: 'assistant', error: expect.objectContaining({ description: 'labels changed' }) }), + ]) + expect(result.current.tracking.isSendInFlight(PENDING_SEND_CONVERSATION_ID)).toBe(false) + }) + + it('sends converted pieces and shows a text-to-file conversion as an attachment', async () => { + api.submitMessageSend.mockReturnValue(deferred().promise) + const conversion: PieceConversion = { + pieceId: 'text', pieceType: 'text', converterInstanceIds: ['qr'], convertedValue: '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/media/out.png', + originalValue: 'hello', convertedDataType: 'image_path', + } + const { result } = renderSend({ converters: convertersWith({ text: conversion }) }) + + await act(async () => { void result.current.send.send('hello', undefined, []) }) + + expect(result.current.messages[0]).toEqual(expect.objectContaining({ + content: 'hello', + attachments: [expect.objectContaining({ name: 'out.png', mimeType: 'application/octet-stream' })], + })) + expect(api.submitMessageSend).toHaveBeenCalledWith('attack', expect.objectContaining({ + pieces: [expect.objectContaining({ + original_value: 'hello', converted_value: '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/media/out.png', converted_value_data_type: 'image_path', + applied_converter_ids: ['qr'], + })], + })) + }) + + it('offers the prompt back when preparation fails before target dispatch', async () => { + api.submitMessageSend.mockResolvedValue({ + ...accepted('a', 'failed'), failure_stage: 'preparation', error: 'Converter failed.', + }) + const { result, callbacks } = renderSend() + + let outcome: unknown + await act(async () => { outcome = await result.current.send.send('hello', undefined, [], undefined) }) + + expect(outcome).toEqual({ status: 'retryable_failure', clearDraft: false }) + expect(result.current.send.sendIssue).toEqual(expect.objectContaining({ + description: 'Converter failed.', blocking: false, draft: expect.anything(), + })) + + act(() => { result.current.send.restorePreparationDraft() }) + + expect(callbacks.restoreSendDraft).toHaveBeenCalledWith('hello', [], undefined, {}, undefined) + }) + + it('records the last single send as undoable once its response is saved', async () => { + api.submitMessageSend.mockResolvedValue(accepted('a')) + api.getMessages.mockResolvedValue({ + conversation_id: 'a', + messages: [ + { turn_number: 1, role: 'user', message_pieces: [], created_at: '' }, + { + turn_number: 2, role: 'assistant', created_at: '', + message_pieces: [{ + id: 'reply', original_value_data_type: 'text', converted_value_data_type: 'text', + converted_value: 'hi', scores: [], response_error: 'none', + }], + }, + ], + target_response_status: { request_turn_number: 1, response_turn_number: 2, response_error: 'none' }, + } as ConversationMessagesResponse) + const { result } = renderSend() + + await act(async () => { await result.current.send.send('hello', undefined, []) }) + + expect(result.current.tracking.state.undoable).toEqual(expect.objectContaining({ + attackResultId: 'attack', conversationId: 'a', cutoffIndex: 0, originalValue: 'hello', + })) + + act(() => { result.current.tracking.clearUndoableSend() }) + expect(result.current.tracking.state.undoable).toBeNull() + }) +}) diff --git a/frontend/src/hooks/useChatSend.ts b/frontend/src/hooks/useChatSend.ts new file mode 100644 index 0000000000..ed024ec498 --- /dev/null +++ b/frontend/src/hooks/useChatSend.ts @@ -0,0 +1,986 @@ +import { useCallback, useEffect, useMemo, useReducer, useRef } from 'react' +import type { Dispatch, RefObject } from 'react' + +import { + applyConvertedValues, + basenameFromValue, + buildConverterInputs, + buildDraftPieceIds, + buildMediaUrl, + buildRequestConverterConfigurations, + dataTypeToAttachmentKind, + withDraftIdentity, +} from '@/components/Chat/converterTypes' +import { attacksApi } from '@/services/api' +import { toApiError } from '@/services/errors' +import type { + AddMessageResponse, + AttackSummary, + AttackTargetResolutionStatus, + BackendMessage, + ChatConverterController, + ChatSendOutcome, + ConversationMessagesResponse, + ConverterPipelineStage, + CreateAttackRequest, + Message, + MessageAttachment, + MessageSendConversation, + MessageSendObservation, + MessageSendRequest, + MessageSendStatus, + MultiSendOptions, + PieceConversion, + RegisteredComponentReference, + ScorerInstance, + TargetInstance, + TargetReference, +} from '@/types' +import { + chatSendReducer, + getPersistedProcessingRecovery, + INITIAL_CHAT_SEND_STATE, + isSendFinished, + PENDING_SEND_CONVERSATION_ID, + userPieceIds, +} from '@/utils/chatSendState' +import type { + ChatSendAction, + ChatSendState, + PendingSend, + RecoverableSendDraft, + RepeatSendGroup, + RepeatSendView, + SendIssue, +} from '@/utils/chatSendState' +import type { ConversationMessages } from '@/hooks/useConversationMessages' +import { generateClientId } from '@/utils/clientId' +import { backendMessagesToFrontend, buildMessagePieces } from '@/utils/messageMapper' +import { conversationPieceSignature } from '@/utils/promptRestore' +import { buildTemperatureTarget } from '@/services/targetRegistry' +import { targetReference } from '@/utils/targetIdentity' + +/** Synchronous send locks and transcript snapshots. Reads must not wait for a render. */ +export interface ChatSendLocks { + /** Conversations with an in-flight send; marked before any state update can trigger a load. */ + readonly sendingIds: Set + /** Optimistic user messages per conversation that the server may not have stored yet. */ + readonly pendingUserMessages: Map + /** The current send per conversation; a send that is no longer here has lost ownership. */ + readonly pendingSends: Map + readonly loadedUserPieceIds: Map> + readonly loadedBackendMessages: Map +} + +export interface UseChatSendStateOptions { + activeConversationId: string | null + viewedConversationId: string | null + runtimeGeneration: string +} + +export interface ChatSendTracking { + readonly state: ChatSendState + readonly dispatch: Dispatch + readonly locksRef: RefObject + /** True while the active conversation (or, before one exists, any conversation) is sending. */ + readonly isSending: boolean + /** The viewed conversation's recovery, without converter state from another runtime generation. */ + readonly recoverableSend: RecoverableSendDraft | undefined + readonly isSendInFlight: (conversationId: string) => boolean + /** Records a loaded transcript and re-appends the optimistic turn of a send that still owns it. */ + readonly reconcileLoadedConversation: ( + conversationId: string, response: ConversationMessagesResponse, frontendMessages: Message[], + ) => Message[] + readonly getPendingSend: (conversationId: string) => PendingSend | undefined + readonly getLoadedBackendMessages: (conversationId: string) => BackendMessage[] | undefined + readonly rememberBackendMessages: (conversationId: string, messages: BackendMessage[]) => void + readonly clearUndoableSend: () => void + /** Drops every recovery when the attack is reset; safe to call while rendering. */ + readonly clearRecoveries: () => void +} + +function createLocks(): ChatSendLocks { + return { + sendingIds: new Set(), + pendingUserMessages: new Map(), + pendingSends: new Map(), + loadedUserPieceIds: new Map(), + loadedBackendMessages: new Map(), + } +} + +/** + * Owns the send workflow's state: a pure reducer for what renders, plus the synchronous + * per-conversation locks. Conversation loading consumes this before `useChatSend` composes the commands. + */ +export function useChatSendState({ + activeConversationId, + viewedConversationId, + runtimeGeneration, +}: UseChatSendStateOptions): ChatSendTracking { + const [state, dispatch] = useReducer(chatSendReducer, INITIAL_CHAT_SEND_STATE) + const locksRef = useRef(createLocks()) + + useEffect(() => { + const { pendingSends } = locksRef.current + return () => { + for (const operation of pendingSends.values()) { + operation.controller.abort() + } + pendingSends.clear() + } + }, []) + + const isSendInFlight = useCallback( + (conversationId: string): boolean => locksRef.current.sendingIds.has(conversationId), + [], + ) + + const reconcileLoadedConversation = useCallback(( + conversationId: string, response: ConversationMessagesResponse, frontendMessages: Message[], + ): Message[] => { + const locks = locksRef.current + const savedUserIds = userPieceIds(response) + locks.loadedUserPieceIds.set(conversationId, savedUserIds) + if (response.messages) { + locks.loadedBackendMessages.set(conversationId, response.messages) + } + dispatch({ + type: 'recovery-loaded', conversationId, recovery: getPersistedProcessingRecovery(conversationId, response), + }) + // If this conversation has an in-flight send, append any pending user + // messages (that the server may not have stored yet) and a loading indicator. + if (locks.sendingIds.has(conversationId)) { + const operation = locks.pendingSends.get(conversationId) + const pending = locks.pendingUserMessages.get(conversationId) ?? [] + const requestStored = operation?.progress?.request_turn_number != null + ? response.messages.some((message: BackendMessage) => ( + message.role === 'user' && message.turn_number === operation.progress?.request_turn_number + )) + : operation && [...savedUserIds].some((id) => !operation.priorUserPieceIds.has(id)) + if (!operation?.progress || !isSendFinished(operation.progress)) { + if (!requestStored) { frontendMessages.push(...pending) } + frontendMessages.push({ + role: 'assistant', + content: '...', + timestamp: new Date().toISOString(), + isLoading: true, + }) + } + } + return frontendMessages + }, []) + + const getPendingSend = useCallback( + (conversationId: string): PendingSend | undefined => locksRef.current.pendingSends.get(conversationId), + [], + ) + const getLoadedBackendMessages = useCallback( + (conversationId: string): BackendMessage[] | undefined => locksRef.current.loadedBackendMessages.get(conversationId), + [], + ) + const rememberBackendMessages = useCallback((conversationId: string, messages: BackendMessage[]): void => { + locksRef.current.loadedBackendMessages.set(conversationId, messages) + }, []) + const clearUndoableSend = useCallback((): void => { dispatch({ type: 'undo-cleared' }) }, []) + const clearRecoveries = useCallback((): void => { dispatch({ type: 'recoveries-cleared' }) }, []) + + const isSending = activeConversationId ? state.sending.has(activeConversationId) : Boolean(state.sending.size) + const savedRecovery = viewedConversationId ? state.recoveries[viewedConversationId] : undefined + const recoverableSend = useMemo(() => ( + savedRecovery?.converterGeneration !== undefined && savedRecovery.converterGeneration !== runtimeGeneration + ? { + ...savedRecovery, conversions: {}, pipelines: undefined, source: 'persisted', + } + : savedRecovery + ), [savedRecovery, runtimeGeneration]) + + return { + state, + dispatch, + locksRef, + isSending, + recoverableSend, + isSendInFlight, + reconcileLoadedConversation, + getPendingSend, + getLoadedBackendMessages, + rememberBackendMessages, + clearUndoableSend, + clearRecoveries, + } +} + +export interface ChatSendLaunchState { + generation: string + ready: boolean + defaultsReady: boolean + scorerSelectionReady: boolean +} + +/** Settings a first send uses to create its attack. */ +export interface ChatSendNewAttack { + objective: string + temperature: string + systemPrompt: string + supportsSystemPrompt: boolean + labels?: Record + operationId: string | null + /** The operator's explicit draft scorer choice, or undefined to use the default. */ + draftScorer: RegisteredComponentReference | null | undefined + defaultChatScorer?: RegisteredComponentReference | null +} + +export interface ScoringNotice { + id: string + message: string + conversationId: string +} + +/** Which conversation a send belongs to, plus live reads that detect the user moving on mid-send. */ +export interface ChatSendRoute { + attackResultId: string | null + conversationId: string | null + activeConversationId: string | null + viewedConversationId: string | null + getViewedAttackId: () => string | null + setViewedAttackId: (attackResultId: string) => void + getNavigationRevision: () => number +} + +/** Whether a send may start now, and a live read of the same launch state for in-flight checks. */ +export interface ChatSendReadiness { + runtimeReady: boolean + runtimeGeneration: string + defaultsReady: boolean + scorerSelectionReady: boolean + /** True when another workflow (loading, editing, locking, undo) currently forbids sending. */ + isSendBlocked: boolean + getLaunchState: () => ChatSendLaunchState +} + +/** What the submission targets and how a first send creates its attack. */ +export interface ChatSendRequest { + activeTarget: TargetInstance | null + targetResolutionStatus: AttackTargetResolutionStatus + newAttack: ChatSendNewAttack + /** The loaded attack's scorer, recorded with the send for preference observation. */ + chatScorer: RegisteredComponentReference | null + availableScorers: ScorerInstance[] +} + +/** The draft a send captures, and how the composer is cleared or restored afterwards. */ +export interface ChatSendComposer { + converters: ChatConverterController + getDraftRevision: () => number | undefined + getTextMetadata: () => Record | undefined + /** Clears the composer after a refreshed send settles, when its draft revision is still shown. */ + clearSentDraft: (draftRevision: number | undefined) => void + restoreSendDraft: ( + text: string, attachments: MessageAttachment[], textMetadata: Record | undefined, + conversions: Record, pipelines: Record | undefined, + ) => void + clearPreservedDraft: (sequence: number | undefined, attackId: string | null, conversationId: string | null) => void +} + +/** The transcript and load ownership from `useConversationMessages`. */ +export type ChatSendLoader = Pick + +/** Effects outside the send workflow: scoring display, notices, the panel and the parent route. */ +export interface ChatSendCallbacks { + observeChatSend: ( + attackId: string, acceptance: Promise, target: TargetReference, + scorerChoice: RegisteredComponentReference | null | undefined, scorerExplicit: boolean, scorers: ScorerInstance[], + ) => MessageSendObservation + showConversationScoring: (conversationId: string, response: ConversationMessagesResponse) => void + showScoringNotice: (notice: ScoringNotice) => void + setEditorNotice: (notice: string | null) => void + /** Shows the conversations panel for a repeated send, except on narrow screens. */ + revealRepeatConversations: () => void + refreshPanel: () => void + onConversationCreated: ( + attackResultId: string, conversationId: string, objective?: string, target?: TargetInstance | null, + ) => void + /** Keeps the composer when a first send's created conversation becomes the route. */ + onCreatedDestination: (attackResultId: string, conversationId: string) => void + onAttackChange?: (attack: AttackSummary) => void +} + +export interface UseChatSendOptions { + tracking: ChatSendTracking + route: ChatSendRoute + readiness: ChatSendReadiness + request: ChatSendRequest + composer: ChatSendComposer + loader: ChatSendLoader + callbacks: ChatSendCallbacks +} + +export interface ChatSend { + readonly sendIssue: SendIssue | undefined + /** Repeated sends started from the current attack. */ + readonly repeatSends: RepeatSendView[] + readonly send: ( + originalValue: string, convertedValue: string | undefined, attachments: MessageAttachment[], options?: MultiSendOptions, + ) => Promise + /** Re-reads the viewed conversation's send without resubmitting it. */ + readonly refreshSend: () => Promise + readonly refreshRepeatSend: (sendId: string) => void + readonly dismissRepeatSend: (sendId: string) => void + readonly restorePreparationDraft: () => void +} + +/** + * Message sending: optimistic messages, per-conversation locking, attachment and conversion capture, + * progress tracking, and recovery after unknown delivery. State transitions go through `chatSendReducer`. + */ +export function useChatSend({ + tracking, route, readiness, request, composer, loader, callbacks, +}: UseChatSendOptions): ChatSend { + const { + attackResultId, conversationId, activeConversationId, viewedConversationId, + getViewedAttackId, setViewedAttackId, getNavigationRevision, + } = route + const { runtimeReady, runtimeGeneration, defaultsReady, scorerSelectionReady, isSendBlocked, getLaunchState } = readiness + const { activeTarget, targetResolutionStatus, newAttack, chatScorer, availableScorers } = request + const { converters, getDraftRevision, getTextMetadata, clearSentDraft, restoreSendDraft, clearPreservedDraft } = composer + const { + messages, setMessages, loadedConversationId, invalidateConversationLoads, claimConversationRead, + isLatestConversationRead, markConversationLoaded, getViewedConversationId, setViewedConversationId, + getLoadedConversationId, + } = loader + const { + observeChatSend, showConversationScoring, showScoringNotice, setEditorNotice, revealRepeatConversations, + refreshPanel, onConversationCreated, onCreatedDestination, onAttackChange, + } = callbacks + const { state, dispatch, locksRef } = tracking + const latestSendRef = useRef(null) + const sendIssueConversationId = attackResultId ? viewedConversationId : loadedConversationId ?? viewedConversationId + const sendIssue = state.issues[sendIssueConversationId ?? PENDING_SEND_CONVERSATION_ID] + + const isCurrentSend = (operation: PendingSend): boolean => ( + !operation.controller.signal.aborted + && locksRef.current.pendingSends.get(operation.conversationId) === operation + ) + const checkSendPreparation = (operation: PendingSend, requireDefaults: boolean): void => { + const current = getLaunchState() + if (current.generation !== operation.converterGeneration || !current.ready + || (requireDefaults && (!current.defaultsReady || !current.scorerSelectionReady))) { + throw new Error('Runtime or default labels changed while preparing this message. Your draft is preserved. Retry after default labels finish loading.') + } + } + const isViewingSend = (operation: PendingSend): boolean => ( + getViewedAttackId() === operation.attackResultId + && ( + getViewedConversationId() === operation.conversationId + || (getViewedConversationId() === null && operation.conversationId === PENDING_SEND_CONVERSATION_ID + && getNavigationRevision() === operation.navigationRevision) + ) + ) + const setSendIssue = (conversation: string, issue?: SendIssue): void => { + dispatch({ type: 'issue-changed', conversationId: conversation, issue }) + } + const finishTracking = (operation: PendingSend): void => { + const locks = locksRef.current + if (!isCurrentSend(operation) || !locks.sendingIds.has(operation.conversationId)) { return } + if (operation.responseReadId === undefined + || isLatestConversationRead(operation.conversationId, operation.responseReadId)) { + invalidateConversationLoads(operation.conversationId) + } + if (isViewingSend(operation)) { + setMessages((previous) => previous.filter((message) => !message.isLoading)) + } + locks.sendingIds.delete(operation.conversationId) + locks.pendingUserMessages.delete(operation.conversationId) + dispatch({ type: 'tracking-finished', conversationId: operation.conversationId }) + refreshPanel() + } + const retireSend = (operation: PendingSend): void => { + if (isCurrentSend(operation) && !operation.needsRefresh + && operation.progress?.failure_stage !== 'preparation') { + locksRef.current.pendingSends.delete(operation.conversationId) + } + } + const stopSendSpinner = (operation: PendingSend): void => { + if (!isViewingSend(operation)) { return } + const hasMatchingTranscript = getLoadedConversationId() === operation.conversationId + const pending = locksRef.current.pendingUserMessages.get(operation.conversationId) ?? [] + setMessages((previous) => (hasMatchingTranscript + ? previous + : [...operation.initialMessages, ...pending] + ).filter((message) => !message.isLoading)) + markConversationLoaded(operation.conversationId) + } + + const applySendResponse = ( + operation: PendingSend, response: AddMessageResponse, isLatestRead: boolean, + ): ChatSendOutcome => { + const effectiveConvId = operation.conversationId + const targetResponseStatus = response.messages.target_response_status + const recovery = operation.progress + && !['interrupted', 'finalization'].includes(operation.progress.failure_stage ?? '') + ? getPersistedProcessingRecovery(effectiveConvId, response.messages) + : undefined + const processingFailure = recovery?.failedRequestTurnNumber === operation.progress?.request_turn_number + && recovery !== undefined + const status: ChatSendOutcome['status'] = operation.progress?.failure_stage === 'preparation' + || processingFailure + ? 'retryable_failure' + : operation.progress?.failure_stage + || (targetResponseStatus?.response_error && targetResponseStatus.response_error !== 'none') + ? 'non_retryable_failure' + : 'sent' + const backendMessages = backendMessagesToFrontend(response.messages.messages) + const recoveredDraft: RecoverableSendDraft | undefined = processingFailure && recovery ? { + ...recovery, + originalValue: operation.originalValue, + textMetadata: operation.textMetadata, + attachments: operation.attachments, + conversions: operation.conversions, + converterGeneration: operation.converterGeneration, + pipelines: operation.pipelines, + source: 'live', + } : recovery + if (isLatestRead) { + const locks = locksRef.current + locks.loadedUserPieceIds.set(effectiveConvId, userPieceIds(response.messages)) + if (response.messages?.messages) { + locks.loadedBackendMessages.set(effectiveConvId, response.messages.messages) + } + dispatch({ type: 'recovery-replaced', conversationId: effectiveConvId, recovery: recoveredDraft }) + } + if (isLatestRead && isViewingSend(operation)) { + invalidateConversationLoads(effectiveConvId) + setMessages(backendMessages) + showConversationScoring(effectiveConvId, response.messages) + markConversationLoaded(effectiveConvId) + onAttackChange?.(response.attack) + const scoringError = operation.progress?.scoring_error + const result = response.messages.scoring_failure + if (scoringError && result && result.conversation_id === effectiveConvId) { + showScoringNotice({ + id: operation.submissionId, conversationId: effectiveConvId, + message: 'A scoring error occurred. Open the score above for details.', + }) + } + const lastMessage = response.messages.messages[response.messages.messages.length - 1] + if ( + status === 'sent' && operation.progress?.state === 'completed' + && latestSendRef.current === operation.submissionId + && !operation.repeatGroup && operation.converterSnapshot && operation.attackResultId + && typeof targetResponseStatus?.request_turn_number === 'number' + && targetResponseStatus.request_turn_number === operation.progress.request_turn_number + && lastMessage?.role === 'assistant' && lastMessage.message_pieces.length > 0 + ) { + dispatch({ + type: 'undo-recorded', + undoable: { + attackResultId: operation.attackResultId, + conversationId: effectiveConvId, + historySignature: conversationPieceSignature(response.messages), + cutoffIndex: targetResponseStatus.request_turn_number - 1, + originalValue: operation.originalValue, + textMetadata: operation.textMetadata, + attachments: operation.attachments, + converters: operation.converterSnapshot, + history: response.messages.messages.filter( + (message: BackendMessage) => message.turn_number < targetResponseStatus.request_turn_number, + ).map((message: BackendMessage) => ({ role: message.role })), + }, + }) + } + } + return { + status, + clearDraft: status !== 'retryable_failure' && latestSendRef.current === operation.submissionId + && (!operation.repeatGroup || operation.repeatGroup.source === operation), + } + } + + const updateRepeatView = (group: RepeatSendGroup): void => { + if (group.source.controller.signal.aborted) return + const needsRefresh = [...group.conversations.values()].some( + (operation: PendingSend) => isCurrentSend(operation) && operation.needsRefresh, + ) + dispatch({ type: 'repeat-progressed', progress: group.progress, needsRefresh }) + } + + const receiveRepeatProgress = (group: RepeatSendGroup, progress: MessageSendStatus): void => { + if (group.source.controller.signal.aborted) return + const locks = locksRef.current + group.progress = progress + let addedConversations = false + for (const conversation of progress.conversations ?? []) { + if (group.conversations.has(conversation.conversation_id)) continue + addedConversations = true + const operation: PendingSend = { + ...group.source, + conversationId: conversation.conversation_id, + draftRevision: undefined, + responseReadId: undefined, + needsRefresh: false, + progress: { ...progress, ...conversation }, + } + group.conversations.set(operation.conversationId, operation) + // A finished sibling may already have a newer send by the time this snapshot arrives. + if (locks.pendingSends.has(operation.conversationId)) continue + locks.pendingSends.set(operation.conversationId, operation) + locks.sendingIds.add(operation.conversationId) + const pending = locks.pendingUserMessages.get(group.source.conversationId) + if (pending) locks.pendingUserMessages.set(operation.conversationId, [...pending]) + dispatch({ type: 'tracking-started', conversationId: operation.conversationId }) + void trackSend(operation).then(() => { retireSend(operation) }) + } + if (addedConversations) refreshPanel() + updateRepeatView(group) + } + + const readSendProgress = async (operation: PendingSend): Promise => { + const { attackResultId: sendAttackId, progress: previousProgress } = operation + if (!sendAttackId || !previousProgress) throw new Error('The send has no progress handle.') + const group = operation.repeatGroup + const read = (): Promise => operation.observation + ? operation.observation.readProgress(operation.needsRefresh) + : attacksApi.getMessageSend(sendAttackId, previousProgress.send_id, operation.controller.signal) + if (!group) return read() + // Every conversation uses the same in-flight GET, but settles its own evidence reads and ownership. + group.read ??= read().then((progress: MessageSendStatus) => { + receiveRepeatProgress(group, progress) + return progress + }).finally(() => { group.read = undefined }) + const progress = await group.read + const conversation = progress.conversations?.find( + (candidate: MessageSendConversation) => candidate.conversation_id === operation.conversationId, + ) + return conversation ? { ...progress, ...conversation } : progress + } + + const trackSend = async (operation: PendingSend): Promise => { + try { + if (!operation.attackResultId) { throw new Error('The send has no attack ID.') } + while (operation.progress) { + const repeatProgress = operation.repeatGroup?.progress + // The last conversation can release ownership before the operation publishes its final summary. + const awaitingSummary = repeatProgress && !isSendFinished(repeatProgress) + && repeatProgress.conversations?.length && repeatProgress.conversations.every(isSendFinished) + if (isSendFinished(operation.progress) && !awaitingSummary) break + let progress: MessageSendStatus | undefined + try { + progress = await readSendProgress(operation) + } catch (err) { + if (toApiError(err).status !== 404) { throw err } + // Lost handles permit evidence reads, never a new submission or a claim of delivery. + } + if (!isCurrentSend(operation)) { return { status: 'non_retryable_failure', clearDraft: false } } + operation.progress = progress + dispatch({ type: 'scoring-observed', conversationId: operation.conversationId, scoring: progress?.is_scoring === true }) + } + operation.responseReadId = claimConversationRead(operation.conversationId) + const [attack, conversation] = await Promise.all([ + operation.observation?.readAttack(operation.needsRefresh) ?? attacksApi.getAttack(operation.attackResultId), + attacksApi.getMessages(operation.attackResultId, operation.conversationId), + ]) + if (!isCurrentSend(operation)) { return { status: 'non_retryable_failure', clearDraft: false } } + const isLatestRead = isLatestConversationRead(operation.conversationId, operation.responseReadId) + const outcome = applySendResponse(operation, { attack, messages: conversation }, isLatestRead) + const progress = operation.progress + const hasProcessingRecovery = conversation.target_response_status?.response_error === 'processing' + && conversation.target_response_status.request_turn_number === progress?.request_turn_number + if (!progress || progress.failure_stage === 'interrupted' || progress.failure_stage === 'finalization' + || (progress.failure_stage === 'sending' && !hasProcessingRecovery)) { + operation.needsRefresh = true + setSendIssue(operation.conversationId, { + description: `${progress?.error ?? 'Send acceptance is unknown.'} Refresh saved messages only; do not resend.`, + blocking: true, + }) + return { status: 'non_retryable_failure', clearDraft: false } + } + setSendIssue(operation.conversationId, progress.failure_stage === 'preparation' + ? { + description: progress.error ?? 'Message preparation failed before target dispatch.', + blocking: false, + draft: operation, + } + : undefined) + operation.needsRefresh = false + if (outcome.status !== 'retryable_failure' && operation.preservedDraft) { + const preserved = operation.preservedDraft + clearPreservedDraft(preserved.sequence, preserved.originatingAttackId, preserved.originatingConversationId) + operation.preservedDraft = undefined + } + return outcome + } catch (err) { + if (isCurrentSend(operation)) { + operation.needsRefresh = true + const error = toApiError(err) + const detail = error.isTimeout ? 'The read timed out.' + : error.isNetworkError ? 'The backend could not be reached.' : error.detail + const phase = operation.progress && isSendFinished(operation.progress) + ? `${operation.progress.error ?? 'Sending finished.'} Saved messages or attack details could not be loaded.` + : 'Send status is unavailable. Delivery may be unknown.' + setSendIssue(operation.conversationId, { + description: `${phase} ${detail} Refresh only; do not resend.`, + blocking: true, + }) + stopSendSpinner(operation) + } + return { status: 'non_retryable_failure', clearDraft: false } + } finally { + finishTracking(operation) + if (operation.repeatGroup) updateRepeatView(operation.repeatGroup) + } + } + + const refreshConversationSend = async (conversationIdToRefresh: string): Promise => { + const locks = locksRef.current + const operation = locks.pendingSends.get(conversationIdToRefresh) + if (!operation || locks.sendingIds.has(operation.conversationId)) { return } + locks.sendingIds.add(operation.conversationId) + dispatch({ type: 'tracking-started', conversationId: operation.conversationId }) + const outcome = await trackSend(operation) + if (isCurrentSend(operation) && isViewingSend(operation) && outcome.clearDraft) { + clearSentDraft(operation.draftRevision) + } + retireSend(operation) + } + + const refreshSend = (): Promise => refreshConversationSend(sendIssueConversationId ?? PENDING_SEND_CONVERSATION_ID) + + const refreshRepeatSend = (sendId: string): void => { + for (const operation of locksRef.current.pendingSends.values()) { + if (operation.repeatGroup?.progress.send_id === sendId && operation.needsRefresh) { + void refreshConversationSend(operation.conversationId) + } + } + } + + const dismissRepeatSend = (sendId: string): void => { dispatch({ type: 'repeat-dismissed', sendId }) } + + const restorePreparationDraft = (): void => { + const operation = sendIssue?.draft + if (!operation || !isCurrentSend(operation) || !isViewingSend(operation)) return + const sameGeneration = operation.converterGeneration === runtimeGeneration + const attachments = operation.attachments.map(withDraftIdentity) + restoreSendDraft( + operation.originalValue, attachments, operation.textMetadata, + sameGeneration ? operation.conversions : {}, sameGeneration ? operation.pipelines : undefined, + ) + if (!sameGeneration) setSendIssue(operation.conversationId, { + ...sendIssue, + description: 'Prompt restored after the runtime changed. Review converters before sending.', + }) + } + + const send = async ( + originalValue: string, + convertedValue: string | undefined, + attachments: MessageAttachment[], + options?: MultiSendOptions, + ): Promise => { + if ( + !runtimeReady + || (!attackResultId && (!defaultsReady || !scorerSelectionReady)) + || !activeTarget + || isSendBlocked + || sendIssue?.blocking + ) { + return { status: 'retryable_failure', clearDraft: false } + } + + const locks = locksRef.current + const initialSendConvId = activeConversationId ?? conversationId ?? PENDING_SEND_CONVERSATION_ID + if (locks.sendingIds.has(initialSendConvId)) { + return { status: 'retryable_failure', clearDraft: false } + } + + setEditorNotice(null) + invalidateConversationLoads(initialSendConvId) + + // Capture all piece conversions upfront before any async work or state clears + const conversions = { ...converters.applied } + const count = options?.count ?? 1 + const converterMode = options?.requestConverterMode ?? 'shared' + const pipelines = count > 1 ? { ...converters.pipelines } : undefined + const { draftScorer, defaultChatScorer, objective: pendingObjective } = newAttack + const operation: PendingSend = { + submissionId: generateClientId(), + controller: new AbortController(), + draftRevision: getDraftRevision(), + originalValue, + textMetadata: getTextMetadata(), + attachments: attachments.map((attachment) => ({ ...attachment })), + conversions, + priorUserPieceIds: new Set(locks.loadedUserPieceIds.get(initialSendConvId)), + initialMessages: [...messages], + navigationRevision: getNavigationRevision(), + converterGeneration: runtimeGeneration, + target: targetReference(activeTarget), + chatScorerExplicit: draftScorer !== undefined, + chatScorerChoice: attackResultId ? chatScorer : draftScorer === undefined ? defaultChatScorer : draftScorer, + converterSnapshot: count === 1 ? converters.snapshot() : undefined, + pipelines, + attackResultId, + conversationId: initialSendConvId, + needsRefresh: false, + } + locks.pendingSends.set(initialSendConvId, operation) + latestSendRef.current = operation.submissionId + const submittedNavigationRevision = getNavigationRevision() + let submissionAttempted = false + const textConversion = conversions['text'] + const isTextTextConversion = textConversion?.convertedDataType === 'text' + const isTextFileConversion = Boolean(textConversion) && !isTextTextConversion + + // Mark synchronously so the useEffect guard sees it immediately + locks.sendingIds.add(initialSendConvId) + + // When a text→text converter is active, show the converted text as the bubble's + // primary content. When a text→file converter is active, keep the typed text + // as content and synthesize a file attachment so the bubble shows both. + const displayContent = isTextTextConversion && convertedValue != null ? convertedValue : originalValue + const optimisticAttachments: MessageAttachment[] = [...attachments] + if (isTextFileConversion && textConversion) { + const url = buildMediaUrl(textConversion.convertedValue) + const kind = dataTypeToAttachmentKind(textConversion.convertedDataType) + optimisticAttachments.push({ + type: kind, + name: basenameFromValue(textConversion.convertedValue, `output.${kind}`), + url, + mimeType: 'application/octet-stream', + }) + } + + // Add user message with attachments for display + const userMessage: Message = { + role: 'user', + content: displayContent, + timestamp: new Date().toISOString(), + attachments: optimisticAttachments.length > 0 ? optimisticAttachments : undefined, + originalContent: isTextTextConversion ? originalValue : undefined, + } + setMessages(prev => [...prev, userMessage]) + + // Track as pending so switching back before the server stores it still shows it + const pending = locks.pendingUserMessages.get(initialSendConvId) ?? [] + pending.push(userMessage) + locks.pendingUserMessages.set(initialSendConvId, pending) + + // Show loading indicator + dispatch({ type: 'send-started', conversationId: initialSendConvId }) + const loadingMessage: Message = { + role: 'assistant', + content: '...', + timestamp: new Date().toISOString(), + isLoading: true, + } + setMessages(prev => [...prev, loadingMessage]) + + try { + // Build message pieces from text + attachments — always use original text + const pieceIds = buildDraftPieceIds(originalValue, attachments, conversions) + const originalPieces = await buildMessagePieces(originalValue, attachments, operation.textMetadata) + if (textConversion && !originalValue.trim()) { + originalPieces.unshift({ data_type: 'text', original_value: originalValue }) + } + const pieces = applyConvertedValues( + originalPieces, + pieceIds, + conversions, + ) + const requestConfigurations = count > 1 && converterMode === 'per_branch' ? buildRequestConverterConfigurations( + buildConverterInputs(originalValue, attachments), pieceIds, pipelines ?? {}, conversions, + ) : [] + if (!isCurrentSend(operation)) { return { status: 'non_retryable_failure', clearDraft: false } } + + // Create attack lazily on first message + let currentAttackResultId = attackResultId + let currentConversationId = conversationId + let currentActiveConversationId = activeConversationId + if (!currentAttackResultId) { + checkSendPreparation(operation, true) + let selectedTarget = activeTarget + if (newAttack.temperature.trim()) { + selectedTarget = await buildTemperatureTarget(activeTarget, Number(newAttack.temperature)) + if (!isCurrentSend(operation)) { return { status: 'non_retryable_failure', clearDraft: false } } + } + checkSendPreparation(operation, true) + const createRequest: CreateAttackRequest = { + target_registry_name: activeTarget.target_registry_name, + ...(selectedTarget.binding ? { target_binding: selectedTarget.binding } : {}), + objective: pendingObjective || undefined, + // TODO(PyRIT 1.4): Pass only dedicated attribution after legacy label aliases are removed. + // The create-attack API normalizes these aliases through _AttackAttributionInput. + labels: newAttack.labels, + operation_id: newAttack.operationId ?? undefined, + system_prompt: newAttack.supportsSystemPrompt ? newAttack.systemPrompt.trim() || undefined : undefined, + ...(draftScorer !== undefined ? { chat_scorer: draftScorer } + : defaultChatScorer === null || pendingObjective.trim() && defaultChatScorer + ? { chat_scorer: defaultChatScorer } : {}), + } + const createResponse = await attacksApi.createAttack(createRequest) + operation.chatScorerChoice = createRequest.chat_scorer + if (!isCurrentSend(operation)) { return { status: 'non_retryable_failure', clearDraft: false } } + currentAttackResultId = createResponse.attack_result_id + currentConversationId = createResponse.conversation_id + currentActiveConversationId = currentConversationId + // Mark new ID in synchronous ref *before* triggering the state + // update that changes activeConversationId (and fires the useEffect) + locks.sendingIds.delete(PENDING_SEND_CONVERSATION_ID) + locks.sendingIds.add(currentConversationId) + // Move pending messages to the real conversation ID + const pendingMsgs = locks.pendingUserMessages.get(PENDING_SEND_CONVERSATION_ID) + if (pendingMsgs) { + locks.pendingUserMessages.delete(PENDING_SEND_CONVERSATION_ID) + locks.pendingUserMessages.set(currentConversationId, pendingMsgs) + } + locks.pendingSends.delete(PENDING_SEND_CONVERSATION_ID) + operation.attackResultId = currentAttackResultId + operation.conversationId = currentConversationId + locks.pendingSends.set(currentConversationId, operation) + if (getNavigationRevision() === submittedNavigationRevision) { + onCreatedDestination(currentAttackResultId, currentConversationId) + if (selectedTarget.binding) { + onConversationCreated(currentAttackResultId, currentConversationId, pendingObjective || undefined, selectedTarget) + } else { + onConversationCreated(currentAttackResultId, currentConversationId, pendingObjective || undefined) + } + setViewedAttackId(currentAttackResultId) + setViewedConversationId(currentConversationId) + } + // Update sending tracker to use real ID instead of the pending key + dispatch({ type: 'send-conversation-created', from: PENDING_SEND_CONVERSATION_ID, to: currentConversationId }) + } + + // The effective conversation we're sending for + const effectiveConvId = currentActiveConversationId ?? currentConversationId + + // Send message to target + if (!currentAttackResultId || !effectiveConvId) { + throw new Error('Message send is missing an attack or conversation ID.') + } + const addMessageRequest: MessageSendRequest = { + role: 'user', + pieces, + send: true, + target_registry_name: activeTarget.target_registry_name, + target_conversation_id: effectiveConvId, + submission_id: operation.submissionId, + ...(count > 1 ? { + count, + request_converter_mode: converterMode, + } : {}), + ...(requestConfigurations.length ? { request_converter_configurations: requestConfigurations } : {}), + } + if (targetResolutionStatus === 'unbound' && newAttack.temperature.trim()) { + const selectedTarget = await buildTemperatureTarget(activeTarget, Number(newAttack.temperature)) + if (!isCurrentSend(operation)) { return { status: 'non_retryable_failure', clearDraft: false } } + addMessageRequest.target_binding = selectedTarget.binding + } + checkSendPreparation(operation, false) + submissionAttempted = true + const acceptance = attacksApi.submitMessageSend(currentAttackResultId, addMessageRequest) + operation.observation = observeChatSend( + currentAttackResultId, acceptance, operation.target, + operation.chatScorerChoice, operation.chatScorerExplicit, availableScorers, + ) + operation.progress = await acceptance + if (!isCurrentSend(operation)) { return { status: 'non_retryable_failure', clearDraft: false } } + if (count > 1) { + const group: RepeatSendGroup = { + source: operation, + progress: operation.progress, + conversations: new Map([[operation.conversationId, operation]]), + } + operation.repeatGroup = group + dispatch({ type: 'repeat-started', progress: group.progress }) + receiveRepeatProgress(group, group.progress) + const sourceProgress = group.progress.conversations?.find( + (conversation: MessageSendConversation) => conversation.conversation_id === operation.conversationId, + ) + if (sourceProgress) operation.progress = { ...group.progress, ...sourceProgress } + if (isViewingSend(operation)) revealRepeatConversations() + refreshPanel() + } + return await trackSend(operation) + } catch (err) { + if (!isCurrentSend(operation)) { return { status: 'non_retryable_failure', clearDraft: false } } + const sendConvId = operation.conversationId + const apiError = toApiError(err) + if (submissionAttempted && ![400, 401, 403, 404, 409, 422, 429].includes(apiError.status ?? 0)) { + operation.needsRefresh = true + const detail = apiError.isTimeout ? 'Request timed out.' + : apiError.isNetworkError ? 'Network error. The backend could not be reached.' : apiError.detail + setSendIssue(sendConvId, { + description: `${detail} Send acceptance is unknown. Refresh saved messages only; do not resend.`, + blocking: true, + }) + stopSendSpinner(operation) + return { status: 'non_retryable_failure', clearDraft: false } + } + const viewedId = getViewedConversationId() + const isViewingFailedConversation = isViewingSend(operation) + + // Only show error in UI if user is still on this conversation + if (isViewingFailedConversation) { + const hasMatchingTranscript = getLoadedConversationId() === sendConvId + // Mark the viewed conversation as loaded so first-send failures do not + // get stuck behind the "Loading conversation..." placeholder. + if (viewedId) { + markConversationLoaded(viewedId) + } else if (sendConvId !== PENDING_SEND_CONVERSATION_ID) { + markConversationLoaded(sendConvId) + } + + let description: string + if (apiError.isNetworkError) { + description = 'Network error — check that the backend is running and reachable.' + } else if (apiError.isTimeout) { + description = 'Request timed out. The server may be busy — please try again.' + } else { + description = apiError.detail + } + + const errorMessage: Message = { + role: 'assistant', + content: '', + timestamp: new Date().toISOString(), + error: { + type: apiError.isNetworkError ? 'network' : apiError.isTimeout ? 'timeout' : 'unknown', + description, + }, + } + setMessages(prev => { + // A pending navigation load may still leave a different conversation in state. + const failedMessages = hasMatchingTranscript ? prev : [...messages, userMessage] + const lastFailedMessage = failedMessages[failedMessages.length - 1] + if (failedMessages.length > 0 && lastFailedMessage?.isLoading) { + return [...failedMessages.slice(0, -1), errorMessage] + } + return [...failedMessages, errorMessage] + }) + + } + return { + status: 'retryable_failure', + clearDraft: false, + } + } finally { + finishTracking(operation) + retireSend(operation) + } + } + + return { + sendIssue, + repeatSends: state.repeatSends.filter((view: RepeatSendView) => view.progress.attack_result_id === attackResultId), + send, + refreshSend, + refreshRepeatSend, + dismissRepeatSend, + restorePreparationDraft, + } +} diff --git a/frontend/src/utils/chatSendState.test.ts b/frontend/src/utils/chatSendState.test.ts new file mode 100644 index 0000000000..990f91e10a --- /dev/null +++ b/frontend/src/utils/chatSendState.test.ts @@ -0,0 +1,234 @@ +import type { ConversationMessagesResponse, MessageSendStatus } from '@/types' + +import { + chatSendReducer, + getPersistedProcessingRecovery, + INITIAL_CHAT_SEND_STATE, + isSendFinished, + mergeLoadedRecovery, + PENDING_SEND_CONVERSATION_ID, +} from './chatSendState' +import type { ChatSendAction, ChatSendState, RecoverableSendDraft, UndoableSend } from './chatSendState' + +function reduce(actions: ChatSendAction[], state: ChatSendState = INITIAL_CHAT_SEND_STATE): ChatSendState { + return actions.reduce(chatSendReducer, state) +} + +function recovery(overrides: Partial = {}): RecoverableSendDraft { + return { + history: [], + conversationId: 'conv', + failedRequestTurnNumber: 1, + failedResponseTurnNumber: 2, + historyCutoffIndex: 0, + failedRequestMessageIndex: 0, + originalValue: 'persisted prompt', + attachments: [], + conversions: {}, + source: 'persisted', + ...overrides, + } +} + +function progress(sendId: string, state: MessageSendStatus['state']): MessageSendStatus { + return { + send_id: sendId, attack_result_id: 'attack', conversation_id: 'conv', request_turn_number: 1, + state, error: null, failure_stage: null, + } +} + +const undoable: UndoableSend = { + attackResultId: 'attack', conversationId: 'conv', historySignature: 'sig', cutoffIndex: 0, originalValue: 'hi', + attachments: [], history: [], + converters: { generation: 'g1', pipelines: {}, workingInputs: {}, stageResults: {}, errors: {}, applied: {} }, +} + +describe('chatSendReducer', () => { + it('locks each conversation independently', () => { + const state = reduce([ + { type: 'send-started', conversationId: 'a' }, + { type: 'send-started', conversationId: 'b' }, + { type: 'tracking-finished', conversationId: 'a' }, + ]) + + expect([...state.sending]).toEqual(['b']) + }) + + it('clears the conversation issue, recovery and undo when a send starts', () => { + const started = reduce([ + { type: 'issue-changed', conversationId: 'a', issue: { description: 'old', blocking: true } }, + { type: 'issue-changed', conversationId: 'b', issue: { description: 'other', blocking: true } }, + { type: 'recovery-replaced', conversationId: 'a', recovery: recovery({ conversationId: 'a' }) }, + { type: 'undo-recorded', undoable }, + { type: 'send-started', conversationId: 'a' }, + ]) + + expect(started.issues).toEqual({ b: { description: 'other', blocking: true } }) + expect(started.recoveries).toEqual({}) + expect(started.undoable).toBeNull() + }) + + it('moves a first send lock from the pending key to the created conversation', () => { + const state = reduce([ + { type: 'send-started', conversationId: PENDING_SEND_CONVERSATION_ID }, + { type: 'send-conversation-created', from: PENDING_SEND_CONVERSATION_ID, to: 'created' }, + ]) + + expect([...state.sending]).toEqual(['created']) + }) + + it('tracks scoring per conversation and releases it with the send', () => { + const scoring = reduce([ + { type: 'tracking-started', conversationId: 'a' }, + { type: 'scoring-observed', conversationId: 'a', scoring: true }, + { type: 'scoring-observed', conversationId: 'b', scoring: true }, + ]) + expect([...scoring.scoring]).toEqual(['a', 'b']) + + const finished = chatSendReducer(scoring, { type: 'tracking-finished', conversationId: 'a' }) + expect([...finished.scoring]).toEqual(['b']) + expect(finished.sending.size).toBe(0) + }) + + it('returns the same state for transitions that change nothing', () => { + const state = reduce([{ type: 'tracking-started', conversationId: 'a' }]) + + expect(chatSendReducer(state, { type: 'tracking-started', conversationId: 'a' })).toBe(state) + expect(chatSendReducer(state, { type: 'tracking-finished', conversationId: 'b' })).toBe(state) + expect(chatSendReducer(state, { type: 'scoring-observed', conversationId: 'a', scoring: false })).toBe(state) + expect(chatSendReducer(state, { type: 'issue-changed', conversationId: 'a' })).toBe(state) + expect(chatSendReducer(state, { type: 'recovery-loaded', conversationId: 'a' })).toBe(state) + expect(chatSendReducer(state, { type: 'recovery-replaced', conversationId: 'a' })).toBe(state) + expect(chatSendReducer(state, { type: 'recoveries-cleared' })).toBe(state) + expect(chatSendReducer(state, { type: 'undo-cleared' })).toBe(state) + }) + + it('keeps a live recovery when a reload reports the same failed turn', () => { + const live = recovery({ source: 'live', originalValue: 'typed prompt', historyCutoffIndex: 0, failedRequestMessageIndex: 0 }) + const state = reduce([ + { type: 'recovery-replaced', conversationId: 'conv', recovery: live }, + { + type: 'recovery-loaded', conversationId: 'conv', + recovery: recovery({ historyCutoffIndex: 3, failedRequestMessageIndex: 4 }), + }, + ]) + + expect(state.recoveries.conv).toEqual({ ...live, historyCutoffIndex: 3, failedRequestMessageIndex: 4 }) + }) + + it('replaces a recovery for a different failed turn and drops it when the load has none', () => { + const live = recovery({ source: 'live', originalValue: 'typed prompt' }) + const persisted = recovery({ failedRequestTurnNumber: 3, failedResponseTurnNumber: 4 }) + const replaced = reduce([ + { type: 'recovery-replaced', conversationId: 'conv', recovery: live }, + { type: 'recovery-loaded', conversationId: 'conv', recovery: persisted }, + ]) + expect(replaced.recoveries.conv).toBe(persisted) + + const cleared = chatSendReducer(replaced, { type: 'recovery-loaded', conversationId: 'conv' }) + expect(cleared.recoveries).toEqual({}) + }) + + it('lets a send response replace a live recovery even for the same turn', () => { + const state = reduce([ + { type: 'recovery-replaced', conversationId: 'conv', recovery: recovery({ source: 'live' }) }, + { type: 'recovery-replaced', conversationId: 'conv', recovery: recovery() }, + ]) + + expect(state.recoveries.conv.source).toBe('persisted') + }) + + it('clears every recovery when the attack resets', () => { + const state = reduce([ + { type: 'recovery-replaced', conversationId: 'a', recovery: recovery() }, + { type: 'recovery-replaced', conversationId: 'b', recovery: recovery() }, + { type: 'recoveries-cleared' }, + ]) + + expect(state.recoveries).toEqual({}) + }) + + it('replaces finished repeated sends when a new one starts and updates only the matching view', () => { + const state = reduce([ + { type: 'repeat-started', progress: progress('done', 'completed') }, + { type: 'repeat-started', progress: progress('running', 'sending') }, + { type: 'repeat-started', progress: progress('next', 'queued') }, + { type: 'repeat-progressed', progress: progress('running', 'failed'), needsRefresh: true }, + ]) + + expect(state.repeatSends).toEqual([ + { progress: progress('running', 'failed'), needsRefresh: true }, + { progress: progress('next', 'queued'), needsRefresh: false }, + ]) + expect(chatSendReducer(state, { type: 'repeat-dismissed', sendId: 'running' }).repeatSends).toEqual([ + { progress: progress('next', 'queued'), needsRefresh: false }, + ]) + }) + + it('records and clears the undoable send', () => { + const recorded = chatSendReducer(INITIAL_CHAT_SEND_STATE, { type: 'undo-recorded', undoable }) + expect(recorded.undoable).toBe(undoable) + expect(chatSendReducer(recorded, { type: 'undo-cleared' }).undoable).toBeNull() + }) +}) + +describe('mergeLoadedRecovery', () => { + it('returns nothing when the load has no recovery', () => { + expect(mergeLoadedRecovery(recovery({ source: 'live' }), undefined)).toBeUndefined() + }) + + it('prefers the persisted recovery over an older persisted one', () => { + const persisted = recovery({ historyCutoffIndex: 2 }) + expect(mergeLoadedRecovery(recovery(), persisted)).toBe(persisted) + }) +}) + +describe('isSendFinished', () => { + it.each([ + ['completed', true], ['failed', true], ['interrupted', true], ['queued', false], ['sending', false], ['finalizing', false], + ] as const)('%s is finished: %s', (state, finished) => { + expect(isSendFinished(progress('send', state))).toBe(finished) + }) +}) + +describe('getPersistedProcessingRecovery', () => { + const piece = (id: string, value: string, responseError: 'none' | 'processing' = 'none') => ({ + id, original_value_data_type: 'text', converted_value_data_type: 'text', original_value: value, + converted_value: value, scores: [], response_error: responseError, prompt_metadata: { tone: id }, + }) + const response = (status: ConversationMessagesResponse['target_response_status']): ConversationMessagesResponse => ({ + conversation_id: 'conv', + messages: [ + { turn_number: 1, role: 'user', message_pieces: [piece('u1', 'first')], created_at: '' }, + { turn_number: 2, role: 'assistant', message_pieces: [piece('a1', 'reply')], created_at: '' }, + { turn_number: 3, role: 'user', message_pieces: [piece('u2', 'retry me')], created_at: '' }, + { turn_number: 4, role: 'assistant', message_pieces: [piece('a2', '', 'processing')], created_at: '' }, + ], + target_response_status: status, + }) + + it('restores the failed request and keeps only the history before it', () => { + const result = getPersistedProcessingRecovery('conv', response({ + request_turn_number: 3, response_turn_number: 4, response_error: 'processing', + })) + + expect(result).toEqual(expect.objectContaining({ + conversationId: 'conv', + failedRequestTurnNumber: 3, + failedResponseTurnNumber: 4, + historyCutoffIndex: 2, + history: [{ role: 'user' }, { role: 'assistant' }], + failedRequestMessageIndex: 2, + originalValue: 'retry me', + textMetadata: { tone: 'u2' }, + source: 'persisted', + })) + }) + + it('ignores responses that are not retryable processing failures', () => { + expect(getPersistedProcessingRecovery('conv', response(null))).toBeUndefined() + expect(getPersistedProcessingRecovery('conv', response({ + request_turn_number: 9, response_turn_number: 10, response_error: 'processing', + }))).toBeUndefined() + }) +}) diff --git a/frontend/src/utils/chatSendState.ts b/frontend/src/utils/chatSendState.ts new file mode 100644 index 0000000000..a28ac5a7d6 --- /dev/null +++ b/frontend/src/utils/chatSendState.ts @@ -0,0 +1,328 @@ +import type { + BackendMessage, + ChatConverterSnapshot, + ChatDraftContextState, + ConversationMessagesResponse, + ConverterPipelineStage, + Message, + MessageAttachment, + MessageSendConversation, + MessageSendObservation, + MessageSendStatus, + PieceConversion, + RegisteredComponentReference, + TargetReference, +} from '@/types' +import { backendMessageToOriginalDraft } from '@/utils/messageMapper' + +/** Lock key for a first send whose attack and conversation are not created yet. */ +export const PENDING_SEND_CONVERSATION_ID = '__pending__' + +const RETRYABLE_TARGET_RESPONSE_ERROR = 'processing' + +/** A failed prompt that can be restored into a new conversation without resending the failed turn. */ +export interface RecoverableSendDraft { + history: Array> + conversationId: string + failedRequestTurnNumber: number + failedResponseTurnNumber: number + historyCutoffIndex: number + failedRequestMessageIndex: number + originalValue: string + textMetadata?: Record + attachments: MessageAttachment[] + conversions: Record + source: 'live' | 'persisted' + converterGeneration?: string + pipelines?: Record +} + +/** One submitted send. Its identity is the lock owner for `conversationId`; fields mutate as the send advances. */ +export interface PendingSend { + readonly submissionId: string + readonly controller: AbortController + readonly draftRevision: number | undefined + readonly originalValue: string + readonly textMetadata?: Record + readonly attachments: MessageAttachment[] + readonly conversions: Record + readonly priorUserPieceIds: Set + readonly initialMessages: Message[] + readonly navigationRevision: number + readonly converterGeneration: string + readonly target: TargetReference + readonly chatScorerExplicit: boolean + chatScorerChoice?: RegisteredComponentReference | null + observation?: MessageSendObservation + readonly converterSnapshot?: ChatConverterSnapshot + readonly pipelines?: Record + attackResultId: string | null + conversationId: string + needsRefresh: boolean + responseReadId?: number + progress?: MessageSendStatus + repeatGroup?: RepeatSendGroup + preservedDraft?: Pick +} + +/** The last single send from this tab, kept while its converters can still be restored. */ +export interface UndoableSend { + attackResultId: string + conversationId: string + historySignature: string + cutoffIndex: number + originalValue: string + textMetadata?: Record + attachments: MessageAttachment[] + converters: ChatConverterSnapshot + history: Array> +} + +/** A repeated send whose conversations share one progress handle. */ +export interface RepeatSendGroup { + source: PendingSend + progress: MessageSendStatus + conversations: Map + read?: Promise +} + +export interface RepeatSendView { + progress: MessageSendStatus + needsRefresh: boolean +} + +export interface SendIssue { + description: string + blocking: boolean + draft?: PendingSend +} + +/** Rendered send state. The synchronous per-conversation locks live beside it in `useChatSendState`. */ +export interface ChatSendState { + /** Conversations with an in-flight send, so parallel conversations can send independently. */ + readonly sending: ReadonlySet + /** Conversations whose latest response is being scored by an in-flight send. */ + readonly scoring: ReadonlySet + readonly issues: Readonly> + readonly recoveries: Readonly> + readonly repeatSends: readonly RepeatSendView[] + readonly undoable: UndoableSend | null +} + +export type ChatSendAction = + /** A new submission owns the conversation: clear its previous issue, recovery and the tab's undo. */ + | { readonly type: 'send-started'; readonly conversationId: string } + /** The first send created its attack; move its lock from the pending key to the created conversation. */ + | { readonly type: 'send-conversation-created'; readonly from: string; readonly to: string } + /** A refresh or repeat sibling resumed tracking an accepted send. */ + | { readonly type: 'tracking-started'; readonly conversationId: string } + | { readonly type: 'tracking-finished'; readonly conversationId: string } + | { readonly type: 'scoring-observed'; readonly conversationId: string; readonly scoring: boolean } + | { readonly type: 'issue-changed'; readonly conversationId: string; readonly issue?: SendIssue } + /** A conversation load reported its persisted recovery, or the lack of one. */ + | { readonly type: 'recovery-loaded'; readonly conversationId: string; readonly recovery?: RecoverableSendDraft } + /** A send's own response read replaces the conversation's recovery. */ + | { readonly type: 'recovery-replaced'; readonly conversationId: string; readonly recovery?: RecoverableSendDraft } + | { readonly type: 'recoveries-cleared' } + | { readonly type: 'repeat-started'; readonly progress: MessageSendStatus } + | { readonly type: 'repeat-progressed'; readonly progress: MessageSendStatus; readonly needsRefresh: boolean } + | { readonly type: 'repeat-dismissed'; readonly sendId: string } + | { readonly type: 'undo-recorded'; readonly undoable: UndoableSend } + | { readonly type: 'undo-cleared' } + +export const INITIAL_CHAT_SEND_STATE: ChatSendState = { + sending: new Set(), + scoring: new Set(), + issues: {}, + recoveries: {}, + repeatSends: [], + undoable: null, +} + +function withMember(set: ReadonlySet, member: string): ReadonlySet { + return set.has(member) ? set : new Set(set).add(member) +} + +function withoutMember(set: ReadonlySet, member: string): ReadonlySet { + if (!set.has(member)) return set + const next = new Set(set) + next.delete(member) + return next +} + +function withEntry(record: Readonly>, key: string, value: T | undefined): Readonly> { + if (value === undefined) { + if (!(key in record)) return record + const next = { ...record } + delete next[key] + return next + } + return { ...record, [key]: value } +} + +/** Keeps live draft content when a reload reports the same failed turn the send already recovered. */ +export function mergeLoadedRecovery( + current: RecoverableSendDraft | undefined, + persisted: RecoverableSendDraft | undefined, +): RecoverableSendDraft | undefined { + if (!persisted) return undefined + if ( + current?.source === 'live' + && current.failedRequestTurnNumber === persisted.failedRequestTurnNumber + && current.failedResponseTurnNumber === persisted.failedResponseTurnNumber + ) { + return { + ...current, + failedRequestMessageIndex: persisted.failedRequestMessageIndex, + historyCutoffIndex: persisted.historyCutoffIndex, + } + } + return persisted +} + +export function chatSendReducer(state: ChatSendState, action: ChatSendAction): ChatSendState { + switch (action.type) { + case 'send-started': + return { + ...state, + sending: withMember(state.sending, action.conversationId), + issues: withEntry(state.issues, action.conversationId, undefined), + recoveries: withEntry(state.recoveries, action.conversationId, undefined), + undoable: null, + } + case 'send-conversation-created': { + const sending = new Set(state.sending) + sending.delete(action.from) + sending.add(action.to) + return { ...state, sending } + } + case 'tracking-started': { + const sending = withMember(state.sending, action.conversationId) + return sending === state.sending ? state : { ...state, sending } + } + case 'tracking-finished': { + const sending = withoutMember(state.sending, action.conversationId) + const scoring = withoutMember(state.scoring, action.conversationId) + return sending === state.sending && scoring === state.scoring ? state : { ...state, sending, scoring } + } + case 'scoring-observed': { + const scoring = action.scoring + ? withMember(state.scoring, action.conversationId) + : withoutMember(state.scoring, action.conversationId) + return scoring === state.scoring ? state : { ...state, scoring } + } + case 'issue-changed': { + const issues = withEntry(state.issues, action.conversationId, action.issue) + return issues === state.issues ? state : { ...state, issues } + } + case 'recovery-loaded': { + const recovery = mergeLoadedRecovery(state.recoveries[action.conversationId], action.recovery) + const recoveries = withEntry(state.recoveries, action.conversationId, recovery) + return recoveries === state.recoveries ? state : { ...state, recoveries } + } + case 'recovery-replaced': { + const recoveries = withEntry(state.recoveries, action.conversationId, action.recovery) + return recoveries === state.recoveries ? state : { ...state, recoveries } + } + case 'recoveries-cleared': + return Object.keys(state.recoveries).length === 0 ? state : { ...state, recoveries: {} } + case 'repeat-started': + return { + ...state, + repeatSends: [ + ...state.repeatSends.filter((view: RepeatSendView) => !isSendFinished(view.progress)), + { progress: action.progress, needsRefresh: false }, + ], + } + case 'repeat-progressed': + return { + ...state, + repeatSends: state.repeatSends.map((view: RepeatSendView) => ( + view.progress.send_id === action.progress.send_id + ? { progress: action.progress, needsRefresh: action.needsRefresh } : view + )), + } + case 'repeat-dismissed': + return { + ...state, + repeatSends: state.repeatSends.filter((view: RepeatSendView) => view.progress.send_id !== action.sendId), + } + case 'undo-recorded': + return { ...state, undoable: action.undoable } + case 'undo-cleared': + return state.undoable === null ? state : { ...state, undoable: null } + } +} + +export function isSendFinished(progress: MessageSendConversation): boolean { + return ['completed', 'failed', 'interrupted'].includes(progress.state) +} + +export function userPieceIds(response: ConversationMessagesResponse): Set { + return new Set(response.messages.filter((message) => message.role === 'user') + .flatMap((message) => message.message_pieces.map((piece) => piece.id))) +} + +function getRecoveryHistoryCutoff(messages: BackendMessage[], failedRequestTurnNumber: number): number { + let precedingUserTurnNumber: number | undefined + for (const message of messages) { + if (message.turn_number >= failedRequestTurnNumber) { + break + } + if (message.role === 'user') { + precedingUserTurnNumber = message.turn_number + } + for (const piece of message.message_pieces) { + if (piece.response_error === RETRYABLE_TARGET_RESPONSE_ERROR) { + // Later replies can depend on the failed turn, so retain only its preceding history. + return (precedingUserTurnNumber ?? message.turn_number) - 1 + } + } + } + return failedRequestTurnNumber - 1 +} + +export function getPersistedProcessingRecovery( + conversationId: string, + response: ConversationMessagesResponse, +): RecoverableSendDraft | undefined { + const responseStatus = response.target_response_status + if (responseStatus?.response_error !== RETRYABLE_TARGET_RESPONSE_ERROR) { + return undefined + } + + const failedRequest = response.messages.find( + (message) => ( + message.role === 'user' + && message.turn_number === responseStatus.request_turn_number + ), + ) + const errorMessageIndex = response.messages.findIndex( + (message) => ( + message.role === 'assistant' + && message.turn_number === responseStatus.response_turn_number + ), + ) + if (!failedRequest || errorMessageIndex < 0) { + return undefined + } + + const originalDraft = backendMessageToOriginalDraft(failedRequest) + const textMetadata = failedRequest.message_pieces.filter((piece) => piece.original_value_data_type === 'text') + .reduce>((metadata: Record, piece) => ({ ...metadata, ...piece.prompt_metadata }), {}) + const cutoffIndex = getRecoveryHistoryCutoff(response.messages, responseStatus.request_turn_number) + return { + conversationId, + failedRequestTurnNumber: responseStatus.request_turn_number, + failedResponseTurnNumber: responseStatus.response_turn_number, + historyCutoffIndex: cutoffIndex, + history: response.messages.filter((message: BackendMessage) => message.turn_number <= cutoffIndex) + .map((message: BackendMessage) => ({ role: message.role })), + failedRequestMessageIndex: response.messages.indexOf(failedRequest), + originalValue: originalDraft.content, + textMetadata: Object.keys(textMetadata).length ? textMetadata : undefined, + attachments: (originalDraft.attachments ?? []).map((attachment) => ({ ...attachment })), + conversions: {}, + source: 'persisted', + } +} From 38fc8953d15a23b014970aa7855c84732e8e36f2 Mon Sep 17 00:00:00 2001 From: Roman Lutz Date: Fri, 13 Nov 2026 00:52:40 -0800 Subject: [PATCH 2/2] TEST: Add hook-level repeated-send coverage and mark the tracking seam Adds a useChatSend test for a count > 1 send: one submission with the repeat options, sibling conversation adoption with its own lock and evidence read, lock release, and the repeat view surviving completion until dismissed. Documents dispatch/locksRef on ChatSendTracking as the seam driven by useChatSend only. Co-Authored-By: Claude Fable 5 --- frontend/src/hooks/useChatSend.test.ts | 39 ++++++++++++++++++++++++-- frontend/src/hooks/useChatSend.ts | 1 + 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/frontend/src/hooks/useChatSend.test.ts b/frontend/src/hooks/useChatSend.test.ts index 12b9e69b8c..2ba28f9a64 100644 --- a/frontend/src/hooks/useChatSend.test.ts +++ b/frontend/src/hooks/useChatSend.test.ts @@ -5,8 +5,8 @@ import { attacksApi } from '@/services/api' import { deferred } from '@/test-utils/deferred' import { makeTarget } from '@/test-utils/targetFixtures' import type { - AttackSummary, ChatConverterController, ConversationMessagesResponse, Message, MessageSendStatus, PieceConversion, - RequestGenerationDraft, TargetCapabilities, TargetInstance, + AttackSummary, ChatConverterController, ConversationMessagesResponse, Message, MessageSendConversation, + MessageSendStatus, PieceConversion, RequestGenerationDraft, TargetCapabilities, TargetInstance, } from '@/types' import { PENDING_SEND_CONVERSATION_ID } from '@/utils/chatSendState' @@ -237,6 +237,41 @@ describe('useChatSend', () => { expect(result.current.tracking.isSending).toBe(true) }) + it('adopts repeated-send sibling conversations with their own locks and settles each', async () => { + const conversation = (conversationId: string): MessageSendConversation => ({ + conversation_id: conversationId, request_turn_number: 1, state: 'completed', error: null, failure_stage: null, + }) + api.submitMessageSend.mockResolvedValue({ + ...accepted('a'), count: 2, conversations: [conversation('a'), conversation('b')], + }) + const { result, callbacks } = renderSend() + + let outcome: unknown + await act(async () => { + outcome = await result.current.send.send('repeat me', undefined, [], { count: 2, requestConverterMode: 'shared' }) + }) + + expect(api.submitMessageSend).toHaveBeenCalledTimes(1) + expect(api.submitMessageSend).toHaveBeenCalledWith('attack', expect.objectContaining({ + count: 2, request_converter_mode: 'shared', + })) + // The source conversation settles its own outcome and may clear the draft. + expect(outcome).toEqual({ status: 'sent', clearDraft: true }) + // The sibling was adopted with its own lock and settled through its own evidence read. + expect(api.getMessages).toHaveBeenCalledWith('attack', 'a') + expect(api.getMessages).toHaveBeenCalledWith('attack', 'b') + expect(result.current.tracking.isSendInFlight('a')).toBe(false) + expect(result.current.tracking.isSendInFlight('b')).toBe(false) + expect(result.current.tracking.state.sending.size).toBe(0) + expect(callbacks.revealRepeatConversations).toHaveBeenCalled() + // The repeat view survives completion until dismissed. + expect(result.current.send.repeatSends).toEqual([ + expect.objectContaining({ needsRefresh: false, progress: expect.objectContaining({ send_id: 'send-a' }) }), + ]) + act(() => { result.current.send.dismissRepeatSend('send-a') }) + expect(result.current.send.repeatSends).toEqual([]) + }) + it('restores the optimistic prompt when the user returns to a conversation that is still sending', async () => { api.submitMessageSend.mockReturnValue(deferred().promise) const { result, view } = renderSend() diff --git a/frontend/src/hooks/useChatSend.ts b/frontend/src/hooks/useChatSend.ts index 50a8fbd24c..a849c64577 100644 --- a/frontend/src/hooks/useChatSend.ts +++ b/frontend/src/hooks/useChatSend.ts @@ -80,6 +80,7 @@ export interface UseChatSendStateOptions { export interface ChatSendTracking { readonly state: ChatSendState + /** The seam `useChatSend` drives. Other consumers read through the helpers below, never these two. */ readonly dispatch: Dispatch readonly locksRef: RefObject /** True while the active conversation (or, before one exists, any conversation) is sending. */