From 081e7fbf55b5a503c4c57744359dea8a529b0169 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Julio=20C=C3=A9sar=20Su=C3=A1stegui?= Date: Sun, 18 Oct 2026 09:05:23 -0600 Subject: [PATCH 1/2] MAINT: Extract score, objective and export into hooks --- frontend/src/components/Chat/ChatWindow.tsx | 148 +++--------- frontend/src/hooks/useAttackMutations.test.ts | 224 ++++++++++++++++++ frontend/src/hooks/useAttackMutations.ts | 128 ++++++++++ .../src/hooks/useConversationExport.test.ts | 89 +++++++ frontend/src/hooks/useConversationExport.ts | 53 +++++ 5 files changed, 533 insertions(+), 109 deletions(-) create mode 100644 frontend/src/hooks/useAttackMutations.test.ts create mode 100644 frontend/src/hooks/useAttackMutations.ts create mode 100644 frontend/src/hooks/useConversationExport.test.ts create mode 100644 frontend/src/hooks/useConversationExport.ts diff --git a/frontend/src/components/Chat/ChatWindow.tsx b/frontend/src/components/Chat/ChatWindow.tsx index 15e64f228c..48d341e55c 100644 --- a/frontend/src/components/Chat/ChatWindow.tsx +++ b/frontend/src/components/Chat/ChatWindow.tsx @@ -47,6 +47,8 @@ import { import { useConversationSave } from '@/hooks/useConversationSave' import { useConversationDraft } from '@/hooks/useConversationDraft' import { useConversationMessages } from '@/hooks/useConversationMessages' +import { useAttackMutations } from '@/hooks/useAttackMutations' +import { useConversationExport } from '@/hooks/useConversationExport' import type { PieceConversion } from './converterTypes' import { useChatConverters } from '@/hooks/useChatConverters' import { useRuntime } from '@/hooks/useRuntime' @@ -64,15 +66,13 @@ import { withDraftIdentity, } from './converterTypes' import type { ChatInputAreaHandle } from './ChatInputArea' -import { attacksApi, scoresApi } from '../../services/api' +import { attacksApi } from '../../services/api' import { toApiError } from '../../services/errors' import { buildMessagePieces, backendMessageToOriginalDraft, backendMessagesToFrontend, } from '../../utils/messageMapper' -import { exportConversation } from '../../utils/conversationExport' -import type { ExportFormat } from '../../utils/conversationExport' import type { AddMessageResponse, AttackOutcome, @@ -366,7 +366,6 @@ export default function ChatWindow({ const navigate = useNavigate() const [isFindingDialogOpen, setIsFindingDialogOpen] = useState(false) const outcomeButtonRef = useRef(null) - const [pendingObjective, setPendingObjective] = useState('') const [temperature, setTemperature] = useState('') const [temperatureExplanationAttackId, setTemperatureExplanationAttackId] = useState(null) const [temperatureAttackId, setTemperatureAttackId] = useState(attackResultId) @@ -374,7 +373,6 @@ export default function ChatWindow({ setTemperatureAttackId(attackResultId) setTemperature('') } - const currentObjective = attackResultId ? objective : pendingObjective const runtime = useRuntime() const newAttackContext: NewAttackContext = { generation: runtime.generation, ready: runtime.ready && defaultsReady, labels, operationId, @@ -411,8 +409,6 @@ export default function ChatWindow({ const [sendingConversations, setSendingConversations] = useState>(new Set()) const isSending = activeConversationId ? sendingConversations.has(activeConversationId) : Boolean(sendingConversations.size) const [isPanelOpen, setIsPanelOpen] = useState(false) - const [isExporting, setIsExporting] = useState(false) - const isExportingRef = useRef(false) const [isNarrowScreen, setIsNarrowScreen] = useState(matchesNarrowScreen) const [isConverterPanelOpen, setIsConverterPanelOpen] = useState(false) const launchStateRef = useRef({ generation: runtime.generation, ready: runtime.ready, defaultsReady }) @@ -625,6 +621,30 @@ export default function ChatWindow({ ) // Any failed invariant keeps all mutation controls and handlers read-only. const isMutationLocked = isOperatorLocked || isCrossTargetLocked || isTargetResolutionLocked || isEvidenceUnavailable + const isScoreLocked = isOperatorLocked || Boolean(isLoadingAttack) || isLoadingMessages + || awaitingConversationLoad || isEvidenceUnavailable + const { + pendingObjective, + currentObjective, + resetPendingObjective, + updateHumanScore, + removeHumanScore, + changeObjective, + } = useAttackMutations({ + attackResultId, + activeConversationId, + objective, + lastResponseMessagePieceId, + humanScore, + isScoreLocked, + isEditingDraft: editDraft !== null, + setEditorObjective, + loadConversation, + getViewedConversationId, + onHumanScoreChange, + onAttackChange, + onObjectiveChange, + }) // Clear internal messages when attack state is reset (e.g. New Attack). // Uses the "adjust state during render" pattern (see React docs: @@ -637,7 +657,7 @@ export default function ChatWindow({ setRecoverableSends({}) resetConversationMessages() setSystemPrompt('') - setPendingObjective('') + resetPendingObjective() } } @@ -648,8 +668,6 @@ export default function ChatWindow({ setSystemPrompt('') } - const isScoreLocked = isOperatorLocked || Boolean(isLoadingAttack) || isLoadingMessages - || awaitingConversationLoad || isEvidenceUnavailable const isFindingActionDisabled = Boolean(editDraft !== null || !attackResultId || !activeConversationId || isEvidenceUnavailable || isLoadingAttack || isLoadingMessages || awaitingConversationLoad) @@ -1443,71 +1461,6 @@ export default function ChatWindow({ isMutationLocked, ]) - const handleHumanScoreUpdate = useCallback(async (value: boolean, rationale: string): Promise => { - if ( - !attackResultId - || !lastResponseMessagePieceId - || !currentObjective.trim() - || isScoreLocked - ) { - return - } - - const score = await scoresApi.createManualScore({ - attack_result_id: attackResultId, - message_id: lastResponseMessagePieceId, - value, - rationale, - update_attack: true, - }) - onHumanScoreChange?.(score, value ? 'success' : 'failure') - if (activeConversationId && getViewedConversationId() === activeConversationId) { - await loadConversation(attackResultId, activeConversationId) - } - }, [ - activeConversationId, - attackResultId, - getViewedConversationId, - isScoreLocked, - lastResponseMessagePieceId, - loadConversation, - onHumanScoreChange, - currentObjective, - ]) - - const handleHumanScoreRemove = useCallback(async (): Promise => { - if (!attackResultId || !humanScore || isScoreLocked) return - - const attack = await attacksApi.removeHumanScore(attackResultId) - onHumanScoreChange?.(null, attack.outcome ?? 'undetermined') - if (activeConversationId && getViewedConversationId() === activeConversationId) { - await loadConversation(attackResultId, activeConversationId) - } - }, [ - activeConversationId, - attackResultId, - getViewedConversationId, - humanScore, - isScoreLocked, - loadConversation, - onHumanScoreChange, - ]) - - const handleAddObjective = useCallback(async (newObjective: string, expectedObjective: string): Promise => { - if (editDraft !== null) { - setEditorObjective(newObjective) - return - } - if (!attackResultId) { - setPendingObjective(newObjective) - return - } - - const updatedAttack = await attacksApi.updateAttack(attackResultId, { objective: newObjective, expected_objective: expectedObjective }) - onAttackChange?.(updatedAttack) - onObjectiveChange?.(updatedAttack.objective) - }, [attackResultId, onAttackChange, onObjectiveChange, editDraft, setEditorObjective]) - const beginEdit = async ( target: TargetInstance | null = activeTarget, ): Promise => { @@ -1850,34 +1803,11 @@ export default function ChatWindow({ const handleUseAsTemplate = (): void => { void beginEdit(defaultBranchTarget ?? activeTarget) } - // Export is available whenever there is a stable, viewable conversation: - // not while empty, loading, or mid-send. A lone system prompt (rendered only - // in the banner, not the chat body) does not count as an exportable message. - // Read-only / operator-lock / cross-target states do not block export. - const canExportConversation = - messages.some((message) => !message.isLoading && message.role !== 'system') && - !isSending && - !isLoadingAttack && - !isLoadingMessages && - !awaitingConversationLoad - - const handleExport = async (format: ExportFormat) => { - // A ref, not the state flag: two clicks in the same tick would both read - // the pre-render value and start duplicate exports. - if (isExportingRef.current) { - return - } - isExportingRef.current = true - setIsExporting(true) - try { - await exportConversation({ messages, conversationId: activeConversationId ?? conversationId, format }) - } catch (err) { - console.error('Failed to export conversation:', err) - } finally { - isExportingRef.current = false - setIsExporting(false) - } - } + const { canExport: canExportConversation, isExporting, exportAs } = useConversationExport({ + messages, + conversationId: activeConversationId ?? conversationId, + blocked: isSending || Boolean(isLoadingAttack) || isLoadingMessages || awaitingConversationLoad, + }) // Chat owns these handlers and states even when the layout hosts the controls. const toolbar = ( @@ -1981,16 +1911,16 @@ export default function ChatWindow({ handleExport('markdown')} + onClick={() => exportAs('markdown')} disabled={isExporting} data-testid="export-markdown-item" > Export as Markdown (.md) - handleExport('json')} disabled={isExporting} data-testid="export-json-item"> + exportAs('json')} disabled={isExporting} data-testid="export-json-item"> Export as JSON (.json) - handleExport('html')} disabled={isExporting} data-testid="export-html-item"> + exportAs('html')} disabled={isExporting} data-testid="export-html-item"> Export as HTML (.html) @@ -2090,8 +2020,8 @@ export default function ChatWindow({ && Boolean(humanScore) && !isScoreLocked } - onUpdateHumanScore={handleHumanScoreUpdate} - onRemoveHumanScore={handleHumanScoreRemove} + onUpdateHumanScore={updateHumanScore} + onRemoveHumanScore={removeHumanScore} canAdd={ !isSavingEditor && !isLoadingAttack @@ -2099,7 +2029,7 @@ export default function ChatWindow({ && !awaitingConversationLoad && (editDraft !== null || !isOperatorLocked) } - onAdd={handleAddObjective} + onAdd={changeObjective} onAddFinding={() => setIsFindingDialogOpen(true)} canAddFinding={!isFindingActionDisabled} outcomeButtonRef={outcomeButtonRef} diff --git a/frontend/src/hooks/useAttackMutations.test.ts b/frontend/src/hooks/useAttackMutations.test.ts new file mode 100644 index 0000000000..82972e391a --- /dev/null +++ b/frontend/src/hooks/useAttackMutations.test.ts @@ -0,0 +1,224 @@ +import { act, renderHook } from '@testing-library/react' + +import { attacksApi, scoresApi } from '@/services/api' +import type { AttackSummary, BackendScore } from '@/types' + +import { useAttackMutations } from './useAttackMutations' +import type { UseAttackMutationsOptions } from './useAttackMutations' + +jest.mock('@/services/api', () => ({ + attacksApi: { removeHumanScore: jest.fn(), updateAttack: jest.fn() }, + scoresApi: { createManualScore: jest.fn() }, +})) + +interface Deferred { + promise: Promise + resolve: (value: T) => void + reject: (cause: unknown) => void +} + +function deferred(): Deferred { + let resolve: (value: T) => void = () => {} + let reject: (cause: unknown) => void = () => {} + const promise = new Promise((onResolve, onReject) => { + resolve = onResolve + reject = onReject + }) + return { promise, resolve, reject } +} + +const attack: AttackSummary = { + attack_result_id: 'attack', conversation_id: 'main', attack_type: 'ManualAttack', objective: 'Updated objective', + converters: [], message_count: 2, related_conversation_ids: [], labels: {}, created_at: '', updated_at: '', +} +const score = { id: 'score' } as unknown as BackendScore + +function renderMutations(overrides: Partial = {}) { + const options: UseAttackMutationsOptions = { + attackResultId: 'attack', + activeConversationId: 'main', + objective: 'Objective', + lastResponseMessagePieceId: 'piece', + humanScore: score, + isScoreLocked: false, + isEditingDraft: false, + setEditorObjective: jest.fn(), + loadConversation: jest.fn().mockResolvedValue(undefined), + getViewedConversationId: () => 'main', + onHumanScoreChange: jest.fn(), + onAttackChange: jest.fn(), + onObjectiveChange: jest.fn(), + ...overrides, + } + return { options, ...renderHook((props: UseAttackMutationsOptions) => useAttackMutations(props), { initialProps: options }) } +} + +describe('useAttackMutations', () => { + beforeEach(() => jest.resetAllMocks()) + + describe('updateHumanScore', () => { + it('should send the exact manual score and reload the viewed conversation', async () => { + jest.mocked(scoresApi.createManualScore).mockResolvedValue(score) + const { result, options } = renderMutations() + + await act(async () => { await result.current.updateHumanScore(false, 'Refused') }) + + expect(scoresApi.createManualScore).toHaveBeenCalledWith({ + attack_result_id: 'attack', message_id: 'piece', value: false, rationale: 'Refused', update_attack: true, + }) + expect(options.onHumanScoreChange).toHaveBeenCalledWith(score, 'failure') + expect(options.loadConversation).toHaveBeenCalledWith('attack', 'main') + }) + + it('should skip the reload when the user navigated away while the score was saving', async () => { + const save = deferred() + jest.mocked(scoresApi.createManualScore).mockReturnValue(save.promise) + let viewed = 'main' + const { result, options } = renderMutations({ getViewedConversationId: () => viewed }) + + let pending: Promise = Promise.resolve() + act(() => { pending = result.current.updateHumanScore(true, 'Jailbroken') }) + viewed = 'branch' + await act(async () => { + save.resolve(score) + await pending + }) + + expect(options.onHumanScoreChange).toHaveBeenCalledWith(score, 'success') + expect(options.loadConversation).not.toHaveBeenCalled() + }) + + it.each([ + ['no attack', { attackResultId: null }], + ['no response piece', { lastResponseMessagePieceId: null }], + ['a blank objective', { objective: ' ' }], + ['a score lock', { isScoreLocked: true }], + ])('should not save a score with %s', async (_case: string, overrides: Partial) => { + const { result, options } = renderMutations(overrides) + + await act(async () => { await result.current.updateHumanScore(true, 'Rationale') }) + + expect(scoresApi.createManualScore).not.toHaveBeenCalled() + expect(options.onHumanScoreChange).not.toHaveBeenCalled() + }) + + it('should honor a score lock applied after the first render', async () => { + const { result, rerender, options } = renderMutations() + rerender({ ...options, isScoreLocked: true }) + + await act(async () => { await result.current.updateHumanScore(true, 'Rationale') }) + + expect(scoresApi.createManualScore).not.toHaveBeenCalled() + }) + + it('should propagate a failed save without reporting or reloading', async () => { + jest.mocked(scoresApi.createManualScore).mockRejectedValue(new Error('Save failed')) + const { result, options } = renderMutations() + + await act(async () => { + await expect(result.current.updateHumanScore(true, 'Rationale')).rejects.toThrow('Save failed') + }) + + expect(options.onHumanScoreChange).not.toHaveBeenCalled() + expect(options.loadConversation).not.toHaveBeenCalled() + }) + }) + + describe('removeHumanScore', () => { + it('should remove the score, fall back to an undetermined outcome and reload', async () => { + jest.mocked(attacksApi.removeHumanScore).mockResolvedValue({ ...attack, outcome: undefined }) + const { result, options } = renderMutations() + + await act(async () => { await result.current.removeHumanScore() }) + + expect(attacksApi.removeHumanScore).toHaveBeenCalledWith('attack') + expect(options.onHumanScoreChange).toHaveBeenCalledWith(null, 'undetermined') + expect(options.loadConversation).toHaveBeenCalledWith('attack', 'main') + }) + + it('should report the outcome the backend recalculated', async () => { + jest.mocked(attacksApi.removeHumanScore).mockResolvedValue({ ...attack, outcome: 'success' }) + const { result, options } = renderMutations({ getViewedConversationId: () => 'branch' }) + + await act(async () => { await result.current.removeHumanScore() }) + + expect(options.onHumanScoreChange).toHaveBeenCalledWith(null, 'success') + expect(options.loadConversation).not.toHaveBeenCalled() + }) + + it.each([ + ['no attack', { attackResultId: null }], + ['no human score', { humanScore: null }], + ['a score lock', { isScoreLocked: true }], + ])('should not remove a score with %s', async (_case: string, overrides: Partial) => { + const { result } = renderMutations(overrides) + + await act(async () => { await result.current.removeHumanScore() }) + + expect(attacksApi.removeHumanScore).not.toHaveBeenCalled() + }) + + it('should propagate a failed removal without reporting', async () => { + jest.mocked(attacksApi.removeHumanScore).mockRejectedValue(new Error('Remove failed')) + const { result, options } = renderMutations() + + await act(async () => { await expect(result.current.removeHumanScore()).rejects.toThrow('Remove failed') }) + + expect(options.onHumanScoreChange).not.toHaveBeenCalled() + }) + }) + + describe('changeObjective', () => { + it('should send the exact objective update and report the attack before the objective', async () => { + jest.mocked(attacksApi.updateAttack).mockResolvedValue(attack) + const calls: string[] = [] + const { result } = renderMutations({ + onAttackChange: () => { calls.push('attack') }, + onObjectiveChange: (objective: string) => { calls.push(`objective:${objective}`) }, + }) + + await act(async () => { await result.current.changeObjective('New objective', 'Objective') }) + + expect(attacksApi.updateAttack).toHaveBeenCalledWith('attack', { + objective: 'New objective', expected_objective: 'Objective', + }) + expect(calls).toEqual(['attack', 'objective:Updated objective']) + }) + + it('should send the objective to the editor while a draft is open', async () => { + const { result, options } = renderMutations({ isEditingDraft: true }) + + await act(async () => { await result.current.changeObjective('Draft objective', 'Objective') }) + + expect(options.setEditorObjective).toHaveBeenCalledWith('Draft objective') + expect(attacksApi.updateAttack).not.toHaveBeenCalled() + }) + + it('should keep a pending objective until the attack exists and clear it on reset', async () => { + const { result, rerender, options } = renderMutations({ attackResultId: null }) + + await act(async () => { await result.current.changeObjective('Pending objective', '') }) + expect(result.current.pendingObjective).toBe('Pending objective') + expect(result.current.currentObjective).toBe('Pending objective') + expect(attacksApi.updateAttack).not.toHaveBeenCalled() + + rerender({ ...options, attackResultId: 'attack' }) + expect(result.current.currentObjective).toBe('Objective') + + act(() => { result.current.resetPendingObjective() }) + expect(result.current.pendingObjective).toBe('') + }) + + it('should propagate a conflicting objective update without reporting', async () => { + jest.mocked(attacksApi.updateAttack).mockRejectedValue(new Error('Conflict')) + const { result, options } = renderMutations() + + await act(async () => { + await expect(result.current.changeObjective('New objective', 'Stale')).rejects.toThrow('Conflict') + }) + + expect(options.onAttackChange).not.toHaveBeenCalled() + expect(options.onObjectiveChange).not.toHaveBeenCalled() + }) + }) +}) diff --git a/frontend/src/hooks/useAttackMutations.ts b/frontend/src/hooks/useAttackMutations.ts new file mode 100644 index 0000000000..92b5705329 --- /dev/null +++ b/frontend/src/hooks/useAttackMutations.ts @@ -0,0 +1,128 @@ +import { useCallback, useState } from 'react' + +import { attacksApi, scoresApi } from '@/services/api' +import type { AttackOutcome, AttackSummary, BackendScore } from '@/types' + +export interface UseAttackMutationsOptions { + attackResultId: string | null + activeConversationId: string | null + /** The loaded attack's objective. */ + objective: string + lastResponseMessagePieceId?: string | null + humanScore?: BackendScore | null + isScoreLocked: boolean + /** Objective changes go to the conversation editor while it is open. */ + isEditingDraft: boolean + setEditorObjective: (objective: string) => void + loadConversation: (attackResultId: string, conversationId: string) => Promise + getViewedConversationId: () => string | null + onHumanScoreChange?: (score: BackendScore | null, outcome: AttackOutcome) => void + onAttackChange?: (attack: AttackSummary) => void + onObjectiveChange?: (objective: string) => void +} + +export interface AttackMutations { + /** Objective typed before the first send creates the attack. */ + pendingObjective: string + currentObjective: string + /** Clears the pending objective when the attack is reset; safe to call while rendering. */ + resetPendingObjective: () => void + updateHumanScore: (value: boolean, rationale: string) => Promise + removeHumanScore: () => Promise + changeObjective: (objective: string, expectedObjective: string) => Promise +} + +export function useAttackMutations({ + attackResultId, + activeConversationId, + objective, + lastResponseMessagePieceId, + humanScore, + isScoreLocked, + isEditingDraft, + setEditorObjective, + loadConversation, + getViewedConversationId, + onHumanScoreChange, + onAttackChange, + onObjectiveChange, +}: UseAttackMutationsOptions): AttackMutations { + const [pendingObjective, setPendingObjective] = useState('') + const currentObjective = attackResultId ? objective : pendingObjective + + const resetPendingObjective = useCallback((): void => { setPendingObjective('') }, []) + + const updateHumanScore = useCallback(async (value: boolean, rationale: string): Promise => { + if ( + !attackResultId + || !lastResponseMessagePieceId + || !currentObjective.trim() + || isScoreLocked + ) { + return + } + + const score = await scoresApi.createManualScore({ + attack_result_id: attackResultId, + message_id: lastResponseMessagePieceId, + value, + rationale, + update_attack: true, + }) + onHumanScoreChange?.(score, value ? 'success' : 'failure') + if (activeConversationId && getViewedConversationId() === activeConversationId) { + await loadConversation(attackResultId, activeConversationId) + } + }, [ + activeConversationId, + attackResultId, + getViewedConversationId, + isScoreLocked, + lastResponseMessagePieceId, + loadConversation, + onHumanScoreChange, + currentObjective, + ]) + + const removeHumanScore = useCallback(async (): Promise => { + if (!attackResultId || !humanScore || isScoreLocked) return + + const attack = await attacksApi.removeHumanScore(attackResultId) + onHumanScoreChange?.(null, attack.outcome ?? 'undetermined') + if (activeConversationId && getViewedConversationId() === activeConversationId) { + await loadConversation(attackResultId, activeConversationId) + } + }, [ + activeConversationId, + attackResultId, + getViewedConversationId, + humanScore, + isScoreLocked, + loadConversation, + onHumanScoreChange, + ]) + + const changeObjective = useCallback(async (newObjective: string, expectedObjective: string): Promise => { + if (isEditingDraft) { + setEditorObjective(newObjective) + return + } + if (!attackResultId) { + setPendingObjective(newObjective) + return + } + + const updatedAttack = await attacksApi.updateAttack(attackResultId, { objective: newObjective, expected_objective: expectedObjective }) + onAttackChange?.(updatedAttack) + onObjectiveChange?.(updatedAttack.objective) + }, [attackResultId, onAttackChange, onObjectiveChange, isEditingDraft, setEditorObjective]) + + return { + pendingObjective, + currentObjective, + resetPendingObjective, + updateHumanScore, + removeHumanScore, + changeObjective, + } +} diff --git a/frontend/src/hooks/useConversationExport.test.ts b/frontend/src/hooks/useConversationExport.test.ts new file mode 100644 index 0000000000..2aee95fb76 --- /dev/null +++ b/frontend/src/hooks/useConversationExport.test.ts @@ -0,0 +1,89 @@ +import { act, renderHook } from '@testing-library/react' + +import type { Message } from '@/types' +import { exportConversation } from '@/utils/conversationExport' + +import { useConversationExport } from './useConversationExport' +import type { UseConversationExportOptions } from './useConversationExport' + +jest.mock('@/utils/conversationExport', () => ({ exportConversation: jest.fn() })) + +const userMessage: Message = { role: 'user', content: 'Prompt', timestamp: '' } + +function renderExport(overrides: Partial = {}) { + return renderHook( + (props: UseConversationExportOptions) => useConversationExport(props), + { initialProps: { messages: [userMessage], conversationId: 'main', blocked: false, ...overrides } }, + ) +} + +describe('useConversationExport', () => { + beforeEach(() => jest.resetAllMocks()) + afterEach(() => jest.restoreAllMocks()) + + describe('canExport', () => { + it.each([ + ['an empty transcript', [], false], + ['only a loading placeholder', [{ role: 'assistant', content: '...', timestamp: '', isLoading: true }], false], + ['only a system prompt', [{ role: 'system', content: 'System', timestamp: '' }], false], + ['a user message', [userMessage], true], + ])('should report %s as exportable: %s', (_case: string, messages: Message[], expected: boolean) => { + const { result } = renderExport({ messages }) + expect(result.current.canExport).toBe(expected) + }) + + it('should be false while the transcript is blocked', () => { + const { result } = renderExport({ blocked: true }) + expect(result.current.canExport).toBe(false) + }) + }) + + it('should export the displayed messages and conversation in the chosen format', async () => { + jest.mocked(exportConversation).mockResolvedValue(undefined) + const { result } = renderExport({ conversationId: 'branch' }) + + await act(async () => { await result.current.exportAs('html') }) + + expect(exportConversation).toHaveBeenCalledWith({ messages: [userMessage], conversationId: 'branch', format: 'html' }) + expect(result.current.isExporting).toBe(false) + }) + + it('should ignore a second export requested in the same tick and allow one after it finishes', async () => { + let finish: () => void = () => {} + jest.mocked(exportConversation).mockImplementationOnce(() => new Promise((resolve) => { finish = resolve })) + const { result } = renderExport() + + let first: Promise = Promise.resolve() + act(() => { + first = result.current.exportAs('markdown') + void result.current.exportAs('json') + }) + expect(exportConversation).toHaveBeenCalledTimes(1) + expect(result.current.isExporting).toBe(true) + + await act(async () => { + finish() + await first + }) + expect(result.current.isExporting).toBe(false) + + jest.mocked(exportConversation).mockResolvedValueOnce(undefined) + await act(async () => { await result.current.exportAs('json') }) + expect(exportConversation).toHaveBeenCalledTimes(2) + expect(exportConversation).toHaveBeenLastCalledWith(expect.objectContaining({ format: 'json' })) + }) + + it('should log a failed export and release the lock', async () => { + const error = new Error('Download failed') + const consoleError = jest.spyOn(console, 'error').mockImplementation(() => {}) + jest.mocked(exportConversation).mockRejectedValueOnce(error).mockResolvedValueOnce(undefined) + const { result } = renderExport() + + await act(async () => { await result.current.exportAs('markdown') }) + expect(consoleError).toHaveBeenCalledWith('Failed to export conversation:', error) + expect(result.current.isExporting).toBe(false) + + await act(async () => { await result.current.exportAs('markdown') }) + expect(exportConversation).toHaveBeenCalledTimes(2) + }) +}) diff --git a/frontend/src/hooks/useConversationExport.ts b/frontend/src/hooks/useConversationExport.ts new file mode 100644 index 0000000000..ea2e005075 --- /dev/null +++ b/frontend/src/hooks/useConversationExport.ts @@ -0,0 +1,53 @@ +import { useCallback, useRef, useState } from 'react' + +import type { Message } from '@/types' +import { exportConversation } from '@/utils/conversationExport' +import type { ExportFormat } from '@/utils/conversationExport' + +export interface UseConversationExportOptions { + messages: Message[] + conversationId: string | null + /** True while the transcript is not stable: sending or loading. */ + blocked: boolean +} + +export interface ConversationExport { + canExport: boolean + isExporting: boolean + exportAs: (format: ExportFormat) => Promise +} + +export function useConversationExport({ + messages, + conversationId, + blocked, +}: UseConversationExportOptions): ConversationExport { + const [isExporting, setIsExporting] = useState(false) + const isExportingRef = useRef(false) + + // Export is available whenever there is a stable, viewable conversation: + // not while empty, loading, or mid-send. A lone system prompt (rendered only + // in the banner, not the chat body) does not count as an exportable message. + // Read-only / operator-lock / cross-target states do not block export. + const canExport = messages.some((message) => !message.isLoading && message.role !== 'system') && !blocked + + const exportAs = useCallback(async (format: ExportFormat): Promise => { + // A ref, not the state flag: two clicks in the same tick would both read + // the pre-render value and start duplicate exports. + if (isExportingRef.current) { + return + } + isExportingRef.current = true + setIsExporting(true) + try { + await exportConversation({ messages, conversationId, format }) + } catch (err) { + console.error('Failed to export conversation:', err) + } finally { + isExportingRef.current = false + setIsExporting(false) + } + }, [messages, conversationId]) + + return { canExport, isExporting, exportAs } +} From cf143a00cfd172ad20644890cd539467c332e222 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Julio=20C=C3=A9sar=20Su=C3=A1stegui?= Date: Sun, 18 Oct 2026 12:46:32 -0600 Subject: [PATCH 2/2] MAINT: Keep editor objective routing in ChatWindow and share deferred test helper --- frontend/src/components/Chat/ChatWindow.tsx | 12 ++++++-- frontend/src/hooks/useAttackMutations.test.ts | 28 +------------------ frontend/src/hooks/useAttackMutations.ts | 11 +------- frontend/src/hooks/useConversationExport.ts | 6 ++-- .../src/hooks/useConversationMessages.test.ts | 17 +---------- frontend/src/test-utils/deferred.ts | 16 +++++++++++ 6 files changed, 31 insertions(+), 59 deletions(-) create mode 100644 frontend/src/test-utils/deferred.ts diff --git a/frontend/src/components/Chat/ChatWindow.tsx b/frontend/src/components/Chat/ChatWindow.tsx index 48d341e55c..7fd7ef997c 100644 --- a/frontend/src/components/Chat/ChatWindow.tsx +++ b/frontend/src/components/Chat/ChatWindow.tsx @@ -637,8 +637,6 @@ export default function ChatWindow({ lastResponseMessagePieceId, humanScore, isScoreLocked, - isEditingDraft: editDraft !== null, - setEditorObjective, loadConversation, getViewedConversationId, onHumanScoreChange, @@ -1461,6 +1459,14 @@ export default function ChatWindow({ isMutationLocked, ]) + const handleAddObjective = useCallback(async (newObjective: string, expectedObjective: string): Promise => { + if (editDraft !== null) { + setEditorObjective(newObjective) + return + } + await changeObjective(newObjective, expectedObjective) + }, [changeObjective, editDraft, setEditorObjective]) + const beginEdit = async ( target: TargetInstance | null = activeTarget, ): Promise => { @@ -2029,7 +2035,7 @@ export default function ChatWindow({ && !awaitingConversationLoad && (editDraft !== null || !isOperatorLocked) } - onAdd={changeObjective} + onAdd={handleAddObjective} onAddFinding={() => setIsFindingDialogOpen(true)} canAddFinding={!isFindingActionDisabled} outcomeButtonRef={outcomeButtonRef} diff --git a/frontend/src/hooks/useAttackMutations.test.ts b/frontend/src/hooks/useAttackMutations.test.ts index 82972e391a..5fc85dea79 100644 --- a/frontend/src/hooks/useAttackMutations.test.ts +++ b/frontend/src/hooks/useAttackMutations.test.ts @@ -1,6 +1,7 @@ import { act, renderHook } from '@testing-library/react' import { attacksApi, scoresApi } from '@/services/api' +import { deferred } from '@/test-utils/deferred' import type { AttackSummary, BackendScore } from '@/types' import { useAttackMutations } from './useAttackMutations' @@ -11,22 +12,6 @@ jest.mock('@/services/api', () => ({ scoresApi: { createManualScore: jest.fn() }, })) -interface Deferred { - promise: Promise - resolve: (value: T) => void - reject: (cause: unknown) => void -} - -function deferred(): Deferred { - let resolve: (value: T) => void = () => {} - let reject: (cause: unknown) => void = () => {} - const promise = new Promise((onResolve, onReject) => { - resolve = onResolve - reject = onReject - }) - return { promise, resolve, reject } -} - const attack: AttackSummary = { attack_result_id: 'attack', conversation_id: 'main', attack_type: 'ManualAttack', objective: 'Updated objective', converters: [], message_count: 2, related_conversation_ids: [], labels: {}, created_at: '', updated_at: '', @@ -41,8 +26,6 @@ function renderMutations(overrides: Partial = {}) { lastResponseMessagePieceId: 'piece', humanScore: score, isScoreLocked: false, - isEditingDraft: false, - setEditorObjective: jest.fn(), loadConversation: jest.fn().mockResolvedValue(undefined), getViewedConversationId: () => 'main', onHumanScoreChange: jest.fn(), @@ -185,15 +168,6 @@ describe('useAttackMutations', () => { expect(calls).toEqual(['attack', 'objective:Updated objective']) }) - it('should send the objective to the editor while a draft is open', async () => { - const { result, options } = renderMutations({ isEditingDraft: true }) - - await act(async () => { await result.current.changeObjective('Draft objective', 'Objective') }) - - expect(options.setEditorObjective).toHaveBeenCalledWith('Draft objective') - expect(attacksApi.updateAttack).not.toHaveBeenCalled() - }) - it('should keep a pending objective until the attack exists and clear it on reset', async () => { const { result, rerender, options } = renderMutations({ attackResultId: null }) diff --git a/frontend/src/hooks/useAttackMutations.ts b/frontend/src/hooks/useAttackMutations.ts index 92b5705329..f61066eb36 100644 --- a/frontend/src/hooks/useAttackMutations.ts +++ b/frontend/src/hooks/useAttackMutations.ts @@ -11,9 +11,6 @@ export interface UseAttackMutationsOptions { lastResponseMessagePieceId?: string | null humanScore?: BackendScore | null isScoreLocked: boolean - /** Objective changes go to the conversation editor while it is open. */ - isEditingDraft: boolean - setEditorObjective: (objective: string) => void loadConversation: (attackResultId: string, conversationId: string) => Promise getViewedConversationId: () => string | null onHumanScoreChange?: (score: BackendScore | null, outcome: AttackOutcome) => void @@ -39,8 +36,6 @@ export function useAttackMutations({ lastResponseMessagePieceId, humanScore, isScoreLocked, - isEditingDraft, - setEditorObjective, loadConversation, getViewedConversationId, onHumanScoreChange, @@ -103,10 +98,6 @@ export function useAttackMutations({ ]) const changeObjective = useCallback(async (newObjective: string, expectedObjective: string): Promise => { - if (isEditingDraft) { - setEditorObjective(newObjective) - return - } if (!attackResultId) { setPendingObjective(newObjective) return @@ -115,7 +106,7 @@ export function useAttackMutations({ const updatedAttack = await attacksApi.updateAttack(attackResultId, { objective: newObjective, expected_objective: expectedObjective }) onAttackChange?.(updatedAttack) onObjectiveChange?.(updatedAttack.objective) - }, [attackResultId, onAttackChange, onObjectiveChange, isEditingDraft, setEditorObjective]) + }, [attackResultId, onAttackChange, onObjectiveChange]) return { pendingObjective, diff --git a/frontend/src/hooks/useConversationExport.ts b/frontend/src/hooks/useConversationExport.ts index ea2e005075..81dc9712ca 100644 --- a/frontend/src/hooks/useConversationExport.ts +++ b/frontend/src/hooks/useConversationExport.ts @@ -1,4 +1,4 @@ -import { useCallback, useRef, useState } from 'react' +import { useRef, useState } from 'react' import type { Message } from '@/types' import { exportConversation } from '@/utils/conversationExport' @@ -31,7 +31,7 @@ export function useConversationExport({ // Read-only / operator-lock / cross-target states do not block export. const canExport = messages.some((message) => !message.isLoading && message.role !== 'system') && !blocked - const exportAs = useCallback(async (format: ExportFormat): Promise => { + const exportAs = async (format: ExportFormat): Promise => { // A ref, not the state flag: two clicks in the same tick would both read // the pre-render value and start duplicate exports. if (isExportingRef.current) { @@ -47,7 +47,7 @@ export function useConversationExport({ isExportingRef.current = false setIsExporting(false) } - }, [messages, conversationId]) + } return { canExport, isExporting, exportAs } } diff --git a/frontend/src/hooks/useConversationMessages.test.ts b/frontend/src/hooks/useConversationMessages.test.ts index cdb1d91732..5f450a4ab3 100644 --- a/frontend/src/hooks/useConversationMessages.test.ts +++ b/frontend/src/hooks/useConversationMessages.test.ts @@ -1,6 +1,7 @@ import { act, renderHook, waitFor } from '@testing-library/react' import { attacksApi } from '@/services/api' +import { deferred } from '@/test-utils/deferred' import type { BackendMessage, ConversationMessagesResponse, Message } from '@/types' import { backendMessagesToFrontend } from '@/utils/messageMapper' @@ -10,22 +11,6 @@ import type { UseConversationMessagesOptions } from './useConversationMessages' jest.mock('@/services/api', () => ({ attacksApi: { getMessages: jest.fn() } })) jest.mock('@/utils/messageMapper', () => ({ backendMessagesToFrontend: jest.fn() })) -interface Deferred { - promise: Promise - resolve: (value: T) => void - reject: (cause: unknown) => void -} - -function deferred(): Deferred { - let resolve: (value: T) => void = () => {} - let reject: (cause: unknown) => void = () => {} - const promise = new Promise((onResolve, onReject) => { - resolve = onResolve - reject = onReject - }) - return { promise, resolve, reject } -} - function transcript(conversationId: string, turns: number[] = [1]): ConversationMessagesResponse { return { conversation_id: conversationId, diff --git a/frontend/src/test-utils/deferred.ts b/frontend/src/test-utils/deferred.ts new file mode 100644 index 0000000000..6ec287c3eb --- /dev/null +++ b/frontend/src/test-utils/deferred.ts @@ -0,0 +1,16 @@ +export interface Deferred { + promise: Promise + resolve: (value: T) => void + reject: (cause: unknown) => void +} + +/** A promise plus the functions that settle it, for holding async work mid-flight in tests. */ +export function deferred(): Deferred { + let resolve!: (value: T) => void + let reject!: (cause: unknown) => void + const promise = new Promise((onResolve, onReject) => { + resolve = onResolve + reject = onReject + }) + return { promise, resolve, reject } +}