File size: 17,783 Bytes
af1bee9 fb43301 af1bee9 fb43301 af1bee9 fb43301 af1bee9 fb43301 af1bee9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 | 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>
);
}
|