Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions frontend/src/app/AppShell.recordSelection.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import '@testing-library/jest-dom/vitest'
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { draftFixture, entryFixture, findingFixture } from '../test/fixtures'
import { cleanupControllerTest, getTauriMock, setupControllerTest, useAppController } from './useAppController.testHarness'

const { AppShell } = await import('./AppShell')
const tauri = getTauriMock()
function Subject() { return <AppShell {...useAppController()} /> }

beforeEach(() => {
setupControllerTest()
HTMLElement.prototype.scrollIntoView = vi.fn()
tauri.listDrafts.mockResolvedValue([
draftFixture({ id: 'draft-new', title: 'Newer test cases', updatedAt: '2026-11-13T09:00:00Z' }),
draftFixture({ id: 'draft-old', title: 'Older test cases', updatedAt: '2026-07-22T00:00:00Z' }),
])
tauri.listFindings.mockResolvedValue([
findingFixture({ id: 'finding-new', title: 'Newer finding', updatedAt: '2026-11-13T09:00:00Z' }),
findingFixture({ id: 'finding-old', title: 'Older finding', updatedAt: '2026-07-22T00:00:00Z' }),
])
tauri.readNoteSource.mockResolvedValue({ entry: entryFixture({ body: '<p>Pay with a saved card.</p>' }), revision: 0 })
})
afterEach(cleanupControllerTest)

const openTab = async (name: RegExp) => fireEvent.click(await screen.findByRole('tab', { name }))
const shownRecord = (title: string) => screen.findByRole('heading', { level: 2, name: title })

async function selectRecord(listName: string, title: string) {
fireEvent.click(await within(await screen.findByRole('complementary', { name: listName })).findByText(title))
await shownRecord(title)
}

async function openAndCancelDraft(createLabel: string, titleLabel: string) {
const create = screen.getByRole('button', { name: createLabel })
await waitFor(() => expect(create).toBeEnabled())
fireEvent.click(create)
await screen.findByRole('textbox', { name: titleLabel })
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
await waitFor(() => expect(screen.queryByRole('textbox', { name: titleLabel })).not.toBeInTheDocument())
}

it('keeps the selected test cases when another tab opens and a new draft is cancelled', async () => {
render(<Subject />)
await openTab(/Test cases/)
await selectRecord('Test cases records', 'Older test cases')

await openTab(/Findings/)
await shownRecord('Newer finding')
await openTab(/Test cases/)
expect(await shownRecord('Older test cases')).toBeInTheDocument()

await openAndCancelDraft('Create test cases', 'Test case title')
expect(await shownRecord('Older test cases')).toBeInTheDocument()
})

