A silent direct message or admin login can retry by flood, past a dead route
The companion keeps one route for each contact and never forgets a dead one, so each retry on it was lost with no error. Now ^R on a direct message that went along the learned route asks: Cancel, On route, or By flood. By flood forgets the route (nothing is transmitted), flushes the contact cache, and sends the one retry. A message that already went by flood keeps the plain ^R. The admin login offers Try by flood the same way after a silence from a node that has a route, one time for each flow. Nothing floods unless the user chooses it. Refs: #34 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ec64076d44
commit
73ae08b365
6 files changed
+614
-16
No files matched your search
@@ -698,6 +698,12 @@ class ChatMessage:
|
||||
messages. This includes our own posts, which a room never sends back. It also
|
||||
includes the command-line replies of a room, which have its conversation key
|
||||
but are not posts (refer to :attr:`is_post`).
|
||||
flood: How the device sent our last transmission of an outbound direct message:
|
||||
``True`` to the whole mesh, ``False`` along the route that it learned. ``None``
|
||||
when the device did not tell, and for each message that is not our own direct
|
||||
message. MeshTerm does not store this value. A message that is loaded from the
|
||||
history has ``None``. The chat uses it to decide whether ^R offers a retry by
|
||||
flood (a route that gets no ack can be stale, and a flood goes around it).
|
||||
"""
|
||||
|
||||
text: str
|
||||
@@ -715,6 +721,7 @@ class ChatMessage:
|
||||
row_id: int | None = None
|
||||
scope: str | None = None
|
||||
author: str | None = None
|
||||
flood: bool | None = field(default=None, compare=False)
|
||||
|
||||
@property
|
||||
def is_post(self) -> bool:
|
||||
|
||||
@@ -511,7 +511,9 @@ class ChatService:
|
||||
return is_direct_messageable(contact.node_type)
|
||||
return False
|
||||
|
||||
async def _deliver_direct(self, contact: Contact, text: str) -> tuple[bool, list[str]]:
|
||||
async def _deliver_direct(
|
||||
self, contact: Contact, text: str
|
||||
) -> tuple[bool, list[str], bool | None]:
|
||||
"""Transmit a direct message, and try again softly until it is acknowledged.
|
||||
|
||||
One logical send makes one first transmission, plus up to
|
||||
@@ -531,8 +533,10 @@ class ChatService:
|
||||
text: The message body.
|
||||
|
||||
Returns:
|
||||
Whether an attempt was acknowledged in its wait, and the ack code of each
|
||||
attempt. A late ack can still carry any of these codes (the device keeps them).
|
||||
Whether an attempt was acknowledged in its wait, the ack code of each attempt,
|
||||
and how the device sent the last attempt (``True`` flood, ``False`` along its
|
||||
learned route, ``None`` if it did not tell). A late ack can still carry any of
|
||||
the codes (the device keeps them).
|
||||
|
||||
Raises:
|
||||
Exception: A hard send failure (the companion rejects the send) goes to the
|
||||
@@ -542,12 +546,14 @@ class ChatService:
|
||||
device = await self._ctx.device()
|
||||
attempts = max(0, self._ctx.preferences.direct_message_soft_retries) + 1
|
||||
codes: list[str] = []
|
||||
flood: bool | None = None
|
||||
for attempt in range(1, attempts + 1):
|
||||
delivery: Delivery = await device.send_direct_message(contact, text)
|
||||
flood = delivery.flood
|
||||
if delivery.code:
|
||||
codes.append(delivery.code)
|
||||
if delivery.acked:
|
||||
return True, codes
|
||||
return True, codes, flood
|
||||
if attempt < attempts:
|
||||
self._ctx.log.debug(
|
||||
"chat: DM to %s unacked on try %d/%d; soft-retrying",
|
||||
@@ -555,7 +561,7 @@ class ChatService:
|
||||
attempt,
|
||||
attempts,
|
||||
)
|
||||
return False, codes
|
||||
return False, codes, flood
|
||||
|
||||
async def send_direct(
|
||||
self, contact: Contact, text: str, *, on_late_ack: LateAck | None = None
|
||||
@@ -579,7 +585,7 @@ class ChatService:
|
||||
The stored outbound :class:`ChatMessage`. Its ``acked`` shows whether a
|
||||
delivery acknowledgement arrived in the wait, until now.
|
||||
"""
|
||||
acked, codes = await self._deliver_direct(contact, text)
|
||||
acked, codes, flood = await self._deliver_direct(contact, text)
|
||||
chat = ChatMessage(
|
||||
text=text,
|
||||
outbound=True,
|
||||
@@ -588,13 +594,16 @@ class ChatService:
|
||||
peer_name=contact.name,
|
||||
acked=acked,
|
||||
created_at=utcnow(),
|
||||
flood=flood,
|
||||
)
|
||||
chat.row_id = self._ctx.repo.record_chat_message(chat, run_id=self._run_id)
|
||||
if not acked:
|
||||
self._await_ack(chat, codes, on_late_ack)
|
||||
return chat
|
||||
|
||||
async def resend_direct(self, contact: Contact, message: ChatMessage) -> ChatMessage:
|
||||
async def resend_direct(
|
||||
self, contact: Contact, message: ChatMessage, *, flood: bool = False
|
||||
) -> ChatMessage:
|
||||
"""Try again to deliver an unacknowledged direct message, and change it in place.
|
||||
|
||||
MeshTerm uses this method to try again a message that was transmitted but never
|
||||
@@ -605,15 +614,32 @@ class ChatService:
|
||||
up to ``preferences.direct_message_soft_retries`` soft retries of its own (refer to
|
||||
:meth:`_deliver_direct`).
|
||||
|
||||
The companion keeps one route for each contact, and it replaces the route only when
|
||||
a path return arrives. A route that is no longer valid loses each message with no
|
||||
error (GitHub issue 34). With ``flood`` set, the method first forgets the route
|
||||
(a local action, nothing is transmitted). Thus the retry floods, and the companion
|
||||
learns a new route from the answer. The user must choose this, and the method
|
||||
never does it by itself.
|
||||
|
||||
Args:
|
||||
contact: The recipient.
|
||||
message: The :class:`ChatMessage` that was sent before, to transmit again. The
|
||||
method changes it in place with the new delivery state.
|
||||
flood: Forget the route to the contact before the retry, so that the retry
|
||||
floods the whole mesh.
|
||||
|
||||
Returns:
|
||||
The same ``message``, with :attr:`~ChatMessage.acked` updated.
|
||||
"""
|
||||
acked, codes = await self._deliver_direct(contact, message.text)
|
||||
if flood:
|
||||
device = await self._ctx.device()
|
||||
await device.reset_route(contact)
|
||||
# The route in the contact cache is not valid now. The next read gets it again.
|
||||
devstate = getattr(self._ctx, "devstate", None)
|
||||
if devstate is not None:
|
||||
devstate.invalidate_contacts()
|
||||
acked, codes, how = await self._deliver_direct(contact, message.text)
|
||||
message.flood = how
|
||||
if message.acked:
|
||||
return message # a late ack for an earlier attempt settled it during this send
|
||||
message.acked = acked
|
||||
|
||||
@@ -23,6 +23,13 @@ password, and a node whose password changed gets the new one in one step.
|
||||
|
||||
The CLI cannot ask. Its error for the same silence says how to give the new password
|
||||
(:func:`no_reply_error`).
|
||||
|
||||
A third cause of the same silence is a stale route (GitHub issue 34). The companion keeps
|
||||
one route for each node and replaces it only when a path return arrives. Nothing makes it
|
||||
forget a dead route, so each login on that route is lost with no error. When the node has
|
||||
a route, the dialog of the silence also offers ``Try by flood``. The button forgets the
|
||||
route (nothing is transmitted), and then the one next login floods. The user chooses this
|
||||
step, and the flow never floods by itself.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -40,6 +47,9 @@ if TYPE_CHECKING:
|
||||
#: The title of each dialog of the login.
|
||||
TITLE = "Admin login"
|
||||
|
||||
#: The value of the ``Try by flood`` button of :func:`offer_no_reply`.
|
||||
RETRY_FLOOD = "flood"
|
||||
|
||||
|
||||
async def ask_password(ctx: AppContext, node: Contact, *, why: str) -> str | None:
|
||||
"""Ask for the admin password of ``node`` in a floating prompt.
|
||||
@@ -155,6 +165,70 @@ async def offer_new_password(ctx: AppContext, node: Contact) -> bool:
|
||||
)
|
||||
|
||||
|
||||
async def forget_route(ctx: AppContext, device: Device, node: Contact) -> None:
|
||||
"""Forget the route that the radio learned to ``node``, so that its next login floods.
|
||||
|
||||
This is a local action on the companion. Nothing goes on the air. The route in the
|
||||
contact cache is not valid after it, so the function also makes the cache read the
|
||||
contacts again. The login that follows is the one transmission.
|
||||
|
||||
Args:
|
||||
ctx: The shared application context.
|
||||
device: The connected device.
|
||||
node: The node whose route to forget.
|
||||
"""
|
||||
await device.reset_route(node)
|
||||
devstate = getattr(ctx, "devstate", None)
|
||||
if devstate is not None:
|
||||
devstate.invalidate_contacts()
|
||||
|
||||
|
||||
async def offer_no_reply(ctx: AppContext, node: Contact, *, saved: bool) -> object:
|
||||
"""Ask what to do after a login got no reply from a node that has a learned route.
|
||||
|
||||
The silence has three causes that MeshTerm cannot tell apart: the node is down, its
|
||||
password changed (or the typed password is wrong), or the route is stale. A flood costs
|
||||
the least to test, because it needs no typing. Thus ``Try by flood`` is the default. It
|
||||
is the one next login, and the user chooses it. The dialog has a maximum of three
|
||||
buttons, so the row fits the dialog of the handhelds.
|
||||
|
||||
Args:
|
||||
ctx: The shared application context (the interactive menu must be running).
|
||||
node: The node that did not answer. It must have a route (``route_hops`` is not
|
||||
``None``).
|
||||
saved: The password came from the admin store. Then the dialog also offers a new
|
||||
password.
|
||||
|
||||
Returns:
|
||||
:data:`RETRY_FLOOD` for ``Try by flood``, ``True`` for ``New password…``, and a
|
||||
false value to stop.
|
||||
"""
|
||||
stale = (
|
||||
"The login went along a route that your radio learned, and a route goes stale "
|
||||
"when the mesh changes. A flood goes around it."
|
||||
)
|
||||
if saved:
|
||||
text = (
|
||||
f"No reply from {node.name} — it may be out of reach, asleep, or busy. Or its "
|
||||
"admin password changed: a node does not answer a wrong password. The saved "
|
||||
f"password is kept until a new one works. {stale}"
|
||||
)
|
||||
buttons: list[tuple[str, object]] = [
|
||||
("Cancel", None),
|
||||
("New password…", True),
|
||||
("Try by flood", RETRY_FLOOD),
|
||||
]
|
||||
default = 2
|
||||
else:
|
||||
text = (
|
||||
f"No reply from {node.name} — it may be out of reach, or the password is "
|
||||
f"wrong: a node does not answer a wrong password. {stale}"
|
||||
)
|
||||
buttons = [("Cancel", None), ("Try by flood", RETRY_FLOOD)]
|
||||
default = 1
|
||||
return await ctx.ui.dialog(Text(text, style="warn"), buttons, title=TITLE, default=default)
|
||||
|
||||
|
||||
async def log_in(
|
||||
ctx: AppContext,
|
||||
device: Device,
|
||||
@@ -175,6 +249,11 @@ async def log_in(
|
||||
3. After a refusal, or after a silence for a typed password, show why, and stop.
|
||||
4. After a silence for a stored password, offer a new password
|
||||
(:func:`offer_new_password`). If the user accepts, go back to step 1.
|
||||
5. After a silence from a node that has a learned route, the dialog of step 3 or step 4
|
||||
also offers ``Try by flood`` (:func:`offer_no_reply`). If the user accepts, the flow
|
||||
forgets the route (:func:`forget_route`) and logs in again with the same password.
|
||||
The flow offers this step one time only. A flood that also gets no reply ends in
|
||||
step 3 or step 4 as before.
|
||||
|
||||
Args:
|
||||
ctx: The shared application context (the interactive menu must be running).
|
||||
@@ -194,6 +273,7 @@ async def log_in(
|
||||
session = ctx.ui.session
|
||||
password = ctx.admin_store.get(node)
|
||||
saved = password is not None
|
||||
flooded = False
|
||||
while True:
|
||||
if password is None:
|
||||
password = await ask_password(ctx, node, why=why)
|
||||
@@ -211,6 +291,16 @@ async def log_in(
|
||||
Text(refused_text(node, saved=saved, again=again), style="err"), title=TITLE
|
||||
)
|
||||
return False
|
||||
if node.route_hops is not None and not flooded:
|
||||
choice = await offer_no_reply(ctx, node, saved=saved)
|
||||
if choice == RETRY_FLOOD:
|
||||
await forget_route(ctx, device, node)
|
||||
flooded = True
|
||||
continue
|
||||
if not choice:
|
||||
return False
|
||||
password, saved = None, False
|
||||
continue
|
||||
if not saved:
|
||||
await session.message_dialog(
|
||||
Text(no_reply_text(node, again=again), style="warn"), title=TITLE
|
||||
|
||||
+114
-8
@@ -279,6 +279,7 @@ class ChatScreen(Screen):
|
||||
pages: ContactPages | None = None,
|
||||
self_name: str | None = None,
|
||||
self_key: str | None = None,
|
||||
resend_flood: Callable[[ChatMessage], Awaitable[ChatMessage]] | None = None,
|
||||
) -> None:
|
||||
"""Build the chat screen.
|
||||
|
||||
@@ -319,6 +320,9 @@ class ChatScreen(Screen):
|
||||
self_name: The name of our node (refer to :func:`our_node`). Our messages and
|
||||
the mentions of our name show it (:func:`~meshterm.ui.widgets.self_chip`).
|
||||
self_key: Our public key, which gives the hue of that chip.
|
||||
resend_flood: Like ``resend``, but it first forgets the route that the device
|
||||
learned to the contact, so that the retry floods (direct chats only).
|
||||
With ``None``, ^R always retries on the route, as it did before.
|
||||
"""
|
||||
super().__init__()
|
||||
self._self_name = self_name
|
||||
@@ -346,6 +350,8 @@ class ChatScreen(Screen):
|
||||
self._messages = list(messages)
|
||||
self._send = send
|
||||
self._resend = resend
|
||||
self._resend_flood = resend_flood if not conversation.is_channel else None
|
||||
self._route_contact = contact
|
||||
self._resend_unscoped = resend_unscoped if conversation.is_channel else None
|
||||
self._paths = paths
|
||||
self._locator = locator
|
||||
@@ -367,6 +373,7 @@ class ChatScreen(Screen):
|
||||
self._codes_open = False # one share screen of links at a time
|
||||
self._paste_open = False # one paste-confirm dialog at a time
|
||||
self._resend_open = False # one resend-unscoped confirm at a time
|
||||
self._retry_open = False # one route-or-flood choice at a time
|
||||
# The selection: the index of the highlighted message (or None when the compose
|
||||
# line has the focus), and the body line where it rendered, so that the frame keeps
|
||||
# it visible.
|
||||
@@ -1607,17 +1614,90 @@ class ChatScreen(Screen):
|
||||
None,
|
||||
)
|
||||
|
||||
def _went_by_route(self, message: ChatMessage) -> bool:
|
||||
"""Whether the last transmission of ``message`` went along a learned route.
|
||||
|
||||
The device tells how it sent the message (:attr:`ChatMessage.flood`). A message
|
||||
that is loaded from the history has no such fact. For that message, the answer
|
||||
comes from the contact: a contact with a route is sent to along that route. Thus
|
||||
the answer is ``False`` when no flood retry is connected.
|
||||
"""
|
||||
if self._resend_flood is None:
|
||||
return False
|
||||
if message.flood is not None:
|
||||
return not message.flood
|
||||
contact = self._route_contact
|
||||
return contact is not None and contact.route_hops is not None
|
||||
|
||||
def _retry(self) -> None:
|
||||
"""Try again to deliver the most recent unacknowledged direct message (Ctrl-R)."""
|
||||
"""Try again to deliver the most recent unacknowledged direct message (Ctrl-R).
|
||||
|
||||
A message that went along the learned route gets a choice first
|
||||
(:meth:`_begin_retry_choice`). The route is the most common cause of a message
|
||||
that is lost with no error, and a retry on the same route fails in the same way.
|
||||
A message that already went by flood is sent again at once, with no question.
|
||||
"""
|
||||
target = self._retry_target()
|
||||
if target is None:
|
||||
if target is None or self._retry_open:
|
||||
return
|
||||
if self._went_by_route(target):
|
||||
self._begin_retry_choice(target)
|
||||
return
|
||||
self._start_retry(target, flood=False)
|
||||
|
||||
def _start_retry(self, target: ChatMessage, *, flood: bool) -> None:
|
||||
"""Send ``target`` again, one time, on the route or (with ``flood``) by flood."""
|
||||
self._sending = True
|
||||
target.acked = None # back to the spinner while the retry is in flight
|
||||
self._status = "retrying…"
|
||||
self._status = "retrying by flood…" if flood else "retrying…"
|
||||
self._stick = True
|
||||
self._session.invalidate()
|
||||
self._spawn(self._resend_message(target))
|
||||
self._spawn(self._resend_message(target, flood=flood))
|
||||
|
||||
def _begin_retry_choice(self, target: ChatMessage) -> None:
|
||||
"""Ask whether to retry on the learned route or by flood, then send one time (^R).
|
||||
|
||||
The companion keeps one route for each contact and never forgets a route that is
|
||||
no longer valid. Thus a message on a dead route gets no ack, and each retry on that
|
||||
route fails in the same way (GitHub issue 34). A flood goes around the route, and
|
||||
the companion learns a new one from the answer. A flood reaches each repeater in
|
||||
range, so it is the choice of the user, never a default of the program. The
|
||||
buttons follow the dialog standard: the safe way out on the left, and the
|
||||
committing choice on the right, which is also the default. Either choice is the
|
||||
one transmission.
|
||||
"""
|
||||
self._retry_open = True
|
||||
preview = target.text if len(target.text) <= 32 else target.text[:31] + "…"
|
||||
|
||||
async def run() -> None:
|
||||
try:
|
||||
choice = await self._session.button_dialog(
|
||||
Text(
|
||||
f"“{preview}” got no ack on the route that your radio learned. A "
|
||||
"route goes stale when the mesh changes. Send it again on the "
|
||||
"route, or by flood?"
|
||||
),
|
||||
[("Cancel", None), ("On route", "route"), ("By flood", "flood")],
|
||||
title="Retry",
|
||||
default=2,
|
||||
footer_hint="←→ choose · Enter select · Esc cancel",
|
||||
)
|
||||
finally:
|
||||
self._retry_open = False
|
||||
# A late ack can settle the message while the dialog is up. Then nothing remains
|
||||
# to send.
|
||||
usable = (
|
||||
choice in ("route", "flood")
|
||||
and not self._sending
|
||||
and self._resend is not None
|
||||
and target.acked is False
|
||||
)
|
||||
if not usable or (choice == "flood" and self._resend_flood is None):
|
||||
self._session.invalidate()
|
||||
return
|
||||
self._start_retry(target, flood=choice == "flood")
|
||||
|
||||
self._spawn(run())
|
||||
|
||||
def _begin_resend_unscoped(self) -> None:
|
||||
"""Confirm, then send a scoped channel message again, unscoped (^R).
|
||||
@@ -1676,16 +1756,31 @@ class ChatScreen(Screen):
|
||||
|
||||
self._spawn(run())
|
||||
|
||||
async def _resend_message(self, message: ChatMessage) -> None:
|
||||
"""Run a retry to its end, and refresh the delivery state of the message in place."""
|
||||
async def _resend_message(self, message: ChatMessage, *, flood: bool = False) -> None:
|
||||
"""Run a retry to its end, and refresh the delivery state of the message in place.
|
||||
|
||||
With ``flood``, the retry first forgets the route of the contact (the
|
||||
``resend_flood`` callable). If the retry still gets no ack, the status line says
|
||||
that ^R can try again. It also names the flood choice when the last send went
|
||||
along the route.
|
||||
"""
|
||||
assert self._resend is not None
|
||||
try:
|
||||
await self._spin_while(self._resend(message))
|
||||
if flood:
|
||||
assert self._resend_flood is not None
|
||||
await self._spin_while(self._resend_flood(message))
|
||||
else:
|
||||
await self._spin_while(self._resend(message))
|
||||
except Exception as exc: # noqa: BLE001 - show the error inline, keep the chat open
|
||||
message.acked = False
|
||||
self._status = f"retry failed: {exc}"
|
||||
else:
|
||||
self._status = "" if message.acked else "still no ack — ^R to retry"
|
||||
if message.acked:
|
||||
self._status = ""
|
||||
elif self._went_by_route(message):
|
||||
self._status = "still no ack — ^R to retry on the route or by flood"
|
||||
else:
|
||||
self._status = "still no ack — ^R to retry"
|
||||
finally:
|
||||
self._sending = False
|
||||
self._stick = True
|
||||
@@ -1801,6 +1896,16 @@ async def open_chat(ctx: AppContext, conversation: Conversation) -> int:
|
||||
ctx, lambda: ctx.chat.resend_direct(conversation.contact, message)
|
||||
)
|
||||
|
||||
resend_flood: Callable[[ChatMessage], Awaitable[ChatMessage]] | None = None
|
||||
if not conversation.is_channel:
|
||||
|
||||
async def resend_flood(message: ChatMessage) -> ChatMessage:
|
||||
assert conversation.contact is not None
|
||||
return await _with_restore(
|
||||
ctx,
|
||||
lambda: ctx.chat.resend_direct(conversation.contact, message, flood=True),
|
||||
)
|
||||
|
||||
from .map_screen import Locator
|
||||
from .node_detail_screen import ContactPages
|
||||
|
||||
@@ -1821,6 +1926,7 @@ async def open_chat(ctx: AppContext, conversation: Conversation) -> int:
|
||||
pages=await ContactPages.gather(ctx, self_key=self_key or ""),
|
||||
self_name=self_name,
|
||||
self_key=self_key,
|
||||
resend_flood=resend_flood,
|
||||
)
|
||||
ctx.chat.set_active(conversation.key)
|
||||
|
||||
|
||||
@@ -770,6 +770,163 @@ async def test_a_typed_password_with_no_reply_asks_nothing_more(ctx) -> None: #
|
||||
assert ctx.admin_store.get(_NODE) is None
|
||||
|
||||
|
||||
class _RoutedNode:
|
||||
"""A device whose node is silent while its route is stale, as the companion's is.
|
||||
|
||||
``reset_route`` forgets the stale route, and then the node answers its password.
|
||||
``log`` lists the calls in order, and ``routes`` counts the ``reset_route`` calls.
|
||||
"""
|
||||
|
||||
def __init__(self, password: str, *, stale: bool = True) -> None:
|
||||
self.password = password
|
||||
self.stale = stale
|
||||
self.log: list[str] = []
|
||||
|
||||
async def admin_login(self, node: Contact, password: str) -> LoginResult: # noqa: ARG002
|
||||
self.log.append(f"login:{password}")
|
||||
await asyncio.sleep(0)
|
||||
if self.stale or password != self.password:
|
||||
return LoginResult.NO_REPLY
|
||||
return LoginResult.ACCEPTED
|
||||
|
||||
async def reset_route(self, node: Contact) -> None: # noqa: ARG002
|
||||
self.log.append("reset")
|
||||
self.stale = False
|
||||
|
||||
|
||||
_ROUTED = Contact(
|
||||
name="Yagi-Repeater", public_key="a1b2c3d4" * 8, key_prefix="a1b2c3d4", route_hops=("3d",)
|
||||
)
|
||||
|
||||
|
||||
def _watch_cache(ctx) -> list[int]: # noqa: ANN001
|
||||
"""Replace the contact cache of the context with one that counts its invalidations."""
|
||||
from types import SimpleNamespace
|
||||
|
||||
flushed: list[int] = []
|
||||
ctx._devstate = SimpleNamespace(invalidate_contacts=lambda: flushed.append(1))
|
||||
return flushed
|
||||
|
||||
|
||||
async def test_a_silent_stored_password_on_a_route_offers_a_flood_and_it_works(ctx) -> None: # noqa: ANN001
|
||||
"""GitHub issue 34. A stale route is silent. Try by flood forgets it, then logs in once."""
|
||||
from meshterm.ui.admin_login import log_in
|
||||
from meshterm.ui.surface import TuiUi
|
||||
from meshterm.ui.tui.prompt import ButtonDialog
|
||||
from meshterm.ui.tui.session import TuiSession
|
||||
|
||||
ctx.ui = TuiUi(TuiSession())
|
||||
flushed = _watch_cache(ctx)
|
||||
ctx.admin_store.remember(_ROUTED, "secret")
|
||||
device = _RoutedNode("secret")
|
||||
task = asyncio.ensure_future(log_in(ctx, device, _ROUTED, why="Log in.", again="try again"))
|
||||
try:
|
||||
offer = await _top(ctx, ButtonDialog)
|
||||
assert offer is not None, "a silence on a route offers a choice"
|
||||
assert [label for label, _ in offer._buttons] == [
|
||||
"Cancel",
|
||||
"New password…",
|
||||
"Try by flood",
|
||||
]
|
||||
assert offer._index == 2, "Try by flood is the default on the right"
|
||||
assert "route" in offer._prompt.plain and "password changed" in offer._prompt.plain
|
||||
assert device.log == ["login:secret"], "nothing floods before the user chooses"
|
||||
offer.resolve("flood")
|
||||
ok = await task
|
||||
finally:
|
||||
if not task.done():
|
||||
task.cancel()
|
||||
|
||||
assert ok is True
|
||||
assert device.log == ["login:secret", "reset", "login:secret"]
|
||||
assert flushed == [1]
|
||||
|
||||
|
||||
async def test_cancel_on_the_flood_offer_sends_nothing_more(ctx) -> None: # noqa: ANN001
|
||||
"""Cancel leaves the route as it was and sends no second login."""
|
||||
from meshterm.ui.admin_login import log_in
|
||||
from meshterm.ui.surface import TuiUi
|
||||
from meshterm.ui.tui.prompt import ButtonDialog
|
||||
from meshterm.ui.tui.session import TuiSession
|
||||
|
||||
ctx.ui = TuiUi(TuiSession())
|
||||
flushed = _watch_cache(ctx)
|
||||
ctx.admin_store.remember(_ROUTED, "secret")
|
||||
device = _RoutedNode("secret")
|
||||
task = asyncio.ensure_future(log_in(ctx, device, _ROUTED, why="Log in.", again="try again"))
|
||||
try:
|
||||
(await _top(ctx, ButtonDialog)).resolve(None)
|
||||
ok = await task
|
||||
finally:
|
||||
if not task.done():
|
||||
task.cancel()
|
||||
|
||||
assert ok is False
|
||||
assert device.log == ["login:secret"] and flushed == []
|
||||
assert ctx.admin_store.get(_ROUTED) == "secret"
|
||||
|
||||
|
||||
async def test_a_typed_password_on_a_route_offers_only_cancel_and_flood(ctx) -> None: # noqa: ANN001
|
||||
"""With no stored password, a new password is not a choice. The flood is."""
|
||||
from meshterm.ui.admin_login import log_in
|
||||
from meshterm.ui.surface import TuiUi
|
||||
from meshterm.ui.tui.prompt import ButtonDialog, TextScreen
|
||||
from meshterm.ui.tui.session import TuiSession
|
||||
|
||||
ctx.ui = TuiUi(TuiSession())
|
||||
_watch_cache(ctx)
|
||||
device = _RoutedNode("typed")
|
||||
task = asyncio.ensure_future(log_in(ctx, device, _ROUTED, why="Log in.", again="try again"))
|
||||
try:
|
||||
(await _top(ctx, TextScreen)).resolve("typed")
|
||||
offer = await _top(ctx, ButtonDialog)
|
||||
assert [label for label, _ in offer._buttons] == ["Cancel", "Try by flood"]
|
||||
assert offer._index == 1
|
||||
offer.resolve("flood")
|
||||
ok = await task
|
||||
finally:
|
||||
if not task.done():
|
||||
task.cancel()
|
||||
|
||||
assert ok is True
|
||||
assert device.log == ["login:typed", "reset", "login:typed"]
|
||||
assert ctx.admin_store.get(_ROUTED) == "typed"
|
||||
|
||||
|
||||
async def test_a_flood_that_also_gets_no_reply_is_not_offered_again(ctx) -> None: # noqa: ANN001
|
||||
"""One flood for each flow. The next silence gets the dialog of before (no flood button)."""
|
||||
from meshterm.ui.admin_login import log_in
|
||||
from meshterm.ui.surface import TuiUi
|
||||
from meshterm.ui.tui.prompt import ButtonDialog
|
||||
from meshterm.ui.tui.session import TuiSession
|
||||
|
||||
ctx.ui = TuiUi(TuiSession())
|
||||
_watch_cache(ctx)
|
||||
ctx.admin_store.remember(_ROUTED, "old")
|
||||
# The node is down, or its password changed. A flood changes nothing.
|
||||
device = _RoutedNode("other")
|
||||
task = asyncio.ensure_future(log_in(ctx, device, _ROUTED, why="Log in.", again="try again"))
|
||||
try:
|
||||
(await _top(ctx, ButtonDialog)).resolve("flood")
|
||||
again = await _step_until(
|
||||
lambda: (
|
||||
ctx.ui.session.top
|
||||
if isinstance(ctx.ui.session.top, ButtonDialog) and len(device.log) == 3
|
||||
else None
|
||||
)
|
||||
)
|
||||
assert again is not None
|
||||
assert [label for label, _ in again._buttons] == ["Cancel", "New password…"]
|
||||
again.resolve(None)
|
||||
ok = await task
|
||||
finally:
|
||||
if not task.done():
|
||||
task.cancel()
|
||||
|
||||
assert ok is False
|
||||
assert device.log == ["login:old", "reset", "login:old"], "exactly one flood"
|
||||
|
||||
|
||||
def test_a_refusal_message_starts_its_sentences_with_a_capital() -> None:
|
||||
"""A typed password has nothing to clear. The message once read "(wrong password?). try"."""
|
||||
from meshterm.ui.admin_login import refused_text
|
||||
|
||||
@@ -1110,6 +1110,166 @@ async def test_chat_screen_retry_resends_failed_message() -> None:
|
||||
assert "✓" in "\n".join(screen.render_body(60))
|
||||
|
||||
|
||||
class _ChoiceSession(_PasteSession):
|
||||
"""A stub session. Its button dialogs give a scripted answer, such as ``"flood"``."""
|
||||
|
||||
|
||||
def _dm_screen(
|
||||
session: _StubSession,
|
||||
messages: list[ChatMessage],
|
||||
calls: list[str],
|
||||
*,
|
||||
route: tuple[str, ...] | None = ("3d",),
|
||||
with_flood: bool = True,
|
||||
) -> ChatScreen:
|
||||
"""A direct chat whose two resend hooks write down which one ran.
|
||||
|
||||
Each hook stands in for the real retry: it marks the message as delivered.
|
||||
"""
|
||||
|
||||
async def resend(message: ChatMessage) -> ChatMessage:
|
||||
calls.append("route")
|
||||
message.acked = True
|
||||
return message
|
||||
|
||||
async def resend_flood(message: ChatMessage) -> ChatMessage:
|
||||
calls.append("flood")
|
||||
message.acked = True
|
||||
return message
|
||||
|
||||
conv = Conversation(
|
||||
label="Alice",
|
||||
is_channel=False,
|
||||
contact=Contact(
|
||||
name="Alice", public_key="d4" + "0" * 62, key_prefix="d4e5f6a7", route_hops=route
|
||||
),
|
||||
)
|
||||
return ChatScreen(
|
||||
conv,
|
||||
messages,
|
||||
send=None,
|
||||
names={},
|
||||
session=session,
|
||||
resend=resend,
|
||||
resend_flood=resend_flood if with_flood else None,
|
||||
)
|
||||
|
||||
|
||||
async def _drain_retry(screen: ChatScreen) -> None:
|
||||
"""Let the scheduled retry choice and the retry task run to their end."""
|
||||
for _ in range(100):
|
||||
await asyncio.sleep(0)
|
||||
assert not screen._retry_open and not screen._sending
|
||||
|
||||
|
||||
async def test_ctrl_r_on_a_message_that_went_by_route_asks_route_or_flood() -> None:
|
||||
"""The dialog has Cancel, On route, and By flood. The flood is the default on the right."""
|
||||
session = _ChoiceSession(answer=None)
|
||||
sent = ChatMessage(text="hello", outbound=True, peer="d4e5f6a7", acked=False, flood=False)
|
||||
calls: list[str] = []
|
||||
screen = _dm_screen(session, [sent], calls)
|
||||
|
||||
screen.handle("retry")
|
||||
await _drain_retry(screen)
|
||||
|
||||
assert len(session.dialogs) == 1
|
||||
prompt, buttons, kwargs = session.dialogs[0]
|
||||
assert [label for label, _ in buttons] == ["Cancel", "On route", "By flood"]
|
||||
assert kwargs["default"] == 2 and kwargs["title"] == "Retry"
|
||||
assert kwargs["footer_hint"] == "←→ choose · Enter select · Esc cancel"
|
||||
assert "hello" in prompt.plain and "flood" in prompt.plain
|
||||
assert calls == [] and sent.acked is False, "Cancel transmits nothing"
|
||||
|
||||
|
||||
async def test_ctrl_r_by_flood_forgets_the_route_through_the_flood_hook_only() -> None:
|
||||
"""Choosing By flood calls the flood retry one time. The retry on the route stays unused."""
|
||||
session = _ChoiceSession(answer="flood")
|
||||
sent = ChatMessage(text="hello", outbound=True, peer="d4e5f6a7", acked=False, flood=False)
|
||||
calls: list[str] = []
|
||||
screen = _dm_screen(session, [sent], calls)
|
||||
|
||||
screen.handle("retry")
|
||||
await _drain_retry(screen)
|
||||
|
||||
assert calls == ["flood"]
|
||||
assert sent.acked is True
|
||||
|
||||
|
||||
async def test_ctrl_r_on_route_keeps_the_old_retry() -> None:
|
||||
"""Choosing On route is the plain retry of before: one send, no route change."""
|
||||
session = _ChoiceSession(answer="route")
|
||||
sent = ChatMessage(text="hello", outbound=True, peer="d4e5f6a7", acked=False, flood=False)
|
||||
calls: list[str] = []
|
||||
screen = _dm_screen(session, [sent], calls)
|
||||
|
||||
screen.handle("retry")
|
||||
await _drain_retry(screen)
|
||||
|
||||
assert calls == ["route"]
|
||||
|
||||
|
||||
async def test_ctrl_r_on_a_message_that_went_by_flood_retries_with_no_question() -> None:
|
||||
"""A flood cannot be stale. The plain ^R stays, and it never floods by itself."""
|
||||
session = _ChoiceSession(answer="flood")
|
||||
sent = ChatMessage(text="hello", outbound=True, peer="d4e5f6a7", acked=False, flood=True)
|
||||
calls: list[str] = []
|
||||
screen = _dm_screen(session, [sent], calls)
|
||||
|
||||
screen.handle("retry")
|
||||
await _drain_retry(screen)
|
||||
|
||||
assert session.dialogs == []
|
||||
assert calls == ["route"] # the plain retry hook: it sends as the device decides
|
||||
|
||||
|
||||
async def test_ctrl_r_on_a_stored_message_follows_the_route_of_the_contact() -> None:
|
||||
"""A message from the history has no flood fact. The route of the contact decides."""
|
||||
stored = ChatMessage(text="old", outbound=True, peer="d4e5f6a7", acked=False)
|
||||
with_route, without_route = _ChoiceSession(answer=None), _ChoiceSession(answer=None)
|
||||
|
||||
routed = _dm_screen(with_route, [stored], [], route=("3d",))
|
||||
routed.handle("retry")
|
||||
await _drain_retry(routed)
|
||||
assert len(with_route.dialogs) == 1
|
||||
|
||||
calls: list[str] = []
|
||||
flooded = _dm_screen(without_route, [stored], calls, route=None)
|
||||
flooded.handle("retry")
|
||||
await _drain_retry(flooded)
|
||||
assert without_route.dialogs == [] and calls == ["route"]
|
||||
|
||||
|
||||
async def test_ctrl_r_without_a_flood_hook_is_the_plain_retry() -> None:
|
||||
"""A chat with no flood retry connected never asks."""
|
||||
session = _ChoiceSession(answer="flood")
|
||||
sent = ChatMessage(text="hello", outbound=True, peer="d4e5f6a7", acked=False, flood=False)
|
||||
calls: list[str] = []
|
||||
screen = _dm_screen(session, [sent], calls, with_flood=False)
|
||||
|
||||
screen.handle("retry")
|
||||
await _drain_retry(screen)
|
||||
|
||||
assert session.dialogs == [] and calls == ["route"]
|
||||
|
||||
|
||||
async def test_the_status_line_names_the_flood_choice_after_a_failed_route_retry() -> None:
|
||||
"""A retry on the route that still gets no ack says that ^R can also flood."""
|
||||
session = _ChoiceSession(answer="route")
|
||||
sent = ChatMessage(text="hello", outbound=True, peer="d4e5f6a7", acked=False, flood=False)
|
||||
screen = _dm_screen(session, [sent], [])
|
||||
|
||||
async def failing(message: ChatMessage) -> ChatMessage:
|
||||
message.acked = False
|
||||
message.flood = False
|
||||
return message
|
||||
|
||||
screen._resend = failing
|
||||
screen.handle("retry")
|
||||
await _drain_retry(screen)
|
||||
|
||||
assert screen._status == "still no ack — ^R to retry on the route or by flood"
|
||||
|
||||
|
||||
async def test_chat_fkey_lane_dims_retry_and_the_nav_slots() -> None:
|
||||
"""The lane offers Retry only for a message to retry, and navigation only with a transcript."""
|
||||
|
||||
@@ -1840,6 +2000,58 @@ async def test_service_resend_updates_ack_in_place(repo: Repository) -> None:
|
||||
await device.disconnect()
|
||||
|
||||
|
||||
async def test_service_resend_by_flood_forgets_the_route_first(repo: Repository) -> None:
|
||||
"""A retry by flood forgets the route (a local action), flushes the cache, and sends once."""
|
||||
from types import SimpleNamespace
|
||||
|
||||
device = MockDevice()
|
||||
ctx = _StubContext(device, repo)
|
||||
invalidated: list[int] = []
|
||||
ctx.devstate = SimpleNamespace(invalidate_contacts=lambda: invalidated.append(1))
|
||||
chat = ChatService(ctx)
|
||||
await chat.start()
|
||||
try:
|
||||
alice = next(c for c in await device.get_contacts() if c.name == "Alice")
|
||||
assert alice.route_hops is not None
|
||||
sent = await chat.send_direct(alice, "hey")
|
||||
assert sent.flood is False, "the first send went along the learned route"
|
||||
|
||||
before = device._sent_codes
|
||||
await chat.resend_direct(alice, sent, flood=True)
|
||||
|
||||
held = next(c for c in await device.get_contacts() if c.name == "Alice")
|
||||
assert held.route_hops is None, "the route is forgotten"
|
||||
assert sent.flood is True, "the retry flooded"
|
||||
assert invalidated == [1]
|
||||
assert device._sent_codes == before + 1, "one transmission"
|
||||
finally:
|
||||
await chat.stop()
|
||||
await device.disconnect()
|
||||
|
||||
|
||||
async def test_service_resend_on_the_route_leaves_the_route_alone(repo: Repository) -> None:
|
||||
"""The plain retry never touches the route and never flushes the cache."""
|
||||
from types import SimpleNamespace
|
||||
|
||||
device = MockDevice()
|
||||
ctx = _StubContext(device, repo)
|
||||
invalidated: list[int] = []
|
||||
ctx.devstate = SimpleNamespace(invalidate_contacts=lambda: invalidated.append(1))
|
||||
chat = ChatService(ctx)
|
||||
await chat.start()
|
||||
try:
|
||||
alice = next(c for c in await device.get_contacts() if c.name == "Alice")
|
||||
sent = await chat.send_direct(alice, "hey")
|
||||
await chat.resend_direct(alice, sent)
|
||||
|
||||
held = next(c for c in await device.get_contacts() if c.name == "Alice")
|
||||
assert held.route_hops == alice.route_hops and sent.flood is False
|
||||
assert invalidated == []
|
||||
finally:
|
||||
await chat.stop()
|
||||
await device.disconnect()
|
||||
|
||||
|
||||
class _ScriptedDevice:
|
||||
"""A device stub. The acks of its direct messages follow a fixed script.
|
||||
|
||||
|
||||
Reference in new issue
Block a user