diff --git a/docs/factory-report-feature-hook-returns-1.md b/docs/factory-report-feature-hook-returns-1.md new file mode 100644 index 0000000..cc59af2 --- /dev/null +++ b/docs/factory-report-feature-hook-returns-1.md @@ -0,0 +1,82 @@ +# Factory report: every hook returns a string + +- Work file: `docs/hook-returns-plan.md` +- Branch: `feature/hook-returns`, cut from `chore/pythonic-meditations-1` at `6b942e3` +- Reviews: 1. Adversary: sol. + +## Where the plan and the repo differed + +- The plan says to delete the drafts `hook_message_2` and `report_2`. Neither exists in `lifecycle.py`, so there was nothing to delete. +- The plan says the files in `examples/` need no change. Five of them returned `None` on some paths, so fixing them was added as work item 4. + +## Work items + +1. **`lifecycle.py` and `server.py`** (`b66f2f9`): `call`, `fire`, `fire_error` and `report` follow the plan's sketch. `Hook` is `Callable[..., str]`. `fire_done` and `hook_message` are deleted. `after_reply` runs `on_done` through `fire`. +2. **Tests** (`b66f2f9`, with item 1 because the suite cannot pass in between): the plan's test changes and new tests, plus a test that `""` from `on_done` stops the later `on_done` hooks. +3. **Docs** (`b8a80fd`): `docs/hooks.md` tables, the six recipes and the `on_error` section, and `sidecar/README.md`. One sentence was added to `docs/hooks.md`: `""` from `on_done` stops only the later `on_done` hooks. +4. **Examples** (`d231ef6`): `ask.py`, `terminal.py`, `translate.py`, `talk_like_a_pirate.py` and `voice_commands.py` return a str on every path. Where a hook returned `None` it now returns the text it was given. + +## Review 1: trimmed list (`6b942e3..d231ef6`) + +### Fix + +None. + +### Nit + +1. **`terminal.py` docstrings say "shell", the code matches "terminal"** + - Where: `examples/terminal.py:1` and `:19`. + - Problem: both docstrings tell the user to start with "shell", but `PREFIX` matches `terminal\b` and `examples/README.md` says "Terminal, ...". It predates this diff, in a file the diff touches. + - Fix: change "shell" to "terminal" in both docstrings. + - Confidence: high. + +2. **Nested call in `fire_error` breaks the one-job-per-line rule** + - Where: `sidecar/src/kiku_sidecar/lifecycle.py:123`. + - Problem: `message = one_line(call("on_error", path, hook, e, message))` reads from the inside out, against `docs/pythonic.md`. The line is verbatim from the plan's sketch; the repo rule outranks the sketch. + - Fix: inside the `try`, `returned = call("on_error", path, hook, e, message)`, then `message = one_line(returned)`. + - Confidence: high. + +3. **`test_on_done_returning_empty_stops_the_later_on_done` cannot tell a stop from a failure** + - Where: `sidecar/tests/test_server.py:417`. + - Problem: it asserts only that the last recorded call is `on_sent`, which would also pass if `on_done` raised. + - Fix: keep the response and assert status 200, that log.txt holds the text, and `errors(tmp_path) == []`. + - Confidence: high. + +### Wontfix + +- **An `on_error` hook that does `raise e` adds its note to the shared exception, so later `on_error` hooks see `on_error in a.py:2` as the last note.** The base commit behaved the same way, the plan's criterion (the reported message is unchanged) is met and tested, and a working fix adds a special case to a function the plan wants simple. +- **Whitespace-only text stops `after_reply` but not `fire` or `process`.** It predates the diff, the line is untouched, and the plan's rule is `""`. +- **No upgrade note in the docs.** The plan lists no upgrade section; "release notes" means the GitHub release text. Kept as an open item below. +- **No test that every recipe returns a str on every path.** The recipes do return a str on every path. Calling them from tests would write to `~/Documents/Dictations.txt` and open a network connection unless mocked, and one sample would not cover every path. +- **Split `Hook` into `TextHook` and `ErrorHook`.** The plan asks for `Callable[..., str]`. + +### Split + +None. + +### Counts + +8 candidates, 3 kept (0 fix, 3 nit). Adversary: sol. One exchange, covering four candidates; sol backed the filter agent's verdict on all four. + +## Fix pass 1 + +The implementer folded in all three nits with no pushback. + +1. `f9c7e83`: both docstrings in `examples/terminal.py` say "terminal". +2. `0b8d1cc`: `fire_error` names the hook's return before passing it to `one_line`. +3. `bd71806`: the `on_done` test also asserts status 200, the log entry and an empty errors.txt. + +## Open items + +- **Release notes.** Both breaks need to go in the next GitHub release: a text hook that returns nothing now fails the dictation (fix: `return t`), and an `on_error(e)` hook is skipped and recorded until it becomes `on_error(e, message)` and returns `message`. +- **`raise e` inside an `on_error` hook** adds an `on_error in ` note to the original exception, so a later `on_error` hook reads that as the last note. Left as it was before this branch. +- **Whitespace-only text** stops `after_reply` but not `fire` or `process`. Left as it was before this branch. +- `docs/hook-returns-plan.md` is untracked in the worktree and was not committed. + +## Checks + +Run in `sidecar/` at `bd71806`: + +- `uv run python -m pytest -q`: 107 passed (99 at the base). +- `uv run python -m pyright`: 0 errors. +- `uv run ruff check`: all checks passed. diff --git a/docs/hooks.md b/docs/hooks.md index af6823c..ddae2ca 100644 --- a/docs/hooks.md +++ b/docs/hooks.md @@ -29,19 +29,18 @@ Kiku Flow loads every `*.py` file in that folder. A build from source links the | `on_transcribed(t)` | after speech recognition | what you said | the text the cleanup model sees | | `on_cleaned(t)` | after the cleanup model | the cleaned text | the text that is pasted | | `on_sent(t)` | once the text has gone off to be pasted | the pasted text | the log entry | -| `on_done(t)` | after the log entry is written | the log entry | nothing; the return is ignored | -| `on_error(e)` | after a failure | the exception | the message shown and kept | +| `on_done(t)` | after the log entry is written | the log entry | the text the next `on_done` hook gets | +| `on_error(e, message)` | after a failure | the exception and the message so far | the message shown and kept | -The first three are the text hooks, and a return from one means: +The first four are the text hooks, and a return from one means: | Return | Effect | | --- | --- | -| a string | It replaces the text. | -| `None`, or no return at all | The text stays as it was. | +| a string | It replaces the text. To change nothing, return `t`. | | `""` | The dictation stops there. | -| anything else | A `TypeError`, treated like any other [failure](#when-a-hook-fails). | +| anything else, `None` or no return at all included | A `TypeError`, treated like any other [failure](#when-a-hook-fails). | -Stopping in `on_transcribed` or `on_cleaned` means nothing is pasted and nothing is logged. By `on_sent` the paste has already happened, so `""` there only keeps the dictation out of the log, and `on_done` doesn't fire. +Stopping in `on_transcribed` or `on_cleaned` means nothing is pasted and nothing is logged. By `on_sent` the paste has already happened, so `""` there only keeps the dictation out of the log, and `on_done` doesn't fire. `""` from `on_done` only means the later `on_done` hooks don't fire. If you said nothing, no hooks fire. @@ -99,12 +98,14 @@ raw = "" def on_transcribed(t): global raw raw = t + return t def on_cleaned(t): first, _, rest = raw.partition(" ") if first.strip(",.").lower() == "verbatim": return rest + return t ``` ### Choose what goes in the log @@ -118,6 +119,7 @@ raw = "" def on_transcribed(t): global raw raw = t + return t def on_sent(t): @@ -143,6 +145,7 @@ import re def on_sent(t): if re.match(r"private\b", t, re.IGNORECASE): return "" + return t ``` ### Keep your own archive @@ -159,6 +162,7 @@ ARCHIVE = Path.home() / "Documents/Dictations.txt" def on_done(t): with ARCHIVE.open("a", encoding="utf-8") as f: f.write(f"{datetime.now():%Y-%m-%d %H:%M} {' '.join(t.split())}\n") + return t ``` ## When a hook fails @@ -171,7 +175,7 @@ A hook that raises stops the dictation, and nothing after it runs. The message g If the failure came before the paste, the HUD shows the message too and nothing is pasted. -So a hook that calls something that can fail should catch its own errors and return `None`, which keeps the dictation. `polish.py` sends the cleaned text to a service of yours and pastes it unpolished when the service doesn't answer. +So a hook that calls something that can fail should catch its own errors and return the text it was given, which keeps the dictation. `polish.py` sends the cleaned text to a service of yours and pastes it unpolished when the service doesn't answer. ```python import json @@ -186,27 +190,29 @@ def on_cleaned(t): with urllib.request.urlopen(request, timeout=5) as response: return json.load(response)["text"] except OSError: - return None + return t ``` ## on_error -`on_error(e)` gets the exception from any failure in a dictation: a hook, speech recognition, the cleanup model or the log write. `e.__notes__[-1]` says which, as `on_cleaned in voice.py:3`, `speech recognition`, `cleanup model` or `log write`. +`on_error(e, message)` gets the exception from any failure in a dictation: a hook, speech recognition, the cleanup model or the log write. `e.__notes__[-1]` says which, as `on_cleaned in voice.py:3`, `speech recognition`, `cleanup model` or `log write`. + +It also gets the message so far. The first `on_error` hook gets the default message, such as `on_cleaned in voice.py:3: KeyError: 'x'`. | Return | Effect | | --- | --- | -| a string | It is the message, in the HUD and in `errors.txt`. | -| `None`, or no return at all | The default message is used. | +| a string | It is the message, in the HUD and in `errors.txt`. To change nothing, return `message`. | | `""` | No message: nothing in the HUD, nothing in `errors.txt`. | -`on_error` hooks run in filename order and the first to return a string decides. One that raises is skipped, and its own failure goes in `errors.txt`. +`on_error` hooks run in filename order, each getting the message the one before it returned, and the last one's return is the message. After `""`, no later `on_error` hook runs. One that raises, or returns anything but a string, is skipped, and its own failure goes in `errors.txt`. `offline.py` keeps network failures out of `errors.txt`, for a hook that posts somewhere and doesn't catch its own errors. `urllib` wraps the `ConnectionError` in `e.reason`. Before the paste this is a silent failure: nothing is pasted and nothing says why. ```python -def on_error(e): +def on_error(e, message): if isinstance(getattr(e, "reason", e), ConnectionError): return "" + return message ``` Two failures never reach `on_error`: the models or a hook file failing to load, and the engine crashing. Both go in `errors.txt`, a run of crashes once. diff --git a/examples/ask.py b/examples/ask.py index 4b5f781..77b6f1a 100644 --- a/examples/ask.py +++ b/examples/ask.py @@ -17,15 +17,16 @@ def on_transcribed(t): global asking said = PREFIX.match(t) asking = bool(said) - return said and said[1] + return said[1] if said else t def on_cleaned(t): if not asking: - return None + return t chat = tokenizer.apply_chat_template( [{"role": "system", "content": PROMPT}, {"role": "user", "content": t}], add_generation_prompt=True, tokenize=False, ) - return generate(model, tokenizer, chat, max_tokens=256).strip() or None + reply = generate(model, tokenizer, chat, max_tokens=256).strip() + return reply or t diff --git a/examples/talk_like_a_pirate.py b/examples/talk_like_a_pirate.py index db92ae2..44aa1b7 100644 --- a/examples/talk_like_a_pirate.py +++ b/examples/talk_like_a_pirate.py @@ -18,4 +18,5 @@ def on_cleaned(t): tokenize=False, ) max_tokens = 4 * len(tokenizer.encode(t)) + 64 - return generate(model, tokenizer, chat, max_tokens=max_tokens).strip() or None + pirate = generate(model, tokenizer, chat, max_tokens=max_tokens).strip() + return pirate or t diff --git a/examples/terminal.py b/examples/terminal.py index b4610d2..ed0c526 100644 --- a/examples/terminal.py +++ b/examples/terminal.py @@ -1,4 +1,4 @@ -"""Start with "shell" and the command that does what you said is pasted. It is never run.""" +"""Start with "terminal" and the command that does what you said is pasted. It is never run.""" import re @@ -16,19 +16,20 @@ def on_transcribed(t): - """Take "shell" off the front, so the cleanup model sees only the request.""" + """Take "terminal" off the front, so the cleanup model sees only the request.""" global wanted said = PREFIX.match(t) wanted = bool(said) - return said and said[1] + return said[1] if said else t def on_cleaned(t): if not wanted: - return None + return t chat = tokenizer.apply_chat_template( [{"role": "system", "content": PROMPT}, {"role": "user", "content": t}], add_generation_prompt=True, tokenize=False, ) - return generate(model, tokenizer, chat, max_tokens=128).strip() or None + reply = generate(model, tokenizer, chat, max_tokens=128).strip() + return reply or t diff --git a/examples/translate.py b/examples/translate.py index 25dd79e..d660099 100644 --- a/examples/translate.py +++ b/examples/translate.py @@ -21,16 +21,17 @@ def on_transcribed(t): global language said = PREFIX.match(t) language = said and said[1] - return said and said[2] + return said[2] if said else t def on_cleaned(t): if not language: - return None + return t chat = tokenizer.apply_chat_template( [{"role": "system", "content": PROMPT.format(language)}, {"role": "user", "content": t}], add_generation_prompt=True, tokenize=False, ) max_tokens = 4 * len(tokenizer.encode(t)) + 64 - return generate(model, tokenizer, chat, max_tokens=max_tokens).strip() or None + translation = generate(model, tokenizer, chat, max_tokens=max_tokens).strip() + return translation or t diff --git a/examples/voice_commands.py b/examples/voice_commands.py index 8f206c6..d65bec2 100644 --- a/examples/voice_commands.py +++ b/examples/voice_commands.py @@ -18,7 +18,7 @@ def on_transcribed(t): said = PREFIX.match(t) if not said: - return None + return t name = said[1].lower() if name.startswith("open "): argv = ["open", "-a", name.removeprefix("open ")] diff --git a/sidecar/README.md b/sidecar/README.md index 178adfc..820d341 100644 --- a/sidecar/README.md +++ b/sidecar/README.md @@ -50,9 +50,9 @@ Response: `clean` equals `raw` when the cleanup output is empty or nothing was said, unless a hook changed it. Audio under 0.1 s returns empty strings. Paste `clean`. -Four lifecycle hooks take the text as a plain string and return the text for the next phase: `on_transcribed` after speech recognition (the cleanup model gets its result), `on_cleaned` after the cleanup stage (`clean` is its result), then, once the response has been sent, `on_sent` (the log gets its result), the log and `on_done`. Those three do not delay the reply, but they run on the model thread, so a slow hook holds up the next dictation. `raw` is always the speech recognition output. Once the text is empty, nothing further runs, the log included. The log is always written, by the sidecar itself: the last 100 texts in `~/Library/Application Support/KikuFlow/log.txt`, newest first, one line each. Hook files are the `*.py` files in `~/Library/Application Support/KikuFlow/hooks/`, which a build from source links to `hooks/` in the repo unless the folder is already there. They load before the models, and one that fails to import fails the load. Examples: `docs/hooks.md`. +Four lifecycle hooks take the text as a plain string and return the text for the next step: `on_transcribed` after speech recognition (the cleanup model gets its result), `on_cleaned` after the cleanup stage (`clean` is its result), then, once the response has been sent, `on_sent` (the log gets its result), the log and `on_done` (the next `on_done` hook gets its result). Those three do not delay the reply, but they run on the model thread, so a slow hook holds up the next dictation. `raw` is always the speech recognition output. Once the text is empty, nothing further runs, the log included. The log is always written, by the sidecar itself: the last 100 texts in `~/Library/Application Support/KikuFlow/log.txt`, newest first, one line each. Hook files are the `*.py` files in `~/Library/Application Support/KikuFlow/hooks/`, which a build from source links to `hooks/` in the repo unless the folder is already there. They load before the models, and one that fails to import fails the load. Examples: `docs/hooks.md`. -An exception from speech recognition, the cleanup model, a hook or the log write is not caught and carried on: nothing after it runs. The sidecar adds a note to it naming where it came from (`speech recognition`, `cleanup model`, `log write`, or the hook as `on_cleaned in voice.py:3`) and the default message is `on_cleaned in voice.py:3: KeyError: 'x'`, on one line. A hook that returns neither a string nor `None` raises `TypeError: on_cleaned returned dict, not str or None`. `on_error(e)` hooks get the exception, in filename order; the first that returns a string decides the message, `""` means none, and one that raises is skipped and recorded under its own default message. The message goes into `~/Library/Application Support/KikuFlow/errors.txt`, the last 50, newest first, with the time in front, and the traceback to stderr. The app keeps stderr in `sidecar.log` beside it and empties that file when it starts. A failure after the response goes nowhere else. A model-load failure skips `on_error` and always goes into errors.txt. +An exception from speech recognition, the cleanup model, a hook or the log write is not caught and carried on: nothing after it runs. The sidecar adds a note to it naming where it came from (`speech recognition`, `cleanup model`, `log write`, or the hook as `on_cleaned in voice.py:3`) and the default message is `on_cleaned in voice.py:3: KeyError: 'x'`, on one line. A hook that does not return a string, `None` included, raises `TypeError: on_cleaned returned NoneType, not str`. `on_error(e, message)` hooks get the exception and the message, in filename order: the first gets the default message, each later one gets what the one before returned, and the last one's return is the message. `""` means none and stops the chain, and one that raises or does not return a string is skipped and recorded under its own default message. The message goes into `~/Library/Application Support/KikuFlow/errors.txt`, the last 50, newest first, with the time in front, and the traceback to stderr. The app keeps stderr in `sidecar.log` beside it and empties that file when it starts. A failure after the response goes nowhere else. A model-load failure skips `on_error` and always goes into errors.txt. Errors: `400` malformed audio; `500` a failure before the response, with the message as `detail` (`""` when `on_error` returned `""`); `503` models not loaded (`detail` holds the reason). Requests are processed one at a time; one sent while models load waits for them. diff --git a/sidecar/src/kiku_sidecar/lifecycle.py b/sidecar/src/kiku_sidecar/lifecycle.py index fd743e2..74cf719 100644 --- a/sidecar/src/kiku_sidecar/lifecycle.py +++ b/sidecar/src/kiku_sidecar/lifecycle.py @@ -7,7 +7,6 @@ from contextlib import contextmanager from datetime import datetime from pathlib import Path -from typing import Any from .config import APP_DIR @@ -18,7 +17,7 @@ LOG_FILE = APP_DIR / "log.txt" ERRORS = APP_DIR / "errors.txt" -type Hook = Callable[[Any], str | None] +type Hook = Callable[..., str] type Hooks = dict[str, list[tuple[Path, Hook]]] @@ -94,12 +93,12 @@ def load_hooks(directory: Path) -> Hooks: return hooks -def call(point: str, path: Path, hook: Hook, arg: str | Exception) -> str | None: - """Call `hook(arg)` and label any failure, including a return that is not str or None.""" +def call(point: str, path: Path, hook: Hook, *args: str | Exception) -> str: + """Call `hook(*args)` and label any failure, including a return that is not a str.""" try: - result = hook(arg) - if result is not None and not isinstance(result, str): - raise TypeError(f"{point} returned {type(result).__name__}, not str or None") + result = hook(*args) + if not isinstance(result, str): + raise TypeError(f"{point} returned {type(result).__name__}, not str") except Exception as e: e.add_note(hook_label(point, path, e)) raise @@ -107,43 +106,32 @@ def call(point: str, path: Path, hook: Hook, arg: str | Exception) -> str | None def fire(hooks: Hooks, point: str, text: str) -> str: - """Run the hooks for `point` in order while there is text. A returned str replaces it.""" + """Pipe `text` through the hooks for `point` in order, while there is text.""" for path, hook in hooks[point]: if not text: break - next_text = call(point, path, hook, text) - if next_text is not None: - text = next_text + text = call(point, path, hook, text) return text -def fire_done(hooks: Hooks, text: str) -> None: - """Run every on_done hook with `text`. What a hook returns changes nothing.""" - for path, hook in hooks["on_done"]: - call("on_done", path, hook, text) - - -def hook_message(hooks: Hooks, e: Exception) -> str | None: - """Return the first str from an on_error hook for `e`. A failed hook is recorded and skipped.""" +def fire_error(hooks: Hooks, e: Exception, message: str) -> str: + """Pipe `message` through the on_error hooks. A failed hook is recorded and skipped.""" for path, hook in hooks["on_error"]: + if not message: + break try: - message = call("on_error", path, hook, e) + returned = call("on_error", path, hook, e, message) + message = one_line(returned) except Exception as failure: log.error("on_error hook failed", exc_info=failure) write_error(default_message(failure)) - continue - if message is not None: - return one_line(message) - return None + return message def report(hooks: Hooks, e: Exception) -> str: """Write the message for `e` to errors.txt, unless it is empty, and return it.""" log.error("dictation failed", exc_info=e) - default = default_message(e) - message = hook_message(hooks, e) - if message is None: - message = default + message = fire_error(hooks, e, default_message(e)) if message: write_error(message) return message diff --git a/sidecar/src/kiku_sidecar/server.py b/sidecar/src/kiku_sidecar/server.py index 0bb946d..66c5c9a 100644 --- a/sidecar/src/kiku_sidecar/server.py +++ b/sidecar/src/kiku_sidecar/server.py @@ -24,7 +24,6 @@ Hooks, default_message, fire, - fire_done, labelled, load_hooks, report, @@ -144,7 +143,7 @@ def after_reply(hooks: Hooks, text: str) -> None: return with labelled("log write"): write_log(text) - fire_done(hooks, text) + fire(hooks, "on_done", text) except Exception as e: report(hooks, e) diff --git a/sidecar/tests/test_lifecycle.py b/sidecar/tests/test_lifecycle.py index 5498ece..b0b225b 100644 --- a/sidecar/tests/test_lifecycle.py +++ b/sidecar/tests/test_lifecycle.py @@ -7,7 +7,6 @@ POINTS, default_message, fire, - fire_done, labelled, load_hooks, report, @@ -29,6 +28,7 @@ def write(path: Path, source: str) -> Path: def on_transcribed(t): global raw raw = t + return t def on_cleaned(t): return raw @@ -37,7 +37,7 @@ def on_cleaned(t): def test_loads_hooks_in_filename_order(tmp_path: Path): write(tmp_path / "b.py", "def on_cleaned(t): return t + ' b'") - write(tmp_path / "a.py", "def on_cleaned(t): return t + ' a'\ndef on_done(t): pass") + write(tmp_path / "a.py", "def on_cleaned(t): return t + ' a'\ndef on_done(t): return t") hooks = load_hooks(tmp_path) assert [len(hooks[p]) for p in POINTS] == [0, 2, 0, 1] assert fire(hooks, "on_cleaned", "hello") == "hello a b" @@ -56,11 +56,21 @@ def test_file_failing_to_import_raises_labelled(tmp_path: Path): ) -def test_returned_str_replaces_the_text_and_none_keeps_it(): - hooks = {"on_cleaned": [(HERE, lambda t: "shouted " + t.upper()), (HERE, lambda t: None)]} +def test_returned_str_replaces_the_text(): + hooks = {"on_cleaned": [(HERE, lambda t: "shouted " + t.upper())]} assert fire(hooks, "on_cleaned", "hello") == "shouted HELLO" +@pytest.mark.parametrize("point", POINTS) +def test_hook_returning_none_raises_labelled(tmp_path: Path, point: str): + write(tmp_path / "a.py", f"def {point}(t):\n t.upper()\n") + with pytest.raises(TypeError) as info: + fire(load_hooks(tmp_path), point, "hello") + assert default_message(info.value) == ( + f"{point} in a.py: TypeError: {point} returned NoneType, not str" + ) + + def test_hook_file_keeps_state_between_its_hooks(tmp_path: Path): write(tmp_path / "a.py", STATEFUL) hooks = load_hooks(tmp_path) @@ -68,18 +78,16 @@ def test_hook_file_keeps_state_between_its_hooks(tmp_path: Path): assert fire(hooks, "on_cleaned", "Hello.") == "um hello" -def test_on_done_return_values_are_ignored(): +def test_failing_hook_raises_labelled_and_later_hooks_do_not_run(tmp_path: Path): calls = [] - hooks = {"on_done": [(HERE, lambda t: ""), (HERE, calls.append)]} - fire_done(hooks, "hello") - assert calls == ["hello"] + def later(t: str) -> str: + calls.append(t) + return t -def test_failing_hook_raises_labelled_and_later_hooks_do_not_run(tmp_path: Path): - calls = [] write(tmp_path / "voice.py", "def on_cleaned(t):\n return {}['x']\n") hooks = load_hooks(tmp_path) - hooks["on_cleaned"].append((HERE, calls.append)) + hooks["on_cleaned"].append((HERE, later)) with pytest.raises(KeyError) as info: fire(hooks, "on_cleaned", "hello") assert info.value.__notes__ == ["on_cleaned in voice.py:2"] @@ -142,31 +150,55 @@ def labelled_error() -> KeyError: def test_on_error_loads_beside_the_text_hooks(tmp_path: Path, errors: Path): - write(tmp_path / "errors.py", "def on_error(e): return 'nope'") + write(tmp_path / "errors.py", "def on_error(e, message): return 'nope'") hooks = load_hooks(tmp_path) assert [path.name for path, _ in hooks["on_error"]] == ["errors.py"] assert report(hooks, labelled_error()) == "nope" -def test_first_str_from_on_error_wins(tmp_path: Path, errors: Path): - write(tmp_path / "a.py", "def on_error(e): return None") - write(tmp_path / "b.py", "def on_error(e):\n return f'first:\\n {type(e).__name__}'") - write(tmp_path / "c.py", "def on_error(e): return 'second'") - assert report(load_hooks(tmp_path), labelled_error()) == "first: KeyError" - assert entries(errors) == ["first: KeyError"] +def test_each_on_error_gets_the_message_from_the_one_before(tmp_path: Path, errors: Path): + write( + tmp_path / "a.py", "def on_error(e, message):\n return f'first:\\n {type(e).__name__}'" + ) + write(tmp_path / "b.py", "def on_error(e, message): return message + ', then second'") + assert report(load_hooks(tmp_path), labelled_error()) == "first: KeyError, then second" + assert entries(errors) == ["first: KeyError, then second"] -def test_on_error_returning_none_or_nothing_gives_the_default(tmp_path: Path, errors: Path): - write(tmp_path / "a.py", "def on_error(e): pass") +def test_on_error_returning_its_message_gives_the_default(tmp_path: Path, errors: Path): + write(tmp_path / "a.py", "def on_error(e, message): return message") expected = "on_cleaned in voice.py:3: KeyError: 'x'" assert report(load_hooks(tmp_path), labelled_error()) == expected assert report(load_hooks(tmp_path / "missing"), labelled_error()) == expected assert entries(errors) == [expected, expected] +def test_on_error_returning_none_is_skipped_and_recorded(tmp_path: Path, errors: Path): + write(tmp_path / "a.py", "def on_error(e, message): pass") + default = "on_cleaned in voice.py:3: KeyError: 'x'" + assert report(load_hooks(tmp_path), labelled_error()) == default + failure = "on_error in a.py: TypeError: on_error returned NoneType, not str" + assert entries(errors) == [default, failure] + + +def test_on_error_reraising_its_exception_keeps_the_message(tmp_path: Path, errors: Path): + write(tmp_path / "a.py", "def on_error(e, message):\n raise e") + default = "on_cleaned in voice.py:3: KeyError: 'x'" + assert report(load_hooks(tmp_path), labelled_error()) == default + assert entries(errors) == [default, "on_error in a.py:2: KeyError: 'x'"] + + +def test_on_error_with_the_old_signature_is_skipped_and_recorded(tmp_path: Path, errors: Path): + write(tmp_path / "a.py", "def on_error(e): return 'old'") + default = "on_cleaned in voice.py:3: KeyError: 'x'" + assert report(load_hooks(tmp_path), labelled_error()) == default + failure = "on_error in a.py: TypeError: on_error() takes 1 positional argument but 2 were given" + assert entries(errors) == [default, failure] + + def test_on_error_returning_empty_suppresses_the_message(tmp_path: Path, errors: Path): - write(tmp_path / "a.py", "def on_error(e): return ''") - write(tmp_path / "b.py", "def on_error(e): return 'not reached'") + write(tmp_path / "a.py", "def on_error(e, message): return ''") + write(tmp_path / "b.py", "def on_error(e, message): return 'not reached'") assert report(load_hooks(tmp_path), labelled_error()) == "" assert not errors.exists() @@ -174,9 +206,10 @@ def test_on_error_returning_empty_suppresses_the_message(tmp_path: Path, errors: def test_on_error_gets_the_exception_with_its_type_and_note(tmp_path: Path, errors: Path): write( tmp_path / "a.py", - "def on_error(e):\n" + "def on_error(e, message):\n" " if isinstance(e, KeyError) and 'voice.py:3' in str(e.__notes__):\n" - " return 'seen'\n", + " return 'seen'\n" + " return message\n", ) assert report(load_hooks(tmp_path), labelled_error()) == "seen" @@ -184,8 +217,8 @@ def test_on_error_gets_the_exception_with_its_type_and_note(tmp_path: Path, erro def test_raising_on_error_is_skipped_and_recorded( tmp_path: Path, errors: Path, caplog: pytest.LogCaptureFixture ): - write(tmp_path / "a.py", "def on_error(e):\n raise RuntimeError('broken')") - write(tmp_path / "b.py", "def on_error(e): return 'next'") + write(tmp_path / "a.py", "def on_error(e, message):\n raise RuntimeError('broken')") + write(tmp_path / "b.py", "def on_error(e, message): return 'next'") assert report(load_hooks(tmp_path), labelled_error()) == "next" assert "on_error in a.py:2" in caplog.text # Its own failure is recorded under the default message, without going through on_error. @@ -193,10 +226,10 @@ def test_raising_on_error_is_skipped_and_recorded( def test_on_error_returning_a_wrong_type_is_skipped_and_recorded(tmp_path: Path, errors: Path): - write(tmp_path / "offline.py", "def on_error(e): return {}") - write(tmp_path / "z.py", "def on_error(e): return 'next'") + write(tmp_path / "offline.py", "def on_error(e, message): return {}") + write(tmp_path / "z.py", "def on_error(e, message): return 'next'") assert report(load_hooks(tmp_path), labelled_error()) == "next" - failure = "on_error in offline.py: TypeError: on_error returned dict, not str or None" + failure = "on_error in offline.py: TypeError: on_error returned dict, not str" assert entries(errors) == ["next", failure] (tmp_path / "z.py").unlink() default = "on_cleaned in voice.py:3: KeyError: 'x'" diff --git a/sidecar/tests/test_server.py b/sidecar/tests/test_server.py index 044573b..41deda2 100644 --- a/sidecar/tests/test_server.py +++ b/sidecar/tests/test_server.py @@ -24,11 +24,12 @@ def record(point, t): logged = Path(__file__).parents[1].joinpath("log.txt").exists() with Path(__file__).with_name("calls.txt").open("a") as f: print(point, t, threading.current_thread().name, logged, sep="|", file=f) + return t -def on_transcribed(t): record("on_transcribed", t) -def on_cleaned(t): record("on_cleaned", t) -def on_sent(t): record("on_sent", t) -def on_done(t): record("on_done", t) +def on_transcribed(t): return record("on_transcribed", t) +def on_cleaned(t): return record("on_cleaned", t) +def on_sent(t): return record("on_sent", t) +def on_done(t): return record("on_done", t) """ @@ -202,7 +203,6 @@ def test_hooks_shape_the_text_around_cleanup( ["on_sent", "Please call Anna tomorrow.!"], ["on_done", "Please call Anna tomorrow.!"], ] - # The recorder's on_sent returns None, so the text that was sent is logged. assert (tmp_path / "log.txt").read_text() == "Please call Anna tomorrow.!" @@ -339,7 +339,7 @@ def test_hook_returning_a_wrong_type_before_the_reply_gives_500( (hooks / "a.py").write_text("def on_cleaned(t): return {}\n") server.start_loading() response = client.post("/transcribe", content=SPEECH) - detail = "on_cleaned in a.py: TypeError: on_cleaned returned dict, not str or None" + detail = "on_cleaned in a.py: TypeError: on_cleaned returned dict, not str" assert (response.status_code, response.json()) == (500, {"detail": detail}) assert [c[0] for c in calls(hooks)] == ["on_transcribed"] assert errors(tmp_path) == [detail] @@ -396,14 +396,14 @@ def test_hook_returning_a_wrong_type_after_the_reply_is_recorded( (hooks / "a.py").write_text(f"def {point}(t): return {{}}\n") server.start_loading() assert client.post("/transcribe", content=SPEECH).status_code == 200 - message = f"{point} in a.py: TypeError: {point} returned dict, not str or None" + message = f"{point} in a.py: TypeError: {point} returned dict, not str" assert errors(tmp_path) == [message] assert (tmp_path / "log.txt").exists() == (point == "on_done") ran = ["on_transcribed", "on_cleaned", *(["on_sent"] if point == "on_done" else [])] assert [c[0] for c in calls(hooks)] == ran -def test_on_done_returning_a_string_changes_nothing( +def test_on_done_passes_its_return_to_the_next_on_done( hooks: Path, tmp_path: Path, client: TestClient ): (hooks / "a.py").write_text("def on_done(t): return 'other'\n") @@ -411,13 +411,35 @@ def test_on_done_returning_a_string_changes_nothing( assert client.post("/transcribe", content=SPEECH).status_code == 200 assert errors(tmp_path) == [] assert (tmp_path / "log.txt").read_text() == "We should meet on Friday." + assert calls(hooks)[-1][:2] == ["on_done", "other"] + + +def test_on_done_returning_empty_stops_the_later_on_done( + hooks: Path, tmp_path: Path, client: TestClient +): + (hooks / "a.py").write_text("def on_done(t): return ''\n") + server.start_loading() + assert client.post("/transcribe", content=SPEECH).status_code == 200 + assert (tmp_path / "log.txt").read_text() == "We should meet on Friday." + assert errors(tmp_path) == [] + assert calls(hooks)[-1][0] == "on_sent" + + +def test_hook_with_no_return_fails_the_dictation(hooks: Path, tmp_path: Path, client: TestClient): + (hooks / "a.py").write_text("def on_cleaned(t):\n t.upper()\n") + server.start_loading() + response = client.post("/transcribe", content=SPEECH) + detail = "on_cleaned in a.py: TypeError: on_cleaned returned NoneType, not str" + assert (response.status_code, response.json()) == (500, {"detail": detail}) + assert errors(tmp_path) == [detail] def test_on_error_returning_empty_gives_500_with_empty_detail( hooks: Path, tmp_path: Path, client: TestClient ): (hooks / "a.py").write_text( - "def on_transcribed(t):\n raise ValueError('no')\n\ndef on_error(e):\n return ''\n" + "def on_transcribed(t):\n raise ValueError('no')\n\n" + "def on_error(e, message):\n return ''\n" ) server.start_loading() response = client.post("/transcribe", content=SPEECH) @@ -428,7 +450,7 @@ def test_on_error_returning_empty_gives_500_with_empty_detail( def test_on_error_message_is_the_detail(hooks: Path, tmp_path: Path, client: TestClient): (hooks / "a.py").write_text( "def on_transcribed(t):\n raise ValueError('no')\n\n" - "def on_error(e):\n return f'Oops,\\n{e}'\n" + "def on_error(e, message):\n return f'Oops,\\n{e}'\n" ) server.start_loading() assert client.post("/transcribe", content=SPEECH).json() == {"detail": "Oops, no"} @@ -436,7 +458,7 @@ def test_on_error_message_is_the_detail(hooks: Path, tmp_path: Path, client: Tes def test_503_while_models_are_not_loaded_is_left_alone(fakes: Fakes, hooks: Path, tmp_path: Path): - (hooks / "a.py").write_text("def on_error(e):\n return 'from on_error'\n") + (hooks / "a.py").write_text("def on_error(e, message):\n return 'from on_error'\n") fakes.config = Config(stt_engine="vosk") with TestClient(server.app) as client: wait_for_load() @@ -456,9 +478,10 @@ def test_on_error_can_keep_a_failure_after_the_reply_out_of_errors_txt( "def on_done(t):\n raise urllib.error.URLError(ConnectionRefusedError())\n" ) (hooks / "offline.py").write_text( - "def on_error(e):\n" + "def on_error(e, message):\n" " if isinstance(getattr(e, 'reason', e), ConnectionError):\n" " return ''\n" + " return message\n" ) server.start_loading() assert client.post("/transcribe", content=SPEECH).status_code == 200