it('keeps the selected finding when the Note opens and a new draft is cancelled', async () => {
render(<Subject />)
await openTab(/Findings/)
await selectRecord('Findings records', 'Older finding')

await openTab(/Note/)
await openTab(/Findings/)
expect(await shownRecord('Older finding')).toBeInTheDocument()

await openAndCancelDraft('Create finding', 'Finding title')
expect(await shownRecord('Older finding')).toBeInTheDocument()
})
6 changes: 4 additions & 2 deletions frontend/src/app/AppShell.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,8 @@ export function AppShell(c: AppController) {
error={c.error}
isBusy={c.isBusy}
activeGenerationJob={c.activeTestwareJob}
initialSelectedRecordId={c.focusedRecordId}
initialSelectedRecordId={c.selectedRecordIds.testware}
onSelectedRecordChange={c.selectRecord.testware}
Comment thread
vriesd marked this conversation as resolved.
Resolved
createdRecordEditTarget={c.createdRecordEditTarget?.sessionId === c.activeSession?.id && c.createdRecordEditTarget?.kind === 'testware' ? c.createdRecordEditTarget : null}
onCreatedRecordEditTargetConsumed={c.consumeCreatedRecordEditTarget}
loadState={c.draftLoadState}
Expand Down Expand Up @@ -215,7 +216,8 @@ export function AppShell(c: AppController) {
error={c.error}
isBusy={c.isBusy}
activeGenerationJob={c.activeFindingJob}
initialSelectedRecordId={c.focusedRecordId}
initialSelectedRecordId={c.selectedRecordIds.findings}
onSelectedRecordChange={c.selectRecord.findings}
createdRecordEditTarget={c.createdRecordEditTarget?.sessionId === c.activeSession?.id && c.createdRecordEditTarget?.kind === 'finding' ? c.createdRecordEditTarget : null}
onCreatedRecordEditTargetConsumed={c.consumeCreatedRecordEditTarget}
loadState={c.findingLoadState}
Expand Down
8 changes: 4 additions & 4 deletions frontend/src/app/sessionNavigationActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ type SessionNavigationContext = {
requestSessionNavigation: (view: MainView, navigate: () => Promise<void>) => Promise<void>
setActiveView: Dispatch<SetStateAction<MainView>>
setError: Dispatch<SetStateAction<string | null>>
setFocusedRecordId: Dispatch<SetStateAction<string | null>>
focusRecord: (view: MainView, recordId: string | null) => void
setPendingSettingsSection: Dispatch<SetStateAction<string | null>>
setSettingsSection: Dispatch<SetStateAction<string | null>>
}
Expand All @@ -48,7 +48,7 @@ export function createSessionNavigationActions(ctx: SessionNavigationContext) {
const session = ctx.sessions.find((candidate) => candidate.id === sessionId) ?? await reopenSession(sessionId)
if (!ctx.sessionActions.sessionNavigationIsCurrent(epoch)) return
await ctx.sessionActions.openSession(session, () => {
ctx.setFocusedRecordId(recordId)
ctx.focusRecord(view, recordId)
ctx.setActiveView(view)
}, epoch)
} catch (cause) {
Expand All @@ -72,7 +72,7 @@ export function createSessionNavigationActions(ctx: SessionNavigationContext) {
return
}
if (!route.sessionId || ctx.activeSessionId === route.sessionId) {
ctx.setFocusedRecordId(route.recordId)
ctx.focusRecord(route.view, route.recordId)
ctx.requestActiveView(route.view)
return
}
Expand All @@ -82,7 +82,7 @@ export function createSessionNavigationActions(ctx: SessionNavigationContext) {
const session = ctx.sessions.find((candidate) => candidate.id === route.sessionId) ?? await reopenSession(route.sessionId!)
if (!ctx.sessionActions.sessionNavigationIsCurrent(epoch)) return
await ctx.sessionActions.openSession(session, () => {
ctx.setFocusedRecordId(route.recordId)
ctx.focusRecord(route.view, route.recordId)
ctx.setActiveView(route.view)
}, epoch)
} catch (cause) {
Expand Down
6 changes: 3 additions & 3 deletions frontend/src/app/useAppController.navigation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ type AppControllerNavigationContext = {
settingsSection: string | null
setActiveView: Dispatch<SetStateAction<MainView>>
setError: Dispatch<SetStateAction<string | null>>
setFocusedRecordId: Dispatch<SetStateAction<string | null>>
focusRecord: (view: MainView, recordId: string | null) => void
setCreatedRecordEditTarget: Dispatch<SetStateAction<CreatedRecordEditTarget | null>>
setPendingNavigationView: Dispatch<SetStateAction<MainView | null>>
setPendingSettingsSection: Dispatch<SetStateAction<string | null>>
Expand All @@ -58,7 +58,7 @@ export function useAppControllerNavigation(ctx: AppControllerNavigationContext)
const view = target.kind === 'testware' ? 'testware' : 'findings'
finishActiveViewNavigation(view, () => {
if (!isCurrent()) return
ctx.setFocusedRecordId(null)
ctx.focusRecord(view, null)
ctx.setCreatedRecordEditTarget(target)
ctx.setActiveView(view)
})
Expand Down Expand Up @@ -190,7 +190,7 @@ export function useAppControllerNavigation(ctx: AppControllerNavigationContext)
requestSessionNavigation,
setActiveView: ctx.setActiveView,
setError: ctx.setError,
setFocusedRecordId: ctx.setFocusedRecordId,
focusRecord: ctx.focusRecord,
setPendingSettingsSection: ctx.setPendingSettingsSection,
setSettingsSection: ctx.setSettingsSection,
})
Expand Down
8 changes: 4 additions & 4 deletions frontend/src/app/useAppController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,12 @@ import { useSettingsSectionFocus } from './useAppController.settingsFocus'
import { useAppSettlement } from './appSettlement'
import { useAppControllerNavigation } from './useAppController.navigation'
import { useAttachmentCleanup } from './useAttachmentCleanup'
import { useRecordSelection } from './useRecordSelection'
import { useSummaryRecovery } from './useSummaryRecovery'
import { captureAvailableRecordContext } from './conversationPresentation'
import { useSessionChat } from './useSessionChat'
import { findingFromTestCase } from '../findings/fromTestCase'
import type { TestRunCase } from '../tauri'
export { mergeRecordLists } from './useRecordHydration'
export function useAppController() {
const {
sessions,
Expand Down Expand Up @@ -68,7 +68,7 @@ export function useAppController() {
const pendingNavigationContinuationRef = useRef<(() => void | Promise<void>) | null>(null)
const pendingNavigationEpochRef = useRef(0)
const [settingsSection, setSettingsSection] = useState<string | null>(null)
const [focusedRecordId, setFocusedRecordId] = useState<string | null>(null)
const { focusedRecordId, selectedRecordIds, selectRecord, focusRecord } = useRecordSelection()
const [createdRecordEditTarget, setCreatedRecordEditTarget] = useState<CreatedRecordEditTarget | null>(null)
const [initialNavigationRoute] = useState(() => parseNavigationRoute(window.location.hash))
const settingsReturnViewRef = useRef<MainView>('sessions')
Expand Down Expand Up @@ -208,7 +208,7 @@ export function useAppController() {
discardSettingsDraft, focusedRecordId, pendingNavigationContinuationRef, pendingNavigationEpochRef,
pendingNavigationView, recordActions,
sessionActions, sessions, settingsDirty, settingsReturnViewRef, settingsSection,
setActiveView, setError, setFocusedRecordId, setCreatedRecordEditTarget, setPendingNavigationView, setPendingSettingsSection, setSettingsSection,
setActiveView, setError, focusRecord, setCreatedRecordEditTarget, setPendingNavigationView, setPendingSettingsSection, setSettingsSection,
})
usePendingChangeProtection({
hasPendingChanges: settlement.hasPendingChanges,
Expand Down Expand Up @@ -257,7 +257,7 @@ export function useAppController() {
busyAction, deleteConfirmation,
deleteCopy,
error,
focusedRecordId,
focusedRecordId, selectedRecordIds, selectRecord,
isBusy, canSwitchSession,
latestNoteGenerationUndo,
noteBody, noteBodyHtml,
Expand Down
12 changes: 12 additions & 0 deletions frontend/src/app/useRecordSelection.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { act, renderHook } from '@testing-library/react'
import { expect, it } from 'vitest'
import { useRecordSelection } from './useRecordSelection'

it('keeps the record navigation asked for while the view has no record to show yet', () => {
const { result } = renderHook(() => useRecordSelection())
act(() => result.current.focusRecord('findings', 'finding-old'))
act(() => result.current.selectRecord.findings(null))
expect(result.current.selectedRecordIds.findings).toBe('finding-old')
act(() => result.current.selectRecord.findings('finding-new'))
expect(result.current.selectedRecordIds).toEqual({ testware: null, findings: 'finding-new' })
})
29 changes: 29 additions & 0 deletions frontend/src/app/useRecordSelection.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { useCallback, useMemo, useState } from 'react'
import type { MainView } from '../ui/types'

export type RecordView = 'testware' | 'findings'
type RecordSelection = Record<RecordView, string | null>

const isRecordView = (view: MainView): view is RecordView => view === 'testware' || view === 'findings'

/**
* The record each record view shows. A view unmounts when another tab is open, so its selection is kept here:
* returning to Test cases or Findings, or leaving a new draft, shows the record that was selected, not the newest.
* `focusedRecordId` is the record navigation last opened, which the route names.
*/
export function useRecordSelection() {
const [focusedRecordId, setFocusedRecordId] = useState<string | null>(null)
const [selectedRecordIds, setSelectedRecordIds] = useState<RecordSelection>({ testware: null, findings: null })
const select = useCallback((view: RecordView, id: string | null) =>
setSelectedRecordIds((previous) => previous[view] === id ? previous : { ...previous, [view]: id }), [])
// A view shows no record while its records load, so an empty report keeps the record navigation asked for.
const selectRecord = useMemo(() => ({
testware: (id: string | null) => { if (id) select('testware', id) },
findings: (id: string | null) => { if (id) select('findings', id) },
}), [select])
const focusRecord = useCallback((view: MainView, id: string | null) => {
setFocusedRecordId(id)
if (isRecordView(view)) select(view, id)
}, [select])
return { focusedRecordId, selectedRecordIds, selectRecord, focusRecord }
}
Comment thread
vriesd marked this conversation as resolved.
Resolved
4 changes: 0 additions & 4 deletions frontend/src/ui/format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,10 +98,6 @@ function escapeRegExp(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}

export function statusLabel(status: string): string {
return status.replace(/([A-Z])/g, ' $1').toLowerCase()
}

/** A day and month, such as `13 Nov` in a day-first locale. */
export function formatShortDate(value: string): string {
const date = new Date(value)
Expand Down
4 changes: 4 additions & 0 deletions frontend/src/views/FindingsView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ export function FindingsView({
isBusy,
activeGenerationJob,
initialSelectedRecordId = null,
onSelectedRecordChange,
createdRecordEditTarget = null,
onCreatedRecordEditTargetConsumed,
loadState = 'ready',
Expand All @@ -90,7 +91,9 @@ export function FindingsView({
error: string | null
isBusy: boolean
activeGenerationJob: GenerationJobStatus | null
/** The record to show first; told each record the view selects, so it can be shown again after the view returns. */
initialSelectedRecordId?: string | null
onSelectedRecordChange?: (id: string | null) => void
createdRecordEditTarget?: CreatedRecordEditTarget | null
onCreatedRecordEditTargetConsumed?: (target: CreatedRecordEditTarget) => void
loadState?: RecordLoadState
Expand Down Expand Up @@ -121,6 +124,7 @@ export function FindingsView({
isBusy={isBusy}
activeGenerationJob={activeGenerationJob}
initialSelectedRecordId={initialSelectedRecordId}
onSelectedRecordChange={onSelectedRecordChange}
createdRecordEditTarget={createdRecordEditTarget}
onCreatedRecordEditTargetConsumed={onCreatedRecordEditTargetConsumed}
loadState={loadState}
Expand Down
12 changes: 10 additions & 2 deletions frontend/src/views/TestwareView.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { RecordChatActions } from '../app/sessionChat.context'
import type { RecordCreationCommands } from './RecordCreationActions'
import { Box } from 'lucide-react'
import { useEffect, useRef } from 'react'
import { useCallback, useEffect, useRef } from 'react'
import { Badge } from '../components/Badge'
import type { RichEditorImageUpload } from '../editor/RichTextEditor'
import { testwareGenerationSummary } from '../testware/generationPreferences'
Expand Down Expand Up @@ -48,6 +48,7 @@ export function TestwareView({
isBusy,
activeGenerationJob,
initialSelectedRecordId = null,
onSelectedRecordChange,
createdRecordEditTarget = null,
onCreatedRecordEditTargetConsumed,
loadState = 'ready',
Expand Down Expand Up @@ -80,7 +81,9 @@ export function TestwareView({
error: string | null
isBusy: boolean
activeGenerationJob: GenerationJobStatus | null
/** The record to show first; told each record the view selects, so it can be shown again after the view returns. */
initialSelectedRecordId?: string | null
onSelectedRecordChange?: (id: string | null) => void
createdRecordEditTarget?: CreatedRecordEditTarget | null
onCreatedRecordEditTargetConsumed?: (target: CreatedRecordEditTarget) => void
loadState?: RecordLoadState
Expand All @@ -97,6 +100,11 @@ export function TestwareView({
}) {
const testRuns = useTestRuns(sessionId)
useShownTestRun(recordChat, sessionId, testRuns)
const { keepForDraft } = testRuns
const selectDraft = useCallback((id: string | null) => {
keepForDraft(id)
onSelectedRecordChange?.(id)
}, [keepForDraft, onSelectedRecordChange])
const runsOf = (draftId: string) => testRuns.summaries.filter((summary) => summary.draftId === draftId)
return (
<RecordCollectionView
Expand Down Expand Up @@ -141,7 +149,7 @@ export function TestwareView({
onDelete={testRuns.deleteRun} onChangeCase={testRuns.changeCase}
askAi={recordChat?.onAskAiRun ? { expanded: recordChat.openRunId === testRuns.open.runId, onOpen: recordChat.onAskAiRun } : undefined} />
) : null}
onSelectedRecordChange={testRuns.keepForDraft}
onSelectedRecordChange={selectDraft}
busyActionFor={(draft, kind) => {
switch (kind) {
case 'delete':
Expand Down
Loading