spooling 0.2.15__tar.gz → 0.2.16__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. {spooling-0.2.15/spooling.egg-info → spooling-0.2.16}/PKG-INFO +10 -7
  2. {spooling-0.2.15 → spooling-0.2.16}/README.md +9 -6
  3. {spooling-0.2.15 → spooling-0.2.16}/pyproject.toml +1 -1
  4. {spooling-0.2.15 → spooling-0.2.16}/spooling/cli.py +10 -0
  5. {spooling-0.2.15 → spooling-0.2.16}/spooling/cloud.py +14 -6
  6. spooling-0.2.16/spooling/device_login.py +88 -0
  7. {spooling-0.2.15 → spooling-0.2.16/spooling.egg-info}/PKG-INFO +10 -7
  8. {spooling-0.2.15 → spooling-0.2.16}/spooling.egg-info/SOURCES.txt +2 -0
  9. spooling-0.2.16/tests/test_device_login.py +155 -0
  10. {spooling-0.2.15 → spooling-0.2.16}/LICENSE +0 -0
  11. {spooling-0.2.15 → spooling-0.2.16}/setup.cfg +0 -0
  12. {spooling-0.2.15 → spooling-0.2.16}/spooling/__init__.py +0 -0
  13. {spooling-0.2.15 → spooling-0.2.16}/spooling/agent.py +0 -0
  14. {spooling-0.2.15 → spooling-0.2.16}/spooling/classifiers.py +0 -0
  15. {spooling-0.2.15 → spooling-0.2.16}/spooling/config.py +0 -0
  16. {spooling-0.2.15 → spooling-0.2.16}/spooling/connectors/__init__.py +0 -0
  17. {spooling-0.2.15 → spooling-0.2.16}/spooling/connectors/base.py +0 -0
  18. {spooling-0.2.15 → spooling-0.2.16}/spooling/connectors/bigquery.py +0 -0
  19. {spooling-0.2.15 → spooling-0.2.16}/spooling/connectors/clickhouse.py +0 -0
  20. {spooling-0.2.15 → spooling-0.2.16}/spooling/connectors/factory.py +0 -0
  21. {spooling-0.2.15 → spooling-0.2.16}/spooling/connectors/mongodb.py +0 -0
  22. {spooling-0.2.15 → spooling-0.2.16}/spooling/connectors/mysql.py +0 -0
  23. {spooling-0.2.15 → spooling-0.2.16}/spooling/connectors/postgresql.py +0 -0
  24. {spooling-0.2.15 → spooling-0.2.16}/spooling/connectors/rest/__init__.py +0 -0
  25. {spooling-0.2.15 → spooling-0.2.16}/spooling/connectors/rest/base.py +0 -0
  26. {spooling-0.2.15 → spooling-0.2.16}/spooling/connectors/rest/shopify_connectors.py +0 -0
  27. {spooling-0.2.15 → spooling-0.2.16}/spooling/connectors/snowflake.py +0 -0
  28. {spooling-0.2.15 → spooling-0.2.16}/spooling/connectors/types.py +0 -0
  29. {spooling-0.2.15 → spooling-0.2.16}/spooling/db.py +0 -0
  30. {spooling-0.2.15 → spooling-0.2.16}/spooling/embeddings.py +0 -0
  31. {spooling-0.2.15 → spooling-0.2.16}/spooling/evals.py +0 -0
  32. {spooling-0.2.15 → spooling-0.2.16}/spooling/experiments.py +0 -0
  33. {spooling-0.2.15 → spooling-0.2.16}/spooling/ingest.py +0 -0
  34. {spooling-0.2.15 → spooling-0.2.16}/spooling/insights.py +0 -0
  35. {spooling-0.2.15 → spooling-0.2.16}/spooling/mcp_server.py +0 -0
  36. {spooling-0.2.15 → spooling-0.2.16}/spooling/optimize.py +0 -0
  37. {spooling-0.2.15 → spooling-0.2.16}/spooling/parser.py +0 -0
  38. {spooling-0.2.15 → spooling-0.2.16}/spooling/pricing.py +0 -0
  39. {spooling-0.2.15 → spooling-0.2.16}/spooling/providers/__init__.py +0 -0
  40. {spooling-0.2.15 → spooling-0.2.16}/spooling/providers/antigravity.py +0 -0
  41. {spooling-0.2.15 → spooling-0.2.16}/spooling/providers/base.py +0 -0
  42. {spooling-0.2.15 → spooling-0.2.16}/spooling/providers/claude_code.py +0 -0
  43. {spooling-0.2.15 → spooling-0.2.16}/spooling/providers/codex.py +0 -0
  44. {spooling-0.2.15 → spooling-0.2.16}/spooling/providers/copilot.py +0 -0
  45. {spooling-0.2.15 → spooling-0.2.16}/spooling/providers/cortex_code.py +0 -0
  46. {spooling-0.2.15 → spooling-0.2.16}/spooling/providers/cursor.py +0 -0
  47. {spooling-0.2.15 → spooling-0.2.16}/spooling/providers/gemini.py +0 -0
  48. {spooling-0.2.15 → spooling-0.2.16}/spooling/providers/github.py +0 -0
  49. {spooling-0.2.15 → spooling-0.2.16}/spooling/providers/gitlab.py +0 -0
  50. {spooling-0.2.15 → spooling-0.2.16}/spooling/providers/kiro.py +0 -0
  51. {spooling-0.2.15 → spooling-0.2.16}/spooling/providers/opencode.py +0 -0
  52. {spooling-0.2.15 → spooling-0.2.16}/spooling/providers/session_file.py +0 -0
  53. {spooling-0.2.15 → spooling-0.2.16}/spooling/providers/windsurf.py +0 -0
  54. {spooling-0.2.15 → spooling-0.2.16}/spooling/redact.py +0 -0
  55. {spooling-0.2.15 → spooling-0.2.16}/spooling/remote_otel.py +0 -0
  56. {spooling-0.2.15 → spooling-0.2.16}/spooling/schema.py +0 -0
  57. {spooling-0.2.15 → spooling-0.2.16}/spooling/sdk.py +0 -0
  58. {spooling-0.2.15 → spooling-0.2.16}/spooling/search.py +0 -0
  59. {spooling-0.2.15 → spooling-0.2.16}/spooling/server.py +0 -0
  60. {spooling-0.2.15 → spooling-0.2.16}/spooling/sessions.py +0 -0
  61. {spooling-0.2.15 → spooling-0.2.16}/spooling/stats.py +0 -0
  62. {spooling-0.2.15 → spooling-0.2.16}/spooling/subscription_pricing.py +0 -0
  63. {spooling-0.2.15 → spooling-0.2.16}/spooling/tracing.py +0 -0
  64. {spooling-0.2.15 → spooling-0.2.16}/spooling/tunnel.py +0 -0
  65. {spooling-0.2.15 → spooling-0.2.16}/spooling/tunnel_auth.py +0 -0
  66. {spooling-0.2.15 → spooling-0.2.16}/spooling/watcher.py +0 -0
  67. {spooling-0.2.15 → spooling-0.2.16}/spooling.egg-info/dependency_links.txt +0 -0
  68. {spooling-0.2.15 → spooling-0.2.16}/spooling.egg-info/entry_points.txt +0 -0
  69. {spooling-0.2.15 → spooling-0.2.16}/spooling.egg-info/requires.txt +0 -0
  70. {spooling-0.2.15 → spooling-0.2.16}/spooling.egg-info/top_level.txt +0 -0
  71. {spooling-0.2.15 → spooling-0.2.16}/tests/test_agent_spans.py +0 -0
  72. {spooling-0.2.15 → spooling-0.2.16}/tests/test_claude_code_provider.py +0 -0
  73. {spooling-0.2.15 → spooling-0.2.16}/tests/test_cloud_errors.py +0 -0
  74. {spooling-0.2.15 → spooling-0.2.16}/tests/test_cloud_teams.py +0 -0
  75. {spooling-0.2.15 → spooling-0.2.16}/tests/test_docs.py +0 -0
  76. {spooling-0.2.15 → spooling-0.2.16}/tests/test_insights.py +0 -0
  77. {spooling-0.2.15 → spooling-0.2.16}/tests/test_mcp_auth_middleware.py +0 -0
  78. {spooling-0.2.15 → spooling-0.2.16}/tests/test_session_ids.py +0 -0
  79. {spooling-0.2.15 → spooling-0.2.16}/tests/test_storage_optimizations.py +0 -0
  80. {spooling-0.2.15 → spooling-0.2.16}/tests/test_tunnel_auth.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: spooling
