Spaces:
Running
Running
File size: 9,284 Bytes
b2c1c67 | 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 | import { useEffect, useRef, useState } from "react";
import { BrainCircuit, FileUp, Send, Square } from "lucide-react";
import { api, streamChat } from "../lib/api.js";
import MessageBubble from "./MessageBubble.jsx";
const SUGGESTIONS = [
{ title: "Search the web", prompt: "Search the web for the latest breakthroughs in AI agents and summarize the top 3." },
{ title: "Check the weather", prompt: "What's the weather like in Patiala right now?" },
{ title: "Crunch numbers", prompt: "What is (1.07 ** 30) * 25000? Explain what this means for compound interest." },
{ title: "Ask your documents", prompt: "Summarize the key points from my uploaded documents." },
];
// In the public demo a sample report is preloaded, so the prompts point at it
// and show retrieval with citations on the very first message.
const DEMO_SUGGESTIONS = [
{
title: "Query the preloaded report",
prompt: "What was Northwind's 2026 revenue and gross margin?",
},
{
title: "Multi-step retrieval",
prompt: "Summarize the autonomy research section and the three key results.",
},
{
title: "Live weather tool",
prompt: "What's the weather in Amsterdam right now?",
},
{
title: "Precise arithmetic",
prompt: "What is (1.07 ** 30) * 25000? Explain what this means for compound interest.",
},
];
export default function ChatView({
appInfo,
sessionId,
session,
ensureSession,
onSessionMeta,
onOpenDocs,
}) {
const [messages, setMessages] = useState([]);
const [input, setInput] = useState("");
const [streaming, setStreaming] = useState(false);
const [error, setError] = useState("");
const [model, setModel] = useState("");
const abortRef = useRef(null);
const scrollRef = useRef(null);
const textareaRef = useRef(null);
// Session ids this view created itself while sending. Reloading history for
// those would wipe the reply that is still streaming into local state.
const selfCreatedRef = useRef(null);
const effectiveModel =
model || session?.model || appInfo?.default_model || "";
const suggestions = appInfo?.demo_mode ? DEMO_SUGGESTIONS : SUGGESTIONS;
useEffect(() => {
if (!sessionId) {
setMessages([]);
return;
}
if (selfCreatedRef.current === sessionId) {
// Skip exactly once, for the transition that created this session.
selfCreatedRef.current = null;
return;
}
api(`/api/sessions/${sessionId}/messages`)
.then((list) =>
setMessages(
list.map((m) => ({
id: m.id,
role: m.role,
content: m.content,
tools: safeParse(m.tool_calls_json) || [],
citations: safeParse(m.citations_json) || [],
meta:
m.role === "assistant"
? {
model: m.model,
input_tokens: m.input_tokens,
output_tokens: m.output_tokens,
cost_usd: m.cost_usd,
latency_ms: m.latency_ms,
}
: null,
}))
)
)
.catch((err) => setError(err.message));
}, [sessionId]);
useEffect(() => {
const el = scrollRef.current;
if (el) el.scrollTop = el.scrollHeight;
}, [messages, streaming]);
function safeParse(json) {
try {
return json ? JSON.parse(json) : null;
} catch {
return null;
}
}
function autoResize() {
const el = textareaRef.current;
if (!el) return;
el.style.height = "auto";
el.style.height = Math.min(el.scrollHeight, 200) + "px";
}
async function send(text) {
const content = (text ?? input).trim();
if (!content || streaming) return;
setError("");
setInput("");
requestAnimationFrame(autoResize);
setStreaming(true);
setMessages((prev) => [
...prev,
{ id: `u-${Date.now()}`, role: "user", content, tools: [], citations: [] },
{
id: `a-${Date.now()}`,
role: "assistant",
content: "",
tools: [],
citations: [],
meta: null,
live: true,
},
]);
const controller = new AbortController();
abortRef.current = controller;
try {
const id = await ensureSession();
selfCreatedRef.current = id;
await streamChat(
id,
{ content, model: effectiveModel || undefined },
{
onEvent: (event) => {
setMessages((prev) => {
const next = [...prev];
const last = { ...next[next.length - 1] };
if (event.type === "token") {
last.content += event.text;
} else if (event.type === "tool_start") {
last.tools = [
...last.tools,
{ name: event.name, arguments: event.arguments, status: "running" },
];
} else if (event.type === "tool_end") {
last.tools = last.tools.map((tool) =>
tool.name === event.name && tool.status === "running"
? { ...tool, status: "done", result_preview: event.result_preview }
: tool
);
} else if (event.type === "citations") {
last.citations = event.citations;
} else if (event.type === "usage") {
last.meta = event;
} else if (event.type === "title") {
onSessionMeta(id, { title: event.title });
} else if (event.type === "done") {
last.live = false;
} else if (event.type === "error") {
setError(event.message);
last.live = false;
}
next[next.length - 1] = last;
return next;
});
},
},
controller.signal
);
} catch (err) {
if (err.name !== "AbortError") setError(err.message);
} finally {
setStreaming(false);
abortRef.current = null;
setMessages((prev) =>
prev.map((m) => (m.live ? { ...m, live: false } : m))
);
}
}
function stop() {
abortRef.current?.abort();
}
const showEmpty = messages.length === 0;
return (
<>
<div className="topbar">
<span className="topbar-title">
{session?.title || "New conversation"}
</span>
<div className="topbar-spacer" />
<button className="icon-btn" title="Upload documents" onClick={onOpenDocs}>
<FileUp size={17} />
</button>
{appInfo?.available_models?.length > 0 && (
<select
className="model-select"
value={effectiveModel}
onChange={(e) => setModel(e.target.value)}
title="Model for this conversation"
>
{appInfo.available_models.map((m) => (
<option key={m} value={m}>
{m}
</option>
))}
</select>
)}
</div>
<div className="chat-scroll" ref={scrollRef}>
{showEmpty ? (
<div className="empty-state fade-in">
<div className="empty-logo">
<BrainCircuit size={30} />
</div>
<h1>What can I do for you?</h1>
<p>
I'm Synapse. I can search the web, check the weather, do precise
math, and answer questions about your uploaded documents, with
sources cited.
</p>
<div className="suggestions">
{suggestions.map((s) => (
<button
key={s.title}
className="suggestion-card"
onClick={() => send(s.prompt)}
>
<b>{s.title}</b>
{s.prompt}
</button>
))}
</div>
</div>
) : (
<div className="chat-inner">
{error && <div className="error-banner">{error}</div>}
{messages.map((message) => (
<MessageBubble key={message.id} message={message} />
))}
</div>
)}
</div>
<div className="composer-wrap">
<div className="composer">
<textarea
ref={textareaRef}
rows={1}
placeholder="Message Synapse..."
value={input}
onChange={(e) => {
setInput(e.target.value);
autoResize();
}}
onKeyDown={(e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
send();
}
}}
/>
{streaming ? (
<button className="send-btn stop" title="Stop" onClick={stop}>
<Square size={15} />
</button>
) : (
<button
className="send-btn"
title="Send"
disabled={!input.trim()}
onClick={() => send()}
>
<Send size={16} />
</button>
)}
</div>
<div className="composer-hint">
Synapse can use tools autonomously. Enter to send, Shift+Enter for a new line.
</div>
</div>
</>
);
}
|