Skip to content

The agent that grows with you

fix(photon): setup only says "complete" once the number can route; bound the opt-in wait

Tekniumd47a49d46cb4
diff --git a/plugins/platforms/photon/auth.py b/plugins/platforms/photon/auth.py
index 2f82c05a684..06f5d84a63c 100644
--- a/plugins/platforms/photon/auth.py
+++ b/plugins/platforms/photon/auth.py
@@ -625,10 +625,13 @@ def find_routable_user(users: list[dict[str, Any]], phone_number: str) -> Option
def wait_for_opted_in_user(
project_id: str, project_secret: str, phone_number: str, *, timeout_s: float = 300.0,
interval_s: float = 5.0, on_waiting: Optional[Callable[[int], None]] = None,
- sleep_fn: Callable[[float], None] = time.sleep) -> Optional[dict[str, Any]]:
+ sleep_fn: Callable[[float], None] = time.sleep,
+ clock: Callable[[], float] = time.monotonic) -> Optional[dict[str, Any]]:
"""Poll until ``phone_number``'s row is opted in; the opted-in row, or None at the bound.
- A failed list call is a missed poll (the wait rides out the operator's manual step); the
- attempt cap keeps instant-``sleep_fn`` tests deterministic."""
+ A failed list call is a missed poll (the wait rides out the operator's manual step). Two
+ bounds: the attempt cap, and a wall-clock deadline so slow list calls (30 s HTTP timeout
+ each) cannot stretch the promised wait far past ``timeout_s``."""
+ deadline = clock() + timeout_s
max_attempts = max(1, int(timeout_s / interval_s))
for attempt in range(1, max_attempts + 1):
try:
@@ -639,8 +642,9 @@ def wait_for_opted_in_user(
logger.debug("photon: opt-in poll failed (attempt %d): %s", attempt, exc)
if on_waiting is not None:
on_waiting(attempt)
- if attempt < max_attempts:
- sleep_fn(interval_s)
+ if attempt == max_attempts or clock() + interval_s > deadline:
+ break
+ sleep_fn(interval_s)
return None
diff --git a/plugins/platforms/photon/cli.py b/plugins/platforms/photon/cli.py
index 910d088bab1..7296f25629f 100644
--- a/plugins/platforms/photon/cli.py
+++ b/plugins/platforms/photon/cli.py
@@ -161,6 +161,7 @@ def _cmd_setup(args: argparse.Namespace) -> int:
# 4. Register the operator's phone number as a Spectrum user (idempotent).
phone = args.phone or _prompt(color("[4/5] Your iMessage phone number (E.164, e.g. +15551234567): ", Colors.CYAN))
agent_number = registered_phone = registered_user_id = None
+ routing_live = True
if not phone:
print(" Skipped user registration (no phone given). Re-run with --phone later.")
else:
@@ -186,7 +187,9 @@ def _cmd_setup(args: argparse.Namespace) -> int:
if photon_auth.user_opted_in(user):
print(" ✓ number is opted in — routing is live")
else:
- agent_number = _wait_for_opt_in(dashboard_id, secret, phone, agent_number)
+ opted = _wait_for_opt_in(dashboard_id, secret, phone, agent_number)
+ routing_live = opted is not None
+ agent_number = photon_auth.user_assigned_line(opted) or agent_number
# Otherwise the gateway denies the operator's own inbound and has no cron home space.
_autoconfigure_access(phone)
# 5. Surface the agent's iMessage number.
@@ -227,13 +230,20 @@ def _cmd_setup(args: argparse.Namespace) -> int:
print(" ✓ photon platform enabled in config.yaml")
except Exception as e:
print(f" (could not enable Photon in config: {e})", file=sys.stderr)
+ if not routing_live: # saved, but not "complete": the gateway cannot reach this number yet
+ print(f"\n⚠ Photon setup saved, but iMessage routing is NOT live: text {agent_number or 'your assigned line'} "
+ f"once from {phone}.\n Check with `hermes photon status`; start the gateway once it shows opted in.")
+ return 0
print("\n✓ Photon setup complete.\n Start the gateway: hermes gateway start")
return 0
-def _wait_for_opt_in(dashboard_id: str, secret: str, phone: str, agent_number: Optional[str]) -> Optional[str]:
- """Print the opt-in step and, on a TTY, wait for it to land. Returns the agent number
- (the assignment can materialize with the opt-in)."""
+_OPT_IN_WAIT_S = 300
+
+
+def _wait_for_opt_in(dashboard_id: str, secret: str, phone: str, agent_number: Optional[str]) -> Optional[dict]:
+ """Print the opt-in step and, on a TTY, wait (bounded) for it to land. Returns the
+ opted-in user row, or None when skipped, timed out or interrupted."""
line_hint = agent_number or "the line Photon assigns to your number"
print("\n" + color(" One manual step: opt in by texting your agent", Colors.CYAN, Colors.BOLD))
print(" Your number only enters iMessage routing after it has messaged the line\n"
@@ -241,24 +251,26 @@ def _wait_for_opt_in(dashboard_id: str, secret: str, phone: str, agent_number: O
f" 2. Text {line_hint} — one message of any content is enough.")
if not sys.stdin.isatty(): # scripted setup / CI: nobody can answer the poll
print(" Non-interactive run — skipping the opt-in wait. Verify later with `hermes photon status`.")
- return agent_number
- print(" Setup waits here (up to 5 minutes) and continues once the opt-in lands.\n"
+ return None
+ print(f" Setup waits here (up to {_OPT_IN_WAIT_S // 60} minutes) and continues once the opt-in lands.\n"
" (Ctrl-C to skip — re-running setup resumes where it left off.)")
def _on_waiting(attempt: int) -> None:
if attempt % 6 == 0:
print(" ... still waiting for your message to land")
try:
- opted = photon_auth.wait_for_opted_in_user(dashboard_id, secret, phone, on_waiting=_on_waiting)
+ opted = photon_auth.wait_for_opted_in_user(
+ dashboard_id, secret, phone, timeout_s=_OPT_IN_WAIT_S, on_waiting=_on_waiting)
+ why = f"No opt-in seen within {_OPT_IN_WAIT_S // 60} minutes."
except KeyboardInterrupt:
- opted = None
+ opted, why = None, "Wait skipped (Ctrl-C)."
print()
if opted is None:
- print(f" ⚠ {phone} is not opted in yet. Send one message from {phone} to {line_hint}, "
- "then re-run `hermes photon setup` — it resumes where it left off.")
- return agent_number
+ print(f" ⚠ {why}\n {phone} is not opted in yet: text {line_hint} once from it, then re-run\n"
+ " `hermes photon setup` (it resumes where it left off).")
+ return None
print(" ✓ opt-in landed — routing is live")
- return photon_auth.user_assigned_line(opted) or agent_number
+ return opted
def _autoconfigure_access(phone: str) -> None:
diff --git a/tests/plugins/platforms/photon/test_auth.py b/tests/plugins/platforms/photon/test_auth.py
index 249d36c759e..acc64e1a82d 100644
--- a/tests/plugins/platforms/photon/test_auth.py
+++ b/tests/plugins/platforms/photon/test_auth.py
@@ -348,6 +348,23 @@ def test_wait_for_opted_in_user_polls_until_flag_lands(
) is None
+def test_wait_for_opted_in_user_wall_clock_bound(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Slow list calls must not stretch the promised wait past timeout_s (attempt cap is 12)."""
+ now = {"t": 0.0, "calls": 0}
+
+ def slow_get(url: str, **kwargs: Any) -> _FakeResponse:
+ now["calls"] += 1
+ now["t"] += 31.0 # each call burns most of its 30 s HTTP timeout
+ return _users_body({"id": "u1", "phoneNumber": "+15551234567", "meta": {}})
+
+ monkeypatch.setattr(photon_auth.httpx, "get", slow_get)
+ assert photon_auth.wait_for_opted_in_user(
+ "proj", "secret", "+15551234567", timeout_s=60, interval_s=5,
+ sleep_fn=lambda s: now.__setitem__("t", now["t"] + s), clock=lambda: now["t"],
+ ) is None
+ assert now["calls"] == 2 and now["t"] <= 60 + 31
+
+
def test_register_user_if_absent_reuses_opted_in_duplicate(
monkeypatch: pytest.MonkeyPatch,
) -> None:
diff --git a/tests/plugins/platforms/photon/test_setup_access.py b/tests/plugins/platforms/photon/test_setup_access.py
index 5ac25b259bf..9b87994e9e7 100644
--- a/tests/plugins/platforms/photon/test_setup_access.py
+++ b/tests/plugins/platforms/photon/test_setup_access.py
@@ -147,3 +147,29 @@ def test_setup_regenerates_when_existing_secret_invalid(
out = capsys.readouterr().out
assert "new secret saved" in out
assert "restart it so the sidecar" in out
+
+
+def test_setup_without_opt_in_does_not_report_complete(
+ monkeypatch: pytest.MonkeyPatch, capsys,
+) -> None:
+ """A number that never texted its assigned line cannot route: setup must not end on
+ "complete" (non-TTY run, so the opt-in wait is skipped rather than blocking)."""
+ monkeypatch.setattr(cli.photon_auth, "load_photon_token", lambda: "token")
+ monkeypatch.setattr(cli.photon_auth, "check_photon_token_valid", lambda token: True)
+ monkeypatch.setattr(cli.photon_auth, "load_dashboard_project_id", lambda: "dashboard")
+ monkeypatch.setattr(cli.photon_auth, "load_project_credentials", lambda: ("dashboard", "s"))
+ monkeypatch.setattr(cli.photon_auth, "list_users", lambda pid, secret: [])
+ monkeypatch.setattr(cli.photon_auth, "store_project_credentials", lambda **kwargs: None)
+ monkeypatch.setattr(cli.photon_auth, "register_user_if_absent", lambda *a, **k: (
+ {"id": "u1", "phoneNumber": "+15551234567", "assignedPhoneNumber": "+16282679185", "meta": {}}, True))
+ monkeypatch.setattr(cli.photon_auth, "store_user_numbers", lambda **kwargs: None)
+ monkeypatch.setattr(cli.sys.stdin, "isatty", lambda: False, raising=False)
+
+ rc = cli._cmd_setup(argparse.Namespace(
+ project_name=None, phone="+15551234567", first_name=None, last_name=None,
+ email=None, no_browser=True, skip_sidecar_install=True))
+
+ out = capsys.readouterr().out
+ assert rc == 0
+ assert "setup complete" not in out
+ assert "routing is NOT live" in out and "+16282679185" in out