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
21.5 KiB450 linesraw
1// serve/web/chats-ui.js - the chat history on the page: the saved-chats list, and edit / regenerate / go back / branch / undo.
2// One design for the proposals in PRs #1787 (list), #2615 (edit, regenerate, undo) and issue #3823 (rewind asks: here or a branch);
3// the pure part is serve/web/history.js, the browser store is serve/web/chatstore.js.
4//
5// Both are opt-in (Chat settings > Chats) and off by default: off, the page keeps the one chat it always had, with "New chat"
6// clearing it (and an Undo). Nothing here goes to the server.
7//
8// This file is loaded before app.js and uses its globals when its functions run: $, esc, icon, node, toast, store, settings,
9// messages, attachments, busy, pending, setBusy, renderChat, renderAttachments, autosize, generateReply, releasePending.
10// app.js calls initChats() once, from start().
11"use strict";
12
13const H = StrataHistory;
14const untitled = () => tr("chat.untitled", "New chat");
15const node = (tag, cls, text) => {
16  const n = document.createElement(tag);
17  if (cls) n.className = cls;
18  if (text != null) n.textContent = text;
19  return n;
20};
21
22// ------------------------------------------------------------------ state
23let listOn = false;                  // the saved-chats list is on
24let chats = [], chat = null, chatId = "";
25let sidebarQuery = "", sidebarOpen = true;
26let undoState = null;                // one change, in memory until a new question, another chat or a reload
27let panel = null;                    // the open "Rewind to here" panel or answer editor: {kind, index, el}
28const chatStore = StrataChatStore.createChatStore({
29  onProblem(kind) {
30    toast("warn", tr("store.title", "Chat list not saved"), kind === "memory"
31      ? tr("store.memory", "This browser will not keep the chat list. It stays in memory until you close the page.")
32      : kind === "quota" ? tr("store.quota", "This browser cannot keep more. The chats on the screen are still there.")
33      : tr("store.failed", "The chat list could not be saved. The chats on the screen are still there."), 6000);
34  },
35});
36
37// the open chat's messages are the page's `messages`; with the list on they are also the chat's, the same array
38function setMessages(next) {
39  messages = next;
40  if (chat) chat.messages = next;
41}
42function saveChat() {
43  if (!listOn) { store.set("chat", H.cleanMessages(messages)); return; }   // off: one chat, as before
44  chat.time = Date.now();
45  chatStore.put(H.cleanChat(chat));
46  renderSidebar();
47}
48function stillWriting() { toast("warn", tr("busy.stillWriting", "Still writing"), tr("busy.stopFirst", "Stop the answer first.")); }
49
50// ------------------------------------------------------------------ the saved-chats list (#1787)
51// Turning the list on: the chat on the screen becomes the first record. Only when the switch is flipped in this visit: on a page
52// load the list is the list, so a fresh chat stays empty and the single chat of before ("strata.chat") is read once, when the
53// store is empty.
54async function openChats(fromScreen) {
55  await chatStore.start();
56  chats = await chatStore.all();
57  if (!chats.length) {
58    const old = fromScreen ? messages : store.get("chat", []);
59    if (old.length) {
60      const c = {...H.newChat(), messages: old, time: old[old.length - 1].time || Date.now()};
61      chats = [c];
62      chatStore.put(H.cleanChat(c));                    // the migrated chat is a record like the others
63    }
64  }
65  chat = chats.find((c) => c.id === store.get("chatId", "")) || chats[0] || H.newChat();
66  if (!chats.includes(chat)) chats.push(chat);
67  chatId = chat.id;
68  setMessages(chat.messages);
69}
70async function setChatList(on, fromScreen) {
71  listOn = on;
72  $("sidebar").hidden = !on;
73  $("new-btn").hidden = on;                              // the list has its own New chat
74  if (!on) {                                             // off writes the single chat, so a reload shows the chat you were in
75    if (chat) messages = chat.messages;
76    chat = null;
77    store.set("chat", H.cleanMessages(messages));
78    renderChat();
79    return;
80  }
81  await openChats(fromScreen);
82  renderChat();
83}
84
85function groupName(key) {
86  return {today: tr("group.today", "Today"), yesterday: tr("group.yesterday", "Yesterday"), week: tr("group.week", "Previous 7 days"),
87          month: tr("group.month", "Previous 30 days"), older: tr("group.older", "Older")}[key];
88}
89function chatItem(c) {
90  const t = H.chatTitle(c, untitled());
91  const row = node("div", `chat-item${c.id === chatId ? " on" : ""}`);
92  row.dataset.id = c.id;
93  row.innerHTML = `<button class="chat-item__title" data-open-chat title="${esc(t)}">${esc(t)}</button>` +
94    `<span class="chat-item__actions">` +
95    `<button class="st-btn st-btn--icon" data-rename aria-label="${esc(tr("sidebar.rename", "Rename this chat"))}" title="${esc(tr("sidebar.renameShort", "Rename"))}">${icon("edit")}</button>` +
96    `<button class="st-btn st-btn--icon" data-delete aria-label="${esc(tr("sidebar.delete", "Delete this chat"))}" title="${esc(tr("sidebar.deleteShort", "Delete"))}">${icon("trash")}</button>` +
97    `</span>`;
98  return row;
99}
100function renderSidebar() {
101  if (!listOn) return;
102  // the search reads every chat's message text, so the whole store is in memory after the first load
103  const list = H.filterChats(chats, sidebarQuery, untitled());
104  const box = $("sidebar-list");
105  box.innerHTML = "";
106  if (!list.length) {
107    box.appendChild(node("p", "muted small sidebar-empty", sidebarQuery.trim() ? tr("sidebar.noMatch", "No chat matches") : tr("sidebar.none", "No chats yet")));
108  } else {
109    let group = "";
110    for (const c of list) {
111      const g = H.groupKey(c.time);
112      if (g !== group) { group = g; box.appendChild(node("p", "sidebar-group", groupName(g))); }
113      box.appendChild(chatItem(c));
114    }
115  }
116  $("sidebar-foot").textContent = tr("sidebar.foot", {one: "{n} chat · kept in this browser", other: "{n} chats · kept in this browser"}, {n: chats.length});
117}
118
119function showChat(c) {
120  clearUndo();
121  chat = c; chatId = c.id; messages = c.messages;
122  store.set("chatId", chatId);
123  chatStore.put(H.cleanChat(chat));       // renderChat renders the list, so the write here does not render it again
124  renderChat();
125}
126function openChat(id) {
127  if (busy) { stillWriting(); return; }
128  const c = chats.find((x) => x.id === id);
129  if (!c || c === chat) return;
130  releasePending();
131  closePanel();
132  showChat(c);
133}
134function startChat() {
135  if (busy) { stillWriting(); return; }
136  if (!messages.length && !chat.parent) { $("input").focus(); return; }          // already a fresh chat
137  releasePending();
138  closePanel();
139  const prev = chatId, c = H.newChat();
140  chats.push(c);
141  showChat(c);
142  $("input").focus();
143  toast("info", tr("chat.newToast", "New chat"), tr("chat.newToastText", "The one you were in is in the list on the left."), 6000,
144        {label: tr("undo", "Undo"), run: () => openChat(prev)});
145}
146function deleteChat(c) {
147  if (busy && c.id === chatId) { stillWriting(); return; }
148  const i = chats.indexOf(c), wasOpen = c.id === chatId;
149  if (i < 0) return;                                // the list only ever passes a chat it holds
150  chats.splice(i, 1);
151  chatStore.remove(c.id);                           // the record; the Undo puts it back
152  if (wasOpen) {
153    releasePending();
154    closePanel();
155    const next = chats[0] || H.newChat();
156    if (!chats.includes(next)) chats.push(next);
157    showChat(next);
158  } else renderSidebar();
159  toast("info", tr("chat.deleted", "Chat deleted"), H.chatTitle(c, untitled()), 6000, {label: tr("undo", "Undo"), run: () => {
160    if (chats.includes(c)) return;                  // already put back
161    chats.splice(Math.min(i, chats.length), 0, c);  // the display is sorted by time, so only the index matters
162    if (wasOpen) showChat(c); else { chatStore.put(H.cleanChat(c)); renderSidebar(); }
163  }});
164}
165// rename: the row turns into a field; Enter or a click outside keeps the name, Escape gives it up
166function renameChat(row, c) {
167  const title = row.querySelector(".chat-item__title");
168  const input = node("input", "st-input chat-item__input");
169  input.value = H.chatTitle(c, untitled());
170  input.setAttribute("aria-label", tr("sidebar.nameFor", "Name for this chat"));
171  title.replaceWith(input);
172  input.focus(); input.select();
173  let done = false;
174  const finish = (keep) => {
175    if (done) return;
176    done = true;
177    if (keep) { c.title = input.value.trim(); chatStore.put(H.cleanChat(c)); }
178    renderSidebar();
179  };
180  input.addEventListener("keydown", (e) => {
181    if (e.key === "Enter") { e.preventDefault(); finish(true); }
182    else if (e.key === "Escape") { e.preventDefault(); finish(false); }
183  });
184  input.addEventListener("blur", () => finish(true));
185}
186function setSidebar(open, save) {
187  sidebarOpen = open;
188  $("sidebar").dataset.open = String(open);
189  const t = open ? tr("sidebar.collapse", "Collapse the chat list") : tr("sidebar.expand", "Open the chat list");
190  $("sidebar-toggle").title = t; $("sidebar-toggle").setAttribute("aria-label", t);
191  $("sidebar-toggle").setAttribute("aria-expanded", String(open));
192  if (save) store.set("sidebar", open);
193}
194
195// a chat that was branched from another says so, and links back while the original is still in the list
196function renderParent() {
197  const bar = $("chat-parent");
198  const p = listOn && chat ? chat.parent : null;
199  bar.hidden = !p;
200  if (!p) return;
201  const alive = chats.some((c) => c.id === p.id);
202  bar.innerHTML = "";
203  bar.appendChild(node("span", "muted", tr("branch.from", "Branched from “{title}”", {title: p.title})));
204  if (alive) {
205    const b = node("button", "st-btn st-btn--secondary", tr("branch.open", "Open the original"));
206    b.type = "button";
207    b.onclick = () => openChat(p.id);
208    bar.appendChild(b);
209  }
210}
211
212// ------------------------------------------------------------------ edit, regenerate, go back (#2615, #3823)
213// Every change keeps the messages it replaced for one Undo: a new question, another chat or a reload ends it. The controls
214// are off while an answer is written (stop it first), while something is open, and while a message waits to be sent.
215const historyLocked = () => !!busy || !!panel || !!pending;
216function clearUndo() { undoState = null; renderUndoBar(); }
217function renderUndoBar() {
218  let el = $("history-undo");
219  if (!settings.chatEdit || !undoState) { if (el) el.remove(); return; }
220  if (!el) {
221    el = node("div", "history-undo");
222    el.id = "history-undo";
223    el.setAttribute("role", "status");
224    el.innerHTML = "<span></span><button type=\"button\" class=\"st-btn st-btn--secondary\"></button>";
225    el.querySelector("button").onclick = undoHistory;
226    $("composer").before(el);
227  }
228  el.querySelector("span").textContent = undoState.text;
229  el.querySelector("button").textContent = tr("undo", "Undo");
230  el.querySelector("button").disabled = historyLocked();
231}
232// replace the messages with `next`; text says what happened, for the Undo bar
233function commit(next, text) {
234  undoState = {messages, text, inserted: undefined, draftBefore: null};
235  setMessages(next);
236  saveChat();
237  renderChat();
238  return undoState;
239}
240function undoHistory() {
241  if (!settings.chatEdit || !undoState || historyLocked()) return false;
242  const u = undoState;
243  setMessages(u.messages);
244  if (u.inserted !== undefined && $("input").value === u.inserted && u.draftBefore) {   // the box still holds what the rewind put there
245    $("input").value = u.draftBefore.text;
246    attachments = u.draftBefore.attachments;
247    renderAttachments(); autosize();
248  }
249  undoState = null;
250  saveChat();
251  renderChat();
252  $("input").focus();
253  return true;
254}
255const hiddenText = (n) => tr("hist.hidden", {one: "{n} message hidden", other: "{n} messages hidden"}, {n});
256
257function msgActions(m, i) {
258  if (!settings.chatEdit) return null;
259  if (busy && busy.msg === m) return null;              // the answer being written has no buttons until it is done
260  const row = node("div", "history-actions");
261  const lock = historyLocked();
262  const add = (label, title, run) => {
263    const b = node("button", "st-btn st-btn--secondary", label);
264    b.type = "button"; b.title = title; b.disabled = lock; b.onclick = run;
265    row.appendChild(b);
266  };
267  const last = i === messages.length - 1;
268  if (m.role === "assistant" || last) {
269    add(tr("hist.regenerate", "Regenerate"), tr("hist.regenerateTitle", "Ask for a new answer to this question. Tools may run again."), () => regenerateAt(i));
270  }
271  if (m.role === "assistant") add(tr("hist.editAnswer", "Edit answer"), tr("hist.editAnswerTitle", "Correct the answer's text. No request is sent."), () => editAnswerAt(i));
272  add(tr("hist.rewind", "Rewind to here"), tr("hist.rewindTitle", "Go back to this point in the chat"), () => openRewind(i));
273  return row;
274}
275// true when a history change may start now (and says why not when it may not)
276function historyReady() {
277  if (!settings.chatEdit) return false;
278  if (busy) { stillWriting(); return false; }
279  if (panel) { toast("warn", tr("hist.finishFirst", "Finish what is open first"), tr("hist.finishFirstText", "Save it or press Cancel.")); return false; }
280  if (pending) { toast("warn", tr("hist.pendingFirst", "A message is waiting"), tr("hist.pendingFirstText", "Send it or take it back first.")); return false; }
281  return true;
282}
283// the action rows under the messages follow the switch, without replacing any message (an answer may be streaming into one)
284function syncActions() {
285  for (const el of $("chat").querySelectorAll(".st-msg")) {
286    const i = +el.dataset.i;
287    const old = el.querySelector(".history-actions");
288    if (old) old.remove();
289    const row = messages[i] ? msgActions(messages[i], i) : null;
290    if (row) el.appendChild(row);
291  }
292}
293function closePanel() {
294  if (!panel) return;
295  const {el} = panel;
296  const open = el.querySelector(".history-panel, .history-editor");
297  if (open) open.remove();
298  delete el.dataset.editing;
299  panel = null;
300  setBusy(!!busy);
301}
302function regenerateAt(i) {
303  if (!historyReady()) return false;
304  const plan = H.regenerate(messages, i);
305  if (!plan) return false;
306  if (H.lostAttachments(messages[plan.keep.length - 1])) {
307    toast("warn", tr("hist.lostTitle", "Attachments need to be added again"), tr("hist.lostText", "This browser kept their names, not their contents. Start a new chat and attach them again."), 7000);
308    return false;
309  }
310  commit(plan.keep, tr("hist.replaced", "The answer was replaced"));
311  return generateReply();
312}
313
314// edit an answer: its text, in place. The old thinking and tool calls go, and so do the messages after it.
315function editAnswerAt(i) {
316  if (!historyReady() || !messages[i]) return false;
317  const m = messages[i], el = $("chat").querySelector(`[data-i="${i}"]`);
318  const later = messages.length - i - 1;
319  const box = node("div", "history-editor");
320  box.innerHTML = "<label></label><textarea class=\"st-input\" rows=\"6\"></textarea><p class=\"muted small\"></p>" +
321    "<div class=\"history-editor__actions\"><button type=\"button\" class=\"st-btn st-btn--primary\" data-edit-save></button>" +
322    "<button type=\"button\" class=\"st-btn st-btn--secondary\" data-edit-cancel></button></div>";
323  const label = tr("hist.editLabel", "Edit the answer");
324  box.querySelector("label").textContent = label;
325  const input = box.querySelector("textarea");
326  input.setAttribute("aria-label", label);
327  input.value = m.text || "";
328  box.querySelector("p").textContent = (later ? tr("hist.editRemoves", {one: "Saving hides the {n} message after it. ", other: "Saving hides the {n} messages after it. "}, {n: later}) : "") +
329    tr("hist.editNote", "The answer's old thinking and tool calls are removed. No request is sent.");
330  const save = box.querySelector("[data-edit-save]");
331  save.textContent = tr("hist.save", "Save");
332  box.querySelector("[data-edit-cancel]").textContent = tr("cancel", "Cancel");
333  save.onclick = () => saveAnswerEdit(i, input.value);
334  box.querySelector("[data-edit-cancel]").onclick = closePanel;
335  input.onkeydown = (e) => {
336    if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); closePanel(); }
337    if (e.key === "Enter" && (e.ctrlKey || e.metaKey) && !e.isComposing) { e.preventDefault(); save.click(); }
338  };
339  el.dataset.editing = "true";
340  el.appendChild(box);
341  panel = {kind: "edit", index: i, el};
342  setBusy(!!busy);
343  input.focus();
344  input.scrollIntoView({block: "nearest"});
345  return true;
346}
347function saveAnswerEdit(i, text) {
348  if (busy || !panel || panel.kind !== "edit" || panel.index !== i) return false;
349  if (typeof text !== "string" || !text.trim()) { toast("warn", tr("hist.empty", "The answer is empty"), tr("hist.emptyText", "Write something before saving.")); return false; }
350  const plan = H.editAnswer(messages, i, text, tr("hist.edited", "Edited"));
351  if (!plan) return false;
352  closePanel();
353  commit(plan.keep, plan.hidden ? tr("hist.editedHidden", {one: "Answer edited, {n} message hidden", other: "Answer edited, {n} messages hidden"}, {n: plan.hidden})
354                                : tr("hist.editedOnly", "Answer edited"));
355  return true;
356}
357
358// "Rewind to here" asks what to do (#3823): go back HERE (this chat, with an Undo) or BRANCH (a new chat, this one stays)
359function openRewind(i) {
360  if (!historyReady() || !messages[i]) return false;
361  const m = messages[i], el = $("chat").querySelector(`[data-i="${i}"]`);
362  const user = m.role === "user";
363  const box = node("div", "history-panel");
364  box.setAttribute("role", "group");
365  box.setAttribute("aria-label", tr("rewind.title", "Rewind to here"));
366  const choice = (label, text, run, primary) => {
367    const row = node("div", "history-choice");
368    const b = node("button", `st-btn ${primary ? "st-btn--primary" : "st-btn--secondary"}`, label);
369    b.type = "button"; b.onclick = run;
370    row.appendChild(b);
371    row.appendChild(node("span", "muted small", text));
372    box.appendChild(row);
373  };
374  choice(user ? tr("rewind.hereUser", "Edit and send again here") : tr("rewind.hereAnswer", "Continue from here"),
375         user ? tr("rewind.hereUserText", "Hides this message and the ones after it, and puts your message in the box below. Undo brings them back.")
376              : tr("rewind.hereAnswerText", "Hides the messages after this answer. Undo brings them back."),
377         () => rewindHere(i), true);
378  if (listOn) {
379    choice(tr("rewind.branch", "Branch from here"),
380           user ? tr("rewind.branchUserText", "Starts a new chat with the messages before this one, and puts your message in its box. This chat stays as it is.")
381                : tr("rewind.branchAnswerText", "Starts a new chat with the messages up to this answer. This chat stays as it is."),
382           () => branchHere(i), false);
383  } else {
384    box.appendChild(node("p", "muted small", tr("rewind.noList", "To start a new chat from here instead, turn on Saved chats in Chat settings.")));
385  }
386  const cancel = node("button", "st-btn st-btn--secondary", tr("cancel", "Cancel"));
387  cancel.type = "button"; cancel.onclick = closePanel;
388  box.appendChild(cancel);
389  box.onkeydown = (e) => { if (e.key === "Escape") { e.preventDefault(); closePanel(); } };
390  el.appendChild(box);
391  panel = {kind: "rewind", index: i, el};
392  setBusy(!!busy);
393  box.querySelector("button").focus();
394  box.scrollIntoView({block: "nearest"});
395  return true;
396}
397function fillBox(draft) {
398  $("input").value = draft.text;
399  attachments = [...draft.images, ...draft.files];
400  renderAttachments();
401  autosize();
402  if (draft.lost) toast("warn", tr("hist.lostTitle", "Attachments need to be added again"), tr("hist.lostText2", "This browser kept their names, not their contents. Attach them again."), 7000);
403}
404function rewindHere(i) {
405  if (!settings.chatEdit || busy || pending || !panel || panel.kind !== "rewind") return false;     // called from the open panel
406  const plan = H.rewind(messages, i);
407  if (!plan) return false;
408  const draftBefore = {text: $("input").value, attachments: attachments.slice()};
409  closePanel();
410  const u = commit(plan.keep, plan.hidden ? hiddenText(plan.hidden) : tr("hist.nothingHidden", "Back at this message"));
411  if (plan.draft) { u.draftBefore = draftBefore; fillBox(plan.draft); u.inserted = $("input").value; }
412  $("input").focus();
413  return true;
414}
415function branchHere(i) {
416  if (!listOn || busy || pending || !panel || panel.kind !== "rewind") return false;
417  const plan = H.rewind(messages, i);
418  if (!plan) return false;
419  closePanel();
420  const prev = chatId;
421  const c = H.branch(chat, plan.keep, plan.keep.length, tr("branch.title", "Branch of {title}", {title: H.chatTitle(chat, untitled())}));
422  chats.push(c);
423  showChat(c);
424  if (plan.draft) fillBox(plan.draft);
425  $("input").focus();
426  toast("info", tr("branch.started", "Branch started"), tr("branch.startedText", "The chat you were in is unchanged, in the list on the left."), 8000,
427        {label: tr("branch.back", "Back to it"), run: () => openChat(prev)});
428  return true;
429}
430
431// ------------------------------------------------------------------ wiring (called once by app.js)
432function initChats() {
433  $("sidebar-toggle").onclick = () => setSidebar(!sidebarOpen, true);
434  $("sidebar-new").onclick = startChat;
435  $("sidebar-search").addEventListener("input", () => { sidebarQuery = $("sidebar-search").value; renderSidebar(); });
436  $("sidebar-list").addEventListener("click", (e) => {
437    // a click inside the rename field is caret placement, not a click on the row: the row's handler would open the chat,
438    // which re-renders the list and takes the field away mid-click
439    if (e.target.closest(".chat-item__input")) return;
440    const row = e.target.closest(".chat-item");
441    if (!row) return;
442    const c = chats.find((x) => x.id === row.dataset.id);
443    if (!c) return;
444    if (e.target.closest("[data-delete]")) { deleteChat(c); return; }
445    if (e.target.closest("[data-rename]")) { renameChat(row, c); return; }
446    openChat(c.id);
447  });
448  // a narrow screen starts with the list closed so the chat has room
449  setSidebar(store.get("sidebar", true) && !matchMedia("(max-width: 760px)").matches, false);
450}