Download web/src/chat/AskChat.tsx from EnergyVenom/patchwise-agent-studio: direct link, hf CLI and curl.
- Browser
- Download file 17.8 kB
-
https://huggingface.co/spaces/EnergyVenom/patchwise-agent-studio/resolve/main/web/src/chat/AskChat.tsx
- Command line
-
hf download hf://spaces/EnergyVenom/patchwise-agent-studio/web/src/chat/AskChat.tsx
-
curl -L -o AskChat.tsx https://huggingface.co/spaces/EnergyVenom/patchwise-agent-studio/resolve/main/web/src/chat/AskChat.tsx
17.8 kB
| import { ActionIcon, Button, Drawer, Text, Textarea } from '@mantine/core'; | |
| import { IconArrowUp, IconMessages, IconPlus, IconShieldLock, IconTrash, IconX } from '@/components/icons'; | |
| import { useQuery, useQueryClient } from '@tanstack/react-query'; | |
| import { useCallback, useEffect, useRef, useState, type FormEvent, type KeyboardEvent as ReactKeyboardEvent } from 'react'; | |
| import { Link, useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom'; | |
| import { MODULE_NAMES } from '../domain/agents'; | |
| import { errorMessage } from '../api/client'; | |
| import { askErrorWords, useAssistantAsk, useAssistantStatus, useRun } from '../api/hooks'; | |
| import { useShell } from '../components/shell/prefs'; | |
| import { TopBar } from '../components/shell/TopBar'; | |
| import { QueryState } from '../components/states'; | |
| import { runTitle, shortWhen } from '../domain/runName'; | |
| import { AnswerCard, ConfirmCard, ScreenLinks, Sources } from './ChatCards'; | |
| import { | |
| createConversation, deleteConversation, getConversation, listConversations, sendMessage, | |
| type ChatAction, type ChatContext, type ChatMessage, type ChatResult, type ConversationSummary, | |
| } from './api'; | |
| import { CoworkerAvatar } from '../components/CoworkerAvatar'; | |
| import { COWORKERS } from '../domain/coworkers'; | |
| import { speakerFor, type Speaker } from './speaker'; | |
| import type { AskArrival } from './useAsk'; | |
| import './ask.css'; | |
| const STARTERS_PATCH = ['Is Procure-to-Pay ready for 26C?', 'What does this patch change in invoice matching?', 'What is not covered yet?', 'What is waiting for me?']; | |
| const STARTERS_RUN = ['What is waiting for me in this test run?', 'Why did the requisition approval scenario fail?', 'What does this patch change in invoice matching?']; | |
| /** A question that asks the co-worker to do something: it always goes to the built-in assistant, whose proposed actions | |
| * keep their confirm cards. Everything else goes to Hermes when an admin switched Hermes on. */ | |
| const ACTION_WORDS = /^(please\s+)?(start|run|launch|re-?run|approve|skip|cancel|stop|add a note|note)\b/i; | |
| /** Shown under the input only while Hermes is the one answering. */ | |
| export const HERMES_NOTICE = "Answered by the Hermes assistant using NVIDIA's AI model. Don't paste client data."; | |
| /** What the co-worker looks at: the test run in the address (/assistant/:runId), or a business area (?module=). Context, | |
| * never an instruction. */ | |
| function useAskContext() { | |
| const { id: runId } = useParams(); | |
| const [params] = useSearchParams(); | |
| const module = params.get('module'); | |
| const run = useRun(runId ?? '', !!runId); | |
| const context: ChatContext = { run_id: runId ?? null, module: module ?? run.data?.modules?.[0] ?? undefined }; | |
| const label = runId ? `${run.data ? runTitle(run.data) : 'this test run'} · this test run` : module ? (MODULE_NAMES[module] ?? module) : 'All areas'; | |
| return { runId: runId ?? null, context, label, narrowed: !!runId || !!module }; | |
| } | |
| /** Who is answering: the coworker's face (moving while it works), its name and role. Decorative for screen readers, | |
| * which hear the answer itself. */ | |
| function SpeakerRow({ who, working }: { who: Speaker; working: boolean }) { | |
| return ( | |
| <div className="ask-speaker" data-kind={who.kind} aria-hidden> | |
| {who.kind === 'coworker' ? <CoworkerAvatar name={who.name} size={24} working={working} /> | |
| : who.kind === 'patchwise' | |
| ? <span className="ask-speaker-mark"><img className="trio-logo" data-for="light" src="/favicon-graphite.svg" alt="" width={24} height={24} /><img className="trio-logo" data-for="dark" src="/favicon-paper.svg" alt="" width={24} height={24} /></span> | |
| : <span className="ask-speaker-mark ask-speaker-plain">H</span>} | |
| <span className="ask-speaker-name">{who.name}</span> | |
| <span className="ask-speaker-role">· {who.role}</span> | |
| </div> | |
| ); | |
| } | |
| function Message({ m, onAction }: { m: ChatMessage; onAction: (a: ChatAction) => void }) { | |
| if (m.role === 'user') { | |
| return <div className="ask-msg" data-role="user"><span className="fpt-sr-only">You asked: </span>{m.text}</div>; | |
| } | |
| const r: ChatResult | undefined = m.result; | |
| const who = speakerFor(m); | |
| return ( | |
| <div className="ask-msg" data-role="assistant" data-testid="chat-answer" aria-busy={m.pending || undefined}> | |
| <SpeakerRow who={who} working={!!m.pending} /> | |
| {/* the placeholder is hidden from assistive tech, so the answer is announced once, when it is complete */} | |
| {m.pending && !m.text && <p className="ask-thinking" aria-hidden>{who.name} is looking it up…</p>} | |
| {/* plain text only: nothing the model or a tool writes is ever rendered as markup or as a link */} | |
| {m.text && <p className="ask-answer">{m.text}</p>} | |
| {m.error && <p className="ask-error" role="alert">{m.error}</p>} | |
| {r?.cards.map((c, i) => <AnswerCard key={i} card={c} />)} | |
| {m.action && <ConfirmCard action={m.action} onChange={onAction} />} | |
| {r && <ScreenLinks links={r.links} />} | |
| {r && <Sources sources={r.sources} noSource={r.no_source} />} | |
| {m.by === 'hermes' && !m.pending && m.text && <Text size="xs" c="dimmed" data-testid="hermes-answered">Answered by the Hermes assistant{m.model ? ` (${m.model})` : ''}.</Text>} | |
| </div> | |
| ); | |
| } | |
| /** The person's earlier conversations, newest first; the open one is marked. */ | |
| function History({ current, onNew, onDelete, onPick }: { current: string | null; onNew: () => void; onDelete: (c: ConversationSummary) => void; onPick?: () => void }) { | |
| const q = useQuery({ queryKey: ['chat-conversations'], queryFn: listConversations }); | |
| const items = q.data?.items ?? []; | |
| const loc = useLocation(); | |
| const base = loc.pathname; | |
| return ( | |
| <div className="ask-history"> | |
| <Button variant="default" fullWidth justify="flex-start" leftSection={<IconPlus size={16} aria-hidden />} onClick={onNew} data-testid="chat-new">New conversation</Button> | |
| <nav aria-label="Conversations" className="ask-history-list"> | |
| <QueryState q={q} isEmpty={items.length === 0} errorTitle="Your conversations could not be loaded" | |
| empty={<p className="ask-history-empty">Your questions are kept here, so you can come back to an answer.</p>}> | |
| <ul> | |
| {items.map((c) => { | |
| const title = c.title?.trim() || 'New conversation'; | |
| return ( | |
| <li key={c.id} className="ask-history-item" aria-current={c.id === current ? 'page' : undefined}> | |
| <Link to={`${base}?c=${encodeURIComponent(c.id)}`} onClick={onPick} aria-current={c.id === current ? 'page' : undefined}> | |
| <span className="ask-history-title">{title}</span> | |
| <span className="ask-history-when">{shortWhen(c.last_at)}</span> | |
| </Link> | |
| <ActionIcon variant="subtle" color="gray" size="sm" aria-label={`Delete the conversation “${title}”`} onClick={() => onDelete(c)}> | |
| <IconTrash size={14} aria-hidden /> | |
| </ActionIcon> | |
| </li> | |
| ); | |
| })} | |
| </ul> | |
| </QueryState> | |
| </nav> | |
| </div> | |
| ); | |
| } | |
| /** | |
| * The Ask page: earlier conversations on the left, the thread in the middle, the question field anchored at the bottom. | |
| * Answers read like notes with their evidence (text, data cards, links to the screens, the source). The built-in | |
| * assistant answers from the app's own data; Hermes answers general questions when an administrator switched it on. | |
| */ | |
| export function AskChat() { | |
| const qc = useQueryClient(); | |
| const nav = useNavigate(); | |
| const loc = useLocation(); | |
| const { size } = useShell(); | |
| const narrow = size === 'tablet' || size === 'phone'; | |
| const [params, setParams] = useSearchParams(); | |
| const current = params.get('c'); | |
| const ctx = useAskContext(); | |
| const status = useAssistantStatus(); | |
| const askHermes = useAssistantAsk(); | |
| const hermesOn = !!status.data?.enabled && !!status.data?.configured; | |
| const [hermesConv, setHermesConv] = useState<string | null>(null); | |
| const [messages, setMessages] = useState<ChatMessage[]>([]); | |
| const [text, setText] = useState(''); | |
| const [busy, setBusy] = useState(false); | |
| const [historyOpen, setHistoryOpen] = useState(false); | |
| const convRef = useRef<string | null>(current); | |
| const created = useRef<string | null>(null); // the conversation this page just created: nothing to load for it | |
| const lastPrompt = useRef(''); | |
| const inputRef = useRef<HTMLTextAreaElement>(null); | |
| const logRef = useRef<HTMLDivElement>(null); | |
| const seq = useRef(0); | |
| // open the conversation named in the address (?c=), or a fresh one | |
| useEffect(() => { | |
| convRef.current = current; | |
| if (!current) { setMessages([]); setHermesConv(null); return; } | |
| if (current === created.current) return; | |
| let live = true; | |
| getConversation(current).then((c) => { | |
| if (live) setMessages(c.messages.map((m) => ({ key: `h${m.id}`, role: m.role, text: m.text, tool: m.tool, action: m.action }))); | |
| }).catch(() => { | |
| if (!live) return; | |
| setMessages([]); | |
| setParams((p) => { const n = new URLSearchParams(p); n.delete('c'); return n; }, { replace: true }); | |
| }); | |
| return () => { live = false; }; | |
| }, [current]); // eslint-disable-line react-hooks/exhaustive-deps -- setParams changes identity with the address | |
| useEffect(() => { const el = logRef.current; if (el) el.scrollTop = el.scrollHeight; }, [messages]); | |
| const patch = (key: string, f: (m: ChatMessage) => ChatMessage) => setMessages((ms) => ms.map((m) => (m.key === key ? f(m) : m))); | |
| /** The built-in assistant: answers from the app's own data, with cards, sources and confirm cards. */ | |
| const askBuiltIn = async (q: string, aKey: string) => { | |
| let id = convRef.current; | |
| if (!id) { | |
| id = (await createConversation(ctx.runId)).id; | |
| created.current = id; | |
| convRef.current = id; | |
| setParams((p) => { const n = new URLSearchParams(p); n.set('c', id as string); return n; }, { replace: true }); | |
| } | |
| await sendMessage(id, q, ctx.context, (ev, data) => { | |
| const d = data as Record<string, unknown>; | |
| if (ev === 'intent') patch(aKey, (m) => ({ ...m, tool: String(d.tool) })); | |
| else if (ev === 'delta') patch(aKey, (m) => ({ ...m, text: m.text + String(d.text ?? '') })); | |
| else if (ev === 'result') patch(aKey, (m) => ({ ...m, result: data as ChatResult })); | |
| else if (ev === 'action') patch(aKey, (m) => ({ ...m, action: data as ChatAction })); | |
| else if (ev === 'error') patch(aKey, (m) => ({ ...m, error: String(d.detail ?? 'The answer could not be completed.') })); | |
| }); | |
| }; | |
| const send = async (raw: string) => { | |
| const q = raw.trim(); | |
| if (!q || busy) return; | |
| lastPrompt.current = q; | |
| setText(''); | |
| setBusy(true); | |
| const aKey = `a${++seq.current}-${Date.now()}`; | |
| const viaHermes = hermesOn && !ACTION_WORDS.test(q); | |
| setMessages((ms) => [...ms, { key: `u${aKey}`, role: 'user', text: q }, { key: aKey, role: 'assistant', text: '', pending: true, by: viaHermes ? 'hermes' : 'builtin' }]); | |
| try { | |
| if (viaHermes) { | |
| try { | |
| const out = await askHermes.mutateAsync({ question: q, conversation_id: hermesConv ?? undefined }); | |
| setHermesConv(out.conversation_id); | |
| patch(aKey, (m) => ({ ...m, text: out.answer, model: out.model })); | |
| } catch (e) { | |
| const code = (e as { code?: string }).code; | |
| if (code === 'NOT_FOUND') setHermesConv(null); | |
| if (code === 'HERMES_OFF') { // switched off meanwhile: the built-in assistant answers this one | |
| patch(aKey, (m) => ({ ...m, by: 'builtin' })); | |
| await askBuiltIn(q, aKey); | |
| } else patch(aKey, (m) => ({ ...m, error: askErrorWords(e) })); | |
| } | |
| } else await askBuiltIn(q, aKey); | |
| } catch (e) { | |
| const gone = (e as { status?: number }).status === 404; | |
| if (gone) { convRef.current = null; setParams((p) => { const n = new URLSearchParams(p); n.delete('c'); return n; }, { replace: true }); } | |
| patch(aKey, (m) => ({ ...m, error: gone ? 'This conversation is no longer available. Ask again to start a new one.' : errorMessage(e) })); | |
| } finally { | |
| patch(aKey, (m) => ({ ...m, pending: false })); | |
| setBusy(false); | |
| void qc.invalidateQueries({ queryKey: ['chat-conversations'] }); | |
| } | |
| }; | |
| const sendRef = useRef(send); | |
| sendRef.current = send; | |
| // arriving from elsewhere (Ctrl K, a screen's Ask): focus the field, and send the question that came along | |
| useEffect(() => { | |
| const arrival = loc.state as AskArrival | null; | |
| window.setTimeout(() => inputRef.current?.focus(), 30); | |
| if (arrival?.ask) { | |
| const q = arrival.ask; | |
| nav(`${loc.pathname}${loc.search}`, { replace: true, state: null }); | |
| window.setTimeout(() => void sendRef.current(q), 60); | |
| } | |
| }, [loc.key]); // eslint-disable-line react-hooks/exhaustive-deps -- once per arrival | |
| const startNew = useCallback(() => { | |
| created.current = null; | |
| setHistoryOpen(false); | |
| setParams((p) => { const n = new URLSearchParams(p); n.delete('c'); return n; }); | |
| window.setTimeout(() => inputRef.current?.focus(), 30); | |
| }, [setParams]); | |
| const remove = async (c: ConversationSummary) => { | |
| await deleteConversation(c.id).catch(() => undefined); | |
| if (c.id === current) startNew(); | |
| void qc.invalidateQueries({ queryKey: ['chat-conversations'] }); | |
| }; | |
| const widen = () => nav(`/assistant${current ? `?c=${encodeURIComponent(current)}` : ''}`); | |
| const onSubmit = (e: FormEvent) => { e.preventDefault(); void send(text); }; | |
| const onKeyDown = (e: ReactKeyboardEvent<HTMLTextAreaElement>) => { | |
| if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); void send(text); } | |
| else if (e.key === 'ArrowUp' && !text && lastPrompt.current) { e.preventDefault(); setText(lastPrompt.current); } | |
| }; | |
| const starters = ctx.runId ? STARTERS_RUN : STARTERS_PATCH; | |
| return ( | |
| <div className="ask" data-testid="chat-page"> | |
| <TopBar title="Ask" actions={narrow | |
| ? <Button variant="default" size="xs" leftSection={<IconMessages size={15} aria-hidden />} onClick={() => setHistoryOpen(true)}>Conversations</Button> | |
| : undefined} /> | |
| <div className="ask-body"> | |
| {!narrow && <History current={current} onNew={startNew} onDelete={(c) => void remove(c)} />} | |
| <section className="ask-thread" aria-label="Conversation"> | |
| <div className="ask-log" ref={logRef} role="log" aria-live="polite" aria-label="Conversation with the co-worker"> | |
| <div className="ask-col"> | |
| <p className="ask-mock" role="note" data-testid="chat-mock-strip"><IconShieldLock size={14} aria-hidden />Practice environment: answers describe the local mock app, not Oracle Fusion.</p> | |
| {messages.length === 0 && ( | |
| <div className="ask-empty"> | |
| <h2>{ctx.runId ? 'Ask about this test run' : 'Ask about this patch'}</h2> | |
| <p>I answer from your test runs and the patch research, and I show where each answer comes from. Anything I can do here, you can also do on the screens.</p> | |
| <div className="ask-team" aria-hidden> | |
| <span className="ask-team-label">Ask any of them</span> | |
| <ul>{COWORKERS.map((c) => <li key={c.key}><CoworkerAvatar name={c.name} size={28} /><span>{c.name}</span></li>)}</ul> | |
| </div> | |
| <ul className="ask-starters" aria-label="Questions to start with"> | |
| {starters.map((s) => <li key={s}><button type="button" onClick={() => void send(s)}>{s}</button></li>)} | |
| </ul> | |
| </div> | |
| )} | |
| {messages.map((m) => <Message key={m.key} m={m} onAction={(a) => patch(m.key, (x) => ({ ...x, action: a }))} />)} | |
| </div> | |
| </div> | |
| <div className="ask-dock"> | |
| <form className="ask-col ask-composer" onSubmit={onSubmit} aria-label="Ask a question"> | |
| <Textarea ref={inputRef} aria-label="Ask the co-worker" placeholder="Ask about a run, a defect or an area" variant="unstyled" autosize minRows={1} maxRows={6} | |
| value={text} maxLength={2000} onChange={(e) => setText(e.currentTarget.value)} onKeyDown={onKeyDown} /> | |
| <div className="ask-composer-row"> | |
| <div className="ask-context" data-testid="chat-context" title="What the co-worker looks at when you ask"> | |
| <span>Looking at</span> <b>{ctx.label}</b> | |
| {ctx.narrowed && <button type="button" aria-label="Ask about all areas instead" onClick={widen}><IconX size={12} aria-hidden /></button>} | |
| </div> | |
| <ActionIcon type="submit" variant="filled" size="lg" radius="xl" aria-label="Send" loading={busy} disabled={!text.trim()}><IconArrowUp size={18} aria-hidden /></ActionIcon> | |
| </div> | |
| </form> | |
| {hermesOn && <p className="ask-col ask-hermes" data-testid="hermes-notice">{HERMES_NOTICE}</p>} | |
| </div> | |
| </section> | |
| </div> | |
| {narrow && ( | |
| <Drawer opened={historyOpen} onClose={() => setHistoryOpen(false)} position="left" size="min(320px, 88vw)" title="Conversations" closeButtonProps={{ 'aria-label': 'Close the conversations' }}> | |
| <History current={current} onNew={startNew} onDelete={(c) => void remove(c)} onPick={() => setHistoryOpen(false)} /> | |
| </Drawer> | |
| )} | |
| </div> | |
| ); | |
| } | |