Compare commits

..

6 Commits

Author SHA1 Message Date
Jack Kingsman 2de946318c Fix migration bump 2026-04-27 16:20:10 -07:00
Jack Kingsman 26983667bd Propagate to HA 2026-04-27 16:10:13 -07:00
Jack Kingsman 72efe214e9 Reject repeaters from contact telemetry opt-in 2026-04-27 13:51:17 -07:00
Jack Kingsman 8aac6a9771 Split up setting to be a bit neater 2026-04-27 13:24:48 -07:00
Jack Kingsman d019ab4ee1 Add telemetry config to radio settings 2026-04-27 12:44:52 -07:00
Jack Kingsman 53f701938b Initial tracke telemetry for contacts 2026-04-27 12:10:49 -07:00
72 changed files with 2096 additions and 1100 deletions
-1
View File
@@ -25,7 +25,6 @@ references/
# ancillary LLM files
.claude/
.codex
# local Docker compose files
docker-compose.yml
+5 -1
View File
@@ -350,6 +350,8 @@ All endpoints are prefixed with `/api` (e.g., `/api/health`).
| POST | `/api/contacts/{public_key}/repeater/advert-intervals` | Fetch advert intervals |
| POST | `/api/contacts/{public_key}/repeater/owner-info` | Fetch owner info |
| GET | `/api/contacts/{public_key}/repeater/telemetry-history` | Stored telemetry history for a repeater (read-only, no radio access) |
| POST | `/api/contacts/{public_key}/telemetry` | Fetch CayenneLPP telemetry from any contact (single attempt, 10s timeout) |
| GET | `/api/contacts/{public_key}/telemetry-history` | Stored LPP telemetry history for a contact (read-only, no radio access) |
| POST | `/api/contacts/{public_key}/room/login` | Log in to a room server |
| POST | `/api/contacts/{public_key}/room/status` | Fetch room-server status telemetry |
| POST | `/api/contacts/{public_key}/room/lpp-telemetry` | Fetch room-server CayenneLPP sensor data |
@@ -380,6 +382,8 @@ All endpoints are prefixed with `/api` (e.g., `/api/health`).
| POST | `/api/settings/blocked-names/toggle` | Toggle blocked name |
| POST | `/api/settings/tracked-telemetry/toggle` | Toggle tracked telemetry repeater |
| GET | `/api/settings/tracked-telemetry/schedule` | Current telemetry scheduling derivation and next-run-at timestamp |
| POST | `/api/settings/tracked-telemetry-contacts/toggle` | Toggle tracked LPP telemetry for any contact |
| GET | `/api/settings/tracked-telemetry-contacts/schedule` | Contact telemetry scheduling derivation (shared ceiling with repeaters) |
| POST | `/api/settings/muted-channels/toggle` | Toggle muted status for a channel |
| GET | `/api/fanout` | List all fanout configs |
| POST | `/api/fanout` | Create new fanout config |
@@ -508,7 +512,7 @@ mc.subscribe(EventType.ACK, handler)
| `MESHCORE_LOAD_WITH_AUTOEVICT` | `false` | Enable autoevict contact loading: sets `AUTO_ADD_OVERWRITE_OLDEST` on the radio so adds never fail with TABLE_FULL, skips the removal phase during reconcile, and allows blind loading when `get_contacts` fails. Loaded contacts are not radio-favorited and may be evicted by new adverts when the table is full. |
| `MESHCORE_ENABLE_LOCAL_PRIVATE_KEY_EXPORT` | `false` | Enable `GET /api/radio/private-key` to return the in-memory private key as hex. Disabled by default; only enable on a trusted network where you need to retrieve the key (e.g. for backup or migration). |
**Note:** Runtime app settings are stored in the database (`app_settings` table), not environment variables. These include `max_radio_contacts`, `auto_decrypt_dm_on_advert`, `advert_interval`, `last_advert_time`, `last_message_times`, `flood_scope`, `blocked_keys`, `blocked_names`, `discovery_blocked_types`, `tracked_telemetry_repeaters`, `auto_resend_channel`, and `telemetry_interval_hours`. `max_radio_contacts` is the configured radio contact capacity baseline used by background maintenance: favorites reload first, non-favorite fill targets about 80% of that value, and full offload/reload triggers around 95% occupancy. They are configured via `GET/PATCH /api/settings`. MQTT, bot, webhook, Apprise, and SQS configs are stored in the `fanout_configs` table, managed via `/api/fanout`. If the radio's channel slots appear unstable or another client is mutating them underneath this app, operators can force the old always-reconfigure send path with `MESHCORE_FORCE_CHANNEL_SLOT_RECONFIGURE=true`.
**Note:** Runtime app settings are stored in the database (`app_settings` table), not environment variables. These include `max_radio_contacts`, `auto_decrypt_dm_on_advert`, `advert_interval`, `last_advert_time`, `last_message_times`, `flood_scope`, `blocked_keys`, `blocked_names`, `discovery_blocked_types`, `tracked_telemetry_repeaters`, `tracked_telemetry_contacts`, `auto_resend_channel`, and `telemetry_interval_hours`. `max_radio_contacts` is the configured radio contact capacity baseline used by background maintenance: favorites reload first, non-favorite fill targets about 80% of that value, and full offload/reload triggers around 95% occupancy. They are configured via `GET/PATCH /api/settings`. MQTT, bot, webhook, Apprise, and SQS configs are stored in the `fanout_configs` table, managed via `/api/fanout`. If the radio's channel slots appear unstable or another client is mutating them underneath this app, operators can force the old always-reconfigure send path with `MESHCORE_FORCE_CHANNEL_SLOT_RECONFIGURE=true`.
Byte-perfect channel retries are user-triggered via `POST /api/messages/channel/{message_id}/resend` and are allowed for 30 seconds after the original send.
-15
View File
@@ -1,18 +1,3 @@
## [3.13.0] - 2026-04-30
* Feature: Error counts included in repeater telemetry
* Feature: RX error rate + percentage surfaced and tracked for repeaters
* Feature: Dynamic as-you-type text replacement for Cyrillic byte optimization
* Feature: Permit hourly checks for direct/routed repeaters
* Feature: Allow newlines in input
* Feature: Packet-send radio time added to packet analyzer
* Feature: Enable forced plaintext for Apprise
* Bugfix: Less annoying MQTT failure notifications with backoff
* Bugfis: Don't obscure input; use dvh everywhere
* Bugfix: Clearer save button for advert interval
* Misc: Library updates
* Misc: Rewrite 5xx to 4xx to avoid issues with proxies that don't react well to 503/504
## [3.12.3] - 2026-04-24
* Feature: Customizable Apprise strings
+1 -1
View File
@@ -330,7 +330,7 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
</details>
### meshcore (2.3.7) — MIT
### meshcore (2.3.2) — MIT
<details>
<summary>Full license text</summary>
+8 -2
View File
@@ -169,7 +169,8 @@ app/
- Configs stored in `fanout_configs` table, managed via `GET/POST/PATCH/DELETE /api/fanout`.
- `broadcast_event()` in `websocket.py` dispatches to the fanout manager for `message`, `raw_packet`, and `contact` events.
- `on_message` and `on_raw` are scope-gated. `on_contact`, `on_telemetry`, and `on_health` are dispatched to all modules unconditionally (modules filter internally).
- Repeater telemetry broadcasts are emitted after `RepeaterTelemetryRepository.record()` in both `radio_sync.py` (auto-collect) and `routers/repeaters.py` (manual fetch).
- Repeater telemetry broadcasts are emitted after `RepeaterTelemetryRepository.record()` in both `radio_sync.py` (auto-collect) and `routers/repeaters.py` (manual fetch). Contact LPP telemetry is similarly recorded to `ContactTelemetryRepository` and dispatched to fanout.
- The telemetry collection loop in `radio_sync.py` is unified: it iterates over both `tracked_telemetry_repeaters` and `tracked_telemetry_contacts`, dispatching to `_collect_repeater_telemetry` (type 2) or `_collect_contact_telemetry` (others). The daily check ceiling uses the combined count.
- The 60-second radio stats sampling loop in `radio_stats.py` dispatches an enriched health snapshot (radio identity + full stats) to all fanout modules after each sample.
- Community MQTT publishes raw packets only, but its derived `path` field for direct packets is emitted as comma-separated hop identifiers, not flat path bytes.
- See `app/fanout/AGENTS_fanout.md` for full architecture details and event payload shapes.
@@ -227,6 +228,8 @@ Web Push is a standalone subsystem in `app/push/`, separate from the fanout modu
- `POST /contacts/{public_key}/repeater/advert-intervals`
- `POST /contacts/{public_key}/repeater/owner-info`
- `GET /contacts/{public_key}/repeater/telemetry-history` — stored telemetry history for a repeater (read-only, no radio access)
- `POST /contacts/{public_key}/telemetry` — on-demand CayenneLPP telemetry from any contact (persists in `contact_telemetry_history`)
- `GET /contacts/{public_key}/telemetry-history` — stored LPP telemetry history for a contact (read-only)
- `POST /contacts/{public_key}/room/login`
- `POST /contacts/{public_key}/room/status`
- `POST /contacts/{public_key}/room/lpp-telemetry`
@@ -267,6 +270,8 @@ Web Push is a standalone subsystem in `app/push/`, separate from the fanout modu
- `POST /settings/blocked-names/toggle`
- `POST /settings/tracked-telemetry/toggle`
- `GET /settings/tracked-telemetry/schedule` — current telemetry scheduling derivation, interval options, and next-run-at timestamp
- `POST /settings/tracked-telemetry-contacts/toggle` — toggle tracked LPP telemetry for any contact (max 8)
- `GET /settings/tracked-telemetry-contacts/schedule` — contact telemetry scheduling (shared ceiling with repeaters)
- `POST /settings/muted-channels/toggle`
### Fanout
@@ -320,6 +325,7 @@ Main tables:
- `contact_advert_paths` (recent unique advertisement paths per contact, keyed by contact + path bytes + hop count)
- `contact_name_history` (tracks name changes over time)
- `repeater_telemetry_history` (time-series telemetry snapshots for tracked repeaters)
- `contact_telemetry_history` (time-series LPP telemetry snapshots for tracked contacts; same schema as repeater table)
- `fanout_configs` (MQTT, bot, webhook, Apprise, SQS integration configs)
- `push_subscriptions` (Web Push browser subscriptions with delivery metadata; UNIQUE on endpoint)
- `app_settings` (includes `vapid_private_key` and `vapid_public_key` for Web Push VAPID signing)
@@ -343,7 +349,7 @@ Repository writes should prefer typed models such as `ContactUpsert` over ad hoc
- `last_advert_time`
- `flood_scope`
- `blocked_keys`, `blocked_names`, `discovery_blocked_types`
- `tracked_telemetry_repeaters`
- `tracked_telemetry_repeaters`, `tracked_telemetry_contacts`
- `auto_resend_channel`
- `telemetry_interval_hours`
+24 -93
View File
@@ -11,9 +11,6 @@ from app.path_utils import split_path_hex
logger = logging.getLogger(__name__)
_MAX_SEND_ATTEMPTS = 3
_RETRY_DELAY_S = 2
DEFAULT_BODY_FORMAT_DM = "**DM:** {sender_name}: {text} **via:** [{hops_backticked}]"
DEFAULT_BODY_FORMAT_CHANNEL = (
"**{channel_name}:** {sender_name}: {text} **via:** [{hops_backticked}]"
@@ -21,12 +18,6 @@ DEFAULT_BODY_FORMAT_CHANNEL = (
_DEFAULT_BODY_FORMAT_DM_NO_PATH = "**DM:** {sender_name}: {text}"
_DEFAULT_BODY_FORMAT_CHANNEL_NO_PATH = "**{channel_name}:** {sender_name}: {text}"
# Plain-text variants (no markdown formatting)
DEFAULT_BODY_FORMAT_DM_PLAIN = "DM: {sender_name}: {text} via: [{hops}]"
DEFAULT_BODY_FORMAT_CHANNEL_PLAIN = "{channel_name}: {sender_name}: {text} via: [{hops}]"
_DEFAULT_BODY_FORMAT_DM_NO_PATH_PLAIN = "DM: {sender_name}: {text}"
_DEFAULT_BODY_FORMAT_CHANNEL_NO_PATH_PLAIN = "{channel_name}: {sender_name}: {text}"
# Variables available for user format strings
FORMAT_VARIABLES = (
"type",
@@ -139,17 +130,10 @@ def _apply_format(fmt: str, variables: dict[str, str]) -> str:
def _format_body(
data: dict,
*,
body_format_dm: str | None = None,
body_format_channel: str | None = None,
markdown: bool = True,
body_format_dm: str = DEFAULT_BODY_FORMAT_DM,
body_format_channel: str = DEFAULT_BODY_FORMAT_CHANNEL,
) -> str:
"""Build a notification body from message data using format strings."""
if body_format_dm is None:
body_format_dm = DEFAULT_BODY_FORMAT_DM if markdown else DEFAULT_BODY_FORMAT_DM_PLAIN
if body_format_channel is None:
body_format_channel = (
DEFAULT_BODY_FORMAT_CHANNEL if markdown else DEFAULT_BODY_FORMAT_CHANNEL_PLAIN
)
variables = _build_template_vars(data)
msg_type = data.get("type", "")
fmt = body_format_dm if msg_type == "PRIV" else body_format_channel
@@ -157,21 +141,13 @@ def _format_body(
return _apply_format(fmt, variables)
except Exception:
logger.warning("Apprise format string error, falling back to default")
if markdown:
default = DEFAULT_BODY_FORMAT_DM if msg_type == "PRIV" else DEFAULT_BODY_FORMAT_CHANNEL
else:
default = (
DEFAULT_BODY_FORMAT_DM_PLAIN
if msg_type == "PRIV"
else DEFAULT_BODY_FORMAT_CHANNEL_PLAIN
)
default = DEFAULT_BODY_FORMAT_DM if msg_type == "PRIV" else DEFAULT_BODY_FORMAT_CHANNEL
return _apply_format(default, variables)
def _send_sync(urls_raw: str, body: str, *, preserve_identity: bool, markdown: bool = True) -> bool:
def _send_sync(urls_raw: str, body: str, *, preserve_identity: bool) -> bool:
"""Send notification synchronously via Apprise. Returns True on success."""
import apprise as apprise_lib
from apprise import NotifyFormat
urls = _parse_urls(urls_raw)
if not urls:
@@ -183,8 +159,7 @@ def _send_sync(urls_raw: str, body: str, *, preserve_identity: bool, markdown: b
url = _normalize_discord_url(url)
notifier.add(url)
body_fmt = NotifyFormat.MARKDOWN if markdown else NotifyFormat.TEXT
return bool(notifier.notify(title="", body=body, body_format=body_fmt))
return bool(notifier.notify(title="", body=body))
class AppriseModule(FanoutModule):
@@ -203,7 +178,6 @@ class AppriseModule(FanoutModule):
return
preserve_identity = self.config.get("preserve_identity", True)
markdown = self.config.get("markdown_format", True)
# Read format strings; treat empty/whitespace as unset (use default).
# Fall back to legacy include_path for pre-migration configs.
@@ -212,73 +186,30 @@ class AppriseModule(FanoutModule):
if body_format_dm is None or body_format_channel is None:
include_path = self.config.get("include_path", True)
if body_format_dm is None:
if markdown:
body_format_dm = (
DEFAULT_BODY_FORMAT_DM if include_path else _DEFAULT_BODY_FORMAT_DM_NO_PATH
)
else:
body_format_dm = (
DEFAULT_BODY_FORMAT_DM_PLAIN
if include_path
else _DEFAULT_BODY_FORMAT_DM_NO_PATH_PLAIN
)
body_format_dm = (
DEFAULT_BODY_FORMAT_DM if include_path else _DEFAULT_BODY_FORMAT_DM_NO_PATH
)
if body_format_channel is None:
if markdown:
body_format_channel = (
DEFAULT_BODY_FORMAT_CHANNEL
if include_path
else _DEFAULT_BODY_FORMAT_CHANNEL_NO_PATH
)
else:
body_format_channel = (
DEFAULT_BODY_FORMAT_CHANNEL_PLAIN
if include_path
else _DEFAULT_BODY_FORMAT_CHANNEL_NO_PATH_PLAIN
)
body_format_channel = (
DEFAULT_BODY_FORMAT_CHANNEL
if include_path
else _DEFAULT_BODY_FORMAT_CHANNEL_NO_PATH
)
body = _format_body(
data,
body_format_dm=body_format_dm,
body_format_channel=body_format_channel,
markdown=markdown,
data, body_format_dm=body_format_dm, body_format_channel=body_format_channel
)
last_exc: Exception | None = None
for attempt in range(_MAX_SEND_ATTEMPTS):
try:
success = await asyncio.to_thread(
_send_sync,
urls,
body,
preserve_identity=preserve_identity,
markdown=markdown,
)
if success:
self._set_last_error(None)
return
logger.warning(
"Apprise notification failed for module %s (attempt %d/%d)",
self.config_id,
attempt + 1,
_MAX_SEND_ATTEMPTS,
)
except Exception as exc:
last_exc = exc
logger.warning(
"Apprise send error for module %s (attempt %d/%d): %s",
self.config_id,
attempt + 1,
_MAX_SEND_ATTEMPTS,
exc,
)
if attempt < _MAX_SEND_ATTEMPTS - 1:
await asyncio.sleep(_RETRY_DELAY_S)
# All attempts exhausted
if last_exc is not None:
self._set_last_error(str(last_exc))
else:
self._set_last_error("Apprise notify returned failure")
try:
success = await asyncio.to_thread(
_send_sync, urls, body, preserve_identity=preserve_identity
)
self._set_last_error(None if success else "Apprise notify returned failure")
if not success:
logger.warning("Apprise notification failed for module %s", self.config_id)
except Exception as exc:
self._set_last_error(str(exc))
logger.exception("Apprise send error for module %s", self.config_id)
@property
def status(self) -> str:
+1 -1
View File
@@ -245,7 +245,7 @@ def _get_client_version() -> str:
class CommunityMqttPublisher(BaseMqttPublisher):
"""Manages the community MQTT connection and publishes raw packets."""
_backoff_max = 3600
_backoff_max = 60
_log_prefix = "Community MQTT"
_not_configured_timeout: float | None = 30
+1 -1
View File
@@ -27,7 +27,7 @@ class PrivateMqttSettings(Protocol):
class MqttPublisher(BaseMqttPublisher):
"""Manages an MQTT connection and publishes mesh network events."""
_backoff_max = 3600
_backoff_max = 30
_log_prefix = "MQTT"
def _is_configured(self) -> bool:
+3 -8
View File
@@ -65,7 +65,6 @@ class BaseMqttPublisher(ABC):
self.connected: bool = False
self.integration_name: str = ""
self._last_error: str | None = None
self._error_notified: bool = False
def set_integration_name(self, name: str) -> None:
"""Attach the configured fanout-module name for operator-facing logs."""
@@ -105,7 +104,6 @@ class BaseMqttPublisher(ABC):
self._client = None
self.connected = False
self._last_error = None
self._error_notified = False
async def restart(self, settings: object) -> None:
"""Called when settings change — stop + start."""
@@ -219,7 +217,6 @@ class BaseMqttPublisher(ABC):
self._client = client
self.connected = True
self._last_error = None
self._error_notified = False
backoff = _BACKOFF_MIN
title, detail = self._on_connected(settings)
@@ -284,11 +281,9 @@ class BaseMqttPublisher(ABC):
)
return
if not self._error_notified:
title, detail = self._on_error()
broadcast_error(title, detail)
_broadcast_health()
self._error_notified = True
title, detail = self._on_error()
broadcast_error(title, detail)
_broadcast_health()
logger.warning(
"%s connection error. This is usually transient network noise; "
"if it self-resolves, it is generally not a concern: %s "
+32 -3
View File
@@ -316,7 +316,7 @@ def _device_payload(
class _HaMqttPublisher(BaseMqttPublisher):
"""Thin MQTT lifecycle wrapper for the HA discovery module."""
_backoff_max = 3600
_backoff_max = 30
_log_prefix = "HA-MQTT"
def __init__(self) -> None:
@@ -576,12 +576,30 @@ class MqttHaModule(FanoutModule):
)
)
# Tracked contacts — resolve names from DB best-effort
# Tracked contacts — resolve names and LPP sensors from DB best-effort
for pub_key in self._tracked_contacts:
cname = await self._resolve_contact_name(pub_key)
configs.append(
_contact_tracker_discovery_config(self._prefix, pub_key, cname, self._radio_key)
)
# LPP sensor entities for contacts with telemetry history
latest_ct = await self._resolve_latest_contact_telemetry(pub_key)
latest_ct_data = latest_ct.get("data", {}) if latest_ct else {}
ct_lpp_sensors = latest_ct_data.get("lpp_sensors", [])
if ct_lpp_sensors:
ct_nid = _node_id(pub_key)
ct_device = _device_payload(pub_key, cname, "Node", via_device_key=self._radio_key)
ct_state_topic = f"{self._prefix}/{ct_nid}/telemetry"
configs.extend(
_lpp_discovery_configs(
self._prefix, pub_key, ct_device, ct_lpp_sensors, ct_state_topic
)
)
if latest_ct_data:
ct_payload = _repeater_telemetry_payload(latest_ct_data)
cached_repeater_states.append(
(f"{self._prefix}/{_node_id(pub_key)}/telemetry", ct_payload)
)
# Message event entity (namespaced to this radio)
configs.append(_message_event_discovery_config(self._prefix, self._radio_key, radio_name))
@@ -644,6 +662,17 @@ class MqttHaModule(FanoutModule):
pass
return None
@staticmethod
async def _resolve_latest_contact_telemetry(pub_key: str) -> dict | None:
"""Return the most recent contact telemetry row, or None."""
try:
from app.repository.contact_telemetry import ContactTelemetryRepository
return await ContactTelemetryRepository.get_latest(pub_key)
except Exception:
pass
return None
def _seed_radio_identity_from_runtime(self) -> None:
"""Best-effort bootstrap from the currently connected radio session."""
try:
@@ -749,7 +778,7 @@ class MqttHaModule(FanoutModule):
return
pub_key = data.get("public_key", "")
if pub_key not in self._tracked_repeaters:
if pub_key not in self._tracked_repeaters and pub_key not in self._tracked_contacts:
return
nid = _node_id(pub_key)
+2 -2
View File
@@ -176,8 +176,8 @@ app.add_middleware(
@app.exception_handler(RadioDisconnectedError)
async def radio_disconnected_handler(request: Request, exc: RadioDisconnectedError):
"""Return 423 when a radio disconnect race occurs during an operation."""
return JSONResponse(status_code=423, content={"detail": "Radio not connected"})
"""Return 503 when a radio disconnect race occurs during an operation."""
return JSONResponse(status_code=503, content={"detail": "Radio not connected"})
@app.middleware("http")
@@ -0,0 +1,40 @@
import logging
import aiosqlite
logger = logging.getLogger(__name__)
async def migrate(conn: aiosqlite.Connection) -> None:
"""Create contact_telemetry_history table and tracked_telemetry_contacts setting."""
tables_cursor = await conn.execute("SELECT name FROM sqlite_master WHERE type='table'")
tables = {row[0] for row in await tables_cursor.fetchall()}
if "contact_telemetry_history" not in tables:
await conn.execute(
"""
CREATE TABLE contact_telemetry_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
public_key TEXT NOT NULL,
timestamp INTEGER NOT NULL,
data TEXT NOT NULL,
FOREIGN KEY (public_key) REFERENCES contacts(public_key) ON DELETE CASCADE
)
"""
)
await conn.execute(
"""
CREATE INDEX IF NOT EXISTS idx_contact_telemetry_pk_ts
ON contact_telemetry_history(public_key, timestamp)
"""
)
if "app_settings" in tables:
col_cursor = await conn.execute("PRAGMA table_info(app_settings)")
columns = {row[1] for row in await col_cursor.fetchall()}
if "tracked_telemetry_contacts" not in columns:
await conn.execute(
"ALTER TABLE app_settings ADD COLUMN tracked_telemetry_contacts TEXT DEFAULT '[]'"
)
await conn.commit()
+21 -7
View File
@@ -1,3 +1,5 @@
from __future__ import annotations
from typing import Literal
from pydantic import BaseModel, Field
@@ -42,7 +44,7 @@ class ContactUpsert(BaseModel):
first_seen: int | None = None
@classmethod
def from_contact(cls, contact: "Contact", **changes) -> "ContactUpsert":
def from_contact(cls, contact: Contact, **changes) -> ContactUpsert:
return cls.model_validate(
{
**contact.model_dump(exclude={"last_read_at"}),
@@ -53,7 +55,7 @@ class ContactUpsert(BaseModel):
@classmethod
def from_radio_dict(
cls, public_key: str, radio_data: dict, on_radio: bool = False
) -> "ContactUpsert":
) -> ContactUpsert:
"""Convert radio contact data to the contact-row write shape."""
direct_path, direct_path_len, direct_path_hash_mode = normalize_contact_route(
radio_data.get("out_path"),
@@ -448,8 +450,6 @@ class RawPacketDecryptedInfo(BaseModel):
sender: str | None = None
channel_key: str | None = None
contact_key: str | None = None
sender_timestamp: int | None = None
message: str | None = None
class RawPacketBroadcast(BaseModel):
@@ -543,7 +543,7 @@ class RepeaterStatusResponse(BaseModel):
direct_dups: int = Field(description="Duplicate direct packets")
full_events: int = Field(description="Full event queue count")
recv_errors: int | None = Field(default=None, description="Radio-level RX packet errors")
telemetry_history: list["TelemetryHistoryEntry"] = Field(
telemetry_history: list[TelemetryHistoryEntry] = Field(
default_factory=list, description="Recent telemetry history snapshots"
)
@@ -598,6 +598,16 @@ class RepeaterLppTelemetryResponse(BaseModel):
sensors: list[LppSensor] = Field(default_factory=list, description="List of sensor readings")
class ContactTelemetryResponse(BaseModel):
"""On-demand CayenneLPP telemetry snapshot from any contact."""
sensors: list[LppSensor] = Field(default_factory=list, description="List of sensor readings")
fetched_at: int = Field(description="Unix timestamp when this telemetry was fetched")
telemetry_history: list[TelemetryHistoryEntry] = Field(
default_factory=list, description="Recent telemetry history entries"
)
class NeighborInfo(BaseModel):
"""Information about a neighbor seen by a repeater."""
@@ -849,18 +859,22 @@ class AppSettings(BaseModel):
default_factory=list,
description="Public keys of repeaters opted into periodic telemetry collection (max 8)",
)
tracked_telemetry_contacts: list[str] = Field(
default_factory=list,
description="Public keys of contacts opted into periodic LPP telemetry collection (max 8)",
)
telemetry_interval_hours: int = Field(
default=8,
description=(
"User-preferred telemetry collection interval in hours. The backend "
"clamps this up to the shortest legal interval given the number of "
"tracked repeaters so daily checks stay under a 24/day ceiling."
"tracked repeaters and contacts so daily checks stay under a 24/day ceiling."
),
)
telemetry_routed_hourly: bool = Field(
default=False,
description=(
"When enabled, tracked repeaters with a direct or routed (non-flood) "
"When enabled, tracked repeaters/contacts with a direct or routed (non-flood) "
"path are polled every hour instead of on the normal scheduled interval."
),
)
-6
View File
@@ -366,8 +366,6 @@ async def process_raw_packet(
sender=result["sender"],
channel_key=result.get("channel_key"),
contact_key=result.get("contact_key"),
sender_timestamp=result.get("sender_timestamp"),
message=result.get("message"),
)
if result["decrypted"]
else None,
@@ -430,8 +428,6 @@ async def _process_group_text(
"sender": decrypted.sender,
"message_id": msg_id, # None if duplicate, msg_id if new
"channel_key": channel.key,
"sender_timestamp": decrypted.timestamp,
"message": decrypted.message,
}
# Couldn't decrypt with any known key
@@ -698,8 +694,6 @@ async def _process_direct_message(
"sender": contact.name or contact.public_key[:12],
"message_id": msg_id,
"contact_key": contact.public_key,
"sender_timestamp": result.timestamp,
"message": result.message,
}
# Couldn't decrypt with any known contact
+114 -15
View File
@@ -31,6 +31,7 @@ from app.repository import (
ContactRepository,
RepeaterTelemetryRepository,
)
from app.repository.contact_telemetry import ContactTelemetryRepository
from app.services.contact_reconciliation import (
promote_prefix_contacts_for_contact,
reconcile_contact_messages,
@@ -1890,10 +1891,87 @@ async def _collect_repeater_telemetry(mc: MeshCore, contact: Contact) -> bool:
return False
async def _run_telemetry_cycle(*, routed_only: bool = False) -> None:
"""Collect one telemetry sample from tracked repeaters.
async def _collect_contact_telemetry(mc: MeshCore, contact: Contact) -> bool:
"""Fetch LPP telemetry from a non-repeater contact and record it.
When *routed_only* is True, only repeaters whose effective route is
Unlike repeaters, companions/rooms/sensors only respond to
req_telemetry_sync (LPP), not req_status_sync (repeater status struct).
All sensor values including multi-value (GPS, accel) are stored.
Returns True on success, False on failure (logged, not raised).
"""
try:
await mc.commands.add_contact(contact.to_radio_dict())
lpp_raw = await mc.commands.req_telemetry_sync(
contact.public_key, timeout=10, min_timeout=5
)
except Exception as e:
logger.debug(
"Contact telemetry collect: radio command failed for %s: %s",
contact.public_key[:12],
e,
)
return False
if lpp_raw is None:
logger.debug("Contact telemetry collect: no response from %s", contact.public_key[:12])
return False
lpp_sensors = []
for entry in lpp_raw:
lpp_sensors.append(
{
"channel": entry.get("channel", 0),
"type_name": str(entry.get("type", "unknown")),
"value": entry.get("value", 0),
}
)
data: dict = {}
if lpp_sensors:
data["lpp_sensors"] = lpp_sensors
try:
timestamp = int(time.time())
await ContactTelemetryRepository.record(
public_key=contact.public_key,
timestamp=timestamp,
data=data,
)
logger.info(
"Contact telemetry collect: recorded snapshot for %s (%s)",
contact.name or contact.public_key[:12],
contact.public_key[:12],
)
# Dispatch to fanout modules
from app.fanout.manager import fanout_manager
asyncio.create_task(
fanout_manager.broadcast_telemetry(
{
"public_key": contact.public_key,
"name": contact.name or contact.public_key[:12],
"timestamp": timestamp,
**data,
}
)
)
return True
except Exception as e:
logger.warning(
"Contact telemetry collect: failed to record for %s: %s",
contact.public_key[:12],
e,
)
return False
async def _run_telemetry_cycle(*, routed_only: bool = False) -> None:
"""Collect one telemetry sample from tracked repeaters and contacts.
When *routed_only* is True, only targets whose effective route is
``"direct"`` or ``"override"`` (i.e. not ``"flood"``) are collected.
This is used by the hourly routed-path fast-poll feature.
"""
@@ -1902,12 +1980,14 @@ async def _run_telemetry_cycle(*, routed_only: bool = False) -> None:
return
app_settings = await AppSettingsRepository.get()
tracked = app_settings.tracked_telemetry_repeaters
if not tracked:
tracked_repeaters = app_settings.tracked_telemetry_repeaters
tracked_contacts = app_settings.tracked_telemetry_contacts
if not tracked_repeaters and not tracked_contacts:
return
candidates: list[tuple[str, Contact]] = []
for pub_key in tracked:
# Build repeater candidates
candidates: list[tuple[str, Contact, bool]] = [] # (key, contact, is_repeater)
for pub_key in tracked_repeaters:
contact = await ContactRepository.get_by_key(pub_key)
if not contact or contact.type != 2:
logger.debug(
@@ -1917,29 +1997,46 @@ async def _run_telemetry_cycle(*, routed_only: bool = False) -> None:
continue
if routed_only and (not contact.effective_route or contact.effective_route.path_len < 0):
continue
candidates.append((pub_key, contact))
candidates.append((pub_key, contact, True))
# Build contact (non-repeater) candidates
for pub_key in tracked_contacts:
contact = await ContactRepository.get_by_key(pub_key)
if not contact:
logger.debug(
"Telemetry collect: skipping contact %s (not found)",
pub_key[:12],
)
continue
if routed_only and (not contact.effective_route or contact.effective_route.path_len < 0):
continue
candidates.append((pub_key, contact, False))
if not candidates:
if routed_only:
logger.debug("Telemetry collect: no routed repeaters to poll this hour")
logger.debug("Telemetry collect: no routed targets to poll this hour")
return
label = "routed" if routed_only else "full"
logger.info(
"Telemetry collect: starting %s cycle for %d repeater(s)",
"Telemetry collect: starting %s cycle for %d target(s)",
label,
len(candidates),
)
collected = 0
for _pub_key, contact in candidates:
for _pub_key, contact, is_repeater in candidates:
try:
async with radio_manager.radio_operation(
"telemetry_collect",
blocking=False,
suspend_auto_fetch=True,
) as mc:
if await _collect_repeater_telemetry(mc, contact):
if is_repeater:
success = await _collect_repeater_telemetry(mc, contact)
else:
success = await _collect_contact_telemetry(mc, contact)
if success:
collected += 1
except RadioOperationBusyError:
logger.debug(
@@ -1975,7 +2072,9 @@ async def _maybe_run_scheduled_cycle(now: datetime) -> None:
telemetry).
"""
app_settings = await AppSettingsRepository.get()
tracked_count = len(app_settings.tracked_telemetry_repeaters)
tracked_count = len(app_settings.tracked_telemetry_repeaters) + len(
app_settings.tracked_telemetry_contacts
)
if tracked_count == 0:
return
effective_hours = clamp_telemetry_interval(app_settings.telemetry_interval_hours, tracked_count)
@@ -1985,10 +2084,10 @@ async def _maybe_run_scheduled_cycle(now: datetime) -> None:
is_normal_cycle = now.hour % effective_hours == 0
if is_normal_cycle:
# Normal scheduled boundary: collect ALL tracked repeaters.
# Normal scheduled boundary: collect ALL tracked targets.
await _run_telemetry_cycle()
elif app_settings.telemetry_routed_hourly:
# Hourly routed-path fast-poll: only repeaters with a non-flood route.
# Hourly routed-path fast-poll: only targets with a non-flood route.
await _run_telemetry_cycle(routed_only=True)
+100
View File
@@ -0,0 +1,100 @@
import json
import logging
import time
from app.database import db
logger = logging.getLogger(__name__)
# Maximum age for telemetry history entries (30 days)
_MAX_AGE_SECONDS = 30 * 86400
# Maximum entries to keep per contact (sanity cap)
_MAX_ENTRIES_PER_CONTACT = 1000
class ContactTelemetryRepository:
@staticmethod
async def record(
public_key: str,
timestamp: int,
data: dict,
) -> None:
"""Insert a telemetry history row and prune stale entries."""
cutoff = int(time.time()) - _MAX_AGE_SECONDS
async with db.tx() as conn:
async with conn.execute(
"""
INSERT INTO contact_telemetry_history
(public_key, timestamp, data)
VALUES (?, ?, ?)
""",
(public_key, timestamp, json.dumps(data)),
):
pass
# Prune entries older than 30 days
async with conn.execute(
"DELETE FROM contact_telemetry_history WHERE public_key = ? AND timestamp < ?",
(public_key, cutoff),
):
pass
# Cap at _MAX_ENTRIES_PER_CONTACT (keep newest)
async with conn.execute(
"""
DELETE FROM contact_telemetry_history
WHERE public_key = ? AND id NOT IN (
SELECT id FROM contact_telemetry_history
WHERE public_key = ?
ORDER BY timestamp DESC
LIMIT ?
)
""",
(public_key, public_key, _MAX_ENTRIES_PER_CONTACT),
):
pass
@staticmethod
async def get_history(public_key: str, since_timestamp: int) -> list[dict]:
"""Return telemetry rows for a contact since a given timestamp, ordered ASC."""
async with db.readonly() as conn:
async with conn.execute(
"""
SELECT timestamp, data
FROM contact_telemetry_history
WHERE public_key = ? AND timestamp >= ?
ORDER BY timestamp ASC
""",
(public_key, since_timestamp),
) as cursor:
rows = await cursor.fetchall()
return [
{
"timestamp": row["timestamp"],
"data": json.loads(row["data"]),
}
for row in rows
]
@staticmethod
async def get_latest(public_key: str) -> dict | None:
"""Return the most recent telemetry row for a contact, or None."""
async with db.readonly() as conn:
async with conn.execute(
"""
SELECT timestamp, data
FROM contact_telemetry_history
WHERE public_key = ?
ORDER BY timestamp DESC
LIMIT 1
""",
(public_key,),
) as cursor:
row = await cursor.fetchone()
if row is None:
return None
return {
"timestamp": row["timestamp"],
"data": json.loads(row["data"]),
}
+19 -1
View File
@@ -41,7 +41,8 @@ class AppSettingsRepository:
last_message_times,
advert_interval, last_advert_time, flood_scope,
blocked_keys, blocked_names, discovery_blocked_types,
tracked_telemetry_repeaters, auto_resend_channel,
tracked_telemetry_repeaters, tracked_telemetry_contacts,
auto_resend_channel,
telemetry_interval_hours, telemetry_routed_hourly
FROM app_settings WHERE id = 1
"""
@@ -97,6 +98,15 @@ class AppSettingsRepository:
except (json.JSONDecodeError, TypeError, KeyError):
tracked_telemetry_repeaters = []
# Parse tracked_telemetry_contacts JSON
tracked_telemetry_contacts: list[str] = []
try:
raw_tracked_contacts = row["tracked_telemetry_contacts"]
if raw_tracked_contacts:
tracked_telemetry_contacts = json.loads(raw_tracked_contacts)
except (json.JSONDecodeError, TypeError, KeyError):
tracked_telemetry_contacts = []
# Parse auto_resend_channel boolean
try:
auto_resend_channel = bool(row["auto_resend_channel"])
@@ -130,6 +140,7 @@ class AppSettingsRepository:
blocked_names=blocked_names,
discovery_blocked_types=discovery_blocked_types,
tracked_telemetry_repeaters=tracked_telemetry_repeaters,
tracked_telemetry_contacts=tracked_telemetry_contacts,
auto_resend_channel=auto_resend_channel,
telemetry_interval_hours=telemetry_interval_hours,
telemetry_routed_hourly=telemetry_routed_hourly,
@@ -149,6 +160,7 @@ class AppSettingsRepository:
blocked_names: list[str] | None = None,
discovery_blocked_types: list[int] | None = None,
tracked_telemetry_repeaters: list[str] | None = None,
tracked_telemetry_contacts: list[str] | None = None,
auto_resend_channel: bool | None = None,
telemetry_interval_hours: int | None = None,
telemetry_routed_hourly: bool | None = None,
@@ -201,6 +213,10 @@ class AppSettingsRepository:
updates.append("tracked_telemetry_repeaters = ?")
params.append(json.dumps(tracked_telemetry_repeaters))
if tracked_telemetry_contacts is not None:
updates.append("tracked_telemetry_contacts = ?")
params.append(json.dumps(tracked_telemetry_contacts))
if auto_resend_channel is not None:
updates.append("auto_resend_channel = ?")
params.append(1 if auto_resend_channel else 0)
@@ -239,6 +255,7 @@ class AppSettingsRepository:
blocked_names: list[str] | None = None,
discovery_blocked_types: list[int] | None = None,
tracked_telemetry_repeaters: list[str] | None = None,
tracked_telemetry_contacts: list[str] | None = None,
auto_resend_channel: bool | None = None,
telemetry_interval_hours: int | None = None,
telemetry_routed_hourly: bool | None = None,
@@ -257,6 +274,7 @@ class AppSettingsRepository:
blocked_names=blocked_names,
discovery_blocked_types=discovery_blocked_types,
tracked_telemetry_repeaters=tracked_telemetry_repeaters,
tracked_telemetry_contacts=tracked_telemetry_contacts,
auto_resend_channel=auto_resend_channel,
telemetry_interval_hours=telemetry_interval_hours,
telemetry_routed_hourly=telemetry_routed_hourly,
+91 -6
View File
@@ -14,11 +14,14 @@ from app.models import (
ContactAdvertPathSummary,
ContactAnalytics,
ContactRoutingOverrideRequest,
ContactTelemetryResponse,
ContactUpsert,
CreateContactRequest,
LppSensor,
NearestRepeater,
PathDiscoveryResponse,
PathDiscoveryRoute,
TelemetryHistoryEntry,
TraceResponse,
)
from app.packet_processor import start_historical_dm_decryption
@@ -66,11 +69,11 @@ async def _resolve_contact_or_404(
async def _ensure_on_radio(mc, contact: Contact) -> None:
"""Add a contact to the radio for routing, raising 422 on failure."""
"""Add a contact to the radio for routing, raising 500 on failure."""
add_result = await mc.commands.add_contact(contact.to_radio_dict())
if add_result is not None and add_result.type == EventType.ERROR:
raise HTTPException(
status_code=422, detail=f"Failed to add contact to radio: {add_result.payload}"
status_code=500, detail=f"Failed to add contact to radio: {add_result.payload}"
)
@@ -452,7 +455,7 @@ async def request_trace(public_key: str) -> TraceResponse:
)
if result.type == EventType.ERROR:
raise HTTPException(status_code=422, detail=f"Failed to send trace: {result.payload}")
raise HTTPException(status_code=500, detail=f"Failed to send trace: {result.payload}")
# Wait for the matching TRACE_DATA event
event = await mc.wait_for_event(
@@ -462,7 +465,7 @@ async def request_trace(public_key: str) -> TraceResponse:
)
if event is None:
raise HTTPException(status_code=408, detail="No trace response heard")
raise HTTPException(status_code=504, detail="No trace response heard")
trace = event.payload
path = trace.get("path", [])
@@ -506,7 +509,7 @@ async def request_path_discovery(public_key: str) -> PathDiscoveryResponse:
result = await mc.commands.send_path_discovery(contact.public_key)
if result.type == EventType.ERROR:
raise HTTPException(
status_code=422,
status_code=500,
detail=f"Failed to send path discovery: {result.payload}",
)
@@ -518,7 +521,7 @@ async def request_path_discovery(public_key: str) -> PathDiscoveryResponse:
await response_task
if event is None:
raise HTTPException(status_code=408, detail="No path discovery response heard")
raise HTTPException(status_code=504, detail="No path discovery response heard")
payload = event.payload
forward_path = str(payload.get("out_path") or "")
@@ -613,3 +616,85 @@ async def set_contact_routing_override(
await _broadcast_contact_update(updated_contact)
return {"status": "ok", "public_key": contact.public_key}
# ---------------------------------------------------------------------------
# On-demand contact telemetry (CayenneLPP)
# ---------------------------------------------------------------------------
@router.post("/{public_key}/telemetry", response_model=ContactTelemetryResponse)
async def request_contact_telemetry(public_key: str) -> ContactTelemetryResponse:
"""Fetch CayenneLPP telemetry from any contact (single attempt, 10s timeout).
Persists the result in contact_telemetry_history and returns the latest
sensor readings along with recent telemetry history.
"""
from app.repository.contact_telemetry import ContactTelemetryRepository
radio_manager.require_connected()
contact = await _resolve_contact_or_404(public_key)
async with radio_manager.radio_operation(
"contact_telemetry", pause_polling=True, suspend_auto_fetch=True
) as mc:
await _ensure_on_radio(mc, contact)
telemetry = await mc.commands.req_telemetry_sync(
contact.public_key, timeout=10, min_timeout=5
)
if telemetry is None:
raise HTTPException(status_code=504, detail="No telemetry response from contact")
sensors: list[LppSensor] = []
for entry in telemetry:
channel = entry.get("channel", 0)
type_name = str(entry.get("type", "unknown"))
value = entry.get("value", 0)
sensors.append(LppSensor(channel=channel, type_name=type_name, value=value))
fetched_at = int(time.time())
# Persist snapshot
data = {"lpp_sensors": [s.model_dump() for s in sensors]}
await ContactTelemetryRepository.record(
public_key=contact.public_key,
timestamp=fetched_at,
data=data,
)
# Dispatch to fanout modules (e.g. HA MQTT)
from app.fanout.manager import fanout_manager
asyncio.create_task(
fanout_manager.broadcast_telemetry(
{
"public_key": contact.public_key,
"name": contact.name or contact.public_key[:12],
"timestamp": fetched_at,
**data,
}
)
)
# Fetch recent history (30 days)
since = fetched_at - 30 * 86400
rows = await ContactTelemetryRepository.get_history(contact.public_key, since)
history = [TelemetryHistoryEntry(**row) for row in rows]
return ContactTelemetryResponse(
sensors=sensors,
fetched_at=fetched_at,
telemetry_history=history,
)
@router.get("/{public_key}/telemetry-history", response_model=list[TelemetryHistoryEntry])
async def get_contact_telemetry_history(public_key: str) -> list[TelemetryHistoryEntry]:
"""Get stored telemetry history for a contact (read-only, no radio access)."""
from app.repository.contact_telemetry import ContactTelemetryRepository
contact = await _resolve_contact_or_404(public_key)
since = int(time.time()) - 30 * 86400
rows = await ContactTelemetryRepository.get_history(contact.public_key, since)
return [TelemetryHistoryEntry(**row) for row in rows]
-4
View File
@@ -274,10 +274,6 @@ def _validate_apprise_config(config: dict) -> None:
status_code=400, detail=f"Invalid format string in {field}"
) from None
markdown_format = config.get("markdown_format")
if markdown_format is not None:
config["markdown_format"] = bool(markdown_format)
def _validate_webhook_config(config: dict) -> None:
"""Validate webhook config blob."""
-4
View File
@@ -128,15 +128,11 @@ async def get_raw_packet(packet_id: int) -> RawPacketDetail:
sender=message.sender_name,
channel_key=message.conversation_key,
contact_key=message.sender_key,
sender_timestamp=message.sender_timestamp,
message=message.text,
)
else:
decrypted_info = RawPacketDecryptedInfo(
sender=message.sender_name,
contact_key=message.conversation_key,
sender_timestamp=message.sender_timestamp,
message=message.text,
)
return RawPacketDetail(
+5 -5
View File
@@ -48,7 +48,7 @@ async def vapid_public_key() -> VapidPublicKeyResponse:
"""Return the VAPID public key for browser PushManager.subscribe()."""
key = get_vapid_public_key()
if not key:
raise HTTPException(status_code=423, detail="VAPID keys not initialized")
raise HTTPException(status_code=503, detail="VAPID keys not initialized")
return VapidPublicKeyResponse(public_key=key)
@@ -103,7 +103,7 @@ async def test_push(subscription_id: str) -> dict:
vapid_key = get_vapid_private_key()
if not vapid_key:
raise HTTPException(status_code=423, detail="VAPID keys not initialized")
raise HTTPException(status_code=503, detail="VAPID keys not initialized")
payload = json.dumps(
{
@@ -127,7 +127,7 @@ async def test_push(subscription_id: str) -> dict:
)
return {"status": "sent"}
except TimeoutError:
raise HTTPException(status_code=408, detail="Push delivery timed out") from None
raise HTTPException(status_code=504, detail="Push delivery timed out") from None
except WebPushException as e:
status_code = getattr(getattr(e, "response", None), "status_code", 0)
if status_code in (403, 404, 410):
@@ -143,10 +143,10 @@ async def test_push(subscription_id: str) -> dict:
"Re-enable push from a conversation header.",
) from None
logger.warning("Test push failed: %s", e)
raise HTTPException(status_code=422, detail=f"Push delivery failed: {e}") from None
raise HTTPException(status_code=502, detail=f"Push delivery failed: {e}") from None
except Exception as e:
logger.warning("Test push failed: %s", e)
raise HTTPException(status_code=422, detail=f"Push delivery failed: {e}") from None
raise HTTPException(status_code=502, detail=f"Push delivery failed: {e}") from None
# ── Global push conversation management ──────────────────────────────────
+39 -15
View File
@@ -101,6 +101,18 @@ class RadioConfigResponse(BaseModel):
default=False,
description="Whether the radio sends an extra direct ACK transmission",
)
telemetry_mode_base: int = Field(
default=0,
description="Base telemetry sharing mode (0=deny, 1=per-contact, 2=allow-all)",
)
telemetry_mode_loc: int = Field(
default=0,
description="Location telemetry sharing mode (0=deny, 1=per-contact, 2=allow-all)",
)
telemetry_mode_env: int = Field(
default=0,
description="Environment sensor sharing mode (0=deny, 1=per-contact, 2=allow-all)",
)
class RadioConfigUpdate(BaseModel):
@@ -123,6 +135,15 @@ class RadioConfigUpdate(BaseModel):
default=None,
description="Whether the radio sends an extra direct ACK transmission",
)
telemetry_mode_base: int | None = Field(
default=None, ge=0, le=2, description="Base telemetry sharing mode"
)
telemetry_mode_loc: int | None = Field(
default=None, ge=0, le=2, description="Location telemetry sharing mode"
)
telemetry_mode_env: int | None = Field(
default=None, ge=0, le=2, description="Environment sensor sharing mode"
)
class PrivateKeyUpdate(BaseModel):
@@ -338,7 +359,7 @@ async def get_radio_config() -> RadioConfigResponse:
info = mc.self_info
if not info:
raise HTTPException(status_code=423, detail="Radio info not available")
raise HTTPException(status_code=503, detail="Radio info not available")
adv_loc_policy = info.get("adv_loc_policy", 1)
advert_location_source: AdvertLocationSource = "off" if adv_loc_policy == 0 else "current"
@@ -360,6 +381,9 @@ async def get_radio_config() -> RadioConfigResponse:
path_hash_mode_supported=radio_manager.path_hash_mode_supported,
advert_location_source=advert_location_source,
multi_acks_enabled=bool(info.get("multi_acks", 0)),
telemetry_mode_base=info.get("telemetry_mode_base", 0),
telemetry_mode_loc=info.get("telemetry_mode_loc", 0),
telemetry_mode_env=info.get("telemetry_mode_env", 0),
)
@@ -380,7 +404,7 @@ async def update_radio_config(update: RadioConfigUpdate) -> RadioConfigResponse:
except PathHashModeUnsupportedError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
except RadioCommandRejectedError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
raise HTTPException(status_code=500, detail=str(exc)) from exc
return await get_radio_config()
@@ -430,7 +454,7 @@ async def set_private_key(update: PrivateKeyUpdate) -> dict:
export_and_store_private_key_fn=export_and_store_private_key,
)
except (RadioCommandRejectedError, KeystoreRefreshError) as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
raise HTTPException(status_code=500, detail=str(exc)) from exc
return {"status": "ok"}
@@ -454,7 +478,7 @@ async def send_advertisement(request: RadioAdvertiseRequest | None = None) -> di
success = await do_send_advertisement(mc, force=True, mode=mode)
if not success:
raise HTTPException(status_code=422, detail=f"Failed to send {mode} advertisement")
raise HTTPException(status_code=500, detail=f"Failed to send {mode} advertisement")
return {"status": "ok"}
@@ -486,7 +510,7 @@ async def discover_mesh(request: RadioDiscoveryRequest) -> RadioDiscoveryRespons
tag=tag,
)
if send_result is None or send_result.type == EventType.ERROR:
raise HTTPException(status_code=422, detail="Failed to start mesh discovery")
raise HTTPException(status_code=500, detail="Failed to start mesh discovery")
deadline = _monotonic() + DISCOVERY_WINDOW_SECONDS
results_by_key: dict[str, RadioDiscoveryResult] = {}
@@ -538,7 +562,7 @@ async def trace_path(request: RadioTraceRequest) -> RadioTraceResponse:
async with radio_manager.radio_operation("radio_trace", pause_polling=True) as mc:
local_public_key = str((mc.self_info or {}).get("public_key") or "").lower()
if len(local_public_key) != 64:
raise HTTPException(status_code=423, detail="Local radio public key is unavailable")
raise HTTPException(status_code=503, detail="Local radio public key is unavailable")
local_name = (mc.self_info or {}).get("name")
response_task = asyncio.create_task(
@@ -555,13 +579,13 @@ async def trace_path(request: RadioTraceRequest) -> RadioTraceResponse:
flags=trace_flags,
)
if send_result is None or send_result.type == EventType.ERROR:
raise HTTPException(status_code=422, detail="Failed to send trace")
raise HTTPException(status_code=500, detail="Failed to send trace")
timeout_seconds = _trace_timeout_seconds(send_result)
try:
event = await asyncio.wait_for(response_task, timeout=timeout_seconds)
except TimeoutError as exc:
raise HTTPException(status_code=408, detail="No trace response heard") from exc
raise HTTPException(status_code=504, detail="No trace response heard") from exc
finally:
if not response_task.done():
response_task.cancel()
@@ -569,12 +593,12 @@ async def trace_path(request: RadioTraceRequest) -> RadioTraceResponse:
await response_task
if event is None:
raise HTTPException(status_code=408, detail="No trace response heard")
raise HTTPException(status_code=504, detail="No trace response heard")
payload = event.payload if isinstance(event.payload, dict) else {}
path_len = payload.get("path_len")
if not isinstance(path_len, int):
raise HTTPException(status_code=422, detail="Trace response was malformed")
raise HTTPException(status_code=500, detail="Trace response was malformed")
raw_path = payload.get("path")
path_nodes = raw_path if isinstance(raw_path, list) else []
@@ -588,7 +612,7 @@ async def trace_path(request: RadioTraceRequest) -> RadioTraceResponse:
hashed_nodes = path_nodes[:-1] if final_local_node is not None else path_nodes
if len(hashed_nodes) < len(trace_nodes):
raise HTTPException(status_code=422, detail="Trace response was incomplete")
raise HTTPException(status_code=500, detail="Trace response was incomplete")
nodes: list[RadioTraceNode] = []
for index, trace_node in enumerate(trace_nodes):
@@ -641,13 +665,13 @@ async def _attempt_reconnect() -> dict:
except Exception as e:
logger.exception("Post-connect setup failed after reconnect")
raise HTTPException(
status_code=423,
status_code=503,
detail=f"Radio connected but setup failed: {e}",
) from e
if not success:
raise HTTPException(
status_code=423, detail="Failed to reconnect. Check radio connection and power."
status_code=503, detail="Failed to reconnect. Check radio connection and power."
)
return {"status": "ok", "message": "Reconnected successfully", "connected": True}
@@ -702,14 +726,14 @@ async def reconnect_radio() -> dict:
logger.info("Radio connected but setup incomplete, retrying setup")
try:
if not await _prepare_connected(broadcast_on_success=True):
raise HTTPException(status_code=423, detail="Radio connection is paused")
raise HTTPException(status_code=503, detail="Radio connection is paused")
return {"status": "ok", "message": "Setup completed", "connected": True}
except HTTPException:
raise
except Exception as e:
logger.exception("Post-connect setup failed")
raise HTTPException(
status_code=423,
status_code=503,
detail=f"Radio connected but setup failed: {e}",
) from e
+2 -2
View File
@@ -113,7 +113,7 @@ async def repeater_status(public_key: str) -> RepeaterStatusResponse:
logger.debug("LPP sensor fetch failed for %s (non-fatal): %s", public_key[:12], e)
if status is None:
raise HTTPException(status_code=408, detail="No status response from repeater")
raise HTTPException(status_code=504, detail="No status response from repeater")
response = RepeaterStatusResponse(
battery_volts=status.get("bat", 0) / 1000.0,
@@ -222,7 +222,7 @@ async def repeater_lpp_telemetry(public_key: str) -> RepeaterLppTelemetryRespons
)
if telemetry is None:
raise HTTPException(status_code=408, detail="No telemetry response from repeater")
raise HTTPException(status_code=504, detail="No telemetry response from repeater")
sensors: list[LppSensor] = []
for entry in telemetry:
+2 -2
View File
@@ -58,7 +58,7 @@ async def room_status(public_key: str) -> RepeaterStatusResponse:
status = await mc.commands.req_status_sync(contact.public_key, timeout=10, min_timeout=5)
if status is None:
raise HTTPException(status_code=408, detail="No status response from room server")
raise HTTPException(status_code=504, detail="No status response from room server")
return RepeaterStatusResponse(
battery_volts=status.get("bat", 0) / 1000.0,
@@ -98,7 +98,7 @@ async def room_lpp_telemetry(public_key: str) -> RepeaterLppTelemetryResponse:
)
if telemetry is None:
raise HTTPException(status_code=408, detail="No telemetry response from room server")
raise HTTPException(status_code=504, detail="No telemetry response from room server")
sensors = [
LppSensor(
+1 -1
View File
@@ -291,7 +291,7 @@ async def send_contact_cli_command(
if send_result.type == EventType.ERROR:
raise HTTPException(
status_code=422, detail=f"Failed to send command: {send_result.payload}"
status_code=500, detail=f"Failed to send command: {send_result.payload}"
)
response_event = await fetch_contact_cli_response(mc, contact.public_key[:12])
+118 -3
View File
@@ -20,6 +20,7 @@ logger = logging.getLogger(__name__)
router = APIRouter(prefix="/settings", tags=["settings"])
MAX_TRACKED_TELEMETRY_REPEATERS = 8
MAX_TRACKED_TELEMETRY_CONTACTS = 8
class AppSettingsUpdate(BaseModel):
@@ -350,6 +351,8 @@ async def toggle_tracked_telemetry(request: TrackedTelemetryRequest) -> TrackedT
names[k] = contact.name if contact and contact.name else k[:12]
return names
n_contacts = len(settings.tracked_telemetry_contacts)
if key in current:
# Remove
new_list = [k for k in current if k != key]
@@ -359,7 +362,7 @@ async def toggle_tracked_telemetry(request: TrackedTelemetryRequest) -> TrackedT
tracked_telemetry_repeaters=new_list,
names=await _resolve_names(new_list),
schedule=_build_schedule(
len(new_list),
len(new_list) + n_contacts,
settings.telemetry_interval_hours,
settings.telemetry_routed_hourly,
),
@@ -390,7 +393,7 @@ async def toggle_tracked_telemetry(request: TrackedTelemetryRequest) -> TrackedT
tracked_telemetry_repeaters=new_list,
names=await _resolve_names(new_list),
schedule=_build_schedule(
len(new_list),
len(new_list) + n_contacts,
settings.telemetry_interval_hours,
settings.telemetry_routed_hourly,
),
@@ -404,10 +407,122 @@ async def get_telemetry_schedule() -> TelemetrySchedule:
The UI uses this to render the interval dropdown (legal options),
surface saved-vs-effective when they differ, and show the next-run-at
timestamp so users know when the next cycle will fire.
The tracked count includes both repeaters and contacts for ceiling
enforcement.
"""
app_settings = await AppSettingsRepository.get()
combined_count = len(app_settings.tracked_telemetry_repeaters) + len(
app_settings.tracked_telemetry_contacts
)
return _build_schedule(
len(app_settings.tracked_telemetry_repeaters),
combined_count,
app_settings.telemetry_interval_hours,
app_settings.telemetry_routed_hourly,
)
# ---------------------------------------------------------------------------
# Tracked contact telemetry (non-repeater LPP telemetry collection)
# ---------------------------------------------------------------------------
class TrackedTelemetryContactsResponse(BaseModel):
tracked_telemetry_contacts: list[str] = Field(
description="Current list of tracked contact public keys"
)
names: dict[str, str] = Field(
description="Map of public key to display name for tracked contacts"
)
schedule: TelemetrySchedule = Field(description="Current scheduling state")
@router.post("/tracked-telemetry-contacts/toggle", response_model=TrackedTelemetryContactsResponse)
async def toggle_tracked_telemetry_contact(
request: TrackedTelemetryRequest,
) -> TrackedTelemetryContactsResponse:
"""Toggle periodic LPP telemetry collection for any contact.
Max 8 contacts may be tracked. The daily check ceiling is shared with
tracked repeaters.
"""
key = request.public_key.lower()
settings = await AppSettingsRepository.get()
current = settings.tracked_telemetry_contacts
async def _resolve_names(keys: list[str]) -> dict[str, str]:
names: dict[str, str] = {}
for k in keys:
contact = await ContactRepository.get_by_key(k)
names[k] = contact.name if contact and contact.name else k[:12]
return names
def combined_count(lst: list[str]) -> int:
return len(settings.tracked_telemetry_repeaters) + len(lst)
if key in current:
# Remove
new_list = [k for k in current if k != key]
logger.info("Removing contact %s from tracked telemetry", key[:12])
await AppSettingsRepository.update(tracked_telemetry_contacts=new_list)
return TrackedTelemetryContactsResponse(
tracked_telemetry_contacts=new_list,
names=await _resolve_names(new_list),
schedule=_build_schedule(
combined_count(new_list),
settings.telemetry_interval_hours,
settings.telemetry_routed_hourly,
),
)
# Validate contact exists and is not a repeater (repeaters use tracked_telemetry_repeaters)
contact = await ContactRepository.get_by_key(key)
if not contact:
raise HTTPException(status_code=404, detail="Contact not found")
if contact.type == CONTACT_TYPE_REPEATER:
raise HTTPException(
status_code=400,
detail="Repeaters use the dedicated repeater telemetry tracking list",
)
if len(current) >= MAX_TRACKED_TELEMETRY_CONTACTS:
names = await _resolve_names(current)
raise HTTPException(
status_code=409,
detail={
"message": f"Limit of {MAX_TRACKED_TELEMETRY_CONTACTS} tracked contacts reached",
"tracked_telemetry_contacts": current,
"names": names,
},
)
new_list = current + [key]
logger.info("Adding contact %s to tracked telemetry", key[:12])
await AppSettingsRepository.update(tracked_telemetry_contacts=new_list)
return TrackedTelemetryContactsResponse(
tracked_telemetry_contacts=new_list,
names=await _resolve_names(new_list),
schedule=_build_schedule(
combined_count(new_list),
settings.telemetry_interval_hours,
settings.telemetry_routed_hourly,
),
)
@router.get("/tracked-telemetry-contacts/schedule", response_model=TelemetrySchedule)
async def get_contact_telemetry_schedule() -> TelemetrySchedule:
"""Return the current telemetry scheduling derivation for contacts.
Uses the combined tracked count (repeaters + contacts) for ceiling
enforcement since they share one collection loop.
"""
app_settings = await AppSettingsRepository.get()
combined_count = len(app_settings.tracked_telemetry_repeaters) + len(
app_settings.tracked_telemetry_contacts
)
return _build_schedule(
combined_count,
app_settings.telemetry_interval_hours,
app_settings.telemetry_routed_hourly,
)
+16 -16
View File
@@ -159,7 +159,7 @@ async def send_channel_message_with_effective_scope(
override_result.payload,
)
raise HTTPException(
status_code=422,
status_code=500,
detail=(
f"Failed to apply regional override {override_scope!r} before {action_label}: "
f"{override_result.payload}"
@@ -189,7 +189,7 @@ async def send_channel_message_with_effective_scope(
phm_result.payload,
)
raise HTTPException(
status_code=422,
status_code=500,
detail=(
f"Failed to apply path hash mode override before {action_label}: "
f"{phm_result.payload}"
@@ -233,7 +233,7 @@ async def send_channel_message_with_effective_scope(
set_result.payload,
)
raise HTTPException(
status_code=422,
status_code=500,
detail=f"Failed to configure channel on radio before {action_label}",
)
radio_manager.note_channel_slot_loaded(channel_key, channel_slot)
@@ -256,7 +256,7 @@ async def send_channel_message_with_effective_scope(
action_label,
channel.name,
)
raise HTTPException(status_code=408, detail=NO_RADIO_RESPONSE_AFTER_SEND_DETAIL)
raise HTTPException(status_code=504, detail=NO_RADIO_RESPONSE_AFTER_SEND_DETAIL)
if send_result.type == EventType.ERROR:
logger.error(
"Radio returned error during %s for channel %s: %s",
@@ -598,10 +598,10 @@ async def send_direct_message_to_contact(
"No response from radio after direct send to %s; send outcome is unknown",
contact.public_key[:12],
)
raise HTTPException(status_code=408, detail=NO_RADIO_RESPONSE_AFTER_SEND_DETAIL)
raise HTTPException(status_code=504, detail=NO_RADIO_RESPONSE_AFTER_SEND_DETAIL)
if result.type == EventType.ERROR:
raise HTTPException(status_code=422, detail=f"Failed to send message: {result.payload}")
raise HTTPException(status_code=500, detail=f"Failed to send message: {result.payload}")
message = await create_outgoing_direct_message(
conversation_key=contact.public_key.lower(),
@@ -613,7 +613,7 @@ async def send_direct_message_to_contact(
)
if message is None:
raise HTTPException(
status_code=422,
status_code=500,
detail="Failed to store outgoing message - unexpected duplicate",
)
finally:
@@ -626,7 +626,7 @@ async def send_direct_message_to_contact(
)
if sent_at is None or sender_timestamp is None or message is None or result is None:
raise HTTPException(status_code=422, detail="Failed to store outgoing message")
raise HTTPException(status_code=500, detail="Failed to store outgoing message")
await contact_repository.update_last_contacted(contact.public_key.lower(), sent_at)
@@ -791,7 +791,7 @@ async def send_channel_message_to_channel(
)
if outgoing_message is None:
raise HTTPException(
status_code=422,
status_code=500,
detail="Failed to store outgoing message - unexpected duplicate",
)
@@ -813,11 +813,11 @@ async def send_channel_message_to_channel(
"No response from radio after channel send to %s; send outcome is unknown",
channel.name,
)
raise HTTPException(status_code=408, detail=NO_RADIO_RESPONSE_AFTER_SEND_DETAIL)
raise HTTPException(status_code=504, detail=NO_RADIO_RESPONSE_AFTER_SEND_DETAIL)
if result.type == EventType.ERROR:
raise HTTPException(
status_code=422, detail=f"Failed to send message: {result.payload}"
status_code=500, detail=f"Failed to send message: {result.payload}"
)
except Exception:
if outgoing_message is not None:
@@ -834,7 +834,7 @@ async def send_channel_message_to_channel(
)
if sent_at is None or sender_timestamp is None or outgoing_message is None:
raise HTTPException(status_code=422, detail="Failed to store outgoing message")
raise HTTPException(status_code=500, detail="Failed to store outgoing message")
outgoing_message = await build_stored_outgoing_channel_message(
message_id=outgoing_message.id,
@@ -928,7 +928,7 @@ async def resend_channel_message_record(
)
if new_message is None:
raise HTTPException(
status_code=422,
status_code=500,
detail="Failed to store resent message - unexpected duplicate",
)
@@ -949,10 +949,10 @@ async def resend_channel_message_record(
"No response from radio after channel resend to %s; send outcome is unknown",
channel.name,
)
raise HTTPException(status_code=408, detail=NO_RADIO_RESPONSE_AFTER_SEND_DETAIL)
raise HTTPException(status_code=504, detail=NO_RADIO_RESPONSE_AFTER_SEND_DETAIL)
if result.type == EventType.ERROR:
raise HTTPException(
status_code=422,
status_code=500,
detail=f"Failed to resend message: {result.payload}",
)
except Exception:
@@ -971,7 +971,7 @@ async def resend_channel_message_record(
if new_timestamp:
if sent_at is None or new_message is None:
raise HTTPException(status_code=422, detail="Failed to assign resend timestamp")
raise HTTPException(status_code=500, detail="Failed to assign resend timestamp")
new_message = await build_stored_outgoing_channel_message(
message_id=new_message.id,
+24
View File
@@ -51,6 +51,30 @@ async def apply_radio_config_update(
if result is not None and result.type == EventType.ERROR:
raise RadioCommandRejectedError(f"Failed to set multi ACKs: {result.payload}")
if update.telemetry_mode_base is not None:
logger.info("Setting telemetry_mode_base to %d", update.telemetry_mode_base)
result = await mc.commands.set_telemetry_mode_base(update.telemetry_mode_base)
if result is not None and result.type == EventType.ERROR:
raise RadioCommandRejectedError(
f"Failed to set telemetry mode (base): {result.payload}"
)
if update.telemetry_mode_loc is not None:
logger.info("Setting telemetry_mode_loc to %d", update.telemetry_mode_loc)
result = await mc.commands.set_telemetry_mode_loc(update.telemetry_mode_loc)
if result is not None and result.type == EventType.ERROR:
raise RadioCommandRejectedError(
f"Failed to set telemetry mode (location): {result.payload}"
)
if update.telemetry_mode_env is not None:
logger.info("Setting telemetry_mode_env to %d", update.telemetry_mode_env)
result = await mc.commands.set_telemetry_mode_env(update.telemetry_mode_env)
if result is not None and result.type == EventType.ERROR:
raise RadioCommandRejectedError(
f"Failed to set telemetry mode (environment): {result.payload}"
)
if update.name is not None:
logger.info("Setting radio name to %s", update.name)
await mc.commands.set_name(update.name)
+3 -3
View File
@@ -52,12 +52,12 @@ class RadioRuntime:
def require_connected(self):
"""Return MeshCore when available, mirroring existing HTTP semantics."""
if self.is_setup_in_progress:
raise HTTPException(status_code=423, detail="Radio is initializing")
raise HTTPException(status_code=503, detail="Radio is initializing")
if not self.is_connected:
raise HTTPException(status_code=423, detail="Radio not connected")
raise HTTPException(status_code=503, detail="Radio not connected")
mc = self.meshcore
if mc is None:
raise HTTPException(status_code=423, detail="Radio not connected")
raise HTTPException(status_code=503, detail="Radio not connected")
return mc
@asynccontextmanager
+5 -3
View File
@@ -141,7 +141,8 @@ frontend/src/
│ │ ├── SettingsRadioSection.tsx # Name, keys, advert interval, max contacts, radio preset, freq/bw/sf/cr, txPower, lat/lon, reboot, mesh discovery
│ │ ├── SettingsLocalSection.tsx # Browser-local settings: theme, relative font scale, local label, reopen last conversation
│ │ ├── SettingsFanoutSection.tsx # Fanout integrations: MQTT, bots, config CRUD
│ │ ├── SettingsDatabaseSection.tsx # DB size, cleanup, auto-decrypt, local label
│ │ ├── SettingsRadioAppSection.tsx # Radio-App Management: tracked telemetry, contact management, blocked lists
│ │ ├── SettingsDatabaseSection.tsx # Database: DB size, storage cleanup, auto-decrypt
│ │ ├── SettingsStatisticsSection.tsx # Read-only mesh network stats
│ │ ├── SettingsAboutSection.tsx # Version, author, license, links
│ │ ├── ThemeSelector.tsx # Color theme picker
@@ -323,7 +324,7 @@ Supported routes:
- `#contact/{publicKey}`
- `#contact/{publicKey}/{label}`
Where `{section}` is one of `radio`, `local`, `fanout`, `database`, `statistics`, or `about`.
Where `{section}` is one of `radio`, `local`, `radio-app`, `database`, `fanout`, `statistics`, or `about`.
Legacy name-based channel/contact hashes are still accepted for compatibility.
@@ -361,7 +362,7 @@ Distance/validation helpers used by path + map UI.
- `last_advert_time`
- `flood_scope`
- `blocked_keys`, `blocked_names`, `discovery_blocked_types`
- `tracked_telemetry_repeaters`
- `tracked_telemetry_repeaters`, `tracked_telemetry_contacts`
- `auto_resend_channel`
- `telemetry_interval_hours`
@@ -382,6 +383,7 @@ Clicking a contact's avatar in `ChatHeader` or `MessageList` opens a `ContactInf
- Header: avatar, name, public key, type badge, on-radio badge
- Info grid: last seen, first heard, last contacted, distance, hops
- GPS location (clickable → map)
- On-demand LPP telemetry: "Request" button fetches `POST /contacts/{key}/telemetry`, displays sensor readings via `LppSensorRow`, optional GPS mini-map (Leaflet), and history chart (Recharts). Opt-in tracking toggle uses `POST /settings/tracked-telemetry-contacts/toggle`.
- Favorite toggle
- Name history ("Also Known As") — shown only when the contact has used multiple names
- Message stats: DM count, channel message count
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "remoteterm-meshcore-frontend",
"private": true,
"version": "3.13.0",
"version": "3.12.3",
"type": "module",
"scripts": {
"dev": "vite",
+5
View File
@@ -166,6 +166,7 @@ export function App() {
handleToggleBlockedKey,
handleToggleBlockedName,
handleToggleTrackedTelemetry,
handleToggleTrackedTelemetryContact,
} = useAppSettings();
// Keep user's name in ref for mention detection in WebSocket callback
@@ -715,6 +716,8 @@ export function App() {
},
trackedTelemetryRepeaters: appSettings?.tracked_telemetry_repeaters ?? [],
onToggleTrackedTelemetry: handleToggleTrackedTelemetry,
trackedTelemetryContacts: appSettings?.tracked_telemetry_contacts ?? [],
onToggleTrackedTelemetryContact: handleToggleTrackedTelemetryContact,
};
const crackerProps = {
packets: rawPackets,
@@ -748,6 +751,8 @@ export function App() {
onToggleBlockedName: handleBlockName,
blockedKeys: appSettings?.blocked_keys ?? [],
blockedNames: appSettings?.blocked_names ?? [],
trackedTelemetryContacts: appSettings?.tracked_telemetry_contacts ?? [],
onToggleTrackedTelemetryContact: handleToggleTrackedTelemetryContact,
};
const channelInfoPaneProps = {
channelKey: infoPaneChannelKey,
+19
View File
@@ -8,6 +8,7 @@ import type {
Contact,
ContactAnalytics,
ContactAdvertPathSummary,
ContactTelemetryResponse,
FanoutConfig,
HealthStatus,
MaintenanceResult,
@@ -35,6 +36,7 @@ import type {
RepeaterStatusResponse,
TelemetryHistoryEntry,
TelemetrySchedule,
TrackedTelemetryContactsResponse,
TrackedTelemetryResponse,
StatisticsResponse,
TraceResponse,
@@ -337,6 +339,16 @@ export const api = {
getTelemetrySchedule: () => fetchJson<TelemetrySchedule>('/settings/tracked-telemetry/schedule'),
// Tracked contact telemetry
toggleTrackedTelemetryContact: (publicKey: string) =>
fetchJson<TrackedTelemetryContactsResponse>('/settings/tracked-telemetry-contacts/toggle', {
method: 'POST',
body: JSON.stringify({ public_key: publicKey }),
}),
getContactTelemetrySchedule: () =>
fetchJson<TelemetrySchedule>('/settings/tracked-telemetry-contacts/schedule'),
// Favorites
toggleFavorite: (type: 'channel' | 'contact', id: string) =>
fetchJson<{ type: string; id: string; favorite: boolean }>('/settings/favorites/toggle', {
@@ -432,6 +444,13 @@ export const api = {
}),
repeaterTelemetryHistory: (publicKey: string) =>
fetchJson<TelemetryHistoryEntry[]>(`/contacts/${publicKey}/repeater/telemetry-history`),
// Contact telemetry (universal, any contact type)
requestContactTelemetry: (publicKey: string) =>
fetchJson<ContactTelemetryResponse>(`/contacts/${publicKey}/telemetry`, {
method: 'POST',
}),
contactTelemetryHistory: (publicKey: string) =>
fetchJson<TelemetryHistoryEntry[]>(`/contacts/${publicKey}/telemetry-history`),
roomLogin: (publicKey: string, password: string) =>
fetchJson<RepeaterLoginResponse>(`/contacts/${publicKey}/room/login`, {
method: 'POST',
+368 -2
View File
@@ -1,6 +1,8 @@
import { type ReactNode, useEffect, useMemo, useState } from 'react';
import { Ban, Search, Star } from 'lucide-react';
import { type ReactNode, useCallback, useEffect, useMemo, useState } from 'react';
import { Activity, Ban, ChevronDown, ChevronRight, Search, Star } from 'lucide-react';
import {
AreaChart,
Area,
LineChart,
Line,
XAxis,
@@ -10,6 +12,8 @@ import {
ResponsiveContainer,
Legend,
} from 'recharts';
import { MapContainer, TileLayer, CircleMarker, Popup } from 'react-leaflet';
import 'leaflet/dist/leaflet.css';
import { api, isAbortError } from '../api';
import { formatTime } from '../utils/messageParser';
import {
@@ -31,6 +35,7 @@ import { isPublicChannelKey } from '../utils/publicChannel';
import { getMapFocusHash } from '../utils/urlHash';
import { handleKeyboardActivate } from '../utils/a11y';
import { ContactAvatar } from './ContactAvatar';
import { LppSensorRow, formatLppLabel } from './repeater/repeaterPaneShared';
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from './ui/sheet';
import { toast } from './ui/sonner';
import { useDistanceUnit } from '../contexts/DistanceUnitContext';
@@ -41,7 +46,10 @@ import type {
ContactAnalytics,
ContactAnalyticsHourlyBucket,
ContactAnalyticsWeeklyBucket,
LppSensor,
RadioConfig,
TelemetryHistoryEntry,
TelemetryLppSensor,
} from '../types';
const CONTACT_TYPE_LABELS: Record<number, string> = {
@@ -73,6 +81,8 @@ interface ContactInfoPaneProps {
blockedNames?: string[];
onToggleBlockedKey?: (key: string) => void;
onToggleBlockedName?: (name: string) => void;
trackedTelemetryContacts?: string[];
onToggleTrackedTelemetryContact?: (publicKey: string) => Promise<void>;
}
export function ContactInfoPane({
@@ -89,6 +99,8 @@ export function ContactInfoPane({
blockedNames = [],
onToggleBlockedKey,
onToggleBlockedName,
trackedTelemetryContacts = [],
onToggleTrackedTelemetryContact,
}: ContactInfoPaneProps) {
const { distanceUnit } = useDistanceUnit();
const isNameOnly = contactKey?.startsWith('name:') ?? false;
@@ -96,6 +108,8 @@ export function ContactInfoPane({
const [analytics, setAnalytics] = useState<ContactAnalytics | null>(null);
const [loading, setLoading] = useState(false);
const [telemetryLoading, setTelemetryLoading] = useState(false);
const [telemetryHistory, setTelemetryHistory] = useState<TelemetryHistoryEntry[]>([]);
// Get live contact data from contacts array (real-time via WS)
const liveContact =
@@ -133,6 +147,41 @@ export function ContactInfoPane({
};
}, [contactKey, isNameOnly, nameOnlyValue]);
// Load telemetry history when pane opens for a contact
useEffect(() => {
if (!contactKey || isNameOnly) {
setTelemetryHistory([]);
return;
}
let cancelled = false;
api
.contactTelemetryHistory(contactKey)
.then((data) => {
if (!cancelled) setTelemetryHistory(data);
})
.catch(() => {
if (!cancelled) setTelemetryHistory([]);
});
return () => {
cancelled = true;
};
}, [contactKey, isNameOnly]);
const handleFetchTelemetry = useCallback(async () => {
if (!contactKey || isNameOnly) return;
setTelemetryLoading(true);
try {
const result = await api.requestContactTelemetry(contactKey);
setTelemetryHistory(result.telemetry_history);
} catch (err) {
if (!isAbortError(err)) {
toast.error(err instanceof Error ? err.message : 'Failed to fetch telemetry');
}
} finally {
setTelemetryLoading(false);
}
}, [contactKey, isNameOnly]);
// Use live contact data where available, fall back to analytics snapshot
const contact = liveContact ?? analytics?.contact ?? null;
@@ -371,6 +420,16 @@ export function ContactInfoPane({
</div>
)}
{/* Contact Telemetry */}
<ContactTelemetrySection
contact={contact}
loading={telemetryLoading}
onFetch={handleFetchTelemetry}
telemetryHistory={telemetryHistory}
isTracked={trackedTelemetryContacts.includes(contact.public_key)}
onToggleTracked={onToggleTrackedTelemetryContact}
/>
{/* Favorite toggle */}
<div className="px-5 py-3 border-b border-border">
<button
@@ -909,3 +968,310 @@ function InfoItem({ label, value }: { label: string; value: ReactNode }) {
</div>
);
}
// Stable color rotation for dynamic LPP sensors in the history chart
const LPP_CHART_COLORS = ['#22c55e', '#8b5cf6', '#0ea5e9', '#ef4444', '#f59e0b', '#ec4899'];
function ContactTelemetrySection({
contact,
loading,
onFetch,
telemetryHistory,
isTracked,
onToggleTracked,
}: {
contact: Contact;
loading: boolean;
onFetch: () => void;
telemetryHistory: TelemetryHistoryEntry[];
isTracked: boolean;
onToggleTracked?: (publicKey: string) => Promise<void>;
}) {
const { distanceUnit } = useDistanceUnit();
const [expanded, setExpanded] = useState(true);
const [mapExpanded, setMapExpanded] = useState(false);
const [chartExpanded, setChartExpanded] = useState(false);
const [toggling, setToggling] = useState(false);
// Latest telemetry snapshot from history
const latestEntry =
telemetryHistory.length > 0 ? telemetryHistory[telemetryHistory.length - 1] : null;
const sensors: LppSensor[] = useMemo(() => {
if (!latestEntry?.data?.lpp_sensors) return [];
return latestEntry.data.lpp_sensors.map((s: TelemetryLppSensor) => ({
channel: s.channel,
type_name: s.type_name,
value: s.value,
}));
}, [latestEntry]);
const fetchedAt = latestEntry?.timestamp ?? null;
// Extract GPS from sensors
const gpsSensor = sensors.find(
(s) => s.type_name === 'gps' && typeof s.value === 'object' && s.value !== null
);
const gpsValue = gpsSensor?.value as Record<string, number> | undefined;
const hasGps =
gpsValue != null &&
typeof gpsValue.latitude === 'number' &&
typeof gpsValue.longitude === 'number';
// Non-GPS sensors for display
const displaySensors = sensors.filter((s) => s.type_name !== 'gps');
// Build disambiguated labels
const labels = useMemo(() => {
const counts = new Map<string, number>();
return displaySensors.map((s) => {
const base = `${s.type_name}_${s.channel}`;
const n = (counts.get(base) ?? 0) + 1;
counts.set(base, n);
return formatLppLabel(s.type_name) + (n > 1 ? ` (${n})` : '');
});
}, [displaySensors]);
// Discover unique LPP sensor series from history for charting
const sensorSeries = useMemo(() => {
const seen = new Map<string, { type_name: string; channel: number }>();
for (const entry of telemetryHistory) {
for (const s of entry.data?.lpp_sensors ?? []) {
if (typeof s.value !== 'number') continue;
const key = `${s.type_name}_ch${s.channel}`;
if (!seen.has(key)) seen.set(key, { type_name: s.type_name, channel: s.channel });
}
}
return Array.from(seen.entries()).map(([key, info], i) => ({
key,
label: formatLppLabel(info.type_name),
color: LPP_CHART_COLORS[i % LPP_CHART_COLORS.length],
...info,
}));
}, [telemetryHistory]);
const [selectedMetric, setSelectedMetric] = useState<string | null>(null);
const activeMetric = selectedMetric ?? (sensorSeries.length > 0 ? sensorSeries[0].key : null);
// Build chart data for selected metric
const chartData = useMemo(() => {
if (!activeMetric) return [];
const series = sensorSeries.find((s) => s.key === activeMetric);
if (!series) return [];
return telemetryHistory
.filter((e) => e.data?.lpp_sensors)
.map((e) => {
const sensor = (e.data.lpp_sensors ?? []).find(
(s: TelemetryLppSensor) =>
s.type_name === series.type_name && s.channel === series.channel
);
return {
time: e.timestamp,
value: sensor && typeof sensor.value === 'number' ? sensor.value : null,
};
})
.filter((d) => d.value !== null);
}, [telemetryHistory, activeMetric, sensorSeries]);
const activeSeries = sensorSeries.find((s) => s.key === activeMetric);
return (
<div className="px-5 py-3 border-b border-border">
<div className="flex items-center justify-between">
<button
type="button"
className="flex items-center gap-1.5 text-[0.625rem] uppercase tracking-wider text-muted-foreground font-medium"
onClick={() => setExpanded(!expanded)}
>
{expanded ? <ChevronDown className="h-3 w-3" /> : <ChevronRight className="h-3 w-3" />}
Telemetry
</button>
<button
type="button"
onClick={onFetch}
disabled={loading}
className="text-xs px-2 py-0.5 rounded border border-border hover:bg-accent disabled:opacity-50 transition-colors flex items-center gap-1"
>
<Activity className="h-3 w-3" />
{loading ? 'Fetching...' : 'Request'}
</button>
</div>
{expanded && (
<div className="mt-2">
{sensors.length === 0 ? (
<p className="text-sm text-muted-foreground italic">
{fetchedAt ? 'No sensor data in last response' : 'Not yet fetched'}
</p>
) : (
<>
<div className="space-y-0.5">
{displaySensors.map((sensor, i) => (
<LppSensorRow
key={`${sensor.type_name}-${sensor.channel}-${i}`}
sensor={sensor}
unitPref={distanceUnit}
label={labels[i]}
/>
))}
</div>
{hasGps && (
<div className="mt-2">
<button
type="button"
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-primary transition-colors"
onClick={() => setMapExpanded(!mapExpanded)}
>
{mapExpanded ? (
<ChevronDown className="h-3 w-3" />
) : (
<ChevronRight className="h-3 w-3" />
)}
GPS: {gpsValue!.latitude.toFixed(5)}, {gpsValue!.longitude.toFixed(5)}
</button>
{mapExpanded && (
<div className="mt-1 h-48 rounded border border-border overflow-hidden">
<MapContainer
center={[gpsValue!.latitude, gpsValue!.longitude]}
zoom={13}
className="h-full w-full"
style={{ background: '#1a1a2e' }}
>
<TileLayer
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<CircleMarker
center={[gpsValue!.latitude, gpsValue!.longitude]}
radius={7}
pathOptions={{
color: '#1d4ed8',
fillColor: '#3b82f6',
fillOpacity: 1,
weight: 2,
}}
>
<Popup>
<span className="text-sm">
{contact.name ?? contact.public_key.slice(0, 12)}
</span>
</Popup>
</CircleMarker>
</MapContainer>
</div>
)}
</div>
)}
{fetchedAt && (
<p className="text-[0.6875rem] text-muted-foreground mt-1.5">
Fetched {formatTime(fetchedAt)}
</p>
)}
</>
)}
{/* History chart */}
{telemetryHistory.length > 1 && sensorSeries.length > 0 && (
<div className="mt-2">
<button
type="button"
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-primary transition-colors"
onClick={() => setChartExpanded(!chartExpanded)}
>
{chartExpanded ? (
<ChevronDown className="h-3 w-3" />
) : (
<ChevronRight className="h-3 w-3" />
)}
History ({telemetryHistory.length} samples)
</button>
{chartExpanded && (
<div className="mt-1">
<div className="flex flex-wrap gap-1 mb-2">
{sensorSeries.map((s) => (
<button
key={s.key}
type="button"
onClick={() => setSelectedMetric(s.key)}
className={`text-[0.625rem] uppercase tracking-wider px-1.5 py-0.5 rounded transition-colors ${
activeMetric === s.key
? 'bg-primary/10 text-primary'
: 'bg-muted text-muted-foreground hover:text-foreground'
}`}
>
{s.label}
</button>
))}
</div>
{chartData.length > 1 && activeSeries && (
<ResponsiveContainer width="100%" height={120}>
<AreaChart data={chartData}>
<CartesianGrid strokeDasharray="3 3" stroke="var(--border)" />
<XAxis
dataKey="time"
tickFormatter={(t: number) => {
const d = new Date(t * 1000);
return `${d.getMonth() + 1}/${d.getDate()} ${d.getHours()}:${d.getMinutes().toString().padStart(2, '0')}`;
}}
fontSize={9}
tick={{ fill: 'var(--muted-foreground)' }}
/>
<YAxis fontSize={9} tick={{ fill: 'var(--muted-foreground)' }} width={40} />
<RechartsTooltip
labelFormatter={(t) => new Date(Number(t) * 1000).toLocaleString()}
contentStyle={{
backgroundColor: 'var(--popover)',
border: '1px solid var(--border)',
fontSize: '0.75rem',
}}
/>
<Area
type="monotone"
dataKey="value"
name={activeSeries.label}
stroke={activeSeries.color}
fill={activeSeries.color}
fillOpacity={0.15}
dot={false}
/>
</AreaChart>
</ResponsiveContainer>
)}
</div>
)}
</div>
)}
{/* Tracking toggle */}
{onToggleTracked && (
<div className="mt-2 pt-2 border-t border-border/50">
<button
type="button"
disabled={toggling}
onClick={async () => {
setToggling(true);
try {
await onToggleTracked(contact.public_key);
} finally {
setToggling(false);
}
}}
className={`text-xs px-2 py-1 rounded border transition-colors w-full ${
isTracked
? 'border-destructive/50 text-destructive hover:bg-destructive/10'
: 'border-green-600/50 text-green-600 hover:bg-green-600/10'
} disabled:opacity-50`}
>
{toggling
? 'Updating...'
: isTracked
? 'Stop Tracking Telemetry'
: 'Track Telemetry on Interval'}
</button>
</div>
)}
</div>
)}
</div>
);
}
+14 -34
View File
@@ -4,12 +4,12 @@ import {
useImperativeHandle,
forwardRef,
useRef,
useEffect,
useMemo,
type ChangeEvent,
type FormEvent,
type KeyboardEvent,
} from 'react';
import { Input } from './ui/input';
import { Button } from './ui/button';
import { toast } from './ui/sonner';
import { cn } from '@/lib/utils';
@@ -59,32 +59,19 @@ export const MessageInput = forwardRef<MessageInputHandle, MessageInputProps>(fu
) {
const [text, setText] = useState('');
const [sending, setSending] = useState(false);
const textareaRef = useRef<HTMLTextAreaElement>(null);
/** Resize textarea to fit content, clamped between 1 row and ~6 rows. */
const autoResize = useCallback(() => {
const el = textareaRef.current;
if (!el) return;
el.style.height = 'auto';
// Clamp: min 40px (≈1 row), max 160px (≈6 rows)
el.style.height = `${Math.min(el.scrollHeight, 160)}px`;
}, []);
const inputRef = useRef<HTMLInputElement>(null);
useImperativeHandle(ref, () => ({
appendText: (appendedText: string) => {
setText((prev) => prev + appendedText);
textareaRef.current?.focus();
// Focus the input after appending
inputRef.current?.focus();
},
focus: () => {
textareaRef.current?.focus();
inputRef.current?.focus();
},
}));
// Re-measure height whenever text changes (covers programmatic updates like appendText)
useEffect(() => {
autoResize();
}, [text, autoResize]);
// Calculate character limits based on conversation type
const limits = useMemo(() => {
if (conversationType === 'contact') {
@@ -152,13 +139,13 @@ export const MessageInput = forwardRef<MessageInputHandle, MessageInputProps>(fu
} finally {
setSending(false);
}
// Refocus after React re-enables the textarea
setTimeout(() => textareaRef.current?.focus(), 0);
// Refocus after React re-enables the input
setTimeout(() => inputRef.current?.focus(), 0);
},
[text, sending, disabled, onSend]
);
const handleChange = useCallback((e: ChangeEvent<HTMLTextAreaElement>) => {
const handleChange = useCallback((e: ChangeEvent<HTMLInputElement>) => {
const input = e.target;
const raw = input.value;
// Skip replacement during IME / dead-key composition to avoid garbling interim input
@@ -184,12 +171,11 @@ export const MessageInput = forwardRef<MessageInputHandle, MessageInputProps>(fu
}, []);
const handleKeyDown = useCallback(
(e: KeyboardEvent<HTMLTextAreaElement>) => {
(e: KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSubmit(e as unknown as FormEvent);
}
// Shift+Enter falls through naturally and inserts a newline
},
[handleSubmit]
);
@@ -207,28 +193,22 @@ export const MessageInput = forwardRef<MessageInputHandle, MessageInputProps>(fu
onSubmit={handleSubmit}
autoComplete="off"
>
<div className="flex gap-2 items-end">
<textarea
ref={textareaRef}
<div className="flex gap-2">
<Input
ref={inputRef}
type="text"
autoComplete="off"
name="chat-message-input"
aria-label={placeholder || 'Type a message'}
data-lpignore="true"
data-1p-ignore="true"
data-bwignore="true"
rows={1}
value={text}
onChange={handleChange}
onKeyDown={handleKeyDown}
placeholder={placeholder || 'Type a message...'}
disabled={disabled || sending}
className={cn(
'flex-1 min-w-0 resize-none overflow-y-auto',
'rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background',
'placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2',
'disabled:cursor-not-allowed disabled:opacity-50 md:text-sm'
)}
style={{ minHeight: '40px', maxHeight: '160px' }}
className="flex-1 min-w-0"
/>
<Button
type="submit"
+36 -8
View File
@@ -20,6 +20,7 @@ import {
import { SettingsRadioSection } from './settings/SettingsRadioSection';
import { SettingsLocalSection } from './settings/SettingsLocalSection';
import { SettingsRadioAppSection } from './settings/SettingsRadioAppSection';
import { SettingsFanoutSection } from './settings/SettingsFanoutSection';
import { SettingsDatabaseSection } from './settings/SettingsDatabaseSection';
import { SettingsStatisticsSection } from './settings/SettingsStatisticsSection';
@@ -54,6 +55,8 @@ interface SettingsModalBaseProps {
onBulkDeleteContacts?: (deletedKeys: string[]) => void;
trackedTelemetryRepeaters?: string[];
onToggleTrackedTelemetry?: (publicKey: string) => Promise<void>;
trackedTelemetryContacts?: string[];
onToggleTrackedTelemetryContact?: (publicKey: string) => Promise<void>;
}
export type SettingsModalProps = SettingsModalBaseProps &
@@ -92,6 +95,8 @@ export function SettingsModal(props: SettingsModalProps) {
onBulkDeleteContacts,
trackedTelemetryRepeaters,
onToggleTrackedTelemetry,
trackedTelemetryContacts,
onToggleTrackedTelemetryContact,
} = props;
const externalSidebarNav = props.externalSidebarNav === true;
const desktopSection = props.externalSidebarNav ? props.desktopSection : undefined;
@@ -106,6 +111,7 @@ export function SettingsModal(props: SettingsModalProps) {
const [expandedSections, setExpandedSections] = useState<Record<SettingsSection, boolean>>({
radio: false,
local: false,
'radio-app': false,
fanout: false,
database: false,
statistics: false,
@@ -239,6 +245,36 @@ export function SettingsModal(props: SettingsModalProps) {
</section>
)}
{shouldRenderSection('radio-app') && (
<section className={sectionWrapperClass}>
{renderSectionHeader('radio-app')}
{isSectionVisible('radio-app') &&
(appSettings ? (
<SettingsRadioAppSection
appSettings={appSettings}
onSaveAppSettings={onSaveAppSettings}
blockedKeys={blockedKeys}
blockedNames={blockedNames}
onToggleBlockedKey={onToggleBlockedKey}
onToggleBlockedName={onToggleBlockedName}
contacts={contacts}
onBulkDeleteContacts={onBulkDeleteContacts}
trackedTelemetryRepeaters={trackedTelemetryRepeaters}
onToggleTrackedTelemetry={onToggleTrackedTelemetry}
trackedTelemetryContacts={trackedTelemetryContacts}
onToggleTrackedTelemetryContact={onToggleTrackedTelemetryContact}
className={sectionContentClass}
/>
) : (
<div className={sectionContentClass}>
<div className="rounded-md border border-input bg-muted/20 px-4 py-3 text-sm text-muted-foreground">
Loading app settings...
</div>
</div>
))}
</section>
)}
{shouldRenderSection('database') && (
<section className={sectionWrapperClass}>
{renderSectionHeader('database')}
@@ -249,14 +285,6 @@ export function SettingsModal(props: SettingsModalProps) {
health={health}
onSaveAppSettings={onSaveAppSettings}
onHealthRefresh={onHealthRefresh}
blockedKeys={blockedKeys}
blockedNames={blockedNames}
onToggleBlockedKey={onToggleBlockedKey}
onToggleBlockedName={onToggleBlockedName}
contacts={contacts}
onBulkDeleteContacts={onBulkDeleteContacts}
trackedTelemetryRepeaters={trackedTelemetryRepeaters}
onToggleTrackedTelemetry={onToggleTrackedTelemetry}
className={sectionContentClass}
/>
) : (
@@ -247,10 +247,10 @@ export function TelemetryHistoryPane({
), or when the repeater is opted into interval telemetry polling, in which case the
repeater will be polled for metrics automatically. Fetch frequency can be configured in{' '}
<a
href="#settings/database"
href="#settings/radio-app"
className="underline text-primary hover:text-primary/80 transition-colors"
>
Settings &rarr; Database &amp; Messaging
Settings &rarr; Radio-App Management
</a>
, where you can also see which repeaters are currently opted in. A maximum of{' '}
{MAX_TRACKED} repeaters may be opted into this for the sake of keeping mesh congestion
@@ -6,117 +6,32 @@ import { Separator } from '../ui/separator';
import { toast } from '../ui/sonner';
import { api } from '../../api';
import { formatTime } from '../../utils/messageParser';
import { lppDisplayUnit } from '../repeater/repeaterPaneShared';
import { useDistanceUnit } from '../../contexts/DistanceUnitContext';
import { BulkDeleteContactsModal } from './BulkDeleteContactsModal';
import type {
AppSettings,
AppSettingsUpdate,
Contact,
HealthStatus,
TelemetryHistoryEntry,
TelemetrySchedule,
} from '../../types';
import type { AppSettings, AppSettingsUpdate, HealthStatus } from '../../types';
export function SettingsDatabaseSection({
appSettings,
health,
onSaveAppSettings,
onHealthRefresh,
blockedKeys = [],
blockedNames = [],
onToggleBlockedKey,
onToggleBlockedName,
contacts = [],
onBulkDeleteContacts,
trackedTelemetryRepeaters = [],
onToggleTrackedTelemetry,
className,
}: {
appSettings: AppSettings;
health: HealthStatus | null;
onSaveAppSettings: (update: AppSettingsUpdate) => Promise<void>;
onHealthRefresh: () => Promise<void>;
blockedKeys?: string[];
blockedNames?: string[];
onToggleBlockedKey?: (key: string) => void;
onToggleBlockedName?: (name: string) => void;
contacts?: Contact[];
onBulkDeleteContacts?: (deletedKeys: string[]) => void;
trackedTelemetryRepeaters?: string[];
onToggleTrackedTelemetry?: (publicKey: string) => Promise<void>;
className?: string;
}) {
const { distanceUnit } = useDistanceUnit();
const [retentionDays, setRetentionDays] = useState('14');
const [cleaning, setCleaning] = useState(false);
const [purgingDecryptedRaw, setPurgingDecryptedRaw] = useState(false);
const [autoDecryptOnAdvert, setAutoDecryptOnAdvert] = useState(false);
const [discoveryBlockedTypes, setDiscoveryBlockedTypes] = useState<number[]>([]);
const [bulkDeleteOpen, setBulkDeleteOpen] = useState(false);
const [latestTelemetry, setLatestTelemetry] = useState<
Record<string, TelemetryHistoryEntry | null>
>({});
const telemetryFetchedRef = useRef(false);
const [schedule, setSchedule] = useState<TelemetrySchedule | null>(null);
const [intervalDraft, setIntervalDraft] = useState<number>(appSettings.telemetry_interval_hours);
// Serialization chain for every auto-persisted control on this page.
// Without this, rapid successive toggles (or mixed dropdown + checkbox
// interactions) can dispatch overlapping PATCHes that land out of order
// on HTTP/2 — a stale write then wins, reverting the user's last click.
// Each call awaits the previous one before sending its request, so the
// server sees updates in the order the user made them.
const saveChainRef = useRef<Promise<void>>(Promise.resolve());
useEffect(() => {
setAutoDecryptOnAdvert(appSettings.auto_decrypt_dm_on_advert);
setDiscoveryBlockedTypes(appSettings.discovery_blocked_types ?? []);
setIntervalDraft(appSettings.telemetry_interval_hours);
}, [appSettings]);
// Re-fetch the scheduler derivation whenever the tracked list changes or
// the stored preference changes. Cheap: single GET, no radio lock.
useEffect(() => {
let cancelled = false;
api
.getTelemetrySchedule()
.then((s) => {
if (!cancelled) setSchedule(s);
})
.catch(() => {
// Non-critical: dropdown falls back to the unfiltered menu.
});
return () => {
cancelled = true;
};
}, [
trackedTelemetryRepeaters.length,
appSettings.telemetry_interval_hours,
appSettings.telemetry_routed_hourly,
]);
useEffect(() => {
if (trackedTelemetryRepeaters.length === 0 || telemetryFetchedRef.current) return;
telemetryFetchedRef.current = true;
let cancelled = false;
const fetches = trackedTelemetryRepeaters.map((key) =>
api.repeaterTelemetryHistory(key).then(
(history) => [key, history.length > 0 ? history[history.length - 1] : null] as const,
() => [key, null] as const
)
);
Promise.all(fetches).then((entries) => {
if (cancelled) return;
setLatestTelemetry(Object.fromEntries(entries));
});
return () => {
cancelled = true;
};
}, [trackedTelemetryRepeaters]);
const handleCleanup = async () => {
const days = parseInt(retentionDays, 10);
if (isNaN(days) || days < 1) {
@@ -163,12 +78,6 @@ export function SettingsDatabaseSection({
}
};
/**
* Apply an AppSettings PATCH after any already-queued saves finish, and
* revert local state if the save fails. Every auto-persist control on
* this page routes through here so the user-visible order of clicks is
* the order the backend sees, regardless of network reordering.
*/
const persistAppSettings = (update: AppSettingsUpdate, revert: () => void): Promise<void> => {
const chained = saveChainRef.current.then(async () => {
try {
@@ -295,330 +204,6 @@ export function SettingsDatabaseSection({
contact sends an advertisement. This may cause brief delays on large packet backlogs.
</p>
</div>
<Separator />
{/* ── Tracked Repeater Telemetry ── */}
<div className="space-y-3">
<h3 className="text-base font-semibold tracking-tight">Tracked Repeater Telemetry</h3>
<p className="text-[0.8125rem] text-muted-foreground">
Repeaters opted into automatic telemetry collection are polled on a scheduled interval. To
limit mesh traffic, the app caps telemetry at 24 checks per day across all tracked
repeaters so fewer tracked repeaters allows shorter intervals, and more tracked
repeaters forces longer ones. Up to {schedule?.max_tracked ?? 8} repeaters may be tracked
at once ({trackedTelemetryRepeaters.length} / {schedule?.max_tracked ?? 8} slots used).
</p>
{/* Interval picker. Legal options depend on current tracked count;
we list only those. If the saved preference is no longer legal,
the effective interval is shown below so the user knows what the
scheduler is actually using. */}
<div className="space-y-1.5">
<Label htmlFor="telemetry-interval" className="text-sm">
Collection interval
</Label>
<div className="flex items-center gap-2">
<select
id="telemetry-interval"
value={intervalDraft}
onChange={(e) => {
const nextValue = Number(e.target.value);
if (!Number.isFinite(nextValue) || nextValue === intervalDraft) return;
const prevValue = intervalDraft;
setIntervalDraft(nextValue);
void persistAppSettings({ telemetry_interval_hours: nextValue }, () =>
setIntervalDraft(prevValue)
);
}}
className="h-9 px-3 rounded-md border border-input bg-background text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
>
{(schedule?.options ?? [1, 2, 3, 4, 6, 8, 12, 24]).map((hrs) => (
<option key={hrs} value={hrs}>
Every {hrs} hour{hrs === 1 ? '' : 's'} ({Math.floor(24 / hrs)} check
{Math.floor(24 / hrs) === 1 ? '' : 's'}/day)
</option>
))}
</select>
</div>
{schedule && schedule.effective_hours !== schedule.preferred_hours && (
<p className="text-xs text-warning">
Saved preference is {schedule.preferred_hours} hour
{schedule.preferred_hours === 1 ? '' : 's'}, but the scheduler is using{' '}
{schedule.effective_hours} hours because {schedule.tracked_count} repeater
{schedule.tracked_count === 1 ? '' : 's'}{' '}
{schedule.tracked_count === 1 ? 'is' : 'are'} tracked. Your preference will be
restored if you drop back to a supported count.
</p>
)}
</div>
{/* Routed hourly toggle */}
<label className="flex items-start gap-2 cursor-pointer">
<input
type="checkbox"
checked={appSettings.telemetry_routed_hourly}
onChange={() => {
const next = !appSettings.telemetry_routed_hourly;
void persistAppSettings({ telemetry_routed_hourly: next }, () => {});
}}
className="w-4 h-4 rounded border-input accent-primary mt-0.5"
/>
<div>
<span className="text-sm">Poll direct/routed-path repeaters hourly</span>
<p className="text-[0.8125rem] text-muted-foreground">
When enabled, tracked repeaters with a direct or routed path (not flood) are polled
every hour instead of on the scheduled interval above. Flood-only repeaters still
follow the normal schedule.
</p>
</div>
</label>
{schedule?.next_run_at != null && (
<p className="text-xs text-muted-foreground">
{schedule.routed_hourly ? 'Next flood run at' : 'Next run at'}{' '}
{formatTime(schedule.next_run_at)} (UTC top of hour).
</p>
)}
{schedule?.next_routed_run_at != null && (
<p className="text-xs text-muted-foreground">
Next direct/routed run at {formatTime(schedule.next_routed_run_at)} (UTC top of hour).
</p>
)}
{trackedTelemetryRepeaters.length === 0 ? (
<p className="text-sm text-muted-foreground italic">
No repeaters are being tracked. Enable tracking from a repeater's dashboard.
</p>
) : (
<div className="space-y-2">
{trackedTelemetryRepeaters.map((key) => {
const contact = contacts.find((c) => c.public_key === key);
const displayName = contact?.name ?? key.slice(0, 12);
const routeSource = contact?.effective_route_source ?? 'flood';
// A forced-flood override (path_len < 0) still reports source
// "override", but the actual route is flood. Check the real path.
const hasRealPath =
contact?.effective_route != null && contact.effective_route.path_len >= 0;
const routeLabel = !hasRealPath
? 'flood'
: routeSource === 'override'
? 'routed'
: routeSource === 'direct'
? 'direct'
: 'flood';
const routeColor = hasRealPath
? 'text-primary bg-primary/10'
: 'text-muted-foreground bg-muted';
const snap = latestTelemetry[key];
const d = snap?.data;
return (
<div key={key} className="rounded-md border border-border px-3 py-2">
<div className="flex items-center justify-between gap-2">
<div className="flex-1 min-w-0">
<span className="text-sm truncate block">{displayName}</span>
<div className="flex items-center gap-1.5">
<span className="text-[0.625rem] text-muted-foreground font-mono">
{key.slice(0, 12)}
</span>
<span
className={`text-[0.625rem] uppercase tracking-wider px-1.5 py-0.5 rounded font-medium ${routeColor}`}
>
{routeLabel}
</span>
</div>
</div>
{onToggleTrackedTelemetry && (
<Button
variant="ghost"
size="sm"
onClick={() => onToggleTrackedTelemetry(key)}
className="h-7 text-xs flex-shrink-0 text-destructive hover:text-destructive"
>
Remove
</Button>
)}
</div>
{d ? (
<div className="mt-1.5 flex flex-wrap gap-x-3 gap-y-0.5 text-[0.625rem] text-muted-foreground">
<span>{d.battery_volts?.toFixed(2)}V</span>
<span>noise {d.noise_floor_dbm} dBm</span>
<span>
rx {d.packets_received != null ? d.packets_received.toLocaleString() : '?'}
</span>
<span>
tx {d.packets_sent != null ? d.packets_sent.toLocaleString() : '?'}
</span>
{d.lpp_sensors?.map((s) => {
const display = lppDisplayUnit(s.type_name, s.value, distanceUnit);
const val =
typeof display.value === 'number'
? display.value % 1 === 0
? display.value
: display.value.toFixed(1)
: display.value;
const label = s.type_name.charAt(0).toUpperCase() + s.type_name.slice(1);
return (
<span key={`${s.type_name}-${s.channel}`}>
{label} {val}
{display.unit ? ` ${display.unit}` : ''}
</span>
);
})}
<span className="ml-auto">checked {formatTime(snap.timestamp)}</span>
</div>
) : snap === null ? (
<div className="mt-1 text-[0.625rem] text-muted-foreground italic">
No telemetry recorded yet
</div>
) : null}
</div>
);
})}
</div>
)}
</div>
<Separator />
{/* ── Contact Management ── */}
<div className="space-y-5">
<h3 className="text-base font-semibold tracking-tight">Contact Management</h3>
{/* Block discovery of new node types */}
<div className="space-y-3">
<h4 className="text-sm font-semibold">Block Discovery of New Node Types</h4>
<p className="text-[0.8125rem] text-muted-foreground">
Checked types will be ignored when heard via advertisement. Existing contacts of these
types are still updated. This does not affect contacts added manually or via DM.
</p>
<div className="space-y-1.5">
{(
[
[1, 'Block clients'],
[2, 'Block repeaters'],
[3, 'Block room servers'],
[4, 'Block sensors'],
] as const
).map(([typeCode, label]) => {
const checked = discoveryBlockedTypes.includes(typeCode);
return (
<label key={typeCode} className="flex items-center gap-2 text-sm cursor-pointer">
<input
type="checkbox"
checked={checked}
onChange={() => {
const prev = discoveryBlockedTypes;
const next = checked
? prev.filter((t) => t !== typeCode)
: [...prev, typeCode];
setDiscoveryBlockedTypes(next);
void persistAppSettings({ discovery_blocked_types: next }, () =>
setDiscoveryBlockedTypes(prev)
);
}}
className="rounded border-input"
/>
{label}
</label>
);
})}
</div>
{discoveryBlockedTypes.length > 0 && (
<p className="text-xs text-warning">
New{' '}
{discoveryBlockedTypes
.map((t) =>
t === 1 ? 'clients' : t === 2 ? 'repeaters' : t === 3 ? 'room servers' : 'sensors'
)
.join(', ')}{' '}
heard via advertisement will not be added to your contact list.
</p>
)}
</div>
{/* Blocked contacts list */}
<div className="space-y-3">
<h4 className="text-sm font-semibold">Blocked Contacts</h4>
<p className="text-[0.8125rem] text-muted-foreground">
Blocked contacts are hidden from the sidebar. Blocking only hides messages from the UI
MQTT forwarding and bot responses are not affected. Messages are still stored and will
reappear if unblocked.
</p>
{blockedKeys.length === 0 && blockedNames.length === 0 ? (
<p className="text-sm text-muted-foreground italic">
No blocked contacts. Block contacts from their info pane, viewed by clicking their
avatar in any channel, or their name within the top status bar with the conversation
open.
</p>
) : (
<div className="space-y-2">
{blockedKeys.length > 0 && (
<div>
<span className="text-xs text-muted-foreground font-medium">Blocked Keys</span>
<div className="mt-1 space-y-1">
{blockedKeys.map((key) => (
<div key={key} className="flex items-center justify-between gap-2">
<span className="text-xs font-mono truncate flex-1">{key}</span>
{onToggleBlockedKey && (
<Button
variant="ghost"
size="sm"
onClick={() => onToggleBlockedKey(key)}
className="h-7 text-xs flex-shrink-0"
>
Unblock
</Button>
)}
</div>
))}
</div>
</div>
)}
{blockedNames.length > 0 && (
<div>
<span className="text-xs text-muted-foreground font-medium">Blocked Names</span>
<div className="mt-1 space-y-1">
{blockedNames.map((name) => (
<div key={name} className="flex items-center justify-between gap-2">
<span className="text-sm truncate flex-1">{name}</span>
{onToggleBlockedName && (
<Button
variant="ghost"
size="sm"
onClick={() => onToggleBlockedName(name)}
className="h-7 text-xs flex-shrink-0"
>
Unblock
</Button>
)}
</div>
))}
</div>
</div>
)}
</div>
)}
</div>
{/* Bulk delete */}
<div className="space-y-3">
<h4 className="text-sm font-semibold">Bulk Delete Contacts</h4>
<p className="text-[0.8125rem] text-muted-foreground">
Remove multiple contacts or repeaters at once. Useful for cleaning up spam or unwanted
nodes. Message history will be preserved.
</p>
<Button variant="outline" className="w-full" onClick={() => setBulkDeleteOpen(true)}>
Open Bulk Delete
</Button>
<BulkDeleteContactsModal
open={bulkDeleteOpen}
onClose={() => setBulkDeleteOpen(false)}
contacts={contacts}
onDeleted={(keys) => onBulkDeleteContacts?.(keys)}
/>
</div>
</div>
</div>
);
}
@@ -287,7 +287,6 @@ const CREATE_INTEGRATION_DEFINITIONS: readonly CreateIntegrationDefinition[] = [
config: {
urls: '',
preserve_identity: true,
markdown_format: true,
body_format_dm: '**DM:** {sender_name}: {text} **via:** [{hops_backticked}]',
body_format_channel:
'**{channel_name}:** {sender_name}: {text} **via:** [{hops_backticked}]',
@@ -2391,8 +2390,6 @@ function ScopeSelector({
const APPRISE_DEFAULT_DM = '**DM:** {sender_name}: {text} **via:** [{hops_backticked}]';
const APPRISE_DEFAULT_CHANNEL =
'**{channel_name}:** {sender_name}: {text} **via:** [{hops_backticked}]';
const APPRISE_DEFAULT_DM_PLAIN = 'DM: {sender_name}: {text} via: [{hops}]';
const APPRISE_DEFAULT_CHANNEL_PLAIN = '{channel_name}: {sender_name}: {text} via: [{hops}]';
const APPRISE_SAMPLE_VARS: Record<string, string> = {
type: 'CHAN',
@@ -2423,32 +2420,19 @@ function appriseApplyFormat(fmt: string, vars: Record<string, string>): string {
return result;
}
/** Render a markdown-ish string into inline React elements (bold, italic, code). */
/** Render a markdown-ish string into inline React elements (bold + code spans). */
function appriseRenderMarkdown(s: string): ReactNode[] {
const nodes: ReactNode[] = [];
let key = 0;
// Split on **bold**, __bold__, *italic*, _italic_, and `code` spans.
// Longer delimiters first so ** and __ match before * and _.
const parts = s.split(/(\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\*[^*]+\*|_[^_]+_)/g);
// Split on **bold** and `code` spans
const parts = s.split(/(\*\*[^*]+\*\*|`[^`]+`)/g);
for (const part of parts) {
if (
(part.startsWith('**') && part.endsWith('**')) ||
(part.startsWith('__') && part.endsWith('__'))
) {
if (part.startsWith('**') && part.endsWith('**')) {
nodes.push(
<strong key={key++} className="font-bold">
{part.slice(2, -2)}
</strong>
);
} else if (
(part.startsWith('*') && part.endsWith('*')) ||
(part.startsWith('_') && part.endsWith('_'))
) {
nodes.push(
<em key={key++} className="italic">
{part.slice(1, -1)}
</em>
);
} else if (part.startsWith('`') && part.endsWith('`')) {
nodes.push(
<code key={key++} className="rounded bg-muted px-1 py-0.5 text-[0.6875rem] font-mono">
@@ -2462,29 +2446,19 @@ function appriseRenderMarkdown(s: string): ReactNode[] {
return nodes;
}
function AppriseFormatPreview({
format,
vars,
markdown = true,
}: {
format: string;
vars: Record<string, string>;
markdown?: boolean;
}) {
function AppriseFormatPreview({ format, vars }: { format: string; vars: Record<string, string> }) {
const raw = appriseApplyFormat(format, vars);
return (
<div className="rounded-md border border-border bg-muted/30 p-2 space-y-1.5">
{markdown && (
<div>
<span className="text-[0.625rem] uppercase tracking-wider text-muted-foreground font-medium">
Rendered (Discord, Slack, Telegram)
</span>
<p className="text-xs break-all">{appriseRenderMarkdown(raw)}</p>
</div>
)}
<div>
<span className="text-[0.625rem] uppercase tracking-wider text-muted-foreground font-medium">
{markdown ? 'Raw (email, SMS)' : 'Preview'}
Rendered (Discord, Slack)
</span>
<p className="text-xs break-all">{appriseRenderMarkdown(raw)}</p>
</div>
<div>
<span className="text-[0.625rem] uppercase tracking-wider text-muted-foreground font-medium">
Raw (Telegram, email)
</span>
<p className="text-xs font-mono break-all text-muted-foreground">{raw}</p>
</div>
@@ -2509,11 +2483,9 @@ function AppriseConfigEditor({
onChange: (config: Record<string, unknown>) => void;
onScopeChange: (scope: Record<string, unknown>) => void;
}) {
const markdown = config.markdown_format !== false;
const defaultDm = markdown ? APPRISE_DEFAULT_DM : APPRISE_DEFAULT_DM_PLAIN;
const defaultChan = markdown ? APPRISE_DEFAULT_CHANNEL : APPRISE_DEFAULT_CHANNEL_PLAIN;
const dmFormat = ((config.body_format_dm as string) || '').trim() || defaultDm;
const chanFormat = ((config.body_format_channel as string) || '').trim() || defaultChan;
const dmFormat = ((config.body_format_dm as string) || '').trim() || APPRISE_DEFAULT_DM;
const chanFormat =
((config.body_format_channel as string) || '').trim() || APPRISE_DEFAULT_CHANNEL;
return (
<div className="space-y-3">
@@ -2577,39 +2549,6 @@ function AppriseConfigEditor({
<h3 className="text-base font-semibold tracking-tight">Message Format</h3>
<label className="flex items-center gap-3 cursor-pointer">
<input
type="checkbox"
checked={markdown}
onChange={(e) => {
const md = e.target.checked;
const updates: Record<string, unknown> = { ...config, markdown_format: md };
const curDm = ((config.body_format_dm as string) || '').trim();
const curChan = ((config.body_format_channel as string) || '').trim();
if (md) {
if (!curDm || curDm === APPRISE_DEFAULT_DM_PLAIN)
updates.body_format_dm = APPRISE_DEFAULT_DM;
if (!curChan || curChan === APPRISE_DEFAULT_CHANNEL_PLAIN)
updates.body_format_channel = APPRISE_DEFAULT_CHANNEL;
} else {
if (!curDm || curDm === APPRISE_DEFAULT_DM)
updates.body_format_dm = APPRISE_DEFAULT_DM_PLAIN;
if (!curChan || curChan === APPRISE_DEFAULT_CHANNEL)
updates.body_format_channel = APPRISE_DEFAULT_CHANNEL_PLAIN;
}
onChange(updates);
}}
className="h-4 w-4 rounded border-border"
/>
<div>
<span className="text-sm">Markdown formatting</span>
<p className="text-[0.8125rem] text-muted-foreground">
If notifications fail on services like Telegram due to special characters in sender
names, disable this option.
</p>
</div>
</label>
<details className="group">
<summary className="text-sm font-medium text-foreground cursor-pointer select-none flex items-center gap-1">
<ChevronDown className="h-3 w-3 transition-transform group-open:rotate-0 -rotate-90" />
@@ -2665,12 +2604,12 @@ function AppriseConfigEditor({
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label htmlFor="fanout-apprise-fmt-dm">DM format</Label>
{!appriseIsDefault(config.body_format_dm, defaultDm) && (
{!appriseIsDefault(config.body_format_dm, APPRISE_DEFAULT_DM) && (
<button
type="button"
aria-label="Reset DM format to default"
className="text-xs text-muted-foreground hover:text-foreground transition-colors"
onClick={() => onChange({ ...config, body_format_dm: defaultDm })}
onClick={() => onChange({ ...config, body_format_dm: APPRISE_DEFAULT_DM })}
>
Reset to default
</button>
@@ -2679,23 +2618,23 @@ function AppriseConfigEditor({
<textarea
id="fanout-apprise-fmt-dm"
className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm font-mono min-h-[56px]"
placeholder={defaultDm}
placeholder={APPRISE_DEFAULT_DM}
value={(config.body_format_dm as string) ?? ''}
onChange={(e) => onChange({ ...config, body_format_dm: e.target.value })}
rows={2}
/>
<AppriseFormatPreview format={dmFormat} vars={APPRISE_SAMPLE_VARS_DM} markdown={markdown} />
<AppriseFormatPreview format={dmFormat} vars={APPRISE_SAMPLE_VARS_DM} />
</div>
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label htmlFor="fanout-apprise-fmt-chan">Channel format</Label>
{!appriseIsDefault(config.body_format_channel, defaultChan) && (
{!appriseIsDefault(config.body_format_channel, APPRISE_DEFAULT_CHANNEL) && (
<button
type="button"
aria-label="Reset channel format to default"
className="text-xs text-muted-foreground hover:text-foreground transition-colors"
onClick={() => onChange({ ...config, body_format_channel: defaultChan })}
onClick={() => onChange({ ...config, body_format_channel: APPRISE_DEFAULT_CHANNEL })}
>
Reset to default
</button>
@@ -2704,12 +2643,12 @@ function AppriseConfigEditor({
<textarea
id="fanout-apprise-fmt-chan"
className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm font-mono min-h-[56px]"
placeholder={defaultChan}
placeholder={APPRISE_DEFAULT_CHANNEL}
value={(config.body_format_channel as string) ?? ''}
onChange={(e) => onChange({ ...config, body_format_channel: e.target.value })}
rows={2}
/>
<AppriseFormatPreview format={chanFormat} vars={APPRISE_SAMPLE_VARS} markdown={markdown} />
<AppriseFormatPreview format={chanFormat} vars={APPRISE_SAMPLE_VARS} />
</div>
<Separator />
@@ -0,0 +1,555 @@
import { useState, useEffect, useRef } from 'react';
import { Label } from '../ui/label';
import { Button } from '../ui/button';
import { Separator } from '../ui/separator';
import { toast } from '../ui/sonner';
import { api } from '../../api';
import { formatTime } from '../../utils/messageParser';
import { lppDisplayUnit } from '../repeater/repeaterPaneShared';
import { useDistanceUnit } from '../../contexts/DistanceUnitContext';
import { BulkDeleteContactsModal } from './BulkDeleteContactsModal';
import type {
AppSettings,
AppSettingsUpdate,
Contact,
TelemetryHistoryEntry,
TelemetrySchedule,
} from '../../types';
export function SettingsRadioAppSection({
appSettings,
onSaveAppSettings,
blockedKeys = [],
blockedNames = [],
onToggleBlockedKey,
onToggleBlockedName,
contacts = [],
onBulkDeleteContacts,
trackedTelemetryRepeaters = [],
onToggleTrackedTelemetry,
trackedTelemetryContacts = [],
onToggleTrackedTelemetryContact,
className,
}: {
appSettings: AppSettings;
onSaveAppSettings: (update: AppSettingsUpdate) => Promise<void>;
blockedKeys?: string[];
blockedNames?: string[];
onToggleBlockedKey?: (key: string) => void;
onToggleBlockedName?: (name: string) => void;
contacts?: Contact[];
onBulkDeleteContacts?: (deletedKeys: string[]) => void;
trackedTelemetryRepeaters?: string[];
onToggleTrackedTelemetry?: (publicKey: string) => Promise<void>;
trackedTelemetryContacts?: string[];
onToggleTrackedTelemetryContact?: (publicKey: string) => Promise<void>;
className?: string;
}) {
const { distanceUnit } = useDistanceUnit();
const [discoveryBlockedTypes, setDiscoveryBlockedTypes] = useState<number[]>([]);
const [bulkDeleteOpen, setBulkDeleteOpen] = useState(false);
const [latestTelemetry, setLatestTelemetry] = useState<
Record<string, TelemetryHistoryEntry | null>
>({});
const telemetryFetchedRef = useRef(false);
const [latestContactTelemetry, setLatestContactTelemetry] = useState<
Record<string, TelemetryHistoryEntry | null>
>({});
const contactTelemetryFetchedRef = useRef(false);
const [schedule, setSchedule] = useState<TelemetrySchedule | null>(null);
const [intervalDraft, setIntervalDraft] = useState<number>(appSettings.telemetry_interval_hours);
const saveChainRef = useRef<Promise<void>>(Promise.resolve());
useEffect(() => {
setDiscoveryBlockedTypes(appSettings.discovery_blocked_types ?? []);
setIntervalDraft(appSettings.telemetry_interval_hours);
}, [appSettings]);
useEffect(() => {
let cancelled = false;
api
.getTelemetrySchedule()
.then((s) => {
if (!cancelled) setSchedule(s);
})
.catch(() => {});
return () => {
cancelled = true;
};
}, [
trackedTelemetryRepeaters.length,
trackedTelemetryContacts.length,
appSettings.telemetry_interval_hours,
appSettings.telemetry_routed_hourly,
]);
useEffect(() => {
if (trackedTelemetryRepeaters.length === 0 || telemetryFetchedRef.current) return;
telemetryFetchedRef.current = true;
let cancelled = false;
const fetches = trackedTelemetryRepeaters.map((key) =>
api.repeaterTelemetryHistory(key).then(
(history) => [key, history.length > 0 ? history[history.length - 1] : null] as const,
() => [key, null] as const
)
);
Promise.all(fetches).then((entries) => {
if (cancelled) return;
setLatestTelemetry(Object.fromEntries(entries));
});
return () => {
cancelled = true;
};
}, [trackedTelemetryRepeaters]);
useEffect(() => {
if (trackedTelemetryContacts.length === 0 || contactTelemetryFetchedRef.current) return;
contactTelemetryFetchedRef.current = true;
let cancelled = false;
const fetches = trackedTelemetryContacts.map((key) =>
api.contactTelemetryHistory(key).then(
(history) => [key, history.length > 0 ? history[history.length - 1] : null] as const,
() => [key, null] as const
)
);
Promise.all(fetches).then((entries) => {
if (cancelled) return;
setLatestContactTelemetry(Object.fromEntries(entries));
});
return () => {
cancelled = true;
};
}, [trackedTelemetryContacts]);
const persistAppSettings = (update: AppSettingsUpdate, revert: () => void): Promise<void> => {
const chained = saveChainRef.current.then(async () => {
try {
await onSaveAppSettings(update);
} catch (err) {
console.error('Failed to save radio-app settings:', err);
revert();
toast.error('Failed to save setting', {
description: err instanceof Error ? err.message : 'Unknown error',
});
}
});
saveChainRef.current = chained;
return chained;
};
return (
<div className={className}>
{/* ── Tracked Repeater Telemetry ── */}
<div className="space-y-3">
<h3 className="text-base font-semibold tracking-tight">Tracked Repeater Telemetry</h3>
<p className="text-[0.8125rem] text-muted-foreground">
Repeaters opted into automatic telemetry collection are polled on a scheduled interval. To
limit mesh traffic, the app caps telemetry at 24 checks per day across all tracked
repeaters so fewer tracked repeaters allows shorter intervals, and more tracked
repeaters forces longer ones. Up to {schedule?.max_tracked ?? 8} repeaters may be tracked
at once ({trackedTelemetryRepeaters.length} / {schedule?.max_tracked ?? 8} slots used).
</p>
<div className="space-y-1.5">
<Label htmlFor="telemetry-interval" className="text-sm">
Collection interval
</Label>
<div className="flex items-center gap-2">
<select
id="telemetry-interval"
value={intervalDraft}
onChange={(e) => {
const nextValue = Number(e.target.value);
if (!Number.isFinite(nextValue) || nextValue === intervalDraft) return;
const prevValue = intervalDraft;
setIntervalDraft(nextValue);
void persistAppSettings({ telemetry_interval_hours: nextValue }, () =>
setIntervalDraft(prevValue)
);
}}
className="h-9 px-3 rounded-md border border-input bg-background text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
>
{(schedule?.options ?? [1, 2, 3, 4, 6, 8, 12, 24]).map((hrs) => (
<option key={hrs} value={hrs}>
Every {hrs} hour{hrs === 1 ? '' : 's'} ({Math.floor(24 / hrs)} check
{Math.floor(24 / hrs) === 1 ? '' : 's'}/day)
</option>
))}
</select>
</div>
{schedule && schedule.effective_hours !== schedule.preferred_hours && (
<p className="text-xs text-warning">
Saved preference is {schedule.preferred_hours} hour
{schedule.preferred_hours === 1 ? '' : 's'}, but the scheduler is using{' '}
{schedule.effective_hours} hours because {schedule.tracked_count} repeater
{schedule.tracked_count === 1 ? '' : 's'}{' '}
{schedule.tracked_count === 1 ? 'is' : 'are'} tracked. Your preference will be
restored if you drop back to a supported count.
</p>
)}
</div>
<label className="flex items-start gap-2 cursor-pointer">
<input
type="checkbox"
checked={appSettings.telemetry_routed_hourly}
onChange={() => {
const next = !appSettings.telemetry_routed_hourly;
void persistAppSettings({ telemetry_routed_hourly: next }, () => {});
}}
className="w-4 h-4 rounded border-input accent-primary mt-0.5"
/>
<div>
<span className="text-sm">Poll direct/routed-path repeaters hourly</span>
<p className="text-[0.8125rem] text-muted-foreground">
When enabled, tracked repeaters with a direct or routed path (not flood) are polled
every hour instead of on the scheduled interval above. Flood-only repeaters still
follow the normal schedule.
</p>
</div>
</label>
{schedule?.next_run_at != null && (
<p className="text-xs text-muted-foreground">
{schedule.routed_hourly ? 'Next flood run at' : 'Next run at'}{' '}
{formatTime(schedule.next_run_at)} (UTC top of hour).
</p>
)}
{schedule?.next_routed_run_at != null && (
<p className="text-xs text-muted-foreground">
Next direct/routed run at {formatTime(schedule.next_routed_run_at)} (UTC top of hour).
</p>
)}
{trackedTelemetryRepeaters.length === 0 ? (
<p className="text-sm text-muted-foreground italic">
No repeaters are being tracked. Enable tracking from a repeater's dashboard.
</p>
) : (
<div className="space-y-2">
{trackedTelemetryRepeaters.map((key) => {
const contact = contacts.find((c) => c.public_key === key);
const displayName = contact?.name ?? key.slice(0, 12);
const routeSource = contact?.effective_route_source ?? 'flood';
const hasRealPath =
contact?.effective_route != null && contact.effective_route.path_len >= 0;
const routeLabel = !hasRealPath
? 'flood'
: routeSource === 'override'
? 'routed'
: routeSource === 'direct'
? 'direct'
: 'flood';
const routeColor = hasRealPath
? 'text-primary bg-primary/10'
: 'text-muted-foreground bg-muted';
const snap = latestTelemetry[key];
const d = snap?.data;
return (
<div key={key} className="rounded-md border border-border px-3 py-2">
<div className="flex items-center justify-between gap-2">
<div className="flex-1 min-w-0">
<span className="text-sm truncate block">{displayName}</span>
<div className="flex items-center gap-1.5">
<span className="text-[0.625rem] text-muted-foreground font-mono">
{key.slice(0, 12)}
</span>
<span
className={`text-[0.625rem] uppercase tracking-wider px-1.5 py-0.5 rounded font-medium ${routeColor}`}
>
{routeLabel}
</span>
</div>
</div>
{onToggleTrackedTelemetry && (
<Button
variant="ghost"
size="sm"
onClick={() => onToggleTrackedTelemetry(key)}
className="h-7 text-xs flex-shrink-0 text-destructive hover:text-destructive"
>
Remove
</Button>
)}
</div>
{d ? (
<div className="mt-1.5 flex flex-wrap gap-x-3 gap-y-0.5 text-[0.625rem] text-muted-foreground">
<span>{d.battery_volts?.toFixed(2)}V</span>
<span>noise {d.noise_floor_dbm} dBm</span>
<span>
rx {d.packets_received != null ? d.packets_received.toLocaleString() : '?'}
</span>
<span>
tx {d.packets_sent != null ? d.packets_sent.toLocaleString() : '?'}
</span>
{d.lpp_sensors?.map((s) => {
const display = lppDisplayUnit(s.type_name, s.value, distanceUnit);
const val =
typeof display.value === 'number'
? display.value % 1 === 0
? display.value
: display.value.toFixed(1)
: display.value;
const label = s.type_name.charAt(0).toUpperCase() + s.type_name.slice(1);
return (
<span key={`${s.type_name}-${s.channel}`}>
{label} {val}
{display.unit ? ` ${display.unit}` : ''}
</span>
);
})}
<span className="ml-auto">checked {formatTime(snap.timestamp)}</span>
</div>
) : snap === null ? (
<div className="mt-1 text-[0.625rem] text-muted-foreground italic">
No telemetry recorded yet
</div>
) : null}
</div>
);
})}
</div>
)}
</div>
<Separator />
{/* ── Tracked Contact Telemetry ── */}
<div className="space-y-3">
<h3 className="text-base font-semibold tracking-tight">Tracked Contact Telemetry</h3>
<p className="text-[0.8125rem] text-muted-foreground">
Non-repeater contacts (companions, rooms, sensors) can also be tracked for periodic LPP
telemetry collection (battery, sensors, GPS). Up to 8 contacts may be tracked. The daily
check ceiling is shared with tracked repeaters adding contacts may clamp the interval
upward.
</p>
{trackedTelemetryContacts.length === 0 ? (
<p className="text-sm text-muted-foreground italic">
No contacts are being tracked. Enable tracking from a contact&apos;s info pane.
</p>
) : (
<div className="space-y-2">
{trackedTelemetryContacts.map((key) => {
const contact = contacts.find((c) => c.public_key === key);
const displayName = contact?.name ?? key.slice(0, 12);
const routeSource = contact?.effective_route_source ?? 'flood';
const hasRealPath =
contact?.effective_route != null && contact.effective_route.path_len >= 0;
const routeLabel = !hasRealPath
? 'flood'
: routeSource === 'override'
? 'routed'
: routeSource === 'direct'
? 'direct'
: 'flood';
const routeColor = hasRealPath
? 'text-primary bg-primary/10'
: 'text-muted-foreground bg-muted';
const snap = latestContactTelemetry[key];
const d = snap?.data;
return (
<div key={key} className="rounded-md border border-border px-3 py-2">
<div className="flex items-center justify-between gap-2">
<div className="flex-1 min-w-0">
<span className="text-sm truncate block">{displayName}</span>
<div className="flex items-center gap-1.5">
<span className="text-[0.625rem] text-muted-foreground font-mono">
{key.slice(0, 12)}
</span>
<span
className={`text-[0.625rem] uppercase tracking-wider px-1.5 py-0.5 rounded font-medium ${routeColor}`}
>
{routeLabel}
</span>
</div>
</div>
{onToggleTrackedTelemetryContact && (
<Button
variant="ghost"
size="sm"
onClick={() => onToggleTrackedTelemetryContact(key)}
className="h-7 text-xs flex-shrink-0 text-destructive hover:text-destructive"
>
Remove
</Button>
)}
</div>
{d ? (
<div className="mt-1.5 flex flex-wrap gap-x-3 gap-y-0.5 text-[0.625rem] text-muted-foreground">
{d.lpp_sensors?.map((s) => {
if (typeof s.value !== 'number') return null;
const display = lppDisplayUnit(s.type_name, s.value, distanceUnit);
const val =
typeof display.value === 'number'
? display.value % 1 === 0
? display.value
: display.value.toFixed(1)
: display.value;
const label = s.type_name.charAt(0).toUpperCase() + s.type_name.slice(1);
return (
<span key={`${s.type_name}-${s.channel}`}>
{label} {val}
{display.unit ? ` ${display.unit}` : ''}
</span>
);
})}
<span className="ml-auto">checked {formatTime(snap.timestamp)}</span>
</div>
) : snap === null ? (
<div className="mt-1 text-[0.625rem] text-muted-foreground italic">
No telemetry recorded yet
</div>
) : null}
</div>
);
})}
</div>
)}
</div>
<Separator />
{/* ── Contact Management ── */}
<div className="space-y-5">
<h3 className="text-base font-semibold tracking-tight">Contact Management</h3>
<div className="space-y-3">
<h4 className="text-sm font-semibold">Block Discovery of New Node Types</h4>
<p className="text-[0.8125rem] text-muted-foreground">
Checked types will be ignored when heard via advertisement. Existing contacts of these
types are still updated. This does not affect contacts added manually or via DM.
</p>
<div className="space-y-1.5">
{(
[
[1, 'Block clients'],
[2, 'Block repeaters'],
[3, 'Block room servers'],
[4, 'Block sensors'],
] as const
).map(([typeCode, label]) => {
const checked = discoveryBlockedTypes.includes(typeCode);
return (
<label key={typeCode} className="flex items-center gap-2 text-sm cursor-pointer">
<input
type="checkbox"
checked={checked}
onChange={() => {
const prev = discoveryBlockedTypes;
const next = checked
? prev.filter((t) => t !== typeCode)
: [...prev, typeCode];
setDiscoveryBlockedTypes(next);
void persistAppSettings({ discovery_blocked_types: next }, () =>
setDiscoveryBlockedTypes(prev)
);
}}
className="rounded border-input"
/>
{label}
</label>
);
})}
</div>
{discoveryBlockedTypes.length > 0 && (
<p className="text-xs text-warning">
New{' '}
{discoveryBlockedTypes
.map((t) =>
t === 1 ? 'clients' : t === 2 ? 'repeaters' : t === 3 ? 'room servers' : 'sensors'
)
.join(', ')}{' '}
heard via advertisement will not be added to your contact list.
</p>
)}
</div>
<div className="space-y-3">
<h4 className="text-sm font-semibold">Blocked Contacts</h4>
<p className="text-[0.8125rem] text-muted-foreground">
Blocked contacts are hidden from the sidebar. Blocking only hides messages from the UI
MQTT forwarding and bot responses are not affected. Messages are still stored and will
reappear if unblocked.
</p>
{blockedKeys.length === 0 && blockedNames.length === 0 ? (
<p className="text-sm text-muted-foreground italic">
No blocked contacts. Block contacts from their info pane, viewed by clicking their
avatar in any channel, or their name within the top status bar with the conversation
open.
</p>
) : (
<div className="space-y-2">
{blockedKeys.length > 0 && (
<div>
<span className="text-xs text-muted-foreground font-medium">Blocked Keys</span>
<div className="mt-1 space-y-1">
{blockedKeys.map((key) => (
<div key={key} className="flex items-center justify-between gap-2">
<span className="text-xs font-mono truncate flex-1">{key}</span>
{onToggleBlockedKey && (
<Button
variant="ghost"
size="sm"
onClick={() => onToggleBlockedKey(key)}
className="h-7 text-xs flex-shrink-0"
>
Unblock
</Button>
)}
</div>
))}
</div>
</div>
)}
{blockedNames.length > 0 && (
<div>
<span className="text-xs text-muted-foreground font-medium">Blocked Names</span>
<div className="mt-1 space-y-1">
{blockedNames.map((name) => (
<div key={name} className="flex items-center justify-between gap-2">
<span className="text-sm truncate flex-1">{name}</span>
{onToggleBlockedName && (
<Button
variant="ghost"
size="sm"
onClick={() => onToggleBlockedName(name)}
className="h-7 text-xs flex-shrink-0"
>
Unblock
</Button>
)}
</div>
))}
</div>
</div>
)}
</div>
)}
</div>
<div className="space-y-3">
<h4 className="text-sm font-semibold">Bulk Delete Contacts</h4>
<p className="text-[0.8125rem] text-muted-foreground">
Remove multiple contacts or repeaters at once. Useful for cleaning up spam or unwanted
nodes. Message history will be preserved.
</p>
<Button variant="outline" className="w-full" onClick={() => setBulkDeleteOpen(true)}>
Open Bulk Delete
</Button>
<BulkDeleteContactsModal
open={bulkDeleteOpen}
onClose={() => setBulkDeleteOpen(false)}
contacts={contacts}
onDeleted={(keys) => onBulkDeleteContacts?.(keys)}
/>
</div>
</div>
</div>
);
}
@@ -183,6 +183,9 @@ export function SettingsRadioSection({
const [pathHashMode, setPathHashMode] = useState('0');
const [advertLocationSource, setAdvertLocationSource] = useState<'off' | 'current'>('current');
const [multiAcksEnabled, setMultiAcksEnabled] = useState(false);
const [telemetryModeBase, setTelemetryModeBase] = useState(0);
const [telemetryModeLoc, setTelemetryModeLoc] = useState(0);
const [telemetryModeEnv, setTelemetryModeEnv] = useState(0);
const [gettingLocation, setGettingLocation] = useState(false);
const [busy, setBusy] = useState(false);
const [rebooting, setRebooting] = useState(false);
@@ -218,6 +221,9 @@ export function SettingsRadioSection({
setPathHashMode(String(config.path_hash_mode));
setAdvertLocationSource(config.advert_location_source ?? 'current');
setMultiAcksEnabled(config.multi_acks_enabled ?? false);
setTelemetryModeBase(config.telemetry_mode_base ?? 0);
setTelemetryModeLoc(config.telemetry_mode_loc ?? 0);
setTelemetryModeEnv(config.telemetry_mode_env ?? 0);
}, [config]);
useEffect(() => {
@@ -313,6 +319,15 @@ export function SettingsRadioSection({
...(multiAcksEnabled !== (config.multi_acks_enabled ?? false)
? { multi_acks_enabled: multiAcksEnabled }
: {}),
...(telemetryModeBase !== (config.telemetry_mode_base ?? 0)
? { telemetry_mode_base: telemetryModeBase }
: {}),
...(telemetryModeLoc !== (config.telemetry_mode_loc ?? 0)
? { telemetry_mode_loc: telemetryModeLoc }
: {}),
...(telemetryModeEnv !== (config.telemetry_mode_env ?? 0)
? { telemetry_mode_env: telemetryModeEnv }
: {}),
radio: {
freq: parsedFreq,
bw: parsedBw,
@@ -468,6 +483,9 @@ export function SettingsRadioSection({
path_hash_mode: config.path_hash_mode,
advert_location_source: config.advert_location_source ?? 'current',
multi_acks_enabled: config.multi_acks_enabled ?? false,
telemetry_mode_base: config.telemetry_mode_base ?? 0,
telemetry_mode_loc: config.telemetry_mode_loc ?? 0,
telemetry_mode_env: config.telemetry_mode_env ?? 0,
});
const downloadJson = (profile: object, suffix: string) => {
@@ -539,6 +557,10 @@ export function SettingsRadioSection({
if (data.advert_location_source === 'off' || data.advert_location_source === 'current')
setAdvertLocationSource(data.advert_location_source);
if (typeof data.multi_acks_enabled === 'boolean') setMultiAcksEnabled(data.multi_acks_enabled);
if (typeof data.telemetry_mode_base === 'number')
setTelemetryModeBase(data.telemetry_mode_base);
if (typeof data.telemetry_mode_loc === 'number') setTelemetryModeLoc(data.telemetry_mode_loc);
if (typeof data.telemetry_mode_env === 'number') setTelemetryModeEnv(data.telemetry_mode_env);
};
const buildUpdateFromImport = (data: Record<string, unknown>): RadioConfigUpdate => {
@@ -554,6 +576,12 @@ export function SettingsRadioSection({
update.advert_location_source = data.advert_location_source;
if (typeof data.multi_acks_enabled === 'boolean')
update.multi_acks_enabled = data.multi_acks_enabled;
if (typeof data.telemetry_mode_base === 'number')
update.telemetry_mode_base = data.telemetry_mode_base as number;
if (typeof data.telemetry_mode_loc === 'number')
update.telemetry_mode_loc = data.telemetry_mode_loc as number;
if (typeof data.telemetry_mode_env === 'number')
update.telemetry_mode_env = data.telemetry_mode_env as number;
if (config.path_hash_mode_supported && typeof data.path_hash_mode === 'number')
update.path_hash_mode = data.path_hash_mode as number;
return update;
@@ -954,6 +982,66 @@ export function SettingsRadioSection({
</div>
</div>
<Separator />
{/* ── Telemetry Sharing ── */}
<div className="space-y-3">
<h3 className="text-base font-semibold tracking-tight">Telemetry Sharing</h3>
<p className="text-[0.8125rem] text-muted-foreground">
Controls what this radio shares when other nodes request its telemetry. &ldquo;Deny&rdquo;
blocks all requests, &ldquo;Per-Contact&rdquo; uses per-contact permission flags on the
radio, and &ldquo;Allow All&rdquo; shares with any requester.
</p>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
<div className="space-y-1.5">
<Label htmlFor="telemetry-mode-base" className="text-sm">
Battery &amp; Base
</Label>
<select
id="telemetry-mode-base"
value={telemetryModeBase}
onChange={(e) => setTelemetryModeBase(Number(e.target.value))}
className="w-full h-9 px-3 rounded-md border border-input bg-background text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
>
<option value={0}>Deny</option>
<option value={1}>Per-Contact</option>
<option value={2}>Allow All</option>
</select>
</div>
<div className="space-y-1.5">
<Label htmlFor="telemetry-mode-loc" className="text-sm">
Location
</Label>
<select
id="telemetry-mode-loc"
value={telemetryModeLoc}
onChange={(e) => setTelemetryModeLoc(Number(e.target.value))}
className="w-full h-9 px-3 rounded-md border border-input bg-background text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
>
<option value={0}>Deny</option>
<option value={1}>Per-Contact</option>
<option value={2}>Allow All</option>
</select>
</div>
<div className="space-y-1.5">
<Label htmlFor="telemetry-mode-env" className="text-sm">
Environment Sensors
</Label>
<select
id="telemetry-mode-env"
value={telemetryModeEnv}
onChange={(e) => setTelemetryModeEnv(Number(e.target.value))}
className="w-full h-9 px-3 rounded-md border border-input bg-background text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
>
<option value={0}>Deny</option>
<option value={1}>Per-Contact</option>
<option value={2}>Allow All</option>
</select>
</div>
</div>
</div>
{error && (
<div className="text-sm text-destructive" role="alert">
{error}
@@ -5,16 +5,25 @@ import {
MonitorCog,
RadioTower,
Share2,
SlidersHorizontal,
type LucideIcon,
} from 'lucide-react';
export type SettingsSection = 'radio' | 'local' | 'database' | 'fanout' | 'statistics' | 'about';
export type SettingsSection =
| 'radio'
| 'local'
| 'radio-app'
| 'database'
| 'fanout'
| 'statistics'
| 'about';
export const SETTINGS_SECTION_ORDER: SettingsSection[] = [
'radio',
'local',
'database',
'fanout',
'radio-app',
'database',
'statistics',
'about',
];
@@ -22,7 +31,8 @@ export const SETTINGS_SECTION_ORDER: SettingsSection[] = [
export const SETTINGS_SECTION_LABELS: Record<SettingsSection, string> = {
radio: 'Radio',
local: 'Local Configuration',
database: 'Database & Messaging',
'radio-app': 'Radio-App Management',
database: 'Database',
fanout: 'MQTT & Automation',
statistics: 'Statistics',
about: 'About',
@@ -31,6 +41,7 @@ export const SETTINGS_SECTION_LABELS: Record<SettingsSection, string> = {
export const SETTINGS_SECTION_ICONS: Record<SettingsSection, LucideIcon> = {
radio: RadioTower,
local: MonitorCog,
'radio-app': SlidersHorizontal,
database: Database,
fanout: Share2,
statistics: BarChart3,
+34
View File
@@ -113,6 +113,39 @@ export function useAppSettings() {
}
}, []);
const handleToggleTrackedTelemetryContact = useCallback(async (publicKey: string) => {
const key = publicKey.toLowerCase();
setAppSettings((prev) => {
if (!prev) return prev;
const current = prev.tracked_telemetry_contacts ?? [];
const wasTracked = current.includes(key);
const optimistic = wasTracked ? current.filter((k) => k !== key) : [...current, key];
return { ...prev, tracked_telemetry_contacts: optimistic };
});
try {
const result = await api.toggleTrackedTelemetryContact(publicKey);
setAppSettings((prev) =>
prev ? { ...prev, tracked_telemetry_contacts: result.tracked_telemetry_contacts } : prev
);
} catch (err) {
console.error('Failed to toggle tracked contact telemetry:', err);
try {
const settings = await api.getSettings();
setAppSettings(settings);
} catch {
// If refetch also fails, leave optimistic state
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const detail = (err as any)?.body?.detail;
if (typeof detail === 'object' && detail?.message) {
toast.error(detail.message);
} else {
toast.error('Failed to update tracked contact telemetry');
}
}
}, []);
// Legacy favorites migration: if pre-server-side favorites exist in
// localStorage, toggle each one via the existing API and clear the key.
useEffect(() => {
@@ -153,5 +186,6 @@ export function useAppSettings() {
handleToggleBlockedKey,
handleToggleBlockedName,
handleToggleTrackedTelemetry,
handleToggleTrackedTelemetryContact,
};
}
+1 -4
View File
@@ -6,10 +6,7 @@
padding: 0;
}
html {
height: 100dvh;
}
html,
body,
#root {
height: 100%;
+3 -2
View File
@@ -149,11 +149,12 @@ vi.mock('../components/SettingsModal', () => ({
SettingsModal: ({ desktopSection }: { desktopSection?: string }) => (
<div data-testid="settings-modal-section">{desktopSection ?? 'none'}</div>
),
SETTINGS_SECTION_ORDER: ['radio', 'local', 'database', 'bot'],
SETTINGS_SECTION_ORDER: ['radio', 'local', 'radio-app', 'database', 'bot'],
SETTINGS_SECTION_LABELS: {
radio: '📻 Radio',
local: '🖥️ Local Configuration',
database: '🗄️ Database & Messaging',
'radio-app': '🗄️ Radio-App Management',
database: '🗄️ Database',
bot: '🤖 Bot',
},
}));
+3 -2
View File
@@ -92,11 +92,12 @@ vi.mock('../components/SettingsModal', () => ({
SettingsModal: ({ desktopSection }: { desktopSection?: string }) => (
<div data-testid="settings-modal-section">{desktopSection ?? 'none'}</div>
),
SETTINGS_SECTION_ORDER: ['radio', 'local', 'database', 'bot'],
SETTINGS_SECTION_ORDER: ['radio', 'local', 'radio-app', 'database', 'bot'],
SETTINGS_SECTION_LABELS: {
radio: 'Radio',
local: 'Local Configuration',
database: 'Database & Messaging',
'radio-app': 'Radio-App Management',
database: 'Database',
bot: 'Bot',
},
}));
+13 -1
View File
@@ -4,14 +4,17 @@ import { describe, expect, it, vi, beforeEach } from 'vitest';
import { ContactInfoPane } from '../components/ContactInfoPane';
import type { Contact, ContactAnalytics } from '../types';
const { getContactAnalytics } = vi.hoisted(() => ({
const { getContactAnalytics, contactTelemetryHistory } = vi.hoisted(() => ({
getContactAnalytics: vi.fn(),
contactTelemetryHistory: vi.fn(),
}));
vi.mock('../api', () => ({
api: {
getContactAnalytics,
contactTelemetryHistory,
},
isAbortError: () => false,
}));
vi.mock('../components/ui/sheet', () => ({
@@ -26,6 +29,13 @@ vi.mock('../components/ContactAvatar', () => ({
ContactAvatar: () => <div data-testid="contact-avatar" />,
}));
vi.mock('react-leaflet', () => ({
MapContainer: () => null,
TileLayer: () => null,
CircleMarker: () => null,
Popup: () => null,
}));
vi.mock('../components/ui/sonner', () => ({
toast: {
error: vi.fn(),
@@ -99,6 +109,8 @@ const baseProps = {
describe('ContactInfoPane', () => {
beforeEach(() => {
getContactAnalytics.mockReset();
contactTelemetryHistory.mockReset();
contactTelemetryHistory.mockResolvedValue([]);
baseProps.onSearchMessagesByKey = vi.fn();
baseProps.onSearchMessagesByName = vi.fn();
});
+2
View File
@@ -109,6 +109,7 @@ beforeEach(() => {
blocked_names: [],
discovery_blocked_types: [],
tracked_telemetry_repeaters: [],
tracked_telemetry_contacts: [],
auto_resend_channel: false,
telemetry_interval_hours: 8,
telemetry_routed_hourly: false,
@@ -1049,6 +1050,7 @@ describe('SettingsFanoutSection', () => {
blocked_names: [],
discovery_blocked_types: [],
tracked_telemetry_repeaters: ['cc'.repeat(32)],
tracked_telemetry_contacts: [],
auto_resend_channel: false,
telemetry_interval_hours: 8,
telemetry_routed_hourly: false,
+1 -1
View File
@@ -51,7 +51,7 @@ describe('MessageInput', () => {
}
function getInput() {
return screen.getByPlaceholderText('Type a message...') as HTMLTextAreaElement;
return screen.getByPlaceholderText('Type a message...') as HTMLInputElement;
}
function getSendButton() {
+2 -8
View File
@@ -94,8 +94,6 @@ describe('buildRawPacketStatsSnapshot', () => {
sender: 'Alpha',
channel_key: null,
contact_key: '0a'.repeat(32),
sender_timestamp: null,
message: null,
},
};
@@ -147,9 +145,7 @@ describe('buildRawPacketStatsSnapshot', () => {
'2-5',
'6-10',
'11-15',
'16-20',
'21-31',
'32+',
'16+',
]);
expect(stats.hopProfile).toEqual(
expect.arrayContaining([
@@ -158,9 +154,7 @@ describe('buildRawPacketStatsSnapshot', () => {
expect.objectContaining({ label: '2-5', count: 1 }),
expect.objectContaining({ label: '6-10', count: 0 }),
expect.objectContaining({ label: '11-15', count: 0 }),
expect.objectContaining({ label: '16-20', count: 0 }),
expect.objectContaining({ label: '21-31', count: 0 }),
expect.objectContaining({ label: '32+', count: 0 }),
expect.objectContaining({ label: '16+', count: 0 }),
])
);
expect(stats.hopByteWidthProfile).toEqual(
+6 -5
View File
@@ -70,6 +70,7 @@ const baseSettings: AppSettings = {
blocked_names: [],
discovery_blocked_types: [],
tracked_telemetry_repeaters: [],
tracked_telemetry_contacts: [],
auto_resend_channel: false,
telemetry_interval_hours: 8,
telemetry_routed_hourly: false,
@@ -177,7 +178,7 @@ function setMatchMedia(matches: boolean) {
}
function openRadioSection() {
const radioToggle = screen.getByRole('button', { name: /Radio/i });
const radioToggle = screen.getByRole('button', { name: /^Radio$/i });
fireEvent.click(radioToggle);
}
@@ -250,7 +251,7 @@ describe('SettingsModal', () => {
it('shows radio-unavailable message when config is null', () => {
renderModal({ config: null });
const radioToggle = screen.getByRole('button', { name: /Radio/i });
const radioToggle = screen.getByRole('button', { name: /^Radio$/i });
expect(radioToggle).not.toBeDisabled();
fireEvent.click(radioToggle);
@@ -499,7 +500,7 @@ describe('SettingsModal', () => {
renderModal({
externalSidebarNav: true,
desktopSection: 'database',
desktopSection: 'radio-app',
onSaveAppSettings,
});
@@ -806,7 +807,7 @@ describe('SettingsModal', () => {
renderModal({
externalSidebarNav: true,
desktopSection: 'database',
desktopSection: 'radio-app',
onSaveAppSettings,
});
@@ -831,7 +832,7 @@ describe('SettingsModal', () => {
renderModal({
externalSidebarNav: true,
desktopSection: 'database',
desktopSection: 'radio-app',
appSettings: {
...baseSettings,
tracked_telemetry_repeaters: [directKey],
+19 -2
View File
@@ -17,6 +17,9 @@ export interface RadioConfig {
path_hash_mode_supported: boolean;
advert_location_source?: 'off' | 'current';
multi_acks_enabled?: boolean;
telemetry_mode_base?: number;
telemetry_mode_loc?: number;
telemetry_mode_env?: number;
}
export interface RadioConfigUpdate {
@@ -28,6 +31,9 @@ export interface RadioConfigUpdate {
path_hash_mode?: number;
advert_location_source?: 'off' | 'current';
multi_acks_enabled?: boolean;
telemetry_mode_base?: number;
telemetry_mode_loc?: number;
telemetry_mode_env?: number;
}
export type RadioDiscoveryTarget = 'repeaters' | 'sensors' | 'all';
@@ -343,8 +349,6 @@ export interface RawPacket {
sender: string | null;
channel_key: string | null;
contact_key: string | null;
sender_timestamp: number | null;
message: string | null;
} | null;
}
@@ -359,6 +363,7 @@ export interface AppSettings {
blocked_names: string[];
discovery_blocked_types: number[];
tracked_telemetry_repeaters: string[];
tracked_telemetry_contacts: string[];
auto_resend_channel: boolean;
telemetry_interval_hours: number;
telemetry_routed_hourly: boolean;
@@ -492,6 +497,18 @@ export interface RepeaterLppTelemetryResponse {
sensors: LppSensor[];
}
export interface ContactTelemetryResponse {
sensors: LppSensor[];
fetched_at: number;
telemetry_history: TelemetryHistoryEntry[];
}
export interface TrackedTelemetryContactsResponse {
tracked_telemetry_contacts: string[];
names: Record<string, string>;
schedule: TelemetrySchedule;
}
export type PaneName =
| 'status'
| 'nodeInfo'
+45 -50
View File
@@ -324,56 +324,51 @@ export function inspectRawPacketWithOptions(
createPacketField('payload', `payload-${index}`, segment, structure.payload.startByte)
);
const enrichedPayloadFields = payloadFields.map((field) => {
if (!decoded?.isValid || field.name !== 'Ciphertext') {
return field;
}
const withStructure = {
...field,
description: describeCiphertextStructure(
decoded.payloadType,
field.endByte - field.startByte + 1,
field.description
),
};
// GroupText: client-side decoder has the decrypted content
if (decoded.payloadType === PayloadType.GroupText && decoded.payload.decoded) {
const payload = decoded.payload.decoded as {
decrypted?: { timestamp?: number; flags?: number; sender?: string; message?: string };
};
if (!payload.decrypted?.message) {
return withStructure;
}
const detailLines = [
payload.decrypted.timestamp != null
? `Sent (packet): ${formatUnixTimestamp(payload.decrypted.timestamp)}`
: null,
payload.decrypted.flags != null
? `Flags: 0x${payload.decrypted.flags.toString(16).padStart(2, '0')}`
: null,
payload.decrypted.sender ? `Sender: ${payload.decrypted.sender}` : null,
`Message: ${payload.decrypted.message}`,
].filter((line): line is string => line !== null);
return { ...withStructure, decryptedMessage: detailLines.join('\n') };
}
// TextMessage (DM): server-side decryption via decrypted_info
if (decoded.payloadType === PayloadType.TextMessage && packet.decrypted_info?.message) {
const info = packet.decrypted_info;
const detailLines = [
info.sender_timestamp != null
? `Sent (packet): ${formatUnixTimestamp(info.sender_timestamp)}`
: null,
info.sender ? `Sender: ${info.sender}` : null,
`Message: ${info.message}`,
].filter((line): line is string => line !== null);
return { ...withStructure, decryptedMessage: detailLines.join('\n') };
}
return withStructure;
});
const enrichedPayloadFields =
decoded?.isValid && decoded.payloadType === PayloadType.GroupText && decoded.payload.decoded
? payloadFields.map((field) => {
if (field.name !== 'Ciphertext') {
return field;
}
const payload = decoded.payload.decoded as {
decrypted?: { timestamp?: number; flags?: number; sender?: string; message?: string };
};
if (!payload.decrypted?.message) {
return field;
}
const detailLines = [
payload.decrypted.timestamp != null
? `Timestamp: ${formatUnixTimestamp(payload.decrypted.timestamp)}`
: null,
payload.decrypted.flags != null
? `Flags: 0x${payload.decrypted.flags.toString(16).padStart(2, '0')}`
: null,
payload.decrypted.sender ? `Sender: ${payload.decrypted.sender}` : null,
`Message: ${payload.decrypted.message}`,
].filter((line): line is string => line !== null);
return {
...field,
description: describeCiphertextStructure(
decoded.payloadType,
field.endByte - field.startByte + 1,
field.description
),
decryptedMessage: detailLines.join('\n'),
};
})
: payloadFields.map((field) => {
if (!decoded?.isValid || field.name !== 'Ciphertext') {
return field;
}
return {
...field,
description: describeCiphertextStructure(
decoded.payloadType,
field.endByte - field.startByte + 1,
field.description
),
};
});
return {
decoded,
+2 -10
View File
@@ -322,13 +322,7 @@ function getHopProfileBucket(pathTokenCount: number): string {
if (pathTokenCount <= 15) {
return '11-15';
}
if (pathTokenCount <= 20) {
return '16-20';
}
if (pathTokenCount <= 31) {
return '21-31';
}
return '32+';
return '16+';
}
export function buildRawPacketStatsSnapshot(
@@ -360,9 +354,7 @@ export function buildRawPacketStatsSnapshot(
['2-5', 0],
['6-10', 0],
['11-15', 0],
['16-20', 0],
['21-31', 0],
['32+', 0],
['16+', 0],
]);
const hopByteWidthCounts = new Map<string, number>([
['No path', 0],
+1
View File
@@ -16,6 +16,7 @@ interface ParsedHashConversation {
const SETTINGS_SECTIONS: SettingsSection[] = [
'radio',
'local',
'radio-app',
'fanout',
'database',
'statistics',
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "remoteterm-meshcore"
version = "3.13.0"
version = "3.12.3"
description = "RemoteTerm - Web interface for MeshCore radio mesh networks"
readme = "README.md"
requires-python = ">=3.11"
+2
View File
@@ -30,6 +30,7 @@ async def test_db():
"""Create an in-memory test database with schema + migrations."""
from app.repository import (
channels,
contact_telemetry,
contacts,
messages,
raw_packets,
@@ -49,6 +50,7 @@ async def test_db():
settings,
fanout_repo,
repeater_telemetry,
contact_telemetry,
]
originals = [(mod, mod.db) for mod in submodules]
+6 -7
View File
@@ -23,9 +23,8 @@ test.describe('Channel messaging in #flightless', () => {
// Send it
await page.getByRole('button', { name: 'Send', exact: true }).click();
// Verify message appears in the message list (use locator('span') to avoid
// matching the textarea which may briefly retain the sent text)
await expect(page.locator('span', { hasText: testMessage })).toBeVisible({ timeout: 15_000 });
// Verify message appears in the message list
await expect(page.getByText(testMessage)).toBeVisible({ timeout: 15_000 });
});
test('outgoing message shows ack indicator', async ({ page }) => {
@@ -38,8 +37,8 @@ test.describe('Channel messaging in #flightless', () => {
await input.fill(testMessage);
await page.getByRole('button', { name: 'Send', exact: true }).click();
// Wait for the message to appear in the message list
const messageEl = page.locator('span', { hasText: testMessage });
// Wait for the message to appear
const messageEl = page.getByText(testMessage);
await expect(messageEl).toBeVisible({ timeout: 15_000 });
// Outgoing messages show either "?" (pending) or "✓" (acked)
@@ -59,7 +58,7 @@ test.describe('Channel messaging in #flightless', () => {
await input.fill(testMessage);
await page.getByRole('button', { name: 'Send', exact: true }).click();
const messageEl = page.locator('span', { hasText: testMessage }).first();
const messageEl = page.getByText(testMessage).first();
await expect(messageEl).toBeVisible({ timeout: 15_000 });
const messageContainer = messageEl.locator(
@@ -95,6 +94,6 @@ test.describe('Channel messaging in #flightless', () => {
await expect(page.getByText('Message resent')).toBeVisible({ timeout: 10_000 });
// Byte-perfect resend should not create a second visible row in this conversation.
await expect(page.locator('span', { hasText: testMessage })).toHaveCount(1);
await expect(page.getByText(testMessage)).toHaveCount(1);
});
});
+17 -17
View File
@@ -50,7 +50,7 @@ def _patch_require_connected(mc=None, *, detail="Radio not connected"):
if mc is None:
return patch(
"app.services.radio_runtime.radio_runtime.require_connected",
side_effect=HTTPException(status_code=423, detail=detail),
side_effect=HTTPException(status_code=503, detail=detail),
)
return patch("app.services.radio_runtime.radio_runtime.require_connected", return_value=mc)
@@ -422,11 +422,11 @@ class TestDebugEndpoint:
class TestRadioDisconnectedHandler:
"""Test that RadioDisconnectedError maps to 423."""
"""Test that RadioDisconnectedError maps to 503."""
@pytest.mark.asyncio
async def test_disconnect_race_returns_423(self, test_db, client):
"""If radio disconnects between require_connected() and lock acquisition, return 423."""
async def test_disconnect_race_returns_503(self, test_db, client):
"""If radio disconnects between require_connected() and lock acquisition, return 503."""
pub_key = "ab" * 32
await _insert_contact(pub_key, "Alice")
@@ -437,7 +437,7 @@ class TestRadioDisconnectedHandler:
"/api/messages/direct", json={"destination": pub_key, "text": "Hi"}
)
assert response.status_code == 423
assert response.status_code == 503
assert "not connected" in response.json()["detail"].lower()
@@ -500,25 +500,25 @@ class TestMessagesEndpoint:
@pytest.mark.asyncio
async def test_send_direct_message_requires_connection(self, test_db, client):
"""Sending message when disconnected returns 423."""
"""Sending message when disconnected returns 503."""
with _patch_require_connected():
response = await client.post(
"/api/messages/direct", json={"destination": "abc123", "text": "Hello"}
)
assert response.status_code == 423
assert response.status_code == 503
assert "not connected" in response.json()["detail"].lower()
@pytest.mark.asyncio
async def test_send_channel_message_requires_connection(self, test_db, client):
"""Sending channel message when disconnected returns 423."""
"""Sending channel message when disconnected returns 503."""
with _patch_require_connected():
response = await client.post(
"/api/messages/channel",
json={"channel_key": "0123456789ABCDEF0123456789ABCDEF", "text": "Hello"},
)
assert response.status_code == 423
assert response.status_code == 503
@pytest.mark.asyncio
async def test_send_direct_message_emits_websocket_message_event(self, test_db, client):
@@ -603,8 +603,8 @@ class TestMessagesEndpoint:
assert "not found" in response.json()["detail"].lower()
@pytest.mark.asyncio
async def test_send_direct_message_duplicate_returns_422(self, test_db):
"""If MessageRepository.create returns None (duplicate), returns 422."""
async def test_send_direct_message_duplicate_returns_500(self, test_db):
"""If MessageRepository.create returns None (duplicate), returns 500."""
from app.models import SendDirectMessageRequest
from app.routers.messages import send_direct_message
@@ -636,12 +636,12 @@ class TestMessagesEndpoint:
SendDirectMessageRequest(destination=pub_key, text="Hello")
)
assert exc_info.value.status_code == 422
assert exc_info.value.status_code == 500
assert "unexpected duplicate" in exc_info.value.detail.lower()
@pytest.mark.asyncio
async def test_send_channel_message_duplicate_returns_422(self, test_db):
"""If MessageRepository.create returns None (duplicate), returns 422."""
async def test_send_channel_message_duplicate_returns_500(self, test_db):
"""If MessageRepository.create returns None (duplicate), returns 500."""
from app.models import SendChannelMessageRequest
from app.routers.messages import send_channel_message
@@ -672,16 +672,16 @@ class TestMessagesEndpoint:
SendChannelMessageRequest(channel_key=chan_key, text="Hello")
)
assert exc_info.value.status_code == 422
assert exc_info.value.status_code == 500
assert "unexpected duplicate" in exc_info.value.detail.lower()
@pytest.mark.asyncio
async def test_resend_channel_message_requires_connection(self, test_db, client):
"""Resend endpoint returns 423 when radio is disconnected."""
"""Resend endpoint returns 503 when radio is disconnected."""
with _patch_require_connected():
response = await client.post("/api/messages/channel/1/resend")
assert response.status_code == 423
assert response.status_code == 503
assert "not connected" in response.json()["detail"].lower()
@pytest.mark.asyncio
+1 -1
View File
@@ -709,7 +709,7 @@ class TestBotMessageRateLimiting:
patch(
"app.routers.messages.send_direct_message",
new_callable=AsyncMock,
side_effect=HTTPException(status_code=422, detail="Send failed"),
side_effect=HTTPException(status_code=500, detail="Send failed"),
),
):
await process_bot_response(
+88 -2
View File
@@ -317,7 +317,7 @@ class TestPathDiscovery:
mock_broadcast.assert_called_once_with("contact", updated.model_dump())
@pytest.mark.asyncio
async def test_returns_408_when_no_response_is_heard(self, test_db, client):
async def test_returns_504_when_no_response_is_heard(self, test_db, client):
await _insert_contact(KEY_A, "Alice", type=1)
mc = MagicMock()
mc.commands = MagicMock()
@@ -332,7 +332,7 @@ class TestPathDiscovery:
mock_rm.radio_operation = _noop_radio_operation(mc)
response = await client.post(f"/api/contacts/{KEY_A}/path-discovery")
assert response.status_code == 408
assert response.status_code == 504
assert "No path discovery response heard" in response.json()["detail"]
@@ -675,3 +675,89 @@ class TestRoutingOverride:
assert response.status_code == 400
assert "same width" in response.json()["detail"].lower()
class TestContactTelemetry:
"""Tests for on-demand contact telemetry endpoint."""
@pytest.mark.asyncio
async def test_telemetry_happy_path(self, test_db, client):
"""Successful telemetry request returns sensors and persists history."""
await _insert_contact(KEY_A, name="Alice")
mock_mc = MagicMock()
mock_mc.commands.add_contact = AsyncMock(return_value=_radio_result())
mock_mc.commands.req_telemetry_sync = AsyncMock(
return_value=[
{"channel": 1, "type": "voltage", "value": 3.7},
{"channel": 1, "type": "temperature", "value": 22.5},
]
)
with (
patch("app.routers.contacts.radio_manager") as mock_rm,
patch("app.websocket.broadcast_event"),
):
mock_rm.is_connected = True
mock_rm.require_connected = MagicMock()
mock_rm.radio_operation = _noop_radio_operation(mock_mc)
response = await client.post(f"/api/contacts/{KEY_A}/telemetry")
assert response.status_code == 200
data = response.json()
assert len(data["sensors"]) == 2
assert data["sensors"][0]["type_name"] == "voltage"
assert data["sensors"][0]["value"] == 3.7
assert data["fetched_at"] > 0
assert len(data["telemetry_history"]) >= 1
@pytest.mark.asyncio
async def test_telemetry_timeout_returns_504(self, test_db, client):
"""No response from contact returns 504."""
await _insert_contact(KEY_A)
mock_mc = MagicMock()
mock_mc.commands.add_contact = AsyncMock(return_value=_radio_result())
mock_mc.commands.req_telemetry_sync = AsyncMock(return_value=None)
with (
patch("app.routers.contacts.radio_manager") as mock_rm,
):
mock_rm.is_connected = True
mock_rm.require_connected = MagicMock()
mock_rm.radio_operation = _noop_radio_operation(mock_mc)
response = await client.post(f"/api/contacts/{KEY_A}/telemetry")
assert response.status_code == 504
@pytest.mark.asyncio
async def test_telemetry_history_endpoint(self, test_db, client):
"""History endpoint returns stored telemetry snapshots."""
import time
from app.repository.contact_telemetry import ContactTelemetryRepository
await _insert_contact(KEY_A)
now = int(time.time())
await ContactTelemetryRepository.record(
KEY_A, now, {"lpp_sensors": [{"channel": 1, "type_name": "voltage", "value": 3.6}]}
)
response = await client.get(f"/api/contacts/{KEY_A}/telemetry-history")
assert response.status_code == 200
data = response.json()
assert len(data) == 1
assert data[0]["data"]["lpp_sensors"][0]["value"] == 3.6
@pytest.mark.asyncio
async def test_telemetry_contact_not_found(self, test_db, client):
"""Telemetry for non-existent contact returns 404."""
with patch("app.routers.contacts.radio_manager") as mock_rm:
mock_rm.is_connected = True
mock_rm.require_connected = MagicMock()
response = await client.post(f"/api/contacts/{KEY_A}/telemetry")
assert response.status_code == 404
-128
View File
@@ -1367,134 +1367,6 @@ class TestAppriseValidation:
assert scope["raw_packets"] == "none"
assert scope["messages"] == "all"
def test_validate_apprise_config_accepts_markdown_format_bool(self):
from app.routers.fanout import _validate_apprise_config
_validate_apprise_config({"urls": "discord://123/abc", "markdown_format": False})
def test_validate_apprise_config_normalizes_markdown_format(self):
from app.routers.fanout import _validate_apprise_config
config: dict = {"urls": "discord://123/abc", "markdown_format": 0}
_validate_apprise_config(config)
assert config["markdown_format"] is False
def test_validate_apprise_config_works_without_markdown_format(self):
from app.routers.fanout import _validate_apprise_config
_validate_apprise_config({"urls": "discord://123/abc"})
class TestAppriseMarkdownFormat:
def test_format_body_markdown_true_uses_markdown_fallback(self):
from app.fanout.apprise_mod import _format_body
body = _format_body(
{"type": "PRIV", "text": "hi", "sender_name": "Alice"},
markdown=True,
)
assert "**DM:**" in body
def test_format_body_markdown_false_uses_plain_fallback(self):
from app.fanout.apprise_mod import _format_body
body = _format_body(
{"type": "PRIV", "text": "hi", "sender_name": "Alice"},
markdown=False,
)
assert "**" not in body
assert "DM:" in body
assert "Alice" in body
def test_format_body_markdown_false_channel(self):
from app.fanout.apprise_mod import _format_body
body = _format_body(
{"type": "CHAN", "text": "hi", "sender_name": "Bob", "channel_name": "#gen"},
markdown=False,
)
assert "**" not in body
assert "#gen:" in body
def test_send_sync_passes_markdown_body_format(self):
from unittest.mock import MagicMock, patch
with patch("app.fanout.apprise_mod.apprise_lib", create=True) as mock_lib:
mock_notifier = MagicMock()
mock_notifier.notify.return_value = True
mock_lib.Apprise.return_value = mock_notifier
with patch.dict("sys.modules", {"apprise": mock_lib}):
from app.fanout.apprise_mod import _send_sync
_send_sync("json://localhost", "test", preserve_identity=False, markdown=True)
call_kwargs = mock_notifier.notify.call_args
assert call_kwargs.kwargs.get("body_format") or call_kwargs[1].get("body_format")
def test_send_sync_passes_text_body_format_when_markdown_false(self):
from unittest.mock import MagicMock, patch
with patch("app.fanout.apprise_mod.apprise_lib", create=True) as mock_lib:
mock_notifier = MagicMock()
mock_notifier.notify.return_value = True
mock_lib.Apprise.return_value = mock_notifier
with patch.dict("sys.modules", {"apprise": mock_lib}):
from app.fanout.apprise_mod import _send_sync
_send_sync("json://localhost", "test", preserve_identity=False, markdown=False)
call_kwargs = mock_notifier.notify.call_args
assert call_kwargs.kwargs.get("body_format") or call_kwargs[1].get("body_format")
@pytest.mark.asyncio
async def test_on_message_reads_markdown_format_config(self):
from unittest.mock import patch as _patch
from app.fanout.apprise_mod import AppriseModule
mod = AppriseModule("test", {"urls": "json://localhost", "markdown_format": False})
with _patch("app.fanout.apprise_mod._send_sync", return_value=True) as mock_send:
await mod.on_message(
{"type": "PRIV", "text": "hello", "outgoing": False, "sender_name": "S_Borkin"}
)
mock_send.assert_called_once()
assert mock_send.call_args.kwargs.get("markdown") is False
@pytest.mark.asyncio
async def test_on_message_defaults_markdown_true(self):
from unittest.mock import patch as _patch
from app.fanout.apprise_mod import AppriseModule
mod = AppriseModule("test", {"urls": "json://localhost"})
with _patch("app.fanout.apprise_mod._send_sync", return_value=True) as mock_send:
await mod.on_message(
{"type": "PRIV", "text": "hello", "outgoing": False, "sender_name": "Alice"}
)
mock_send.assert_called_once()
assert mock_send.call_args.kwargs.get("markdown") is True
@pytest.mark.asyncio
async def test_on_message_markdown_false_uses_plain_default_format(self):
from unittest.mock import patch as _patch
from app.fanout.apprise_mod import AppriseModule
mod = AppriseModule("test", {"urls": "json://localhost", "markdown_format": False})
with _patch("app.fanout.apprise_mod._send_sync", return_value=True) as mock_send:
await mod.on_message(
{
"type": "CHAN",
"text": "hi",
"outgoing": False,
"sender_name": "Bob",
"channel_name": "#general",
}
)
body = mock_send.call_args[0][1]
assert "**" not in body
assert "#general:" in body
# ---------------------------------------------------------------------------
# Comprehensive scope/filter selection logic tests
-40
View File
@@ -1580,46 +1580,6 @@ class TestFanoutAppriseIntegration:
assert "Eve" in body_text
assert "routed msg" in body_text
@pytest.mark.asyncio
async def test_apprise_markdown_false_delivers_plain_text(
self, apprise_capture_server, integration_db
):
"""Apprise with markdown_format=False delivers without markdown formatting."""
cfg = await FanoutConfigRepository.create(
config_type="apprise",
name="Plain Apprise",
config={
"urls": f"json://127.0.0.1:{apprise_capture_server.port}",
"markdown_format": False,
},
scope={"messages": "all", "raw_packets": "none"},
enabled=True,
)
manager = FanoutManager()
try:
await manager.load_from_db()
assert cfg["id"] in manager._modules
await manager.broadcast_message(
{
"type": "PRIV",
"conversation_key": "pk1",
"text": "hello",
"sender_name": "S_Borkin",
}
)
results = await apprise_capture_server.wait_for(1)
finally:
await manager.stop_all()
assert len(results) >= 1
body_text = str(results[0])
assert "S_Borkin" in body_text
assert "hello" in body_text
assert "**" not in body_text
# ---------------------------------------------------------------------------
# Bot lifecycle tests
+1 -1
View File
@@ -2,4 +2,4 @@
# run ``run_migrations`` to completion assert ``get_version == LATEST`` and
# ``applied == LATEST - starting_version`` so only this constant needs to
# change, not every individual assertion.
LATEST_SCHEMA_VERSION = 61
LATEST_SCHEMA_VERSION = 62
+2 -2
View File
@@ -342,8 +342,8 @@ class TestConnectionLoop:
assert sleep_args[0] == _BACKOFF_MIN
assert sleep_args[1] == _BACKOFF_MIN * 2
assert sleep_args[2] == _BACKOFF_MIN * 4
# Fourth is still doubling (5*8=40), not yet at _backoff_max
assert sleep_args[3] == _BACKOFF_MIN * 8
# Fourth should be capped at _backoff_max (5*8=40 > 30)
assert sleep_args[3] == MqttPublisher._backoff_max
@pytest.mark.asyncio
async def test_waits_for_settings_when_unconfigured(self):
-2
View File
@@ -95,8 +95,6 @@ class TestGetRawPacket:
"sender": "Alice",
"channel_key": channel_key,
"contact_key": None,
"sender_timestamp": 1700000000,
"message": "Alice: hello",
}
+6 -6
View File
@@ -174,8 +174,8 @@ class TestRadioOperationYield:
class TestRequireConnected:
"""Test the require_connected() FastAPI dependency."""
def test_raises_423_when_setup_in_progress(self):
"""HTTPException 423 is raised when radio is connected but setup is still in progress."""
def test_raises_503_when_setup_in_progress(self):
"""HTTPException 503 is raised when radio is connected but setup is still in progress."""
from fastapi import HTTPException
from app.services.radio_runtime import radio_runtime
@@ -188,11 +188,11 @@ class TestRequireConnected:
with pytest.raises(HTTPException) as exc_info:
radio_runtime.require_connected()
assert exc_info.value.status_code == 423
assert exc_info.value.status_code == 503
assert "initializing" in exc_info.value.detail.lower()
def test_raises_423_when_not_connected(self):
"""HTTPException 423 is raised when radio is not connected."""
def test_raises_503_when_not_connected(self):
"""HTTPException 503 is raised when radio is not connected."""
from fastapi import HTTPException
from app.services.radio_runtime import radio_runtime
@@ -205,7 +205,7 @@ class TestRequireConnected:
with pytest.raises(HTTPException) as exc_info:
radio_runtime.require_connected()
assert exc_info.value.status_code == 423
assert exc_info.value.status_code == 503
def test_returns_meshcore_when_connected_and_setup_complete(self):
"""Returns meshcore instance when radio is connected and setup is complete."""
+11 -11
View File
@@ -131,14 +131,14 @@ class TestGetRadioConfig:
assert response.advert_location_source == "current"
@pytest.mark.asyncio
async def test_returns_423_when_self_info_missing(self):
async def test_returns_503_when_self_info_missing(self):
mc = MagicMock()
mc.self_info = None
with patch("app.routers.radio.radio_manager.require_connected", return_value=mc):
with pytest.raises(HTTPException) as exc:
await get_radio_config()
assert exc.value.status_code == 423
assert exc.value.status_code == 503
class TestUpdateRadioConfig:
@@ -278,7 +278,7 @@ class TestUpdateRadioConfig:
with pytest.raises(HTTPException) as exc:
await update_radio_config(RadioConfigUpdate(path_hash_mode=1))
assert exc.value.status_code == 422
assert exc.value.status_code == 500
assert "Failed to set path hash mode" in str(exc.value.detail)
assert radio_manager.path_hash_mode == 0
mc.commands.send_appstart.assert_not_awaited()
@@ -339,7 +339,7 @@ class TestPrivateKeyImport:
with pytest.raises(HTTPException) as exc:
await set_private_key(PrivateKeyUpdate(private_key="aa" * 64))
assert exc.value.status_code == 422
assert exc.value.status_code == 500
class TestDiscoverMesh:
@@ -699,7 +699,7 @@ class TestTracePath:
assert "not a repeater" in exc.value.detail
@pytest.mark.asyncio
async def test_returns_408_when_no_trace_response_is_heard(self):
async def test_returns_504_when_no_trace_response_is_heard(self):
mc = _mock_meshcore_with_info()
repeater = Contact(
public_key="44" * 32,
@@ -741,7 +741,7 @@ class TestTracePath:
)
)
assert exc.value.status_code == 408
assert exc.value.status_code == 504
assert "No trace response heard" in exc.value.detail
@pytest.mark.asyncio
@@ -850,7 +850,7 @@ class TestTracePath:
with pytest.raises(HTTPException) as exc:
await discover_mesh(RadioDiscoveryRequest(target="sensors"))
assert exc.value.status_code == 422
assert exc.value.status_code == 500
assert exc.value.detail == "Failed to start mesh discovery"
@pytest.mark.asyncio
@@ -887,7 +887,7 @@ class TestTracePath:
with pytest.raises(HTTPException) as exc:
await set_private_key(PrivateKeyUpdate(private_key="aa" * 64))
assert exc.value.status_code == 422
assert exc.value.status_code == 500
assert "keystore" in exc.value.detail.lower()
# Called twice: initial attempt + one retry
assert mock_export.await_count == 2
@@ -926,7 +926,7 @@ class TestAdvertise:
with pytest.raises(HTTPException) as exc:
await send_advertisement()
assert exc.value.status_code == 422
assert exc.value.status_code == 500
@pytest.mark.asyncio
async def test_defaults_to_flood_mode(self):
@@ -1059,7 +1059,7 @@ class TestRebootAndReconnect:
assert result["connected"] is True
@pytest.mark.asyncio
async def test_reconnect_raises_423_on_failure(self):
async def test_reconnect_raises_503_on_failure(self):
mock_rm = MagicMock()
mock_rm.is_connected = False
mock_rm.is_reconnecting = False
@@ -1070,7 +1070,7 @@ class TestRebootAndReconnect:
with pytest.raises(HTTPException) as exc:
await reconnect_radio()
assert exc.value.status_code == 423
assert exc.value.status_code == 503
@pytest.mark.asyncio
async def test_disconnect_pauses_connection_attempts_and_broadcasts_health(self):
+2 -2
View File
@@ -57,12 +57,12 @@ def test_require_connected_preserves_http_semantics():
)
with pytest.raises(HTTPException, match="Radio is initializing") as exc:
runtime.require_connected()
assert exc.value.status_code == 423
assert exc.value.status_code == 503
runtime = RadioRuntime(_Manager(meshcore=None, is_connected=False, is_setup_in_progress=False))
with pytest.raises(HTTPException, match="Radio not connected") as exc:
runtime.require_connected()
assert exc.value.status_code == 423
assert exc.value.status_code == 503
def test_require_connected_returns_fresh_meshcore_after_connectivity_check():
+13 -13
View File
@@ -302,7 +302,7 @@ class TestRepeaterCommandRoute:
with pytest.raises(HTTPException) as exc:
await send_repeater_command(KEY_A, CommandRequest(command="ver"))
assert exc.value.status_code == 422
assert exc.value.status_code == 500
mc.start_auto_message_fetching.assert_awaited_once()
@pytest.mark.asyncio
@@ -502,7 +502,7 @@ class TestTraceRoute:
with pytest.raises(HTTPException) as exc:
await request_trace(KEY_A)
assert exc.value.status_code == 422
assert exc.value.status_code == 500
mc.commands.send_trace.assert_awaited_once_with(
path=KEY_A[:8],
tag=1234,
@@ -510,7 +510,7 @@ class TestTraceRoute:
)
@pytest.mark.asyncio
async def test_wait_timeout_returns_408(self, test_db):
async def test_wait_timeout_returns_504(self, test_db):
mc = _mock_mc()
await _insert_contact(KEY_A, name="Client", contact_type=1)
mc.commands.send_trace = AsyncMock(return_value=_radio_result(EventType.OK))
@@ -524,7 +524,7 @@ class TestTraceRoute:
with pytest.raises(HTTPException) as exc:
await request_trace(KEY_A)
assert exc.value.status_code == 408
assert exc.value.status_code == 504
mc.commands.send_trace.assert_awaited_once_with(
path=KEY_A[:8],
tag=1234,
@@ -745,7 +745,7 @@ class TestRepeaterStatus:
assert response.recv_errors == 42
@pytest.mark.asyncio
async def test_408_on_timeout(self, test_db):
async def test_504_on_timeout(self, test_db):
mc = _mock_mc()
await _insert_contact(KEY_A, name="Repeater", contact_type=2)
mc.commands.req_status_sync = AsyncMock(return_value=None)
@@ -756,7 +756,7 @@ class TestRepeaterStatus:
):
with pytest.raises(HTTPException) as exc:
await repeater_status(KEY_A)
assert exc.value.status_code == 408
assert exc.value.status_code == 504
@pytest.mark.asyncio
async def test_400_not_repeater(self, test_db):
@@ -819,7 +819,7 @@ class TestRepeaterLppTelemetry:
assert response.sensors == []
@pytest.mark.asyncio
async def test_408_on_timeout(self, test_db):
async def test_504_on_timeout(self, test_db):
mc = _mock_mc()
await _insert_contact(KEY_A, name="Repeater", contact_type=2)
mc.commands.req_telemetry_sync = AsyncMock(return_value=None)
@@ -830,7 +830,7 @@ class TestRepeaterLppTelemetry:
):
with pytest.raises(HTTPException) as exc:
await repeater_lpp_telemetry(KEY_A)
assert exc.value.status_code == 408
assert exc.value.status_code == 504
@pytest.mark.asyncio
async def test_400_not_repeater(self, test_db):
@@ -1234,7 +1234,7 @@ class TestBatchCliFetch:
with pytest.raises(HTTPException) as exc:
await _batch_cli_fetch(contact, "test_op", [("ver", "firmware_version")])
assert exc.value.status_code == 422
assert exc.value.status_code == 500
assert "Failed to add contact to radio" in exc.value.detail
@pytest.mark.asyncio
@@ -1307,7 +1307,7 @@ class TestRepeaterAddContactError:
with pytest.raises(HTTPException) as exc:
await repeater_status(KEY_A)
assert exc.value.status_code == 422
assert exc.value.status_code == 500
assert "Failed to add contact to radio" in exc.value.detail
@pytest.mark.asyncio
@@ -1325,7 +1325,7 @@ class TestRepeaterAddContactError:
with pytest.raises(HTTPException) as exc:
await repeater_lpp_telemetry(KEY_A)
assert exc.value.status_code == 422
assert exc.value.status_code == 500
assert "Failed to add contact to radio" in exc.value.detail
@pytest.mark.asyncio
@@ -1343,7 +1343,7 @@ class TestRepeaterAddContactError:
with pytest.raises(HTTPException) as exc:
await repeater_neighbors(KEY_A)
assert exc.value.status_code == 422
assert exc.value.status_code == 500
assert "Failed to add contact to radio" in exc.value.detail
@pytest.mark.asyncio
@@ -1361,5 +1361,5 @@ class TestRepeaterAddContactError:
with pytest.raises(HTTPException) as exc:
await repeater_acl(KEY_A)
assert exc.value.status_code == 422
assert exc.value.status_code == 500
assert "Failed to add contact to radio" in exc.value.detail
+10 -10
View File
@@ -646,7 +646,7 @@ class TestOutgoingChannelBroadcast:
request = SendChannelMessageRequest(channel_key=chan_key, text="hello")
await send_channel_message(request)
assert exc_info.value.status_code == 422
assert exc_info.value.status_code == 500
assert "regional override" in exc_info.value.detail.lower()
mc.commands.set_channel.assert_not_awaited()
mc.commands.send_chan_msg.assert_not_awaited()
@@ -790,7 +790,7 @@ class TestOutgoingChannelBroadcast:
SendChannelMessageRequest(channel_key=chan_key, text="this will fail")
)
assert exc_info.value.status_code == 422
assert exc_info.value.status_code == 500
assert radio_manager.get_cached_channel_slot(chan_key) is None
@@ -969,7 +969,7 @@ class TestResendChannelMessage:
assert sent_timestamp == now + 1
@pytest.mark.asyncio
async def test_resend_no_radio_response_returns_408_and_creates_no_new_row(self, test_db):
async def test_resend_no_radio_response_returns_504_and_creates_no_new_row(self, test_db):
"""When resend returns None, report unknown outcome and create no new message row."""
mc = _make_mc(name="MyNode")
chan_key = "c1" * 16
@@ -995,7 +995,7 @@ class TestResendChannelMessage:
):
await resend_channel_message(msg_id, new_timestamp=True)
assert exc_info.value.status_code == 408
assert exc_info.value.status_code == 504
assert exc_info.value.detail == NO_RADIO_RESPONSE_AFTER_SEND_DETAIL
messages = await MessageRepository.get_all(
@@ -1317,7 +1317,7 @@ class TestPathHashModeOverride:
SendChannelMessageRequest(channel_key=chan_key, text="hello")
)
assert exc_info.value.status_code == 422
assert exc_info.value.status_code == 500
assert "path hash mode" in exc_info.value.detail.lower()
mc.commands.send_chan_msg.assert_not_awaited()
@@ -1567,7 +1567,7 @@ class TestRadioExceptionMidSend:
assert len(messages) == 0
@pytest.mark.asyncio
async def test_dm_send_no_radio_response_returns_408_without_storing_message(self, test_db):
async def test_dm_send_no_radio_response_returns_504_without_storing_message(self, test_db):
"""When mc.commands.send_msg() returns None, report unknown outcome and store nothing."""
mc = _make_mc()
pub_key = "ac" * 32
@@ -1584,7 +1584,7 @@ class TestRadioExceptionMidSend:
SendDirectMessageRequest(destination=pub_key, text="Did this send?")
)
assert exc_info.value.status_code == 408
assert exc_info.value.status_code == 504
assert exc_info.value.detail == NO_RADIO_RESPONSE_AFTER_SEND_DETAIL
messages = await MessageRepository.get_all(
@@ -1593,7 +1593,7 @@ class TestRadioExceptionMidSend:
assert len(messages) == 0
@pytest.mark.asyncio
async def test_channel_send_no_radio_response_returns_408_without_storing_message(
async def test_channel_send_no_radio_response_returns_504_without_storing_message(
self, test_db
):
"""When mc.commands.send_chan_msg() returns None, report unknown outcome and store nothing."""
@@ -1612,7 +1612,7 @@ class TestRadioExceptionMidSend:
SendChannelMessageRequest(channel_key=chan_key, text="Did this send?")
)
assert exc_info.value.status_code == 408
assert exc_info.value.status_code == 504
assert exc_info.value.detail == NO_RADIO_RESPONSE_AFTER_SEND_DETAIL
messages = await MessageRepository.get_all(
@@ -1733,7 +1733,7 @@ class TestRadioExceptionMidSend:
SendChannelMessageRequest(channel_key=chan_key_b, text="Never sent")
)
assert exc_info.value.status_code == 422
assert exc_info.value.status_code == 500
assert radio_manager.get_cached_channel_slot(chan_key_a) is None
assert radio_manager.get_cached_channel_slot(chan_key_b) is None
mc.commands.send_chan_msg.assert_not_called()
Generated
+1 -1
View File
@@ -1533,7 +1533,7 @@ wheels = [
[[package]]
name = "remoteterm-meshcore"
version = "3.13.0"
version = "3.12.3"
source = { virtual = "." }
dependencies = [
{ name = "aiomqtt" },