Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

dbbasic-object-server/tests/test_app_talk_object.py
Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 18 minutes ago History
test_app_talk_object.py · 62.2 KB · 1465 lines
1"""Tests for packages/app-shell's Talk surface (site_talk / /talk).
2
3Talk is a second projection of the same conversation as the shell: same
4POST /api/ai/chat, same prefs/model/tools, same shell_commands history --
5just staged as voice instead of transcript. These tests mirror the
6package/renderer testing conventions used in tests/test_app_views_package.py
7and add coverage specific to Talk's conversation-mode mic loop and the
8places shell.py was patched to stay in sync with it.
9"""
10
11import importlib.util
12import json
13import re
14import shutil
15import subprocess
16
17import pytest
18from pathlib import Path
19
20import object_execution
21import object_packages
22import object_permissions
23import python_object_runtime
24
25pytestmark = pytest.mark.node # needs the `node` binary; `pytest -m node` selects these (scripts/release_gate.sh node)
26
27PACKAGES_ROOT = Path(__file__).resolve().parents[1] / "packages"
28APP_SHELL_DIR = PACKAGES_ROOT / "app-shell"
29TALK_PATH = APP_SHELL_DIR / "objects" / "site" / "talk.py"
30TALK_SOURCE = TALK_PATH.read_text()
31SHELL_SOURCE = (APP_SHELL_DIR / "objects" / "site" / "shell.py").read_text()
32SHELL_PREFS_SCHEMA = json.loads((APP_SHELL_DIR / "schemas" / "shell_preferences.json").read_text())
33
34
35def _render_talk_html(user_id="u1"):
36 """Import talk.py fresh and render its GET() body for a signed-in user,
37 the same way the object runtime would -- used by tests that need the
38 *actual evaluated* inline <script>, not just the Python source text."""
39 spec = importlib.util.spec_from_file_location("site_talk_under_test", TALK_PATH)
40 module = importlib.util.module_from_spec(spec)
41 spec.loader.exec_module(module)
42
43 class _NullLogger:
44 def info(self, *args, **kwargs):
45 pass
46
47 module._logger = _NullLogger()
48 return module.GET({"_identity": {"user_id": user_id}})["body"]
49
50
51def _extract_inline_script(html):
52 """Pull the content of the one bare `<script>...</script>` block (the
53 page's own inline script, as opposed to the `<script src=...>` tags)."""
54 blocks = re.findall(r"<script>(.*?)</script>", html, re.S)
55 assert blocks, "no inline <script> block found in rendered Talk HTML"
56 return blocks[0]
57
58
59def test_get_package_lists_site_talk_alongside_site_shell():
60 package = object_packages.get_package("app-shell", root=PACKAGES_ROOT)
61
62 assert package["id"] == "app-shell"
63 assert {obj["id"] for obj in package["objects"]} == {"site_shell", "site_talk"}
64 ids_to_paths = {obj["id"]: obj["path"] for obj in package["objects"]}
65 assert ids_to_paths["site_talk"] == "objects/site/talk.py"
66
67
68def test_dry_run_app_shell_package_is_safe(tmp_path):
69 object_root = tmp_path / "objects"
70 object_root.mkdir()
71
72 plan = object_packages.dry_run_package(
73 "app-shell",
74 root=PACKAGES_ROOT,
75 base_dir=tmp_path / "data",
76 object_roots=[object_root],
77 )
78
79 assert plan["safe_to_install"] is True
80 assert plan["warnings"] == []
81
82
83def test_install_app_shell_package_writes_talk_object(tmp_path):
84 data_dir = tmp_path / "data"
85 object_root = tmp_path / "objects"
86 object_root.mkdir()
87
88 object_packages.install_package(
89 "app-shell",
90 root=PACKAGES_ROOT,
91 base_dir=data_dir,
92 object_roots=[object_root],
93 )
94
95 assert (object_root / "site" / "talk.py").is_file()
96 # Convention routing (/talk -> site_talk, no site_routes record needed)
97 # is exactly what lets a page-object addition create its own URL, the
98 # same way /shell -> site_shell already works.
99 import object_site_routes
100
101 assert object_site_routes.convention_object_id("/talk") == "site_talk"
102 assert object_site_routes.convention_object_id("/shell") == "site_shell"
103
104
105def _app_shell_policy():
106 payload = json.loads((APP_SHELL_DIR / "permissions" / "rules.json").read_text())
107 return object_permissions.policy_from_dict({"access_mode": "role_based", "rules": payload["rules"]})
108
109
110def test_talk_page_execute_is_public_like_shell():
111 policy = _app_shell_policy()
112
113 for object_id in ("site_shell", "site_talk"):
114 decision = object_permissions.check_permission(
115 None, object_permissions.EXECUTE, policy=policy, object_id=object_id
116 )
117 assert decision.allowed is True, object_id
118
119
120def test_talk_object_serves_sign_in_prompt_when_anonymous(tmp_path):
121 data_dir = tmp_path / "data"
122 object_root = tmp_path / "objects"
123 object_root.mkdir()
124 object_packages.install_package(
125 "app-shell", root=PACKAGES_ROOT, base_dir=data_dir, object_roots=[object_root]
126 )
127
128 runtime = python_object_runtime.PythonObjectRuntime(base_dir=data_dir)
129 result = object_execution.execute_object(
130 runtime,
131 object_execution.ObjectExecutionRequest("site_talk", payload={"_identity": {}}),
132 roots=[object_root],
133 )
134
135 assert result.ok is True
136 body = result.result["body"]
137 assert result.result["content_type"] == "text/html; charset=utf-8"
138 assert "Sign in" in body
139 assert "/login?next=/talk" in body
140
141
142def test_talk_object_serves_stage_scaffolding_when_signed_in(tmp_path):
143 data_dir = tmp_path / "data"
144 object_root = tmp_path / "objects"
145 object_root.mkdir()
146 object_packages.install_package(
147 "app-shell", root=PACKAGES_ROOT, base_dir=data_dir, object_roots=[object_root]
148 )
149
150 runtime = python_object_runtime.PythonObjectRuntime(base_dir=data_dir)
151 result = object_execution.execute_object(
152 runtime,
153 object_execution.ObjectExecutionRequest(
154 "site_talk", payload={"_identity": {"user_id": "u1"}}
155 ),
156 roots=[object_root],
157 )
158
159 assert result.ok is True
160 body = result.result["body"]
161 assert result.result["content_type"] == "text/html; charset=utf-8"
162 # Stage/caption/mic scaffolding.
163 assert 'id="stage"' in body
164 assert 'id="capUser"' in body and 'id="capAssistant"' in body
165 assert 'id="mic"' in body
166 assert 'id="prompt"' in body
167 assert 'href="/shell"' in body
168 # Same brain: it is the /api/ai/chat call, not a new endpoint.
169 assert "/api/ai/chat" in body
170 # History is written server-side now; the page carries its session id
171 # instead of a collections URL.
172 assert "session_id: SESSION_ID" in body
173 # The talk-mode system prompt marker, plus the base capabilities text
174 # copied verbatim from shell.py (proves the two are still in sync).
175 assert "You are in voice mode" in body
176 assert "NEVER read ids, urls, uuids, or paths aloud" in body
177 assert "MATERIALIZE PAGES" in body
178 assert "u1" in body
179
180
181def test_talk_source_pauses_recognition_around_tts_playback():
182 """The core anti-feedback-loop requirement: the mic must not hear the
183 machine talk. Assert the shape directly on source since it's an
184 interaction between async callbacks that's easiest to prove by
185 inspecting the wiring: speak() marks `speaking` and stops listening
186 before playback, both playback-completion paths clear it and resume,
187 and onend / startListening both respect the `speaking` flag.
188 """
189 assert "speaking = true" in TALK_SOURCE
190 assert "stopListening();" in TALK_SOURCE
191
192 speak_fn = re.search(r"async function speak\(text\) \{(.*?)\n\}\n", TALK_SOURCE, re.S)
193 assert speak_fn, "speak() not found in talk.py"
194 body = speak_fn.group(1)
195 # speaking flips true and recognition RELEASE IS AWAITED before either
196 # playback path -- not merely requested. iOS shares one audio session
197 # between mic and speaker, and recognizer.stop() is a request whose
198 # teardown completes asynchronously (onend); starting playback before
199 # that finishes can play into a still-recording session and come out
200 # silent, with no error anywhere -- Dan's own diagnosis of an iPad
201 # that spoke on desktop but not there, verbatim: "listening while
202 # talking, maybe not allowed."
203 assert body.index("speaking = true") < body.index('await player.play()')
204 assert body.index("await stopListeningAndWaitForRelease();") < body.index('await player.play()')
205 # Both the server-TTS path and the speechSynthesis fallback route
206 # playback-completion through the ONE shared stopSpeaking() (see
207 # test_talk_stop_speaking_is_shared_by_natural_end_and_interrupt for
208 # its actual cleanup behavior) rather than each duplicating
209 # `speaking = false; resumeListeningIfNeeded();` inline -- that
210 # duplication is exactly what would let a natural end and a
211 # deliberate interrupt (headphones mode) drift apart.
212 assert "player.onended = stopSpeaking;" in body
213 assert "player.onerror = stopSpeaking;" in body
214 assert "player.onstalled = stopSpeaking;" in body
215 assert "speaking = false;" in TALK_SOURCE
216 assert "resumeListeningIfNeeded();" in TALK_SOURCE
217
218 # startListening() itself refuses to start while speaking, and the
219 # recognizer's own onend only auto-restarts when not speaking.
220 assert "if (!recognizer || listening || speaking) return;" in TALK_SOURCE
221 assert "if (conversationMode && !speaking) startListening();" in TALK_SOURCE
222
223
224def test_talk_source_conversation_mode_auto_restarts_on_end():
225 assert "conversationMode" in TALK_SOURCE
226 assert "recognizer.onend = () => {" in TALK_SOURCE
227 assert "resumeListeningIfNeeded" in TALK_SOURCE
228
229
230def test_talk_stripforspeech_strips_urls_and_view_paths():
231 fn = re.search(r"function stripForSpeech\(text\) \{(.*?)\n\}\n", TALK_SOURCE, re.S)
232 assert fn, "stripForSpeech() not found in talk.py"
233 body = fn.group(1)
234 assert "https?" in body
235 assert "/views" in body
236
237
238def test_talk_base_capabilities_match_shell_verbatim():
239 """The views MATERIALIZE PAGES block must be copied verbatim into
240 talk.py so the two prompts stay in sync, per the module docstring."""
241 marker = "You can also MATERIALIZE PAGES"
242 assert marker in TALK_SOURCE
243 assert marker in SHELL_SOURCE
244
245 talk_block = TALK_SOURCE[TALK_SOURCE.index(marker):TALK_SOURCE.index(marker) + 900]
246 shell_block = SHELL_SOURCE[SHELL_SOURCE.index(marker):SHELL_SOURCE.index(marker) + 900]
247 # Normalize away Python vs. JS string-literal concatenation syntax so
248 # this compares the actual prose, not the quoting style.
249 def normalize(s):
250 s = re.sub(r'["\'+]|\\+', "", s)
251 return re.sub(r"\s+", " ", s).strip()
252
253 assert normalize(talk_block)[:400] == normalize(shell_block)[:400]
254
255
256def test_talk_marker_instruction_has_worked_example():
257 """Live use showed the model ignoring the [[view:<id>]] marker
258 instruction; a literal worked example was added to the shared
259 MATERIALIZE-PAGES block (in both files) to reinforce it."""
260 example_id = "26b247ed-3b1a-4206-b060-1d92847194de"
261 expected = f'Example reply: "Here are your open tasks. [[view:{example_id}]]"'
262
263 spec = importlib.util.spec_from_file_location("site_talk_marker_example", TALK_PATH)
264 module = importlib.util.module_from_spec(spec)
265 spec.loader.exec_module(module)
266 assert expected in module.TALK_SYSTEM
267
268 assert f"[[view:{example_id}]]" in SHELL_SOURCE
269 assert "Example reply" in SHELL_SOURCE
270
271
272def test_talk_marker_example_renders_verbatim_identical_in_shell_js(tmp_path):
273 """Behavioral verbatim-sync check for the appended example specifically
274 (the source-level verbatim test above only compares the first 400
275 normalized chars of the block, which ends before the example): evaluate
276 shell.py's actual system-prompt JS expression under node and confirm it
277 contains the exact same example text as talk.py's TALK_SYSTEM."""
278 node = shutil.which("node")
279 if not node:
280 pytest.skip("node not installed")
281
282 example_id = "26b247ed-3b1a-4206-b060-1d92847194de"
283 expected = f'Example reply: "Here are your open tasks. [[view:{example_id}]]"'
284
285 spec = importlib.util.spec_from_file_location("site_shell_under_test", APP_SHELL_DIR / "objects" / "site" / "shell.py")
286 module = importlib.util.module_from_spec(spec)
287
288 class _NullLogger:
289 def info(self, *args, **kwargs):
290 pass
291
292 module._logger = _NullLogger()
293 spec.loader.exec_module(module)
294
295 script = module._SCRIPT
296 start = script.index('system: "You are the shell')
297 # The system prompt is a chain of string literals joined by `+`. Match
298 # exactly that chain, so fields the request object carries after it
299 # (context:, callbacks) can never leak into the probe.
300 literal = r'"(?:[^"\\\n]|\\.)*"'
301 chain = re.compile(rf"{literal}(?:\s*\+\s*{literal})*")
302 match = chain.match(script, start + len("system: "))
303 assert match, "could not find the system-prompt string expression in shell.py"
304 expr = match.group(0)
305
306 probe_path = tmp_path / "shell_system_probe.js"
307 probe_path.write_text(f"const d = {expr};\nconsole.log(JSON.stringify(d));\n")
308 result = subprocess.run([node, str(probe_path)], capture_output=True, text=True)
309 assert result.returncode == 0, f"node probe failed:\n{result.stderr}"
310 shell_system = json.loads(result.stdout)
311 assert expected in shell_system
312
313
314def test_talk_falls_back_to_tool_calls_for_the_view_path():
315 assert "viewPathFromToolCalls" in TALK_SOURCE
316 assert "create_record" in TALK_SOURCE
317 assert "update_record" in TALK_SOURCE
318 assert 'args.collection !== "views"' in TALK_SOURCE
319
320
321# --- fresh model context per session (no shell_commands replay) ----------
322#
323# Root cause of the model ignoring the [[view:<id>]] marker in live use:
324# Talk used to replay up to 1000 old shell_commands rows into aiHistory on
325# every page load, and every historical turn recorded before the marker
326# convention existed demonstrated the pre-marker habit -- in-context
327# examples override instructions no matter how the system prompt is
328# reworded. Talk must start each session with an empty aiHistory and only
329# ever grow it from turns submitted in *this* session; shell.py's own
330# replay (which drives its visible transcript, not just model context) is
331# unaffected.
332
333
334def test_talk_never_auto_resumes_a_session():
335 """Talk reads shell_commands now -- but only to BUILD the session
336 picker. Restoring old turns into model context is a hand action on
337 the picker, never an automatic on load: a voice page that silently
338 reloads twenty turns changes what the next answer means without the
339 user hearing anything change. (The shell auto-resumes inside a
340 30-minute window; eyes can see a restored transcript, ears cannot.)"""
341 assert "loadHistory" not in TALK_SOURCE
342 assert "let aiHistory = [];" in TALK_SOURCE
343 load = TALK_SOURCE[TALK_SOURCE.index("async function loadSessions"):]
344 load = load[:load.index("loadSessions();")]
345 before_handler = load[:load.index('addEventListener("change"')]
346 assert "aiHistory.push" not in before_handler
347 # Turn WRITES are the server's inside /api/ai/chat; the page only
348 # reads, to fold the picker, and declares its session on each call.
349 assert "session_id: SESSION_ID" in TALK_SOURCE
350
351 # aiHistory grows in exactly two places: submitTurn (the turn just
352 # made) and the picker's change handler (an explicit resume).
353 submit_turn = re.search(r"async function submitTurn\(input\) \{(.*?)\n\}", TALK_SOURCE, re.S)
354 assert submit_turn, "submitTurn() not found in talk.py"
355 push_sites = [m.start() for m in re.finditer(r"aiHistory\.push\(", TALK_SOURCE)]
356 assert len(push_sites) == 4 # 2 in submitTurn, 2 in the resume handler
357 handler_at = TALK_SOURCE.index('addEventListener("change"')
358 for site in push_sites:
359 inside_submit = submit_turn.start() < site < submit_turn.end()
360 inside_resume = site > handler_at
361 assert inside_submit or inside_resume, site
362
363
364def test_talk_object_no_longer_calls_loadhistory_on_page_load():
365 html = _render_talk_html()
366 script = _extract_inline_script(html)
367 assert "loadHistory" not in script
368 # initMic() must run AFTER loadPrefs() resolves, not as two independent
369 # standalone calls -- see test_talk_init_order_loads_prefs_before_deciding_mic_path
370 # for why the ordering itself is load-bearing, not just style.
371 assert "loadPrefs().then(() => { initMic(); initCloudVoiceToggle(); initHeadphonesToggle(); });" in script
372
373
374def test_shell_replay_into_model_context_is_unaffected():
375 """shell.py's replay behavior stays as-is -- it drives the visible
376 transcript on load (not just aiHistory), so it is unrelated to the
377 Talk-specific in-context-examples problem."""
378 assert "async function loadHistory()" in SHELL_SOURCE
379 assert "shell_commands/records?limit=1000" in SHELL_SOURCE
380 assert "aiHistory.push" in SHELL_SOURCE
381 assert "loadHistory();" in SHELL_SOURCE
382
383
384# --- shell.py patches (linkify + embed, extended stripForSpeech) ---------
385
386
387def test_shell_finish_linkifies_and_embeds_views_paths():
388 assert "function linkifyViews(html)" in SHELL_SOURCE
389 assert "VIEWS_PATH_RE" in SHELL_SOURCE
390 assert "viewembed" in SHELL_SOURCE
391 assert 'target="_blank" rel="noopener">open ↗' in SHELL_SOURCE
392
393 finish_fn = re.search(r"function finish\(out, text,.*?\n\}\n", SHELL_SOURCE, re.S)
394 assert finish_fn, "finish() not found in shell.py"
395 body = finish_fn.group(0)
396 assert "linkifyViews(" in body
397 assert "insertAdjacentElement(\"afterend\", embed)" in body
398
399
400def test_shell_stripforspeech_strips_urls_and_view_paths():
401 fn = re.search(r"function stripForSpeech\(text\) \{(.*?)\n\}\n", SHELL_SOURCE, re.S)
402 assert fn, "stripForSpeech() not found in shell.py"
403 body = fn.group(1)
404 assert "https?" in body
405 assert "/views" in body
406
407
408# --- bug fixes: placeholder escaping + the dead submit path --------------
409#
410# The placeholder bug was a context mismatch: `…` is a JS/Python
411# unicode escape, but the placeholder lives in plain HTML markup (the
412# `body` string), not inside the `<script>` tag -- so the browser never
413# gets a chance to interpret it and shows the six literal characters
414# `…` instead of an ellipsis. `node --check` on the *actual evaluated*
415# script is the strongest guard against this whole class of Python-string/
416# JS-string escaping fault recurring; it is skipped (not failed) when node
417# isn't on PATH, falling back to a source assertion that the placeholder
418# is clean.
419
420
421def test_talk_placeholder_has_no_backslash_escape():
422 assert 'placeholder="or type...' in TALK_SOURCE
423 assert "or type\\u2026" not in TALK_SOURCE
424 assert "or type\\\\u2026" not in TALK_SOURCE
425
426 html = _render_talk_html()
427 assert 'placeholder="or type...' in html
428 input_tag = re.search(r'<input name="line"[^>]*>', html)
429 assert input_tag, "line input not found in rendered Talk HTML"
430 assert "\\u2026" not in input_tag.group(0)
431 assert "\\" not in input_tag.group(0)
432
433
434def test_talk_evaluated_script_passes_node_check(tmp_path):
435 html = _render_talk_html()
436 script = _extract_inline_script(html)
437
438 node = shutil.which("node")
439 if not node:
440 # No node on PATH in this environment -- fall back to the source
441 # assertion above, which is the part node --check would have caught
442 # for this specific bug class anyway.
443 assert 'placeholder="or type...' in html
444 return
445
446 script_path = tmp_path / "talk_inline.js"
447 script_path.write_text(script)
448 result = subprocess.run(
449 [node, "--check", str(script_path)], capture_output=True, text=True
450 )
451 assert result.returncode == 0, f"node --check failed:\n{result.stderr}"
452
453
454def test_talk_submit_handler_reads_line_input_and_calls_submitturn():
455 """The dead-send-button symptom: verify the actual wiring end to end --
456 the form's submit listener is attached (not just present as dead code),
457 it prevents default navigation, reads the named `line` input, and always
458 calls submitTurn() so voice and typed input share one code path."""
459 handler = re.search(
460 r'document\.getElementById\("prompt"\)\.addEventListener\("submit", \(event\) => \{(.*?)\n\}\);',
461 TALK_SOURCE,
462 re.S,
463 )
464 assert handler, "submit listener not found in talk.py"
465 body = handler.group(1)
466 assert "event.preventDefault();" in body
467 assert 'event.target.elements["line"]' in body
468 assert "submitTurn(input)" in body
469 # Manual submit folds in the voice buffer regardless of protocol state.
470 assert "pendingText()" in body
471 assert "resetTalkState();" in body
472
473
474def test_talk_recognition_final_results_feed_the_same_submit_function():
475 onresult = re.search(r"recognizer\.onresult = \(event\) => \{(.*?)\n \};", TALK_SOURCE, re.S)
476 assert onresult, "recognizer.onresult not found in talk.py"
477 body = onresult.group(1)
478 assert "processTranscript(isFinal)" in body
479 # processTranscript() is the one funnel that can call submitTurn (via
480 # finalizeVoiceSubmit) -- both the mic path and the form path resolve
481 # to the same submitTurn() used for /api/ai/chat.
482 assert "async function submitTurn(input)" in TALK_SOURCE
483 assert "finalizeVoiceSubmit" in TALK_SOURCE
484 finalize = re.search(r"function finalizeVoiceSubmit\(text\) \{(.*?)\n\}", TALK_SOURCE, re.S)
485 assert finalize
486 assert "submitTurn(clean)" in finalize.group(1)
487
488
489def test_talk_prefs_reads_go_through_pref_helper_not_raw_field_access():
490 """A shell_preferences record written before a field existed in the
491 schema won't have that key; `prefs.tools.split(",")` on undefined would
492 throw and silently kill the turn (send button/voice submit both call
493 submitTurn). pref() with a fallback closes that hole."""
494 submit_turn = re.search(r"async function submitTurn\(input\) \{(.*?)\n\}", TALK_SOURCE, re.S)
495 assert submit_turn, "submitTurn() not found in talk.py"
496 body = submit_turn.group(1)
497 assert "prefs.tools.split" not in body
498 assert 'pref("tools", DEFAULT_TOOLS)' in body
499 assert 'pref("ai_model", DEFAULT_MODEL)' in body
500
501
502# --- radio protocol: wake word / end word / VAD endpointing --------------
503
504
505def test_talk_schema_bumped_with_radio_protocol_fields():
506 assert SHELL_PREFS_SCHEMA["version"] == 7 # +talk_tts_engine, +talk_stt_engine, +talk_headphones_mode
507
508 fields = {f["name"]: f for f in SHELL_PREFS_SCHEMA["fields"]}
509 assert fields["talk_wake_word"]["default"] == "computer"
510 assert fields["talk_end_word"]["default"] == "over"
511 assert fields["talk_endpoint"]["type"] == "enum"
512 assert fields["talk_endpoint"]["default"] == "silence"
513 assert set(fields["talk_endpoint"]["enum"]) == {"silence", "word", "manual"}
514 assert fields["talk_silence_ms"]["default"] == "1400"
515
516 # The defaults are mirrored client-side so a first-ever load (before
517 # loadPrefs() resolves) already behaves per spec.
518 assert 'talk_wake_word: "computer"' in TALK_SOURCE
519 assert 'talk_end_word: "over"' in TALK_SOURCE
520 assert 'talk_endpoint: "silence"' in TALK_SOURCE
521 assert 'talk_silence_ms: "1400"' in TALK_SOURCE
522
523
524def test_talk_cloud_voice_prefs_default_off():
525 fields = {f["name"]: f for f in SHELL_PREFS_SCHEMA["fields"]}
526 # Both default to the free, local, zero-behavior-change option -- a
527 # user who never opens settings must see EXACTLY today's behavior.
528 assert fields["talk_tts_engine"]["type"] == "enum"
529 assert fields["talk_tts_engine"]["default"] == "local"
530 assert set(fields["talk_tts_engine"]["enum"]) == {"local", "openai"}
531 assert fields["talk_stt_engine"]["type"] == "enum"
532 assert fields["talk_stt_engine"]["default"] == "browser"
533 assert set(fields["talk_stt_engine"]["enum"]) == {"browser", "openai"}
534
535 assert 'talk_tts_engine: "local"' in TALK_SOURCE
536 assert 'talk_stt_engine: "browser"' in TALK_SOURCE
537
538 # The settings form must actually surface both, or they're invisible.
539 default_form_fields = SHELL_PREFS_SCHEMA["forms"]["default"]["fields"]
540 assert "talk_tts_engine" in default_form_fields
541 assert "talk_stt_engine" in default_form_fields
542
543
544def test_talk_cloud_voice_url_override():
545 # "/talk?stt=openai" (or ?tts=openai) tries cloud voice for one page
546 # load without touching settings or persisting anything -- both reader
547 # functions must consult the URL before falling back to the stored
548 # preference.
549 override = re.search(r"function urlOverride\(param, allowed\) \{(.*?)\n\}", TALK_SOURCE, re.S)
550 assert override, "urlOverride() not found in talk.py"
551 assert "URLSearchParams(location.search)" in override.group(1)
552
553 tts_fn = re.search(r"function talkTtsEngine\(\) \{(.*?)\n\}", TALK_SOURCE, re.S)
554 assert tts_fn and 'urlOverride("tts", ["local", "openai"])' in tts_fn.group(1)
555
556 stt_fn = re.search(r"function talkSttEngine\(\) \{(.*?)\n\}", TALK_SOURCE, re.S)
557 assert stt_fn and 'urlOverride("stt", ["browser", "openai"])' in stt_fn.group(1)
558
559
560def test_talk_auto_mode_reliably_reaches_openai_engine(tmp_path):
561 """Behavioral, not source-string: a real live test hit exactly this --
562 "?tts=openai" set, still heard an espeak voice -- because "auto" mode
563 used to prefer ANY browser-native speechSynthesis voice over the
564 server unconditionally, before ever consulting the engine choice.
565 Executes the actual talkTtsMode/talkTtsEngine/urlOverride functions
566 under node with a handful of real scenarios, not a string match.
567 """
568 node = shutil.which("node")
569 if not node:
570 pytest.skip("node not installed")
571
572 # Pull each function verbatim (brace-counted scan to its own closing
573 # brace) rather than hand-copying logic into the test -- a future edit
574 # to talk.py is what this test must catch, not a frozen duplicate of it.
575 def extract_function(name):
576 start = TALK_SOURCE.index(f"function {name}(")
577 depth = 0
578 i = TALK_SOURCE.index("{", start)
579 for j in range(i, len(TALK_SOURCE)):
580 if TALK_SOURCE[j] == "{":
581 depth += 1
582 elif TALK_SOURCE[j] == "}":
583 depth -= 1
584 if depth == 0:
585 return TALK_SOURCE[start : j + 1]
586 raise AssertionError(f"unbalanced braces extracting {name}()")
587
588 functions = "\n".join(
589 extract_function(name) for name in
590 ("urlOverride", "talkTtsEngine", "talkSttEngine", "talkTtsMode")
591 )
592
593 probe = f"""
594const DEFAULT_TALK_TTS = "auto";
595const DEFAULT_TALK_TTS_ENGINE = "local";
596const DEFAULT_TALK_STT_ENGINE = "browser";
597let prefs = {{}};
598let location = {{search: ""}};
599function pref(name, fallback) {{
600 const v = prefs[name];
601 return v === undefined || v === null ? fallback : v;
602}}
603{functions}
604
605const results = [];
606// 1. Nobody touched anything: unchanged "auto" behavior (browser wins).
607prefs = {{}}; location = {{search: ""}};
608results.push(["default", talkTtsMode(), talkTtsEngine()]);
609
610// 2. The persisted-setting case: talk_tts_engine=openai, mode left at
611// auto -- must now resolve to "server", not silently stay "auto".
612prefs = {{talk_tts_engine: "openai"}}; location = {{search: ""}};
613results.push(["persisted-openai", talkTtsMode(), talkTtsEngine()]);
614
615// 3. The exact bug reported live: no persisted settings, only a
616// "?tts=openai" URL override -- must also resolve to "server".
617prefs = {{}}; location = {{search: "?tts=openai"}};
618results.push(["url-override", talkTtsMode(), talkTtsEngine()]);
619
620// 4. Explicit "browser" mode is never overridden by engine choice --
621// it is an unconditional "always the browser's own voice" setting.
622prefs = {{talk_tts: "browser", talk_tts_engine: "openai"}}; location = {{search: ""}};
623results.push(["explicit-browser-mode", talkTtsMode(), talkTtsEngine()]);
624
625console.log(JSON.stringify(results));
626"""
627 probe_path = tmp_path / "talk_tts_mode_probe.js"
628 probe_path.write_text(probe)
629 result = subprocess.run([node, str(probe_path)], capture_output=True, text=True)
630 assert result.returncode == 0, f"node probe failed:\n{result.stderr}"
631 outcomes = dict((row[0], (row[1], row[2])) for row in json.loads(result.stdout))
632
633 assert outcomes["default"] == ("auto", "local")
634 assert outcomes["persisted-openai"] == ("server", "openai")
635 assert outcomes["url-override"] == ("server", "openai")
636 assert outcomes["explicit-browser-mode"] == ("browser", "openai")
637
638
639def test_reader_context_note_grounds_followups_in_real_links(tmp_path):
640 """Behavioral: a real live session hit exactly this -- read_page
641 fetched Techmeme, the model summarized it in prose with no link
642 numbers, and the next turn ("go to that story about Astra") had no
643 real href to resolve against because only the model's own prose
644 survives in conversation history, never a tool's actual result.
645 readerContextNote() re-grounds the NEXT turn in the real (capped)
646 link list from object_ai.py's new tool_calls[].result echo.
647 """
648 node = shutil.which("node")
649 if not node:
650 pytest.skip("node not installed")
651
652 match = re.search(r"function readerContextNote\(\) \{(.*?)\n\}", TALK_SOURCE, re.S)
653 assert match, "readerContextNote() not found in talk.py"
654
655 probe = f"""
656let lastReaderPage = null;
657function readerContextNote() {{{match.group(1)}\n}}
658
659const results = {{}};
660results.noPage = readerContextNote();
661
662lastReaderPage = {{
663 title: "Techmeme", final_url: "https://techmeme.com",
664 links: [
665 {{n: 1, label: "OpenAI announces Astra", href: "https://example.com/astra"}},
666 {{n: 2, label: "Other story", href: "https://example.com/other"}},
667 ],
668}};
669results.withPage = readerContextNote();
670
671lastReaderPage = {{title: "Empty page", final_url: "https://example.com", links: []}};
672results.noLinks = readerContextNote();
673
674console.log(JSON.stringify(results));
675"""
676 probe_path = tmp_path / "reader_context_note_probe.js"
677 probe_path.write_text(probe)
678 result = subprocess.run([node, str(probe_path)], capture_output=True, text=True)
679 assert result.returncode == 0, f"node probe failed:\n{result.stderr}"
680 outcomes = json.loads(result.stdout)
681
682 assert outcomes["noPage"] == ""
683 assert outcomes["noLinks"] == ""
684 assert "Techmeme" in outcomes["withPage"]
685 assert "https://techmeme.com" in outcomes["withPage"]
686 assert "OpenAI announces Astra" in outcomes["withPage"]
687 assert "https://example.com/astra" in outcomes["withPage"]
688 assert "Other story" in outcomes["withPage"]
689
690
691def test_talk_captures_reader_result_and_resets_it_with_session():
692 # The capture: a read_page tool call's echoed result (object_ai.py's
693 # new tool_calls[].result) becomes lastReaderPage for the NEXT turn.
694 assert (
695 'const readerCall = (body.tool_calls || []).find((c) => c.name === "read_page" && c.result);'
696 in TALK_SOURCE
697 )
698 assert "if (readerCall) lastReaderPage = readerCall.result;" in TALK_SOURCE
699
700 # The reset: switching sessions must not carry a PREVIOUS session's
701 # read page into a different conversation's context.
702 reset_sites = [
703 m.start() for m in re.finditer(r"aiHistory = \[\];", TALK_SOURCE)
704 ]
705 # One is the top-level declaration-adjacent initial value; the other
706 # two are the "new session" / "resume a session" handlers, and both
707 # must reset lastReaderPage right alongside aiHistory.
708 assert len(reset_sites) >= 2
709 for site in reset_sites:
710 nearby = TALK_SOURCE[site : site + 120]
711 if TALK_SOURCE[max(0, site - 4) : site] == "let ":
712 continue # the initial declaration, not a reset handler
713 assert "lastReaderPage = null;" in nearby, (
714 f"an aiHistory reset near offset {site} does not also reset lastReaderPage"
715 )
716
717
718def test_talk_page_has_cloud_voice_toggle_button():
719 assert '<button type="button" id="cloudvoice" class="backlink" hidden>cloud voice: off</button>' in TALK_SOURCE
720 assert "#cloudvoice, #headphonestoggle { background: none; border: none;" in TALK_SOURCE
721
722
723def test_talk_init_order_loads_prefs_before_deciding_mic_path():
724 # The real bug this guards: initMic() decides browser-vs-cloud ONCE,
725 # synchronously, at load -- calling it before loadPrefs() resolves
726 # means it always saw the shipped defaults, never the real stored
727 # talk_stt_engine, so settings-based cloud STT could never activate
728 # (only a ?stt= URL override, which doesn't depend on prefs, ever
729 # could). initCloudVoiceToggle() has the identical dependency for its
730 # initial label.
731 assert "loadPrefs().then(() => { initMic(); initCloudVoiceToggle(); initHeadphonesToggle(); });" in TALK_SOURCE
732 assert re.search(r"^initMic\(\);\s*$", TALK_SOURCE, re.M) is None, (
733 "initMic() must not be called standalone before loadPrefs() resolves"
734 )
735
736
737def test_talk_cloud_voice_toggle_resolves_and_saves_both_engines_together(tmp_path):
738 """Behavioral: executes the real resolvedCloudVoiceOn()/initCloudVoiceToggle()
739 functions under node with a fake DOM/fetch, not a source-text match --
740 clicking the toggle must flip BOTH talk_tts_engine and talk_stt_engine
741 together (the whole point is one switch for "this mode", not two
742 settings to remember), persist them via the real savePrefs()/api()
743 call shape, and land on a query-string-free URL afterward so a stale
744 ?stt=/?tts= link can never look like the toggle silently did nothing.
745 """
746 node = shutil.which("node")
747 if not node:
748 pytest.skip("node not installed")
749
750 def extract_function(name):
751 start = TALK_SOURCE.index(f"function {name}(")
752 depth = 0
753 i = TALK_SOURCE.index("{", start)
754 for j in range(i, len(TALK_SOURCE)):
755 if TALK_SOURCE[j] == "{":
756 depth += 1
757 elif TALK_SOURCE[j] == "}":
758 depth -= 1
759 if depth == 0:
760 return TALK_SOURCE[start : j + 1]
761 raise AssertionError(f"unbalanced braces extracting {name}()")
762
763 def extract_async_function(name):
764 start = TALK_SOURCE.index(f"async function {name}(")
765 depth = 0
766 i = TALK_SOURCE.index("{", start)
767 for j in range(i, len(TALK_SOURCE)):
768 if TALK_SOURCE[j] == "{":
769 depth += 1
770 elif TALK_SOURCE[j] == "}":
771 depth -= 1
772 if depth == 0:
773 return TALK_SOURCE[start : j + 1]
774 raise AssertionError(f"unbalanced braces extracting {name}()")
775
776 functions = "\n".join([
777 extract_function("urlOverride"),
778 extract_function("talkTtsEngine"),
779 extract_function("talkSttEngine"),
780 extract_function("resolvedCloudVoiceOn"),
781 extract_async_function("api"),
782 extract_async_function("savePrefs"),
783 extract_function("initCloudVoiceToggle"),
784 ])
785
786 probe = f"""
787const DEFAULT_TALK_TTS_ENGINE = "local";
788const DEFAULT_TALK_STT_ENGINE = "browser";
789const OWNER_ID = "dan";
790let prefs = {{talk_tts_engine: "local", talk_stt_engine: "browser"}};
791let location = {{search: "", pathname: "/talk", href: "/talk"}};
792function pref(name, fallback) {{
793 const v = prefs[name];
794 return v === undefined || v === null ? fallback : v;
795}}
796
797const putCalls = [];
798function fetch(path, opts) {{
799 const body = opts.body ? JSON.parse(opts.body) : undefined;
800 putCalls.push({{method: opts.method, path, body}});
801 return Promise.resolve({{ok: true, json: () => Promise.resolve({{status: "ok"}})}});
802}}
803
804class FakeButton {{
805 constructor() {{ this.hidden = true; this.textContent = ""; this.disabled = false; this._handlers = {{}}; }}
806 addEventListener(name, fn) {{ this._handlers[name] = fn; }}
807 click() {{ return this._handlers["click"](); }}
808}}
809const btn = new FakeButton();
810const document = {{getElementById: (id) => id === "cloudvoice" ? btn : null}};
811
812{functions}
813
814const results = {{}};
815initCloudVoiceToggle();
816results.initialHidden = btn.hidden;
817results.initialText = btn.textContent;
818
819(async () => {{
820 await btn.click();
821 results.afterClickText = btn.textContent;
822 results.putCalls = putCalls;
823 results.finalHref = location.href;
824 results.finalPrefs = prefs;
825 console.log(JSON.stringify(results));
826}})();
827"""
828 probe_path = tmp_path / "talk_cloud_toggle_probe.js"
829 probe_path.write_text(probe)
830 result = subprocess.run([node, str(probe_path)], capture_output=True, text=True)
831 assert result.returncode == 0, f"node probe failed:\n{result.stderr}"
832 outcome = json.loads(result.stdout)
833
834 assert outcome["initialHidden"] is False
835 assert outcome["initialText"] == "cloud voice: off"
836
837 put_calls = outcome["putCalls"]
838 assert len(put_calls) == 1
839 call = put_calls[0]
840 assert call["method"] == "PUT"
841 assert call["path"] == "/collections/shell_preferences/records/dan"
842 # Both engines flip TOGETHER in one call -- not two separate saves a
843 # user could half-apply.
844 assert call["body"] == {"talk_tts_engine": "openai", "talk_stt_engine": "openai"}
845
846 assert outcome["finalPrefs"]["talk_tts_engine"] == "openai"
847 assert outcome["finalPrefs"]["talk_stt_engine"] == "openai"
848 # Lands on a clean, query-string-free URL -- no leftover ?tts=/?stt=
849 # that could make the freshly-saved preference look inert.
850 assert outcome["finalHref"] == "/talk"
851
852
853def test_talk_headphones_mode_pref_defaults_off():
854 fields = {f["name"]: f for f in SHELL_PREFS_SCHEMA["fields"]}
855 assert fields["talk_headphones_mode"]["type"] == "boolean"
856 assert fields["talk_headphones_mode"]["default"] == "false"
857 default_form_fields = SHELL_PREFS_SCHEMA["forms"]["default"]["fields"]
858 assert "talk_headphones_mode" in default_form_fields
859
860 assert 'function talkHeadphonesMode() {' in TALK_SOURCE
861 assert 'String(pref("talk_headphones_mode", "false")).trim() === "true"' in TALK_SOURCE
862
863
864def test_talk_headphones_mode_wired_into_cloud_mic_click_handler():
865 fn = re.search(r"function initCloudMic\(mic\) \{(.*?)\n\}\n", TALK_SOURCE, re.S)
866 assert fn, "initCloudMic() not found in talk.py"
867 body = fn.group(1)
868 assert "if (talkHeadphonesMode()) {" in body
869 assert "if (headphonesArmed) stopHeadphonesMode(mic); else await startHeadphonesMode(mic);" in body
870
871
872def test_talk_headphones_mode_interrupts_speech_not_just_ignores_it():
873 """The one genuinely new behavior versus push-to-talk: real speech
874 detected WHILE the assistant is talking must interrupt it (safe only
875 because headphones mean the mic can't be hearing the assistant's own
876 voice), not be silently dropped or queued."""
877 frame = re.search(r"function frame\(\) \{(.*?)\n \}\n headphonesRafId", TALK_SOURCE, re.S)
878 assert frame, "headphones mode's frame() loop not found in talk.py"
879 body = frame.group(1)
880 assert "if (speaking) stopSpeaking();" in body
881
882
883def test_talk_headphones_mode_rms_matches_the_browser_paths_technique(tmp_path):
884 """Not a shared function (see the comment above headphonesRms in
885 talk.py for why: the browser path's meter is tightly coupled to
886 SpeechRecognition-specific state), but the same amplitude-analysis
887 math -- getByteTimeDomainData -> normalize to [-1, 1] -> RMS."""
888 node = shutil.which("node")
889 if not node:
890 pytest.skip("node not installed")
891
892 match = re.search(r"function headphonesRms\(analyser, data\) \{(.*?)\n\}", TALK_SOURCE, re.S)
893 assert match, "headphonesRms() not found in talk.py"
894
895 probe = f"""
896function headphonesRms(analyser, data) {{{match.group(1)}\n}}
897
898const silent = {{getByteTimeDomainData: (arr) => arr.fill(128)}};
899const loud = {{getByteTimeDomainData: (arr) => {{ for (let i = 0; i < arr.length; i++) arr[i] = i % 2 === 0 ? 0 : 255; }}}};
900
901console.log(JSON.stringify({{
902 silent: headphonesRms(silent, new Uint8Array(8)),
903 loud: headphonesRms(loud, new Uint8Array(8)),
904}}));
905"""
906 probe_path = tmp_path / "rms_probe.js"
907 probe_path.write_text(probe)
908 result = subprocess.run([node, str(probe_path)], capture_output=True, text=True)
909 assert result.returncode == 0, f"node probe failed:\n{result.stderr}"
910 outcome = json.loads(result.stdout)
911 assert outcome["silent"] == 0
912 assert outcome["loud"] > 0.9
913
914
915def test_talk_headphones_mode_resets_alongside_session_switches():
916 # A previous session's live, armed headphones mode must not survive a
917 # session switch -- it holds an open mic stream that belongs to the
918 # conversation that just ended.
919 reset_sites = [
920 m.start() for m in re.finditer(r"lastReaderPage = null;", TALK_SOURCE)
921 ]
922 handler_sites = [
923 site for site in reset_sites
924 if TALK_SOURCE[max(0, site - 4) : site] != "let "
925 ]
926 assert len(handler_sites) >= 2, "expected at least the new-session and resume-session handlers"
927 for site in handler_sites:
928 nearby = TALK_SOURCE[site : site + 200]
929 assert "if (headphonesArmed) stopHeadphonesMode(document.getElementById(\"mic\"));" in nearby
930
931
932def test_talk_page_has_headphones_toggle_button():
933 assert '<button type="button" id="headphonestoggle" class="backlink" hidden>headphones: off</button>' in TALK_SOURCE
934 assert "#cloudvoice, #headphonestoggle { background: none;" in TALK_SOURCE
935
936
937def test_talk_headphones_toggle_hidden_unless_cloud_stt_and_saves_live_without_reload(tmp_path):
938 """Behavioral: unlike the cloud-voice toggle (which reloads, since it
939 changes which mic implementation initMic() wires up), this one must
940 NOT reload -- it only changes behavior read fresh on each tap inside
941 the already-running initCloudMic click handler."""
942 node = shutil.which("node")
943 if not node:
944 pytest.skip("node not installed")
945
946 def extract_function(name):
947 start = TALK_SOURCE.index(f"function {name}(")
948 depth = 0
949 i = TALK_SOURCE.index("{", start)
950 for j in range(i, len(TALK_SOURCE)):
951 if TALK_SOURCE[j] == "{":
952 depth += 1
953 elif TALK_SOURCE[j] == "}":
954 depth -= 1
955 if depth == 0:
956 return TALK_SOURCE[start : j + 1]
957 raise AssertionError(f"unbalanced braces extracting {name}()")
958
959 def extract_async_function(name):
960 start = TALK_SOURCE.index(f"async function {name}(")
961 depth = 0
962 i = TALK_SOURCE.index("{", start)
963 for j in range(i, len(TALK_SOURCE)):
964 if TALK_SOURCE[j] == "{":
965 depth += 1
966 elif TALK_SOURCE[j] == "}":
967 depth -= 1
968 if depth == 0:
969 return TALK_SOURCE[start : j + 1]
970 raise AssertionError(f"unbalanced braces extracting {name}()")
971
972 functions = "\n".join([
973 extract_function("urlOverride"),
974 extract_function("talkSttEngine"),
975 extract_function("talkHeadphonesMode"),
976 extract_async_function("api"),
977 extract_async_function("savePrefs"),
978 extract_function("initHeadphonesToggle"),
979 ])
980
981 probe = f"""
982const DEFAULT_TALK_STT_ENGINE = "browser";
983const OWNER_ID = "dan";
984let prefs = {{talk_stt_engine: "browser"}};
985let location = {{search: ""}};
986function pref(name, fallback) {{
987 const v = prefs[name];
988 return v === undefined || v === null ? fallback : v;
989}}
990const putCalls = [];
991function fetch(path, opts) {{
992 putCalls.push({{path, body: JSON.parse(opts.body)}});
993 return Promise.resolve({{ok: true, json: () => Promise.resolve({{status: "ok"}})}});
994}}
995class FakeButton {{
996 constructor() {{ this.hidden = true; this.textContent = ""; this.disabled = false; this._handlers = {{}}; }}
997 addEventListener(name, fn) {{ this._handlers[name] = fn; }}
998 click() {{ return this._handlers["click"](); }}
999}}
1000const btn = new FakeButton();
1001const document = {{getElementById: (id) => id === "headphonestoggle" ? btn : null}};
1002
1003{functions}
1004
1005const results = {{}};
1006initHeadphonesToggle();
1007results.hiddenWhenBrowserStt = btn.hidden;
1008
1009prefs = {{talk_stt_engine: "openai", talk_headphones_mode: "false"}};
1010initHeadphonesToggle();
1011results.shownWhenCloudStt = btn.hidden;
1012results.initialText = btn.textContent;
1013
1014(async () => {{
1015 await btn.click();
1016 results.afterClickText = btn.textContent;
1017 results.putCalls = putCalls;
1018 results.finalPrefs = prefs;
1019 console.log(JSON.stringify(results));
1020}})();
1021"""
1022 probe_path = tmp_path / "headphones_toggle_probe.js"
1023 probe_path.write_text(probe)
1024 result = subprocess.run([node, str(probe_path)], capture_output=True, text=True)
1025 assert result.returncode == 0, f"node probe failed:\n{result.stderr}"
1026 outcome = json.loads(result.stdout)
1027
1028 assert outcome["hiddenWhenBrowserStt"] is True
1029 assert outcome["shownWhenCloudStt"] is False
1030 assert outcome["initialText"] == "headphones: off"
1031 assert outcome["afterClickText"] == "headphones: on"
1032 assert outcome["putCalls"] == [
1033 {"path": "/collections/shell_preferences/records/dan", "body": {"talk_headphones_mode": "true"}}
1034 ]
1035 assert outcome["finalPrefs"]["talk_headphones_mode"] == "true"
1036
1037
1038def test_talk_stop_speaking_is_shared_by_natural_end_and_interrupt(tmp_path):
1039 """Behavioral: stopSpeaking() must be reachable both as a normal
1040 playback-ended handler AND as a deliberate interrupt call from
1041 outside speak() -- executes the real function under node against a
1042 fake Audio element and fake speechSynthesis.
1043 """
1044 node = shutil.which("node")
1045 if not node:
1046 pytest.skip("node not installed")
1047
1048 def extract_function(name):
1049 start = TALK_SOURCE.index(f"function {name}(")
1050 depth = 0
1051 i = TALK_SOURCE.index("{", start)
1052 for j in range(i, len(TALK_SOURCE)):
1053 if TALK_SOURCE[j] == "{":
1054 depth += 1
1055 elif TALK_SOURCE[j] == "}":
1056 depth -= 1
1057 if depth == 0:
1058 return TALK_SOURCE[start : j + 1]
1059 raise AssertionError(f"unbalanced braces extracting {name}()")
1060
1061 probe = f"""
1062let speaking = true;
1063let currentTtsObjectUrl = "blob:fake-url";
1064let revoked = null;
1065let cancelled = false;
1066let resumeCalled = false;
1067function resumeListeningIfNeeded() {{ resumeCalled = true; }}
1068const URL = {{revokeObjectURL: (u) => {{ revoked = u; }}}};
1069const fakePlayer = {{onended: "x", onerror: "x", onstalled: "x", paused: false, pause() {{ this.paused = true; }}}};
1070function sharedTtsAudio() {{ return fakePlayer; }}
1071const window = {{speechSynthesis: {{cancel: () => {{ cancelled = true; }}}}}};
1072
1073{extract_function("stopSpeaking")}
1074
1075stopSpeaking();
1076console.log(JSON.stringify({{
1077 speaking, revoked, cancelled, resumeCalled,
1078 playerPaused: fakePlayer.paused,
1079 handlersCleared: fakePlayer.onended === null && fakePlayer.onerror === null && fakePlayer.onstalled === null,
1080}}));
1081"""
1082 probe_path = tmp_path / "stop_speaking_probe.js"
1083 probe_path.write_text(probe)
1084 result = subprocess.run([node, str(probe_path)], capture_output=True, text=True)
1085 assert result.returncode == 0, f"node probe failed:\n{result.stderr}"
1086 outcome = json.loads(result.stdout)
1087
1088 assert outcome["speaking"] is False
1089 assert outcome["revoked"] == "blob:fake-url"
1090 assert outcome["cancelled"] is True
1091 assert outcome["resumeCalled"] is True
1092 assert outcome["playerPaused"] is True
1093 assert outcome["handlersCleared"] is True
1094
1095 # Both call sites must actually use it -- a duplicate inline cleanup
1096 # anywhere would mean an interrupt and a natural end could drift apart.
1097 assert "player.onended = stopSpeaking;" in TALK_SOURCE
1098 assert "utter.addEventListener(\"end\", stopSpeaking);" in TALK_SOURCE
1099
1100
1101def test_talk_wake_word_gating_discards_until_heard():
1102 process = re.search(r"function processTranscript\(isFinal\) \{(.*?)\n\}\n", TALK_SOURCE, re.S)
1103 assert process, "processTranscript() not found in talk.py"
1104 body = process.group(1)
1105 assert "if (armed) {" in body
1106 assert "findWakeSplit(combinedRaw, w)" in body
1107 # Nothing found yet -> stays armed and shows the dim hint, does not fold
1108 # into the active buffer.
1109 # Per-event splitting: cumulative interims restate the wake word
1110 # every event, so the split runs every event too (the recorded turn
1111 # "Show me my notes computer show me my notes" is the old behaviour).
1112 assert "if (w && split === null) {" in body
1113 assert "updateCaptionArmed();" in body
1114
1115 armed_caption = re.search(r"function updateCaptionArmed\(\) \{(.*?)\n\}", TALK_SOURCE, re.S)
1116 assert armed_caption
1117 assert "to address me" in armed_caption.group(1)
1118 assert '.add("armed")' in armed_caption.group(1)
1119
1120
1121def test_talk_wake_word_match_is_case_insensitive_word_boundary():
1122 find_split = re.search(r"function findWakeSplit\(text, word\) \{(.*?)\n\}", TALK_SOURCE, re.S)
1123 assert find_split, "findWakeSplit() not found in talk.py"
1124 body = find_split.group(1)
1125 assert ".toLowerCase()" in body
1126 assert "tokenize(text)" in body
1127 # Whole-token compare, not substring -- via matchesWakeWord, which is
1128 # the exact match PLUS a bounded Damerau tolerance ("compture" arrived
1129 # for "computer" and the strict version invisibly discarded everything
1130 # said after it; see tests/test_talk_mobile.py for that contract).
1131 assert "matchesWakeWord(key, target)" in body
1132
1133
1134def test_talk_end_word_tail_match_and_strip():
1135 tail_match = re.search(r"function tailMatchesEndWord\(text, word\) \{(.*?)\n\}", TALK_SOURCE, re.S)
1136 assert tail_match, "tailMatchesEndWord() not found in talk.py"
1137 body = tail_match.group(1)
1138 assert ".toLowerCase()" in body
1139 assert "tokens[tokens.length - 1]" in body # only the tail token
1140 assert "tokens.slice(0, -1).join" in body # strips it from the remainder
1141
1142 word_key = re.search(r"function wordKey\(token\) \{(.*?)\n\}", TALK_SOURCE, re.S)
1143 assert word_key, "wordKey() not found in talk.py"
1144 assert "[.,!?;:]" in word_key.group(1) # tolerant of trailing punctuation
1145
1146 process = re.search(r"function processTranscript\(isFinal\) \{(.*?)\n\}\n", TALK_SOURCE, re.S)
1147 assert process
1148 body = process.group(1)
1149 assert 'endpoint === "word" || endpoint === "silence"' in body
1150 assert "tailMatchesEndWord(active, ew)" in body
1151 assert "finalizeVoiceSubmit(stripped)" in body
1152
1153
1154def test_talk_empty_wake_word_captures_everything():
1155 process = re.search(r"function processTranscript\(isFinal\) \{(.*?)\n\}\n", TALK_SOURCE, re.S)
1156 assert process
1157 body = process.group(1)
1158 assert "armed = false; // empty wake word: capture everything while the mic is on" in body
1159
1160
1161def test_talk_empty_end_word_falls_back_to_debounced_isfinal():
1162 process = re.search(r"function processTranscript\(isFinal\) \{(.*?)\n\}\n", TALK_SOURCE, re.S)
1163 assert process
1164 body = process.group(1)
1165 assert 'endpoint === "word" && !ew' in body
1166 assert "setTimeout(() => {" in body
1167 assert "}, 300);" in body # short: stability endpointing owns the long wait now
1168 assert "finalizeVoiceSubmit(buffer);" in body
1169
1170
1171def test_talk_buffer_cleared_and_rearmed_after_any_submit():
1172 finalize = re.search(r"function finalizeVoiceSubmit\(text\) \{(.*?)\n\}", TALK_SOURCE, re.S)
1173 assert finalize, "finalizeVoiceSubmit() not found in talk.py"
1174 body = finalize.group(1)
1175 assert "resetTalkState();" in body
1176
1177 reset = re.search(r"function resetTalkState\(\) \{(.*?)\n\}", TALK_SOURCE, re.S)
1178 assert reset, "resetTalkState() not found in talk.py"
1179 body = reset.group(1)
1180 assert 'buffer = "";' in body
1181 assert 'sessionLive = "";' in body
1182 assert "armed = true;" in body
1183 assert "clearTimeout(finalDebounceTimer);" in body
1184
1185 # Manual submit also resets before/around submitTurn, per "after any
1186 # submit: clear the buffer and return to armed state".
1187 handler = re.search(
1188 r'document\.getElementById\("prompt"\)\.addEventListener\("submit", \(event\) => \{(.*?)\n\}\);',
1189 TALK_SOURCE,
1190 re.S,
1191 )
1192 assert handler
1193 assert "resetTalkState();" in handler.group(1)
1194
1195
1196def test_talk_manual_submit_bypasses_arming_and_joins_voice_plus_typed():
1197 handler = re.search(
1198 r'document\.getElementById\("prompt"\)\.addEventListener\("submit", \(event\) => \{(.*?)\n\}\);',
1199 TALK_SOURCE,
1200 re.S,
1201 )
1202 assert handler
1203 body = handler.group(1)
1204 assert "const typed = box.value.trim();" in body
1205 assert "const voice = conversationMode ? pendingText() : " in body
1206 assert "[voice, typed].filter(Boolean).join" in body
1207
1208
1209def test_talk_tts_pause_keeps_buffer_from_accumulating_machine_speech():
1210 """Recognition is already stopped for the whole speaking span (asserted
1211 elsewhere); this just confirms the VAD path independently refuses to run
1212 while speaking, since its getUserMedia stream is not gated by the
1213 recognizer's own stop/start."""
1214 vad = re.search(r"function evaluateVAD\(rms, now\) \{(.*?)\n\}", TALK_SOURCE, re.S)
1215 assert vad, "evaluateVAD() not found in talk.py"
1216 assert "if (speaking || !conversationMode) {" in vad.group(1)
1217
1218 meter = re.search(r"function updateMeterVisual\(rms\) \{(.*?)\n\}", TALK_SOURCE, re.S)
1219 assert meter, "updateMeterVisual() not found in talk.py"
1220 assert "speaking ? 0 :" in meter.group(1) # ring idles during playback
1221
1222
1223# --- mic level metering + VAD silence endpointing -------------------------
1224
1225
1226def test_talk_meter_uses_getusermedia_and_analysernode():
1227 start_meter = re.search(r"async function startMeter\(\) \{(.*?)\n\}", TALK_SOURCE, re.S)
1228 assert start_meter, "startMeter() not found in talk.py"
1229 body = start_meter.group(1)
1230 assert "navigator.mediaDevices.getUserMedia({audio: true})" in body
1231 assert "createMediaStreamSource(micStream)" in body
1232 assert "createAnalyser()" in body
1233 assert "requestAnimationFrame(frame)" in body
1234
1235
1236def test_talk_noise_floor_calibration_then_threshold():
1237 start_meter = re.search(r"async function startMeter\(\) \{(.*?)\n\}", TALK_SOURCE, re.S)
1238 assert start_meter
1239 body = start_meter.group(1)
1240 assert "CALIBRATION_MS" in body
1241 assert "calibrationSamples.push(rms)" in body
1242 assert "noiseFloor = avg;" in body
1243 assert "speechThreshold = Math.max(avg * 3, MIN_SPEECH_THRESHOLD);" in body
1244 assert "const CALIBRATION_MS = 800;" in TALK_SOURCE
1245
1246
1247def test_talk_silence_timer_submits_buffer_respecting_wake_gate():
1248 vad = re.search(r"function evaluateVAD\(rms, now\) \{(.*?)\n\}", TALK_SOURCE, re.S)
1249 assert vad
1250 body = vad.group(1)
1251 assert "utteranceStarted" in body
1252 assert "bufferHasContent()" in body
1253 assert "now - silenceStartTs < silenceMs()) return;" in body
1254 assert "if (armed) {" in body
1255 assert "resetTalkState();" in body # discard, not submit, if never woken
1256 assert "finalizeVoiceSubmit(pendingText());" in body # submit once woken
1257
1258
1259def test_talk_meter_stream_released_when_conversation_mode_turns_off():
1260 stop_meter = re.search(r"function stopMeter\(\) \{(.*?)\n\}", TALK_SOURCE, re.S)
1261 assert stop_meter, "stopMeter() not found in talk.py"
1262 body = stop_meter.group(1)
1263 assert "cancelAnimationFrame(meterRafId)" in body
1264 assert "audioCtx.close()" in body
1265 assert "micStream.getTracks().forEach((t) => t.stop())" in body
1266 assert 'ring.hidden = true;' in body # visibly dead -- the privacy indicator
1267
1268 mic_click = re.search(r'mic\.addEventListener\("click", \(\) => \{(.*?)\n \}\);', TALK_SOURCE, re.S)
1269 assert mic_click, "mic click handler not found in talk.py"
1270 body = mic_click.group(1)
1271 # The OFF path must still release the stream from here -- that is what
1272 # this test is for, and the privacy indicator depends on it.
1273 assert "stopMeter();" in body
1274 # The ON path starts the meter AT THE CLICK -- deliberately, again,
1275 # after the deferred design killed desktop endpointing (a meter
1276 # started mid-speech calibrates on the voice itself). The iOS
1277 # exclusive-mic theft is handled by the conviction instead, and the
1278 # conviction flag gates the restart (see tests/test_talk_mobile.py's
1279 # design history note).
1280 assert "startMeter()" in body
1281 assert "!meterContended" in body
1282
1283
1284def test_talk_endpoint_mode_helper_validates_and_defaults():
1285 fn = re.search(r"function endpointMode\(\) \{(.*?)\n\}", TALK_SOURCE, re.S)
1286 assert fn, "endpointMode() not found in talk.py"
1287 body = fn.group(1)
1288 assert '"word"' in body and '"manual"' in body and '"silence"' in body
1289 assert "DEFAULT_ENDPOINT" in body
1290
1291
1292def test_talk_helper_functions_behave_correctly_under_node():
1293 """Behavioral (not just source-string) coverage for the pure word-match
1294 helpers, run against the actual evaluated script when node is available."""
1295 node = shutil.which("node")
1296 if not node:
1297 pytest.skip("node not installed")
1298
1299 html = _render_talk_html()
1300 script = _extract_inline_script(html)
1301 start = script.index("function tokenize(text)")
1302 end = script.index("function resetTalkState()")
1303 helpers = script[start:end]
1304
1305 probe = (
1306 helpers
1307 + "\nconsole.log(JSON.stringify({"
1308 + 'wake: findWakeSplit("hey computer turn on the lights", "computer"),'
1309 + 'noWake: findWakeSplit("turn on the lights", "computer"),'
1310 + 'wakeCasePunct: findWakeSplit("Computer, whats the time", "computer"),'
1311 + 'endStrip: tailMatchesEndWord("turn on the lights over", "over"),'
1312 + 'endStripPunct: tailMatchesEndWord("turn on the lights, over.", "over"),'
1313 + 'noEnd: tailMatchesEndWord("turn on the lights", "over"),'
1314 + "}));\n"
1315 )
1316 result = subprocess.run([node, "-e", probe], capture_output=True, text=True)
1317 assert result.returncode == 0, f"node probe failed:\n{result.stderr}"
1318 out = json.loads(result.stdout)
1319 assert out["wake"] == "turn on the lights"
1320 assert out["noWake"] is None
1321 assert out["wakeCasePunct"] == "whats the time"
1322 assert out["endStrip"] == "turn on the lights"
1323 assert out["endStripPunct"] == "turn on the lights,"
1324 assert out["noEnd"] is None
1325
1326
1327# --- voice engine preference (talk_tts: auto / server / browser) ---------
1328
1329
1330def test_talk_tts_schema_field_added_with_default_auto():
1331 fields = {f["name"]: f for f in SHELL_PREFS_SCHEMA["fields"]}
1332 assert fields["talk_tts"]["type"] == "enum"
1333 assert fields["talk_tts"]["default"] == "auto"
1334 assert set(fields["talk_tts"]["enum"]) == {"auto", "server", "browser"}
1335 assert "talk_tts" in SHELL_PREFS_SCHEMA["forms"]["default"]["fields"]
1336
1337 # Client-side defaults mirror the schema default in both objects.
1338 assert 'talk_tts: "auto"' in TALK_SOURCE
1339 assert 'talk_tts: "auto"' in SHELL_SOURCE
1340
1341
1342def test_talk_speak_routes_by_talk_tts_preference():
1343 fn = re.search(r"async function speak\(text\) \{(.*?)\n\}\n", TALK_SOURCE, re.S)
1344 assert fn, "speak() not found in talk.py"
1345 body = fn.group(1)
1346 assert "talkTtsMode()" in body
1347 assert 'mode === "browser"' in body
1348 assert 'mode === "auto" && window.speechSynthesis && hasLocalVoice()' in body
1349 assert "speakBrowser(spoken)" in body
1350 # "server" (and "auto" without a local voice) keep the original POST
1351 # /api/tts-first, speechSynthesis-fallback behavior.
1352 assert '/api/tts' in body
1353 assert "catch (e) {" in body
1354
1355 mode_fn = re.search(r"function talkTtsMode\(\) \{(.*?)\n\}", TALK_SOURCE, re.S)
1356 assert mode_fn, "talkTtsMode() not found in talk.py"
1357 assert '"server"' in mode_fn.group(1) and '"browser"' in mode_fn.group(1)
1358 assert "DEFAULT_TALK_TTS" in mode_fn.group(1)
1359 assert 'const DEFAULT_TALK_TTS = "auto";' in TALK_SOURCE
1360
1361
1362def test_talk_speak_browser_sets_and_clears_speaking_flag():
1363 """The browser-voice path must uphold the same recognition-pause
1364 contract as the server path: set `speaking` and stop listening before
1365 the utterance, clear it and resume only once the utterance ends."""
1366 fn = re.search(r"async function speakBrowser\(text\) \{(.*?)\n\}\n", TALK_SOURCE, re.S)
1367 assert fn, "speakBrowser() not found in talk.py"
1368 body = fn.group(1)
1369 assert "speaking = true;" in body
1370 # Awaits the real mic release, same as the server-TTS path, and for
1371 # the same iOS shared-audio-session reason.
1372 assert "await stopListeningAndWaitForRelease();" in body
1373 assert "speaking = false; resumeListeningIfNeeded();" in body
1374 assert body.index("speaking = true;") < body.index("window.speechSynthesis.speak(utter);")
1375 assert "utter.addEventListener(\"end\"," in body
1376
1377 # "browser" mode, the "auto"-with-a-local-voice shortcut, and the
1378 # server-mode fallback all funnel through this one function -- no
1379 # separate untracked speechSynthesis path.
1380 speak_fn = re.search(r"async function speak\(text\) \{(.*?)\n\}\n", TALK_SOURCE, re.S)
1381 assert speak_fn
1382 assert speak_fn.group(1).count("speakBrowser(spoken)") == 3
1383
1384
1385def test_talk_pick_voice_prefers_named_then_local_english_else_default():
1386 assert "const PREFERRED_VOICE_RE = /Samantha|Ava|Karen|Daniel/;" in TALK_SOURCE
1387
1388 fn = re.search(r"function pickVoice\(\) \{(.*?)\n\}", TALK_SOURCE, re.S)
1389 assert fn, "pickVoice() not found in talk.py"
1390 body = fn.group(1)
1391 assert "PREFERRED_VOICE_RE.test(v.name)" in body
1392 assert "v.localService && /^en/i.test(v.lang)" in body
1393 assert "return localEn || null;" in body
1394
1395 has_local = re.search(r"function hasLocalVoice\(\) \{(.*?)\n\}", TALK_SOURCE, re.S)
1396 assert has_local, "hasLocalVoice() not found in talk.py"
1397 assert "v.localService" in has_local.group(1)
1398
1399
1400def test_talk_voice_picking_behaves_correctly_under_node(tmp_path):
1401 node = shutil.which("node")
1402 if not node:
1403 pytest.skip("node not installed")
1404
1405 html = _render_talk_html()
1406 script = _extract_inline_script(html)
1407 start = script.index("const PREFERRED_VOICE_RE")
1408 end = script.index("async function speakBrowser(text)")
1409 helpers = script[start:end]
1410
1411 probe = (
1412 "let voicesFixture = [];\n"
1413 "const window = {speechSynthesis: {getVoices: () => voicesFixture}};\n"
1414 + helpers
1415 + "\n"
1416 "voicesFixture = [\n"
1417 " {name: 'Generic Voice', lang: 'en-US', localService: true},\n"
1418 " {name: 'Karen', lang: 'en-AU', localService: true},\n"
1419 "];\n"
1420 "const named = pickVoice();\n"
1421 "voicesFixture = [{name: 'Generic Voice', lang: 'en-US', localService: true}];\n"
1422 "const localEn = pickVoice();\n"
1423 "voicesFixture = [{name: 'Generic Voice', lang: 'fr-FR', localService: false}];\n"
1424 "const none = pickVoice();\n"
1425 "voicesFixture = [{name: 'Generic Voice', lang: 'en-US', localService: true}];\n"
1426 "const anyLocalTrue = hasLocalVoice();\n"
1427 "voicesFixture = [];\n"
1428 "const anyLocalFalse = hasLocalVoice();\n"
1429 "console.log(JSON.stringify({\n"
1430 " named: named && named.name,\n"
1431 " localEn: localEn && localEn.name,\n"
1432 " none,\n"
1433 " anyLocalTrue,\n"
1434 " anyLocalFalse,\n"
1435 "}));\n"
1436 )
1437 probe_path = tmp_path / "voice_probe.js"
1438 probe_path.write_text(probe)
1439 result = subprocess.run([node, str(probe_path)], capture_output=True, text=True)
1440 assert result.returncode == 0, f"node probe failed:\n{result.stderr}"
1441 out = json.loads(result.stdout)
1442 assert out["named"] == "Karen"
1443 assert out["localEn"] == "Generic Voice"
1444 assert out["none"] is None
1445 assert out["anyLocalTrue"] is True
1446 assert out["anyLocalFalse"] is False
1447
1448
1449def test_shell_speak_routes_by_talk_tts_preference():
1450 fn = re.search(r"async function speak\(text\) \{(.*?)\n\}\n", SHELL_SOURCE, re.S)
1451 assert fn, "speak() not found in shell.py"
1452 body = fn.group(1)
1453 assert "talkTtsMode()" in body
1454 assert 'mode === "browser"' in body
1455 assert 'mode === "auto" && window.speechSynthesis && hasLocalVoice()' in body
1456 assert "speakBrowser(spoken)" in body
1457 assert '/api/tts' in body
1458 assert "catch (e) {" in body
1459
1460 assert "function talkTtsMode() {" in SHELL_SOURCE
1461 assert "function speakBrowser(text) {" in SHELL_SOURCE
1462 assert "function pickVoice() {" in SHELL_SOURCE
1463 assert "function hasLocalVoice() {" in SHELL_SOURCE
1464 assert "const PREFERRED_VOICE_RE = /Samantha|Ava|Karen|Daniel/;" in SHELL_SOURCE
1465 assert 'const DEFAULT_TALK_TTS = "auto";' in SHELL_SOURCE