3
- Version: 0.2.15
3
+ Version: 0.2.16
4
4
  Summary: Local session tracker and semantic search for AI coding assistants
5
5
  Author: Parsed Analytics, Inc.
6
6
  License: MIT
@@ -390,16 +390,19 @@ the CLI ships with a `spooling cloud` subcommand.
390
390
 
391
391
  ### One-time setup
392
392
 
393
- 1. Mint an API key in the GUI at `app.spooling.ai/settings/api-keys`
394
- (looks like `sk_live_...`).
395
- 2. Save it locally:
393
+ 1. Sign in from the terminal:
396
394
 
397
395
  ```bash
398
- spooling cloud login --key sk_live_...
396
+ spooling login
399
397
  ```
400
398
 
401
- The key is stored at `~/.config/spooling/cloud.json` with `0600` perms.
402
- You can override the API base with `--api-url` or the
399
+ This opens your browser with a short code (for example `BCDF-GHJK`). Check the code, pick the workspace the
400
+ sessions should go to, and click Approve. The API key is generated on your machine and only its hash is sent to
401
+ Spooling, so there is nothing to copy and paste. It is stored at `~/.config/spooling/cloud.json` with `0600`
402
+ perms. Use `--no-browser` to just print the link (SSH sessions, containers).
403
+
404
+ Prefer to manage keys yourself? Mint one at `app.spooling.ai/settings` and run
405
+ `spooling cloud login --key sk_live_...`. You can override the API base with `--api-url` or the
403
406
  `SPOOLING_CLOUD_URL` env var (default: `https://api.spooling.ai`).
