Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(cli): tag the login link with its source and report the account link result (#2931)

Swati Ahujaf5340cf6ef41
diff --git a/packages/cli/src/repowise/cli/commands/login_cmd.py b/packages/cli/src/repowise/cli/commands/login_cmd.py
index 5529dfa1b..dbea6c623 100644
--- a/packages/cli/src/repowise/cli/commands/login_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/login_cmd.py
@@ -105,12 +105,22 @@ def _greet(account: dict) -> None:
def _link_anonymous_id() -> None:
- """Best-effort: stitch this machine's pre-login telemetry id to the account."""
+ """Best-effort: stitch this machine's pre-login telemetry id to the account.
+
+ The HTTP status (``0`` when there was no answer) goes on this run's
+ telemetry as ``link_anon_status``, and to stderr under
+ ``REPOWISE_TELEMETRY_DEBUG``, so a link that silently fails is visible.
+ """
with contextlib.suppress(Exception):
- from repowise.cli.platform import identity
+ from repowise.cli.platform import identity, settings, telemetry
from repowise.cli.platform.client import default_client
- default_client.post("auth/link-anon", {"anon_id": identity.get_anonymous_id()})
+ status = default_client.post_status(
+ "auth/link-anon", {"anon_id": identity.get_anonymous_id()}
+ )
+ telemetry.add_command_outcome(link_anon_status=status)
+ if settings.debug_mode():
+ click.echo(f"[repowise telemetry] auth/link-anon -> HTTP {status}", err=True)
@click.command(name="login")
@@ -131,6 +141,10 @@ def login_command(with_token: bool, device_name: str | None) -> None:
existing = credentials.load()
if existing and not existing.get("stale"):
+ from repowise.cli.platform import telemetry
+
+ # Not a new sign-in, so this run's "ok" must not count as one.
+ telemetry.add_command_outcome(already_signed_in=True)
account = existing.get("account") or {}
who = account.get("github_username") or "an account"
console.print(
diff --git a/packages/cli/src/repowise/cli/platform/auth.py b/packages/cli/src/repowise/cli/platform/auth.py
index 96b359ca5..7d53057c9 100644
--- a/packages/cli/src/repowise/cli/platform/auth.py
+++ b/packages/cli/src/repowise/cli/platform/auth.py
@@ -15,6 +15,7 @@ then simply proceeds anonymously.
from __future__ import annotations
import base64
+import contextlib
import hashlib
import secrets
import time
@@ -63,6 +64,15 @@ def build_authorize_url(
}
if device_name:
params["device_name"] = device_name
+ # Where the visit came from, so a signup that starts here is credited to
+ # the CLI. The install id rides along only with telemetry on; the site
+ # uses it to tie this install's usage to the new account.
+ params["src"] = "cli_login"
+ with contextlib.suppress(Exception):
+ from repowise.cli.platform import identity, settings
+
+ if settings.is_enabled():
+ params["aid"] = identity.get_anonymous_id()
return f"{AUTHORIZE_URL}?{urlencode(params)}"
diff --git a/packages/cli/src/repowise/cli/platform/client.py b/packages/cli/src/repowise/cli/platform/client.py
index c31e033d4..ac0d51226 100644
--- a/packages/cli/src/repowise/cli/platform/client.py
+++ b/packages/cli/src/repowise/cli/platform/client.py
@@ -93,6 +93,17 @@ class PlatformClient:
timeout: float | None = None,
) -> bool:
"""POST ``payload`` as JSON to ``path``. Returns success, never raises."""
+ return 200 <= self.post_status(path, payload, timeout=timeout) < 300
+
+ def post_status(
+ self,
+ path: str,
+ payload: dict[str, Any],
+ *,
+ timeout: float | None = None,
+ ) -> int:
+ """POST ``payload`` as JSON and return the HTTP status, ``0`` when the
+ request never got an answer. Never raises."""
url = f"{self.base_url}/{path.lstrip('/')}"
try:
import httpx
@@ -103,11 +114,10 @@ class PlatformClient:
headers=self._headers(),
timeout=timeout or self.timeout,
)
- resp.raise_for_status()
- return True
+ return resp.status_code
except Exception:
- # Network, JSON, HTTP-status — all advisory. The CLI works offline.
- return False
+ # Network, JSON — all advisory. The CLI works offline.
+ return 0
def post_form(
self,
diff --git a/tests/unit/cli/test_login.py b/tests/unit/cli/test_login.py
index 72642e6ce..62cb0ab1a 100644
--- a/tests/unit/cli/test_login.py
+++ b/tests/unit/cli/test_login.py
@@ -108,6 +108,28 @@ class TestPkce:
):
assert fragment in url
+ def test_authorize_url_carries_the_link_source_and_install_id(self, monkeypatch):
+ from repowise.cli.platform import identity
+
+ monkeypatch.delenv("DO_NOT_TRACK", raising=False)
+ monkeypatch.delenv("REPOWISE_TELEMETRY_DISABLED", raising=False)
+ url = auth.build_authorize_url(
+ redirect_uri="http://127.0.0.1:5555/callback", code_challenge="c", state="s",
+ device_name=None,
+ )
+ assert "src=cli_login" in url
+ assert f"aid={identity.get_anonymous_id()}" in url
+
+ @pytest.mark.parametrize("env", ["DO_NOT_TRACK", "REPOWISE_TELEMETRY_DISABLED"])
+ def test_authorize_url_omits_the_install_id_with_telemetry_off(self, monkeypatch, env):
+ monkeypatch.setenv(env, "1")
+ url = auth.build_authorize_url(
+ redirect_uri="http://127.0.0.1:5555/callback", code_challenge="c", state="s",
+ device_name=None,
+ )
+ assert "src=cli_login" in url
+ assert "aid=" not in url
+
class TestAuthHeaders:
def test_signed_out_is_anonymous(self):
@@ -261,8 +283,8 @@ class TestCliCommands:
)
linked = {}
monkeypatch.setattr(
- "repowise.cli.platform.client.PlatformClient.post",
- lambda self, path, payload, timeout=None: linked.setdefault(path, payload) or True,
+ "repowise.cli.platform.client.PlatformClient.post_status",
+ lambda self, path, payload, timeout=None: linked.setdefault(path, payload) and 200,
)
result = CliRunner().invoke(login_command, ["--with-token"], input="rw_live_secret123\n")
assert result.exit_code == 0, result.output
@@ -272,3 +294,70 @@ class TestCliCommands:
assert stored["token_kind"] == "api_key"
assert stored["access_token"] == "rw_live_secret123"
assert "auth/link-anon" in linked
+
+ @pytest.mark.parametrize("status", [200, 401, 0])
+ def test_login_records_the_link_anon_status(self, monkeypatch, status):
+ from repowise.cli.commands.login_cmd import login_command
+ from repowise.cli.platform import telemetry
+
+ telemetry.drain_command_outcome()
+ monkeypatch.setattr(auth, "fetch_account", lambda: {"github_username": "raghav"})
+ monkeypatch.setattr(
+ "repowise.cli.platform.client.PlatformClient.post_status",
+ lambda self, path, payload, timeout=None: status,
+ )
+ monkeypatch.setenv("REPOWISE_TELEMETRY_DEBUG", "1")
+ result = CliRunner().invoke(login_command, ["--with-token"], input="rw_live_secret123\n")
+ assert result.exit_code == 0, result.output
+ assert telemetry.drain_command_outcome()["link_anon_status"] == status
+ assert f"auth/link-anon -> HTTP {status}" in result.output
+
+ def test_link_anon_status_is_quiet_without_debug(self, monkeypatch):
+ from repowise.cli.commands.login_cmd import login_command
+
+ monkeypatch.delenv("REPOWISE_TELEMETRY_DEBUG", raising=False)
+ monkeypatch.setattr(auth, "fetch_account", lambda: {"github_username": "raghav"})
+ monkeypatch.setattr(
+ "repowise.cli.platform.client.PlatformClient.post_status",
+ lambda self, path, payload, timeout=None: 200,
+ )
+ result = CliRunner().invoke(login_command, ["--with-token"], input="rw_live_secret123\n")
+ assert "auth/link-anon" not in result.output
+
+ def test_already_signed_in_is_not_counted_as_a_sign_in(self):
+ from repowise.cli.commands.login_cmd import login_command
+ from repowise.cli.platform import telemetry
+
+ telemetry.drain_command_outcome()
+ credentials.save(_oauth_creds(account={"github_username": "raghav"}))
+ result = CliRunner().invoke(login_command, [])
+ assert result.exit_code == 0
+ assert "Already signed in" in result.output
+ assert telemetry.drain_command_outcome() == {"already_signed_in": True}
+
+
+class TestPlatformClientPost:
+ def _client(self, monkeypatch, outcome):
+ import httpx
+
+ def fake_post(url, json=None, headers=None, timeout=None):
+ if isinstance(outcome, Exception):
+ raise outcome
+ return httpx.Response(outcome, request=httpx.Request("POST", url))
+
+ monkeypatch.setattr(httpx, "post", fake_post)
+ return PlatformClient()
+
+ @pytest.mark.parametrize("code", [200, 204, 401, 500])
+ def test_post_status_returns_the_http_status(self, monkeypatch, code):
+ assert self._client(monkeypatch, code).post_status("x", {}) == code
+
+ def test_post_status_is_zero_without_an_answer(self, monkeypatch):
+ import httpx
+
+ client = self._client(monkeypatch, httpx.ConnectError("offline"))
+ assert client.post_status("x", {}) == 0
+
+ @pytest.mark.parametrize(("code", "ok"), [(200, True), (201, True), (401, False), (500, False)])
+ def test_post_still_returns_success(self, monkeypatch, code, ok):
+ assert self._client(monkeypatch, code).post("x", {}) is ok