diff --git a/frontend/README.md b/frontend/README.md
index c58e517b91..e1fc9c7324 100644
--- a/frontend/README.md
+++ b/frontend/README.md
@@ -54,6 +54,12 @@ the source conversation. New outgoing turns are always converted.
## Dataset catalog
+Chat drafts stay in memory while you visit Datasets and return. Text, attachments,
+system prompts, the selected target, and converter setup/results return to their
+original attack and conversation. A loading, missing, or read-only destination
+does not consume the draft. Starting a new attack or leaving the Chat/Datasets
+journey discards the handoff; refreshing the browser does not retain it.
+
The **Datasets** page shows summaries of datasets already loaded into the backend's
memory. When memory is empty, **Learn how to load datasets into memory** opens the
[dataset-loading guide](https://microsoft.github.io/PyRIT/latest/code/datasets/loading-datasets/).
diff --git a/frontend/src/App.drafts.test.tsx b/frontend/src/App.drafts.test.tsx
new file mode 100644
index 0000000000..731215a3b8
--- /dev/null
+++ b/frontend/src/App.drafts.test.tsx
@@ -0,0 +1,680 @@
+import { StrictMode, type ReactNode } from 'react'
+
+import { act, render, screen, waitFor } from '@testing-library/react'
+import userEvent, { type UserEvent } from '@testing-library/user-event'
+import { createMemoryRouter, MemoryRouter } from 'react-router'
+import { RouterProvider } from 'react-router/dom'
+
+import { attacksApi, convertersApi, runtimeApi, targetsApi } from '@/services/api'
+import { deferred } from '@/test-utils/deferred'
+import { makeTarget } from '@/test-utils/targetFixtures'
+import { installRouterTestRequest } from '@/test-utils/routerRequest'
+import type { AttackSummary, BackendMessage, ConverterInstance, ConverterPreviewResponse } from '@/types'
+import { targetReference } from '@/utils/targetIdentity'
+import { DEFAULT_USER_PREFERENCES, writeUserPreferences } from '@/utils/userPreferences'
+
+import App from './App'
+
+jest.mock('@azure/msal-react', () => ({
+ useMsal: () => ({ instance: { getActiveAccount: () => null, getAllAccounts: () => [] } }),
+}))
+jest.mock('react-joyride', () => ({ Joyride: () => null }))
+jest.mock('@/hooks/useTour', () => ({
+ useTour: () => ({ startTour: jest.fn(), tourProps: {} }),
+}))
+jest.mock('@/hooks/useScorerRegistry', () => ({
+ useScorerRegistry: () => ({ scorers: [], loading: false, error: null }),
+}))
+jest.mock('@/hooks/useConnectionHealth', () => ({
+ ConnectionHealthProvider: ({ children }: { children: ReactNode }) => children,
+ useConnectionHealth: () => ({ status: 'connected', reconnectCount: 0 }),
+}))
+jest.mock('@/components/Datasets/DatasetCatalog', () => ({
+ __esModule: true,
+ default: () =>
Dataset catalog
,
+}))
+jest.mock('@/components/Layout/MainLayout', () => {
+ const { useNavigate, useLocation } = jest.requireActual('react-router')
+ const { useChatDraftHandoff } = jest.requireActual('@/hooks/useChatDraftHandoff')
+ return {
+ __esModule: true,
+ default: function DraftTestLayout({ children, onNavigate }: { children: ReactNode; onNavigate: (view: string) => void }) {
+ const navigate = useNavigate()
+ const location = useLocation()
+ const handoff = useChatDraftHandoff()
+ return <>
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {children}
+ >
+ },
+ }
+})
+jest.mock('@/services/api', () => ({
+ runtimeApi: { getReadiness: jest.fn().mockResolvedValue({ ready: true, state: 'ready', generation: '' }) },
+ versionApi: { getVersion: jest.fn().mockResolvedValue({ version: 'test' }) },
+ authApi: { getAccess: jest.fn().mockResolvedValue({ isAdmin: false }) },
+ targetsApi: { listTargets: jest.fn(), getTarget: jest.fn() },
+ attacksApi: {
+ createAttack: jest.fn(),
+ getAttack: jest.fn(),
+ getMessages: jest.fn(),
+ getConversations: jest.fn(),
+ saveConversation: jest.fn(),
+ submitMessageSend: jest.fn(),
+ },
+ convertersApi: {
+ listConverters: jest.fn(),
+ listConverterTypes: jest.fn().mockResolvedValue({ items: [] }),
+ previewConversion: jest.fn(),
+ },
+ labelsApi: { getLabels: jest.fn().mockResolvedValue({ labels: {} }) },
+ datasetsApi: {
+ listDatasets: jest.fn().mockResolvedValue({ items: [{
+ name: 'Example dataset', selection_key: 'example-dataset',
+ loaded: true, provider_available: true, logical_examples: 2, seed_pieces: 2, objectives: 0,
+ modalities: ['text'], harm_categories: [], has_unlabeled_harm_categories: true,
+ }] }),
+ listSeedExamples: jest.fn().mockResolvedValue({
+ items: [], total: 2, pagination: { limit: 20, has_more: false, next_cursor: null, prev_cursor: null },
+ }),
+ },
+}))
+
+const TARGET = makeTarget({
+ target_registry_name: 'draft-target',
+ capabilities: {
+ supports_multi_turn: true,
+ supports_multi_message_pieces: true,
+ supports_json_schema: false,
+ supports_json_output: false,
+ supports_system_prompt: true,
+ supported_input_modalities: ['text', 'image_path', 'audio_path', 'video_path'],
+ supported_output_modalities: ['text'],
+ },
+})
+const CONVERTER: ConverterInstance = {
+ converter_id: 'draft-converter',
+ identifier: {
+ class_name: 'Base64Converter', class_module: 'pyrit.converter', hash: 'converter-hash',
+ pyrit_version: 'test', supported_input_types: ['text'], supported_output_types: ['text'],
+ },
+}
+
+function convertedText(value = 'Converted text', original = 'Original text'): ConverterPreviewResponse {
+ return {
+ original_value: original, original_value_data_type: 'text',
+ converted_value: value, converted_value_data_type: 'text',
+ steps: [{
+ converter_id: CONVERTER.converter_id, converter_type: 'Base64Converter',
+ input_value: original, input_data_type: 'text',
+ output_value: value, output_data_type: 'text',
+ }],
+ }
+}
+
+function savedAttack(id = 'saved'): AttackSummary {
+ return {
+ attack_result_id: id, conversation_id: 'main', attack_type: 'ManualAttack',
+ objective: '', converters: [], message_count: 0, labels: {}, operator: null,
+ related_conversation_ids: ['branch'], target: null, target_unbound: true,
+ created_at: '', updated_at: '',
+ }
+}
+
+function renderChat(path = '/chat', strict = false): ReturnType {
+ const router = createMemoryRouter([{ path: '*', element: }], { initialEntries: [path] })
+ const app =
+ return render(strict ? {app} : app)
+}
+
+async function visitDatasets(user: UserEvent): Promise {
+ await user.click(screen.getByRole('button', { name: 'Datasets', exact: true }))
+ await screen.findByRole('heading', { name: 'Dataset catalog' })
+}
+
+async function returnToChat(user: UserEvent): Promise {
+ await user.click(screen.getByRole('button', { name: 'Chat', exact: true }))
+ await waitFor(() => expect(screen.getByPlaceholderText('Type prompt here')).toBeEnabled())
+}
+
+async function addConverter(user: UserEvent): Promise {
+ await user.click(screen.getByRole('button', { name: 'Toggle converter panel' }))
+ await user.click(await screen.findByRole('combobox', { name: 'Add converter' }))
+ await user.click(await screen.findByRole('option', { name: /draft-converter/ }))
+}
+
+describe('App draft handoff with the real chat and composer', () => {
+ let restoreRequest: () => void
+ beforeAll(() => { restoreRequest = installRouterTestRequest() })
+ afterAll(() => { restoreRequest() })
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ window.localStorage.clear()
+ jest.mocked(runtimeApi.getReadiness).mockResolvedValue({ ready: true, state: 'ready', generation: '' })
+ jest.mocked(targetsApi.listTargets).mockResolvedValue({
+ items: [TARGET], pagination: { limit: 200, has_more: false },
+ })
+ jest.mocked(targetsApi.getTarget).mockResolvedValue(TARGET)
+ jest.mocked(attacksApi.getAttack).mockImplementation(async (id: string) => savedAttack(id))
+ jest.mocked(attacksApi.getMessages).mockImplementation(async (_id: string, conversationId: string) => ({
+ conversation_id: conversationId, messages: [], target_response_status: null,
+ }))
+ jest.mocked(attacksApi.getConversations).mockResolvedValue({ conversations: [], main_conversation_id: 'main' })
+ jest.mocked(convertersApi.listConverters).mockResolvedValue({ items: [CONVERTER] })
+ jest.mocked(convertersApi.previewConversion).mockResolvedValue(convertedText())
+ })
+
+ afterEach(() => { jest.useRealTimers() })
+
+ it.each([false, true])('should preserve an unsaved draft across repeated visits with StrictMode=%s', async (strict: boolean) => {
+ const user = userEvent.setup()
+ renderChat('/chat', strict)
+ await user.type(await screen.findByPlaceholderText('Type prompt here'), 'Unsent prompt')
+ for (let visit = 0; visit < 2; visit += 1) {
+ await visitDatasets(user)
+ await returnToChat(user)
+ expect(screen.getByPlaceholderText('Type prompt here')).toHaveValue('Unsent prompt')
+ }
+ })
+
+ it('should restore a saved conversation only after its attack and transcript load', async () => {
+ const user = userEvent.setup()
+ renderChat('/attacks/saved/conversations/branch')
+ await waitFor(() => expect(screen.getByPlaceholderText('Type prompt here')).toBeEnabled())
+ await user.type(screen.getByPlaceholderText('Type prompt here'), 'Saved attack draft')
+ await user.upload(screen.getByTestId('file-input'), new File(['image'], 'draft.png', { type: 'image/png' }))
+ const url = jest.mocked(URL.createObjectURL).mock.results[0].value
+ await visitDatasets(user)
+ const attackLoad = deferred()
+ jest.mocked(attacksApi.getAttack).mockReturnValueOnce(attackLoad.promise)
+ await user.click(screen.getByRole('button', { name: 'Chat', exact: true }))
+ expect(screen.queryByDisplayValue('Saved attack draft')).not.toBeInTheDocument()
+ await act(async () => { attackLoad.resolve(savedAttack()) })
+ await waitFor(() => expect(screen.getByPlaceholderText('Type prompt here')).toBeEnabled())
+ expect(screen.getByLabelText('Current route')).toHaveTextContent('/attacks/saved/conversations/branch')
+ expect(screen.getByPlaceholderText('Type prompt here')).toHaveValue('Saved attack draft')
+ expect(screen.getByRole('button', { name: 'Remove draft.png' })).toBeInTheDocument()
+ expect(URL.revokeObjectURL).not.toHaveBeenCalledWith(url)
+ })
+
+ it('should keep the historical conversation shell mounted while metadata loads', async () => {
+ const attackLoad = deferred()
+ jest.mocked(attacksApi.getAttack).mockReturnValueOnce(attackLoad.promise)
+ renderChat('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/attacks/saved')
+ const toggle = await screen.findByTestId('toggle-panel-btn')
+ expect(toggle).toBeDisabled()
+ expect(screen.getByText('Loading conversation...', { exact: true })).toBeInTheDocument()
+ expect(screen.getByPlaceholderText('Type prompt here')).toBeDisabled()
+ await act(async () => { attackLoad.resolve(savedAttack()) })
+ await waitFor(() => expect(screen.getByPlaceholderText('Type prompt here')).toBeEnabled())
+ expect(screen.getByTestId('toggle-panel-btn')).toBe(toggle)
+ })
+
+ it('should retain a recovered failed prompt while branching to a new attack', async () => {
+ const originalValue = 'Restore this failed prompt'
+ const failedMessages: BackendMessage[] = [{
+ role: 'user', turn_number: 0, created_at: '',
+ message_pieces: [{
+ id: 'failed-prompt', original_value_data_type: 'text', original_value: originalValue,
+ converted_value_data_type: 'text', converted_value: originalValue, scores: [], response_error: 'none',
+ }],
+ }, {
+ role: 'assistant', turn_number: 1, created_at: '',
+ message_pieces: [{
+ id: 'failed-response', original_value_data_type: 'text', original_value: '',
+ converted_value_data_type: 'text', converted_value: '', scores: [], response_error: 'processing',
+ response_error_description: 'The target could not process this message.',
+ }],
+ }]
+ jest.mocked(attacksApi.createAttack).mockResolvedValue({
+ attack_result_id: 'recovered', conversation_id: 'recovered-main', created_at: '',
+ })
+ jest.mocked(attacksApi.getAttack).mockImplementation(async (id: string) => ({
+ ...savedAttack(id),
+ conversation_id: id === 'recovered' ? 'recovered-main' : 'main',
+ target_unbound: false,
+ target: {
+ target_type: TARGET.identifier.class_name,
+ target_registry_name: TARGET.target_registry_name,
+ identifier_hash: TARGET.identifier.hash,
+ },
+ }))
+ jest.mocked(attacksApi.getMessages).mockImplementation(async (id: string, conversationId: string) => ({
+ conversation_id: conversationId,
+ messages: id === 'saved' ? failedMessages : [],
+ target_response_status: id === 'saved'
+ ? { response_error: 'processing', request_turn_number: 0, response_turn_number: 1 } : null,
+ }))
+ const user = userEvent.setup()
+ renderChat('/attacks/saved/conversations/main')
+ await user.click(await screen.findByTestId('copy-to-input-btn-0'))
+ await user.click(await screen.findByRole('menuitem', { name: 'Branch attack', exact: true }))
+ await waitFor(() => expect(screen.getByLabelText('Current route')).toHaveTextContent(
+ '/attacks/recovered/conversations/recovered-main',
+ ))
+ await waitFor(() => expect(screen.getByPlaceholderText('Type prompt here')).toHaveValue(originalValue))
+ await visitDatasets(user)
+ await returnToChat(user)
+ await waitFor(() => expect(screen.getByPlaceholderText('Type prompt here')).toHaveValue(originalValue))
+ expect(attacksApi.submitMessageSend).not.toHaveBeenCalled()
+ })
+
+ it('should leave an unsaved draft available when another saved attack is opened', async () => {
+ const user = userEvent.setup()
+ renderChat()
+ await user.type(await screen.findByPlaceholderText('Type prompt here'), 'Only for my unsaved chat')
+ await visitDatasets(user)
+ await user.click(screen.getByRole('button', { name: 'Open another attack' }))
+ await waitFor(() => expect(screen.getByPlaceholderText('Type prompt here')).toBeEnabled())
+ expect(screen.getByPlaceholderText('Type prompt here')).toHaveValue('')
+ await visitDatasets(user)
+ await returnToChat(user)
+ expect(screen.getByLabelText('Current route')).toHaveTextContent('/chat')
+ expect(screen.getByPlaceholderText('Type prompt here')).toHaveValue('Only for my unsaved chat')
+ })
+
+ it.each(['operator', 'execution'])('should not consume a draft when its destination becomes %s locked', async (lock: string) => {
+ const user = userEvent.setup()
+ renderChat('/attacks/saved/conversations/main')
+ await waitFor(() => expect(screen.getByPlaceholderText('Type prompt here')).toBeEnabled())
+ await user.type(screen.getByPlaceholderText('Type prompt here'), 'Keep until editable')
+ await visitDatasets(user)
+ const lockedAttack = lock === 'operator'
+ ? { ...savedAttack(), operator: 'another-operator' }
+ : { ...savedAttack(), execution_read_only: true }
+ jest.mocked(attacksApi.getAttack).mockResolvedValue(lockedAttack)
+ await user.click(screen.getByRole('button', { name: 'Chat', exact: true }))
+ if (lock === 'operator') {
+ await screen.findByTestId('operator-locked-banner')
+ } else {
+ await waitFor(() => expect(screen.getByPlaceholderText('Type prompt here')).toBeDisabled())
+ }
+ expect(screen.queryByDisplayValue('Keep until editable')).not.toBeInTheDocument()
+ jest.mocked(attacksApi.getAttack).mockImplementation(async (id: string) => savedAttack(id))
+ await visitDatasets(user)
+ await returnToChat(user)
+ await waitFor(() => expect(screen.getByPlaceholderText('Type prompt here')).toHaveValue('Keep until editable'))
+ })
+
+ it('should retain a draft when its attack is temporarily missing', async () => {
+ const user = userEvent.setup()
+ renderChat('/attacks/saved/conversations/main')
+ await waitFor(() => expect(screen.getByPlaceholderText('Type prompt here')).toBeEnabled())
+ await user.type(screen.getByPlaceholderText('Type prompt here'), 'Retry this destination')
+ await visitDatasets(user)
+ jest.mocked(attacksApi.getAttack).mockRejectedValueOnce({
+ isAxiosError: true, response: { status: 404, data: { detail: 'Missing' } },
+ })
+ await user.click(screen.getByRole('button', { name: 'Chat', exact: true }))
+ await screen.findByText('Attack not found')
+ await visitDatasets(user)
+ await returnToChat(user)
+ await waitFor(() => expect(screen.getByPlaceholderText('Type prompt here')).toHaveValue('Retry this destination'))
+ })
+
+ it('should discard a missing destination when explicitly starting a new attack', async () => {
+ const user = userEvent.setup()
+ renderChat('/attacks/saved/conversations/main')
+ await waitFor(() => expect(screen.getByPlaceholderText('Type prompt here')).toBeEnabled())
+ await user.type(screen.getByPlaceholderText('Type prompt here'), 'Discard this missing destination')
+ await visitDatasets(user)
+ jest.mocked(attacksApi.getAttack).mockRejectedValueOnce({
+ isAxiosError: true, response: { status: 404, data: { detail: 'Missing' } },
+ })
+ await user.click(screen.getByRole('button', { name: 'Chat', exact: true }))
+ await user.click(await screen.findByRole('button', { name: 'Start a new attack' }))
+ await returnToChat(user)
+ expect(screen.getByLabelText('Current route')).toHaveTextContent('/chat')
+ expect(screen.getByPlaceholderText('Type prompt here')).toHaveValue('')
+ })
+
+ it.each([404, 500])('should retain a draft until its transcript can be loaded after HTTP %s', async (status: number) => {
+ const user = userEvent.setup()
+ renderChat('/attacks/saved/conversations/main')
+ await waitFor(() => expect(screen.getByPlaceholderText('Type prompt here')).toBeEnabled())
+ await user.type(screen.getByPlaceholderText('Type prompt here'), 'Retry this transcript')
+ await visitDatasets(user)
+ jest.mocked(attacksApi.getMessages).mockRejectedValueOnce({
+ isAxiosError: true, response: { status, data: { detail: 'Transcript not ready' } },
+ })
+ await returnToChat(user)
+ const retry = await screen.findByRole('button', { name: 'Retry conversation load' })
+ expect(screen.queryByDisplayValue('Retry this transcript')).not.toBeInTheDocument()
+ await user.click(retry)
+ await waitFor(() => expect(screen.getByPlaceholderText('Type prompt here')).toHaveValue('Retry this transcript'))
+ })
+
+ it('should leave a draft available when another conversation in the same attack is opened', async () => {
+ const user = userEvent.setup()
+ renderChat('/attacks/saved/conversations/main')
+ await waitFor(() => expect(screen.getByPlaceholderText('Type prompt here')).toBeEnabled())
+ await user.type(screen.getByPlaceholderText('Type prompt here'), 'Only for the main conversation')
+ await visitDatasets(user)
+ await user.click(screen.getByRole('button', { name: 'Open another conversation' }))
+ await waitFor(() => expect(screen.getByPlaceholderText('Type prompt here')).toBeEnabled())
+ expect(screen.getByPlaceholderText('Type prompt here')).toHaveValue('')
+ await visitDatasets(user)
+ await returnToChat(user)
+ await waitFor(() => expect(screen.getByPlaceholderText('Type prompt here')).toHaveValue('Only for the main conversation'))
+ expect(screen.getByLabelText('Current route')).toHaveTextContent('/attacks/saved/conversations/main')
+ })
+
+ it.each([false, true])('should retain newer edits made before transcript loading with early departure=%s', async (leaveEarly: boolean) => {
+ const user = userEvent.setup()
+ renderChat('/attacks/saved/conversations/main')
+ await waitFor(() => expect(screen.getByPlaceholderText('Type prompt here')).toBeEnabled())
+ await user.type(screen.getByPlaceholderText('Type prompt here'), 'Older draft')
+ await visitDatasets(user)
+ const transcript = deferred>>()
+ jest.mocked(attacksApi.getMessages).mockReturnValueOnce(transcript.promise)
+ await returnToChat(user)
+ await user.type(screen.getByPlaceholderText('Type prompt here'), 'Newer draft')
+ if (leaveEarly) await visitDatasets(user)
+ await act(async () => {
+ transcript.resolve({ conversation_id: 'main', messages: [], target_response_status: null })
+ })
+ if (!leaveEarly) {
+ expect(screen.getByPlaceholderText('Type prompt here')).toHaveValue('Newer draft')
+ await visitDatasets(user)
+ }
+ await returnToChat(user)
+ await waitFor(() => expect(screen.getByPlaceholderText('Type prompt here')).toHaveValue('Newer draft'))
+ })
+
+ it('should preserve target selection and system prompt without changing defaults', async () => {
+ const user = userEvent.setup()
+ renderChat()
+ const selector = await screen.findByRole('combobox', { name: 'Chat target' })
+ await waitFor(() => expect(selector).toBeEnabled())
+ await user.selectOptions(selector, 'draft-target')
+ await user.click(screen.getByRole('button', { name: /system prompt/i }))
+ await user.type(screen.getByRole('textbox', { name: /system prompt/i }), 'System instruction')
+ await visitDatasets(user)
+ await returnToChat(user)
+ expect(screen.getByRole('combobox', { name: 'Chat target' })).toHaveValue('draft-target')
+ await user.click(screen.getByRole('button', { name: /system prompt/i }))
+ expect(screen.getByRole('textbox', { name: /system prompt/i })).toHaveValue('System instruction')
+ })
+
+ it('should preserve a target selected before entering text', async () => {
+ const user = userEvent.setup()
+ renderChat()
+ const selector = await screen.findByRole('combobox', { name: 'Chat target' })
+ await waitFor(() => expect(selector).toBeEnabled())
+ await user.selectOptions(selector, 'draft-target')
+ await visitDatasets(user)
+ await returnToChat(user)
+ expect(screen.getByRole('combobox', { name: 'Chat target' })).toHaveValue('draft-target')
+ expect(screen.getByPlaceholderText('Type prompt here')).toHaveValue('')
+ })
+
+ it('should preserve an explicit empty target instead of reapplying the default', async () => {
+ writeUserPreferences('local', {
+ ...DEFAULT_USER_PREFERENCES,
+ targets: { objective: targetReference(TARGET), adversarial: null },
+ })
+ const user = userEvent.setup()
+ renderChat()
+ const selector = await screen.findByRole('combobox', { name: 'Chat target' })
+ await waitFor(() => expect(selector).toHaveValue('draft-target'))
+ await user.selectOptions(selector, '')
+ await visitDatasets(user)
+ await returnToChat(user)
+ expect(screen.getByRole('combobox', { name: 'Chat target' })).toHaveValue('')
+ })
+
+ it.each(['', 'Unconverted text'])('should preserve an unapplied converter pipeline with text "%s"', async (text: string) => {
+ const user = userEvent.setup()
+ renderChat()
+ await screen.findByPlaceholderText('Type prompt here')
+ if (text) await user.type(screen.getByPlaceholderText('Type prompt here'), text)
+ await addConverter(user)
+ await visitDatasets(user)
+ await returnToChat(user)
+ await user.click(screen.getByRole('button', { name: 'Toggle converter panel' }))
+ expect(await screen.findByRole('button', { name: 'Remove converter draft-converter' })).toBeInTheDocument()
+ })
+
+ it('should preserve manually edited converter inputs, outputs, and applied values', async () => {
+ jest.mocked(convertersApi.previewConversion).mockResolvedValue(convertedText('Converted text', 'Edited working input'))
+ const user = userEvent.setup()
+ renderChat()
+ await user.type(await screen.findByPlaceholderText('Type prompt here'), 'Original text')
+ await addConverter(user)
+ const working = screen.getByRole('textbox', { name: 'Working input - Text' })
+ await user.clear(working)
+ await user.type(working, 'Edited working input')
+ await user.click(screen.getByRole('button', { name: 'Convert', exact: true }))
+ const output = await screen.findByRole('textbox', { name: 'Stage 1 output - Text' })
+ await user.clear(output)
+ await user.type(output, 'Edited stage output')
+ await visitDatasets(user)
+ await returnToChat(user)
+ await user.click(screen.getByRole('button', { name: 'Toggle converter panel' }))
+ expect(await screen.findByRole('textbox', { name: 'Working input - Text' })).toHaveValue('Edited working input')
+ expect(screen.getByRole('textbox', { name: 'Stage 1 output - Text' })).toHaveValue('Edited stage output')
+ expect(screen.getByRole('textbox', { name: /converted prompt/i })).toHaveValue('Edited stage output')
+ expect(screen.getByPlaceholderText('Type prompt here')).toHaveValue('Original text')
+ })
+
+ it('should ignore a conversion that completes after leaving its composer', async () => {
+ const conversion = deferred()
+ jest.mocked(convertersApi.previewConversion).mockReturnValueOnce(conversion.promise)
+ const user = userEvent.setup()
+ renderChat()
+ await user.type(await screen.findByPlaceholderText('Type prompt here'), 'Original text')
+ await addConverter(user)
+ await user.click(screen.getByRole('button', { name: 'Convert', exact: true }))
+ await visitDatasets(user)
+ await returnToChat(user)
+ await act(async () => { conversion.resolve(convertedText('Late conversion')) })
+ await user.click(screen.getByRole('button', { name: 'Toggle converter panel' }))
+ await screen.findByRole('button', { name: 'Remove converter draft-converter' })
+ expect(screen.queryByRole('textbox', { name: 'Stage 1 output - Text' })).not.toBeInTheDocument()
+ expect(screen.getByPlaceholderText('Type prompt here')).toHaveValue('Original text')
+ })
+
+ it('should retain named pipelines but drop generated results after the runtime changes', async () => {
+ jest.useFakeTimers()
+ const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime })
+ renderChat()
+ await waitFor(() => expect(screen.getByPlaceholderText('Type prompt here')).toBeEnabled())
+ await user.type(screen.getByPlaceholderText('Type prompt here'), 'Original text')
+ await addConverter(user)
+ await user.click(screen.getByRole('button', { name: 'Convert', exact: true }))
+ await screen.findByRole('textbox', { name: 'Stage 1 output - Text' })
+ await visitDatasets(user)
+ jest.mocked(runtimeApi.getReadiness).mockResolvedValue({ ready: true, state: 'ready', generation: 'new-runtime' })
+ await act(async () => { jest.advanceTimersByTime(2000) })
+ await returnToChat(user)
+ await user.click(screen.getByRole('button', { name: 'Toggle converter panel' }))
+ await screen.findByRole('button', { name: 'Remove converter draft-converter' })
+ expect(screen.queryByRole('textbox', { name: 'Stage 1 output - Text' })).not.toBeInTheDocument()
+ expect(screen.getByPlaceholderText('Type prompt here')).toHaveValue('Original text')
+ })
+
+ it('should preserve text-only video metadata through editor save, datasets, and send', async () => {
+ const metadata = { video_id: 'existing-video', custom: 'preserved' }
+ const attack: AttackSummary = {
+ ...savedAttack(),
+ target_unbound: false,
+ target: {
+ target_type: TARGET.identifier.class_name,
+ target_registry_name: TARGET.target_registry_name,
+ identifier_hash: TARGET.identifier.hash,
+ },
+ }
+ const source: BackendMessage[] = [{
+ role: 'user', turn_number: 0, created_at: '',
+ message_pieces: [{
+ id: 'text-remix', original_value_data_type: 'text', original_value: 'Change the background',
+ converted_value_data_type: 'text', converted_value: 'Change the background',
+ prompt_metadata: metadata, scores: [], response_error: 'none',
+ }],
+ }]
+ const empty = { conversation_id: 'main', messages: [], target_response_status: null }
+ jest.mocked(attacksApi.getAttack).mockResolvedValue(attack)
+ jest.mocked(attacksApi.getMessages).mockResolvedValue({ ...empty, messages: source })
+ jest.mocked(attacksApi.saveConversation).mockResolvedValue({ attack, messages: empty })
+ jest.mocked(attacksApi.submitMessageSend).mockImplementation(() => new Promise(() => {}))
+ const user = userEvent.setup()
+ renderChat('/attacks/saved/conversations/main')
+ await waitFor(() => expect(screen.getByPlaceholderText('Type prompt here')).toBeEnabled())
+ await user.click(screen.getByRole('button', { name: 'Edit Conversation', exact: true }))
+ await screen.findByRole('region', { name: 'Message 1' })
+ await user.click(screen.getByRole('button', { name: 'Save', exact: true }))
+ await waitFor(() => expect(screen.getByPlaceholderText('Type prompt here')).toHaveValue('Change the background'))
+ expect(attacksApi.saveConversation).toHaveBeenCalledWith(expect.objectContaining({ destination: 'same_attack' }))
+ jest.mocked(attacksApi.getMessages).mockResolvedValue(empty)
+ await visitDatasets(user)
+ await returnToChat(user)
+ await waitFor(() => expect(screen.getByPlaceholderText('Type prompt here')).toHaveValue('Change the background'))
+ await user.type(screen.getByPlaceholderText('Type prompt here'), ' to blue')
+ await user.click(screen.getByRole('button', { name: 'Send message', exact: true }))
+ await waitFor(() => expect(attacksApi.submitMessageSend).toHaveBeenCalledWith(
+ 'saved', expect.objectContaining({
+ pieces: [{ data_type: 'text', original_value: 'Change the background to blue', prompt_metadata: metadata }],
+ }),
+ ))
+ })
+
+ it('should keep cleared text empty while retaining the selected target', async () => {
+ writeUserPreferences('local', {
+ ...DEFAULT_USER_PREFERENCES,
+ targets: { objective: targetReference(TARGET), adversarial: null },
+ })
+ const user = userEvent.setup()
+ renderChat()
+ await user.type(await screen.findByPlaceholderText('Type prompt here'), 'Delete this draft')
+ await visitDatasets(user)
+ await returnToChat(user)
+ await user.clear(screen.getByPlaceholderText('Type prompt here'))
+ await visitDatasets(user)
+ await returnToChat(user)
+ expect(screen.getByPlaceholderText('Type prompt here')).toHaveValue('')
+ expect(screen.getByRole('combobox', { name: 'Chat target' })).toHaveValue('draft-target')
+ })
+
+ it('should retain uploaded media across visits and release it when explicitly removed', async () => {
+ const user = userEvent.setup()
+ renderChat('/chat', true)
+ await screen.findByPlaceholderText('Type prompt here')
+ await user.upload(screen.getByTestId('file-input'), new File(['media'], 'draft.wav', { type: 'audio/wav' }))
+ const url = jest.mocked(URL.createObjectURL).mock.results[0].value
+ for (let visit = 0; visit < 2; visit += 1) {
+ await visitDatasets(user)
+ await returnToChat(user)
+ expect(screen.getByRole('button', { name: 'Remove draft.wav' })).toBeInTheDocument()
+ expect(URL.revokeObjectURL).not.toHaveBeenCalledWith(url)
+ }
+ await user.click(screen.getByRole('button', { name: 'Remove draft.wav' }))
+ expect(URL.revokeObjectURL).toHaveBeenCalledWith(url)
+ })
+
+ it('should not return to a discarded saved draft after starting a new attack', async () => {
+ const user = userEvent.setup()
+ renderChat('/attacks/saved/conversations/main')
+ await waitFor(() => expect(screen.getByPlaceholderText('Type prompt here')).toBeEnabled())
+ await user.type(screen.getByPlaceholderText('Type prompt here'), 'Discard this saved draft')
+ await user.click(screen.getByRole('button', { name: 'New Attack', exact: true }))
+ await user.click(screen.getByRole('button', { name: 'Chat', exact: true }))
+ expect(screen.getByLabelText('Current route')).toHaveTextContent('/chat')
+ expect(screen.getByPlaceholderText('Type prompt here')).toHaveValue('')
+ })
+
+ it('should apply an import only once across edits and Back/Forward navigation', async () => {
+ const user = userEvent.setup()
+ renderChat()
+ await screen.findByPlaceholderText('Type prompt here')
+ await user.click(screen.getByRole('button', { name: 'Stage import' }))
+ expect(screen.getByPlaceholderText('Type prompt here')).toHaveValue('Imported prompt')
+ expect(screen.getByPlaceholderText('Type prompt here')).toHaveFocus()
+ expect(screen.getByLabelText('Pending import')).toHaveTextContent('none')
+ await user.type(screen.getByPlaceholderText('Type prompt here'), ' with my edit')
+ await visitDatasets(user)
+ await user.click(screen.getByRole('button', { name: 'Back', exact: true }))
+ await waitFor(() => expect(screen.getByPlaceholderText('Type prompt here')).toHaveValue('Imported prompt with my edit'))
+ await user.click(screen.getByRole('button', { name: 'Forward', exact: true }))
+ await screen.findByRole('heading', { name: 'Dataset catalog' })
+ await returnToChat(user)
+ expect(screen.getByPlaceholderText('Type prompt here')).toHaveValue('Imported prompt with my edit')
+ })
+
+ it('should protect a preserved dirty draft from an import that cannot replace it', async () => {
+ const user = userEvent.setup()
+ renderChat()
+ await user.type(await screen.findByPlaceholderText('Type prompt here'), 'Keep my original prompt')
+ await visitDatasets(user)
+ await user.click(screen.getByRole('button', { name: 'Stage protected import' }))
+ await returnToChat(user)
+ await waitFor(() => expect(screen.getByPlaceholderText('Type prompt here')).toHaveValue('Keep my original prompt'))
+ expect(screen.getByLabelText('Pending import')).toHaveTextContent('waiting')
+ })
+
+ it('should apply an import only to its exact saved conversation', async () => {
+ const user = userEvent.setup()
+ renderChat('/attacks/saved/conversations/branch')
+ await waitFor(() => expect(screen.getByPlaceholderText('Type prompt here')).toBeEnabled())
+ await user.click(screen.getByRole('button', { name: 'Stage saved import' }))
+ expect(screen.getByPlaceholderText('Type prompt here')).toHaveValue('')
+ expect(screen.getByLabelText('Pending import')).toHaveTextContent('waiting')
+ await user.click(screen.getByRole('button', { name: 'Open saved main' }))
+ await waitFor(() => expect(screen.getByPlaceholderText('Type prompt here')).toHaveValue('Import for saved main'))
+ expect(screen.getByLabelText('Pending import')).toHaveTextContent('none')
+ })
+
+ it.each([false, true])('should release owned media when the App closes with a preserved snapshot=%s', async (preserve: boolean) => {
+ const user = userEvent.setup()
+ const rendered = renderChat('/chat', true)
+ await screen.findByPlaceholderText('Type prompt here')
+ await user.upload(screen.getByTestId('file-input'), new File(['image'], 'owned.png', { type: 'image/png' }))
+ const url = jest.mocked(URL.createObjectURL).mock.results[0].value
+ if (preserve) await visitDatasets(user)
+ expect(URL.revokeObjectURL).not.toHaveBeenCalledWith(url)
+ rendered.unmount()
+ expect(URL.revokeObjectURL).toHaveBeenCalledWith(url)
+ })
+
+ it('should retain dataset return state and cursor history across the round trip', async () => {
+ const user = userEvent.setup()
+ render()
+ await screen.findByRole('heading', { name: 'Example dataset' })
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Previous page' })).toBeEnabled())
+ await returnToChat(user)
+ await user.click(screen.getByRole('button', { name: 'Datasets', exact: true }))
+ await screen.findByRole('heading', { name: 'Example dataset' })
+ expect(screen.getByRole('link', { name: 'Back to datasets' })).toHaveAttribute('href', '/datasets?q=example&sort=name')
+ expect(screen.getByRole('button', { name: 'Previous page' })).toBeEnabled()
+ })
+})
diff --git a/frontend/src/App.test.tsx b/frontend/src/App.test.tsx
index 558d1125b9..576318dbee 100644
--- a/frontend/src/App.test.tsx
+++ b/frontend/src/App.test.tsx
@@ -3,7 +3,7 @@
* Licensed under the MIT license.
*/
-import { Suspense } from "react";
+import { Suspense, useEffect, useLayoutEffect, useRef, useState } from "react";
import { act, render, screen, fireEvent, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { MemoryRouter, useLocation, useNavigate } from "react-router";
@@ -182,9 +182,11 @@ jest.mock("./components/Layout/MainLayout", () => {
jest.mock("./components/Chat/ChatWindow", () => {
const { useLocation } = jest.requireActual("react-router") as typeof import("react-router");
+ const { useChatDraftHandoff } = jest.requireActual("./hooks/useChatDraftHandoff") as typeof import("./hooks/useChatDraftHandoff");
const MockChatWindow = ({
onNewAttack,
activeTarget,
+ draftContext,
attackResultId,
conversationId,
activeConversationId,
@@ -201,6 +203,7 @@ jest.mock("./components/Chat/ChatWindow", () => {
}: {
onNewAttack: () => void;
activeTarget: unknown;
+ draftContext?: Pick;
attackResultId: string | null;
conversationId: string | null;
activeConversationId: string | null;
@@ -216,11 +219,73 @@ jest.mock("./components/Chat/ChatWindow", () => {
isLoadingAttack?: boolean;
}) => {
const location = useLocation();
+ const draftHandoff = useChatDraftHandoff();
+ const [composerText, setComposerText] = useState(() => draftHandoff.preservedDraft?.draft?.text ?? "none");
+ const activeTextRef = useRef(composerText);
+ useLayoutEffect(() => {
+ activeTextRef.current = composerText;
+ }, [composerText]);
+
+ const restoredRef = useRef(false);
+ useEffect(() => {
+ if (!restoredRef.current && draftHandoff.preservedDraft) {
+ restoredRef.current = true;
+ setComposerText(draftHandoff.preservedDraft.draft.text);
+ draftHandoff.consumePreservedDraft(attackResultId, activeConversationId ?? conversationId);
+ }
+ }, [draftHandoff, attackResultId, activeConversationId, conversationId]);
+
+ const preserveDraftRef = useRef(draftHandoff.preserveDraft);
+ useLayoutEffect(() => {
+ preserveDraftRef.current = draftHandoff.preserveDraft;
+ }, [draftHandoff.preserveDraft]);
+
+ const routeRef = useRef({
+ attackResultId,
+ convId: activeConversationId ?? conversationId,
+ path: `${location.pathname}${location.search}${location.hash}`,
+ });
+ useLayoutEffect(() => {
+ routeRef.current = {
+ attackResultId,
+ convId: activeConversationId ?? conversationId,
+ path: `${location.pathname}${location.search}${location.hash}`,
+ };
+ }, [attackResultId, activeConversationId, conversationId, location.pathname, location.search, location.hash]);
+
+ useEffect(() => {
+ return () => {
+ if (activeTextRef.current && activeTextRef.current !== "none") {
+ preserveDraftRef.current({
+ originatingAttackId: routeRef.current.attackResultId,
+ originatingConversationId: routeRef.current.convId,
+ originatingPath: routeRef.current.path,
+ draft: { text: activeTextRef.current, attachments: [] },
+ });
+ }
+ };
+ }, []);
+
if (attackResultId === "ar-123" && mockCreatedAttackRender) {
throw mockCreatedAttackRender;
}
return (
+
{draftContext?.originatingAttackId ?? "none"}
+
{draftContext?.originatingConversationId ?? "none"}
+
{composerText}
+
+
{attackResultId ?? "none"}
{conversationId ?? "none"}
{activeConversationId ?? "none"}
@@ -411,7 +476,23 @@ jest.mock("./components/Home/Home", () => {
});
jest.mock("./components/Datasets/DatasetCatalog", () => {
- const MockDatasetCatalog = () =>
;
+ const { useLocation, useNavigate } = jest.requireActual
("react-router");
+ const MockDatasetCatalog = () => {
+ const location = useLocation();
+ const navigate = useNavigate();
+ return (
+
+ {`${location.pathname}${location.search}`}
+ {JSON.stringify(location.state)}
+
+
+ );
+ };
MockDatasetCatalog.displayName = "MockDatasetCatalog";
return {
__esModule: true,
@@ -1327,17 +1408,15 @@ describe("App", () => {
fireEvent.click(screen.getByTestId("nav-history"));
fireEvent.click(screen.getByTestId("open-attack-2")); // ar-attack-2
- // BEFORE getAttack resolves: ChatWindow must NOT see the stale conv id
- // alongside the new attack id. While attack B loads, its data is not yet
- // ready, so both the attack id and conversation id are withheld — which
- // gates ChatWindow's /messages fetch and prevents the cross-attack 400.
+ // The loading shell must not use attack A's active conversation.
expect(screen.getByTestId("main-layout")).toHaveAttribute(
"data-current-view",
"chat"
);
expect(screen.getByTestId("attack-result-id")).toHaveTextContent("none");
expect(screen.getByTestId("active-conversation-id")).toHaveTextContent("none");
- expect(screen.getByTestId("conversation-id")).toHaveTextContent("none");
+ expect(screen.getByTestId("draft-attack-id")).toHaveTextContent("ar-attack-2");
+ expect(screen.getByTestId("draft-conversation-id")).toHaveTextContent("none");
// After getAttack resolves: the conv id belonging to attack B is committed.
resolveGetAttack({
@@ -1349,6 +1428,7 @@ describe("App", () => {
expect(screen.getByTestId("active-conversation-id")).toHaveTextContent("attack-conv-2")
);
expect(screen.getByTestId("conversation-id")).toHaveTextContent("attack-conv-2");
+ expect(screen.getByTestId("draft-conversation-id")).toHaveTextContent("attack-conv-2");
});
it("merges default labels from backend version API", async () => {
@@ -2377,4 +2457,103 @@ describe("App", () => {
expect(screen.getByTestId("active-target-name")).toHaveTextContent("none");
expect(mockListTargets).not.toHaveBeenCalled();
});
+
+ it("preserves unsaved chat draft across navigation to datasets and back", async () => {
+ const user = userEvent.setup();
+ renderApp("/chat");
+
+ await waitFor(() => expect(screen.getByTestId("chat-window")).toBeInTheDocument());
+ expect(screen.getByTestId("preserved-draft-text")).toHaveTextContent("none");
+
+ // Simulate preserving a draft in unsaved chat
+ await user.click(screen.getByTestId("preserve-draft"));
+ expect(screen.getByTestId("preserved-draft-text")).toHaveTextContent("preserved prompt draft");
+
+ // Navigate to Datasets via sidebar button
+ await user.click(screen.getByTestId("nav-datasets"));
+ await waitFor(() => expect(screen.getByTestId("dataset-catalog")).toBeInTheDocument());
+
+ // Navigate back to Chat via sidebar button
+ await user.click(screen.getByTestId("nav-chat"));
+ await waitFor(() => expect(screen.getByTestId("chat-window")).toBeInTheDocument());
+
+ // Draft and route are preserved
+ expect(screen.getByTestId("preserved-draft-text")).toHaveTextContent("preserved prompt draft");
+ expect(screen.getByTestId("attack-result-id")).toHaveTextContent("none");
+ });
+
+ it("preserves attack conversation origin and restores datasets filter location when navigating between chat and datasets", async () => {
+ mockGetAttack.mockResolvedValue({
+ attack_result_id: "ar-nav-1",
+ conversation_id: "conv-nav-1",
+ labels: {},
+ related_conversation_ids: [],
+ target: null,
+ });
+
+ const user = userEvent.setup();
+ renderApp("/attacks/ar-nav-1/conversations/conv-nav-1");
+
+ await waitFor(() => expect(screen.getByTestId("chat-window")).toBeInTheDocument());
+ expect(screen.getByTestId("route-location")).toHaveTextContent("/attacks/ar-nav-1/conversations/conv-nav-1");
+
+ // Preserve draft from persisted attack conversation
+ await user.click(screen.getByTestId("preserve-draft"));
+ expect(screen.getByTestId("preserved-draft-text")).toHaveTextContent("preserved prompt draft");
+
+ // Navigate to Datasets
+ await user.click(screen.getByTestId("nav-datasets"));
+ await waitFor(() => expect(screen.getByTestId("dataset-catalog")).toBeInTheDocument());
+
+ // Apply a dataset filter (modifies datasets location)
+ await user.click(screen.getByTestId("dataset-set-filter"));
+ await waitFor(() =>
+ expect(screen.getByTestId("dataset-location")).toHaveTextContent("/datasets?filter=harmful")
+ );
+
+ // Navigate back to Chat - should return to originating attack conversation
+ await user.click(screen.getByTestId("nav-chat"));
+ await waitFor(() => expect(screen.getByTestId("chat-window")).toBeInTheDocument());
+ expect(screen.getByTestId("route-location")).toHaveTextContent("/attacks/ar-nav-1/conversations/conv-nav-1");
+
+ // Navigate back to Datasets - should restore exact filtered location and state
+ await user.click(screen.getByTestId("nav-datasets"));
+ await waitFor(() => expect(screen.getByTestId("dataset-catalog")).toBeInTheDocument());
+ expect(screen.getByTestId("dataset-location")).toHaveTextContent("/datasets?filter=harmful");
+ expect(screen.getByTestId("dataset-state")).toHaveTextContent('{"catalogPath":"/datasets?filter=harmful","cursors":["cur-1"]}');
+ });
+
+ it("clearing draft text stays cleared after another round trip to datasets", async () => {
+ const user = userEvent.setup();
+ renderApp("/chat");
+
+ await waitFor(() => expect(screen.getByTestId("chat-window")).toBeInTheDocument());
+ expect(screen.getByTestId("preserved-draft-text")).toHaveTextContent("none");
+
+ // 1. User types prompt and preserves draft
+ await user.click(screen.getByTestId("preserve-draft"));
+ expect(screen.getByTestId("preserved-draft-text")).toHaveTextContent("preserved prompt draft");
+
+ // 2. User visits Datasets
+ await user.click(screen.getByTestId("nav-datasets"));
+ await waitFor(() => expect(screen.getByTestId("dataset-catalog")).toBeInTheDocument());
+
+ // 3. User returns to Chat: draft is restored and consumed
+ await user.click(screen.getByTestId("nav-chat"));
+ await waitFor(() => expect(screen.getByTestId("chat-window")).toBeInTheDocument());
+ expect(screen.getByTestId("preserved-draft-text")).toHaveTextContent("preserved prompt draft");
+
+ // 4. User clears all prompt text
+ await user.click(screen.getByTestId("clear-draft"));
+ expect(screen.getByTestId("preserved-draft-text")).toHaveTextContent("none");
+
+ // 5. User visits Datasets again
+ await user.click(screen.getByTestId("nav-datasets"));
+ await waitFor(() => expect(screen.getByTestId("dataset-catalog")).toBeInTheDocument());
+
+ // 6. User returns to Chat again: cleared prompt must NOT resurrect the old deleted text
+ await user.click(screen.getByTestId("nav-chat"));
+ await waitFor(() => expect(screen.getByTestId("chat-window")).toBeInTheDocument());
+ expect(screen.getByTestId("preserved-draft-text")).toHaveTextContent("none");
+ });
});
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index b6b9da3b50..3e76f74937 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -68,11 +68,14 @@ import {
import { attacksApi, authApi, versionApi } from './services/api'
import { toApiError } from './services/errors'
import { useTour } from './hooks/useTour'
+import { ChatDraftProvider, useChatDraftHandoff } from './hooks/useChatDraftHandoff'
import {
attackConversationRoutePath,
attackRoutePath,
DATASET_DETAIL_PATH,
DATASETS_PATH,
+ isChatPath,
+ isDatasetsPath,
routerPathParamValue,
scenarioRunProvenance,
findingEvidenceOrigin,
@@ -218,16 +221,24 @@ function AppContent({ operatorAlias }: { operatorAlias: string | null }) {
const scorerRegistry = useScorerRegistry()
const { preferences, updatePreferences, error: preferenceError } = useUserPreferences()
const targetDefaults = useTargetPreferences(registry.targets)
+ const draftHandoff = useChatDraftHandoff()
+ const { clearPreservedDraft, dismissPendingImport } = draftHandoff
const [draftSession, setDraftSession] = useState<{
pathname: string
key: number
target: TargetReference | null
}>({ pathname: location.pathname, key: 0, target: targetDefaults.preferences.objective })
if (draftSession.pathname !== location.pathname) {
+ const isReturningToUnsavedChatWithPreservedDraft =
+ location.pathname === VIEW_PATHS.chat &&
+ draftHandoff.preservedDraft?.originatingAttackId === null
+ const nextTarget = isReturningToUnsavedChatWithPreservedDraft && draftHandoff.preservedDraft?.draft.target !== undefined
+ ? draftHandoff.preservedDraft.draft.target
+ : targetDefaults.preferences.objective
setDraftSession({
pathname: location.pathname,
- key: draftSession.key + (location.pathname === VIEW_PATHS.chat ? 1 : 0),
- target: targetDefaults.preferences.objective,
+ key: draftSession.key + (location.pathname === VIEW_PATHS.chat && !isReturningToUnsavedChatWithPreservedDraft ? 1 : 0),
+ target: nextTarget,
})
}
const draftTarget = !registry.loading && !registry.error && draftSession.target
@@ -330,6 +341,8 @@ function AppContent({ operatorAlias }: { operatorAlias: string | null }) {
const lastHistorySearch = useRef('')
const lastScenarioHistorySearch = useRef('')
const lastAnalyticsLocation = useRef('')
+ const lastDatasetsLocation = useRef<{ path: string; state: unknown }>({ path: '', state: null })
+ const lastChatLocation = useRef<{ path: string; state: unknown }>({ path: '', state: null })
useEffect(() => {
if (location.pathname === HISTORY_ATTACKS_PATH) {
lastHistorySearch.current = location.search
@@ -340,7 +353,23 @@ function AppContent({ operatorAlias }: { operatorAlias: string | null }) {
if (location.pathname === VIEW_PATHS.analytics) {
lastAnalyticsLocation.current = location.search + location.hash
}
- }, [location.pathname, location.search, location.hash])
+ if (isDatasetsPath(location.pathname)) {
+ lastDatasetsLocation.current = {
+ path: location.pathname + location.search + location.hash,
+ state: location.state,
+ }
+ }
+ if (isChatPath(location.pathname)) {
+ lastChatLocation.current = {
+ path: location.pathname + location.search + location.hash,
+ state: location.state,
+ }
+ }
+ if (!isDatasetsPath(location.pathname) && !isChatPath(location.pathname)) {
+ clearPreservedDraft()
+ dismissPendingImport()
+ }
+ }, [location.pathname, location.search, location.hash, location.state, clearPreservedDraft, dismissPendingImport])
const handleFiltersChange = useCallback((filters: HistoryFilters) => {
// The label search is controlled by this URL state and must not lag behind typing.
@@ -569,12 +598,40 @@ function AppContent({ operatorAlias }: { operatorAlias: string | null }) {
navigate(VIEW_PATHS.analytics + lastAnalyticsLocation.current)
return
}
+ if (view === 'datasets') {
+ if (lastDatasetsLocation.current.path) {
+ navigate(lastDatasetsLocation.current.path, { state: lastDatasetsLocation.current.state })
+ } else {
+ navigate(VIEW_PATHS.datasets)
+ }
+ return
+ }
+ if (view === 'chat') {
+ if (draftHandoff.preservedDraft?.originatingPath) {
+ navigate(draftHandoff.preservedDraft.originatingPath, { state: draftHandoff.preservedDraft.originatingState })
+ return
+ }
+ if (lastChatLocation.current.path) {
+ navigate(lastChatLocation.current.path, { state: lastChatLocation.current.state })
+ return
+ }
+ navigate(VIEW_PATHS.chat)
+ return
+ }
navigate(VIEW_PATHS[view])
- }, [navigate])
+ }, [navigate, draftHandoff.preservedDraft])
const handleNewAttack = useCallback(() => {
+ clearPreservedDraft()
+ dismissPendingImport()
+ lastChatLocation.current = { path: VIEW_PATHS.chat, state: null }
+ setDraftSession((current) => ({
+ ...current,
+ key: current.key + 1,
+ target: targetDefaults.preferences.objective,
+ }))
navigate(VIEW_PATHS.chat)
- }, [navigate])
+ }, [navigate, clearPreservedDraft, dismissPendingImport, targetDefaults.preferences.objective])
const handleConversationCreated = useCallback((
arId: string,
@@ -682,7 +739,7 @@ function AppContent({ operatorAlias }: { operatorAlias: string | null }) {
attackId={routeAttackId ?? ''}
variant={isAttackError ? 'error' : 'not-found'}
findingEvidenceId={findingEvidenceId}
- onStartNew={() => navigate(VIEW_PATHS.chat)}
+ onStartNew={handleNewAttack}
onBackToHistory={() => navigate(VIEW_PATHS.history)}
/>
) : (
@@ -691,6 +748,11 @@ function AppContent({ operatorAlias }: { operatorAlias: string | null }) {
toolbarContainer={chatToolbarContainer}
onNewAttack={handleNewAttack}
activeTarget={activeTarget}
+ draftTargetReference={routeAttackId === null ? draftSession.target : undefined}
+ draftContext={{
+ originatingAttackId: routeAttackId,
+ originatingConversationId: activeConversationId ?? routeConversationId,
+ }}
availableTargets={registry.targets}
targetsLoading={registry.loading}
targetsError={registry.error}
@@ -970,7 +1032,9 @@ function App() {
-
+
+
+
diff --git a/frontend/src/components/Chat/ChatInputArea.test.tsx b/frontend/src/components/Chat/ChatInputArea.test.tsx
index 828976c607..3a4182d02e 100644
--- a/frontend/src/components/Chat/ChatInputArea.test.tsx
+++ b/frontend/src/components/Chat/ChatInputArea.test.tsx
@@ -1854,4 +1854,118 @@ describe("ChatInputArea", () => {
).toHaveTextContent(/selected converter produces audio output, which this target does not support/);
expect(getSendButton()).toHaveAttribute("aria-disabled", "true");
});
+
+ describe("attachment blob URL lifecycle and metadata", () => {
+ let revokeSpy: jest.SpyInstance;
+
+ beforeEach(() => {
+ revokeSpy = jest.spyOn(URL, "revokeObjectURL").mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ revokeSpy.mockRestore();
+ });
+
+ it("preserves initialAttachments blob URLs without calling URL.revokeObjectURL on mount", () => {
+ const attachment: MessageAttachment = {
+ name: "photo.png",
+ type: "image/png",
+ url: "blob:http://localhost/active-photo",
+ size: 2048,
+ draftId: "draft-photo-1",
+ };
+
+ render(
+
+
+
+ );
+
+ expect(screen.getByText(/photo\.png/)).toBeInTheDocument();
+ expect(revokeSpy).not.toHaveBeenCalled();
+ });
+
+ it("does not revoke blob URL when restoreDraft updates attachments with identical URLs", () => {
+ const handleRef = React.createRef();
+ const initialAttachment: MessageAttachment = {
+ name: "photo.png",
+ type: "image/png",
+ url: "blob:http://localhost/active-photo",
+ size: 2048,
+ draftId: "draft-photo-1",
+ };
+
+ render(
+
+
+
+ );
+
+ expect(revokeSpy).not.toHaveBeenCalled();
+
+ // Calling restoreDraft with the same attachment or cloned copy should NOT revoke its URL
+ act(() => {
+ handleRef.current?.restoreDraft("updated prompt", [{ ...initialAttachment }]);
+ });
+
+ expect(revokeSpy).not.toHaveBeenCalled();
+ });
+
+ it("revokes blob URL when attachment is explicitly removed", async () => {
+ const user = userEvent.setup();
+ const attachment: MessageAttachment = {
+ name: "photo.png",
+ type: "image/png",
+ url: "blob:http://localhost/remove-me",
+ size: 2048,
+ draftId: "draft-photo-2",
+ };
+
+ render(
+
+
+
+ );
+
+ expect(screen.getByText(/photo\.png/)).toBeInTheDocument();
+ expect(revokeSpy).not.toHaveBeenCalled();
+
+ const removeBtn = screen.getByRole("button", { name: "Remove photo.png" });
+ await user.click(removeBtn);
+
+ expect(revokeSpy).toHaveBeenCalledTimes(1);
+ expect(revokeSpy).toHaveBeenCalledWith("blob:http://localhost/remove-me");
+ });
+
+ it("retains initialTextMetadata and exposes via getTextMetadata", () => {
+ const handleRef = React.createRef();
+ const metadata = { datasetId: "ds-123", seedIndex: 42 };
+
+ render(
+
+
+
+ );
+
+ expect(handleRef.current?.getTextMetadata()).toEqual(metadata);
+ });
+ });
});
diff --git a/frontend/src/components/Chat/ChatInputArea.tsx b/frontend/src/components/Chat/ChatInputArea.tsx
index a11d75e380..24a418d596 100644
--- a/frontend/src/components/Chat/ChatInputArea.tsx
+++ b/frontend/src/components/Chat/ChatInputArea.tsx
@@ -147,6 +147,9 @@ interface ChatInputAreaProps {
supportsSystemPrompt?: boolean
systemPrompt?: string
onSystemPromptChange?: (value: string) => void
+ initialText?: string
+ initialAttachments?: MessageAttachment[]
+ initialTextMetadata?: Record
}
const ChatInputArea = forwardRef(function ChatInputArea({
@@ -158,10 +161,11 @@ const ChatInputArea = forwardRef(functi
converterOutputDataTypes = [], mediaConversions = [], onClearMediaConversion, convertedFileChip,
onClearConvertedFileChip, showSystemPrompt = false, supportsSystemPrompt = false, systemPrompt = '', onSystemPromptChange,
repeatDisabledReason, undoLastSend,
+ initialText = '', initialAttachments = [], initialTextMetadata,
}, ref) {
const styles = usePromptEditorStyles()
- const [input, setInput] = useState('')
- const [attachments, setAttachments] = useState([])
+ const [input, setInput] = useState(initialText)
+ const [attachments, setAttachments] = useState(initialAttachments)
const [isInputWarningOpen, setIsInputWarningOpen] = useState(false)
const warningHoverTimer = useRef(undefined)
const cancelWarningHover = useCallback((): void => {
@@ -175,7 +179,7 @@ const ChatInputArea = forwardRef(functi
const disabledOverlayRef = useRef(null)
const inputRef = useRef(input)
const attachmentsRef = useRef(attachments)
- const textMetadataRef = useRef | undefined>(undefined)
+ const textMetadataRef = useRef | undefined>(initialTextMetadata)
const draftRevisionRef = useRef(0)
const previousConversionRevisionKeyRef = useRef(conversionRevisionKey)
const inputDisabledReasons = [...disabledReasons]
@@ -199,8 +203,9 @@ const ChatInputArea = forwardRef(functi
setInput(text)
}
const changeAttachments = (next: MessageAttachment[]): void => {
+ const nextUrls = new Set(next.map((attachment) => attachment.url))
for (const attachment of attachmentsRef.current) {
- if (!next.includes(attachment) && attachment.url.startsWith('blob:')) URL.revokeObjectURL(attachment.url)
+ if (!nextUrls.has(attachment.url) && attachment.url.startsWith('blob:')) URL.revokeObjectURL(attachment.url)
}
attachmentsRef.current = next
draftRevisionRef.current += 1
@@ -217,7 +222,7 @@ const ChatInputArea = forwardRef(functi
restoreDraft: (text: string, draftAttachments: MessageAttachment[], textMetadata?: Record): void => {
changeText(text)
textMetadataRef.current = textMetadata
- changeAttachments(draftAttachments.map(withDraftIdentity))
+ changeAttachments(draftAttachments.map((attachment) => attachment.draftId ? attachment : withDraftIdentity(attachment)))
},
focus: (): void => { textareaRef.current?.focus() },
getDraftRevision: (): number => draftRevisionRef.current,
diff --git a/frontend/src/components/Chat/ChatWindow.tsx b/frontend/src/components/Chat/ChatWindow.tsx
index 8d2b88740f..0d055ba9ea 100644
--- a/frontend/src/components/Chat/ChatWindow.tsx
+++ b/frontend/src/components/Chat/ChatWindow.tsx
@@ -27,7 +27,7 @@ import {
} from '@fluentui/react-components'
import type { SwitchOnChangeData } from '@fluentui/react-components'
import { AddRegular, ArrowDownloadRegular, ArrowShuffleRegular, EditRegular, PanelRightRegular } from '@fluentui/react-icons'
-import { Link, useNavigate } from 'react-router'
+import { Link, useNavigate, useLocation } from 'react-router'
import MessageList from './MessageList'
import ChatInputArea from './ChatInputArea'
import MultiSendProgress from './MultiSendProgress'
@@ -50,6 +50,14 @@ import { useConversationDraft } from '@/hooks/useConversationDraft'
import { useConversationMessages } from '@/hooks/useConversationMessages'
import { useAttackMutations } from '@/hooks/useAttackMutations'
import { useConversationExport } from '@/hooks/useConversationExport'
+import { useChatDraftHandoff } from '@/hooks/useChatDraftHandoff'
+import {
+ shouldApplyPreservedDraft,
+ canApplyPendingImport,
+ hasChatDraftState,
+ isChatDraftDirty,
+} from '@/utils/chatDraft'
+import { targetReference } from '@/utils/targetIdentity'
import type { PieceConversion } from './converterTypes'
import { useChatConverters } from '@/hooks/useChatConverters'
import { useRuntime } from '@/hooks/useRuntime'
@@ -83,6 +91,8 @@ import type {
BackendScore,
ChatSendOutcome,
ChatConverterSnapshot,
+ ChatDraftContent,
+ ChatDraftContextState,
ConversationMessagesResponse,
ConversationDraftPiece,
ConverterPipelineStage,
@@ -97,6 +107,7 @@ import type {
NewAttackContext,
TargetInstance,
TargetInfo,
+ TargetReference,
} from '../../types'
import { isTargetResolutionBlocking, targetInfoMatchesTarget } from '../../utils/targetIdentity'
import { scenarioRunRoutePath } from '../../utils/routeParams'
@@ -273,6 +284,9 @@ interface ChatWindowProps {
toolbarContainer?: HTMLElement | null
onNewAttack: () => void
activeTarget: TargetInstance | null
+ draftTargetReference?: TargetReference | null
+ /** Route identity is available before the attack's metadata has loaded. */
+ draftContext?: Pick
availableTargets: TargetInstance[]
targetsLoading: boolean
targetsError: string | null
@@ -336,6 +350,8 @@ export default function ChatWindow({
toolbarContainer,
onNewAttack,
activeTarget,
+ draftTargetReference,
+ draftContext,
availableTargets,
targetsLoading,
targetsError,
@@ -451,6 +467,19 @@ export default function ChatWindow({
// Conversation-wide preference for rendering message text as Markdown.
const { preferences, updatePreferences } = useUserPreferences()
const globalMarkdown = preferences.chatMarkdown
+ const location = useLocation()
+ const viewedConversationId = activeConversationId ?? conversationId
+ const draftAttackId = draftContext ? draftContext.originatingAttackId : attackResultId
+ const draftConversationId = draftContext ? draftContext.originatingConversationId : viewedConversationId
+ const draftHandoff = useChatDraftHandoff()
+ const matchingPreservedDraft = useMemo(() => (
+ draftHandoff.preservedDraft && shouldApplyPreservedDraft(
+ draftHandoff.preservedDraft,
+ draftAttackId,
+ draftConversationId,
+ ) ? draftHandoff.preservedDraft.draft : null
+ ), [draftHandoff.preservedDraft, draftAttackId, draftConversationId])
+
const [chatInputText, setChatInputText] = useState('')
const [systemPrompt, setSystemPrompt] = useState('')
const [draftAttachments, setDraftAttachments] = useState([])
@@ -459,13 +488,18 @@ export default function ChatWindow({
const [undoableSend, setUndoableSend] = useState(null)
const [isUndoingSend, setIsUndoingSend] = useState(false)
const undoInFlight = useRef(false)
+
+ const handoffRestoredRef = useRef(null)
+ const ownsDraftRef = useRef(false)
+ const discardDraftOnUnmountRef = useRef(false)
+ const preserveOnUnmountRef = useRef<(() => void) | null>(null)
+ useEffect(() => () => { preserveOnUnmountRef.current?.() }, [])
const [recoverableSends, setRecoverableSends] = useState>({})
const [isRecoveringProcessingError, setIsRecoveringProcessingError] = useState(false)
const [recoveredDraftWarningConversationId, setRecoveredDraftWarningConversationId] = useState(null)
const [panelRefreshKey, setPanelRefreshKey] = useState(0)
const inputBoxRef = useRef(null)
const recoveryInFlightRef = useRef(false)
- const viewedConversationId = activeConversationId ?? conversationId
useEffect(() => {
if (editDraft && (editDraft.sourceConversationId !== viewedConversationId || editDraft.sourceAttackId !== attackResultId)) {
discardEditor()
@@ -655,6 +689,50 @@ export default function ChatWindow({
)
// Any failed invariant keeps all mutation controls and handlers read-only.
const isMutationLocked = executionReadOnly || isOperatorLocked || isCrossTargetLocked || isTargetResolutionLocked || isEvidenceUnavailable
+ const isDraftDestinationReady = !isLoadingAttack && !isLoadingMessages && !awaitingConversationLoad && !isSending
+ && conversationLoadIssue?.conversationId !== viewedConversationId
+ && !isMutationLocked && !editDraft && (attackResultId === null || viewedConversationId !== null)
+
+ const activeDraft: ChatDraftContent = {
+ text: chatInputText,
+ attachments: draftAttachments,
+ systemPrompt,
+ target: draftTargetReference !== undefined
+ ? draftTargetReference : activeTarget ? targetReference(activeTarget) : null,
+ converters: converters.snapshot(),
+ }
+ const isActiveDraftDirty = isChatDraftDirty(activeDraft)
+ useLayoutEffect(() => {
+ if (isDraftDestinationReady || isActiveDraftDirty) ownsDraftRef.current = true
+ const savedDraft = { ...activeDraft, textMetadata: inputBoxRef.current?.getTextMetadata() }
+ const isWaitingForRestore = matchingPreservedDraft !== null
+ && handoffRestoredRef.current !== draftHandoff.preservedDraft?.sequence
+ && !isActiveDraftDirty
+ const hasUnrelatedDraft = draftHandoff.preservedDraft !== null && matchingPreservedDraft === null
+ const hasEditedContent = isActiveDraftDirty
+ || Object.values(activeDraft.converters?.pipelines ?? {}).some((stages: ConverterPipelineStage[]) => stages.length > 0)
+ preserveOnUnmountRef.current = (): void => {
+ if (discardDraftOnUnmountRef.current || !ownsDraftRef.current || isWaitingForRestore
+ || !hasChatDraftState(activeDraft) || (hasUnrelatedDraft && !hasEditedContent)) return
+ draftHandoff.preserveDraft({
+ originatingAttackId: draftAttackId,
+ originatingConversationId: draftConversationId,
+ originatingPath: location.pathname + location.search + location.hash,
+ originatingState: location.state,
+ draft: savedDraft,
+ })
+ }
+ })
+
+ const restoreComposerDraft = useCallback((draft: ChatDraftContent): MessageAttachment[] => {
+ const attachments = draft.attachments.map(withDraftIdentity)
+ setChatInputText(draft.text)
+ setDraftAttachments(attachments)
+ if (draft.systemPrompt !== undefined) setSystemPrompt(draft.systemPrompt)
+ inputBoxRef.current?.restoreDraft(draft.text, attachments, draft.textMetadata)
+ return attachments
+ }, [])
+ const restoreConverterSnapshot = converters.restoreSnapshot
const isScoreLocked = isOperatorLocked || Boolean(isLoadingAttack) || isLoadingMessages
|| awaitingConversationLoad || isEvidenceUnavailable
const {
@@ -704,6 +782,70 @@ export default function ChatWindow({
const isFindingActionDisabled = Boolean(editDraft !== null || !attackResultId || !activeConversationId
|| isEvidenceUnavailable || isLoadingAttack || isLoadingMessages || awaitingConversationLoad)
+ const pending = draftHandoff.pendingImport
+ const canApplyImportNow = Boolean(
+ pending
+ && isDraftDestinationReady
+ && runtime.ready
+ && matchingPreservedDraft === null
+ && canApplyPendingImport(pending, draftAttackId, draftConversationId)
+ && pending.sequence >= draftHandoff.activeSequence
+ && (!isActiveDraftDirty || pending.replaceDirty),
+ )
+
+ useEffect(() => {
+ if (pending && pending.sequence < draftHandoff.activeSequence) {
+ draftHandoff.dismissPendingImport(pending.id)
+ return
+ }
+ if (!runtime.ready || !isDraftDestinationReady || !inputBoxRef.current) return
+ const preserved = draftHandoff.preservedDraft
+ const restoringPreserved = Boolean(matchingPreservedDraft && preserved
+ && handoffRestoredRef.current !== preserved.sequence)
+ let draft: ChatDraftContent
+ let focus = false
+ if (restoringPreserved && preserved) {
+ if (isActiveDraftDirty) {
+ draftHandoff.clearPreservedDraft(preserved.sequence)
+ return
+ }
+ const consumed = draftHandoff.consumePreservedDraft(draftAttackId, draftConversationId, preserved.sequence)
+ if (!consumed) return
+ handoffRestoredRef.current = preserved.sequence
+ draft = { ...consumed, systemPrompt: consumed.systemPrompt ?? '' }
+ } else {
+ if (!canApplyImportNow || !pending) return
+ const consumed = draftHandoff.consumePendingImport(pending.id, draftAttackId, draftConversationId)
+ if (!consumed) return
+ converters.clearAll()
+ draft = {
+ text: consumed.content.text,
+ attachments: consumed.content.attachments ?? [],
+ textMetadata: consumed.content.textMetadata,
+ }
+ focus = consumed.focus === true
+ }
+ // Claiming a handoff synchronizes the imperative input and its parent-owned draft atomically.
+ // eslint-disable-next-line react-hooks/set-state-in-effect
+ const attachments = restoreComposerDraft(draft)
+ if (restoringPreserved) {
+ if (draft.converters?.generation === runtime.generation) {
+ restoreConverterSnapshot(draft.converters, draft.text, attachments)
+ } else {
+ restoreConversions(draft.text, attachments, {}, Object.fromEntries(
+ Object.entries(draft.converters?.pipelines ?? {}).map(([pieceType, stages]: [string, ConverterPipelineStage[]]) => [
+ pieceType, stages.map((stage: ConverterPipelineStage) => ({ id: stage.id, converterId: stage.converterId })),
+ ]),
+ ))
+ }
+ }
+ if (focus) inputBoxRef.current.focus()
+ }, [
+ canApplyImportNow, pending, draftHandoff, draftAttackId, draftConversationId, converters,
+ isDraftDestinationReady, matchingPreservedDraft, isActiveDraftDirty, runtime.ready, runtime.generation,
+ restoreComposerDraft, restoreConverterSnapshot, restoreConversions,
+ ])
+
// Handle conversation selection from the panel
// For a different ID the useEffect handles loading; for same ID force a refresh
const handlePanelSelectConversation = useCallback(async (convId: string): Promise => {
@@ -1022,6 +1164,7 @@ export default function ChatWindow({
setChatInputText('')
setDraftAttachments([])
converters.clearAll()
+ draftHandoff.clearPreservedDraft()
}
retireSend(operation)
}
@@ -2042,6 +2185,7 @@ export default function ChatWindow({
onClick={() => {
if (editDraft !== null) editorRef.current?.saveToNewAttack()
else {
+ discardDraftOnUnmountRef.current = true
navigationRevisionRef.current += 1
setIsPanelOpen(false)
onNewAttack()
@@ -2186,7 +2330,7 @@ export default function ChatWindow({
{editDraft === null && conversationLoadIssue?.conversationId === viewedConversationId && (
{conversationLoadIssue.detail}{' '}
- {!conversationLoadIssue.unavailable && attackResultId && viewedConversationId && (
+ {(!conversationLoadIssue.unavailable || !findingEvidenceId) && attackResultId && viewedConversationId && (
@@ -2258,6 +2402,8 @@ export default function ChatWindow({
isUndoing: isUndoingSend,
onUndo: () => { void handleUndoLastSend() },
} : undefined}
+ initialText={chatInputText}
+ initialAttachments={draftAttachments}
onSend={handleSend}
sendDisabled={sendDisabledReasons.length > 0}
sendDisabledReasons={sendDisabledReasons}
diff --git a/frontend/src/components/Configuration/Configuration.test.tsx b/frontend/src/components/Configuration/Configuration.test.tsx
index 40e8370d95..b284612b6a 100644
--- a/frontend/src/components/Configuration/Configuration.test.tsx
+++ b/frontend/src/components/Configuration/Configuration.test.tsx
@@ -6,6 +6,7 @@ import userEvent from '@testing-library/user-event'
import { createMemoryRouter, RouterProvider, useLocation, useNavigate } from 'react-router'
import { configurationApi, initializersApi } from '@/services/api'
+import { installRouterTestRequest } from '@/test-utils/routerRequest'
import Configuration from './Configuration'
@@ -29,19 +30,6 @@ jest.mock('@/services/api', () => ({
const mockedConfigurationApi = jest.mocked(configurationApi)
const mockedInitializersApi = jest.mocked(initializersApi)
-const originalRequest = globalThis.Request
-
-class RouterTestRequest {
- readonly url: string
- readonly method: string
- readonly signal: AbortSignal
-
- constructor(input: string | URL, init?: { method?: string, signal?: AbortSignal | null }) {
- this.url = String(input)
- this.method = init?.method ?? 'GET'
- this.signal = init?.signal ?? new AbortController().signal
- }
-}
function RouterProbe(): ReactElement {
// Keep Fluent focus management mounted across routes, like the app shell.
@@ -97,21 +85,12 @@ function renderPage(
}
describe('Configuration', () => {
+ let restoreRequest: () => void
beforeAll(() => {
- Object.defineProperty(globalThis, 'Request', {
- configurable: true,
- writable: true,
- value: RouterTestRequest,
- })
+ restoreRequest = installRouterTestRequest()
})
- afterAll(() => {
- Object.defineProperty(globalThis, 'Request', {
- configurable: true,
- writable: true,
- value: originalRequest,
- })
- })
+ afterAll(() => { restoreRequest() })
beforeEach(() => {
jest.clearAllMocks()
diff --git a/frontend/src/hooks/useChatDraftHandoff.test.tsx b/frontend/src/hooks/useChatDraftHandoff.test.tsx
new file mode 100644
index 0000000000..29bca6afe7
--- /dev/null
+++ b/frontend/src/hooks/useChatDraftHandoff.test.tsx
@@ -0,0 +1,653 @@
+/**
+ * Copyright (c) Microsoft Corporation.
+ * Licensed under the MIT license.
+ */
+
+import { act, renderHook } from '@testing-library/react'
+import type { ReactNode } from 'react'
+
+import {
+ canApplyPendingImport,
+ hasChatDraftState,
+ isChatDraftDirty,
+ releaseSupersededUrls,
+ revokeAttachmentUrls,
+ shouldApplyPreservedDraft,
+ type ChatDraftContent,
+ type PendingImportPayload,
+} from '@/utils/chatDraft'
+import type { ChatConverterSnapshot, MessageAttachment } from '@/types'
+
+import { ChatDraftProvider, useChatDraftHandoff } from './useChatDraftHandoff'
+
+const CONVERTERS: ChatConverterSnapshot = {
+ generation: 'test',
+ workingInputs: {},
+ pipelines: { text: [{ id: 'rot13-stage', converterId: 'rot13' }] },
+ stageResults: {},
+ errors: {},
+ applied: {
+ text: {
+ pieceId: 'text', pieceType: 'text', originalValue: 'Hello from draft',
+ convertedValue: 'Uryyb sebz qensg', convertedDataType: 'text', converterInstanceIds: ['rot13'],
+ },
+ },
+}
+
+describe('useChatDraftHandoff and chatDraft utilities', () => {
+ let revokeObjectURLSpy: jest.SpyInstance
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ revokeObjectURLSpy = jest.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {})
+ })
+
+ afterEach(() => {
+ revokeObjectURLSpy.mockRestore()
+ })
+
+ describe('isChatDraftDirty', () => {
+ it('returns false for empty and whitespace-only drafts with no extra fields', () => {
+ expect(isChatDraftDirty({ text: '' })).toBe(false)
+ expect(isChatDraftDirty({ text: ' \n\t ' })).toBe(false)
+ expect(
+ isChatDraftDirty({
+ text: '',
+ attachments: [],
+ systemPrompt: '',
+ converters: {
+ ...CONVERTERS,
+ applied: {},
+ pipelines: {},
+ },
+ }),
+ ).toBe(false)
+ })
+
+ it('returns true when text contains non-whitespace content', () => {
+ expect(isChatDraftDirty({ text: 'hello world' })).toBe(true)
+ })
+
+ it('returns true when media attachments are present even with empty text', () => {
+ const attachment: MessageAttachment = {
+ name: 'image.png',
+ type: 'image',
+ mimeType: 'image/png',
+ url: 'blob:http://localhost/test-blob',
+ size: 1024,
+ }
+ expect(isChatDraftDirty({ text: '', attachments: [attachment] })).toBe(true)
+ })
+
+ it('returns true when system prompt is set', () => {
+ expect(isChatDraftDirty({ text: '', systemPrompt: 'You are an adversarial tester' })).toBe(true)
+ })
+
+ it('returns true when applied converters are present', () => {
+ expect(
+ isChatDraftDirty({
+ text: '',
+ converters: CONVERTERS,
+ }),
+ ).toBe(true)
+ })
+ })
+
+ it('preserves target and unapplied setup without marking prompt content dirty', () => {
+ const converterSetup = { ...CONVERTERS, applied: {} }
+ for (const setup of [
+ { target: null },
+ { target: { registryName: 'selected-target', identifierHash: 'selected-hash' } },
+ { converters: converterSetup },
+ ]) {
+ expect(hasChatDraftState({ text: '', attachments: [], ...setup })).toBe(true)
+ expect(isChatDraftDirty({ text: '', attachments: [], ...setup })).toBe(false)
+ }
+ })
+
+ describe('shouldApplyPreservedDraft', () => {
+ it('returns false when preserved draft is null or clean', () => {
+ expect(shouldApplyPreservedDraft(null, null)).toBe(false)
+ expect(shouldApplyPreservedDraft(null, 'attack-123')).toBe(false)
+
+ const cleanDraft = {
+ originatingAttackId: null,
+ originatingConversationId: null,
+ originatingPath: '/chat',
+ draft: { text: ' ', attachments: [] },
+ savedAt: Date.now(),
+ sequence: 1,
+ }
+ expect(shouldApplyPreservedDraft(cleanDraft, null)).toBe(false)
+ })
+
+ it('returns true when draft target matches the active unsaved chat (null)', () => {
+ const unsavedDraft = {
+ originatingAttackId: null,
+ originatingConversationId: null,
+ originatingPath: '/chat',
+ draft: { text: 'draft prompt', attachments: [] },
+ savedAt: Date.now(),
+ sequence: 1,
+ }
+ expect(shouldApplyPreservedDraft(unsavedDraft, null)).toBe(true)
+ })
+
+ it('returns true when draft target matches the active attack ID', () => {
+ const persistedDraft = {
+ originatingAttackId: 'attack-456',
+ originatingConversationId: 'conv-456',
+ originatingPath: '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/attacks/attack-456',
+ draft: { text: 'draft for attack 456', attachments: [] },
+ savedAt: Date.now(),
+ sequence: 1,
+ }
+ expect(shouldApplyPreservedDraft(persistedDraft, 'attack-456')).toBe(false)
+ expect(shouldApplyPreservedDraft(persistedDraft, 'attack-456', 'conv-456')).toBe(true)
+ expect(shouldApplyPreservedDraft(persistedDraft, 'attack-456', 'other-conversation')).toBe(false)
+ })
+
+ it('returns false when active conversation does not match draft destination (prevents draft leak)', () => {
+ const attackDraft = {
+ originatingAttackId: 'attack-1',
+ originatingConversationId: 'conv-1',
+ originatingPath: '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/attacks/attack-1',
+ draft: { text: 'attack 1 prompt', attachments: [] },
+ savedAt: Date.now(),
+ sequence: 1,
+ }
+ expect(shouldApplyPreservedDraft(attackDraft, 'attack-2')).toBe(false)
+ expect(shouldApplyPreservedDraft(attackDraft, null)).toBe(false)
+
+ const unsavedDraft = {
+ originatingAttackId: null,
+ originatingConversationId: null,
+ originatingPath: '/chat',
+ draft: { text: 'unsaved draft', attachments: [] },
+ savedAt: Date.now(),
+ sequence: 1,
+ }
+ expect(shouldApplyPreservedDraft(unsavedDraft, 'attack-1')).toBe(false)
+ })
+ })
+
+ describe('canApplyPendingImport', () => {
+ it('returns false when pending import is null', () => {
+ expect(canApplyPendingImport(null, null)).toBe(false)
+ })
+
+ it('validates destination: new_attack only applies to unsaved chat (null)', () => {
+ const importPayload: PendingImportPayload = {
+ id: 'imp-1',
+ sequence: 1,
+ stagedAt: Date.now(),
+ destinationType: 'new_attack',
+ content: { text: 'imported prompt' },
+ }
+ expect(canApplyPendingImport(importPayload, null)).toBe(true)
+ expect(canApplyPendingImport(importPayload, 'existing-attack')).toBe(false)
+ })
+
+ it('validates destination: current_conversation only applies to matching targetAttackId', () => {
+ const importPayload: PendingImportPayload = {
+ id: 'imp-2',
+ sequence: 1,
+ stagedAt: Date.now(),
+ destinationType: 'current_conversation',
+ targetAttackId: 'target-attack-789',
+ targetConversationId: 'target-conversation-789',
+ content: { text: 'imported prompt' },
+ }
+ expect(canApplyPendingImport(importPayload, 'target-attack-789', 'target-conversation-789')).toBe(true)
+ expect(canApplyPendingImport(importPayload, 'target-attack-789')).toBe(false)
+ expect(canApplyPendingImport(importPayload, 'target-attack-789', 'other-conversation')).toBe(false)
+ expect(canApplyPendingImport(importPayload, 'other-attack')).toBe(false)
+ expect(canApplyPendingImport(importPayload, null)).toBe(false)
+ })
+
+ it('validates destination: any applies to both new and current chat', () => {
+ const importPayload: PendingImportPayload = {
+ id: 'imp-3',
+ sequence: 1,
+ stagedAt: Date.now(),
+ destinationType: 'any',
+ content: { text: 'imported prompt' },
+ }
+ expect(canApplyPendingImport(importPayload, null)).toBe(true)
+ expect(canApplyPendingImport(importPayload, 'attack-abc')).toBe(true)
+ })
+ })
+
+ describe('revokeAttachmentUrls and releaseSupersededUrls', () => {
+ it('revokes only blob: URLs and ignores other URL types', () => {
+ const attachments: MessageAttachment[] = [
+ { name: 'blob.png', type: 'image', mimeType: 'image/png', url: 'blob:http://localhost/test-1', size: 100 },
+ { name: 'blob2.png', type: 'image', mimeType: 'image/png', url: 'blob:http://localhost/test-2', size: 100 },
+ { name: 'data.png', type: 'image', mimeType: 'image/png', url: 'data:image/png;base64,abc', size: 100 },
+ { name: 'remote.png', type: 'image', mimeType: 'image/png', url: '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/api/media?path=test.png', size: 100 },
+ ]
+
+ revokeAttachmentUrls(attachments)
+ expect(revokeObjectURLSpy).toHaveBeenCalledTimes(2)
+ expect(revokeObjectURLSpy).toHaveBeenCalledWith('blob:http://localhost/test-1')
+ expect(revokeObjectURLSpy).toHaveBeenCalledWith('blob:http://localhost/test-2')
+ })
+
+ it('releases only superseded blob URLs that are absent from next attachments', () => {
+ const oldAttachments: MessageAttachment[] = [
+ { name: 'kept.png', type: 'image', mimeType: 'image/png', url: 'blob:http://localhost/kept', size: 100 },
+ { name: 'removed.png', type: 'image', mimeType: 'image/png', url: 'blob:http://localhost/removed', size: 100 },
+ ]
+ const newAttachments: MessageAttachment[] = [
+ { name: 'kept.png', type: 'image', mimeType: 'image/png', url: 'blob:http://localhost/kept', size: 100 },
+ { name: 'added.png', type: 'image', mimeType: 'image/png', url: 'blob:http://localhost/added', size: 100 },
+ ]
+
+ releaseSupersededUrls(oldAttachments, newAttachments)
+ expect(revokeObjectURLSpy).toHaveBeenCalledTimes(1)
+ expect(revokeObjectURLSpy).toHaveBeenCalledWith('blob:http://localhost/removed')
+ })
+ })
+
+ describe('ChatDraftProvider and useChatDraftHandoff hook', () => {
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ {children}
+ )
+
+ it('returns fallback default context safely when used outside of Provider', () => {
+ const { result } = renderHook(() => useChatDraftHandoff())
+ expect(result.current.preservedDraft).toBeNull()
+ expect(result.current.pendingImport).toBeNull()
+ expect(result.current.activeSequence).toBe(0)
+ expect(result.current.consumePendingImport()).toBeNull()
+ expect(result.current.consumePreservedDraft(null)).toBeNull()
+ expect(result.current.isDraftDirty({ text: 'text' })).toBe(true)
+ expect(() => result.current.stagePendingImport({
+ destinationType: 'new_attack', content: { text: 'Cannot stage without an owner' },
+ })).toThrow('Chat imports require a ChatDraftProvider.')
+ })
+
+ it('preserves draft across round trip and returns complete draft content', () => {
+ const { result } = renderHook(() => useChatDraftHandoff(), { wrapper })
+
+ const draftContent: ChatDraftContent = {
+ text: 'Hello from draft',
+ systemPrompt: 'Adversarial system prompt',
+ attachments: [
+ { name: 'sample.png', type: 'image', mimeType: 'image/png', url: 'blob:http://localhost/img1', size: 500 },
+ ],
+ converters: CONVERTERS,
+ }
+
+ act(() => {
+ result.current.preserveDraft({
+ originatingAttackId: null,
+ originatingConversationId: null,
+ originatingPath: '/chat',
+ draft: draftContent,
+ })
+ })
+
+ expect(result.current.preservedDraft).not.toBeNull()
+ expect(result.current.preservedDraft?.draft.text).toBe('Hello from draft')
+ expect(result.current.preservedDraft?.draft.systemPrompt).toBe('Adversarial system prompt')
+ expect(result.current.preservedDraft?.draft.attachments).toHaveLength(1)
+ expect(result.current.preservedDraft?.draft.converters).toEqual(CONVERTERS)
+
+ // Consume preserved draft once
+ let consumed: ChatDraftContent | null = null
+ act(() => {
+ consumed = result.current.consumePreservedDraft(null)
+ })
+ expect(consumed).not.toBeNull()
+ expect(consumed?.text).toBe('Hello from draft')
+ expect(consumed?.converters?.applied.text.convertedValue).toBe('Uryyb sebz qensg')
+
+ // Second consumption returns null (single-use guarantee prevents duplicate restores)
+ act(() => {
+ consumed = result.current.consumePreservedDraft(null)
+ })
+ expect(consumed).toBeNull()
+ expect(result.current.preservedDraft).toBeNull()
+ })
+
+ it('does not consume or leak preserved draft when active context does not match', () => {
+ const { result } = renderHook(() => useChatDraftHandoff(), { wrapper })
+
+ act(() => {
+ result.current.preserveDraft({
+ originatingAttackId: 'attack-100',
+ originatingConversationId: 'conv-100',
+ originatingPath: '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/attacks/attack-100',
+ draft: { text: 'Attack 100 draft', attachments: [] },
+ })
+ })
+
+ // Querying for a different attack ID or unsaved chat returns null
+ let wrongContextDraft: ChatDraftContent | null = null
+ act(() => {
+ wrongContextDraft = result.current.consumePreservedDraft('attack-999')
+ })
+ expect(wrongContextDraft).toBeNull()
+
+ act(() => {
+ wrongContextDraft = result.current.consumePreservedDraft(null)
+ })
+ expect(wrongContextDraft).toBeNull()
+
+ // The draft is NOT discarded by wrong context queries
+ expect(result.current.preservedDraft).not.toBeNull()
+
+ // When correct attack ID is requested, draft is successfully consumed
+ let rightContextDraft: ChatDraftContent | null = null
+ act(() => {
+ rightContextDraft = result.current.consumePreservedDraft('attack-100', 'conv-100')
+ })
+ expect(rightContextDraft?.text).toBe('Attack 100 draft')
+ expect(result.current.preservedDraft).toBeNull()
+ })
+
+ it('ensures clearing a draft stays cleared after consuming: subsequent consume returns null and unmount with empty draft does not resurrect old snapshot', () => {
+ const { result } = renderHook(() => useChatDraftHandoff(), { wrapper })
+
+ act(() => {
+ result.current.preserveDraft({
+ originatingAttackId: null,
+ originatingConversationId: null,
+ originatingPath: '/chat',
+ draft: { text: 'my draft text', attachments: [] },
+ })
+ })
+ expect(result.current.preservedDraft?.draft.text).toBe('my draft text')
+
+ // Consumed when returning to Chat
+ let consumed: ChatDraftContent | null = null
+ act(() => {
+ consumed = result.current.consumePreservedDraft(null)
+ })
+ expect(consumed?.text).toBe('my draft text')
+ expect(result.current.preservedDraft).toBeNull()
+
+ // User clears the text: empty draft is not dirty
+ const emptyDraft: ChatDraftContent = { text: '', attachments: [] }
+ expect(result.current.isDraftDirty(emptyDraft)).toBe(false)
+
+ // When leaving to datasets with empty draft, preservedDraft remains null
+ expect(result.current.preservedDraft).toBeNull()
+ })
+
+ it('cleans up superseded blob URLs when draft is overwritten with new attachments', () => {
+ const { result } = renderHook(() => useChatDraftHandoff(), { wrapper })
+
+ act(() => {
+ result.current.preserveDraft({
+ originatingAttackId: null,
+ originatingConversationId: null,
+ originatingPath: '/chat',
+ draft: {
+ text: 'v1',
+ attachments: [
+ { name: 'old.png', type: 'image', mimeType: 'image/png', url: 'blob:http://localhost/old', size: 100 },
+ ],
+ },
+ })
+ })
+ expect(revokeObjectURLSpy).not.toHaveBeenCalled()
+
+ act(() => {
+ result.current.preserveDraft({
+ originatingAttackId: null,
+ originatingConversationId: null,
+ originatingPath: '/chat',
+ draft: {
+ text: 'v2',
+ attachments: [
+ { name: 'new.png', type: 'image', mimeType: 'image/png', url: 'blob:http://localhost/new', size: 100 },
+ ],
+ },
+ })
+ })
+ expect(revokeObjectURLSpy).toHaveBeenCalledWith('blob:http://localhost/old')
+ expect(revokeObjectURLSpy).not.toHaveBeenCalledWith('blob:http://localhost/new')
+ })
+
+ it('revokes blob URLs and clears state when clearPreservedDraft is called', () => {
+ const { result } = renderHook(() => useChatDraftHandoff(), { wrapper })
+
+ act(() => {
+ result.current.preserveDraft({
+ originatingAttackId: null,
+ originatingConversationId: null,
+ originatingPath: '/chat',
+ draft: {
+ text: 'to be cleared',
+ attachments: [
+ { name: 'blob1.png', type: 'image', mimeType: 'image/png', url: 'blob:http://localhost/blob1', size: 100 },
+ ],
+ },
+ })
+ })
+
+ act(() => {
+ result.current.clearPreservedDraft()
+ })
+ expect(revokeObjectURLSpy).toHaveBeenCalledWith('blob:http://localhost/blob1')
+ expect(result.current.preservedDraft).toBeNull()
+ })
+
+ it('stages, consumes, and dismisses pending imports with single-use guarantee and cleanup', () => {
+ const { result } = renderHook(() => useChatDraftHandoff(), { wrapper })
+
+ let staged: PendingImportPayload | null = null
+ act(() => {
+ staged = result.current.stagePendingImport({
+ destinationType: 'new_attack',
+ content: {
+ text: 'imported seed prompt',
+ attachments: [
+ { name: 'imported.png', type: 'image', mimeType: 'image/png', url: 'blob:http://localhost/imp-blob', size: 200 },
+ ],
+ },
+ })
+ })
+ expect(staged).not.toBeNull()
+ expect(result.current.pendingImport).not.toBeNull()
+ expect(result.current.pendingImport?.content.text).toBe('imported seed prompt')
+
+ // Consuming pending import returns the payload and clears state
+ let consumed: PendingImportPayload | null = null
+ act(() => {
+ consumed = result.current.consumePendingImport()
+ })
+ expect(consumed?.id).toBe(staged?.id)
+ expect(consumed?.content.text).toBe('imported seed prompt')
+ expect(result.current.pendingImport).toBeNull()
+
+ // Subsequent call returns null (protects against rerender duplication)
+ act(() => {
+ consumed = result.current.consumePendingImport()
+ })
+ expect(consumed).toBeNull()
+
+ // Test dismissPendingImport with blob revocation
+ act(() => {
+ result.current.stagePendingImport({
+ destinationType: 'current_conversation',
+ targetAttackId: 'attack-1',
+ targetConversationId: 'conv-1',
+ content: {
+ text: 'dismiss me',
+ attachments: [
+ { name: 'dismissed.png', type: 'image', mimeType: 'image/png', url: 'blob:http://localhost/dismiss-blob', size: 200 },
+ ],
+ },
+ })
+ })
+ act(() => {
+ result.current.dismissPendingImport()
+ })
+ expect(result.current.pendingImport).toBeNull()
+ expect(revokeObjectURLSpy).toHaveBeenCalledWith('blob:http://localhost/dismiss-blob')
+ })
+
+ it('revokes remaining blob URLs on Provider unmount', () => {
+ const { result, unmount } = renderHook(() => useChatDraftHandoff(), { wrapper })
+
+ act(() => {
+ result.current.preserveDraft({
+ originatingAttackId: null,
+ originatingConversationId: null,
+ originatingPath: '/chat',
+ draft: {
+ text: 'unmount draft',
+ attachments: [
+ { name: 'unmount-draft.png', type: 'image', mimeType: 'image/png', url: 'blob:http://localhost/unmount-draft', size: 100 },
+ ],
+ },
+ })
+ result.current.stagePendingImport({
+ destinationType: 'new_attack',
+ content: {
+ text: 'unmount import',
+ attachments: [
+ { name: 'unmount-imp.png', type: 'image', mimeType: 'image/png', url: 'blob:http://localhost/unmount-imp', size: 100 },
+ ],
+ },
+ })
+ })
+
+ unmount()
+ expect(revokeObjectURLSpy).toHaveBeenCalledWith('blob:http://localhost/unmount-draft')
+ expect(revokeObjectURLSpy).toHaveBeenCalledWith('blob:http://localhost/unmount-imp')
+ })
+
+ it('does not let a stale restoration consume a newer snapshot for the same destination', () => {
+ const { result } = renderHook(() => useChatDraftHandoff(), { wrapper })
+ act(() => {
+ result.current.preserveDraft({
+ originatingAttackId: null, originatingConversationId: null, originatingPath: '/chat',
+ draft: { text: 'Earlier draft', attachments: [] },
+ })
+ })
+ const sequence = result.current.preservedDraft?.sequence
+ act(() => {
+ result.current.preserveDraft({
+ originatingAttackId: null, originatingConversationId: null, originatingPath: '/chat',
+ draft: { text: 'Newer draft', attachments: [] },
+ })
+ expect(result.current.consumePreservedDraft(null, null, sequence)).toBeNull()
+ result.current.clearPreservedDraft(sequence)
+ })
+ expect(result.current.preservedDraft?.draft.text).toBe('Newer draft')
+ })
+
+ it.each(['current_conversation', 'new_conversation'] as const)(
+ 'checks the complete %s destination even when no import ID is supplied',
+ (destinationType: 'current_conversation' | 'new_conversation') => {
+ const { result } = renderHook(() => useChatDraftHandoff(), { wrapper })
+ act(() => {
+ result.current.stagePendingImport({
+ destinationType, targetAttackId: 'attack', targetConversationId: 'destination',
+ content: { text: 'Only for the destination' },
+ })
+ expect(result.current.consumePendingImport(undefined, 'attack', null)).toBeNull()
+ expect(result.current.consumePendingImport(undefined, 'attack', 'other')).toBeNull()
+ expect(result.current.consumePendingImport(undefined, 'attack', 'destination')?.content.text)
+ .toBe('Only for the destination')
+ })
+ expect(result.current.pendingImport).toBeNull()
+ },
+ )
+
+ it('rejects an async import prepared before a newer draft or an explicit reset', () => {
+ const { result } = renderHook(() => useChatDraftHandoff(), { wrapper })
+ const sequence = result.current.activeSequence
+ const attachment: MessageAttachment = {
+ type: 'image', mimeType: 'image/png', name: 'stale.png', url: 'blob:stale-import',
+ }
+ act(() => {
+ result.current.preserveDraft({
+ originatingAttackId: null, originatingConversationId: null, originatingPath: '/chat',
+ draft: { text: 'Newer draft', attachments: [] },
+ })
+ expect(result.current.stagePendingImport({
+ destinationType: 'new_attack', content: { text: 'Stale result', attachments: [attachment] },
+ }, sequence)).toBeNull()
+ })
+ expect(result.current.pendingImport).toBeNull()
+ expect(result.current.preservedDraft?.draft.text).toBe('Newer draft')
+ expect(revokeObjectURLSpy).toHaveBeenCalledWith(attachment.url)
+ const beforeReset = result.current.activeSequence
+ act(() => {
+ result.current.clearPreservedDraft()
+ expect(result.current.stagePendingImport({
+ destinationType: 'new_attack', content: { text: 'Result after cancellation' },
+ }, beforeReset)).toBeNull()
+ })
+ expect(result.current.pendingImport).toBeNull()
+ })
+
+ it('keeps shared blob URLs alive when either preserved or pending content is replaced', () => {
+ const { result } = renderHook(() => useChatDraftHandoff(), { wrapper })
+ const attachment: MessageAttachment = {
+ type: 'image', mimeType: 'image/png', name: 'shared.png', url: 'blob:shared',
+ }
+ act(() => {
+ result.current.preserveDraft({
+ originatingAttackId: null, originatingConversationId: null, originatingPath: '/chat',
+ draft: { text: 'Preserved', attachments: [attachment] },
+ })
+ result.current.stagePendingImport({
+ destinationType: 'new_attack', content: { text: 'Pending', attachments: [attachment] },
+ })
+ result.current.stagePendingImport({
+ destinationType: 'new_attack', content: { text: 'Replacement' },
+ })
+ })
+ expect(revokeObjectURLSpy).not.toHaveBeenCalledWith(attachment.url)
+ act(() => { result.current.clearPreservedDraft() })
+ expect(revokeObjectURLSpy).toHaveBeenCalledWith(attachment.url)
+ })
+
+ it('does not revoke a pending import attachment when preserved content is cleared', () => {
+ const { result } = renderHook(() => useChatDraftHandoff(), { wrapper })
+ const attachment: MessageAttachment = {
+ type: 'image', mimeType: 'image/png', name: 'shared.png', url: 'blob:shared',
+ }
+ act(() => {
+ result.current.preserveDraft({
+ originatingAttackId: null, originatingConversationId: null, originatingPath: '/chat',
+ draft: { text: 'Preserved', attachments: [attachment] },
+ })
+ result.current.stagePendingImport({
+ destinationType: 'new_attack', content: { text: 'Pending', attachments: [attachment] },
+ })
+ result.current.clearPreservedDraft()
+ })
+ expect(revokeObjectURLSpy).not.toHaveBeenCalledWith(attachment.url)
+ act(() => { result.current.dismissPendingImport() })
+ expect(revokeObjectURLSpy).toHaveBeenCalledTimes(1)
+ expect(revokeObjectURLSpy).toHaveBeenCalledWith(attachment.url)
+ })
+
+ it('invalidates stale pending content without revoking a newer draft attachment', () => {
+ const { result } = renderHook(() => useChatDraftHandoff(), { wrapper })
+ const attachment: MessageAttachment = {
+ type: 'image', mimeType: 'image/png', name: 'shared.png', url: 'blob:new-owner',
+ }
+ act(() => {
+ result.current.stagePendingImport({
+ destinationType: 'new_attack', content: { text: 'Old import', attachments: [attachment] },
+ })
+ result.current.preserveDraft({
+ originatingAttackId: null, originatingConversationId: null, originatingPath: '/chat',
+ draft: { text: 'Newer draft', attachments: [attachment] },
+ })
+ expect(result.current.consumePendingImport()).toBeNull()
+ })
+ expect(result.current.pendingImport).toBeNull()
+ expect(result.current.preservedDraft?.draft.text).toBe('Newer draft')
+ expect(revokeObjectURLSpy).not.toHaveBeenCalledWith(attachment.url)
+ })
+ })
+})
diff --git a/frontend/src/hooks/useChatDraftHandoff.tsx b/frontend/src/hooks/useChatDraftHandoff.tsx
new file mode 100644
index 0000000000..8c15232bac
--- /dev/null
+++ b/frontend/src/hooks/useChatDraftHandoff.tsx
@@ -0,0 +1,197 @@
+import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
+
+import type {
+ ChatDraftContent, ChatDraftContextState, ChatDraftHandoffContextValue, PendingImportPayload,
+} from '@/types'
+import { generateClientId } from '@/utils/clientId'
+import {
+ canApplyPendingImport,
+ isChatDraftDirty,
+ releaseSupersededUrls,
+ revokeAttachmentUrls,
+ shouldApplyPreservedDraft,
+} from '@/utils/chatDraft'
+
+const ChatDraftHandoffContext = createContext(null)
+
+export function ChatDraftProvider({ children }: { children: ReactNode }) {
+ const [preservedDraft, setPreservedDraft] = useState(null)
+ const [pendingImport, setPendingImport] = useState(null)
+ const [activeSequence, setActiveSequence] = useState(0)
+ const sequenceRef = useRef(0)
+ const preservedDraftRef = useRef(null)
+ const pendingImportRef = useRef(null)
+ const mountedRef = useRef(true)
+
+ useEffect(() => {
+ mountedRef.current = true
+ return () => {
+ mountedRef.current = false
+ revokeAttachmentUrls([
+ ...preservedDraftRef.current?.draft.attachments ?? [],
+ ...pendingImportRef.current?.content.attachments ?? [],
+ ])
+ preservedDraftRef.current = null
+ pendingImportRef.current = null
+ }
+ }, [])
+
+ const advanceSequence = useCallback((): number => {
+ sequenceRef.current += 1
+ setActiveSequence(sequenceRef.current)
+ return sequenceRef.current
+ }, [])
+
+ const preserveDraft = useCallback((state: Omit) => {
+ // Parent effects are cleaned up before the active composer's unmount.
+ if (!mountedRef.current) {
+ revokeAttachmentUrls(state.draft.attachments)
+ return
+ }
+ releaseSupersededUrls(preservedDraftRef.current?.draft.attachments, [
+ ...state.draft.attachments,
+ ...pendingImportRef.current?.content.attachments ?? [],
+ ])
+ const nextState: ChatDraftContextState = {
+ ...state,
+ savedAt: Date.now(),
+ sequence: advanceSequence(),
+ }
+ preservedDraftRef.current = nextState
+ setPreservedDraft(nextState)
+ }, [advanceSequence])
+
+ const clearPreservedDraft = useCallback((expectedSequence?: number) => {
+ const current = preservedDraftRef.current
+ if (expectedSequence !== undefined && current?.sequence !== expectedSequence) return
+ releaseSupersededUrls(current?.draft.attachments, pendingImportRef.current?.content.attachments)
+ preservedDraftRef.current = null
+ setPreservedDraft(null)
+ advanceSequence()
+ }, [advanceSequence])
+
+ const stagePendingImport = useCallback((
+ payload: Omit,
+ expectedSequence?: number,
+ ): PendingImportPayload | null => {
+ if (!mountedRef.current || (expectedSequence !== undefined && expectedSequence !== sequenceRef.current)) {
+ releaseSupersededUrls(payload.content.attachments, [
+ ...preservedDraftRef.current?.draft.attachments ?? [],
+ ...pendingImportRef.current?.content.attachments ?? [],
+ ])
+ return null
+ }
+ releaseSupersededUrls(pendingImportRef.current?.content.attachments, [
+ ...payload.content.attachments ?? [],
+ ...preservedDraftRef.current?.draft.attachments ?? [],
+ ])
+ const staged: PendingImportPayload = {
+ ...payload,
+ id: generateClientId(),
+ sequence: advanceSequence(),
+ stagedAt: Date.now(),
+ }
+ pendingImportRef.current = staged
+ setPendingImport(staged)
+ return staged
+ }, [advanceSequence])
+
+ const consumePendingImport = useCallback((
+ id?: string,
+ currentAttackId: string | null = null,
+ currentConversationId: string | null = null,
+ ): PendingImportPayload | null => {
+ const current = pendingImportRef.current
+ if (!current) return null
+ if (id && current.id !== id) return null
+ // Guard against stale asynchronous completion
+ if (current.sequence < sequenceRef.current) {
+ releaseSupersededUrls(current.content.attachments, preservedDraftRef.current?.draft.attachments)
+ setPendingImport(null)
+ pendingImportRef.current = null
+ return null
+ }
+ // Verify destination matches
+ if (!canApplyPendingImport(current, currentAttackId, currentConversationId)) {
+ return null
+ }
+ // Consumed: clear pending import so it cannot be applied twice
+ setPendingImport(null)
+ pendingImportRef.current = null
+ return current
+ }, [])
+
+ const dismissPendingImport = useCallback((id?: string) => {
+ const current = pendingImportRef.current
+ if (id && current?.id !== id) return
+ releaseSupersededUrls(current?.content.attachments, preservedDraftRef.current?.draft.attachments)
+ pendingImportRef.current = null
+ setPendingImport(null)
+ advanceSequence()
+ }, [advanceSequence])
+
+ const consumePreservedDraft = useCallback((
+ currentAttackId: string | null,
+ currentConversationId: string | null = null,
+ expectedSequence?: number,
+ ): ChatDraftContent | null => {
+ const current = preservedDraftRef.current
+ if (!current) return null
+ if (expectedSequence !== undefined && current.sequence !== expectedSequence) return null
+ if (!shouldApplyPreservedDraft(current, currentAttackId, currentConversationId)) {
+ return null
+ }
+ // Return draft content without revoking attachments (ownership transfers to ChatWindow)
+ setPreservedDraft(null)
+ preservedDraftRef.current = null
+ return current.draft
+ }, [])
+
+ const value = useMemo(() => ({
+ preservedDraft,
+ pendingImport,
+ activeSequence,
+ preserveDraft,
+ clearPreservedDraft,
+ stagePendingImport,
+ consumePendingImport,
+ dismissPendingImport,
+ consumePreservedDraft,
+ isDraftDirty: isChatDraftDirty,
+ }), [
+ preservedDraft,
+ pendingImport,
+ activeSequence,
+ preserveDraft,
+ clearPreservedDraft,
+ stagePendingImport,
+ consumePendingImport,
+ dismissPendingImport,
+ consumePreservedDraft,
+ ])
+
+ return (
+
+ {children}
+
+ )
+}
+
+const DEFAULT_CHAT_DRAFT_HANDOFF: ChatDraftHandoffContextValue = {
+ preservedDraft: null,
+ pendingImport: null,
+ activeSequence: 0,
+ preserveDraft: () => {},
+ clearPreservedDraft: () => {},
+ stagePendingImport: () => { throw new Error('Chat imports require a ChatDraftProvider.') },
+ consumePendingImport: () => null,
+ dismissPendingImport: () => {},
+ consumePreservedDraft: () => null,
+ isDraftDirty: isChatDraftDirty,
+}
+
+// eslint-disable-next-line react-refresh/only-export-components
+export function useChatDraftHandoff(): ChatDraftHandoffContextValue {
+ const context = useContext(ChatDraftHandoffContext)
+ return context ?? DEFAULT_CHAT_DRAFT_HANDOFF
+}
diff --git a/frontend/src/hooks/useConversationMessages.test.ts b/frontend/src/hooks/useConversationMessages.test.ts
index 5f450a4ab3..2e70e7d777 100644
--- a/frontend/src/hooks/useConversationMessages.test.ts
+++ b/frontend/src/hooks/useConversationMessages.test.ts
@@ -137,12 +137,21 @@ describe('useConversationMessages', () => {
await act(async () => { await result.current.loadConversation('attack', 'main') })
expect(contents(result.current.messages)).toEqual(['main:1'])
+ expect(result.current.conversationLoadIssue).toEqual({
+ conversationId: 'main', unavailable: false, detail: 'Could not load conversation: Refresh failed',
+ })
getMessages.mockRejectedValueOnce(new Error('Initial load failed'))
rerender({ activeConversationId: 'branch' })
await waitFor(() => expect(result.current.loadedConversationId).toBe('branch'))
expect(result.current.messages).toEqual([])
expect(result.current.isLoadingMessages).toBe(false)
+ expect(result.current.conversationLoadIssue?.detail).toBe('Could not load conversation: Initial load failed')
+
+ getMessages.mockResolvedValueOnce(transcript('branch'))
+ await act(async () => { await result.current.loadConversation('attack', 'branch') })
+ expect(result.current.conversationLoadIssue).toBeNull()
+ expect(contents(result.current.messages)).toEqual(['branch:1'])
})
it('should skip loaded or sending conversations unless a forced load is requested', async () => {
diff --git a/frontend/src/hooks/useConversationMessages.ts b/frontend/src/hooks/useConversationMessages.ts
index ab80d4ac71..07268a3020 100644
--- a/frontend/src/hooks/useConversationMessages.ts
+++ b/frontend/src/hooks/useConversationMessages.ts
@@ -152,13 +152,12 @@ export function useConversationMessages({
markConversationLoaded(convId)
} catch (cause: unknown) {
if (!isCurrentLoad() || viewedConvRef.current !== convId) { return }
- if (findingEvidenceId) {
- const error = toApiError(cause)
- setConversationLoadIssue({
- conversationId: convId, unavailable: error.status === 404,
- detail: error.status === 404 ? 'Evidence unavailable' : `Could not load conversation: ${error.detail}`,
- })
- }
+ const error = toApiError(cause)
+ setConversationLoadIssue({
+ conversationId: convId, unavailable: error.status === 404,
+ detail: error.status === 404 && findingEvidenceId
+ ? 'Evidence unavailable' : `Could not load conversation: ${error.detail}`,
+ })
// Initial-load failures must not show another conversation's transcript.
// Refresh failures keep the already-loaded transcript and recovery aligned.
if (loadedConversationIdRef.current !== convId) {
diff --git a/frontend/src/test-utils/routerRequest.ts b/frontend/src/test-utils/routerRequest.ts
new file mode 100644
index 0000000000..34b4fc4c50
--- /dev/null
+++ b/frontend/src/test-utils/routerRequest.ts
@@ -0,0 +1,23 @@
+class RouterTestRequest {
+ readonly url: string
+ readonly method: string
+ readonly signal: AbortSignal
+
+ constructor(input: string | URL, init?: { method?: string; signal?: AbortSignal | null }) {
+ this.url = String(input)
+ this.method = init?.method ?? 'GET'
+ this.signal = init?.signal ?? new AbortController().signal
+ }
+}
+
+/** Provides the Request fields used by data-router navigation in JSDOM. */
+export function installRouterTestRequest(): () => void {
+ const original = Object.getOwnPropertyDescriptor(globalThis, 'Request')
+ Object.defineProperty(globalThis, 'Request', {
+ configurable: true, writable: true, value: RouterTestRequest,
+ })
+ return () => {
+ if (original) Object.defineProperty(globalThis, 'Request', original)
+ else Reflect.deleteProperty(globalThis, 'Request')
+ }
+}
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index 19b3bd2317..b2b6b5e0c8 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -98,6 +98,68 @@ export interface ChatConverterSnapshot {
applied: Record
}
+export interface ChatDraftContent {
+ text: string
+ attachments: MessageAttachment[]
+ systemPrompt?: string
+ target?: TargetReference | null
+ converters?: ChatConverterSnapshot
+ textMetadata?: Record
+}
+
+export interface ChatDraftContextState {
+ originatingAttackId: string | null
+ originatingConversationId: string | null
+ originatingPath: string
+ originatingState?: unknown
+ draft: ChatDraftContent
+ savedAt: number
+ sequence: number
+}
+
+export type ImportDestinationType = 'new_attack' | 'current_conversation' | 'new_conversation' | 'any'
+
+export interface PendingImportPayload {
+ id: string
+ sequence: number
+ destinationType: ImportDestinationType
+ targetAttackId?: string | null
+ targetConversationId?: string | null
+ content: {
+ text: string
+ attachments?: MessageAttachment[]
+ textMetadata?: Record
+ }
+ replaceDirty?: boolean
+ focus?: boolean
+ stagedAt: number
+}
+
+export interface ChatDraftHandoffContextValue {
+ preservedDraft: ChatDraftContextState | null
+ pendingImport: PendingImportPayload | null
+ activeSequence: number
+ preserveDraft: (state: Omit) => void
+ clearPreservedDraft: (expectedSequence?: number) => void
+ /** Pass the sequence captured before preparing an import to reject stale async results. */
+ stagePendingImport: (
+ payload: Omit,
+ expectedSequence?: number,
+ ) => PendingImportPayload | null
+ consumePendingImport: (
+ id?: string,
+ currentAttackId?: string | null,
+ currentConversationId?: string | null,
+ ) => PendingImportPayload | null
+ dismissPendingImport: (id?: string) => void
+ consumePreservedDraft: (
+ currentAttackId: string | null,
+ currentConversationId?: string | null,
+ expectedSequence?: number,
+ ) => ChatDraftContent | null
+ isDraftDirty: (draft?: Partial | null) => boolean
+}
+
export interface UndoLastSendAction {
readonly disabledReason?: string
readonly isUndoing: boolean
diff --git a/frontend/src/utils/chatDraft.ts b/frontend/src/utils/chatDraft.ts
new file mode 100644
index 0000000000..6a62986e42
--- /dev/null
+++ b/frontend/src/utils/chatDraft.ts
@@ -0,0 +1,75 @@
+import type {
+ ChatDraftContent, ChatDraftContextState, ConverterPipelineStage, MessageAttachment, PendingImportPayload,
+} from '@/types'
+
+export type { ChatDraftContent, ChatDraftContextState, ChatDraftHandoffContextValue, PendingImportPayload } from '@/types'
+
+/** Explicitly revokes all blob URLs associated with the given attachments. */
+export function revokeAttachmentUrls(attachments?: readonly MessageAttachment[]): void {
+ if (!attachments || typeof URL === 'undefined' || typeof URL.revokeObjectURL !== 'function') return
+ for (const url of new Set(attachments.map((attachment: MessageAttachment) => attachment.url))) {
+ if (url.startsWith('blob:')) URL.revokeObjectURL(url)
+ }
+}
+
+/** Revokes blob URLs in previousAttachments that are not present in nextAttachments. */
+export function releaseSupersededUrls(
+ previousAttachments?: readonly MessageAttachment[],
+ nextAttachments?: readonly MessageAttachment[],
+): void {
+ if (typeof URL === 'undefined' || typeof URL.revokeObjectURL !== 'function') return
+ const activeUrls = new Set((nextAttachments ?? []).map((attachment: MessageAttachment) => attachment.url))
+ revokeAttachmentUrls(previousAttachments?.filter((attachment: MessageAttachment) => !activeUrls.has(attachment.url)))
+}
+
+/** Determines if draft content contains user-entered text, attachments, system prompt, or converters. */
+export function isChatDraftDirty(draft?: Partial | null): boolean {
+ if (!draft) return false
+ if (typeof draft.text === 'string' && draft.text.trim().length > 0) return true
+ if (Array.isArray(draft.attachments) && draft.attachments.length > 0) return true
+ if (typeof draft.systemPrompt === 'string' && draft.systemPrompt.trim().length > 0) return true
+ if (draft.converters?.applied && Object.keys(draft.converters.applied).length > 0) return true
+ return false
+}
+
+/** Setup must survive navigation without counting as prompt replacement. */
+export function hasChatDraftState(draft?: Partial | null): boolean {
+ return Boolean(draft && (
+ isChatDraftDirty(draft)
+ || draft.target !== undefined
+ || Object.values(draft.converters?.pipelines ?? {}).some((stages: ConverterPipelineStage[]) => stages.length > 0)
+ ))
+}
+
+/**
+ * Checks whether a preserved draft belongs to the destination attack and conversation.
+ * Prevents an unrelated draft from overwriting another attack or conversation.
+ */
+export function shouldApplyPreservedDraft(
+ preserved: ChatDraftContextState | null,
+ attackId: string | null,
+ conversationId?: string | null,
+): boolean {
+ return Boolean(preserved && hasChatDraftState(preserved.draft)
+ && attackId === preserved.originatingAttackId
+ && (conversationId ?? null) === preserved.originatingConversationId)
+}
+
+/**
+ * Checks whether a pending import can be applied to the current attack/conversation.
+ */
+export function canApplyPendingImport(
+ pending?: PendingImportPayload | null,
+ attackId?: string | null,
+ conversationId?: string | null,
+): boolean {
+ if (!pending) return false
+ if (pending.destinationType === 'any') {
+ return true
+ }
+ if (pending.destinationType === 'new_attack') {
+ return attackId === null && conversationId == null
+ }
+ return Boolean(pending.targetAttackId && pending.targetConversationId
+ && attackId === pending.targetAttackId && conversationId === pending.targetConversationId)
+}
diff --git a/frontend/src/utils/routeParams.test.ts b/frontend/src/utils/routeParams.test.ts
index 14c9551ed7..dc1f2e98ab 100644
--- a/frontend/src/utils/routeParams.test.ts
+++ b/frontend/src/utils/routeParams.test.ts
@@ -10,6 +10,8 @@ import {
scenarioRunRoutePath,
findingEvidenceOrigin,
selectionKeyFromSearchParams,
+ isDatasetsPath,
+ isChatPath,
} from './routeParams'
const SCENARIO_RESULT_ID = '123e4567-e89b-12d3-a456-426614174000'
@@ -125,3 +127,23 @@ describe('dataset detail paths', () => {
expect(catalogPathFromNavigationState({ catalogPath: '/datasets/../admin' })).toBe('/datasets')
})
})
+
+describe('isDatasetsPath and isChatPath', () => {
+ it('correctly detects datasets routes', () => {
+ expect(isDatasetsPath('/datasets')).toBe(true)
+ expect(isDatasetsPath('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/datasets/detail')).toBe(true)
+ expect(isDatasetsPath('/datasets?filter=harmful')).toBe(true)
+ expect(isDatasetsPath('/chat')).toBe(false)
+ expect(isDatasetsPath('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/attacks/123')).toBe(false)
+ expect(isDatasetsPath('')).toBe(false)
+ })
+
+ it('correctly detects chat and attack routes', () => {
+ expect(isChatPath('/chat')).toBe(true)
+ expect(isChatPath('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/attacks/attack-123')).toBe(true)
+ expect(isChatPath('/attacks/attack-123/conversations/conv-456')).toBe(true)
+ expect(isChatPath('/datasets')).toBe(false)
+ expect(isChatPath('/history')).toBe(false)
+ expect(isChatPath('')).toBe(false)
+ })
+})
diff --git a/frontend/src/utils/routeParams.ts b/frontend/src/utils/routeParams.ts
index d0ca938e3e..a806c314da 100644
--- a/frontend/src/utils/routeParams.ts
+++ b/frontend/src/utils/routeParams.ts
@@ -142,3 +142,17 @@ function isCatalogReturnPath(value: string): boolean {
&& url.pathname === DATASETS_PATH
&& url.hash === ''
}
+
+/** Returns true if the pathname or path belongs to the dataset catalog or dataset detail view. */
+export function isDatasetsPath(pathOrUrl: string): boolean {
+ if (!pathOrUrl) return false
+ const cleanPath = pathOrUrl.split('?')[0].split('#')[0]
+ return cleanPath === DATASETS_PATH || cleanPath === DATASET_DETAIL_PATH || cleanPath.startsWith(`${DATASETS_PATH}/`)
+}
+
+/** Returns true if the pathname or path belongs to the chat view or an attack view. */
+export function isChatPath(pathOrUrl: string): boolean {
+ if (!pathOrUrl) return false
+ const cleanPath = pathOrUrl.split('?')[0].split('#')[0]
+ return cleanPath === '/chat' || cleanPath.startsWith('/attacks/')
+}