askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
test_ai_page_streaming.py · 6.1 KB · 143 lines
| 1 | """The shell and Talk pages show the reply as it is written. |
| 2 | |
| 3 | Both pages ask /api/ai/chat for a stream and read it with one small |
| 4 | function, chatTurn(), that returns the same [ok, body] pair the JSON call |
| 5 | did -- body being the final ``done`` event -- so everything after the call |
| 6 | (rendering, history, speech, view detection) is untouched. A response that |
| 7 | is not an event stream is read as JSON, which keeps refusals made before |
| 8 | the provider call (and any proxy that answers JSON) working. |
| 9 | |
| 10 | The script is checked AFTER Python evaluates the page source: the JS lives |
| 11 | inside a Python string, and a "\\n" written once instead of twice would put |
| 12 | a raw newline inside a JS string literal and break the whole page. |
| 13 | """ |
| 14 | |
| 15 | import importlib.util |
| 16 | import json |
| 17 | import re |
| 18 | import shutil |
| 19 | import subprocess |
| 20 | from pathlib import Path |
| 21 | |
| 22 | import pytest |
| 23 | |
| 24 | pytestmark = pytest.mark.node # needs the `node` binary; `pytest -m node` selects these (scripts/release_gate.sh node) |
| 25 | |
| 26 | SITE = Path(__file__).resolve().parents[1] / "packages" / "app-shell" / "objects" / "site" |
| 27 | |
| 28 | |
| 29 | def _script(name): |
| 30 | spec = importlib.util.spec_from_file_location(f"site_{name}_streaming_probe", SITE / f"{name}.py") |
| 31 | module = importlib.util.module_from_spec(spec) |
| 32 | spec.loader.exec_module(module) |
| 33 | return module._SCRIPT |
| 34 | |
| 35 | |
| 36 | def _chat_turn_source(script): |
| 37 | match = re.search(r"async function chatTurn\(payload, onText\) \{.*?\n\}\n", script, re.S) |
| 38 | assert match, "chatTurn() not found" |
| 39 | return match.group(0) |
| 40 | |
| 41 | |
| 42 | @pytest.mark.parametrize("page", ["shell", "talk"]) |
| 43 | def test_pages_ask_for_a_stream_and_fall_back_to_json(page): |
| 44 | source = _chat_turn_source(_script(page)) |
| 45 | assert '"/api/ai/chat"' in source |
| 46 | assert "{stream: true}" in source |
| 47 | assert 'accept: "text/event-stream, application/json"' in source |
| 48 | assert 'if (!type.startsWith("text/event-stream") || !res.body) return [res.ok, await res.json()];' in source |
| 49 | # Escapes survived Python: JS sees backslash-n, not a raw newline. |
| 50 | assert 'buffer.indexOf("\\n\\n")' in source |
| 51 | assert 'block.split("\\n")' in source |
| 52 | assert 'event === "done"' in source and 'event === "error"' in source |
| 53 | |
| 54 | |
| 55 | def test_shell_streams_into_the_pending_line_then_finishes_with_the_final_reply(): |
| 56 | script = _script("shell") |
| 57 | assert "const [ok, body] = await chatTurn(" in script |
| 58 | assert "showDelta);" in script |
| 59 | assert 'await api("POST", "/api/ai/chat"' not in script |
| 60 | # The authoritative reply still renders through finish(). |
| 61 | assert "finish(out, ok ? body.reply : body.error," in script |
| 62 | |
| 63 | |
| 64 | def test_talk_streams_into_the_caption_but_speaks_only_the_final_reply(): |
| 65 | script = _script("talk") |
| 66 | assert "[ok, body] = await chatTurn(" in script |
| 67 | assert 'await api("POST", "/api/ai/chat"' not in script |
| 68 | submit = re.search(r"async function submitTurn\(input\) \{(.*?)\n\}", script, re.S).group(1) |
| 69 | delta = submit[submit.index("const showDelta"):submit.index("[ok, body] = await chatTurn(")] |
| 70 | assert "capAssistant.textContent" in delta |
| 71 | assert "speak(" not in delta # never speaks a partial reply |
| 72 | assert "stripViewMarker(streamed)" in delta # the machine marker never shows |
| 73 | assert "speak(replyText);" in submit |
| 74 | |
| 75 | |
| 76 | NODE_PROBE = r""" |
| 77 | %(chat_turn)s |
| 78 | |
| 79 | function streamOf(chunks) { |
| 80 | let i = 0; |
| 81 | return {getReader() { return {read: async () => |
| 82 | i < chunks.length ? {value: new TextEncoder().encode(chunks[i++]), done: false} |
| 83 | : {value: undefined, done: true}}; }}; |
| 84 | } |
| 85 | function response(type, chunks, json, ok) { |
| 86 | return {ok, headers: {get: () => type}, body: chunks ? streamOf(chunks) : null, |
| 87 | json: async () => json}; |
| 88 | } |
| 89 | let next = null; |
| 90 | let sent = null; |
| 91 | globalThis.fetch = async (url, init) => { sent = JSON.parse(init.body); return next; }; |
| 92 | |
| 93 | (async () => { |
| 94 | const out = {}; |
| 95 | const sse = 'event: text\ndata: {"text": "Hel"}\n\nevent: te' + |
| 96 | 'xt\ndata: {"text": "lo"}\n\nevent: tool_call\ndata: {"name": "x"}\n\n' + |
| 97 | 'event: done\ndata: {"status": "ok", "reply": "Hello"}\n\n'; |
| 98 | next = response("text/event-stream; charset=utf-8", [sse.slice(0, 17), sse.slice(17, 50), sse.slice(50)], null, true); |
| 99 | const deltas = []; |
| 100 | out.streamed = await chatTurn({message: "hi"}, (t) => deltas.push(t)); |
| 101 | out.deltas = deltas; |
| 102 | out.sentStream = sent.stream; |
| 103 | |
| 104 | next = response("text/event-stream", ['event: error\ndata: {"status": "error", "error": "boom"}\n\n'], null, true); |
| 105 | out.error = await chatTurn({message: "hi"}, null); |
| 106 | |
| 107 | next = response("application/json", null, {status: "error", error: "No anthropic key"}, false); |
| 108 | out.json = await chatTurn({message: "hi"}, null); |
| 109 | |
| 110 | next = response("text/event-stream", ['event: text\ndata: {"text": "cut"}\n\n'], null, true); |
| 111 | out.cut = await chatTurn({message: "hi"}, null); |
| 112 | console.log(JSON.stringify(out)); |
| 113 | })(); |
| 114 | """ |
| 115 | |
| 116 | |
| 117 | @pytest.mark.parametrize("page", ["shell", "talk"]) |
| 118 | def test_chat_turn_reassembles_events_split_across_reads(page, tmp_path): |
| 119 | node = shutil.which("node") |
| 120 | if not node: |
| 121 | pytest.skip("node is not installed") |
| 122 | probe = tmp_path / "chat_turn_probe.js" |
| 123 | probe.write_text(NODE_PROBE % {"chat_turn": _chat_turn_source(_script(page))}) |
| 124 | result = subprocess.run([node, str(probe)], capture_output=True, text=True) |
| 125 | assert result.returncode == 0, result.stderr |
| 126 | out = json.loads(result.stdout) |
| 127 | assert out["deltas"] == ["Hel", "lo"] |
| 128 | assert out["streamed"] == [True, {"status": "ok", "reply": "Hello"}] |
| 129 | assert out["sentStream"] is True |
| 130 | assert out["error"] == [False, {"status": "error", "error": "boom"}] |
| 131 | assert out["json"] == [False, {"status": "error", "error": "No anthropic key"}] |
| 132 | assert out["cut"][0] is False and "stopped" in out["cut"][1]["error"] |
| 133 | |
| 134 | |
| 135 | @pytest.mark.parametrize("page", ["shell", "talk"]) |
| 136 | def test_page_script_parses_under_node(page): |
| 137 | """The whole evaluated script must be valid JavaScript: a syntax error |
| 138 | anywhere breaks the page in every browser.""" |
| 139 | node = shutil.which("node") |
| 140 | if not node: |
| 141 | pytest.skip("node is not installed") |
| 142 | result = subprocess.run([node, "--check", "-"], input=re.sub(r"</?script[^>]*>", "", _script(page)), capture_output=True, text=True) |
| 143 | assert result.returncode == 0, result.stderr |