404
407
 
405
408
  ### Push once
@@ -354,16 +354,19 @@ the CLI ships with a `spooling cloud` subcommand.
354
354
 
355
355
  ### One-time setup
356
356
 
357
- 1. Mint an API key in the GUI at `app.spooling.ai/settings/api-keys`
358
- (looks like `sk_live_...`).
359
- 2. Save it locally:
357
+ 1. Sign in from the terminal:
360
358
 
361
359
  ```bash
362
- spooling cloud login --key sk_live_...
360
+ spooling login
363
361
  ```
364
362
 
365
- The key is stored at `~/.config/spooling/cloud.json` with `0600` perms.
366
- You can override the API base with `--api-url` or the
363
+ This opens your browser with a short code (for example `BCDF-GHJK`). Check the code, pick the workspace the
364
+ sessions should go to, and click Approve. The API key is generated on your machine and only its hash is sent to
365
+ Spooling, so there is nothing to copy and paste. It is stored at `~/.config/spooling/cloud.json` with `0600`
366
+ perms. Use `--no-browser` to just print the link (SSH sessions, containers).
367
+
368
+ Prefer to manage keys yourself? Mint one at `app.spooling.ai/settings` and run
369
+ `spooling cloud login --key sk_live_...`. You can override the API base with `--api-url` or the
367
370
  `SPOOLING_CLOUD_URL` env var (default: `https://api.spooling.ai`).
368
371
 
369
372
  ### Push once
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "spooling"
3
- version = "0.2.15"
3
+ version = "0.2.16"
4
4
  description = "Local session tracker and semantic search for AI coding assistants"
5
5
  readme = "README.md"
6
6
  authors = [{ name = "Parsed Analytics, Inc." }]
@@ -107,6 +107,16 @@ def watch():
107
107
  do_watch()
108
108
 
109
109
 
110
+ @cli.command("login")
111
+ @click.option("--no-browser", is_flag=True, help="Print the approval link instead of opening it")
112
+ @click.option("--api-url", default=None, help="Override the Spooling Cloud API base")
113
+ @click.pass_context
114
+ def login(ctx, no_browser, api_url):
115
+ """Sign in to Spooling Cloud through your browser (shortcut for `spooling cloud login`)."""
116
+ from spooling.cloud import cloud_login
117
+ ctx.invoke(cloud_login, key=None, api_url=api_url, no_browser=no_browser)
118
+
119
+
110
120
  @cli.command()
111
121
  @click.argument("query")
112
122
  @click.option("-n", "--limit", default=10, help="Number of results")
@@ -66,7 +66,7 @@ def _auth_headers() -> dict:
66
66
  cfg = _load_config()
