feat(billing): /credits command — balance + portal top-up handoff (#44776)
* feat(billing): /usage → portal top-up browser handoff
Add the terminal side of the billing slice (phase 2a): start a top-up by
throwing the user to the portal billing page with the top-up modal open. The
terminal does not confirm, poll, or track payment — checkout completes in the
browser and the next /usage shows the new balance.
- nous_account.py: parse organisation.slug/name from /api/oauth/account into
NousPortalAccountInfo; add nous_portal_topup_url() building the org-pinned
{base}/orgs/{slug}/billing?topup=open with a null-slug fallback to the legacy
{base}/billing?topup=open (never /orgs/None/...).
- portal_cli.py: 'hermes portal topup' — fresh account fetch, identity line
(Topping up as <email> / org <name>), browser open with printed-URL fallback,
no-wait closing copy. No polling/confirmation (deferred to 2b).
- account_usage.py: the shared /usage credits block now links the org-pinned
top-up URL (auto-opens the modal) + points to the command.
Depends on NAS #409 (organisation.slug/name + ?topup=open). Do not merge until
that is live on the target env; until then /api/oauth/account returns
organisation: { id } only and the URL falls back to legacy.
* feat(billing): /credits command for balance + top-up handoff
Replace the standalone `hermes portal topup` subcommand with an in-session
/credits slash command — a focused money surface (balance in, top-up out) that
works in the CLI, TUI, and every messaging platform from one registry entry.
- commands.py: register /credits (Info category). Slack is at its 50-slash cap,
so /credits is routed via /hermes credits on Slack only (new
_SLACK_VIA_HERMES_ONLY set) to avoid clamping a canonical command off the
native list and breaking Telegram parity; native everywhere else.
- account_usage.py: build_credits_view() — one portal fetch → balance lines +
identity line + org-pinned top-up URL + depleted flag, consumed by all
surfaces. Reuses the same snapshot/URL builder as /usage so numbers match.
- cli.py: _show_credits() — balance block + identity line + 3-button panel
(Open top-up / Copy link / Cancel) via the existing prompt_toolkit modal.
ASK, never auto-launch; headless falls back to printing the URL.
- gateway/slash_commands.py: _handle_credits_command() — renders the block +
tappable top-up URL + no-wait copy; works on button and plain-text platforms.
- /usage credits line now points to /credits.
- Retire `hermes portal topup` (portal_cli.py back to baseline); the engine
(slug/name parse + nous_portal_topup_url) stays as the shared core.
No polling, no payment confirmation (billing phase 2a). Depends on NAS #409.
* fix(credits): /credits works in the TUI slash-worker (non-interactive)
In the TUI, /credits runs in the slash-worker subprocess where there is no
live prompt_toolkit app and stdin is the JSON-RPC pipe. _show_credits called
the 3-button modal unconditionally, which fell back to reading stdin →
exception → slash.exec rejected → the command produced no output (only the
pre-existing 'Credit access paused' banner showed).
- _show_credits: when self._app is None (TUI worker / piped / non-interactive),
render the text variant — balance block + tappable top-up URL + no-wait line,
same affordance as the messaging surfaces — and skip the modal entirely. The
3-button panel still renders in the interactive CLI.
- Depleted banner copy: 'run /usage for balance' → 'run /credits to top up'
now that /credits is the dedicated money surface (+ tests).
- Regression tests: _show_credits with self._app=None renders text and never
invokes the modal; logged-out path.
* feat(tui): credits.view RPC for the /credits tappable top-up button
Add a credits.view JSON-RPC method returning the structured CreditsView
(logged_in, balance_lines, identity_line, topup_url, depleted) so the TUI can
render a clickable <Link> top-up button instead of plain text. Account-
independent (portal fetch gated on a logged-in Nous account), fail-open to
{logged_in: false} on any hiccup. Mirrors session.usage's credits-block pattern.
Frontend (TUI-local /credits command + Ink component) lands separately.
* feat(tui): /credits command with keyboard-driven top-up confirm
TUI-local /credits: fetches the structured balance via the credits.view RPC,
prints the balance + identity + top-up URL, then arms the EXISTING confirm
overlay (Enter = open top-up in browser via openExternalUrl, Esc = cancel).
Reuses ConfirmReq — no new overlay component/state/input handler. Headless
(openExternalUrl returns false) falls back to printing the URL.
- gatewayTypes.ts: CreditsViewResponse.
- commands/credits.ts: the command (mirrors /status's rpc+guarded pattern).
- registry.ts: register creditsCommands.
- test: balance+overlay armed, headless fallback, no-url, logged-out (4 cases).
Matches the CLI /credits 'Enter to open' affordance. Phase 2a: no polling.
This commit is contained in:
@@ -464,12 +464,12 @@ class TestNoticeCopy:
|
||||
assert "$12.34" in grant_notice.text
|
||||
assert "top-up left" in grant_notice.text
|
||||
|
||||
def test_depleted_mentions_usage_command(self):
|
||||
def test_depleted_mentions_credits_command(self):
|
||||
latch = fresh_latch()
|
||||
s = CreditsState(paid_access=False)
|
||||
to_show, _ = evaluate_credits_notices(s, latch)
|
||||
depleted_notice = next(n for n in to_show if n.key == "credits.depleted")
|
||||
assert "/usage" in depleted_notice.text
|
||||
assert "/credits" in depleted_notice.text
|
||||
|
||||
|
||||
# ── Scenario 8: severity order in a single call ──────────────────────────────
|
||||
|
||||
@@ -0,0 +1,260 @@
|
||||
"""Tests for the /credits command — shared view core + gateway handler.
|
||||
|
||||
`/credits` is the focused money surface (balance in, top-up out). These tests
|
||||
exercise the surface-agnostic `build_credits_view()` core and assert the gateway
|
||||
handler renders the block + tappable top-up URL + no-wait copy. The CLI panel is
|
||||
a thin wrapper over the same view (interactive prompt_toolkit modal — covered by
|
||||
the view-core tests plus manual verification).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
|
||||
import pytest
|
||||
|
||||
import agent.account_usage as account_usage
|
||||
from agent.account_usage import CreditsView, build_credits_view
|
||||
from hermes_cli.nous_account import NousPortalAccountInfo, NousPaidServiceAccessInfo
|
||||
|
||||
|
||||
def _account(**kwargs) -> NousPortalAccountInfo:
|
||||
kwargs.setdefault("logged_in", True)
|
||||
kwargs.setdefault("source", "account_api")
|
||||
kwargs.setdefault("fresh", True)
|
||||
kwargs.setdefault("portal_base_url", "https://portal.example.test")
|
||||
return NousPortalAccountInfo(**kwargs)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def _logged_in_account(monkeypatch):
|
||||
"""Stub the auth token + account fetch so build_credits_view runs offline."""
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.auth.get_provider_auth_state",
|
||||
lambda provider: {"access_token": "tok", "portal_base_url": "https://portal.example.test"},
|
||||
)
|
||||
|
||||
def _install(account):
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.nous_account.get_nous_portal_account_info",
|
||||
lambda *a, **kw: account,
|
||||
)
|
||||
|
||||
return _install
|
||||
|
||||
|
||||
# ── build_credits_view core ─────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_view_logged_out_when_no_token(monkeypatch):
|
||||
monkeypatch.setattr("hermes_cli.auth.get_provider_auth_state", lambda provider: {})
|
||||
view = build_credits_view()
|
||||
assert view == CreditsView(logged_in=False)
|
||||
|
||||
|
||||
def test_view_built_with_org_pinned_url_and_identity(_logged_in_account):
|
||||
_logged_in_account(
|
||||
_account(
|
||||
org_slug="acme",
|
||||
org_name="Acme Inc",
|
||||
email="alice@example.test",
|
||||
paid_service_access=True,
|
||||
paid_service_access_info=NousPaidServiceAccessInfo(
|
||||
purchased_credits_remaining=30.0,
|
||||
total_usable_credits=30.0,
|
||||
),
|
||||
subscription=None,
|
||||
)
|
||||
)
|
||||
|
||||
view = build_credits_view()
|
||||
|
||||
assert view.logged_in is True
|
||||
assert view.topup_url == "https://portal.example.test/orgs/acme/billing?topup=open"
|
||||
assert view.identity_line == "Topping up as alice@example.test / org Acme Inc"
|
||||
assert view.depleted is False
|
||||
# Balance lines carry the magnitudes but NOT the /usage affordance lines.
|
||||
blob = "\n".join(view.balance_lines)
|
||||
assert "Top-up credits: $30.00" in blob
|
||||
assert "Top up:" not in blob # the trailing /usage affordance is stripped
|
||||
assert "(or run" not in blob
|
||||
|
||||
|
||||
def test_view_depleted_flag(_logged_in_account):
|
||||
_logged_in_account(
|
||||
_account(
|
||||
org_slug="acme",
|
||||
email="alice@example.test",
|
||||
paid_service_access=False,
|
||||
paid_service_access_info=NousPaidServiceAccessInfo(
|
||||
total_usable_credits=0.0,
|
||||
),
|
||||
subscription=None,
|
||||
)
|
||||
)
|
||||
|
||||
view = build_credits_view()
|
||||
assert view.depleted is True
|
||||
|
||||
|
||||
def test_view_falls_back_to_legacy_url_when_slug_null(_logged_in_account):
|
||||
_logged_in_account(
|
||||
_account(
|
||||
org_slug=None,
|
||||
email="alice@example.test",
|
||||
paid_service_access=True,
|
||||
paid_service_access_info=NousPaidServiceAccessInfo(
|
||||
purchased_credits_remaining=5.0,
|
||||
total_usable_credits=5.0,
|
||||
),
|
||||
subscription=None,
|
||||
)
|
||||
)
|
||||
|
||||
view = build_credits_view()
|
||||
assert view.topup_url == "https://portal.example.test/billing?topup=open"
|
||||
assert "/orgs/" not in view.topup_url
|
||||
|
||||
|
||||
def test_view_fetch_failure_is_logged_out(monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.auth.get_provider_auth_state",
|
||||
lambda provider: {"access_token": "tok"},
|
||||
)
|
||||
|
||||
def _boom(*a, **kw):
|
||||
raise RuntimeError("portal down")
|
||||
|
||||
monkeypatch.setattr("hermes_cli.nous_account.get_nous_portal_account_info", _boom)
|
||||
|
||||
view = build_credits_view()
|
||||
assert view.logged_in is False
|
||||
|
||||
|
||||
# ── gateway _handle_credits_command ─────────────────────────────────────────
|
||||
|
||||
|
||||
class _FakeEvent:
|
||||
pass
|
||||
|
||||
|
||||
def _make_gateway_stub():
|
||||
"""Minimal object exposing the mixin's _handle_credits_command."""
|
||||
from gateway.slash_commands import GatewaySlashCommandsMixin
|
||||
|
||||
class _Stub(GatewaySlashCommandsMixin):
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
return _Stub()
|
||||
|
||||
|
||||
def test_gateway_credits_renders_block_and_url(monkeypatch):
|
||||
view = CreditsView(
|
||||
logged_in=True,
|
||||
balance_lines=("📈 Nous credits", "Total usable: $52.50"),
|
||||
identity_line="Topping up as alice@example.test / org Acme",
|
||||
topup_url="https://portal.example.test/orgs/acme/billing?topup=open",
|
||||
depleted=False,
|
||||
)
|
||||
monkeypatch.setattr(account_usage, "build_credits_view", lambda *a, **kw: view)
|
||||
|
||||
stub = _make_gateway_stub()
|
||||
out = asyncio.run(stub._handle_credits_command(_FakeEvent()))
|
||||
|
||||
assert "💳" in out
|
||||
assert "Total usable: $52.50" in out
|
||||
assert "Topping up as alice@example.test / org Acme" in out
|
||||
assert "https://portal.example.test/orgs/acme/billing?topup=open" in out
|
||||
assert "credits will appear in /credits shortly" in out
|
||||
# The helper's own 📈 header line is dropped (we render our own 💳 header).
|
||||
assert "📈 Nous credits" not in out
|
||||
|
||||
|
||||
def test_gateway_credits_not_logged_in(monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
account_usage, "build_credits_view", lambda *a, **kw: CreditsView(logged_in=False)
|
||||
)
|
||||
stub = _make_gateway_stub()
|
||||
out = asyncio.run(stub._handle_credits_command(_FakeEvent()))
|
||||
assert "Not logged into Nous Portal" in out
|
||||
|
||||
|
||||
def test_gateway_credits_fetch_exception_is_not_logged_in(monkeypatch):
|
||||
def _boom(*a, **kw):
|
||||
raise RuntimeError("boom")
|
||||
|
||||
monkeypatch.setattr(account_usage, "build_credits_view", _boom)
|
||||
stub = _make_gateway_stub()
|
||||
out = asyncio.run(stub._handle_credits_command(_FakeEvent()))
|
||||
assert "Not logged into Nous Portal" in out
|
||||
|
||||
|
||||
# ── command registry ────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_credits_command_registered():
|
||||
from hermes_cli.commands import resolve_command, COMMAND_REGISTRY
|
||||
|
||||
cmd = resolve_command("credits")
|
||||
assert cmd is not None and cmd.name == "credits"
|
||||
# Available on every surface (not cli_only / gateway_only).
|
||||
entry = next(c for c in COMMAND_REGISTRY if c.name == "credits")
|
||||
assert entry.cli_only is False
|
||||
assert entry.gateway_only is False
|
||||
|
||||
|
||||
# ── CLI _show_credits non-interactive (TUI slash-worker) path ───────────────
|
||||
|
||||
|
||||
def test_cli_show_credits_non_interactive_renders_text_not_modal(monkeypatch, capsys):
|
||||
"""In the TUI slash-worker (no self._app), /credits must render the text
|
||||
variant — never invoke the prompt_toolkit modal, which would read the
|
||||
worker's JSON-RPC stdin and crash the command (only the depleted banner
|
||||
would survive). Regression for that exact failure.
|
||||
"""
|
||||
import agent.account_usage as account_usage
|
||||
from cli import HermesCLI
|
||||
|
||||
monkeypatch.setattr(
|
||||
account_usage,
|
||||
"build_credits_view",
|
||||
lambda *a, **k: CreditsView(
|
||||
logged_in=True,
|
||||
balance_lines=("📈 Nous credits", "Total usable: $0.00"),
|
||||
identity_line="Topping up as a@b.c / org Acme",
|
||||
topup_url="https://prev.test/orgs/acme/billing?topup=open",
|
||||
depleted=True,
|
||||
),
|
||||
)
|
||||
|
||||
cli = HermesCLI.__new__(HermesCLI)
|
||||
cli._app = None # non-interactive, like the slash worker
|
||||
|
||||
# Must NOT call the modal in this context.
|
||||
def _boom_modal(*a, **k):
|
||||
raise AssertionError("modal must not run without a live app")
|
||||
|
||||
monkeypatch.setattr(HermesCLI, "_prompt_text_input_modal", _boom_modal, raising=False)
|
||||
|
||||
cli._show_credits()
|
||||
|
||||
out = capsys.readouterr().out
|
||||
assert "💳 Nous credits" in out
|
||||
assert "Total usable: $0.00" in out
|
||||
assert "Topping up as a@b.c / org Acme" in out
|
||||
assert "https://prev.test/orgs/acme/billing?topup=open" in out
|
||||
assert "credits will appear in /credits shortly" in out
|
||||
|
||||
|
||||
def test_cli_show_credits_logged_out(monkeypatch, capsys):
|
||||
import agent.account_usage as account_usage
|
||||
from cli import HermesCLI
|
||||
|
||||
monkeypatch.setattr(
|
||||
account_usage, "build_credits_view", lambda *a, **k: CreditsView(logged_in=False)
|
||||
)
|
||||
cli = HermesCLI.__new__(HermesCLI)
|
||||
cli._app = None
|
||||
cli._show_credits()
|
||||
assert "Not logged into Nous Portal" in capsys.readouterr().out
|
||||
@@ -124,3 +124,42 @@ def test_never_raises_empty():
|
||||
)
|
||||
# No usable numbers and not depleted -> None, without raising.
|
||||
assert build_nous_credits_snapshot(info) is None
|
||||
|
||||
|
||||
def test_topup_line_is_org_pinned_when_slug_present():
|
||||
info = _account(
|
||||
portal_base_url="https://portal.example.test",
|
||||
org_slug="acme",
|
||||
org_name="Acme Inc",
|
||||
paid_service_access=True,
|
||||
paid_service_access_info=NousPaidServiceAccessInfo(
|
||||
purchased_credits_remaining=30.0,
|
||||
total_usable_credits=30.0,
|
||||
),
|
||||
subscription=None,
|
||||
)
|
||||
snap = build_nous_credits_snapshot(info)
|
||||
assert snap is not None
|
||||
blob = "\n".join(_all_lines(snap))
|
||||
# The /usage top-up link auto-opens the modal and is org-pinned.
|
||||
assert "https://portal.example.test/orgs/acme/billing?topup=open" in blob
|
||||
assert "/credits" in blob
|
||||
|
||||
|
||||
def test_topup_line_falls_back_to_legacy_when_slug_null():
|
||||
info = _account(
|
||||
portal_base_url="https://portal.example.test",
|
||||
org_slug=None,
|
||||
paid_service_access=True,
|
||||
paid_service_access_info=NousPaidServiceAccessInfo(
|
||||
purchased_credits_remaining=30.0,
|
||||
total_usable_credits=30.0,
|
||||
),
|
||||
subscription=None,
|
||||
)
|
||||
snap = build_nous_credits_snapshot(info)
|
||||
assert snap is not None
|
||||
blob = "\n".join(_all_lines(snap))
|
||||
# Null slug → legacy page (which forwards the param); never /orgs/None/...
|
||||
assert "https://portal.example.test/billing?topup=open" in blob
|
||||
assert "/orgs/" not in blob
|
||||
|
||||
@@ -28,9 +28,9 @@ class TestRenderNoticeLine:
|
||||
)
|
||||
assert (
|
||||
render_notice_line(
|
||||
AgentNotice(text="✕ Credit access paused · run /usage for balance", level="error")
|
||||
AgentNotice(text="✕ Credit access paused · run /credits to top up", level="error")
|
||||
)
|
||||
== "✕ Credit access paused · run /usage for balance"
|
||||
== "✕ Credit access paused · run /credits to top up"
|
||||
)
|
||||
|
||||
def test_does_not_prepend_a_second_glyph(self):
|
||||
|
||||
@@ -14,6 +14,7 @@ from hermes_cli.commands import (
|
||||
SlashCommandCompleter,
|
||||
_CMD_NAME_LIMIT,
|
||||
_SLACK_RESERVED_COMMANDS,
|
||||
_SLACK_VIA_HERMES_ONLY,
|
||||
_TG_NAME_LIMIT,
|
||||
_clamp_command_names,
|
||||
_clamp_telegram_names,
|
||||
@@ -378,7 +379,10 @@ class TestSlackNativeSlashes:
|
||||
slack_norm = {_norm(n) for n in slack_names}
|
||||
tg_norm = {_norm(n) for n in tg_names}
|
||||
reserved_norm = {_norm(n) for n in _SLACK_RESERVED_COMMANDS}
|
||||
missing = (tg_norm - slack_norm) - reserved_norm
|
||||
# Commands deliberately routed through /hermes <command> on Slack only
|
||||
# (Slack's 50-slash cap) are expected to be absent from native slashes.
|
||||
via_hermes_norm = {_norm(n) for n in _SLACK_VIA_HERMES_ONLY}
|
||||
missing = (tg_norm - slack_norm) - reserved_norm - via_hermes_norm
|
||||
assert not missing, (
|
||||
f"commands on Telegram but missing from Slack native slashes: {sorted(missing)}"
|
||||
)
|
||||
|
||||
@@ -14,6 +14,7 @@ from hermes_cli.nous_account import (
|
||||
NousPortalAccountInfo,
|
||||
format_nous_portal_entitlement_message,
|
||||
get_nous_portal_account_info,
|
||||
nous_portal_topup_url,
|
||||
reset_nous_portal_account_info_cache,
|
||||
)
|
||||
|
||||
@@ -545,3 +546,89 @@ def test_entitlement_message_for_account_missing():
|
||||
|
||||
assert message is not None
|
||||
assert "could not find a Nous Portal account or organisation" in message
|
||||
|
||||
|
||||
# ── org slug/name parsing + top-up URL builder ──────────────────────────────
|
||||
|
||||
|
||||
def test_account_payload_parses_org_slug_and_name(monkeypatch):
|
||||
token = _jwt({"sub": "user_123", "org_id": "org_123", "exp": int(time.time()) + 900})
|
||||
payload = {
|
||||
"user": {"email": "alice@example.test"},
|
||||
"organisation": {"id": "org_123", "slug": "acme", "name": "Acme Inc"},
|
||||
"paid_service_access": {"allowed": True, "paid_access": True},
|
||||
}
|
||||
monkeypatch.setattr("hermes_cli.auth.get_provider_auth_state", lambda provider: _state(token))
|
||||
monkeypatch.setattr("hermes_cli.auth.resolve_nous_access_token", lambda: "fresh-token")
|
||||
monkeypatch.setattr("hermes_cli.nous_account._fetch_nous_account_info", lambda *a, **kw: payload)
|
||||
|
||||
info = get_nous_portal_account_info(force_fresh=True)
|
||||
|
||||
assert info.source == "account_api"
|
||||
assert info.org_slug == "acme"
|
||||
assert info.org_name == "Acme Inc"
|
||||
|
||||
|
||||
def test_account_payload_org_without_slug_leaves_fields_none(monkeypatch):
|
||||
# Mirrors current main: organisation: { id } only (slug nullable on the portal).
|
||||
token = _jwt({"sub": "user_123", "org_id": "org_123", "exp": int(time.time()) + 900})
|
||||
payload = {
|
||||
"user": {"email": "alice@example.test"},
|
||||
"organisation": {"id": "org_123"},
|
||||
"paid_service_access": {"allowed": True, "paid_access": True},
|
||||
}
|
||||
monkeypatch.setattr("hermes_cli.auth.get_provider_auth_state", lambda provider: _state(token))
|
||||
monkeypatch.setattr("hermes_cli.auth.resolve_nous_access_token", lambda: "fresh-token")
|
||||
monkeypatch.setattr("hermes_cli.nous_account._fetch_nous_account_info", lambda *a, **kw: payload)
|
||||
|
||||
info = get_nous_portal_account_info(force_fresh=True)
|
||||
|
||||
assert info.org_id == "org_123"
|
||||
assert info.org_slug is None
|
||||
assert info.org_name is None
|
||||
|
||||
|
||||
def test_topup_url_is_org_pinned_when_slug_present():
|
||||
info = NousPortalAccountInfo(
|
||||
logged_in=True,
|
||||
source="account_api",
|
||||
fresh=True,
|
||||
portal_base_url="https://portal.example.test",
|
||||
org_slug="acme",
|
||||
)
|
||||
assert (
|
||||
nous_portal_topup_url(info)
|
||||
== "https://portal.example.test/orgs/acme/billing?topup=open"
|
||||
)
|
||||
|
||||
|
||||
def test_topup_url_falls_back_to_legacy_when_slug_null():
|
||||
info = NousPortalAccountInfo(
|
||||
logged_in=True,
|
||||
source="account_api",
|
||||
fresh=True,
|
||||
portal_base_url="https://portal.example.test",
|
||||
org_slug=None,
|
||||
)
|
||||
url = nous_portal_topup_url(info)
|
||||
assert url == "https://portal.example.test/billing?topup=open"
|
||||
assert "/orgs/" not in url
|
||||
|
||||
|
||||
def test_topup_url_strips_trailing_slash_and_encodes_slug():
|
||||
info = NousPortalAccountInfo(
|
||||
logged_in=True,
|
||||
source="account_api",
|
||||
fresh=True,
|
||||
portal_base_url="https://portal.example.test/",
|
||||
org_slug="a/b team",
|
||||
)
|
||||
assert (
|
||||
nous_portal_topup_url(info)
|
||||
== "https://portal.example.test/orgs/a%2Fb%20team/billing?topup=open"
|
||||
)
|
||||
|
||||
|
||||
def test_topup_url_defaults_to_production_portal_for_none():
|
||||
url = nous_portal_topup_url(None)
|
||||
assert url == "https://portal.nousresearch.com/billing?topup=open"
|
||||
|
||||
@@ -1,157 +0,0 @@
|
||||
"""Tests for `hermes portal` dispatch.
|
||||
|
||||
`hermes portal` (no subcommand) is the human-readable alias for the Nous Portal
|
||||
one-shot onboarding (`hermes auth add nous --type oauth` / `hermes setup
|
||||
--portal`). The prior status default moved to `hermes portal info`, with
|
||||
`status` retained as a back-compat alias.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from hermes_cli import portal_cli
|
||||
|
||||
|
||||
def _args(portal_command):
|
||||
return SimpleNamespace(portal_command=portal_command)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("sub", [None, "", "login"])
|
||||
def test_bare_portal_and_login_run_one_shot(monkeypatch, sub):
|
||||
"""`hermes portal`, `hermes portal login` -> one-shot onboarding."""
|
||||
calls = {"login": 0, "status": 0}
|
||||
|
||||
def fake_one_shot(config):
|
||||
calls["login"] += 1
|
||||
|
||||
def fake_status(args):
|
||||
calls["status"] += 1
|
||||
return 0
|
||||
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.setup._run_portal_one_shot", fake_one_shot
|
||||
)
|
||||
monkeypatch.setattr(portal_cli, "_cmd_status", fake_status)
|
||||
monkeypatch.setattr(portal_cli, "load_config", lambda: {})
|
||||
|
||||
rc = portal_cli.portal_command(_args(sub))
|
||||
|
||||
assert rc == 0
|
||||
assert calls["login"] == 1
|
||||
assert calls["status"] == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize("sub", ["info", "status"])
|
||||
def test_info_and_status_alias_run_status(monkeypatch, sub):
|
||||
"""`hermes portal info` and the `status` back-compat alias -> status."""
|
||||
calls = {"login": 0, "status": 0}
|
||||
|
||||
monkeypatch.setattr(
|
||||
"hermes_cli.setup._run_portal_one_shot",
|
||||
lambda config: calls.__setitem__("login", calls["login"] + 1),
|
||||
)
|
||||
|
||||
def fake_status(args):
|
||||
calls["status"] += 1
|
||||
return 0
|
||||
|
||||
monkeypatch.setattr(portal_cli, "_cmd_status", fake_status)
|
||||
|
||||
rc = portal_cli.portal_command(_args(sub))
|
||||
|
||||
assert rc == 0
|
||||
assert calls["status"] == 1
|
||||
assert calls["login"] == 0
|
||||
|
||||
|
||||
def test_open_and_tools_dispatch(monkeypatch):
|
||||
seen = []
|
||||
monkeypatch.setattr(portal_cli, "_cmd_open", lambda a: seen.append("open") or 0)
|
||||
monkeypatch.setattr(portal_cli, "_cmd_tools", lambda a: seen.append("tools") or 0)
|
||||
|
||||
assert portal_cli.portal_command(_args("open")) == 0
|
||||
assert portal_cli.portal_command(_args("tools")) == 0
|
||||
assert seen == ["open", "tools"]
|
||||
|
||||
|
||||
def test_unknown_subcommand_returns_error(capsys):
|
||||
rc = portal_cli.portal_command(_args("bogus"))
|
||||
assert rc == 1
|
||||
err = capsys.readouterr().err
|
||||
assert "Unknown portal subcommand" in err
|
||||
|
||||
|
||||
def test_login_cancelled_returns_one(monkeypatch):
|
||||
def boom(config):
|
||||
raise KeyboardInterrupt
|
||||
|
||||
monkeypatch.setattr("hermes_cli.setup._run_portal_one_shot", boom)
|
||||
monkeypatch.setattr(portal_cli, "load_config", lambda: {})
|
||||
|
||||
rc = portal_cli.portal_command(_args(None))
|
||||
assert rc == 1
|
||||
|
||||
|
||||
def test_parser_registers_subcommands():
|
||||
parser = argparse.ArgumentParser()
|
||||
subparsers = parser.add_subparsers(dest="command")
|
||||
portal_cli.add_parser(subparsers)
|
||||
|
||||
# Bare `portal` resolves to portal_command with no portal_command set.
|
||||
ns = parser.parse_args(["portal"])
|
||||
assert ns.func is portal_cli.portal_command
|
||||
assert getattr(ns, "portal_command", None) in (None, "")
|
||||
|
||||
# All documented subcommands parse.
|
||||
for sub in ("login", "info", "status", "open", "tools"):
|
||||
ns = parser.parse_args(["portal", sub])
|
||||
assert ns.portal_command == sub
|
||||
|
||||
|
||||
def test_one_shot_delegates_to_model_flow_nous(monkeypatch):
|
||||
"""`hermes portal` must run the quick-setup Nous flow (login + MODEL PICK +
|
||||
provider + Tool Gateway), i.e. delegate to `_model_flow_nous` — not the
|
||||
lighter auth-only path that skipped model selection.
|
||||
"""
|
||||
import hermes_cli.setup as setup_mod
|
||||
|
||||
calls = {"model_flow": 0}
|
||||
|
||||
def fake_model_flow(config):
|
||||
calls["model_flow"] += 1
|
||||
|
||||
# _model_flow_nous lives in hermes_cli.main and is imported lazily inside
|
||||
# _run_portal_one_shot, so patch it at the source module.
|
||||
monkeypatch.setattr("hermes_cli.main._model_flow_nous", fake_model_flow)
|
||||
# Keep the disk re-sync a no-op so the test never touches real config.
|
||||
monkeypatch.setattr("hermes_cli.config.load_config", lambda: {})
|
||||
|
||||
setup_mod._run_portal_one_shot({})
|
||||
|
||||
assert calls["model_flow"] == 1, (
|
||||
"`hermes portal` must route through _model_flow_nous so the model "
|
||||
"picker runs every time (matching quick setup)."
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("exc", [KeyboardInterrupt, EOFError, SystemExit])
|
||||
def test_one_shot_swallows_cancel_and_systemexit(monkeypatch, exc):
|
||||
"""A cancel/abort from the delegated Nous flow must NOT escape and kill the
|
||||
CLI. `_login_nous` raises SystemExit(130)/(1) on cancel/failure, and the
|
||||
expired-session re-login path inside `_model_flow_nous` only catches
|
||||
Exception — so SystemExit could otherwise propagate out. The portal handler
|
||||
must treat KeyboardInterrupt/EOFError/SystemExit as a graceful cancel.
|
||||
"""
|
||||
import hermes_cli.setup as setup_mod
|
||||
|
||||
def boom(config):
|
||||
raise exc
|
||||
|
||||
monkeypatch.setattr("hermes_cli.main._model_flow_nous", boom)
|
||||
monkeypatch.setattr("hermes_cli.config.load_config", lambda: {})
|
||||
|
||||
# Must return normally (None), not propagate the exception.
|
||||
assert setup_mod._run_portal_one_shot({}) is None
|
||||
Reference in New Issue
Block a user