103 lines
3.2 KiB
JavaScript
103 lines
3.2 KiB
JavaScript
export function initChatPage() {
|
|
const log = document.getElementById("log");
|
|
const form = document.getElementById("chat-form");
|
|
const input = document.getElementById("chat-input");
|
|
const userLabel = document.getElementById("session-user");
|
|
|
|
const history = [];
|
|
|
|
async function loadUser() {
|
|
const res = await fetch("/api/me");
|
|
if (res.status === 401) {
|
|
window.location.href = "/login";
|
|
return;
|
|
}
|
|
userLabel.textContent = "alice@matrix:~$";
|
|
}
|
|
|
|
function appendLine(role, text) {
|
|
const line = document.createElement("div");
|
|
line.className = `log-line ${role}`;
|
|
const prefix = role === "user" ? "alice:" : role === "error" ? "!!" : "oracle:";
|
|
line.textContent = `${prefix} ${text}`;
|
|
log.appendChild(line);
|
|
log.scrollTop = log.scrollHeight;
|
|
return line;
|
|
}
|
|
|
|
async function sendMessage(message) {
|
|
appendLine("user", message);
|
|
history.push({role: "user", content: message});
|
|
|
|
const assistantLine = appendLine("assistant", "");
|
|
let assistantText = "";
|
|
|
|
let response;
|
|
try {
|
|
response = await fetch("/api/chat", {
|
|
method: "POST",
|
|
headers: {"Content-Type": "application/json"},
|
|
body: JSON.stringify({messages: history}),
|
|
});
|
|
} catch (err) {
|
|
assistantLine.textContent = `!! connection error: ${err.message}`;
|
|
return;
|
|
}
|
|
|
|
if (response.status === 401) {
|
|
window.location.href = "/login";
|
|
return;
|
|
}
|
|
|
|
if (!response.ok || !response.body) {
|
|
assistantLine.textContent = "!! failed to reach model";
|
|
return;
|
|
}
|
|
|
|
const reader = response.body.getReader();
|
|
const decoder = new TextDecoder();
|
|
let buffer = "";
|
|
|
|
while (true) {
|
|
const {done, value} = await reader.read();
|
|
if (done) break;
|
|
buffer += decoder.decode(value, {stream: true});
|
|
const lines = buffer.split("\n");
|
|
buffer = lines.pop() ?? "";
|
|
|
|
for (const line of lines) {
|
|
if (!line.trim()) continue;
|
|
let payload;
|
|
try {
|
|
payload = JSON.parse(line);
|
|
} catch {
|
|
continue;
|
|
}
|
|
if (payload.error) {
|
|
assistantLine.textContent = `!! ${payload.error}`;
|
|
return;
|
|
}
|
|
const chunk = payload.content ?? "";
|
|
assistantText += chunk;
|
|
assistantLine.textContent = `oracle: ${assistantText}`;
|
|
log.scrollTop = log.scrollHeight;
|
|
}
|
|
}
|
|
|
|
history.push({role: "assistant", content: assistantText});
|
|
}
|
|
|
|
form.addEventListener("submit", (event) => {
|
|
event.preventDefault();
|
|
const message = input.value.trim();
|
|
if (!message) return;
|
|
input.value = "";
|
|
sendMessage(message).catch((err) => {
|
|
appendLine("error", `unexpected error: ${err.message}`);
|
|
});
|
|
});
|
|
|
|
loadUser().catch((err) => {
|
|
appendLine("error", `failed to load session: ${err.message}`);
|
|
});
|
|
}
|