okami.mom/strata

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

Niko1221Merge f-0213-guidata (4c4596746) into f-0213-int22a3d7068

main
6.3 KiB133 linesraw
1"""serve/test_web_start_question.py - /?q= fills in the question and never sends it (#4221).
2
3Opening /?q=<text> used to put the text in the box and call send() on load, so any web page could link to
4http://127.0.0.1:<port>/?q=... and make the model answer, with the API key and the MCP tools saved in that browser,
5without the person pressing Send.  The page's own start() runs here under Node against a fake page and a fake credentialed
6backend with a request spy: after navigation and after a reload there are zero generation, tool or chat requests, the
7question is in the box and the box has focus; only an explicit Send (the composer's own handler) reaches the backend.
8Skipped without node.
9
10    python -m unittest serve.test_web_start_question -v
11"""
12from __future__ import annotations
13
14import json
15import re
16import shutil
17import subprocess
18import unittest
19from pathlib import Path
20
21APP = Path(__file__).resolve().parent / "web" / "app.js"
22
23
24def between(src: str, start: str, end: str) -> str:
25    a = src.index(start)
26    return src[a:src.index(end, a)]
27
28
29HARNESS = r"""
30const calls = [];                       // every request the page makes to its backend, in order
31const sends = [];                       // every time the page's send() runs
32const focus = [];
33const input = {value: "", style: {}, scrollHeight: 40, focus() { focus.push("input"); }};
34const page = {url: new URL(%(url)s), hash: ""};
35const location = {
36  get search() { return page.url.search; },
37  get pathname() { return page.url.pathname; },
38  get hash() { return page.hash; },
39};
40const history = {replaceState(_s, _t, url) { page.url = new URL(url, page.url); }};
41const innerHeight = 800;
42const $ = (id) => (id === "input" ? input : {focus() {}, set value(v) {}, get value() { return ""; }});
43// a credentialed backend: the saved API key and the MCP tools are what a send would use
44async function fetch(path, opts) { calls.push({path: String(path), method: (opts && opts.method) || "GET", auth: !!(opts && opts.headers && opts.headers.Authorization)}); return {ok: true, json: async () => ({})}; }
45const StrataI18n = {lang: "en", setLanguage: async () => {}};
46const store = {get: (_k, d) => d};
47const settings = {chatList: false};
48const urlLang = null;
49const tab = "chat";
50function renderEmptyChat() {}
51function initChats() {}
52async function setChatList() {}
53function setBusy() {}
54function renderChat() {}
55function poll() {}
56function fitHeader() {}
57const requestAnimationFrame = () => {};
58async function loadHealth() { await fetch("health"); }
59async function loadMcp() { await fetch("v1/mcp"); }
60function showTab(name) { focus.push("tab:" + (name || "chat")); }
61async function send() { sends.push(input.value); await fetch("v1/chat/completions", {method: "POST", headers: {Authorization: "Bearer saved-key"}}); }
62%(autosize)s
63%(start)s
64(async () => {
65  await start();
66  await new Promise((r) => setTimeout(r, 20));        // let the health and tool-list fetches settle
67  const first = {input: input.value, url: page.url.pathname + page.url.search, calls: calls.slice(), sends: sends.length, focus: focus.slice()};
68  // reload: the browser asks for the address it now has (the ?q= was removed from it by the first start)
69  input.value = ""; calls.length = 0; sends.length = 0; focus.length = 0;
70  await start();
71  await new Promise((r) => setTimeout(r, 20));
72  const second = {input: input.value, calls: calls.slice(), sends: sends.length};
73  console.log(JSON.stringify({first, second}));
74})();
75"""
76
77
78@unittest.skipUnless(shutil.which("node"), "node is not installed")
79class StartQuestion(unittest.TestCase):
80    @classmethod
81    def setUpClass(cls):
82        cls.src = APP.read_text(encoding="utf-8")
83        cls.start = between(cls.src, "async function start() {", "\nstart();")
84        m = re.search(r"function autosize\(\)[^\n]*", cls.src)
85        assert m, "autosize() is gone"
86        cls.autosize = m.group(0)
87
88    def run_page(self, url):
89        js = HARNESS % {"url": json.dumps(url), "start": self.start, "autosize": self.autosize}
90        out = subprocess.run(["node", "-e", js], capture_output=True, text=True, timeout=60)
91        self.assertEqual(out.returncode, 0, out.stderr)
92        return json.loads(out.stdout)
93
94    def test_navigation_fills_the_question_and_sends_nothing(self):
95        r = self.run_page("http://127.0.0.1:8080/?q=Delete%20my%20files")["first"]
96        self.assertEqual(r["input"], "Delete my files")
97        self.assertEqual(r["sends"], 0)
98        generation = [c for c in r["calls"] if c["method"] != "GET" or "chat" in c["path"] or "completions" in c["path"] or "tool" in c["path"]]
99        self.assertEqual(generation, [], "no model or tool request fires on navigation")
100        self.assertFalse([c for c in r["calls"] if c["auth"]], "nothing went out with the saved key")
101        self.assertIn("input", r["focus"], "the box is focused")
102        self.assertEqual(r["url"], "/", "the question is taken out of the address")
103
104    def test_reload_after_that_sends_nothing_and_does_not_refill(self):
105        r = self.run_page("http://127.0.0.1:8080/?q=hello")["second"]
106        self.assertEqual(r["sends"], 0)
107        self.assertEqual(r["input"], "")
108        self.assertEqual([c for c in r["calls"] if c["method"] != "GET"], [])
109
110    def test_no_question_in_the_address_changes_nothing(self):
111        r = self.run_page("http://127.0.0.1:8080/")["first"]
112        self.assertEqual(r["input"], "")
113        self.assertEqual(r["sends"], 0)
114
115    def test_long_and_odd_questions_are_filled_as_text(self):
116        for q in ["%3Cscript%3Ealert(1)%3C%2Fscript%3E", "a" * 5000, "%E4%B8%AD%E6%96%87%20x"]:
117            r = self.run_page(f"http://127.0.0.1:8080/?q={q}")["first"]
118            self.assertEqual(r["sends"], 0)
119            self.assertTrue(r["input"])
120
121    def test_the_page_never_calls_send_from_the_address(self):
122        # the only things that call send() are the composer's own submit and the Enter key
123        text = self.src.splitlines()
124        lines = [n for n, line in enumerate(text, 1) if re.search(r"\bsend\(\)", line.split("//")[0])]
125        self.assertTrue(lines)
126        for n in lines:
127            line = text[n - 1]
128            self.assertTrue("onsubmit" in line or "preventDefault" in line, f"app.js:{n} calls send() outside a person's action: {line.strip()}")
129        self.assertNotIn("startQuestion) { $(\"input\").value = startQuestion; send()", self.src)
130
131
132if __name__ == "__main__":
133    unittest.main()