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
6.1 KiB119 linesraw
1"""The web page's chat history: saved chats in the browser (#1787), edit / regenerate / rewind with an Undo (#2615), the rewind
2choice between "here" and a branch (#3823), and sending while an answer is written (#4004). One design, opt-in, off by default.
3
4The logic runs in Node (serve/test_web_history.js); what the page does in a real browser is in tools/webtest/browser_test.mjs
5(run here when WEBTEST_MODULES is set). These checks read the sources for what must hold whatever the code looks like:
6off is the page from before, and nothing about a chat goes to the server."""
7from __future__ import annotations
8
9import os
10import re
11import shutil
12import subprocess
13import unittest
14import urllib.error
15import urllib.request
16from pathlib import Path
17
18from serve.frontend import ChatTemplate
19from serve.server import ByteTokenizer, MockEngine, Service, serve
20
21ROOT = Path(__file__).resolve().parents[1]
22WEB = Path(__file__).parent / "web"
23
24
25@unittest.skipUnless(shutil.which("node"), "node is not installed")
26class HistoryInNode(unittest.TestCase):
27    def test_messages_titles_branches_and_the_browser_store(self):
28        r = subprocess.run([shutil.which("node"), str(Path(__file__).with_name("test_web_history.js"))],
29                           capture_output=True, text=True, timeout=60)
30        self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
31
32
33class OffIsThePageFromBefore(unittest.TestCase):
34    @classmethod
35    def setUpClass(cls):
36        cls.html = (WEB / "index.html").read_text(encoding="utf-8")
37        cls.app = (WEB / "app.js").read_text(encoding="utf-8")
38        cls.ui = (WEB / "chats-ui.js").read_text(encoding="utf-8")
39        cls.store = (WEB / "chatstore.js").read_text(encoding="utf-8")
40
41    def test_the_three_switches_start_off(self):
42        self.assertIn('chatList: false, chatEdit: false, whileBusy: "wait"', self.app)
43        for el in ("s-list", "s-edit"):
44            self.assertIn('aria-checked="false"', re.search(rf'<button[^>]*id="{el}"[^>]*>', self.html).group(0))
45        self.assertIn('data-v="wait"', self.html)
46        self.assertRegex(self.html, r'<aside class="chat-sidebar"[^>]*\bhidden>')              # no list until it is switched on
47
48    def test_the_browser_store_is_opened_only_for_the_list(self):
49        self.assertEqual(self.ui.count("chatStore.start()"), 1)
50        self.assertRegex(self.ui, r"async function openChats\(fromScreen\) \{\s*await chatStore\.start\(\);")
51        self.assertEqual(len(re.findall(r"\bopenChats\(", self.ui)), 2)       # its definition and the one call, in setChatList
52        self.assertNotIn("indexedDB", self.app, "the page's main script never touches the store")
53        self.assertIn("if (settings.chatList) await setChatList(true, false);", self.app)
54
55    def test_with_the_list_off_one_chat_is_kept_as_before(self):
56        self.assertIn('if (!listOn) { store.set("chat", H.cleanMessages(messages)); return; }', self.ui)
57        self.assertIn('$("new-btn").hidden = on;', self.ui)                  # only the list's own New chat shows while it is on
58
59    def test_pictures_and_files_are_kept_as_names_only(self):
60        self.assertIn("chatStore.put(H.cleanChat(chat))", self.ui)
61        self.assertNotIn("chatStore.put(chat)", self.ui)
62
63    def test_nothing_about_a_chat_goes_to_the_server(self):
64        for name, src in (("app.js", self.app), ("chats-ui.js", self.ui), ("chatstore.js", self.store)):
65            for call in re.findall(r'fetch\(\s*([^,)]+)', src):
66                if call != '"v1/chat/completions"':                    # the question itself, as ever
67                    self.assertNotRegex(call, r"chat|histor", f"{name}: {call}")
68
69    def test_the_edit_controls_wait_for_a_finished_answer(self):
70        self.assertIn("const historyLocked = () => !!busy || !!panel || !!pending;", self.ui)
71        self.assertIn("$(\"s-list\").disabled = $(\"s-edit\").disabled = !!busy || !!panel;", self.app)
72
73    def test_an_interrupted_answer_keeps_what_was_written(self):
74        self.assertIn("if (cut) m.interrupted = true;", self.app)
75        self.assertIn("busy.cutAfterTool = true; return; }   // let the tool finish", self.app)
76        self.assertIn("settlePending(cut, !m.stopped && !m.error);", self.app)
77
78    def test_sending_while_busy_parks_nothing_unless_asked(self):
79        self.assertIn('const parksWhileBusy = () => settings.whileBusy === "queue" || settings.whileBusy === "interject";', self.app)
80        self.assertIn("if (!parksWhileBusy()) return;", self.app)
81
82
83class NothingOnTheServer(unittest.TestCase):
84    @classmethod
85    def setUpClass(cls):
86        tok = ByteTokenizer()
87        cls.svc = Service(MockEngine(tok, "ok"), tok, ChatTemplate(ROOT / "serve" / "chat_template.jinja"))
88        cls.httpd = serve(cls.svc, port=0)
89        cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}"
90
91    @classmethod
92    def tearDownClass(cls):
93        cls.httpd.shutdown()
94        cls.httpd.server_close()
95
96    def test_the_scripts_are_served_and_there_is_no_chat_endpoint(self):
97        for name in ("history.js", "chatstore.js", "chats-ui.js"):
98            with urllib.request.urlopen(f"{self.base}/web/{name}", timeout=10) as r:
99                self.assertEqual(r.status, 200)
100        for path in ("/chats", "/api/chats", "/history", "/api/history"):
101            with self.subTest(path=path):
102                with self.assertRaises(urllib.error.HTTPError) as e:
103                    urllib.request.urlopen(self.base + path, timeout=10)
104                self.assertEqual(e.exception.code, 404)
105
106
107@unittest.skipUnless(os.environ.get("WEBTEST_MODULES") and shutil.which("node"),
108                     "set WEBTEST_MODULES (a folder with node_modules/puppeteer-core) to run the browser tests")
109class InABrowser(unittest.TestCase):
110    def test_history_in_chrome(self):
111        for name in ("history", "list", "rewind", "branch", "regenerate", "edit answer", "while answering"):
112            with self.subTest(name=name):
113                r = subprocess.run([shutil.which("node"), str(ROOT / "tools" / "webtest" / "browser_test.mjs"), name],
114                                   capture_output=True, text=True, timeout=300)
115                self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
116
117
118if __name__ == "__main__":
119    unittest.main()