Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

refactor(messages): centralize message type policy catalog (#1046)

Call White4ff1e06f4204
diff --git a/tests/test_message_type_catalog.py b/tests/test_message_type_catalog.py
new file mode 100644
index 000000000..59fc31236
--- /dev/null
+++ b/tests/test_message_type_catalog.py
@@ -0,0 +1,170 @@
+from __future__ import annotations
+
+import json
+import re
+from importlib import resources
+from typing import Any
+
+import pytest
+
+from core import web_push_notifications
+from storage import agent_activity_service, messages_service
+from storage.models import messages
+from vibe.message_identity import INPUT_TURN_AUTHOR_TYPES
+from vibe.message_types import (
+ build_partial_index_predicate,
+ input_author_type_pairs,
+ spec_for,
+ types_with,
+ types_without,
+)
+
+
+class _EmptyResult:
+ def mappings(self) -> "_EmptyResult":
+ return self
+
+ def all(self) -> list[Any]:
+ return []
+
+
+class _CaptureConnection:
+ def __init__(self) -> None:
+ self.statements: list[Any] = []
+
+ def execute(self, statement: Any) -> _EmptyResult:
+ self.statements.append(statement)
+ return _EmptyResult()
+
+
+def _catalog_document() -> dict[str, Any]:
+ resource = resources.files("vibe").joinpath("message_types.json")
+ assert resource.is_file()
+ return json.loads(resource.read_text(encoding="utf-8"))
+
+
+def _catalog_types() -> tuple[str, ...]:
+ return tuple(_catalog_document()["types"])
+
+
+def _sequence_params(statement: Any) -> set[tuple[str, ...]]:
+ return {
+ tuple(value)
+ for value in statement.compile().params.values()
+ if isinstance(value, (list, tuple))
+ }
+
+
+def _message_type_equality_values(statement: Any) -> tuple[str, ...]:
+ compiled = statement.compile()
+ parameter_names = re.findall(r"\bmessages\.type = :(type_\d+)", str(compiled))
+ return tuple(compiled.params[name] for name in parameter_names)
+
+
+def test_catalog_resource_and_defaults_are_cross_language_data() -> None:
+ document = _catalog_document()
+ expected_default = {
+ name: tuple(value) if isinstance(value, list) else value
+ for name, value in document["defaults"].items()
+ }
+
+ assert dict(spec_for("not_a_catalog_type")) == expected_default
+ with pytest.raises(TypeError):
+ spec_for("user")["transcript"] = False # type: ignore[index]
+
+
+def test_transcript_types_match_current_constant() -> None:
+ assert types_with("transcript") == messages_service.TRANSCRIPT_TYPES
+
+
+def test_searchable_types_match_current_default_query() -> None:
+ connection = _CaptureConnection()
+ messages_service.search_messages(connection, query="catalog-probe")
+
+ assert _sequence_params(connection.statements[-1]) == {types_with("searchable")}
+
+
+def test_inbox_activity_types_match_current_constant() -> None:
+ assert types_without("inboxActivity") == messages_service.NON_CONVERSATION_TYPES
+
+
+def test_inbox_preview_and_settlement_types_match_current_query() -> None:
+ connection = _CaptureConnection()
+ messages_service.list_inbox_sessions(connection)
+ current_query_sets = _sequence_params(connection.statements[-1])
+
+ assert current_query_sets == {
+ messages_service.NON_CONVERSATION_TYPES,
+ types_with("inboxPreview"),
+ types_with("inboxSettlesReply"),
+ }
+
+
+ "query",
+ [messages_service.unread_counts, messages_service.unread_counts_by_session],
+)
+def test_unread_types_match_current_queries(query: Any) -> None:
+ connection = _CaptureConnection()
+ query(connection)
+
+ assert _message_type_equality_values(connection.statements[-1]) == types_with("unread")
+
+
+def test_input_turn_pairs_match_current_constant() -> None:
+ assert input_author_type_pairs() == INPUT_TURN_AUTHOR_TYPES
+
+
+def test_activity_fetch_and_terminal_semantics_match_current_service() -> None:
+ derived_relevant = {
+ message_type
+ for message_type in _catalog_types()
+ if spec_for(message_type)["activityRole"] != "none"
+ or spec_for(message_type)["terminalWhenEvents"]
+ }
+ assert derived_relevant == set(agent_activity_service._RELEVANT_MESSAGE_TYPES)
+
+ for message_type in _catalog_types():
+ spec = spec_for(message_type)
+ for event in (None, "backend_failure", "other"):
+ metadata = {"event": event} if event is not None else {}
+ expected = (
+ spec["activityRole"] == "terminal"
+ or event in spec["terminalWhenEvents"]
+ )
+ assert (
+ agent_activity_service._is_terminal(message_type, "agent", metadata)
+ is expected
+ )
+
+
+def test_web_push_candidate_exact_and_unread_sets_match_current_service() -> None:
+ assert set(types_with("webPush")) | set(
+ types_with("webPushWhenEvents")
+ ) == web_push_notifications._NOTIFIABLE_TYPES
+ assert set(types_with("unread")) == web_push_notifications._UNREAD_GATED_TYPES
+
+ for message_type in _catalog_types():
+ spec = spec_for(message_type)
+ for event in (None, "backend_failure", "other"):
+ metadata = {"event": event} if event is not None else {}
+ expected = spec["webPush"] or event in spec["webPushWhenEvents"]
+ assert (
+ web_push_notifications._is_notifiable_message(message_type, metadata)
+ is expected
+ )
+
+
+ "index_name",
+ [
+ "ix_messages_inbox_activity",
+ "ix_messages_inbox_agent_reply",
+ "ix_messages_inbox_user_send",
+ ],
+)
+def test_partial_index_predicates_match_current_model(index_name: str) -> None:
+ index = next(item for item in messages.indexes if item.name == index_name)
+ current_predicate = index.dialect_options["sqlite"]["where"]
+
+ assert build_partial_index_predicate(index_name) == str(current_predicate)
diff --git a/vibe/message_types.json b/vibe/message_types.json
new file mode 100644
index 000000000..35ee03d3b
--- /dev/null
+++ b/vibe/message_types.json
@@ -0,0 +1,94 @@
+{
+ "defaults": {
+ "transcript": false,
+ "searchable": false,
+ "inputAuthors": [],
+ "inboxActivity": true,
+ "inboxPreview": false,
+ "inboxSettlesReply": false,
+ "activityRole": "none",
+ "terminalWhenEvents": [],
+ "unread": false,
+ "webPush": false,
+ "webPushWhenEvents": [],
+ "acceptedReservation": false,
+ "render": "none"
+ },
+ "types": {
+ "user": {
+ "transcript": true,
+ "searchable": true,
+ "inputAuthors": [
+ "user"
+ ],
+ "activityRole": "turn_start",
+ "acceptedReservation": true,
+ "render": "user"
+ },
+ "harness": {
+ "transcript": true,
+ "searchable": true,
+ "inputAuthors": [
+ "harness"
+ ],
+ "activityRole": "turn_start",
+ "acceptedReservation": true,
+ "render": "harness"
+ },
+ "result": {
+ "transcript": true,
+ "searchable": true,
+ "inboxPreview": true,
+ "inboxSettlesReply": true,
+ "activityRole": "terminal",
+ "unread": true,
+ "webPush": true,
+ "render": "agent"
+ },
+ "notify": {
+ "transcript": true,
+ "inboxPreview": true,
+ "inboxSettlesReply": true,
+ "terminalWhenEvents": [
+ "backend_failure"
+ ],
+ "webPushWhenEvents": [
+ "backend_failure"
+ ],
+ "render": "status"
+ },
+ "error": {
+ "transcript": true,
+ "inboxPreview": true,
+ "inboxSettlesReply": true,
+ "activityRole": "terminal",
+ "webPush": true,
+ "render": "status"
+ },
+ "assistant": {
+ "activityRole": "activity",
+ "render": "activity"
+ },
+ "tool_call": {
+ "render": "activity"
+ },
+ "queued": {
+ "inboxActivity": false,
+ "acceptedReservation": true
+ },
+ "draft": {
+ "inboxActivity": false
+ },
+ "pending": {
+ "inboxActivity": false
+ },
+ "harness_dedupe": {
+ "inboxActivity": false
+ },
+ "silent": {
+ "inboxActivity": false,
+ "inboxSettlesReply": true,
+ "activityRole": "terminal"
+ }
+ }
+}
diff --git a/vibe/message_types.py b/vibe/message_types.py
new file mode 100644
index 000000000..b5d210b13
--- /dev/null
+++ b/vibe/message_types.py
@@ -0,0 +1,176 @@
+"""Read-only message-type policy catalog shared with the Web UI."""
+
+from __future__ import annotations
+
+import json
+from importlib import resources
+from types import MappingProxyType
+from typing import Any, Mapping
+
+_BOOL_PROPERTIES = {
+ "transcript",
+ "searchable",
+ "inboxActivity",
+ "inboxPreview",
+ "inboxSettlesReply",
+ "unread",
+ "webPush",
+ "acceptedReservation",
+}
+_LIST_PROPERTIES = {
+ "inputAuthors",
+ "terminalWhenEvents",
+ "webPushWhenEvents",
+}
+_ENUM_PROPERTIES = {
+ "activityRole": {"none", "turn_start", "activity", "terminal"},
+ "render": {"none", "user", "harness", "agent", "status", "activity"},
+}
+_PROPERTY_NAMES = _BOOL_PROPERTIES | _LIST_PROPERTIES | set(_ENUM_PROPERTIES)
+
+
+def _load_catalog() -> tuple[Mapping[str, Any], Mapping[str, Mapping[str, Any]]]:
+ raw = json.loads(
+ resources.files(__package__).joinpath("message_types.json").read_text(encoding="utf-8")
+ )
+ if not isinstance(raw, dict) or set(raw) != {"defaults", "types"}:
+ raise ValueError("message type catalog must contain defaults and types")
+ defaults = raw["defaults"]
+ type_specs = raw["types"]
+ if not isinstance(defaults, dict) or set(defaults) != _PROPERTY_NAMES:
+ raise ValueError("message type catalog defaults do not match the public properties")
+ if not isinstance(type_specs, dict):
+ raise ValueError("message type catalog types must be an object")
+
+ def freeze_spec(spec: Any, *, partial: bool) -> Mapping[str, Any]:
+ if not isinstance(spec, dict):
+ raise ValueError("each message type spec must be an object")
+ if not set(spec).issubset(_PROPERTY_NAMES):
+ raise ValueError("message type spec contains an unknown property")
+ if not partial and set(spec) != _PROPERTY_NAMES:
+ raise ValueError("message type defaults must define every property")
+
+ frozen: dict[str, Any] = {}
+ for name, value in spec.items():
+ if name in _BOOL_PROPERTIES:
+ if not isinstance(value, bool):
+ raise ValueError(f"{name} must be boolean")
+ frozen[name] = value
+ elif name in _LIST_PROPERTIES:
+ if (
+ not isinstance(value, list)
+ or any(not isinstance(item, str) or not item for item in value)
+ or len(value) != len(set(value))
+ ):
+ raise ValueError(f"{name} must be a list of unique non-empty strings")
+ frozen[name] = tuple(value)
+ else:
+ if value not in _ENUM_PROPERTIES[name]:
+ raise ValueError(f"{name} has an unsupported value")
+ frozen[name] = value
+ return MappingProxyType(frozen)
+
+ frozen_defaults = freeze_spec(defaults, partial=False)
+ frozen_types: dict[str, Mapping[str, Any]] = {}
+ for message_type, overrides in type_specs.items():
+ if not isinstance(message_type, str) or not message_type:
+ raise ValueError("message type names must be non-empty strings")
+ merged = dict(frozen_defaults)
+ merged.update(freeze_spec(overrides, partial=True))
+ frozen_types[message_type] = MappingProxyType(merged)
+ return frozen_defaults, MappingProxyType(frozen_types)
+
+
+_DEFAULT_SPEC, _TYPE_SPECS = _load_catalog()
+
+
+def _property_enabled(property_name: str, value: Any) -> bool:
+ if property_name in _BOOL_PROPERTIES:
+ return bool(value)
+ if property_name in _LIST_PROPERTIES:
+ return bool(value)
+ return value != "none"
+
+
+def types_with(property_name: str) -> tuple[str, ...]:
+ """Return catalog types for which *property_name* is enabled, in catalog order."""
+
+ if property_name not in _PROPERTY_NAMES:
+ raise KeyError(property_name)
+ return tuple(
+ message_type
+ for message_type, spec in _TYPE_SPECS.items()
+ if _property_enabled(property_name, spec[property_name])
+ )
+
+
+def types_without(property_name: str) -> tuple[str, ...]:
+ """Return catalog types for which *property_name* is disabled, in catalog order."""
+
+ if property_name not in _PROPERTY_NAMES:
+ raise KeyError(property_name)
+ return tuple(
+ message_type
+ for message_type, spec in _TYPE_SPECS.items()
+ if not _property_enabled(property_name, spec[property_name])
+ )
+
+
+def input_author_type_pairs() -> tuple[tuple[str, str], ...]:
+ """Return accepted ``(author, message_type)`` input-turn pairs in catalog order."""
+
+ return tuple(
+ (author, message_type)
+ for message_type, spec in _TYPE_SPECS.items()
+ for author in spec["inputAuthors"]
+ )
+
+
+def spec_for(message_type: str) -> Mapping[str, Any]:
+ """Return an immutable resolved spec; unknown types receive catalog defaults."""
+
+ return _TYPE_SPECS.get(message_type, _DEFAULT_SPEC)
+
+
+def _sql_quote(value: str) -> str:
+ return "'" + value.replace("'", "''") + "'"
+
+
+def _sql_values(values: tuple[str, ...]) -> str:
+ if not values:
+ raise ValueError("partial-index predicate requires at least one catalog value")
+ return ", ".join(_sql_quote(value) for value in values)
+
+
+def build_partial_index_predicate(index_name: str) -> str:
+ """Build one current ``messages`` partial-index predicate byte-for-byte."""
+
+ if index_name == "ix_messages_inbox_activity":
+ return (
+ "session_id is not null and type not in "
+ f"({_sql_values(types_without('inboxActivity'))})"
+ )
+ if index_name == "ix_messages_inbox_agent_reply":
+ return (
+ "session_id is not null and type in "
+ f"({_sql_values(types_with('inboxPreview'))})"
+ )
+ if index_name == "ix_messages_inbox_user_send":
+ pairs = input_author_type_pairs()
+ if not pairs:
+ raise ValueError("input-turn partial index requires at least one author/type pair")
+ clauses = " or ".join(
+ f"(author = {_sql_quote(author)} and type = {_sql_quote(message_type)})"
+ for author, message_type in pairs
+ )
+ return f"session_id is not null and ({clauses})"
+ raise KeyError(index_name)
+
+
+__all__ = [
+ "build_partial_index_predicate",
+ "input_author_type_pairs",
+ "spec_for",
+ "types_with",
+ "types_without",
+]