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
2 changes: 1 addition & 1 deletion frontend/e2e/mobile.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
37 changes: 20 additions & 17 deletions frontend/src/components/bookmarks/BookmarkRow/BookmarkRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -58,27 +59,29 @@ function BookmarkRow({

<ItemActions className="gap-0.5">
{onExport && (
<ActionTooltip label={t('bookmarks.exportOne')}>
<Button
variant="action"
size="icon"
disabled={!trial || isExporting}
aria-label={`${t('bookmarks.exportOne')} (${title})`}
onClick={() => trial && onExport(trial)}
>
<FileDown />
</Button>
</ActionTooltip>
)}
<ActionTooltip label={t('bookmarks.remove')}>
<Button
variant="ghost"
variant="action"
size="icon"
disabled={!trial || isExporting}
aria-label={`${t('bookmarks.exportOne')} (${title})`}
title={t('bookmarks.exportOne')}
onClick={() => trial && onExport(trial)}
disabled={isPending}
aria-label={`${t('bookmarks.remove')} (${title})`}
onClick={() => onRemove(trialRef)}
>
<FileDown />
<BookmarkX />
</Button>
)}
<Button
variant="ghost"
size="icon"
disabled={isPending}
aria-label={`${t('bookmarks.remove')} (${title})`}
title={t('bookmarks.remove')}
onClick={() => onRemove(trialRef)}
>
<BookmarkX />
</Button>
</ActionTooltip>
</ItemActions>
</Item>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -52,12 +53,14 @@ function BookmarksSheet({ open, onOpenChange }: BookmarksSheetProps) {
return (
<Sheet open={open} onOpenChange={onOpenChange}>
<SheetContent side="right" showCloseButton={false} className="w-full gap-0 p-0 sm:max-w-md">
<SheetClose
aria-label={t('bookmarks.close')}
className="border-border bg-popover text-muted-foreground hover:text-foreground focus-visible:ring-ring absolute top-1/2 -left-4 flex h-16 w-4 -translate-y-1/2 cursor-pointer items-center justify-center rounded-l-full border border-r-0 shadow-sm transition-colors focus-visible:ring-2 focus-visible:outline-none"
>
<ChevronRight className="size-3" />
</SheetClose>
<ActionTooltip label={t('bookmarks.close')}>
<SheetClose
aria-label={t('bookmarks.close')}
className="border-border bg-popover text-muted-foreground hover:text-foreground focus-visible:ring-ring absolute top-1/2 -left-4 flex h-16 w-4 -translate-y-1/2 cursor-pointer items-center justify-center rounded-l-full border border-r-0 shadow-sm transition-colors focus-visible:ring-2 focus-visible:outline-none"
>
<ChevronRight className="size-3" />
</SheetClose>
</ActionTooltip>

<SheetHeader className="border-border border-b">
<SheetTitle>
Expand Down
20 changes: 11 additions & 9 deletions frontend/src/components/chat/ChatHeader/ChatHeader.tsx
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -11,15 +12,16 @@ function ChatHeader({ onNewConversation }: ChatHeaderProps) {

return (
<header className="border-border flex items-center justify-end border-b px-2 py-1">
<Button
variant="ghost"
size="icon"
aria-label={t('chat.newConversation')}
title={t('chat.newConversation')}
onClick={onNewConversation}
>
<SquarePen />
</Button>
<ActionTooltip label={t('chat.newConversation')}>
<Button
variant="action"
size="icon"
aria-label={t('chat.newConversation')}
onClick={onNewConversation}
>
<SquarePen />
</Button>
</ActionTooltip>
</header>
);
}
Expand Down
51 changes: 49 additions & 2 deletions frontend/src/components/chat/ChatMessages/ChatMessages.test.tsx
Original file line number Diff line number Diff line change
@@ -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(
<ChatMessages messages={messages} sessionId="s1" onCitationClick={vi.fn()} onAskAi={vi.fn()} />,
<ChatMessages
messages={messages}
sessionId="s1"
onCitationClick={vi.fn()}
onAskAi={vi.fn()}
onFindMore={onFindMore}
busy={false}
/>,
{ trials: [mockTrials[0]] }
);
}
Expand Down Expand Up @@ -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].' },
Expand Down
29 changes: 27 additions & 2 deletions frontend/src/components/chat/ChatMessages/ChatMessages.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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 {
Expand All @@ -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<HTMLDivElement>(null);
return (
Expand All @@ -66,7 +79,7 @@ function ChatMessages({ messages, sessionId, onCitationClick, onAskAi }: ChatMes
<MessageContent>{t('chat.starter')}</MessageContent>
</Message>
) : (
messages.map((message) => (
messages.map((message, index) => (
<Message from={message.role} key={message.id}>
<MessageContent>
{message.role !== ChatRole.Assistant ? (
Expand All @@ -89,6 +102,18 @@ function ChatMessages({ messages, sessionId, onCitationClick, onAskAi }: ChatMes
onSelect={onCitationClick}
/>
)}
{message.role === ChatRole.Assistant && message.trials?.length ? (
<MessageTrialActions
turn={{
id: message.id,
question: messages[index - 1]?.content ?? '',
trials: message.trials,
}}
busy={busy}
onShown={onShowTurn}
onFindMore={onFindMore}
/>
) : null}
{message.role === ChatRole.Assistant && message.observationId && (
<MessageFeedback sessionId={sessionId} observationId={message.observationId} />
)}
Expand Down
14 changes: 13 additions & 1 deletion frontend/src/components/chat/ChatPanel/ChatPanel.tsx
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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({
Expand All @@ -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
Expand All @@ -53,6 +62,9 @@ function ChatPanel({ onCitationClick }: ChatPanelProps) {
sessionId={sessionId}
onCitationClick={onCitationClick}
onAskAi={handleAskAi}
onFindMore={handleFindMore}
busy={status === 'streaming' || tourMessages !== undefined}
onShowTurn={onShowTurn}
/>
<div className="border-border bg-secondary/60 relative flex flex-col gap-3 border-t p-2">
<FollowUpChips questions={suggestions} onSelect={handleSend} />
Expand Down
Original file line number Diff line number Diff line change
@@ -1,23 +1,58 @@
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[];
onSelect: (trialRef: string) => void;
}

function MessageContextTrials({ trialRefs, onSelect }: MessageContextTrialsProps) {
const { t } = useTranslation();
const [open, setOpen] = useState(false);

if (trialRefs.length === 0) {
return null;
}

const citations = trialRefs.map((trialRef) => (
<TrialCitation key={trialRef} trialRef={trialRef} onSelect={onSelect} compact />
));

return (
<MessageAttachments className="items-center gap-1">
<Sparkles className="text-primary size-3 shrink-0" />
{trialRefs.map((trialRef) => (
<TrialCitation key={trialRef} trialRef={trialRef} onSelect={onSelect} compact />
))}
{trialRefs.length <= MAX_INLINE_TRIALS ? (
citations
) : (
// A tap toggles it too, since touch never hovers.
<HoverCard open={open} onOpenChange={setOpen} openDelay={100} closeDelay={100}>
<HoverCardTrigger asChild>
<Button
type="button"
variant="outline"
size="sm"
aria-expanded={open}
onClick={() => setOpen((current) => !current)}
className="h-5 rounded-full px-2 text-[0.7rem] font-medium"
>
{t('chat.contextTrials', { count: trialRefs.length })}
</Button>
</HoverCardTrigger>
<HoverCardContent
align="end"
className="flex w-auto max-w-72 flex-col items-start gap-1.5"
>
{citations}
</HoverCardContent>
</HoverCard>
)}
</MessageAttachments>
);
}
Expand Down
Loading
Loading