67
67
  key = cfg.get("api_key") or os.environ.get("SPOOLING_CLOUD_API_KEY")
68
68
  if not key:
69
- raise click.ClickException("Not logged in. Run `spooling cloud login --key sk_...` first.")
69
+ raise click.ClickException("Not logged in. Run `spooling login` first.")
70
70
  return {"Authorization": f"Bearer {key}"}
71
71
 
72
72
 
@@ -218,14 +218,22 @@ def cloud():
218
218
 
219
219
 
220
220
  @cloud.command("login")
221
- @click.option("--key", required=True, help="API key minted at app.spooling.ai/settings/api-keys")
221
+ @click.option("--key", default=None, help="Use an API key you already have (skips the browser)")
222
222
  @click.option("--api-url", default=None, help=f"Override API base (default {DEFAULT_API})")
223
- def cloud_login(key: str, api_url: str | None):
224
- """Store a Spooling Cloud API key in ~/.config/spooling/cloud.json."""
223
+ @click.option("--no-browser", is_flag=True, help="Print the approval link instead of opening it")
224
+ def cloud_login(key: str | None, api_url: str | None, no_browser: bool):
225
+ """Sign in to Spooling Cloud (opens your browser), or store a key you already have."""
225
226
  cfg = _load_config()
226
- cfg["api_key"] = key.strip()
227
227
  if api_url:
228
228
  cfg["api_url"] = api_url.rstrip("/")
229
+ if key:
230
+ cfg["api_key"] = key.strip()
231
+ else:
232
+ from spooling.device_login import run_device_login
233
+ base = cfg.get("api_url") or os.environ.get("SPOOLING_CLOUD_URL") or DEFAULT_API
234
+ cfg["api_key"], ws = run_device_login(base, open_browser=not no_browser)
235
+ if ws.get("name"):
236
+ console.print(f"[green]Approved.[/green] Sessions will be pushed to [bold]{ws['name']}[/bold].")
229
237
  _save_config(cfg)
230
238
 
231
239
  base = cfg.get("api_url") or DEFAULT_API
@@ -246,7 +254,7 @@ def cloud_status():
246
254
  """Show current login + cloud stats."""
247
255
  cfg = _load_config()
248
256
  if not cfg.get("api_key"):
249
- console.print("[yellow]Not logged in.[/yellow] Run `spooling cloud login --key sk_...`.")
257
+ console.print("[yellow]Not logged in.[/yellow] Run `spooling login`.")
250
258
  return
251
259
  base = _api_base()
252
260
  try:
