import { useEffect, useMemo, useRef, useState } from "react"; import { AssistantRuntimeProvider, ComposerPrimitive, ThreadPrimitive, useExternalStoreRuntime, } from "@assistant-ui/react"; import { ApprovalCard } from "./ApprovalCard"; import { itemToMessage, type Item } from "../lib/messages"; import { loadSettings, type Settings } from "../lib/settings"; import { recordAudio, speak, transcribe } from "../lib/voice"; import { WsClient, type ApprovalDecision, type ChatEvent } from "../lib/ws"; function nextId(): string { return `m-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`; } interface ChatProps { onEditSettings: () => void; } export function Chat({ onEditSettings }: ChatProps) { const settings = loadSettings(); const wsRef = useRef(null); const [items, setItems] = useState([]); const [running, setRunning] = useState(false); const [status, setStatus] = useState<"connecting" | "open" | "closed" | "reconnecting">("connecting"); const [recording, setRecording] = useState(false); const [voiceOut, setVoiceOut] = useState(false); const voiceOutRef = useRef(voiceOut); voiceOutRef.current = voiceOut; const stopRecordingRef = useRef<(() => void) | null>(null); const handleEvent = (ev: ChatEvent, s: Settings) => { switch (ev.type) { case "chunk": setItems((prev) => { const last = prev[prev.length - 1]; if (last?.kind === "assistant") { return [...prev.slice(0, -1), { ...last, text: last.text + (ev.content ?? "") }]; } return [...prev, { kind: "assistant", id: nextId(), text: ev.content ?? "" }]; }); break; case "chunk_reset": setItems((prev) => prev[prev.length - 1]?.kind === "assistant" ? prev.slice(0, -1) : prev, ); break; case "thinking": setItems((prev) => [ ...prev.filter((i) => i.kind !== "thinking"), { kind: "thinking", id: nextId(), text: ev.content ?? "" }, ]); break; case "tool_call": setItems((prev) => [ ...prev.filter((i) => i.kind !== "thinking"), { kind: "tool", id: nextId(), toolName: ev.name, args: ev.args }, ]); break; case "tool_result": setItems((prev) => { const idx = [...prev].reverse().findIndex((i) => i.kind === "tool"); if (idx < 0) return prev; const i = prev.length - 1 - idx; const t = prev[i] as Extract; return [...prev.slice(0, i), { ...t, output: ev.output }, ...prev.slice(i + 1)]; }); break; case "done": { setItems((prev) => { const last = prev[prev.length - 1]; const text = ev.full_response ?? (last?.kind === "assistant" ? last.text : ""); if (s.ttsUrl && voiceOutRef.current && text) { speak(s.ttsUrl, text).catch(() => {}); } if (last?.kind === "assistant") return [...prev.slice(0, -1), { ...last, text }]; if (text) return [...prev, { kind: "assistant", id: nextId(), text }]; return prev; }); setRunning(false); break; } case "approval_request": setItems((prev) => [ ...prev, { kind: "approval", id: nextId(), requestId: ev.request_id, tool: ev.tool, summary: ev.arguments_summary ?? "", timeoutSecs: ev.timeout_secs, }, ]); setRunning(false); break; case "error": setItems((prev) => [ ...prev, { kind: "assistant", id: nextId(), text: `Erro: ${ev.message ?? ev.code ?? "desconhecido"}`, }, ]); setRunning(false); break; case "aborted": setRunning(false); break; default: break; } }; useEffect(() => { const ws = new WsClient({ url: wsUrlOf(settings), protocols: ["zeroclaw.v1", `bearer.${settings.token}`], onStatus: setStatus, onEvent: (ev) => handleEvent(ev, settings), }); wsRef.current = ws; ws.connect(); return () => ws.disconnect(); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); const handleApproval = (requestId: string, decision: ApprovalDecision) => { wsRef.current?.sendApproval(requestId, decision); setItems((prev) => prev.map((i) => (i.kind === "approval" && i.requestId === requestId ? { ...i, decision } : i)), ); }; const sendText = (text: string) => { setItems((prev) => [...prev, { kind: "user", id: nextId(), text }]); setRunning(true); wsRef.current?.sendMessage(text); }; const toggleMic = () => { if (recording) { stopRecordingRef.current?.(); setRecording(false); return; } if (!settings.sttUrl) { setItems((prev) => [ ...prev, { kind: "assistant", id: nextId(), text: "Configure a URL de STT (voz → texto) nas configurações para usar o microfone.", }, ]); return; } setRecording(true); stopRecordingRef.current = recordAudio( async (blob) => { setRecording(false); try { const text = await transcribe(settings.sttUrl, blob); if (text) sendText(text); } catch (err) { setItems((prev) => [ ...prev, { kind: "assistant", id: nextId(), text: `Falha na transcrição: ${String(err)}` }, ]); } }, (err) => { setRecording(false); setItems((prev) => [ ...prev, { kind: "assistant", id: nextId(), text: `Microfone indisponível: ${String(err)}` }, ]); }, ); }; const messages = useMemo(() => items.map(itemToMessage), [items]); const runtime = useExternalStoreRuntime({ messages, isRunning: running, convertMessage: (m) => m, onNew: async (message) => { const text = message.content .filter((p): p is { type: "text"; text: string } => p.type === "text") .map((p) => p.text) .join("") .trim(); if (!text) return; sendText(text); }, }); const statusLabel = status === "open" ? "conectado" : status === "connecting" ? "conectando…" : status === "reconnecting" ? "reconectando…" : "desconectado"; const renderItem = (item: Item) => { if (item.kind === "user") { return (
{item.text}
); } if (item.kind === "thinking") { return (
Raciocínio

{item.text}

); } if (item.kind === "tool") { return (
⚙ {item.toolName} {item.output !== undefined && ✓}
); } if (item.kind === "approval") { return (
handleApproval(item.requestId, d)} />
); } return (
{item.text}
); }; return (
Iara {statusLabel}
{items.length === 0 && (
Fale com a Iara — pergunte, peça para criar eventos, tarefas, notas e e-mails.
)}
{items.map(renderItem)}
); } function wsUrlOf(s: Settings): string { const base = s.gatewayUrl.trim().replace(/\/+$/, ""); const params = new URLSearchParams({ agent: s.agent.trim() || "main" }); const name = s.sessionName.trim(); if (name) params.set("name", name); if (s.token.trim()) params.set("token", s.token.trim()); return `${base}?${params.toString()}`; }