933 lines
33 KiB
HTML
933 lines
33 KiB
HTML
<!DOCTYPE html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="UTF-8" />
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
<title>Cet ci pi ti</title>
|
|
<style>
|
|
:root {
|
|
color-scheme: light dark;
|
|
--bg-primary: Canvas;
|
|
--bg-secondary: #ccc;
|
|
--bg-input: #f0f0f0;
|
|
--bg-user-message: Highlight;
|
|
--bg-code: Field;
|
|
--text-primary: CanvasText;
|
|
--text-user: HighlightText;
|
|
--border-color: #aaa;
|
|
}
|
|
|
|
@media (prefers-color-scheme: dark) {
|
|
:root {
|
|
--bg-secondary: #555;
|
|
--bg-input: #444;
|
|
}
|
|
}
|
|
|
|
*,
|
|
*::before,
|
|
*::after {
|
|
box-sizing: border-box;
|
|
font-family: inherit;
|
|
}
|
|
|
|
body {
|
|
margin: 0;
|
|
/* font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; */
|
|
font-family: "JetBrains Mono", Consolas, Menlo, monospace;
|
|
line-height: 1.6;
|
|
font-size: 14px;
|
|
/* color: var(--text-primary); */
|
|
}
|
|
|
|
a {
|
|
color: var(--text-user);
|
|
text-decoration: none;
|
|
}
|
|
|
|
.chat-container {
|
|
height: 100vh;
|
|
display: grid;
|
|
grid-template-columns: 1fr min-content;
|
|
grid-template-rows: 1fr min-content;
|
|
gap: 1rem;
|
|
padding: 1rem;
|
|
grid-template-areas:
|
|
"messages messages"
|
|
"prompt submit";
|
|
}
|
|
|
|
.messages {
|
|
grid-area: messages;
|
|
overflow-y: auto;
|
|
padding-right: 0.5rem;
|
|
}
|
|
|
|
.message {
|
|
padding: 0.8rem 1.2rem;
|
|
border-radius: 0.8rem;
|
|
max-width: 85%;
|
|
}
|
|
|
|
textarea,
|
|
button {
|
|
font-size: inherit;
|
|
font-family: inherit;
|
|
appearance: none;
|
|
}
|
|
|
|
.button {
|
|
text-transform: uppercase;
|
|
letter-spacing: 0.05em;
|
|
}
|
|
|
|
.message + .message {
|
|
margin-top: 1rem;
|
|
}
|
|
|
|
.user-message {
|
|
color: var(--text-user);
|
|
background: var(--bg-user-message);
|
|
margin-left: auto;
|
|
white-space: pre-wrap;
|
|
}
|
|
|
|
.system-message {
|
|
background: var(--bg-secondary);
|
|
margin-right: auto;
|
|
}
|
|
|
|
.system-message pre,
|
|
.system-message code:not(pre code) {
|
|
font-family: menlo, consolas, monospace;
|
|
background: var(--bg-code);
|
|
border-radius: 0.4rem;
|
|
}
|
|
.system-message pre {
|
|
position: relative;
|
|
padding: 0.5rem 2.5rem 0.5rem 0.5rem;
|
|
white-space: pre;
|
|
overflow-x: auto;
|
|
}
|
|
.copy-btn {
|
|
position: absolute;
|
|
top: 0.4rem;
|
|
right: 0.6rem;
|
|
background: var(--bg-secondary);
|
|
color: var(--text-primary);
|
|
border: none;
|
|
border-radius: 0.3rem;
|
|
padding: 0.2rem 0.6rem;
|
|
font-size: 0.9em;
|
|
cursor: pointer;
|
|
opacity: 0.6;
|
|
transition: opacity 0.2s;
|
|
z-index: 2;
|
|
}
|
|
.copy-btn:hover {
|
|
opacity: 1;
|
|
}
|
|
|
|
.system-message code {
|
|
padding: 2px 4px;
|
|
}
|
|
|
|
.prompt {
|
|
grid-area: prompt;
|
|
min-height: 40px;
|
|
padding: 0.8rem;
|
|
border: none;
|
|
border-radius: 0.4rem;
|
|
/* background: var(--bg-input); */
|
|
/* color: var(--text-primary); */
|
|
resize: vertical;
|
|
}
|
|
|
|
.submit {
|
|
grid-area: submit;
|
|
cursor: pointer;
|
|
padding: 0.8rem 2rem;
|
|
background: var(--bg-secondary);
|
|
/* color: var(--text-primary); */
|
|
border: none;
|
|
border-radius: 0.4rem;
|
|
transition: background-color 0.2s ease;
|
|
}
|
|
|
|
.submit:hover {
|
|
background: var(--bg-user-message);
|
|
}
|
|
|
|
/* Scrollbar styling */
|
|
.messages::-webkit-scrollbar {
|
|
width: 4px;
|
|
}
|
|
|
|
.messages::-webkit-scrollbar-track {
|
|
background: var(--bg-primary);
|
|
}
|
|
|
|
.messages::-webkit-scrollbar-thumb {
|
|
background: var(--border-color);
|
|
border-radius: 4px;
|
|
}
|
|
|
|
/* Focus styles */
|
|
.prompt:focus,
|
|
.submit:focus {
|
|
outline: none;
|
|
border-color: var(--bg-user-message);
|
|
}
|
|
|
|
.submit {
|
|
anchor-name: --submit;
|
|
}
|
|
|
|
@keyframes pulse {
|
|
20% {
|
|
opacity: 0.8;
|
|
}
|
|
}
|
|
|
|
.submit.busy {
|
|
animation: both pulse 1s;
|
|
}
|
|
|
|
#model-selector {
|
|
user-select: none;
|
|
position: absolute;
|
|
top: 1rem;
|
|
left: 1rem;
|
|
opacity: 0.3;
|
|
padding: 0.5rem;
|
|
}
|
|
#model-selector:is(:hover, [open]) {
|
|
opacity: 1;
|
|
}
|
|
|
|
/* History panel (mirrors model selector behavior) */
|
|
#history-panel {
|
|
position: absolute;
|
|
user-select: none;
|
|
top: 1rem;
|
|
right: 1rem;
|
|
opacity: 0.3;
|
|
padding: 0.5rem;
|
|
}
|
|
#history-panel:is(:hover, [open]) {
|
|
opacity: 1;
|
|
}
|
|
|
|
#history-panel summary {
|
|
font-weight: bold;
|
|
}
|
|
|
|
.history-item {
|
|
cursor: pointer;
|
|
padding: 0.25rem 0.2rem;
|
|
border-radius: 0.2rem;
|
|
display: flex;
|
|
gap: 0.5rem;
|
|
align-items: center;
|
|
}
|
|
|
|
.history-item:hover {
|
|
background: rgba(0, 0, 0, 0.05);
|
|
}
|
|
|
|
/* History list classes */
|
|
.history-list {
|
|
min-width: 220px;
|
|
max-width: 320px;
|
|
padding-top: 0.5rem;
|
|
}
|
|
|
|
.history-none {
|
|
opacity: 0.7;
|
|
}
|
|
|
|
.history-time {
|
|
font-weight: 700;
|
|
}
|
|
.history-time::after {
|
|
content: " - ";
|
|
}
|
|
|
|
.history-excerpt {
|
|
/* margin-left: 6px; */
|
|
/* display: inline-block; */
|
|
max-width: 220px;
|
|
overflow: hidden;
|
|
text-overflow: ellipsis;
|
|
white-space: nowrap;
|
|
vertical-align: middle;
|
|
}
|
|
|
|
#model-selector summary {
|
|
font-weight: bold;
|
|
}
|
|
|
|
.model-opt__label {
|
|
display: block;
|
|
}
|
|
|
|
details {
|
|
cursor: pointer;
|
|
}
|
|
|
|
blockquote {
|
|
padding: 1rem;
|
|
margin: 1rem 0;
|
|
background-color: rgba(0, 0, 0, 0.1);
|
|
border-left: 3px solid dodgerblue;
|
|
}
|
|
|
|
blockquote > p + p {
|
|
margin: 1em 0 0 0;
|
|
}
|
|
|
|
blockquote > p:only-child {
|
|
margin: 0;
|
|
}
|
|
|
|
ul {
|
|
padding-left: 1rem;
|
|
}
|
|
|
|
td {
|
|
vertical-align: top;
|
|
}
|
|
th {
|
|
vertical-align: top;
|
|
}
|
|
|
|
tr:nth-child(odd) {
|
|
background-color: rgba(0, 0, 0, 0.05);
|
|
}
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<div id="app">
|
|
<div class="chat-container">
|
|
<div id="messages" class="messages"></div>
|
|
<textarea rows="6" id="prompt" class="prompt" placeholder="Type your message..."></textarea>
|
|
<button id="submit" class="submit button">Send</button>
|
|
<details id="model-selector">
|
|
<summary>Model</summary>
|
|
</details>
|
|
</div>
|
|
</div>
|
|
<script type="module">
|
|
import * as smd from "https://cdn.jsdelivr.net/npm/streaming-markdown@latest/smd.min.js";
|
|
window.env ??= {};
|
|
|
|
const models = [
|
|
{ name: "gpt-4.1", chat: chatWithOpenAI },
|
|
{ name: "gpt-4.1-mini", chat: chatWithOpenAI },
|
|
{ name: "gemini-3-flash-preview", chat: chatWithGemini },
|
|
{ name: "claude-haiku-4-5-20251001", chat: chatWithClaude },
|
|
];
|
|
window.env.MODEL ||= "gemini-3-flash-preview";
|
|
|
|
const systemPrompt = `You are a helpful AI assistant.
|
|
Do not preach about implications,
|
|
do not praise excessively.
|
|
Keep a critical mindset,
|
|
do not assume blindly.
|
|
Answer in valid markdown.`;
|
|
|
|
const messages = [
|
|
{
|
|
role: "system",
|
|
content: systemPrompt,
|
|
},
|
|
];
|
|
|
|
const $messages = document.querySelector("#messages");
|
|
const $prompt = document.querySelector("#prompt");
|
|
const $submit = document.querySelector("#submit");
|
|
const $modelSelector = document.querySelector("#model-selector");
|
|
const $historyPanel = (function createHistoryPanel() {
|
|
const details = document.createElement("details");
|
|
details.id = "history-panel";
|
|
details.innerHTML = `<summary>History</summary>`;
|
|
return details;
|
|
})();
|
|
// insert history panel next to model selector
|
|
$modelSelector.parentNode.appendChild($historyPanel);
|
|
|
|
// grow the prompt textarea as needed
|
|
const minRows = +$prompt.rows;
|
|
const maxRows = 10;
|
|
$prompt.addEventListener(
|
|
"input",
|
|
debounce((e) => {
|
|
const lines = e.target.value.split("\n").length;
|
|
e.target.rows = Math.min(maxRows, Math.max(minRows, lines));
|
|
}, 100)
|
|
);
|
|
|
|
// populate model selector
|
|
$modelSelector.append(
|
|
...models.map((model) => {
|
|
const $label = document.createElement("label");
|
|
$label.className = "model-opt__label";
|
|
const $input = document.createElement("input");
|
|
$input.type = "radio";
|
|
$input.name = "model";
|
|
$input.value = model.name;
|
|
$label.append($input, model.name);
|
|
return $label;
|
|
})
|
|
);
|
|
$modelSelector.addEventListener("mouseenter", (e) => {
|
|
const open = $modelSelector.hasAttribute("open");
|
|
if (!open) {
|
|
$modelSelector.setAttribute("open", "");
|
|
}
|
|
});
|
|
|
|
document.querySelectorAll("[name=model]").forEach(($option) => {
|
|
if ($option.value === window.env.MODEL) {
|
|
$option.checked = true;
|
|
}
|
|
});
|
|
|
|
/** @type {AbortController} */
|
|
let abortController = null;
|
|
$submit.addEventListener("click", () => {
|
|
if (abortController) {
|
|
abortController.abort();
|
|
} else {
|
|
handleSubmit();
|
|
}
|
|
});
|
|
|
|
$prompt.addEventListener("keydown", (e) => {
|
|
if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
|
|
e.preventDefault();
|
|
if (!abortController) {
|
|
handleSubmit();
|
|
}
|
|
}
|
|
});
|
|
|
|
const injectedPrompt = window.env.PROMPT?.trim() ?? "";
|
|
if (injectedPrompt) {
|
|
$prompt.value = injectedPrompt + "\n\n";
|
|
}
|
|
$prompt.focus();
|
|
|
|
const STORAGE_KEY = "chat_conversations";
|
|
|
|
function todayKey(date = new Date()) {
|
|
return date.toISOString().slice(0, 10); // YYYY-MM-DD
|
|
}
|
|
|
|
function loadConversations() {
|
|
try {
|
|
const raw = localStorage.getItem(STORAGE_KEY);
|
|
if (!raw) return {};
|
|
return JSON.parse(raw);
|
|
} catch (e) {
|
|
console.error("Failed to load conversations", e);
|
|
return {};
|
|
}
|
|
}
|
|
|
|
function saveConversations(obj) {
|
|
try {
|
|
localStorage.setItem(STORAGE_KEY, JSON.stringify(obj));
|
|
} catch (e) {
|
|
console.error("Failed to save conversations", e);
|
|
}
|
|
}
|
|
|
|
function clearOldConversations() {
|
|
const all = loadConversations();
|
|
const today = todayKey();
|
|
Object.keys(all).forEach((k) => {
|
|
if (k !== today) delete all[k];
|
|
});
|
|
saveConversations(all);
|
|
}
|
|
|
|
function saveConversationNow(messages) {
|
|
// messages: array of {role, content}
|
|
const all = loadConversations();
|
|
const today = todayKey();
|
|
all[today] ||= [];
|
|
const ts = new Date();
|
|
const entry = { time: ts.toISOString(), messages };
|
|
all[today].unshift(entry);
|
|
// keep only last 5
|
|
if (all[today].length > 5) all[today] = all[today].slice(0, 5);
|
|
saveConversations(all);
|
|
renderHistoryList();
|
|
}
|
|
|
|
function formatTime(iso) {
|
|
const d = new Date(iso);
|
|
return d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
|
|
}
|
|
|
|
function renderHistoryList() {
|
|
// remove existing list
|
|
const today = todayKey();
|
|
const all = loadConversations();
|
|
const $list = document.createElement("div");
|
|
$list.className = "history-list";
|
|
|
|
const items = (all[today] || []).slice(0, 5);
|
|
if (items.length === 0) {
|
|
const $none = document.createElement("div");
|
|
$none.textContent = "No recent conversations today";
|
|
$none.className = "history-none";
|
|
$list.appendChild($none);
|
|
} else {
|
|
items.forEach((entry, idx) => {
|
|
const firstUser = entry.messages.find((m) => m.role === "user")?.content || "";
|
|
const preview = firstUser.trim().replace(/\n/g, " ").slice(0, 30);
|
|
|
|
const $line = document.createElement("div");
|
|
$line.className = "history-item";
|
|
$line.dataset.idx = idx;
|
|
|
|
const $timeSpan = document.createElement("span");
|
|
$timeSpan.className = "history-time";
|
|
$timeSpan.textContent = formatTime(entry.time);
|
|
|
|
const $previewSpan = document.createElement("span");
|
|
$previewSpan.className = "history-excerpt";
|
|
$previewSpan.innerText = preview;
|
|
|
|
$line.appendChild($timeSpan);
|
|
$line.appendChild($previewSpan);
|
|
$line.addEventListener("click", () => {
|
|
restoreConversation(entry.messages);
|
|
$historyPanel.removeAttribute("open");
|
|
});
|
|
$list.appendChild($line);
|
|
});
|
|
}
|
|
|
|
// clear previous children and append
|
|
$historyPanel.querySelectorAll(".history-list").forEach((n) => n.remove());
|
|
const wrapper = document.createElement("div");
|
|
wrapper.className = "history-list";
|
|
wrapper.appendChild($list);
|
|
$historyPanel.appendChild(wrapper);
|
|
}
|
|
|
|
function escapeHtml(str) {
|
|
return str.replace(/[&<>"']/g, function (m) {
|
|
return {
|
|
"&": "&",
|
|
"<": "<",
|
|
">": ">",
|
|
'"': """,
|
|
"'": "'",
|
|
}[m];
|
|
});
|
|
}
|
|
|
|
function restoreConversation(messagesArr) {
|
|
// Clear current messages UI and re-populate
|
|
messages.length = 0; // clear array
|
|
// push system prompt back if exists
|
|
messagesArr.forEach((m) => messages.push(m));
|
|
|
|
// re-render messages UI
|
|
$messages.innerHTML = "";
|
|
messages
|
|
.filter((m) => m.role !== "system")
|
|
.forEach((m) => {
|
|
const el = createMessageElement(m.content, m.role === "user");
|
|
if (!(m.role === "user")) {
|
|
el.innerHTML = renderMarkdown(m.content);
|
|
}
|
|
$messages.appendChild(el);
|
|
});
|
|
scrollToBottom($messages);
|
|
}
|
|
|
|
// initialize
|
|
clearOldConversations();
|
|
renderHistoryList();
|
|
|
|
async function handleSubmit() {
|
|
const prompt = $prompt.value.trim();
|
|
if (!prompt) return;
|
|
|
|
$modelSelector.removeAttribute("open");
|
|
|
|
// Add user message
|
|
const $userMessage = createMessageElement(prompt, true);
|
|
$messages.appendChild($userMessage);
|
|
messages.push({ role: "user", content: prompt });
|
|
|
|
// Prepare for system response
|
|
const $systemMessage = createMessageElement("", false);
|
|
$messages.appendChild($systemMessage);
|
|
const md = new StreamingMarkdown($systemMessage);
|
|
let fullResponse = "";
|
|
|
|
$prompt.value = "";
|
|
scrollToBottom($messages);
|
|
|
|
abortController = new AbortController();
|
|
|
|
const pickedModel = document.querySelector("[name=model]:checked")?.value;
|
|
|
|
const chat = models.find((m) => m.name === pickedModel)?.chat;
|
|
|
|
if (!chat) {
|
|
console.error(`Unknown model: ${window.env.MODEL}`);
|
|
return;
|
|
}
|
|
|
|
$submit.textContent = "Cancel";
|
|
$submit.classList.add("busy");
|
|
try {
|
|
await chat({
|
|
model: pickedModel,
|
|
onContent: (content) => {
|
|
fullResponse += content;
|
|
md.append(content);
|
|
scrollToBottom($messages);
|
|
},
|
|
onError(e) {
|
|
md.append("ERROR:```\n" + e.message + "\n```");
|
|
},
|
|
messages,
|
|
signal: abortController.signal,
|
|
});
|
|
if (fullResponse.trim() !== "") {
|
|
messages.push({ role: "assistant", content: fullResponse });
|
|
}
|
|
} catch (err) {
|
|
if (err.name === "AbortError") {
|
|
md.append("\n\n[Cancelled]");
|
|
} else {
|
|
md.append("\n\n[Error: " + err.message + "]");
|
|
}
|
|
} finally {
|
|
md.finish();
|
|
// Save conversation after assistant finishes responding
|
|
try {
|
|
// clone messages to avoid mutation issues
|
|
const clone = messages.map((m) => ({ role: m.role, content: m.content }));
|
|
saveConversationNow(clone);
|
|
} catch (e) {
|
|
console.error("Failed to save conversation", e);
|
|
}
|
|
$submit.textContent = "Send";
|
|
$submit.classList.remove("busy");
|
|
abortController = null;
|
|
}
|
|
}
|
|
|
|
function createMessageElement(content, isUser) {
|
|
const $el = document.createElement("div");
|
|
$el.className = `message ${isUser ? "user-message" : "system-message"}`;
|
|
$el.innerText = content;
|
|
// if (isUser) {
|
|
// } else {
|
|
// // For system messages we create a pre element so streaming markdown can render into it
|
|
// const $pre = document.createElement("pre");
|
|
// $pre.textContent = content;
|
|
// $el.appendChild($pre);
|
|
// }
|
|
return $el;
|
|
}
|
|
|
|
// Auto scroll functionality
|
|
let userHasScrolledUp = false;
|
|
|
|
// Function to check if user is at the bottom
|
|
function isAtBottom($el) {
|
|
const threshold = 50; // Allow some tolerance (50px from bottom)
|
|
return $el.scrollHeight - $el.clientHeight - $el.scrollTop <= threshold;
|
|
}
|
|
|
|
const scrollToBottom = throttle(($el) => {
|
|
if (!userHasScrolledUp) {
|
|
$el.scrollTop = $el.scrollHeight;
|
|
}
|
|
}, 500);
|
|
|
|
$messages.addEventListener("scroll", () => {
|
|
userHasScrolledUp = !isAtBottom($messages);
|
|
});
|
|
|
|
/**
|
|
* @typedef {{
|
|
* onContent: (content: string) => Promise<void>,
|
|
* messages: Array<{ role: string, content: string }>,
|
|
* extraHeaders: Record<string, string>,
|
|
* signal: AbortSignal,
|
|
* apiKey: string,
|
|
* model: string,
|
|
* [key: string]: any
|
|
* }} ChatArgs
|
|
*/
|
|
|
|
/** @param {ChatArgs} args - The arguments for the chatWithClaude function. */
|
|
async function chatWithOpenAI({
|
|
baseUrl = "https://api.openai.com/v1",
|
|
onContent,
|
|
onError,
|
|
messages,
|
|
signal,
|
|
apiKey = window.env.OPENAI_API_KEY,
|
|
model,
|
|
extraHeaders = {},
|
|
...rest
|
|
}) {
|
|
const response = await fetch(`${baseUrl}/chat/completions`, {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
Authorization: `Bearer ${apiKey}`,
|
|
...extraHeaders,
|
|
},
|
|
body: JSON.stringify({
|
|
model,
|
|
messages,
|
|
stream: true,
|
|
...rest,
|
|
}),
|
|
signal,
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const text = await response.text();
|
|
await onError?.(new Error(`HTTP ${response.status}:\n${text.trim()}`));
|
|
return;
|
|
}
|
|
|
|
const reader = response.body.getReader();
|
|
const decoder = new TextDecoder();
|
|
|
|
while (true) {
|
|
const { done, value } = await reader.read();
|
|
if (done) break;
|
|
|
|
const text = decoder.decode(value, { stream: true });
|
|
const lines = text
|
|
.split("\n\n")
|
|
.filter((line) => !!line.trim())
|
|
.map((line) => line.trim().replace("data: ", ""));
|
|
|
|
for (const line of lines) {
|
|
if (line === "[DONE]") return;
|
|
try {
|
|
const parsed = JSON.parse(line);
|
|
const content = parsed.choices[0].delta.content;
|
|
if (content) {
|
|
await onContent(content);
|
|
}
|
|
} catch (e) {}
|
|
}
|
|
}
|
|
}
|
|
|
|
/*** @param {ChatArgs} args - The arguments for the chatWithClaude function. */
|
|
async function chatWithClaude(args) {
|
|
return chatWithOpenAI({
|
|
...args,
|
|
baseUrl: "https://api.anthropic.com/v1",
|
|
extraHeaders: {
|
|
"x-api-key": args.apiKey,
|
|
"anthropic-version": "2023-06-01",
|
|
"anthropic-dangerous-direct-browser-access": "true",
|
|
},
|
|
apiKey: window.env.ANTHROPIC_API_KEY,
|
|
});
|
|
}
|
|
|
|
/*** @param {ChatArgs} args - The arguments for the chatWithGemini function. */
|
|
/**
|
|
* Native Gemini Implementation
|
|
* @param {ChatArgs} args
|
|
*/
|
|
async function chatWithGemini({ onContent, onError, messages, signal, apiKey = window.env.GEMINI_API_KEY, model = "gemini-3-flash-preview", ...rest }) {
|
|
// Convert OpenAI message format to Gemini format
|
|
const contents = messages.map((msg) => ({
|
|
role: msg.role === "assistant" ? "model" : "user",
|
|
parts: [{ text: msg.content }],
|
|
}));
|
|
|
|
try {
|
|
const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${model}:streamGenerateContent?key=${apiKey}`, {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
},
|
|
body: JSON.stringify({
|
|
contents,
|
|
generationConfig: {
|
|
thinkingConfig: {
|
|
thinkingLevel: "low",
|
|
},
|
|
...rest,
|
|
},
|
|
}),
|
|
signal,
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const text = await response.text();
|
|
await onError?.(new Error(`Gemini API Error ${response.status}: ${text}`));
|
|
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 });
|
|
|
|
// Gemini's native stream returns a JSON array of objects.
|
|
// In a streaming context, it looks like: [ { ... }, { ... } ]
|
|
// We need to strip the brackets and commas or parse the chunks.
|
|
|
|
// Note: This is a simplified parser for the typical Gemini stream format
|
|
// which arrives as an array of JSON objects.
|
|
let startIdx;
|
|
while ((startIdx = buffer.indexOf("{")) !== -1) {
|
|
let endIdx = -1;
|
|
let depth = 0;
|
|
|
|
// Find the matching closing bracket
|
|
for (let i = startIdx; i < buffer.length; i++) {
|
|
if (buffer[i] === "{") depth++;
|
|
else if (buffer[i] === "}") depth--;
|
|
|
|
if (depth === 0) {
|
|
endIdx = i;
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (endIdx === -1) break; // Incomplete JSON object
|
|
|
|
const jsonStr = buffer.substring(startIdx, endIdx + 1);
|
|
buffer = buffer.substring(endIdx + 1);
|
|
|
|
try {
|
|
const parsed = JSON.parse(jsonStr);
|
|
const content = parsed.candidates?.[0]?.content?.parts?.[0]?.text;
|
|
if (content) {
|
|
await onContent(content);
|
|
}
|
|
} catch (e) {
|
|
console.error("Error parsing Gemini chunk", e);
|
|
}
|
|
}
|
|
}
|
|
} catch (err) {
|
|
if (err.name !== "AbortError") {
|
|
await onError?.(err);
|
|
}
|
|
}
|
|
}
|
|
|
|
function renderMarkdown(markdown) {
|
|
const $container = document.createElement("div");
|
|
const renderer = smd.default_renderer($container);
|
|
const parser = smd.parser(renderer);
|
|
smd.parser_write(parser, markdown);
|
|
smd.parser_end(parser);
|
|
return $container.innerHTML;
|
|
}
|
|
|
|
class StreamingMarkdown {
|
|
constructor($el) {
|
|
this.$el = $el;
|
|
this.renderer = smd.default_renderer($el);
|
|
this.parser = smd.parser(this.renderer);
|
|
}
|
|
|
|
append(markdown) {
|
|
smd.parser_write(this.parser, markdown);
|
|
// Add copy buttons after rendering new markdown
|
|
addCopyButtonsToCodeBlocks(this.$el);
|
|
}
|
|
|
|
finish() {
|
|
smd.parser_end(this.parser);
|
|
addCopyButtonsToCodeBlocks(this.$el);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Creates a debounced function that delays execution
|
|
* @param {Function} func - Function to debounce
|
|
* @param {number} delay - Delay in milliseconds
|
|
* @returns {Function} Debounced function
|
|
*/
|
|
function debounce(func, delay) {
|
|
let timeoutId;
|
|
return function debounced(...args) {
|
|
clearTimeout(timeoutId);
|
|
timeoutId = setTimeout(() => func.apply(this, args), delay);
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Creates a throttled function that limits execution frequency
|
|
* @param {Function} func - Function to throttle
|
|
* @param {number} limit - Minimum time between calls in milliseconds
|
|
* @returns {Function} Throttled function
|
|
*/
|
|
function throttle(func, limit) {
|
|
let inThrottle;
|
|
return function throttled(...args) {
|
|
if (!inThrottle) {
|
|
func.apply(this, args);
|
|
inThrottle = true;
|
|
setTimeout(() => (inThrottle = false), limit);
|
|
}
|
|
};
|
|
}
|
|
|
|
// Add copy-to-clipboard buttons to code blocks in system messages
|
|
function addCopyButtonsToCodeBlocks($container) {
|
|
// Only add to <pre><code>...</code></pre> blocks
|
|
$container.querySelectorAll("pre").forEach(($pre) => {
|
|
// Avoid duplicate buttons
|
|
if ($pre.querySelector(".copy-btn")) return;
|
|
const $code = $pre.querySelector("code");
|
|
if (!$code) return;
|
|
const $btn = document.createElement("button");
|
|
$btn.className = "copy-btn";
|
|
$btn.type = "button";
|
|
$btn.textContent = "Copy";
|
|
$btn.addEventListener("click", (e) => {
|
|
try {
|
|
const $textArea = document.createElement("textarea");
|
|
$textArea.value = $code.innerText;
|
|
document.body.appendChild($textArea);
|
|
$textArea.select();
|
|
document.execCommand("copy");
|
|
document.body.removeChild($textArea);
|
|
|
|
$btn.textContent = "Copied!";
|
|
setTimeout(() => ($btn.textContent = "Copy"), 1200);
|
|
} catch {
|
|
$btn.textContent = "Failed";
|
|
setTimeout(() => ($btn.textContent = "Copy"), 1200);
|
|
}
|
|
});
|
|
$pre.appendChild($btn);
|
|
});
|
|
}
|
|
</script>
|
|
</body>
|
|
</html>
|