Spaces:
Sleeping
Sleeping
Optimise keeps a complete board unchanged; remove Generate placement; Gemini fallback when busy
04e2ccf verified Download frontend/src/components/AssistantPanel.tsx from mindchainai/PCB_agentic_ai: direct link, hf CLI and curl.
- Browser
- Download file 9.78 kB
-
https://huggingface.co/spaces/mindchainai/PCB_agentic_ai/resolve/main/frontend/src/components/AssistantPanel.tsx
- Command line
-
hf download hf://spaces/mindchainai/PCB_agentic_ai/frontend/src/components/AssistantPanel.tsx
-
curl -L -o AssistantPanel.tsx https://huggingface.co/spaces/mindchainai/PCB_agentic_ai/resolve/main/frontend/src/components/AssistantPanel.tsx
9.78 kB
| import { KeyRound, MessageCircleQuestion, SendHorizontal, Trash2, X } from 'lucide-react' | |
| import { useEffect, useRef, useState } from 'react' | |
| import type { ReactNode } from 'react' | |
| import { ApiError, pcbApi } from '../services/pcbApi' | |
| import type { ChatMessage, Design, Health } from '../types/pcb' | |
| import { Spinner } from './ui' | |
| interface Props { | |
| projectId: string | |
| projectName: string | |
| design: Design | null | |
| health: Health | null | |
| focus: { ref?: string | null; net?: string | null; issue?: string | null } | |
| onClose: () => void | |
| } | |
| const store = new Map<string, ChatMessage[]>() // conversation per project for this browser session | |
| export function AssistantPanel({ projectId, projectName, design, health, focus, onClose }: Props) { | |
| const [messages, setMessages] = useState<ChatMessage[]>(() => store.get(projectId) ?? []) | |
| const [text, setText] = useState('') | |
| const [sending, setSending] = useState(false) | |
| const [error, setError] = useState<{ code: string; message: string } | null>(null) | |
| const [model, setModel] = useState<string | null>(null) | |
| const list = useRef<HTMLDivElement>(null) | |
| const configured = health?.ai.configured ?? false | |
| useEffect(() => { store.set(projectId, messages) }, [projectId, messages]) | |
| useEffect(() => { list.current?.scrollTo({ top: list.current.scrollHeight, behavior: 'smooth' }) }, [messages, sending]) | |
| const send = async (q: string) => { | |
| const question = q.trim() | |
| if (!question || sending) return | |
| const next: ChatMessage[] = [...messages, { role: 'user', content: question }] | |
| setMessages(next) | |
| setText('') | |
| setError(null) | |
| setSending(true) | |
| try { | |
| const res = await pcbApi.chat(projectId, next, { | |
| ref: focus.ref ?? undefined, net: focus.net ?? undefined, issue: focus.issue ?? undefined, | |
| }) | |
| setModel(res.model) | |
| setMessages([...next, { role: 'assistant', content: res.reply }]) | |
| } catch (e) { | |
| const err = e instanceof ApiError ? e : new ApiError('ERROR', (e as Error).message) | |
| setError({ code: err.code, message: err.message }) | |
| // the question was not answered: take it out of the conversation and give it back for a retry | |
| setMessages(messages) | |
| setText(question) | |
| } finally { | |
| setSending(false) | |
| } | |
| } | |
| const v = design?.validation | |
| const m = design?.metrics | |
| const suggestions = [ | |
| 'Give me a short summary of this board', | |
| ...(m && m.routing_percent < 100 ? ['Why are some connections still unrouted, and what can I do?'] : []), | |
| ...(v && v.errors > 0 ? ['Explain the DRC errors and how to fix them'] : []), | |
| ...(focus.ref ? [`What does ${focus.ref} do, and is it placed well?`] : []), | |
| ...(focus.net ? [`Explain the net ${focus.net}`] : []), | |
| 'How do I get this board into KiCad?', | |
| ].slice(0, 5) | |
| return ( | |
| <section className="absolute bottom-3 right-3 top-3 z-20 flex w-[380px] max-w-[calc(100%-1.5rem)] flex-col overflow-hidden rounded-xl border border-ink-600 bg-ink-850/95 shadow-2xl backdrop-blur" | |
| aria-label="AI guide"> | |
| <header className="flex items-center gap-2 border-b border-ink-700 px-3 py-2"> | |
| <MessageCircleQuestion size={16} className="text-accent" /> | |
| <div className="min-w-0 flex-1"> | |
| <div className="text-[13px] font-semibold text-white">AI guide</div> | |
| <div className="truncate text-[11px] text-ink-400"> | |
| {projectName}{model ? ` · ${model}` : configured ? ` · ${health?.ai.provider}` : ''} | |
| </div> | |
| </div> | |
| {messages.length > 0 && ( | |
| <button type="button" className="text-ink-400 hover:text-white" title="Clear the conversation" | |
| onClick={() => { setMessages([]); setError(null) }}><Trash2 size={14} /></button> | |
| )} | |
| <button type="button" className="text-ink-400 hover:text-white" aria-label="Close the AI guide" onClick={onClose}> | |
| <X size={16} /> | |
| </button> | |
| </header> | |
| <div ref={list} className="min-h-0 flex-1 space-y-2.5 overflow-y-auto px-3 py-3 text-[12.5px]"> | |
| {!configured && <SetupNote />} | |
| {messages.length === 0 && configured && ( | |
| <div className="text-ink-300"> | |
| Ask anything about this board: why a net is unrouted, what a DRC error means, what a part does, or how to | |
| use the app. {focus.ref || focus.net ? 'Your current selection is included.' : 'Select a part or net to ask about it.'} | |
| </div> | |
| )} | |
| {messages.map((msg, i) => ( | |
| <div key={i} className={msg.role === 'user' ? 'flex justify-end' : ''}> | |
| <div className={msg.role === 'user' | |
| ? 'max-w-[85%] rounded-lg rounded-br-sm bg-accent/20 px-2.5 py-1.5 text-ink-100 [overflow-wrap:anywhere]' | |
| : 'rounded-lg rounded-bl-sm bg-ink-800 px-2.5 py-1.5 leading-relaxed text-ink-100 [overflow-wrap:anywhere]'}> | |
| {msg.role === 'user' ? msg.content : <Markdown text={msg.content} />} | |
| </div> | |
| </div> | |
| ))} | |
| {sending && <div className="flex items-center gap-2 text-ink-400"><Spinner size={12} /> Thinking…</div>} | |
| {error && (error.code === 'AI_NOT_CONFIGURED' ? <SetupNote /> : ( | |
| <div role="alert" className="rounded border border-bad/40 bg-bad/10 px-2.5 py-1.5 text-red-200"> | |
| <b>{error.code}</b>: {error.message} | |
| <div className="mt-1 text-[11.5px] text-red-200/80">Your question is back in the box below — press Enter to try again.</div> | |
| </div> | |
| ))} | |
| </div> | |
| {messages.length === 0 && configured && ( | |
| <div className="flex flex-wrap gap-1.5 border-t border-ink-700 px-3 py-2"> | |
| {suggestions.map((s) => ( | |
| <button key={s} type="button" disabled={sending} onClick={() => void send(s)} | |
| className="rounded-full border border-ink-600 px-2.5 py-1 text-left text-[11.5px] text-ink-200 hover:border-accent/60 hover:text-white"> | |
| {s} | |
| </button> | |
| ))} | |
| </div> | |
| )} | |
| <form className="flex items-end gap-2 border-t border-ink-700 p-2" onSubmit={(e) => { e.preventDefault(); void send(text) }}> | |
| <textarea className="field min-h-[38px] flex-1 resize-none py-2 text-[12.5px]" rows={2} maxLength={4000} | |
| placeholder={configured ? 'Ask about this board…' : 'Add a Gemini API key to enable the guide'} | |
| value={text} disabled={!configured || sending} aria-label="Question for the AI guide" | |
| onChange={(e) => setText(e.target.value)} | |
| onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); void send(text) } }} /> | |
| <button type="submit" className="btn-primary h-[38px] px-3" disabled={!configured || sending || !text.trim()} | |
| aria-label="Send"> | |
| {sending ? <Spinner /> : <SendHorizontal size={15} />} | |
| </button> | |
| </form> | |
| </section> | |
| ) | |
| } | |
| function SetupNote() { | |
| return ( | |
| <div className="rounded-lg border border-warn/40 bg-warn/10 px-3 py-2 text-[12px] leading-relaxed text-amber-100"> | |
| <div className="mb-1 flex items-center gap-1.5 font-semibold"><KeyRound size={13} /> The AI guide needs an API key</div> | |
| Set <code className="rounded bg-black/30 px-1">GEMINI_API_KEY</code> for the backend, then restart it: | |
| <ul className="mt-1 list-disc pl-4"> | |
| <li>Local: in <code className="rounded bg-black/30 px-1">backend/.env</code></li> | |
| <li>Docker: <code className="rounded bg-black/30 px-1">-e GEMINI_API_KEY=…</code></li> | |
| <li>Hugging Face Space: Settings → Variables and secrets → New secret</li> | |
| </ul> | |
| The key stays on the server; the browser never sees it. | |
| </div> | |
| ) | |
| } | |
| /** Small, safe Markdown renderer (paragraphs, lists, headings, bold, inline code) - no HTML injection. */ | |
| function Markdown({ text }: { text: string }) { | |
| const blocks: ReactNode[] = [] | |
| let list: { ordered: boolean; items: string[] } | null = null | |
| const flush = () => { | |
| if (!list) return | |
| const items = list.items.map((it, i) => <li key={i}>{inline(it)}</li>) | |
| blocks.push(list.ordered | |
| ? <ol key={blocks.length} className="my-1 list-decimal space-y-0.5 pl-4">{items}</ol> | |
| : <ul key={blocks.length} className="my-1 list-disc space-y-0.5 pl-4">{items}</ul>) | |
| list = null | |
| } | |
| for (const raw of text.split('\n')) { | |
| const line = raw.trimEnd() | |
| const bullet = /^\s*[-*•]\s+(.*)$/.exec(line) | |
| const numbered = /^\s*\d+[.)]\s+(.*)$/.exec(line) | |
| if (bullet || numbered) { | |
| const ordered = !!numbered | |
| if (!list || list.ordered !== ordered) { flush(); list = { ordered, items: [] } } | |
| list.items.push((bullet ?? numbered)![1]) | |
| continue | |
| } | |
| flush() | |
| if (!line.trim()) continue | |
| const heading = /^#{1,4}\s+(.*)$/.exec(line) | |
| blocks.push(heading | |
| ? <div key={blocks.length} className="mt-1 font-semibold text-white">{inline(heading[1])}</div> | |
| : <p key={blocks.length} className="my-1">{inline(line)}</p>) | |
| } | |
| flush() | |
| return <>{blocks}</> | |
| } | |
| function inline(s: string): ReactNode[] { | |
| const out: ReactNode[] = [] | |
| const re = /(\*\*[^*]+\*\*|`[^`]+`)/g | |
| let last = 0 | |
| let m: RegExpExecArray | null | |
| while ((m = re.exec(s))) { | |
| if (m.index > last) out.push(s.slice(last, m.index)) | |
| const tok = m[0] | |
| out.push(tok.startsWith('**') | |
| ? <b key={m.index} className="text-white">{tok.slice(2, -2)}</b> | |
| : <code key={m.index} className="rounded bg-black/30 px-1 font-mono text-[11.5px]">{tok.slice(1, -1)}</code>) | |
| last = m.index + tok.length | |
| } | |
| if (last < s.length) out.push(s.slice(last)) | |
| return out | |
| } | |