diff --git a/frontend/e2e/mobile.spec.ts b/frontend/e2e/mobile.spec.ts index a6ae55e..a3fc84f 100644 --- a/frontend/e2e/mobile.spec.ts +++ b/frontend/e2e/mobile.spec.ts @@ -131,5 +131,5 @@ test('the map controls and legend sit level with each other, clear of the search expect(zoom.y).toBeGreaterThan(searchBar.y + searchBar.height); expect(Math.abs(legend.y + legend.height / 2 - (zoom.y + zoom.height / 2))).toBeLessThan(4); - await expect(page.getByRole('button', { name: 'Coverage area' })).toHaveCount(0); + await expect(page.getByRole('button', { name: 'Results history' })).toHaveCount(0); }); diff --git a/frontend/src/components/bookmarks/BookmarkRow/BookmarkRow.tsx b/frontend/src/components/bookmarks/BookmarkRow/BookmarkRow.tsx index 40505b4..38a4bf6 100644 --- a/frontend/src/components/bookmarks/BookmarkRow/BookmarkRow.tsx +++ b/frontend/src/components/bookmarks/BookmarkRow/BookmarkRow.tsx @@ -2,6 +2,7 @@ import { BookmarkX, FileDown } from 'lucide-react'; import { useTranslation } from 'react-i18next'; import { Button } from '@/components/ui/button'; import { Item, ItemActions, ItemContent } from '@/components/ui/item'; +import ActionTooltip from '@/components/common/ActionTooltip/ActionTooltip'; import BookmarkRowSkeleton from '@/components/bookmarks/BookmarkRowSkeleton/BookmarkRowSkeleton'; import TrialBadges from '@/components/bookmarks/TrialBadges/TrialBadges'; import { publicTrialId, trialTitle } from '@/lib/trial'; @@ -58,27 +59,29 @@ function BookmarkRow({ {onExport && ( + + + + )} + - )} - + ); diff --git a/frontend/src/components/bookmarks/BookmarksSheet/BookmarksSheet.tsx b/frontend/src/components/bookmarks/BookmarksSheet/BookmarksSheet.tsx index 5417fec..b69f6c3 100644 --- a/frontend/src/components/bookmarks/BookmarksSheet/BookmarksSheet.tsx +++ b/frontend/src/components/bookmarks/BookmarksSheet/BookmarksSheet.tsx @@ -14,6 +14,7 @@ import { SheetTitle, } from '@/components/ui/sheet'; import BookmarkRow from '@/components/bookmarks/BookmarkRow/BookmarkRow'; +import ActionTooltip from '@/components/common/ActionTooltip/ActionTooltip'; import { useCachedTrialTranslations } from '@/hooks/useTrialTranslation'; import { useTrialPdfExport } from '@/hooks/useTrialPdfExport'; import { trialQuery } from '@/services/trials'; @@ -52,12 +53,14 @@ function BookmarksSheet({ open, onOpenChange }: BookmarksSheetProps) { return ( - - - + + + + + diff --git a/frontend/src/components/chat/ChatHeader/ChatHeader.tsx b/frontend/src/components/chat/ChatHeader/ChatHeader.tsx index d4a6c4d..e7823a9 100644 --- a/frontend/src/components/chat/ChatHeader/ChatHeader.tsx +++ b/frontend/src/components/chat/ChatHeader/ChatHeader.tsx @@ -1,6 +1,7 @@ import { SquarePen } from 'lucide-react'; import { useTranslation } from 'react-i18next'; import { Button } from '@/components/ui/button'; +import ActionTooltip from '@/components/common/ActionTooltip/ActionTooltip'; interface ChatHeaderProps { onNewConversation: () => void; @@ -11,15 +12,16 @@ function ChatHeader({ onNewConversation }: ChatHeaderProps) { return (
- + + +
); } diff --git a/frontend/src/components/chat/ChatMessages/ChatMessages.test.tsx b/frontend/src/components/chat/ChatMessages/ChatMessages.test.tsx index 5637c19..210c25e 100644 --- a/frontend/src/components/chat/ChatMessages/ChatMessages.test.tsx +++ b/frontend/src/components/chat/ChatMessages/ChatMessages.test.tsx @@ -1,14 +1,23 @@ import { screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; import { describe, expect, it, vi } from 'vitest'; import ChatMessages from './ChatMessages'; import { renderWithClient } from '@/test/render'; import { AGENT_NAME, ChatRole } from '@/constants/chat'; import type { ChatMessage } from '@/types/trial'; import { mockTrials } from '@/test/fixtures/trials'; +import { useAppStore } from '@/store/appStore'; -function renderMessages(messages: ChatMessage[]) { +function renderMessages(messages: ChatMessage[], onFindMore = vi.fn()) { renderWithClient( - , + , { trials: [mockTrials[0]] } ); } @@ -41,6 +50,44 @@ describe('ChatMessages', () => { expect(screen.getByRole('button', { name: /show .+ on the map/i })).toBeInTheDocument(); }); + it('folds more than two context trials into one pill that opens them', async () => { + renderMessages([ + { + id: 'a', + role: ChatRole.User, + content: 'Find more trials like these.', + contextTrialRefs: mockTrials.slice(0, 3).map((trial) => trial.trialRef), + }, + ]); + expect(screen.queryByRole('button', { name: /show .+ on the map/i })).not.toBeInTheDocument(); + + await userEvent.click(screen.getByRole('button', { name: '3 trials' })); + + expect(await screen.findAllByRole('button', { name: /show .+ on the map/i })).toHaveLength(3); + }); + + it("puts an earlier answer's trials back on the map and asks for more like them", async () => { + useAppStore.getState().reset(); + const onFindMore = vi.fn(); + renderMessages( + [ + { id: 'a', role: ChatRole.User, content: 'Any breast cancer trials in Toronto?' }, + { id: 'b', role: ChatRole.Assistant, content: 'I found one.', trials: [mockTrials[0]] }, + ], + onFindMore + ); + + await userEvent.click(screen.getByRole('button', { name: /show 1 trial on the map/i })); + expect(useAppStore.getState().shownTurnId).toBe('b'); + expect(useAppStore.getState().resultTurns[0].question).toBe( + 'Any breast cancer trials in Toronto?' + ); + expect(screen.getByRole('button', { name: /on the map/i })).toBeDisabled(); + + await userEvent.click(screen.getByRole('button', { name: /find more like these/i })); + expect(onFindMore).toHaveBeenCalledWith([mockTrials[0].trialRef]); + }); + it('turns a cited trial into a pill with a contact link', () => { renderMessages([ { id: 'c', role: ChatRole.Assistant, content: 'This one fits: [CTC-4267848A].' }, diff --git a/frontend/src/components/chat/ChatMessages/ChatMessages.tsx b/frontend/src/components/chat/ChatMessages/ChatMessages.tsx index cf978e0..df9ead2 100644 --- a/frontend/src/components/chat/ChatMessages/ChatMessages.tsx +++ b/frontend/src/components/chat/ChatMessages/ChatMessages.tsx @@ -10,6 +10,7 @@ import { Message, MessageContent, MessageResponse } from '@/components/ai-elemen import AskAiSelection from '@/components/chat/AskAiSelection/AskAiSelection'; import MessageContextTrials from '@/components/chat/MessageContextTrials/MessageContextTrials'; import MessageFeedback from '@/components/chat/MessageFeedback/MessageFeedback'; +import MessageTrialActions from '@/components/chat/MessageTrialActions/MessageTrialActions'; import SearchingIndicator from '@/components/chat/SearchingIndicator/SearchingIndicator'; import TermDefinition from '@/components/chat/TermDefinition/TermDefinition'; import TrialCitation from '@/components/chat/TrialCitation/TrialCitation'; @@ -28,6 +29,10 @@ interface ChatMessagesProps { sessionId: string; onCitationClick: (trialRef: string) => void; onAskAi: (text: string) => void; + onFindMore: (trialRefs: string[]) => void; + /** A reply is streaming, so nothing new can be sent yet. */ + busy: boolean; + onShowTurn?: () => void; } function createMarkdownComponents(onCitationClick: (trialRef: string) => void): Components { @@ -53,7 +58,15 @@ function createMarkdownComponents(onCitationClick: (trialRef: string) => void): }; } -function ChatMessages({ messages, sessionId, onCitationClick, onAskAi }: ChatMessagesProps) { +function ChatMessages({ + messages, + sessionId, + onCitationClick, + onAskAi, + onFindMore, + busy, + onShowTurn, +}: ChatMessagesProps) { const { t } = useTranslation(); const rootRef = useRef(null); return ( @@ -66,7 +79,7 @@ function ChatMessages({ messages, sessionId, onCitationClick, onAskAi }: ChatMes {t('chat.starter')} ) : ( - messages.map((message) => ( + messages.map((message, index) => ( {message.role !== ChatRole.Assistant ? ( @@ -89,6 +102,18 @@ function ChatMessages({ messages, sessionId, onCitationClick, onAskAi }: ChatMes onSelect={onCitationClick} /> )} + {message.role === ChatRole.Assistant && message.trials?.length ? ( + + ) : null} {message.role === ChatRole.Assistant && message.observationId && ( )} diff --git a/frontend/src/components/chat/ChatPanel/ChatPanel.tsx b/frontend/src/components/chat/ChatPanel/ChatPanel.tsx index 17b2061..f83c110 100644 --- a/frontend/src/components/chat/ChatPanel/ChatPanel.tsx +++ b/frontend/src/components/chat/ChatPanel/ChatPanel.tsx @@ -1,4 +1,5 @@ import { useCallback, useMemo } from 'react'; +import { useTranslation } from 'react-i18next'; import ChatDisclaimer from '@/components/chat/ChatDisclaimer/ChatDisclaimer'; import ChatHeader from '@/components/chat/ChatHeader/ChatHeader'; import ChatInput from '@/components/chat/ChatInput/ChatInput'; @@ -12,9 +13,12 @@ import { useAppStore } from '@/store/appStore'; interface ChatPanelProps { onCitationClick: (trialRef: string) => void; + /** Runs after an answer's trials go back on the map, so a layout can reveal it. */ + onShowTurn?: () => void; } -function ChatPanel({ onCitationClick }: ChatPanelProps) { +function ChatPanel({ onCitationClick, onShowTurn }: ChatPanelProps) { + const { t } = useTranslation(); const turnstile = useTurnstile(); const getTurnstileToken = useCallback(() => turnstile.token, [turnstile.token]); const { messages, status, sessionId, sendMessage, stop, reset } = useChat({ @@ -38,6 +42,11 @@ function ChatPanel({ onCitationClick }: ChatPanelProps) { void sendMessage(`${ASK_AI_PROMPT_PREFIX}"${text}"${ASK_AI_PROMPT_SUFFIX}`); }; + // The answer's trials ride along as context, so the agent searches from them instead of asking again. + const handleFindMore = (trialRefs: string[]) => { + void sendMessage(t('chat.findMorePrompt'), trialRefs); + }; + const suggestions = useMemo(() => { const lastAssistant = displayMessages.findLast( (message) => message.role === ChatRole.Assistant @@ -53,6 +62,9 @@ function ChatPanel({ onCitationClick }: ChatPanelProps) { sessionId={sessionId} onCitationClick={onCitationClick} onAskAi={handleAskAi} + onFindMore={handleFindMore} + busy={status === 'streaming' || tourMessages !== undefined} + onShowTurn={onShowTurn} />
diff --git a/frontend/src/components/chat/MessageContextTrials/MessageContextTrials.tsx b/frontend/src/components/chat/MessageContextTrials/MessageContextTrials.tsx index 0890dfd..e08bfc1 100644 --- a/frontend/src/components/chat/MessageContextTrials/MessageContextTrials.tsx +++ b/frontend/src/components/chat/MessageContextTrials/MessageContextTrials.tsx @@ -1,6 +1,12 @@ +import { useState } from 'react'; import { Sparkles } from 'lucide-react'; +import { useTranslation } from 'react-i18next'; import { MessageAttachments } from '@/components/ai-elements/message'; import TrialCitation from '@/components/chat/TrialCitation/TrialCitation'; +import { Button } from '@/components/ui/button'; +import { HoverCard, HoverCardContent, HoverCardTrigger } from '@/components/ui/hover-card'; + +const MAX_INLINE_TRIALS = 2; interface MessageContextTrialsProps { trialRefs: string[]; @@ -8,16 +14,45 @@ interface MessageContextTrialsProps { } function MessageContextTrials({ trialRefs, onSelect }: MessageContextTrialsProps) { + const { t } = useTranslation(); + const [open, setOpen] = useState(false); + if (trialRefs.length === 0) { return null; } + const citations = trialRefs.map((trialRef) => ( + + )); + return ( - {trialRefs.map((trialRef) => ( - - ))} + {trialRefs.length <= MAX_INLINE_TRIALS ? ( + citations + ) : ( + // A tap toggles it too, since touch never hovers. + + + + + + {citations} + + + )} ); } diff --git a/frontend/src/components/chat/MessageFeedback/MessageFeedback.tsx b/frontend/src/components/chat/MessageFeedback/MessageFeedback.tsx index b6c4972..2ef7725 100644 --- a/frontend/src/components/chat/MessageFeedback/MessageFeedback.tsx +++ b/frontend/src/components/chat/MessageFeedback/MessageFeedback.tsx @@ -5,6 +5,7 @@ import { toast } from 'sonner'; import { MessageAction, MessageActions } from '@/components/ai-elements/message'; import { Badge } from '@/components/ui/badge'; import { Button } from '@/components/ui/button'; +import ActionTooltip from '@/components/common/ActionTooltip/ActionTooltip'; import { Collapsible, CollapsibleContent } from '@/components/ui/collapsible'; import { Input } from '@/components/ui/input'; import { Textarea } from '@/components/ui/textarea'; @@ -138,16 +139,18 @@ function MessageFeedback({ sessionId, observationId }: MessageFeedbackProps) { className="gap-1 py-0.5 pr-1 pl-2 font-mono" > {nct} - + + + ))}
diff --git a/frontend/src/components/chat/MessageTrialActions/MessageTrialActions.tsx b/frontend/src/components/chat/MessageTrialActions/MessageTrialActions.tsx new file mode 100644 index 0000000..aa7cafc --- /dev/null +++ b/frontend/src/components/chat/MessageTrialActions/MessageTrialActions.tsx @@ -0,0 +1,52 @@ +import { ListPlus, MapPinned } from 'lucide-react'; +import { useTranslation } from 'react-i18next'; +import { MessageActions } from '@/components/ai-elements/message'; +import { Button } from '@/components/ui/button'; +import { cn } from '@/lib/utils'; +import { useAppStore } from '@/store/appStore'; +import type { ResultTurn } from '@/types/trial'; + +interface MessageTrialActionsProps { + turn: ResultTurn; + busy: boolean; + onShown?: () => void; + onFindMore: (trialRefs: string[]) => void; +} + +/** Under an answer that found trials: put them back on the map, or ask for more like them. */ +function MessageTrialActions({ turn, busy, onShown, onFindMore }: MessageTrialActionsProps) { + const { t } = useTranslation(); + const shown = useAppStore((state) => state.shownTurnId === turn.id); + const showTurn = useAppStore((state) => state.showTurn); + const count = turn.trials.length; + + return ( + + + + + ); +} + +export default MessageTrialActions; diff --git a/frontend/src/components/chat/SelectedTrials/SelectedTrials.tsx b/frontend/src/components/chat/SelectedTrials/SelectedTrials.tsx index 748dc61..fdd2b47 100644 --- a/frontend/src/components/chat/SelectedTrials/SelectedTrials.tsx +++ b/frontend/src/components/chat/SelectedTrials/SelectedTrials.tsx @@ -2,9 +2,13 @@ import { MapPin, X } from 'lucide-react'; import { useTranslation } from 'react-i18next'; import { Badge } from '@/components/ui/badge'; import { Button } from '@/components/ui/button'; +import ActionTooltip from '@/components/common/ActionTooltip/ActionTooltip'; import { trialTitle } from '@/lib/trial'; +import { truncate } from '@/lib/utils'; import type { Trial } from '@/types/trial'; +const TOOLTIP_TITLE_MAX_LENGTH = 40; + interface SelectedTrialsProps { trials: Trial[]; onRemove: (trialRef: string) => void; @@ -25,16 +29,22 @@ function SelectedTrials({ trials, onRemove }: SelectedTrialsProps) { {label} - + + ); })} diff --git a/frontend/src/components/chat/TrialCitation/TrialCitation.tsx b/frontend/src/components/chat/TrialCitation/TrialCitation.tsx index 604a0d5..3332631 100644 --- a/frontend/src/components/chat/TrialCitation/TrialCitation.tsx +++ b/frontend/src/components/chat/TrialCitation/TrialCitation.tsx @@ -11,17 +11,13 @@ import { import { useIsMobile } from '@/hooks/useIsMobile'; import { useCachedTrialTranslations } from '@/hooks/useTrialTranslation'; import { trialTitle } from '@/lib/trial'; -import { cn } from '@/lib/utils'; +import { cn, truncate } from '@/lib/utils'; import { trialQuery } from '@/services/trials'; const CITATION_TITLE_MAX_LENGTH = 50; const COMPACT_TITLE_MAX_LENGTH = 28; const CITATION_DESCRIPTION_MAX_LENGTH = 200; -function truncate(text: string, max: number): string { - return text.length > max ? `${text.slice(0, max).trimEnd()}…` : text; -} - interface TrialCitationProps { trialRef: string; onSelect: (trialRef: string) => void; diff --git a/frontend/src/components/common/ActionTooltip/ActionTooltip.tsx b/frontend/src/components/common/ActionTooltip/ActionTooltip.tsx new file mode 100644 index 0000000..6b45281 --- /dev/null +++ b/frontend/src/components/common/ActionTooltip/ActionTooltip.tsx @@ -0,0 +1,21 @@ +import type { ReactNode } from 'react'; +import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'; + +interface ActionTooltipProps { + label: string; + children: ReactNode; +} + +/** Hover tooltip for a single action button, which must forward refs and props. */ +function ActionTooltip({ label, children }: ActionTooltipProps) { + return ( + + + {children} + {label} + + + ); +} + +export default ActionTooltip; diff --git a/frontend/src/components/layout/AppHeader/AppHeader.tsx b/frontend/src/components/layout/AppHeader/AppHeader.tsx index 47f11e9..e9bed64 100644 --- a/frontend/src/components/layout/AppHeader/AppHeader.tsx +++ b/frontend/src/components/layout/AppHeader/AppHeader.tsx @@ -44,14 +44,14 @@ function AppHeader({ onOpenBookmarks, onStartTour }: AppHeaderProps) { - - - {t('map.coverageNotice')} - - + )} diff --git a/frontend/src/components/map/ResultHistory/ResultHistory.tsx b/frontend/src/components/map/ResultHistory/ResultHistory.tsx new file mode 100644 index 0000000..60e5584 --- /dev/null +++ b/frontend/src/components/map/ResultHistory/ResultHistory.tsx @@ -0,0 +1,87 @@ +import { History, Info } from 'lucide-react'; +import { useTranslation } from 'react-i18next'; +import ActionTooltip from '@/components/common/ActionTooltip/ActionTooltip'; +import StatusDot from '@/components/trial/StatusDot/StatusDot'; +import { Button } from '@/components/ui/button'; +import { Command, CommandGroup, CommandItem, CommandList } from '@/components/ui/command'; +import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'; +import { deriveTrialStatus } from '@/lib/trial'; +import { useAppStore } from '@/store/appStore'; + +const EDGE_GAP_PX = 12; + +/** Map control listing every answer that found trials, newest first; picking one puts its trials back. */ +function ResultHistory() { + const { t } = useTranslation(); + const turns = useAppStore((state) => state.resultTurns); + const shownTurnId = useAppStore((state) => state.shownTurnId); + const showTurn = useAppStore((state) => state.showTurn); + const newestFirst = turns.map((turn, index) => ({ turn, number: index + 1 })).reverse(); + + return ( + + + + + + + +
+

{t('map.history')}

+
+ {turns.length === 0 ? ( +

{t('map.historyEmpty')}

+ ) : ( + + + + {newestFirst.map(({ turn, number }) => ( + showTurn(turn)} + className="border-border items-start rounded-none border-b px-3 py-2.5 last:border-b-0" + > +
+ + {t('map.historyAnswer', { index: number })} ·{' '} + {t('map.trialCount', { count: turn.trials.length })} + + {turn.question} + + {turn.trials.map((trial) => { + const status = deriveTrialStatus(trial); + return status ? : null; + })} + +
+
+ ))} +
+
+
+ )} +

+ + {t('map.coverageNotice')} +

+
+
+ ); +} + +export default ResultHistory; diff --git a/frontend/src/components/mobile/MobileLayout/MobileLayout.tsx b/frontend/src/components/mobile/MobileLayout/MobileLayout.tsx index faf5280..5a632e6 100644 --- a/frontend/src/components/mobile/MobileLayout/MobileLayout.tsx +++ b/frontend/src/components/mobile/MobileLayout/MobileLayout.tsx @@ -83,7 +83,7 @@ function MobileLayout({ onOpenBookmarks, onStartTour, children }: MobileLayoutPr peekLabel={hasTrials ? t('mobile.chatPeek') : t('mobile.searchPrompt')} onSnapChange={setSnap} > - + setSnap('peek')} /> diff --git a/frontend/src/components/summary/TrialSummaryHeader/TrialSummaryHeader.tsx b/frontend/src/components/summary/TrialSummaryHeader/TrialSummaryHeader.tsx index 0505136..3d0b6e8 100644 --- a/frontend/src/components/summary/TrialSummaryHeader/TrialSummaryHeader.tsx +++ b/frontend/src/components/summary/TrialSummaryHeader/TrialSummaryHeader.tsx @@ -1,8 +1,8 @@ -import { useState, type ReactNode } from 'react'; +import { useState } from 'react'; import { Bookmark, BookmarkCheck, Check, ExternalLink, Mail, Sparkles, X } from 'lucide-react'; import { useTranslation } from 'react-i18next'; import { Button } from '@/components/ui/button'; -import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'; +import ActionTooltip from '@/components/common/ActionTooltip/ActionTooltip'; import ContactDialog from '@/components/contact/ContactDialog/ContactDialog'; import TrialTitle from '@/components/summary/TrialTitle/TrialTitle'; import { TRIAL_SOURCE_CODES, TRIAL_SOURCES } from '@/constants/trialSources'; @@ -26,17 +26,6 @@ interface TrialSummaryHeaderProps extends Omit - - {children} - {label} - - - ); -} - export function TrialSummaryActions({ trial, onAddedToContext, @@ -64,9 +53,9 @@ export function TrialSummaryActions({ return ( <> - + - - + + - - + + - + {registryLinks.map(({ source, href }, index) => { const label = t('summary.viewOn', { registry: TRIAL_SOURCES[source].registry }); return ( - + - + ); })}
{!hideActions && } - + + +
); diff --git a/frontend/src/components/ui/button.tsx b/frontend/src/components/ui/button.tsx index 75b8c3d..7e2781f 100644 --- a/frontend/src/components/ui/button.tsx +++ b/frontend/src/components/ui/button.tsx @@ -19,6 +19,8 @@ const buttonVariants = cva( destructive: "bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40", link: "text-primary underline-offset-4 hover:underline", + action: + "hover:text-foreground aria-expanded:text-foreground [&_svg]:transition-colors hover:[&_svg]:text-highlight focus-visible:[&_svg]:text-highlight aria-expanded:[&_svg]:text-highlight", }, size: { default: diff --git a/frontend/src/hooks/useChat.ts b/frontend/src/hooks/useChat.ts index 8cf1428..992c54a 100644 --- a/frontend/src/hooks/useChat.ts +++ b/frontend/src/hooks/useChat.ts @@ -106,7 +106,7 @@ export function useChat({ getTurnstileToken, verificationId }: UseChatOptions): for (const trial of event.data.trials) { queryClient.setQueryData(trialQuery(trial.trialRef).queryKey, trial); } - store.setTrials(event.data.trials); + store.showTurn({ id: assistantId, question: text, trials: event.data.trials }); } } else { patchMessage(assistantId, { content: '', error: chatErrorForCode(event.data) }); diff --git a/frontend/src/i18n/locales/de.ts b/frontend/src/i18n/locales/de.ts index ae9d523..499b9f5 100644 --- a/frontend/src/i18n/locales/de.ts +++ b/frontend/src/i18n/locales/de.ts @@ -32,6 +32,12 @@ const de = { askAi: 'KI fragen', removeFromContext: '{{trialRef}} aus dem Kontext entfernen', showOnMap: '{{title}} auf der Karte zeigen', + showTrialsOnMap_one: '{{count}} Studie auf der Karte zeigen', + showTrialsOnMap_other: '{{count}} Studien auf der Karte zeigen', + trialsOnMap: 'Auf der Karte', + findMore: 'Ähnliche finden', + findMorePrompt: 'Weitere Studien wie diese finden.', + contextTrials: '{{count}} Studien', definition: 'Definition: {{definition}}', send: 'Senden', }, @@ -91,7 +97,10 @@ const de = { map: { trialCount_one: '{{count}} Studie', trialCount_other: '{{count}} Studien', - coverageArea: 'Abgedecktes Gebiet', + history: 'Ergebnisverlauf', + historyEmpty: + 'Jede Antwort, die Studien findet, steht hier, damit ihre Studien wieder auf die Karte kommen.', + historyAnswer: 'Antwort {{index}}', coverageNotice: 'Die Abdeckung umfasst Studienzentren in ganz Kanada.', emptyHint: 'Studien erscheinen hier im Verlauf des Gesprächs.', }, diff --git a/frontend/src/i18n/locales/en.ts b/frontend/src/i18n/locales/en.ts index 4c8610e..a418917 100644 --- a/frontend/src/i18n/locales/en.ts +++ b/frontend/src/i18n/locales/en.ts @@ -30,6 +30,12 @@ const en = { askAi: 'Ask AI', removeFromContext: 'Remove {{trialRef}} from context', showOnMap: 'Show {{title}} on the map', + showTrialsOnMap_one: 'Show {{count}} trial on the map', + showTrialsOnMap_other: 'Show {{count}} trials on the map', + trialsOnMap: 'On the map', + findMore: 'Find more like these', + findMorePrompt: 'Find more trials like these.', + contextTrials: '{{count}} trials', definition: 'Definition: {{definition}}', send: 'Send', }, @@ -83,7 +89,10 @@ const en = { map: { trialCount_one: '{{count}} trial', trialCount_other: '{{count}} trials', - coverageArea: 'Coverage area', + history: 'Results history', + historyEmpty: + 'Each answer that finds trials is listed here, so you can put its trials back on the map.', + historyAnswer: 'Answer {{index}}', coverageNotice: 'Coverage includes cancer trial sites across Canada.', emptyHint: 'Trials will appear here as you chat.', }, diff --git a/frontend/src/i18n/locales/es.ts b/frontend/src/i18n/locales/es.ts index f6078b7..aa3ee11 100644 --- a/frontend/src/i18n/locales/es.ts +++ b/frontend/src/i18n/locales/es.ts @@ -32,6 +32,12 @@ const es = { askAi: 'Preguntar a la IA', removeFromContext: 'Quitar {{trialRef}} del contexto', showOnMap: 'Mostrar {{title}} en el mapa', + showTrialsOnMap_one: 'Mostrar {{count}} ensayo en el mapa', + showTrialsOnMap_other: 'Mostrar {{count}} ensayos en el mapa', + trialsOnMap: 'En el mapa', + findMore: 'Buscar similares', + findMorePrompt: 'Buscar más ensayos como estos.', + contextTrials: '{{count}} ensayos', definition: 'Definición: {{definition}}', send: 'Enviar', }, @@ -87,7 +93,10 @@ const es = { map: { trialCount_one: '{{count}} ensayo', trialCount_other: '{{count}} ensayos', - coverageArea: 'Área de cobertura', + history: 'Historial de resultados', + historyEmpty: + 'Cada respuesta que encuentra ensayos aparece aquí, para volver a mostrar sus ensayos en el mapa.', + historyAnswer: 'Respuesta {{index}}', coverageNotice: 'La cobertura incluye centros de ensayos clínicos en todo Canadá.', emptyHint: 'Los ensayos aparecerán aquí a medida que converse.', }, diff --git a/frontend/src/i18n/locales/fr-CA.ts b/frontend/src/i18n/locales/fr-CA.ts index 6d7035d..2b353cd 100644 --- a/frontend/src/i18n/locales/fr-CA.ts +++ b/frontend/src/i18n/locales/fr-CA.ts @@ -32,6 +32,12 @@ const frCa = { askAi: 'Demander à l’IA', removeFromContext: 'Retirer {{trialRef}} du contexte', showOnMap: 'Afficher {{title}} sur la carte', + showTrialsOnMap_one: 'Afficher {{count}} essai sur la carte', + showTrialsOnMap_other: 'Afficher {{count}} essais sur la carte', + trialsOnMap: 'Sur la carte', + findMore: 'Trouver des essais semblables', + findMorePrompt: 'Trouver d’autres essais semblables à ceux-ci.', + contextTrials: '{{count}} essais', definition: 'Définition : {{definition}}', send: 'Envoyer', }, @@ -87,7 +93,10 @@ const frCa = { map: { trialCount_one: '{{count}} essai', trialCount_other: '{{count}} essais', - coverageArea: 'Zone couverte', + history: 'Historique des résultats', + historyEmpty: + 'Chaque réponse qui trouve des essais apparaît ici, pour remettre ses essais sur la carte.', + historyAnswer: 'Réponse {{index}}', coverageNotice: 'La couverture comprend des sites d’essais cliniques partout au Canada.', emptyHint: 'Les essais apparaîtront ici au fil de la conversation.', }, diff --git a/frontend/src/i18n/locales/hi.ts b/frontend/src/i18n/locales/hi.ts index 1fecdbb..2e8bfa0 100644 --- a/frontend/src/i18n/locales/hi.ts +++ b/frontend/src/i18n/locales/hi.ts @@ -32,6 +32,12 @@ const hi = { askAi: 'AI से पूछें', removeFromContext: '{{trialRef}} को संदर्भ से हटाएँ', showOnMap: '{{title}} को नक्शे पर दिखाएं', + showTrialsOnMap_one: '{{count}} परीक्षण नक्शे पर दिखाएं', + showTrialsOnMap_other: '{{count}} परीक्षण नक्शे पर दिखाएं', + trialsOnMap: 'नक्शे पर', + findMore: 'ऐसे और खोजें', + findMorePrompt: 'इन जैसे और परीक्षण खोजें।', + contextTrials: '{{count}} परीक्षण', definition: 'परिभाषा: {{definition}}', send: 'भेजें', }, @@ -85,7 +91,10 @@ const hi = { map: { trialCount_one: '{{count}} ट्रायल', trialCount_other: '{{count}} ट्रायल', - coverageArea: 'कवरेज क्षेत्र', + history: 'परिणामों का इतिहास', + historyEmpty: + 'परीक्षण खोजने वाला हर जवाब यहाँ दिखता है, ताकि आप उसके परीक्षण फिर से नक्शे पर ला सकें।', + historyAnswer: 'जवाब {{index}}', coverageNotice: 'कवरेज में पूरे कनाडा के परीक्षण केंद्र शामिल हैं।', emptyHint: 'बातचीत के साथ परीक्षण यहाँ दिखाई देंगे।', }, diff --git a/frontend/src/i18n/locales/yue.ts b/frontend/src/i18n/locales/yue.ts index f51eabd..654f476 100644 --- a/frontend/src/i18n/locales/yue.ts +++ b/frontend/src/i18n/locales/yue.ts @@ -30,6 +30,12 @@ const yue = { askAi: '問下 AI', removeFromContext: '將 {{trialRef}} 由上下文移走', showOnMap: '喺地圖顯示 {{title}}', + showTrialsOnMap_one: '喺地圖顯示 {{count}} 個試驗', + showTrialsOnMap_other: '喺地圖顯示 {{count}} 個試驗', + trialsOnMap: '已經喺地圖上', + findMore: '搵類似嘅試驗', + findMorePrompt: '搵多啲類似嘅試驗。', + contextTrials: '{{count}} 個試驗', definition: '定義:{{definition}}', send: 'send出', }, @@ -81,7 +87,9 @@ const yue = { map: { trialCount_one: '{{count}} 個臨床試驗', trialCount_other: '{{count}} 個臨床試驗', - coverageArea: '覆蓋範圍', + history: '結果紀錄', + historyEmpty: '每個搵到試驗嘅回覆都會列喺呢度,方便你將佢嘅試驗再放返上地圖。', + historyAnswer: '回覆 {{index}}', coverageNotice: '覆蓋範圍包括加拿大各地嘅試驗中心。', emptyHint: '傾落去,試驗就會喺呢度出現。', }, diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index f05ac37..dbbe1dd 100644 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -30,6 +30,12 @@ const zhCn = { askAi: '询问 AI', removeFromContext: '将 {{trialRef}} 移出上下文', showOnMap: '在地图上显示 {{title}}', + showTrialsOnMap_one: '在地图上显示 {{count}} 项试验', + showTrialsOnMap_other: '在地图上显示 {{count}} 项试验', + trialsOnMap: '已在地图上', + findMore: '查找类似试验', + findMorePrompt: '查找更多类似的试验。', + contextTrials: '{{count}} 项试验', definition: '定义:{{definition}}', send: '发送', }, @@ -81,7 +87,9 @@ const zhCn = { map: { trialCount_one: '{{count}} 项试验', trialCount_other: '{{count}} 项试验', - coverageArea: '覆盖范围', + history: '结果记录', + historyEmpty: '每个找到试验的回答都会列在这里,方便您把它的试验重新显示在地图上。', + historyAnswer: '回答 {{index}}', coverageNotice: '覆盖范围包括加拿大各地的试验中心。', emptyHint: '试验将随着对话在此显示。', }, diff --git a/frontend/src/lib/utils.ts b/frontend/src/lib/utils.ts index 2819a83..67248cc 100644 --- a/frontend/src/lib/utils.ts +++ b/frontend/src/lib/utils.ts @@ -4,3 +4,7 @@ import { twMerge } from 'tailwind-merge'; export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)); } + +export function truncate(text: string, max: number): string { + return text.length > max ? `${text.slice(0, max).trimEnd()}…` : text; +} diff --git a/frontend/src/store/appStore.test.ts b/frontend/src/store/appStore.test.ts index 5643316..77422ae 100644 --- a/frontend/src/store/appStore.test.ts +++ b/frontend/src/store/appStore.test.ts @@ -27,6 +27,25 @@ describe('appStore workspace', () => { expect(store().selectedSiteKey).toBeNull(); }); + it('records each answer once and puts an earlier one back, keeping context trials', () => { + store().reset(); + const earlier = { id: 'a1', question: 'Breast cancer in Toronto?', trials: [first] }; + const later = { id: 'a2', question: 'Anything in Ottawa?', trials: [second] }; + store().showTurn(earlier); + store().showTurn(later); + store().addToContext(second.trialRef); + + store().showTurn(earlier); + + expect(store().resultTurns.map((turn) => turn.id)).toEqual(['a1', 'a2']); + expect(store().shownTurnId).toBe('a1'); + expect(refs()).toEqual([first.trialRef, second.trialRef]); + + store().reset(); + expect(store().resultTurns).toEqual([]); + expect(store().shownTurnId).toBeNull(); + }); + it('opens a bookmark onto the map, selected and in context, without duplicating it', () => { store().setTrials([first]); diff --git a/frontend/src/store/appStore.ts b/frontend/src/store/appStore.ts index 2312a40..861519f 100644 --- a/frontend/src/store/appStore.ts +++ b/frontend/src/store/appStore.ts @@ -2,7 +2,7 @@ import { create } from 'zustand'; import { persist } from 'zustand/middleware'; import { LanguageCode } from '@/constants/language'; import type { SheetSnap } from '@/constants/layout'; -import type { ChatMessage, Trial } from '@/types/trial'; +import type { ChatMessage, ResultTurn, Trial } from '@/types/trial'; export type Theme = 'light' | 'dark'; @@ -14,6 +14,10 @@ interface Workspace { contextTrialRefs: string[]; selectedTrialRef: string | null; selectedSiteKey: string | null; + /** Every answer that returned trials, oldest first. */ + resultTurns: ResultTurn[]; + /** The answer whose trials the map shows; null once something else replaced them. */ + shownTurnId: string | null; /** Mobile chat sheet height; kept here so the tour can move it. */ sheetSnap: SheetSnap; } @@ -35,6 +39,7 @@ interface AppState extends Workspace { trialDrawerOpen: boolean; setTrials: (trials: Trial[]) => void; + showTurn: (turn: ResultTurn) => void; setConversationTitle: (conversationTitle: string | null) => void; setSheetSnap: (sheetSnap: SheetSnap) => void; setTrialDrawerOpen: (trialDrawerOpen: boolean) => void; @@ -54,6 +59,22 @@ interface AppState extends Workspace { const without = (refs: string[], trialRef: string) => refs.filter((ref) => ref !== trialRef); +// A set of results owns the map, except trials still in the chat context: they stay pinned until removed. +function placeTrials(state: AppState, trials: Trial[]): Partial { + const returned = new Set(trials.map((trial) => trial.trialRef)); + const kept = state.trials.filter( + (trial) => state.contextTrialRefs.includes(trial.trialRef) && !returned.has(trial.trialRef) + ); + const next = [...trials, ...kept]; + const stillShown = next.some((trial) => trial.trialRef === state.selectedTrialRef); + return { + trials: next, + pinnedTrialRefs: kept.map((trial) => trial.trialRef), + selectedTrialRef: stillShown ? state.selectedTrialRef : null, + selectedSiteKey: stillShown ? state.selectedSiteKey : null, + }; +} + export const selectIsTourRunning = (state: AppState) => state.tour !== null; export const useAppStore = create()( @@ -64,6 +85,8 @@ export const useAppStore = create()( contextTrialRefs: [], selectedTrialRef: null, selectedSiteKey: null, + resultTurns: [], + shownTurnId: null, // A fresh phone visit opens on the map; the search bar or peek bar opens the chat. sheetSnap: 'peek', bookmarkedTrialRefs: [], @@ -75,23 +98,16 @@ export const useAppStore = create()( conversationTitle: null, trialDrawerOpen: false, - // A chat turn owns the map, except trials still in the chat context: they stay pinned until removed. - setTrials: (trials) => - set((state) => { - const returned = new Set(trials.map((trial) => trial.trialRef)); - const kept = state.trials.filter( - (trial) => - state.contextTrialRefs.includes(trial.trialRef) && !returned.has(trial.trialRef) - ); - const next = [...trials, ...kept]; - const stillShown = next.some((trial) => trial.trialRef === state.selectedTrialRef); - return { - trials: next, - pinnedTrialRefs: kept.map((trial) => trial.trialRef), - selectedTrialRef: stillShown ? state.selectedTrialRef : null, - selectedSiteKey: stillShown ? state.selectedSiteKey : null, - }; - }), + setTrials: (trials) => set((state) => ({ ...placeTrials(state, trials), shownTurnId: null })), + // Records an answer the first time it is shown, so a new answer and a revisited one take the same path. + showTurn: (turn) => + set((state) => ({ + ...placeTrials(state, turn.trials), + shownTurnId: turn.id, + resultTurns: state.resultTurns.some((known) => known.id === turn.id) + ? state.resultTurns + : [...state.resultTurns, turn], + })), setConversationTitle: (conversationTitle) => set({ conversationTitle }), setSheetSnap: (sheetSnap) => set({ sheetSnap }), setTrialDrawerOpen: (trialDrawerOpen) => set({ trialDrawerOpen }), @@ -150,12 +166,14 @@ export const useAppStore = create()( selectedSiteKey: null, contextTrialRefs: [], pinnedTrialRefs: [], + resultTurns: [], + shownTurnId: null, conversationTitle: null, }), toggleTheme: () => set((state) => ({ theme: state.theme === 'dark' ? 'light' : 'dark' })), setLanguage: (language) => set({ language }), markLanguageChosen: () => set({ hasChosenLanguage: true }), - // Context is cleared so kept trials do not ride along onto the demo map. + // Context and history are cleared so the patient's own results stay off the demo map. startTour: (messages) => set((state) => ({ tour: { @@ -166,10 +184,14 @@ export const useAppStore = create()( contextTrialRefs: state.contextTrialRefs, selectedTrialRef: state.selectedTrialRef, selectedSiteKey: state.selectedSiteKey, + resultTurns: state.resultTurns, + shownTurnId: state.shownTurnId, sheetSnap: state.sheetSnap, }, }, contextTrialRefs: [], + resultTurns: [], + shownTurnId: null, })), endTour: () => set((state) => diff --git a/frontend/src/types/trial.ts b/frontend/src/types/trial.ts index 77972f7..9670f84 100644 --- a/frontend/src/types/trial.ts +++ b/frontend/src/types/trial.ts @@ -86,6 +86,15 @@ export interface ChatMessage { error?: ChatError; } +/** The trials one answer put on the map, so the map can show them again. */ +export interface ResultTurn { + /** The assistant message's id. */ + id: string; + /** The patient message the answer replied to. */ + question: string; + trials: Trial[]; +} + export interface SourceFreshness { source: TrialSourceCode; name: string;