Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 82 additions & 0 deletions docs/factory-report-feature-hook-returns-1.md
Original file line number Diff line number Diff line change
@@ -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 <file>` 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.
34 changes: 20 additions & 14 deletions docs/hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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
Expand All @@ -118,6 +119,7 @@ raw = ""
def on_transcribed(t):
global raw
raw = t
return t


def on_sent(t):
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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.
7 changes: 4 additions & 3 deletions examples/ask.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
3 changes: 2 additions & 1 deletion examples/talk_like_a_pirate.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
11 changes: 6 additions & 5 deletions examples/terminal.py
Original file line number Diff line number Diff line change
@@ -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

Expand All @@ -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
7 changes: 4 additions & 3 deletions examples/translate.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
2 changes: 1 addition & 1 deletion examples/voice_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 ")]
Expand Down
4 changes: 2 additions & 2 deletions sidecar/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
Loading
Loading