AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary
Python ai-promptsai-skillblueskyclaudeclaude-codeclawhubdeep-researchhackernewsinstagramopenclawpolymarketrecencyredditresearchsocial-mediatiktoktrendstwitterweb-searchyoutube
fix(nux): deterministic first-run welcome + GitHub device code (engine-driven) (#748)
Matt Van Horn6a1d93bdb5f9
diff --git a/AGENTS.md b/AGENTS.mdindex 570624d9..9dcbb741 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -43,7 +43,7 @@ Python 3.12+ required. Use `uv` for the env; the venv lives at `.venv/`.- Do not reduce `fail_under` in `pyproject.toml` (`[tool.coverage.report]`) without documenting why in the PR. The coverage gate is a floor meant to rise over time, not to be relaxed when new code is under-tested.- Every `lib/*.py` call to `log.source_log(...)` must pass `tty_only=False`. The default is `True`, which silently drops every line when stderr isn't a TTY (Claude Code, Codex, CI, captured output) — turning source observability into invisible failure. Enforced by `tests/test_source_log_visibility.py`.- **CLI-gated optional sources** (Digg via `digg-pp-cli`, YouTube via `yt-dlp`) activate only when `shutil.which` resolves the binary on the **agent subprocess PATH** — not merely when the file exists on disk. First-run setup installs Digg through `@mvanhorn/printing-press-library` (default `$HOME/.local/bin`); Hermes/OpenClaw gateways often need that directory on PATH. Setup must distinguish PATH-visible installs from off-PATH binaries and must not claim "now active" unless the engine gate would pass. See `docs/solutions/integration-issues/digg-cli-agent-path-setup-wizard.md`.-- **First-run onboarding is consent-driven, model-led, and host-split.** The setup subprocess does only mechanical work (cookie reads, tool installs, GitHub device-auth) — it cannot prompt, so consent lives in `SKILL.md` Step 0. Step 0 has TWO branches: a **Claude Code Modal Flow** (the restored v3.0.0 `AskUserQuestion`-driven NUX — welcome, Auto/Manual/Skip, cookie consent, ScrapeCreators offer, `INCLUDE_SOURCES` opt-in, first-topic picker) for hosts with modals, and a **Non-Modal Prose Flow** for hosts without (OpenClaw, Codex, Cursor, Gemini CLI). Both ask before reading cookies, surface the macOS Full Disk Access fix on permission-denied, and offer the ScrapeCreators GitHub signup (10,000 free calls) on every first run. A successful `setup --github` persists `SCRAPECREATORS_API_KEY` automatically (via `setup_wizard.write_api_key`, 0o600) and masks the key in stdout. Do NOT collapse the modal flow back into a bare silent `setup` call or flatten it to prose-only — the guided modals are the feature (they eroded once and were restored). The onboarding contract is locked by `tests/test_onboarding_contract.py`. The Step 5 source opt-in is two tiers: **Recommended** (TikTok + Instagram, on with the key) and **Everything** (also Threads, Pinterest, and YouTube/TikTok/Instagram comments via `INCLUDE_SOURCES`). Threads, Pinterest, and YouTube comments are opt-in (gated on `INCLUDE_SOURCES`), not auto-on with the key — they appear only in the Step 5 Everything option, never in the welcome or the Step 4 offer.+- **First-run onboarding is consent-driven, model-led, and host-split.** The setup subprocess does only mechanical work (cookie reads, tool installs, GitHub device-auth, and emitting the engine-owned welcome via `--welcome`) — it cannot prompt, so consent lives in `SKILL.md` Step 0. Two flows are engine-deterministic rather than model-authored: the welcome is printed by `last30days.py --welcome` (Step 1 relays it verbatim, so it can't be skipped or drift), and the GitHub device code is surfaced by a two-command split — `setup --github-start` returns the code fast (foreground, copies to clipboard) and `setup --github-poll` waits for authorization (`setup --github` still chains both for back-compat). Step 0 has TWO branches: a **Claude Code Modal Flow** (the restored v3.0.0 `AskUserQuestion`-driven NUX — welcome, Auto/Manual/Skip, cookie consent, ScrapeCreators offer, `INCLUDE_SOURCES` opt-in, first-topic picker) for hosts with modals, and a **Non-Modal Prose Flow** for hosts without (OpenClaw, Codex, Cursor, Gemini CLI). Both ask before reading cookies, surface the macOS Full Disk Access fix on permission-denied, and offer the ScrapeCreators GitHub signup (10,000 free calls) on every first run. A successful `setup --github` persists `SCRAPECREATORS_API_KEY` automatically (via `setup_wizard.write_api_key`, 0o600) and masks the key in stdout. Do NOT collapse the modal flow back into a bare silent `setup` call or flatten it to prose-only — the guided modals are the feature (they eroded once and were restored). The onboarding contract is locked by `tests/test_onboarding_contract.py`. The Step 5 source opt-in is two tiers: **Recommended** (TikTok + Instagram, on with the key) and **Everything** (also Threads, Pinterest, and YouTube/TikTok/Instagram comments via `INCLUDE_SOURCES`). Threads, Pinterest, and YouTube comments are opt-in (gated on `INCLUDE_SOURCES`), not auto-on with the key — they appear only in the Step 5 Everything option, never in the welcome or the Step 4 offer.## Security hygiene- Never commit real API keys, browser cookies, auth tokens, app passwords, access tokens, or `.env` contents.diff --git a/CONFIGURATION.md b/CONFIGURATION.mdindex de4acbce..83fa4458 100644--- a/CONFIGURATION.md+++ b/CONFIGURATION.md@@ -48,6 +48,8 @@ The engine's `.env` reader doesn't expand `$HOME` — only the tilde, via `Path(- `--publish-html` - with `--emit=html`, publish the rendered HTML to `ht-ml.app` after local output/save-dir writes. This is explicit opt-in only; pages are public by default.- `--publish-password <password>` - optional shared password for `--publish-html`. Prefer `LAST30DAYS_PUBLISH_PASSWORD=<password>` instead so the password is not visible in the process list or shell history. Use a unique non-personal password; never reuse the user's own password. The provider's update key is treated as secret and is not written to stdout, HTML, raw output, or `.publish.json` metadata.- `--preflight` - print a human-readable permission preflight. It reports config source, project config trust/ignore state, browser-cookie plan, planned writes, optional commands, source availability, and endpoint overrides without reading browser cookies, writing setup/config/report files, or running research. Add `--emit=json` for machine-readable preflight JSON; use `--diagnose` when you need the full source diagnostic JSON.+- `--welcome` - print the first-run welcome text (engine-owned; the skill relays it verbatim on first run). Safe: prints and exits, no reads or writes.+- `setup --github-start` / `setup --github-poll` - the two-command ScrapeCreators GitHub device-auth split. `--github-start` submits the device flow, copies the code to the clipboard, opens the browser, and returns the code immediately (foreground); `--github-poll` waits for you to authorize and persists the key. `setup --github` still runs both in one shot for back-compat.The footer line `📎 Raw results saved to ${LAST30DAYS_MEMORY_DIR:-$HOME/Documents/Last30Days}/<slug>-raw.md` is the canonical pointer; if it shows backslashes on Windows update past v3.1.1.diff --git a/skills/last30days/SKILL.md b/skills/last30days/SKILL.mdindex 042904a5..268f21c6 100644--- a/skills/last30days/SKILL.md+++ b/skills/last30days/SKILL.md@@ -419,25 +419,9 @@ When both `LAST30DAYS_API_KEY` and `LAST30DAYS_API_BASE` are set, the engine run**Follow these steps IN ORDER. Do NOT skip ahead to research. The sequence is: (1) welcome text → (2) setup modal → (3) run setup if chosen → (4) ScrapeCreators offer modal → (5) source opt-in modal → (6) first-topic picker. Start at step 1.**-**Step 1 - Welcome (REQUIRED FIRST — do not skip).** You MUST output this welcome text as a normal chat message (not blockquoted) BEFORE calling any AskUserQuestion modal. Skipping the welcome and jumping straight to the setup modal is a bug. Display it ONCE.+**Step 1 - Welcome (REQUIRED FIRST — do not skip).** Run the engine's welcome command and show its output to the user VERBATIM as a normal chat message (not blockquoted) BEFORE calling any AskUserQuestion modal. Do NOT summarize, reformat, shorten, or rewrite it - reproduce it exactly. Skipping the welcome and jumping straight to the setup modal is a bug. Show it ONCE.-Welcome to /last30days!--I research any topic across Reddit, X, YouTube, and more - synthesizing what people are actually saying right now.--Auto setup gives you the core sources free in about 30 seconds:-- X/Twitter - reads your browser cookies to authenticate (read live each run, never saved to disk). I check Chrome first (fastest - a one-time macOS Keychain prompt may appear; click Always Allow), then Firefox and Safari.-- Reddit with comments - public JSON, no API key needed.-- YouTube search + transcripts - installs yt-dlp (open source, 190K+ GitHub stars).-- Digg - trending news, GitHub stars, and pipeline feeds - installs the free, keyless Digg CLI.-- arXiv (📄) + Techmeme (📰) - research papers and tech-news headlines - install free, keyless Printing Press CLIs and run on any topic (arXiv is relevance + recency gated to research topics).-- StockTwits (📈) - retail trader sentiment - auto-on when your topic is a ticker or crypto (e.g. "$NVDA earnings", "bitcoin"), off for everything else.-- Trustpilot (⭐) - brand/company review sentiment - opt-in (add `trustpilot` to `INCLUDE_SOURCES`), off by default because it can do a one-time ~10s headless browser cookie step on first company lookup. Install with `npx -y @mvanhorn/[email protected] install trustpilot --cli-only`.-- Hacker News + Polymarket + GitHub (auto-on if the `gh` CLI is installed) - always on, zero config.--Want TikTok and Instagram too? ScrapeCreators adds those (10,000 free calls, scrapecreators.com). No kickbacks, no affiliation.--Power users can turn on more sources in the Manual Setup guide (LinkedIn, Bluesky, Perplexity, and others) - each needs its own credential, so they are off by default.+Run: `"${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py --welcome` (relative to the skill root) and print its stdout verbatim. The welcome text is engine-owned (single source of truth) so it cannot drift or be accidentally skipped; your job is only to relay it.**Step 2 - Setup choice.** After the welcome message from Step 1 has been shown, call AskUserQuestion with ONLY this question and these options (do not repeat the welcome text inside the modal):@@ -473,17 +457,17 @@ Before the modal, run `which gh` via Bash silently; store as gh_available.**Call AskUserQuestion:**Question: "Want to add TikTok and Instagram? Your key also keeps Reddit and YouTube working when they hit rate limits. (We don't get a cut.)"Options:-- "ScrapeCreators via GitHub (recommended - most free calls)" - description: "Opens GitHub, you paste a short code (~20-30s). Grants the full 10,000 free calls - more than the web signup." (Recommend this over the web option because the GitHub path grants more free calls.) Run this device-code flow **IN ORDER — the steps are numbered because step 3 is the one that keeps getting skipped:**- 1. **Tell the user upfront** (chat message): "GitHub is opening in your browser. Your one-time code will be on your clipboard - on that page, just paste it (Cmd+V) and click Continue."- 2. **Run in the BACKGROUND** (do not block the foreground): `"${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py setup --github` with a 5-minute timeout, in the background.- 3. **Read the code, then STOP and SHOW IT.** Poll its stdout every ~2-3 seconds until a line of the form `{"event":"device_code_ready","user_code":"XXXX-XXXX","verification_uri":"..."}` appears. The MOMENT it appears, output ONE chat message to the user: "Enter this code on the GitHub page: **XXXX-XXXX** - it's already on your clipboard, so just paste (Cmd+V) and click Continue." This is a **REQUIRED** step: do NOT skip it, and do NOT fold it into the completion-wait loop. Surfacing the code is the entire point of this flow.- 4. **Then** wait for the process to exit and parse the **LAST** JSON line of stdout for the final status (stdout carries the early `device_code_ready` line plus the final status blob). Handle it:+- "ScrapeCreators via GitHub (recommended - most free calls)" - description: "Opens GitHub, you paste a short code (~20-30s). Grants the full 10,000 free calls - more than the web signup." (Recommend this over the web option because the GitHub path grants more free calls.) This is a **two-command flow** - `--github-start` returns the code fast (foreground), then `--github-poll` waits for you to authorize. The code comes back in the command output, so it can't be missed:+ 1. **Run `--github-start` in the FOREGROUND** (it returns in ~1-2s, it does NOT block-poll): `"${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py setup --github-start`. It submits the device flow, copies the code to the clipboard, opens the browser, and returns a JSON blob plus a plain `Your GitHub code: XXXX-XXXX` line on stdout.+ - If the returned `status == "already_registered"` (a key was already saved): tell the user "You're already set up - your existing ScrapeCreators key is active" and STOP (do not run poll).+ - If `status == "error"`: show the message and offer the web option below.+ 2. **SHOW THE CODE.** Read the `user_code` from the output and output ONE chat message: "Enter this code on the GitHub page: **XXXX-XXXX** - it's already on your clipboard, so just paste (Cmd+V) and click Continue." (If the output said the clipboard copy failed, tell them to type it instead.) The code is right there in step 1's output - surfacing it is the whole point.+ 3. **Run `--github-poll`** (background with a 5-minute timeout, or foreground): `"${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py setup --github-poll`. Parse the **LAST** JSON line of its stdout for the final status:- `status == "success"`: the engine persisted the key (`"persisted": true`, MASKED `api_key` - never ask for or echo the raw key); confirm "You're in! 10,000 free calls. TikTok, Instagram, and the Reddit/YouTube backups are now active."- - `status == "already_registered"`: "You're already set up - your existing ScrapeCreators key is active."- - `status == "success"` but `"persisted": false` (key write failed): do NOT claim sources are active - tell the user signup worked but saving the key failed, and have them add `SCRAPECREATORS_API_KEY=<key>` to `~/.config/last30days/.env` manually (the key is masked in output; re-run `setup --github` or get it from scrapecreators.com).+ - `status == "success"` but `"persisted": false` (key write failed): do NOT claim sources are active - tell the user signup worked but saving the key failed, and have them add `SCRAPECREATORS_API_KEY=<key>` to `~/.config/last30days/.env` manually.- `status == "error"` **with `message == "Authorized but failed to fetch API key"`**: GitHub authorized fine - do NOT say auth failed. This usually means your GitHub is **already linked** to a ScrapeCreators account. Tell the user: "GitHub authorized, but I couldn't auto-grab your ScrapeCreators key - your GitHub is probably already linked to an account. Get your key at scrapecreators.com and paste it here, or Skip." Then accept a pasted key (write `SCRAPECREATORS_API_KEY` to `.env`) or offer the web/skip options.- `status == "timeout"`, or any other `status == "error"` message: show "GitHub auth didn't complete - no worries, sign up at scrapecreators.com or try again later," then offer the web option below.- - **Host without background execution** (can't background a Bash process): run `setup --github` in the foreground, but tell the user first: "A short code will appear - your clipboard will have it, so just paste (Cmd+V) on the GitHub page that opens." The engine prints the `device_code_ready` line and the code box to the terminal.+ - **One-shot fallback:** hosts that prefer a single call can still run `setup --github` (foreground), which chains start+poll; tell the user first that a code will appear on their clipboard to paste.- "Open scrapecreators.com (Google sign-in)" - run `open https://scrapecreators.com` via Bash, then ask them to paste the API key. Write `SCRAPECREATORS_API_KEY={key}` to `~/.config/last30days/.env`.- "I have a key" - accept the key, write to `.env`.- "Skip for now" - proceed without ScrapeCreators. No TikTok/Instagram, and no ScrapeCreators backup if Reddit or YouTube get rate-limited (your free sources still work).@@ -519,7 +503,7 @@ If the user picks an example, run research with it. If "Type my own", ask what tFor hosts without interactive modal prompts (OpenClaw, Codex, Cursor, Gemini CLI, raw CLI). Same work, done conversationally. Run in order; wait where it says to wait.-**1. Welcome.** One short branded line, e.g.: `Welcome to /last30days - let me get you set up (about 30 seconds).`+**1. Welcome.** Run `"${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py --welcome` and show its stdout to the user VERBATIM (do not summarize or reformat). The welcome is engine-owned so it renders the same everywhere.**2. Permission preflight.** Run `"${LAST30DAYS_PYTHON:-python3}" "${SKILL_DIR}/scripts/last30days.py" --preflight` using the directory of the `SKILL.md` you loaded, then summarize the human-readable result before setup: config source, project config trust/ignore state, planned browser-cookie mode, planned writes, optional commands, and active/ignored endpoint overrides. This is safe: it does not read browser-cookie values, does not write setup/config/report files, and does not run research. For Codex desktop and other folder-mode hosts, if hidden `.claude/last30days.env` project config is shown as ignored, tell the user it remains ignored unless `LAST30DAYS_TRUST_PROJECT_CONFIG=1` is set from the process environment or global config. Do not block normal research on missing optional commands; describe them as optional coverage.@@ -530,9 +514,7 @@ For hosts without interactive modal prompts (OpenClaw, Codex, Cursor, Gemini CLI**4. Full Disk Access remediation (macOS only).** After `setup`, inspect stderr. If it contains `Permission denied reading Cookies.binarycookies` on macOS, surface: `macOS blocked the cookie read. To enable X/Twitter: System Settings > Privacy & Security > Full Disk Access > enable your terminal (or the Claude app), then I can retry.` Offer ONE retry. If skipped, continue.**5. ScrapeCreators signup offer (every first run, consent BEFORE launching the browser).** Explain it grants 10,000 free calls that add TikTok and Instagram, plus a backup that keeps Reddit and YouTube working when they hit rate limits (a Reddit backup and a YouTube transcript fallback), that GitHub signup grants the full 10,000 free calls (more than the web form), and that it opens a GitHub authorization page where you enter a short code. Ask, e.g.: `Want to unlock TikTok, Instagram, and more? I can sign you up for ScrapeCreators with GitHub (10,000 free calls, ~20-30s) - it opens a browser and you enter a short code. (yes / no)` **Wait for the answer.**- - On **yes** → run `"${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py setup --github`. If your host can background a process, run it in the background and poll its stdout; the moment a `{"event":"device_code_ready","user_code":"XXXX-XXXX",...}` line appears, show the user the code and the GitHub URL immediately (do not wait for the process to finish). If you cannot background, run it in the foreground and tell the user to watch for the short code the engine prints, then enter it on the GitHub page. When the process exits, parse the **LAST** JSON line of stdout for the final status. On success the engine persists the key automatically and returns `"persisted": true` with a MASKED `api_key` (never ask for or echo the raw key). Confirm the paid sources are active.- - Also, right after backgrounding, tell the user the code is on their clipboard so they can just paste it (Cmd+V) on the GitHub page - do not make them hunt for it.- - On **`status == "already_registered"`** → tell the user they are already set up; their existing key is active.+ - On **yes** → two commands. FIRST run `"${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py setup --github-start` in the FOREGROUND - it returns in ~1-2s with a `Your GitHub code: XXXX-XXXX` line plus a JSON blob, copies the code to the clipboard, and opens the browser. Read the `user_code` from that output and immediately tell the user: the code, that it's on their clipboard so they can just paste it (Cmd+V) on the GitHub page - do not make them hunt for it. (If `status == "already_registered"`, stop here - their existing key is active. If the output said the clipboard copy failed, tell them to type the code.) THEN run `"${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py setup --github-poll` (background with a 5-min timeout, or foreground) and parse the **LAST** JSON line of its stdout for the final status. On success the engine persists the key automatically and returns `"persisted": true` with a MASKED `api_key` (never ask for or echo the raw key). Confirm the paid sources are active.- On **success but `"persisted": false`** (auth completed yet the key write failed) → do NOT claim sources are active. Tell the user signup worked but saving failed, and have them add `SCRAPECREATORS_API_KEY=<key>` to `~/.config/last30days/.env` manually (the raw key is masked in output, so re-run `setup --github` or retrieve it from scrapecreators.com to get the value).- On **`status == "error"` with `message == "Authorized but failed to fetch API key"`** → GitHub authorized fine, so do NOT say auth failed. This usually means the GitHub account is already linked to a ScrapeCreators account. Tell the user: "GitHub authorized, but I couldn't auto-grab your ScrapeCreators key - your GitHub is probably already linked to an account. Get your key at scrapecreators.com and paste it, or Skip." Accept a pasted key or offer web/skip.- On **timeout, or any other error** → tell the user it didn't complete and offer to retry or the web signup at scrapecreators.com.diff --git a/skills/last30days/scripts/last30days.py b/skills/last30days/scripts/last30days.pyindex b5cd0366..618ef625 100644--- a/skills/last30days/scripts/last30days.py+++ b/skills/last30days/scripts/last30days.py@@ -334,6 +334,8 @@ def build_parser() -> argparse.ArgumentParser:parser.add_argument("--diagnose", action="store_true", help="Print provider and source availability")parser.add_argument("--preflight", action="store_true",help="Print a safe human-readable permission preflight")+ parser.add_argument("--welcome", action="store_true",+ help="Print the first-run welcome text (engine-owned; relay verbatim)")parser.add_argument("--preflight-report-on-save-dir", help=argparse.SUPPRESS)parser.add_argument("--no-browser-cookies", action="store_true",help="Disable browser-cookie extraction even when FROM_BROWSER is configured")@@ -899,6 +901,8 @@ SETUP_PASSTHROUGH_FLAGS = {"--allow-browser-cookies","--device-auth","--github",+ "--github-start",+ "--github-poll","--openclaw",}@@ -956,6 +960,11 @@ def main() -> int:if args.debug:os.environ["LAST30DAYS_DEBUG"] = "1"+ if args.welcome:+ from lib import setup_wizard+ print(setup_wizard.render_welcome())+ return 0+topic = " ".join(args.topic).strip()original_topic = topic_validate_extra_argv(parser, topic, extra_argv)@@ -1003,8 +1012,12 @@ def main() -> int:results = setup_wizard.run_openclaw_setup(config)print(json.dumps(results))return 0- if "--github" in extra_argv or "--device-auth" in extra_argv:- if "--github" in extra_argv:+ if any(f in extra_argv for f in ("--github", "--device-auth", "--github-start", "--github-poll")):+ if "--github-start" in extra_argv:+ results = setup_wizard.run_github_start()+ elif "--github-poll" in extra_argv:+ results = setup_wizard.run_github_poll()+ elif "--github" in extra_argv:results = setup_wizard.run_github_auth()else:results = setup_wizard.run_full_device_auth()diff --git a/skills/last30days/scripts/lib/setup_wizard.py b/skills/last30days/scripts/lib/setup_wizard.pyindex 30f11b46..50c0671d 100644--- a/skills/last30days/scripts/lib/setup_wizard.py+++ b/skills/last30days/scripts/lib/setup_wizard.py@@ -29,6 +29,36 @@ def is_first_run(config: Dict[str, Any]) -> bool:return not config.get("SETUP_COMPLETE")+_WELCOME_TEXT = """Welcome to /last30days!++I research any topic across Reddit, X, YouTube, and more - synthesizing what people are actually saying right now.++Auto setup gives you the core sources free in about 30 seconds:+- X/Twitter - reads your browser cookies to authenticate (read live each run, never saved to disk). I check Chrome first (fastest - a one-time macOS Keychain prompt may appear; click Always Allow), then Firefox and Safari.+- Reddit with comments - public JSON, no API key needed.+- YouTube search + transcripts - installs yt-dlp (open source, 190K+ GitHub stars).+- Digg - trending news, GitHub stars, and pipeline feeds - installs the free, keyless Digg CLI.+- arXiv (papers) + Techmeme (tech-news) - install free, keyless Printing Press CLIs and run on any topic (arXiv is relevance + recency gated to research topics).+- StockTwits - retail trader sentiment - auto-on when your topic is a ticker or crypto (e.g. "$NVDA earnings", "bitcoin"), off for everything else.+- Trustpilot - brand/company review sentiment - opt-in (add trustpilot to INCLUDE_SOURCES), off by default.+- Hacker News + Polymarket + GitHub (auto-on if the gh CLI is installed) - always on, zero config.++Want TikTok and Instagram too? ScrapeCreators adds those (10,000 free calls, scrapecreators.com). No kickbacks, no affiliation.++Power users can turn on more sources in the Manual Setup guide (LinkedIn, Bluesky, Perplexity, and others) - each needs its own credential, so they are off by default."""+++def render_welcome() -> str:+ """Return the first-run welcome text.++ Owned by the engine (single source of truth) so the model relays it rather+ than re-authoring it -- authored prose gets skipped, relayed command output+ does not. Mirrors the SKILL.md welcome; keep in sync if the source set+ changes.+ """+ return _WELCOME_TEXT++def run_auto_setup(config: Dict[str, Any], *, allow_browser_cookies: bool = False) -> Dict[str, Any]:"""Perform the auto-setup actions.@@ -827,44 +857,72 @@ def fetch_api_key(access_token: str) -> Optional[str]:return api_key-def run_full_device_auth(timeout: int = 300) -> Dict[str, Any]:- """Run the complete GitHub device auth flow and return JSON-serializable result.+def _device_handle_path() -> Path:+ """Where run_github_start persists the device_code/interval for run_github_poll.++ Kept next to the .env in the config dir; falls back to the OS temp dir when+ no config dir is resolvable (clean/no-config mode).+ """+ try:+ from . import env as _env- Chains: start device flow -> open browser -> poll -> fetch API key.- Designed to be called from the CLI and have its stdout parsed by the LLM.+ if _env.CONFIG_FILE:+ return _env.CONFIG_FILE.parent / ".github-device-handle.json"+ except Exception:+ pass+ import tempfile- Returns:- Dict with status and relevant fields:- - {"status": "success", "api_key": "sc_...", "user_code": "ABCD-1234"}- - {"status": "error", "message": "..."}- - {"status": "timeout", "user_code": "ABCD-1234"}- - {"status": "denied"}+ return Path(tempfile.gettempdir()) / "last30days-github-device-handle.json"+++def _start_device_flow() -> "Tuple[Dict[str, Any], Optional[Dict[str, Any]]]":+ """Submit the GitHub device flow and surface the code, without polling.++ Returns ``(public_result, handle)``. ``handle`` is None for the+ already-registered and error cases (nothing to poll); otherwise it carries+ the private poll state (``device_code``/``interval``/``user_code``/+ ``clipboard_ok``) that never belongs in the public, stdout-printed result.+ Callers either persist the handle to a file (``run_github_start``, for a+ separate poll process) or hand it straight to ``run_github_poll`` in-memory+ (``run_full_device_auth``, so a failed file write can't strand the one-shot)."""+ import sysimport webbrowser- # Step 1: Start device flow+ # Already-registered short-circuit: a saved key means no device dance. The+ # key is returned raw here and masked at the CLI boundary before print.+ existing = _existing_scrapecreators_key()+ if existing:+ return (+ {+ "status": "already_registered",+ "method": "existing",+ "api_key": existing,+ "persisted": True,+ },+ None,+ )+result = run_device_auth()if result is None:- return {"status": "error", "message": "Failed to start device auth flow"}+ return ({"status": "error", "message": "Failed to start device auth flow"}, None)device_code, user_code, verification_uri, interval = result- import sys-- # Step 1b: Validate the code shape BEFORE copying, labeling, or emitting it.- # A non-conforming user_code (e.g. a key-shaped value) is never surfaced as a+ # Validate the code shape BEFORE copying, labeling, or emitting it. A+ # non-conforming user_code (e.g. a key-shaped value) is never surfaced as a# GitHub device code; we stop rather than instruct the user to paste garbage.if not _DEVICE_CODE_RE.match(user_code):logger.warning("Device auth returned a non-device-shaped user_code; aborting.")- return {- "status": "error",- "message": "ScrapeCreators returned an unexpected device-code format.",- }+ return (+ {+ "status": "error",+ "message": "ScrapeCreators returned an unexpected device-code format.",+ },+ None,+ )- # Step 1c: Surface the code immediately on stdout as a structured line so a- # backgrounded caller can read and show it right away, instead of waiting for- # the whole process to exit. The final status blob is still printed at exit,- # so consumers parse the LAST JSON line for final status.+ # Structured stdout line for machine consumers.print(json.dumps({@@ -876,18 +934,27 @@ def run_full_device_auth(timeout: int = 300) -> Dict[str, Any]:flush=True,)- # Step 2: Copy code to clipboard BEFORE opening browser+ # Copy the code to the clipboard BEFORE opening the browser.clipboard_ok = Falseif sys.platform == "darwin":try:- subprocess.run(- ["pbcopy"], input=user_code.encode(), check=True, timeout=5,- )+ subprocess.run(["pbcopy"], input=user_code.encode(), check=True, timeout=5)clipboard_ok = Trueexcept Exception:pass # pbcopy unavailable or failed, fall through- # Step 3: Show code prominently, then open browser+ # Print the code as a plain HUMAN line on stdout too, so a foreground caller+ # sees it in the returned output even without reading the JSON. The clipboard+ # claim is only made when pbcopy actually succeeded (else: type it).+ if clipboard_ok:+ print(+ f"Your GitHub code: {user_code} (already on your clipboard - just paste it, Cmd+V)",+ flush=True,+ )+ else:+ print(f"Your GitHub code: {user_code} (type it on the GitHub page)", flush=True)++ # Human box on stderr for direct-terminal users.clipboard_hint = " (copied to clipboard)" if clipboard_ok else ""code_line = f" Your code: {user_code}{clipboard_hint}"action_line = " Paste it on the GitHub page that just opened"@@ -904,26 +971,107 @@ def run_full_device_auth(timeout: int = 300) -> Dict[str, Any]:except Exception:print(f"Open: {verification_uri}", file=sys.stderr)- print("Waiting for authorization...", file=sys.stderr, flush=True)+ public = {+ "status": "awaiting_authorization",+ "user_code": user_code,+ "verification_uri": verification_uri,+ "clipboard_ok": clipboard_ok,+ }+ handle = {+ "device_code": device_code,+ "interval": interval,+ "user_code": user_code,+ "clipboard_ok": clipboard_ok,+ }+ return (public, handle)+++def run_github_start() -> Dict[str, Any]:+ """Start the device flow and persist the poll handle for a later+ ``run_github_poll`` process. Returns the public result (never the private+ device_code). See ``_start_device_flow`` for the returned statuses."""+ public, handle = _start_device_flow()+ if handle is not None:+ # Persist the poll handle (0o600) so a separate --github-poll process can+ # resume it. Best-effort: the in-memory one-shot path does not depend on+ # this write succeeding.+ path = _device_handle_path()+ try:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(json.dumps(handle), encoding="utf-8")+ os.chmod(path, 0o600)+ except Exception as exc:+ logger.warning("Could not persist device handle: %s", exc)+ return public+++def run_github_poll(timeout: int = 300, *, _handle: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:+ """Poll for authorization using the handle from start.++ ``_handle`` (in-memory, from the one-shot) takes precedence over the+ persisted handle file. Returns success (with the fetched key), timeout, or+ the honest "Authorized but failed to fetch API key" branch. Deletes the+ persisted handle when the flow terminates.+ """+ import sys++ if _handle is not None:+ data = _handle+ else:+ try:+ data = json.loads(_device_handle_path().read_text(encoding="utf-8"))+ except Exception:+ return {+ "status": "error",+ "message": "No pending GitHub device flow; run setup --github-start first.",+ }++ device_code = data["device_code"]+ interval = int(data.get("interval", 5))+ user_code = data.get("user_code", "")+ # Read the real clipboard state so the polling reminder never falsely claims+ # the code is on the clipboard (non-macOS, or a failed pbcopy). Missing key+ # (older handle) defaults to False -- don't overstate.+ clipboard_ok = bool(data.get("clipboard_ok", False))- # Step 4: Poll for token (with periodic code reminders)+ print("Waiting for authorization...", file=sys.stderr, flush=True)access_token = poll_device_auth(- device_code, interval, timeout=timeout,- user_code=user_code, clipboard_ok=clipboard_ok,+ device_code, interval, timeout=timeout, user_code=user_code, clipboard_ok=clipboard_ok)++ def _cleanup() -> None:+ try:+ _device_handle_path().unlink()+ except Exception:+ pass+if access_token is None:- return {"status": "timeout", "user_code": user_code, "clipboard_ok": clipboard_ok}+ _cleanup()+ return {"status": "timeout", "user_code": user_code}- # Step 4: Fetch API keyapi_key = fetch_api_key(access_token)+ _cleanup()if api_key is None:return {"status": "error","message": "Authorized but failed to fetch API key",- "clipboard_ok": clipboard_ok,}- return {"status": "success", "method": "device", "api_key": api_key, "user_code": user_code, "clipboard_ok": clipboard_ok}+ return {"status": "success", "method": "device", "api_key": api_key, "user_code": user_code}+++def run_full_device_auth(timeout: int = 300) -> Dict[str, Any]:+ """Back-compat one-shot: start the device flow, then poll to completion.++ Passes the poll handle to ``run_github_poll`` IN MEMORY, so a failed handle-+ file write can't strand the one-shot. Kept so callers of ``setup --github`` /+ ``--device-auth`` still work; the model-driven wizard uses the two-command+ split (start then poll) instead.+ """+ public, handle = _start_device_flow()+ if handle is None:+ return public # already_registered or error+ return run_github_poll(timeout=timeout, _handle=handle)# ---------------------------------------------------------------------------@@ -932,23 +1080,10 @@ def run_full_device_auth(timeout: int = 300) -> Dict[str, Any]:def run_github_auth(timeout: int = 300) -> Dict[str, Any]:- """Run the --github setup path via device auth only.-- Kept as the semantic entry point for GitHub-backed setup; this path must- not read or forward local GitHub CLI tokens.+ """Run the --github setup path via device auth (one-shot, back-compat).- Returns JSON-serializable dict with status, method, and api_key.+ The existing-key short-circuit now lives in run_github_start; this delegates+ to the start+poll chain. This path must not read or forward local GitHub CLI+ tokens."""- # Already-registered short-circuit: if a key is already saved, return it- # without forcing another device dance. The key is returned raw here and- # masked at the CLI boundary before print (see last30days.py), so it never- # lands unmasked in the host's captured stdout.- existing = _existing_scrapecreators_key()- if existing:- return {- "status": "already_registered",- "method": "existing",- "api_key": existing,- "persisted": True,- }return run_full_device_auth(timeout=timeout)diff --git a/tests/test_github_device_auth.py b/tests/test_github_device_auth.pyindex 34343cc6..928867eb 100644--- a/tests/test_github_device_auth.py+++ b/tests/test_github_device_auth.py@@ -74,29 +74,104 @@ class TestDeviceCodeReadyEmission:class TestAlreadyRegistered:- """U6: an existing key short-circuits without the device dance."""+ """An existing key short-circuits run_github_start without the device dance."""- @patch("lib.setup_wizard.run_full_device_auth")+ @patch("lib.setup_wizard.run_device_auth")@patch("lib.setup_wizard._existing_scrapecreators_key")- def test_existing_key_short_circuits(self, mock_existing, mock_full):+ def test_existing_key_short_circuits_start(self, mock_existing, mock_device):mock_existing.return_value = "sc_live_realkey1234567890"- result = setup_wizard.run_github_auth(timeout=1)+ result = setup_wizard.run_github_start()assert result["status"] == "already_registered"assert result["persisted"] is True- mock_full.assert_not_called() # no device dance+ mock_device.assert_not_called() # no /code submit, no browser- @patch("lib.setup_wizard.run_full_device_auth")+ @patch("webbrowser.open")+ @patch("lib.setup_wizard.subprocess.run")+ @patch("lib.setup_wizard.run_device_auth")@patch("lib.setup_wizard._existing_scrapecreators_key")- def test_no_existing_key_runs_device_flow(self, mock_existing, mock_full):+ def test_no_existing_key_starts_device_flow(+ self, mock_existing, mock_device, mock_pbcopy, mock_browser+ ):mock_existing.return_value = None- mock_full.return_value = {"status": "success", "api_key": "sc_new"}+ mock_device.return_value = ("dev-code", "819B-F71B", "https://github.com/login/device", 5)++ out = io.StringIO()+ with redirect_stdout(out):+ result = setup_wizard.run_github_start()++ assert result["status"] == "awaiting_authorization"+ assert result["user_code"] == "819B-F71B"+ mock_device.assert_called_once()+ # The code is printed to stdout as a plain human line (the whole point).+ assert "819B-F71B" in out.getvalue()++ @patch("lib.setup_wizard._device_handle_path")+ @patch("lib.setup_wizard.fetch_api_key")+ @patch("lib.setup_wizard.poll_device_auth")+ def test_poll_reads_handle_and_returns_key(self, mock_poll, mock_fetch, mock_handle, tmp_path):+ import json as _json+ handle = tmp_path / "h.json"+ handle.write_text(_json.dumps({"device_code": "dc", "interval": 1, "user_code": "819B-F71B"}))+ mock_handle.return_value = handle+ mock_poll.return_value = "access-token"+ mock_fetch.return_value = "sc_polled_key"++ result = setup_wizard.run_github_poll(timeout=1)++ assert result["status"] == "success"+ assert result["api_key"] == "sc_polled_key"+ assert not handle.exists() # handle cleaned up++ @patch("lib.setup_wizard._device_handle_path")+ def test_poll_without_handle_errors_cleanly(self, mock_handle, tmp_path):+ mock_handle.return_value = tmp_path / "missing.json"+ result = setup_wizard.run_github_poll(timeout=1)+ assert result["status"] == "error"+ assert "github-start" in result["message"]++ @patch("lib.setup_wizard._device_handle_path")+ @patch("lib.setup_wizard.fetch_api_key")+ @patch("lib.setup_wizard.poll_device_auth")+ def test_poll_passes_real_clipboard_state(self, mock_poll, mock_fetch, mock_handle, tmp_path):+ """clipboard_ok is read from the handle, not hardcoded True, so the poll+ reminder never falsely claims the code is on the clipboard."""+ import json as _json+ handle = tmp_path / "h.json"+ handle.write_text(+ _json.dumps({"device_code": "dc", "interval": 1, "user_code": "819B-F71B", "clipboard_ok": False})+ )+ mock_handle.return_value = handle+ mock_poll.return_value = "tok"+ mock_fetch.return_value = "sc_k"++ setup_wizard.run_github_poll(timeout=1)++ assert mock_poll.call_args.kwargs["clipboard_ok"] is False++ @patch("lib.setup_wizard._device_handle_path")+ @patch("lib.setup_wizard.fetch_api_key")+ @patch("lib.setup_wizard.poll_device_auth")+ @patch("lib.setup_wizard._start_device_flow")+ def test_oneshot_uses_in_memory_handle_when_file_write_fails(+ self, mock_start, mock_poll, mock_fetch, mock_handle, tmp_path+ ):+ """run_full_device_auth hands the handle to poll in-memory, so a broken+ handle-file path can't strand the one-shot."""+ mock_handle.return_value = tmp_path / "does-not-exist" / "h.json" # unwritable/unreadable+ mock_start.return_value = (+ {"status": "awaiting_authorization", "user_code": "819B-F71B"},+ {"device_code": "dc", "interval": 1, "user_code": "819B-F71B", "clipboard_ok": True},+ )+ mock_poll.return_value = "tok"+ mock_fetch.return_value = "sc_oneshot_key"- result = setup_wizard.run_github_auth(timeout=1)+ result = setup_wizard.run_full_device_auth(timeout=1)assert result["status"] == "success"- mock_full.assert_called_once()+ assert result["api_key"] == "sc_oneshot_key"+ mock_poll.assert_called_once() # reached poll without a readable handle filedef test_already_registered_key_is_masked_before_output(self):# Defense-in-depth: the mask helper must not echo the raw key.diff --git a/tests/test_onboarding_contract.py b/tests/test_onboarding_contract.pyindex 3442effb..8ebc208b 100644--- a/tests/test_onboarding_contract.py+++ b/tests/test_onboarding_contract.py@@ -16,6 +16,8 @@ wizard in PR #659 and flattened it before this restoration).import unittestfrom pathlib import Path+from lib import setup_wizard+ROOT = Path(__file__).resolve().parents[1]SKILL_MD = ROOT / "skills" / "last30days" / "SKILL.md"@@ -53,7 +55,7 @@ class TestOnboardingContract(unittest.TestCase):def test_modal_flow_stage_order(self):"""Welcome -> setup modal -> cookie consent -> SC offer -> opt-in -> picker."""anchors = [- "Welcome to /last30days!",+ "Step 1 - Welcome (REQUIRED FIRST","How would you like to set up?","scan your browser", # cookie-consent modal"Want to add TikTok and Instagram?", # SC offer@@ -179,9 +181,16 @@ class TestOnboardingContract(unittest.TestCase):"""Full Disk Access is framed as Safari-only, not the default path."""self.assertNotIn("scan your browser (Firefox/Safari)", self.modal)+ def test_welcome_relayed_from_engine(self):+ """The modal relays the engine-owned welcome verbatim (single source of+ truth) rather than inlining it, so it can't be skipped or drift."""+ self.assertIn("last30days.py --welcome", self.modal)+ self.assertIn("VERBATIM", self.modal)+def test_stocktwits_surfaced_as_conditional(self):- """StockTwits is advertised in the welcome as a ticker/crypto-gated source."""- self.assertIn("StockTwits", self.modal)+ """StockTwits is advertised in the engine welcome as a ticker/crypto-gated+ source (welcome text moved out of SKILL.md into the engine)."""+ self.assertIn("StockTwits", setup_wizard.render_welcome())# --- Honest GitHub device-code copy (U4/U7) ---@@ -191,9 +200,12 @@ class TestOnboardingContract(unittest.TestCase):self.assertNotIn("Registers via GitHub CLI in ~2 seconds", self.step0)def test_device_code_surfacing_orchestration_present(self):- """Both flows must surface the device code, not block on a spinner."""- self.assertIn("device_code_ready", self.modal)- self.assertIn("device_code_ready", self.prose)+ """Both flows use the deterministic two-command split (start returns the+ code fast, then poll) instead of a background-and-surface spinner."""+ self.assertIn("setup --github-start", self.modal)+ self.assertIn("setup --github-poll", self.modal)+ self.assertIn("setup --github-start", self.prose)+ self.assertIn("setup --github-poll", self.prose)def test_already_registered_status_handled(self):self.assertIn("already_registered", self.modal)@@ -219,8 +231,9 @@ class TestOnboardingContract(unittest.TestCase):and makes surfacing the code a required step (the bug the user hit)."""self.assertIn("on your clipboard", self.modal)- self.assertIn("paste", self.modal.lower()[self.modal.find("device_code_ready"):])- self.assertIn("REQUIRED", self.modal)+ # Surfacing the code is a required, explicit step in the new split flow.+ self.assertIn("SHOW THE CODE", self.modal)+ self.assertIn("just paste", self.modal)# --- Honest 'authorized but no key' branch, distinct from auth-failed (U4) ---diff --git a/tests/test_welcome.py b/tests/test_welcome.pynew file mode 100644index 00000000..429a3c8f--- /dev/null+++ b/tests/test_welcome.py@@ -0,0 +1,52 @@+"""U1: the first-run welcome is engine-owned so the model relays it (rather than+authoring prose it reliably skips) and it cannot drift from the source set."""++import subprocess+import sys+import unittest+from pathlib import Path++from lib import setup_wizard++ROOT = Path(__file__).resolve().parents[1]+ENGINE = ROOT / "skills" / "last30days" / "scripts" / "last30days.py"+++class TestWelcome(unittest.TestCase):+ def test_render_welcome_names_the_source_set(self):+ text = setup_wizard.render_welcome()+ for source in (+ "X/Twitter",+ "Reddit",+ "YouTube",+ "Digg",+ "arXiv",+ "Techmeme",+ "StockTwits",+ "Trustpilot",+ "Hacker News",+ "Polymarket",+ "GitHub",+ ):+ self.assertIn(source, text, source)++ def test_render_welcome_offers_scrapecreators(self):+ text = setup_wizard.render_welcome()+ self.assertIn("ScrapeCreators", text)+ self.assertIn("10,000 free calls", text)++ def test_welcome_command_prints_and_exits_zero(self):+ proc = subprocess.run(+ [sys.executable, str(ENGINE), "--welcome"],+ capture_output=True,+ text=True,+ timeout=30,+ )+ self.assertEqual(proc.returncode, 0)+ self.assertIn("Welcome to /last30days!", proc.stdout)+ # The command output is exactly the engine welcome (model relays verbatim).+ self.assertEqual(proc.stdout.strip(), setup_wizard.render_welcome().strip())+++if __name__ == "__main__":+ unittest.main()