okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-027-web: the served web chat page for 0.2.75d9f47922

main
5.5 KiB90 linesraw
1// serve/web/history.js - what the chat history does to a list of messages. Pure functions: no page, no storage, no clock of
2// their own, so they can be tested alone (serve/test_web_history.js). app.js draws the controls and keeps the state.
3//
4// One design for five proposals (see docs/DETAILS.md, "The web page"):
5//   #2615 (uppet)         edit your question, correct an answer, regenerate, go back, undo
6//   #1787 (Scotty-Hudson)  saved chats in a list, kept in this browser (IndexedDB), renamed, deleted, searched
7//   #3823 (xvcezrqpbxtpzblrt) "Rewind to here" asks: edit and send again HERE, or BRANCH into a new chat
8//   #3550 / #4004           the header's Load / Unload; sending while an answer is being written (app.js)
9// A message list is an array of {role, text, time, images, files, reasoning, tools, meta, ...}; an attachment that was read
10// in this page has its contents (image url, file text), one that came back from the browser's store has its name only.
11"use strict";
12(function (root) {
13  const TITLE_MAX = 60;
14
15  const newChatId = (now, rnd) => `c${now.toString(36)}${Math.floor(rnd * 1e6).toString(36)}`;
16  function newChat(now = Date.now(), rnd = Math.random()) {
17    return {id: newChatId(now, rnd), title: "", time: now, messages: []};
18  }
19  // the name in the list: what the user called it, else the first line of their first question, else the caller's word for "new"
20  function chatTitle(c, untitled = "New chat") {
21    if (c.title) return c.title;
22    const first = (c.messages.find((m) => m.role === "user") || {}).text || "";
23    return first.split("\n")[0].trim().slice(0, TITLE_MAX) || untitled;
24  }
25
26  // pictures and files are kept as their names only: a data URL would fill the browser's storage
27  const cleanMessages = (list) => list.map((m) => ({...m, images: (m.images || []).map((i) => ({name: i.name})),
28                                                    files: (m.files || []).map((f) => ({name: f.name}))}));
29  const cleanChat = (c) => ({...c, messages: cleanMessages(c.messages)});
30
31  // "today" | "yesterday" | "week" | "month" | "older", by calendar days back from now
32  function groupKey(t, now = Date.now()) {
33    const days = Math.floor((now - t) / 86400000);
34    if (!days) return "today";
35    if (days === 1) return "yesterday";
36    if (days <= 7) return "week";
37    if (days <= 30) return "month";
38    return "older";
39  }
40  // the list for a search box: titles and message text, newest first
41  function filterChats(chats, query, untitled) {
42    const q = String(query || "").trim().toLowerCase();
43    return chats.filter((c) => !q || chatTitle(c, untitled).toLowerCase().includes(q) ||
44                               c.messages.some((m) => (m.text || "").toLowerCase().includes(q)))
45                .sort((a, b) => b.time - a.time);
46  }
47
48  // Can a user turn be sent again as it was? A picture or file that came back from the browser's store has only its name.
49  const lostAttachments = (m) => ((m.images || []).filter((x) => !x.url).length + (m.files || []).filter((x) => typeof x.text !== "string").length);
50  // what goes back into the message box when a user turn is edited: its text and the attachments that still have contents
51  function draftOf(m) {
52    return {text: m.text || "",
53            images: (m.images || []).filter((x) => x.url).map((x) => ({kind: "image", name: x.name, url: x.url})),
54            files: (m.files || []).filter((x) => typeof x.text === "string").map((x) => ({kind: "file", name: x.name, text: x.text})),
55            lost: lostAttachments(m)};
56  }
57
58  // "Rewind to here" on message i. A user turn goes back into the box and leaves the list; an answer stays and the list ends
59  // with it. {keep, draft, hidden}: the messages that stay, the draft for the box (null for an answer), how many are hidden.
60  function rewind(messages, i) {
61    const m = messages[i];
62    if (!m) return null;
63    if (m.role === "user") return {keep: messages.slice(0, i), draft: draftOf(m), hidden: messages.length - i};
64    return {keep: messages.slice(0, i + 1), draft: null, hidden: messages.length - i - 1};
65  }
66  // Regenerate the answer at i (or the last user turn): the list up to and including the user turn before it
67  function regenerate(messages, i) {
68    let u = i;
69    while (u >= 0 && messages[u] && messages[u].role !== "user") u--;
70    if (u < 0 || !messages[u]) return null;
71    return {keep: messages.slice(0, u + 1), hidden: messages.length - u - 1};
72  }
73  // Edit the answer at i: its text replaced, its thinking, tool calls, error and stats dropped, everything after it hidden
74  function editAnswer(messages, i, text, meta = "Edited") {
75    const m = messages[i];
76    if (!m || m.role !== "assistant") return null;
77    return {keep: [...messages.slice(0, i), {role: "assistant", text, time: m.time, meta}], hidden: messages.length - i - 1};
78  }
79  // A branch: a new chat that starts with a copy of the first `end` messages. The original is not touched. The title says
80  // where it came from and stays: the first question does not rename it (the first-message case of #3823).
81  function branch(chat, messages, end, title, now = Date.now(), rnd = Math.random()) {
82    const copy = JSON.parse(JSON.stringify(messages.slice(0, end)));
83    return {...newChat(now, rnd), title, parent: {id: chat.id, title: chatTitle(chat)}, messages: copy};
84  }
85
86  const api = {TITLE_MAX, newChat, chatTitle, cleanMessages, cleanChat, groupKey, filterChats, lostAttachments, draftOf, rewind,
87               regenerate, editAnswer, branch};
88  root.StrataHistory = api;
89  if (typeof module !== "undefined" && module.exports) module.exports = api;
90})(typeof globalThis !== "undefined" ? globalThis : this);