mirror of
https://github.com/kuhyx/signal-bot.git
synced 2026-11-10 18:17:02 +01:00
An unrecognised "!word" was dropped in silence, which made a typo
indistinguishable from the bot being down and threw away the best available
list of commands worth writing. Three things now happen at the one place in
dispatcher.py that used to be a bare `return`.
A near miss is corrected -- "!cta" asks whether you meant "!kot". The
distance is optimal string alignment rather than difflib's ratio: a
transposition is the typo people actually make, it costs one edit here, and
it shreds the matching blocks a ratio counts ("!cta"/"!cat" scores 0.75 but
"!cta"/"!kot" scores 0.50, so no cutoff separates them on principle).
A word with no near miss points at !zaproponuj, which files an idea from
inside the group. Either way the word and the message are recorded, and the
management page grows an Ideas tab that lists them.
Three things stay silent, each for its own reason. "!kot ladny" is a real
trigger with words after it and always has been silent. "!!" is punctuation.
And a command claimed in some *other* group is neither answered nor recorded
-- the album's triggers are real people's names, and pack_scoping.yaml says
it out loud: a refusal would itself announce that the album exists. The
existence check is therefore global, which is what pack_add already asks.
Measured rather than guessed, against the shipped aliases.json:
- a minimum candidate length, because "!ja" is one edit from ~40 of the 676
two-letter words somebody could type; 69 of them got a suggestion before
the rule and 18 after.
- the two-edit budget starts at six characters, not five. At five it put
four pairs of *different* commands within reach of each other --
!pies/!popes, !days/!cats, !dzis/!dni, !mnie/!dni -- and costs nothing to
give up, because every real typo this was written for is one edit away.
test_no_two_commands_are_within_reach_of_each_other fails if a future
alias reopens the gap.
Both new tables are keyed on the envelope's own sent_at_ms, never the wall
clock: signal-cli replays undelivered frames on reconnect, and a clock-keyed
table collects a duplicate row per reconnect instead of ignoring one.
The branch is gated on should_count -- which excludes the bot's own envelope,
and that is the loop guard, since handle() checks is_own nowhere else -- and
wrapped in its own try/except, because it runs above the one that wraps a
handler and Bot.listen has no exception handling of its own.
Suggestions live in SQLite, not in a tracked file, and the export goes to the
state directory. check_personal_data learns the names it refuses from the
live database, so it catches a name somebody has typed and cannot catch a
misspelling of one -- and an unrecognised-command corpus is made of
misspellings. A group-writable file in a public tree is both a leak and a
wedge. The export therefore carries
deliberate !zaproponuj notes in full and unrecognised words as counts only;
bodies stay on the loopback-only page.
Verified on the live bot: restarted, both tables created with every existing
row count unchanged, !cta and !zaproponuj !pogoda delivered through
/_selftest, both rows read back out of the live database, and the journal
names neither the word nor the body.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01416TegJ3sa8xL5qGGgrygP
152 lines
6.1 KiB
Python
152 lines
6.1 KiB
Python
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
|
|
"""The management page's read of the wish list, and the export it writes."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import dataclasses
|
|
import sqlite3
|
|
from pathlib import Path
|
|
from typing import TYPE_CHECKING
|
|
|
|
from signal_bot.manage.routes_suggestions import (
|
|
EXPORT_BODY_LIMIT,
|
|
EXPORT_NAME,
|
|
default_export_path,
|
|
)
|
|
from signal_bot.store import Store
|
|
from tests.manage_fixture import client_for, deps_at
|
|
|
|
if TYPE_CHECKING:
|
|
import pytest
|
|
|
|
from signal_bot.manage.deps import ManageDeps
|
|
|
|
|
|
def seeded(tmp_path: Path) -> ManageDeps:
|
|
"""A management app pointed at a database with one of each row in it."""
|
|
deps = deps_at(tmp_path)
|
|
with Store(str(deps.database_path)) as store:
|
|
store.suggestions.record_suggestion("g1", "!pogoda", "pokaz pogode", 101)
|
|
store.suggestions.record_unknown("g1", "!cta", "!cta", 200)
|
|
store.suggestions.record_unknown("g1", "!cta", "!cta teraz", 201)
|
|
return deps
|
|
|
|
|
|
def test_the_fixture_never_points_at_the_real_database(tmp_path: Path) -> None:
|
|
"""Config.database_path is the *relative* "signal_bot.sqlite3".
|
|
|
|
pytest runs from the repository root, where the operator's real database
|
|
sits, and Store drops the ephemeral tables on a version mismatch. A
|
|
defaulted field on ManageDeps would therefore have let the suite delete
|
|
live cooldowns and announce state -- so the field has no default, and
|
|
this asserts the fixture supplies a temporary one.
|
|
"""
|
|
deps = deps_at(tmp_path)
|
|
assert deps.database_path.is_relative_to(tmp_path)
|
|
assert deps.export_path.is_relative_to(tmp_path)
|
|
|
|
|
|
def test_a_bot_that_has_never_run_is_not_an_error(tmp_path: Path) -> None:
|
|
"""No database yet means nothing collected, not a 500."""
|
|
deps = deps_at(tmp_path)
|
|
assert not deps.database_path.exists()
|
|
body = client_for(deps).get("/api/suggestions").json()
|
|
assert body == {"suggestions": [], "unknown": []}
|
|
|
|
|
|
def test_a_database_older_than_these_tables_is_not_an_error(tmp_path: Path) -> None:
|
|
"""Upgrading the bot must not make the page fail until it restarts."""
|
|
deps = deps_at(tmp_path)
|
|
sqlite3.connect(deps.database_path).close()
|
|
body = client_for(deps).get("/api/suggestions").json()
|
|
assert body == {"suggestions": [], "unknown": []}
|
|
|
|
|
|
def test_a_directory_where_the_database_should_be_is_not_an_error(tmp_path: Path) -> None:
|
|
"""is_file, not exists: a path that is not a file is still "nothing here"."""
|
|
deps = deps_at(tmp_path)
|
|
deps.database_path.mkdir()
|
|
assert client_for(deps).get("/api/suggestions").json()["unknown"] == []
|
|
|
|
|
|
def test_an_unreadable_database_is_not_an_error(tmp_path: Path) -> None:
|
|
"""Whatever is at the path, the page still renders."""
|
|
deps = deps_at(tmp_path)
|
|
deps.database_path.write_text("not a database", encoding="utf-8")
|
|
assert client_for(deps).get("/api/suggestions").json()["suggestions"] == []
|
|
|
|
|
|
def test_the_page_shows_ideas_and_tallies(tmp_path: Path) -> None:
|
|
"""Bodies included, because this response never leaves the loopback port."""
|
|
body = client_for(seeded(tmp_path)).get("/api/suggestions").json()
|
|
assert body["suggestions"][0]["command"] == "!pogoda"
|
|
assert body["suggestions"][0]["body"] == "pokaz pogode"
|
|
assert body["unknown"][0] == {
|
|
"bodies": ["!cta", "!cta teraz"],
|
|
"group_id": "g1",
|
|
"hits": 2,
|
|
"last_seen": 201,
|
|
"word": "!cta",
|
|
}
|
|
|
|
|
|
def test_the_export_keeps_notes_but_reduces_mistyped_words_to_counts(
|
|
tmp_path: Path,
|
|
) -> None:
|
|
"""The asymmetry this whole feature is arranged around.
|
|
|
|
A !zaproponuj body was written on purpose, to the maintainer. An
|
|
unrecognised body is half-typed chat, and a half-typed name is one the
|
|
personal-data gate cannot recognise -- so it becomes a number.
|
|
"""
|
|
deps = seeded(tmp_path)
|
|
answer = client_for(deps).post("/api/suggestions/export", json={}).json()
|
|
assert answer == {"path": str(deps.export_path), "suggestions": 1, "unknown": 1}
|
|
written = deps.export_path.read_text(encoding="utf-8")
|
|
assert "pokaz pogode" in written
|
|
assert "`!cta` x 2" in written
|
|
assert "!cta teraz" not in written
|
|
|
|
|
|
def test_the_export_says_so_when_there_is_nothing_to_say(tmp_path: Path) -> None:
|
|
"""An empty file that reads as empty, rather than two bare headings."""
|
|
deps = deps_at(tmp_path)
|
|
client_for(deps).post("/api/suggestions/export", json={})
|
|
assert deps.export_path.read_text(encoding="utf-8").count("_Nothing yet._") == 2
|
|
|
|
|
|
def test_a_very_long_body_is_truncated_in_the_export(tmp_path: Path) -> None:
|
|
"""One pasted paragraph must not bury the rest of the file."""
|
|
deps = deps_at(tmp_path)
|
|
with Store(str(deps.database_path)) as store:
|
|
store.suggestions.record_suggestion("g1", "!x", "a" * 500, 1)
|
|
client_for(deps).post("/api/suggestions/export", json={})
|
|
written = deps.export_path.read_text(encoding="utf-8")
|
|
assert "a" * EXPORT_BODY_LIMIT in written
|
|
assert "a" * (EXPORT_BODY_LIMIT + 1) not in written
|
|
|
|
|
|
def test_the_default_export_path_is_never_inside_the_repository(
|
|
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
"""A group-writable file in a public git tree is a leak and a wedge.
|
|
|
|
The personal-data gate would refuse every future commit once a real name
|
|
landed in it, and it cannot recognise the misspelled ones this file is
|
|
full of. So the export goes where the album goes.
|
|
"""
|
|
monkeypatch.setenv("STATE_DIRECTORY", str(tmp_path / "state"))
|
|
assert default_export_path() == tmp_path / "state" / EXPORT_NAME
|
|
monkeypatch.delenv("STATE_DIRECTORY")
|
|
monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path / "share"))
|
|
assert default_export_path() == tmp_path / "share" / "signal-bot" / EXPORT_NAME
|
|
monkeypatch.delenv("XDG_DATA_HOME")
|
|
assert default_export_path().is_relative_to(Path.home())
|
|
|
|
|
|
def test_the_export_does_not_need_its_directory_to_exist(tmp_path: Path) -> None:
|
|
"""First run on a fresh install, where the state directory is still empty."""
|
|
deps = dataclasses.replace(deps_at(tmp_path), export_path=tmp_path / "a" / "b" / EXPORT_NAME)
|
|
client_for(deps).post("/api/suggestions/export", json={})
|
|
assert (tmp_path / "a" / "b" / EXPORT_NAME).is_file()
|