@@ -0,0 +1,88 @@
1
+ """Sign the CLI in through the browser: ``spooling login``.
2
+
3
+ The API key is created HERE, on this machine, and only its sha256 is sent to Spooling. You approve the short code in
4
+ your browser (signed in, choosing the workspace), and the server registers that key for you. No secret ever travels
5
+ through the browser, the clipboard, or the server's responses, and there is nothing to copy and paste.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import platform
12
+ import secrets
13
+ import socket
14
+ import time
15
+ import webbrowser
16
+
17
+ import click
18
+ import httpx
19
+ from rich.console import Console
20
+
21
+ console = Console()
22
+
23
+
24
+ class LoginError(click.ClickException):
25
+ pass
26
+
27
+
28
+ def _new_key() -> str:
29
+ return "sk_" + secrets.token_urlsafe(32)
30
+
31
+
32
+ def _client_name() -> str:
33
+ try:
34
+ host = socket.gethostname().split(".")[0]
35
+ except Exception: # noqa: BLE001
36
+ host = "this computer"
37
+ return f"{host} ({platform.system() or 'unknown OS'})"[:80]
38
+
39
+
40
+ def run_device_login(api_base: str, *, open_browser: bool = True, sleep=time.sleep, now=time.monotonic,
41
+ http=httpx, out=console) -> tuple[str, dict]:
42
+ """Do the whole dance. Returns (api_key, workspace). Raises LoginError with a plain-English reason."""
43
+ api_base = api_base.rstrip("/")
44
+ key = _new_key()
45
+ try:
46
+ r = http.post(f"{api_base}/api/v1/auths/device/code", timeout=15, json={
47
+ "client_name": _client_name(), "key_hash": hashlib.sha256(key.encode()).hexdigest(), "key_prefix": key[:12]})
48
+ except httpx.HTTPError as e:
49
+ raise LoginError(f"Could not reach {api_base}: {e}") from e
50
+ if r.status_code == 429:
51
+ raise LoginError("Too many login attempts from this network. Try again in a while.")
52
+ if r.status_code != 200:
53
+ raise LoginError(f"Spooling refused the login request ({r.status_code}).")
54
+ d = r.json()
55
+
56
+ url = d["verification_uri_complete"]
57
+ out.print()
58
+ out.print(f" Your code: [bold cyan]{d['user_code']}[/bold cyan]")
59
+ out.print(f" Approve it at [underline]{url}[/underline]")
60
+ if open_browser:
61
+ try:
62
+ if webbrowser.open(url):
63
+ out.print(" [dim](opened in your browser)[/dim]")
64
+ except Exception: # noqa: BLE001
65
+ pass
66
+ out.print(" [dim]Waiting for approval... (Ctrl+C to cancel)[/dim]\n")
67
+
68
+ interval = max(int(d.get("interval", 5)), 1)
69
+ deadline = now() + int(d.get("expires_in", 600))
70
+ while now() < deadline:
71
+ sleep(interval)
72
+ try:
73
+ p = http.post(f"{api_base}/api/v1/auths/device/poll", json={"device_code": d["device_code"]}, timeout=15)
74
+ except httpx.HTTPError:
75
+ continue # a blip: keep waiting until the code expires
76
+ if p.status_code != 200:
77
+ continue
78
+ j = p.json()
79
+ status = j.get("status")
80
+ if status == "approved":
81
+ return key, j.get("workspace") or {}
82
+ if status == "denied":
83
+ raise LoginError("The request was denied in the browser.")
84
+ if status == "expired":
85
+ raise LoginError("The code expired before it was approved. Run the command again.")
86
+ if status == "slow_down":
87
+ interval = int(j.get("interval", interval + 5))
88
+ raise LoginError("Timed out waiting for approval. Run the command again.")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: spooling
3
- Version: 0.2.15
3
+ Version: 0.2.16
4
4
  Summary: Local session tracker and semantic search for AI coding assistants
5
5
  Author: Parsed Analytics, Inc.
6
6
  License: MIT
@@ -390,16 +390,19 @@ the CLI ships with a `spooling cloud` subcommand.
390
390
 
391
391
  ### One-time setup
392
392
 
393
- 1. Mint an API key in the GUI at `app.spooling.ai/settings/api-keys`
394
- (looks like `sk_live_...`).
395
- 2. Save it locally:
393
+ 1. Sign in from the terminal:
396
394
 
397
395
  ```bash
398
- spooling cloud login --key sk_live_...
396
+ spooling login
399
397
  ```
400
398
 
401
- The key is stored at `~/.config/spooling/cloud.json` with `0600` perms.
402
- You can override the API base with `--api-url` or the
399
+ This opens your browser with a short code (for example `BCDF-GHJK`). Check the code, pick the workspace the
400
+ sessions should go to, and click Approve. The API key is generated on your machine and only its hash is sent to
401
+ Spooling, so there is nothing to copy and paste. It is stored at `~/.config/spooling/cloud.json` with `0600`
402
+ perms. Use `--no-browser` to just print the link (SSH sessions, containers).
403
+
404
+ Prefer to manage keys yourself? Mint one at `app.spooling.ai/settings` and run
405
+ `spooling cloud login --key sk_live_...`. You can override the API base with `--api-url` or the
403
406
  `SPOOLING_CLOUD_URL` env var (default: `https://api.spooling.ai`).
404
407
 
405
408
  ### Push once
@@ -8,6 +8,7 @@ spooling/cli.py
8
8
  spooling/cloud.py
9
9
  spooling/config.py
10
10
  spooling/db.py
11
+ spooling/device_login.py
11
12
  spooling/embeddings.py
12
13
  spooling/evals.py
13
14
  spooling/experiments.py
@@ -68,6 +69,7 @@ tests/test_agent_spans.py
68
69
  tests/test_claude_code_provider.py
69
70
  tests/test_cloud_errors.py
70
71
  tests/test_cloud_teams.py
72
+ tests/test_device_login.py
71
73
  tests/test_docs.py
72
74
  tests/test_insights.py
73
75
  tests/test_mcp_auth_middleware.py
@@ -0,0 +1,155 @@
1
+ """`spooling login`: the key is made locally, only its hash is sent, and every failure is explained."""
2
+ import hashlib
3
+
4
+ import httpx
5
+ import pytest
6
+
7
+ from spooling import device_login
8
+ from spooling.device_login import LoginError, run_device_login
9
+
10
+
11
+ class FakeHttp:
12
+ """Stands in for httpx: records requests and replays a scripted server."""
13
+ HTTPError = httpx.HTTPError
14
+
15
+ def __init__(self, polls, code_status=200):
16
+ self.polls, self.code_status, self.sent, self.poll_calls = list(polls), code_status, None, 0
17
+
18
+ def post(self, url, json=None, timeout=None):
19
+ if url.endswith("/device/code"):
20
+ self.sent = json
21
+ body = {"device_code": "dc", "user_code": "BCDF-GHJK", "verification_uri_complete": "https://app.spooling.ai/device?code=BCDF-GHJK",
22
+ "expires_in": 600, "interval": 5}
23
+ return httpx.Response(self.code_status, json=body, request=httpx.Request("POST", url))
24
+ self.poll_calls += 1
25
+ item = self.polls.pop(0) if self.polls else {"status": "pending"}
26
+ if isinstance(item, Exception):
27
+ raise item
28
+ return httpx.Response(200, json=item, request=httpx.Request("POST", url))
29
+
30
+
31
+ class Clock:
32
+ def __init__(self): self.t = 0
33
+ def now(self): return self.t
34
+ def sleep(self, s): self.t += s
35
+
36
+
37
+ def run(polls, **kw):
38
+ clock, http = Clock(), FakeHttp(polls, **kw)
39
+ return http, lambda: run_device_login("https://api.spooling.ai/", open_browser=False, sleep=clock.sleep, now=clock.now, http=http)
40
+
41
+
42
+ def test_approved_returns_the_locally_generated_key_and_only_its_hash_was_sent():
43
+ http, go = run([{"status": "pending"}, {"status": "approved", "workspace": {"id": "w", "name": "Acme"}}])
44
+ key, ws = go()
45
+ assert key.startswith("sk_") and len(key) > 40 and ws == {"id": "w", "name": "Acme"}
46
+ assert http.sent["key_hash"] == hashlib.sha256(key.encode()).hexdigest()
47
+ assert key not in str(http.sent) and http.sent["key_prefix"] == key[:12]
48
+ assert http.poll_calls == 2
49
+
50
+
51
+ def test_each_login_makes_a_fresh_key():
52
+ assert run([{"status": "approved", "workspace": {}}])[1]()[0] != run([{"status": "approved", "workspace": {}}])[1]()[0]
53
+
54
+
55
+ @pytest.mark.parametrize("status,needle", [("denied", "denied"), ("expired", "expired")])
56
+ def test_denied_and_expired_are_explained(status, needle):
57
+ with pytest.raises(LoginError, match=needle):
58
+ run([{"status": status}])[1]()
59
+
60
+
61
+ def test_network_blips_while_polling_do_not_abort_the_login():
62
+ _, go = run([httpx.ConnectError("boom"), {"status": "approved", "workspace": {"name": "Acme"}}])
63
+ assert go()[1]["name"] == "Acme"
64
+
65
+
66
+ def test_slow_down_widens_the_interval():
67
+ clock = Clock()
68
+ http = FakeHttp([{"status": "slow_down", "interval": 10}, {"status": "approved", "workspace": {}}])
69
+ run_device_login("https://x", open_browser=False, sleep=clock.sleep, now=clock.now, http=http)
70
+ assert clock.t == 5 + 10
71
+
72
+
73
+ def test_gives_up_when_the_code_window_closes():
74
+ clock = Clock()
75
+ http = FakeHttp([]) # pending forever
76
+ with pytest.raises(LoginError, match="Timed out"):
77
+ run_device_login("https://x", open_browser=False, sleep=clock.sleep, now=clock.now, http=http)
78
+ assert clock.t >= 600
79
+
80
+
81
+ def test_rate_limited_and_server_errors_are_explained():
82
+ with pytest.raises(LoginError, match="Too many"):
83
+ run([], code_status=429)[1]()
84
+ with pytest.raises(LoginError, match="refused"):
85
+ run([], code_status=500)[1]()
86
+
87
+
88
+ def test_unreachable_server_is_explained():
89
+ class Down:
90
+ HTTPError = httpx.HTTPError
91
+ def post(self, *a, **k): raise httpx.ConnectError("no route")
92
+ with pytest.raises(LoginError, match="Could not reach"):
93
+ run_device_login("https://nowhere", open_browser=False, http=Down())
94
+
95
+
96
+ def test_the_approval_url_is_printed_even_if_the_browser_cannot_open(monkeypatch):
97
+ printed = []
98
+ class Out:
99
+ def print(self, *a, **k): printed.append(" ".join(str(x) for x in a))
100
+ monkeypatch.setattr(device_login.webbrowser, "open", lambda url: (_ for _ in ()).throw(RuntimeError("no display")))
101
+ clock, http = Clock(), FakeHttp([{"status": "approved", "workspace": {}}])
102
+ run_device_login("https://x", open_browser=True, sleep=clock.sleep, now=clock.now, http=http, out=Out())
103
+ assert any("BCDF-GHJK" in p for p in printed) and any("/device?code=BCDF-GHJK" in p for p in printed)
104
+
105
+
106
+ # --- wiring: `spooling login` and `spooling cloud login` ----------------------------------------------------------
107
+
108
+ def _cli(monkeypatch, tmp_path, result=("sk_made_locally", {"id": "w", "name": "Acme"})):
109
+ from spooling import cloud
110
+ monkeypatch.setattr(cloud, "CONFIG_PATH", tmp_path / "cloud.json")
111
+ monkeypatch.setattr(cloud.httpx, "get", lambda *a, **k: httpx.Response(200, json={"sessions": 3}, request=httpx.Request("GET", a[0])))
112
+ calls = []
113
+ import spooling.device_login as dl
114
+ monkeypatch.setattr(dl, "run_device_login", lambda base, open_browser=True, **k: calls.append((base, open_browser)) or result)
115
+ return cloud, calls
116
+
117
+
118
+ def test_top_level_login_saves_the_key_with_private_permissions(monkeypatch, tmp_path):
119
+ from click.testing import CliRunner
120
+ from spooling.cli import cli
121
+ cloud, calls = _cli(monkeypatch, tmp_path)
122
+ r = CliRunner().invoke(cli, ["login"])
123
+ assert r.exit_code == 0, r.output
124
+ assert calls == [("https://api.spooling.ai", True)]
125
+ assert cloud._load_config()["api_key"] == "sk_made_locally"
126
+ assert oct((tmp_path / "cloud.json").stat().st_mode & 0o777) == "0o600"
127
+ assert "Acme" in r.output
128
+
129
+
130
+ def test_no_browser_flag_and_custom_api_url_are_honoured(monkeypatch, tmp_path):
131
+ from click.testing import CliRunner
132
+ from spooling.cli import cli
133
+ cloud, calls = _cli(monkeypatch, tmp_path)
134
+ assert CliRunner().invoke(cli, ["login", "--no-browser", "--api-url", "https://staging.example/"]).exit_code == 0
135
+ assert calls == [("https://staging.example", False)]
136
+
137
+
138
+ def test_cloud_login_with_a_key_still_works_without_the_browser(monkeypatch, tmp_path):
139
+ from click.testing import CliRunner
140
+ from spooling.cli import cli
141
+ cloud, calls = _cli(monkeypatch, tmp_path)
142
+ assert CliRunner().invoke(cli, ["cloud", "login", "--key", "sk_pasted_key"]).exit_code == 0
143
+ assert calls == [] and cloud._load_config()["api_key"] == "sk_pasted_key"
144
+
145
+
146
+ def test_a_failed_login_leaves_the_existing_key_alone(monkeypatch, tmp_path):
147
+ from click.testing import CliRunner
148
+ from spooling.cli import cli
149
+ cloud, _ = _cli(monkeypatch, tmp_path)
150
+ cloud._save_config({"api_key": "sk_old"})
151
+ import spooling.device_login as dl
152
+ monkeypatch.setattr(dl, "run_device_login", lambda *a, **k: (_ for _ in ()).throw(LoginError("denied in the browser")))
153
+ r = CliRunner().invoke(cli, ["login"])
154
+ assert r.exit_code != 0 and "denied" in r.output
155
+ assert cloud._load_config()["api_key"] == "sk_old"
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes