Spaces:
Running on Zero
Running on Zero
File size: 10,274 Bytes
ad64732 34825de aa05851 34825de aa05851 34825de aa05851 34825de aa05851 72a3c41 aa05851 72a3c41 aa05851 72a3c41 aa05851 72a3c41 aa05851 c27c4a3 34825de aa05851 34825de c27c4a3 aa05851 34825de aa05851 34825de aa05851 c27c4a3 aa05851 34825de c27c4a3 34825de aa05851 72a3c41 aa05851 34825de aa05851 34825de aa05851 c27c4a3 aa05851 34825de c27c4a3 34825de c27c4a3 aa05851 34825de aa05851 b2e251b aa05851 b2e251b aa05851 b2e251b aa05851 ad64732 aa05851 c27c4a3 34825de aa05851 34825de c27c4a3 aa05851 c27c4a3 aa05851 c27c4a3 aa05851 c27c4a3 aa05851 ad64732 aa05851 | 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 | const resampler = element.querySelector(".resampler");
const form = element.querySelector("#composer");
const prompt = element.querySelector("#prompt");
const reasoning = element.querySelector("#reasoning");
const generate = element.querySelector("#generate");
const stop = element.querySelector("#stop");
const status = element.querySelector("#status");
const thought = element.querySelector("#thought");
const thinkingLabel = element.querySelector("#thinking-label");
const reasoningOutput = element.querySelector("#reasoning-output");
const answerOutput = element.querySelector("#answer-output");
const copy = element.querySelector("#copy");
const remake = element.querySelector("#remake");
const resultActions = element.querySelector("#result-actions");
const error = element.querySelector("#error");
const example = element.querySelector("#example");
const history = element.querySelector("#prompt-history");
const historyTab = history.parentElement;
let requestId = null;
let activeSession = null;
let selectedSession = null;
const sentPrompt = element.querySelector("#sent-prompt");
function followReasoning() {
if (thought.open && thinkingLabel.classList.contains("shimmer")) {
reasoningOutput.scrollTop = reasoningOutput.scrollHeight;
}
}
thought.addEventListener("toggle", followReasoning);
function formatThinkingTime(milliseconds) {
const totalSeconds = Math.round(milliseconds / 1000);
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
const secondsLabel = seconds + (seconds === 1 ? " second" : " seconds");
if (!minutes) return totalSeconds ? secondsLabel : "less than a second";
return minutes + (minutes === 1 ? " minute" : " minutes") + " and " + secondsLabel;
}
function renderSession() {
sentPrompt.hidden = !selectedSession;
sentPrompt.textContent = selectedSession?.prompt ?? "";
const waitingForAnswer = selectedSession && selectedSession === activeSession && !selectedSession.answer?.trim();
const hasReasoning = Boolean(selectedSession?.reasoning?.trim());
const label = waitingForAnswer ? (hasReasoning ? "Thinking..." : "Loading...") : hasReasoning
? "Thought for " + formatThinkingTime(selectedSession.thinkingDuration)
: "";
if (thinkingLabel.textContent !== label) thinkingLabel.textContent = label;
thinkingLabel.classList.toggle("shimmer", Boolean(waitingForAnswer));
status.textContent = selectedSession?.status ?? "";
answerOutput.textContent = selectedSession?.answer ?? "";
const reasoningText = selectedSession?.reasoning ?? "";
const reasoningChanged = reasoningOutput.textContent !== reasoningText;
const reasoningScrollTop = reasoningOutput.scrollTop;
const atReasoningEnd = reasoningOutput.scrollHeight - reasoningOutput.clientHeight - reasoningScrollTop <= 2;
if (reasoningChanged) reasoningOutput.textContent = reasoningText;
reasoningOutput.hidden = !hasReasoning;
thought.hidden = !waitingForAnswer && !hasReasoning;
if (reasoningChanged && thought.open) {
if (atReasoningEnd) followReasoning();
else reasoningOutput.scrollTop = reasoningScrollTop;
}
error.textContent = selectedSession?.error ?? "";
error.hidden = !selectedSession?.error;
resultActions.hidden = !selectedSession?.answer || selectedSession === activeSession;
remake.disabled = Boolean(requestId);
syncControls();
}
function selectSession(session) {
selectedSession?.button.removeAttribute("aria-current");
selectedSession = session;
session?.button.setAttribute("aria-current", "true");
thought.open = false;
copy.title = "Copy";
copy.setAttribute("aria-label", "Copy");
renderSession();
}
function sizeHistoryTab() {
const width = Math.max(0, ...Array.from(history.querySelectorAll(".prompt-history-preview"), node => node.scrollWidth));
historyTab.style.setProperty("--history-text-size", width + "px");
}
document.fonts.ready.then(sizeHistoryTab);
function addSentPrompt(text, thinking) {
const item = document.createElement("li");
const number = history.children.length + 1;
const badge = document.createElement("span");
badge.className = "prompt-history-number";
badge.textContent = number;
const preview = document.createElement("span");
preview.className = "prompt-history-preview";
const characters = Array.from(text);
preview.textContent = characters.slice(0, 40).join("").replace(/\s+/g, " ");
preview.toggleAttribute("data-truncated", characters.length > 40);
const button = document.createElement("button");
button.type = "button";
button.className = "prompt-history-button";
button.append(badge, preview);
button.setAttribute("aria-label", "Prompt " + number + ": " + preview.textContent);
item.append(button);
item.dataset.pending = "true";
const session = {prompt: text, thinking, item, button};
button.addEventListener("click", () => selectSession(session));
history.hidden = false;
history.append(item);
sizeHistoryTab();
history.scrollTop = history.scrollHeight;
return session;
}
const historyHoverPadding = 64;
document.addEventListener("pointermove", event => {
if (event.pointerType !== "mouse" || history.hidden) return;
const {left, right, top, bottom} = historyTab.getBoundingClientRect();
const nearby = event.clientX >= left - historyHoverPadding
&& event.clientX <= right + historyHoverPadding
&& event.clientY >= top - historyHoverPadding
&& event.clientY <= bottom + historyHoverPadding;
historyTab.toggleAttribute("data-nearby", nearby);
});
document.addEventListener("pointerleave", () => historyTab.removeAttribute("data-nearby"));
historyTab.addEventListener("click", event => {
if (event.pointerType === "touch" || !matchMedia("(hover: hover)").matches) {
if (!historyTab.hasAttribute("data-expanded")) {
historyTab.setAttribute("data-expanded", "");
} else if (!event.target.closest("button")) {
historyTab.removeAttribute("data-expanded");
}
}
});
element.addEventListener("pointerdown", event => {
if (!historyTab.contains(event.target)) historyTab.removeAttribute("data-expanded");
});
function resizePrompt() {
const scrollTop = prompt.scrollTop;
prompt.style.overflowY = "hidden";
prompt.style.height = "0px";
prompt.style.height = prompt.scrollHeight + "px";
if (prompt.scrollHeight > prompt.clientHeight + 1) {
prompt.style.overflowY = "auto";
prompt.scrollTop = scrollTop;
}
}
function syncPrompt() {
resizePrompt();
syncControls();
}
function syncControls() {
generate.disabled = !prompt.value.trim() || Boolean(requestId);
prompt.readOnly = Boolean(requestId);
example.disabled = Boolean(requestId);
generate.hidden = Boolean(requestId);
stop.hidden = !requestId;
}
function stopThinkingTimer(session) {
if (session.thinkingDuration === null) {
session.thinkingDuration = performance.now() - (session.thinkingStarted ?? session.submittedAt);
}
}
function finish(message) {
stopThinkingTimer(activeSession);
activeSession.status = message;
delete activeSession.item.dataset.pending;
activeSession = null;
requestId = null;
renderSession();
}
function showError(message) {
activeSession.error = message;
finish("");
}
window.addEventListener("resampler:update", ({ detail }) => {
if (!requestId || detail.requestId !== requestId) return;
switch (detail.kind) {
case "update":
activeSession.reasoning = detail.reasoning;
activeSession.answer = detail.answer;
if (detail.reasoning?.trim()) activeSession.thinkingStarted ??= performance.now();
if (detail.answer?.trim()) stopThinkingTimer(activeSession);
break;
case "done":
finish(detail.limited ? "Generation limit reached." : "");
return;
case "error":
showError(detail.message);
return;
}
if (selectedSession === activeSession) renderSession();
});
window.addEventListener("resampler:failed", () => {
if (requestId) showError("Generation could not start. Check the ZeroGPU message and try again.");
});
function startGeneration(session, retry = false) {
requestId = crypto.randomUUID();
activeSession = session;
session.item.dataset.pending = "true";
session.status = "";
session.error = "";
session.reasoning = "";
session.answer = "";
session.submittedAt = performance.now();
session.thinkingStarted = null;
session.thinkingDuration = null;
form.dataset.request = JSON.stringify({
request_id: requestId,
prompt: session.prompt,
reasoning: session.thinking,
remake: retry,
});
selectSession(session);
trigger("submit_prompt");
}
form.addEventListener("submit", event => {
event.preventDefault();
if (generate.disabled || requestId) return;
const session = addSentPrompt(prompt.value.trim(), reasoning.checked);
prompt.value = "";
resizePrompt();
startGeneration(session);
const thinkingTop = thought.getBoundingClientRect().top - resampler.getBoundingClientRect().top;
if (thinkingTop > resampler.clientHeight * 0.4) {
resampler.scrollBy({ top: thinkingTop - resampler.clientHeight * 0.33 });
}
});
remake.addEventListener("click", () => {
if (!requestId && selectedSession) startGeneration(selectedSession, true);
});
stop.addEventListener("click", () => {
trigger("stop_prompt");
finish("Generation stopped.");
});
prompt.addEventListener("input", syncPrompt);
window.addEventListener("resize", resizePrompt);
prompt.addEventListener("keydown", event => {
if (event.key === "Enter" && (event.metaKey || event.ctrlKey) && !event.isComposing) {
event.preventDefault();
form.requestSubmit();
}
});
example.addEventListener("click", () => {
prompt.value = "Maya buys four notebooks for $3 each and pays with a $20 bill. How much change does she get?";
prompt.focus();
syncPrompt();
});
copy.addEventListener("click", async () => {
try {
await navigator.clipboard.writeText(answerOutput.textContent);
copy.title = "Copied";
copy.setAttribute("aria-label", "Copied");
} catch {
copy.title = "Copy unavailable";
copy.setAttribute("aria-label", "Copy unavailable");
}
});
const composerObserver = new ResizeObserver(([entry]) => {
resampler.style.setProperty("--composer-height", entry.target.offsetHeight + "px");
});
composerObserver.observe(form);
syncPrompt();
|