simplex gateway produces link for user to connect to service

This commit is contained in:
gabby committed 2026-10-01 22:27:50 +00:00
1 parent 8751e7c08e
commit 25ade160df
5 files changed
+151 -2

No files matched your search

+5 -1
View File
@@ -816,7 +816,11 @@ CLI, unit tests (24) + box integration tests (2).
`semif-gateway.service` agent process, so the gateway runs across `semif-gateway.service` agent process, so the gateway runs across
logout/reboot. The gateway is its own process — the REPL and the gateway are logout/reboot. The gateway is its own process — the REPL and the gateway are
independent front ends onto the same on-disk logs/registry (do not run two independent front ends onto the same on-disk logs/registry (do not run two
scheduler processes over one skill store concurrently). scheduler processes over one skill store concurrently). **On connect the
gateway prints the bot's own SimpleX contact link once** (show-or-create via
the daemon it already owns, from the CLI, `_gateway_address_callback`) so a
human can reach it without running `scripts/simplex-address.py` — the operator
front end prints it; the command adapter itself gains no address surface.
- **Bot address / v7 relay gotcha.** The daemon must NOT run with `--headless` - **Bot address / v7 relay gotcha.** The daemon must NOT run with `--headless`
or `--relay`: in SimpleX Chat v7 `--headless` means "chat relay" (requires or `--relay`: in SimpleX Chat v7 `--headless` means "chat relay" (requires
`--relay`) and yields a *relay* address, not a user contact address. Run bot `--relay`) and yields a *relay* address, not a user contact address. Run bot
+46
View File
@@ -404,6 +404,49 @@ def scripted(scheduler: Scheduler, path: str) -> int:
return _fatal_exit(scheduler) or 0 return _fatal_exit(scheduler) or 0
def _gateway_address_callback(adapter):
"""Return an `on_connected` coroutine that prints the bot's contact link once.
A human cannot reach the gateway without the bot's SimpleX contact address,
and the only thing that surfaced it before was `scripts/simplex-address.py`
run once at provision time. Print it on connect, from the operator front end
(the CLI), through the daemon the gateway already owns — show-or-create, no
second connection, no new transport surface. The lookup is best-effort: a
failure is reported once (to stderr) and retried on the next connect, and it
never takes the socket down.
"""
printed = False
warned = False
async def _announce() -> None:
nonlocal printed, warned
if printed:
return
try:
link = await adapter.daemon.address()
except Exception as exc:
if not warned:
warned = True
print(
f"gateway simplex: could not read contact link: {exc}",
file=sys.stderr,
)
return
short = (link or {}).get("short_link") or ""
full = (link or {}).get("full_link") or ""
if not (short or full):
if not warned:
warned = True
print("gateway simplex: no contact link available", file=sys.stderr)
return
printed = True
print(f"gateway simplex contact link: {short}")
if full:
print(full)
return _announce
def run_gateway( def run_gateway(
scheduler: Scheduler, scheduler: Scheduler,
config: dict, config: dict,
@@ -420,6 +463,9 @@ def run_gateway(
from .gateway.simplex import SimplexAdapter from .gateway.simplex import SimplexAdapter
adapter = SimplexAdapter(cfg, trace=scheduler.trace) adapter = SimplexAdapter(cfg, trace=scheduler.trace)
# Print the bot's own contact link once, on connect, so the operator can
# actually reach the gateway (see _gateway_address_callback).
adapter.daemon.on_connected = _gateway_address_callback(adapter)
else: else:
print(f"unknown gateway platform {platform!r}") print(f"unknown gateway platform {platform!r}")
return 1 return 1
+7 -1
View File
@@ -308,12 +308,18 @@ class SimplexDaemon:
self._ws = ws self._ws = ws
backoff = self.reconnect_initial backoff = self.reconnect_initial
self._event("gateway_connected", url=self.ws_url) self._event("gateway_connected", url=self.ws_url)
await self._notify_connected()
sender = asyncio.create_task(self._outbound_loop(ws)) sender = asyncio.create_task(self._outbound_loop(ws))
# The on_connected hook may issue correlated commands (e.g.
# the startup contact-address lookup), so run it
# CONCURRENTLY with the read loop: awaiting it inline would
# block the loop that resolves its own response and the
# request would time out.
hook = asyncio.create_task(self._notify_connected())
try: try:
async for raw in ws: async for raw in ws:
await self._consume(raw) await self._consume(raw)
finally: finally:
hook.cancel()
sender.cancel() sender.cancel()
except Exception as exc: # reconnect on any transport failure except Exception as exc: # reconnect on any transport failure
self._event("gateway_error", message=str(exc)[:300]) self._event("gateway_error", message=str(exc)[:300])
+50
View File
@@ -11,6 +11,7 @@ integration concern, not a dev-box unit test.
import asyncio import asyncio
import json import json
from semif_agent.cli import _gateway_address_callback
from semif_agent.decisions import Request from semif_agent.decisions import Request
from semif_agent.engine import EngineConfig, SemIfEngine from semif_agent.engine import EngineConfig, SemIfEngine
from semif_agent.gateway.base import InboundMessage from semif_agent.gateway.base import InboundMessage
@@ -66,6 +67,55 @@ def test_check_requirements_needs_url():
assert "ws_url" in hint assert "ws_url" in hint
# ---- startup contact-link announcement ----
class _FakeDaemon:
def __init__(self, result):
self._result = result
self.calls = 0
async def address(self, timeout=20.0):
self.calls += 1
if isinstance(self._result, Exception):
raise self._result
return self._result
class _FakeAdapter:
def __init__(self, daemon):
self.daemon = daemon
def test_gateway_address_callback_prints_link_once(capsys):
daemon = _FakeDaemon(
{"short_link": "simplex:/abc", "full_link": "simplex://full"}
)
announce = _gateway_address_callback(_FakeAdapter(daemon))
asyncio.run(announce())
asyncio.run(announce()) # a reconnect must not reprint
out = capsys.readouterr()
assert "simplex:/abc" in out.out
assert "simplex://full" in out.out
assert daemon.calls == 1
def test_gateway_address_callback_failure_is_not_fatal(capsys):
daemon = _FakeDaemon(RuntimeError("not connected"))
announce = _gateway_address_callback(_FakeAdapter(daemon))
asyncio.run(announce()) # must not raise
asyncio.run(announce()) # retried on the next connect
captured = capsys.readouterr()
assert "could not read contact link" in captured.err
assert daemon.calls == 2
def test_gateway_address_callback_no_link_warns(capsys):
daemon = _FakeDaemon({"short_link": "", "full_link": ""})
announce = _gateway_address_callback(_FakeAdapter(daemon))
asyncio.run(announce())
assert "no contact link available" in capsys.readouterr().err
# ---- adapter: send command ---- # ---- adapter: send command ----
def test_send_command_is_structured_not_shortcut(): def test_send_command_is_structured_not_shortcut():
+43
View File
@@ -404,6 +404,49 @@ def test_on_connected_hook_runs_and_failures_are_swallowed():
asyncio.run(SimplexDaemon("ws://x")._notify_connected()) asyncio.run(SimplexDaemon("ws://x")._notify_connected())
def test_on_connected_hook_may_roundtrip_while_reading():
"""The hook runs concurrently with the read loop, not blocking it.
Regression: `on_connected` was awaited inline before the read loop started,
so a hook that issued a correlated command (the gateway's startup contact
link) could never receive its own response and always timed out.
"""
daemon = SimplexDaemon("ws://x", user_id=1)
seen = []
async def hook():
link = await daemon.address(timeout=2)
seen.append(link)
daemon.on_connected = hook
daemon._loop = asyncio.new_event_loop()
async def scenario():
daemon._loop = asyncio.get_running_loop()
ws = FakeWS(
daemon,
[
{
"type": "userContactLink",
"contactLink": {
"connLinkContact": {"connShortLink": "simplex:/a", "connFullLink": ""}
},
}
],
)
daemon._ws = ws
hook_task = asyncio.create_task(daemon._notify_connected())
# The read loop is what resolves the correlated response.
for message in list(ws.sent):
pass
await hook_task
return ws
ws = asyncio.run(scenario())
assert seen == [{"short_link": "simplex:/a", "full_link": "", "created": False}]
assert [m["cmd"] for m in ws.sent] == ["/_show_address 1"]
# ---- chat previews / history (true unread) ---- # ---- chat previews / history (true unread) ----
def chat_item(item_id=10, text="hello", status="rcvNew", direction="directRcv", shape="api"): def chat_item(item_id=10, text="hello", status="rcvNew", direction="directRcv", shape="api"):