返回 last30days-skill
test_onboarding_contract.py
根目录 / tests / test_onboarding_contract.py
1 """Contract tests for the restored first-run NUX wizard in SKILL.md.
2
3 Step 0 has three branches: a **Claude Code Modal Flow** (AskUserQuestion-driven,
4 the restored v3.0.0 NUX), a **Non-Modal Prose Flow** for hosts without modals
5 (OpenClaw, Codex, Cursor, Gemini CLI), and a **Grok Bot Prose Flow** (the X
6 connector lane first, keys written only through the engine, no browser-session
7 reads). These tests assert the structural guarantees of the branches, plus the cross-cutting copy rules: the hard
8 "Step 0 before Step 1" gate, Digg threaded alongside yt-dlp, the 10,000-free-calls
9 credit count, and Threads/Pinterest kept out of the onboarding offers. They read
10 SKILL.md as text - the model's runtime contract - matching
11 tests/test_runtime_preflight_contract.py.
12
13 These lock the flow against silent re-erosion (the failure mode that orphaned the
14 wizard in PR #659 and flattened it before this restoration).
15 """
16
17 import unittest
18 from pathlib import Path
19
20 import pytest
21
22 import last30days
23 from lib import env, setup_wizard
24 from tests.skill_contract import contract_documents, reference_text
25
26 ROOT = Path(__file__).resolve().parents[1]
27 SKILL_MD = ROOT / "skills" / "last30days" / "SKILL.md"
28 AGENTS_MD = ROOT / "AGENTS.md"
29
30
31 class TestOnboardingContract(unittest.TestCase):
32 def setUp(self):
33 self.text = SKILL_MD.read_text(encoding="utf-8")
34 # Scope assertions to Step 0 so generic substrings elsewhere in the file
35 # do not satisfy ordering/presence checks.
36 self.step0 = reference_text("setup-wizard")
37 self.assertIn("## Step 0: First-Run Setup Wizard", self.step0)
38 # Branch slices.
39 modal_start = self.step0.index("### Claude Code Modal Flow")
40 prose_start = self.step0.index("### Non-Modal Prose Flow")
41 grok_start = self.step0.index("### Grok Bot Prose Flow")
42 manual_start = self.step0.index("### Manual Setup Guide")
43 self.modal = self.step0[modal_start:prose_start]
44 self.prose = self.step0[prose_start:grok_start]
45 self.grok = self.step0[grok_start:manual_start]
46 self.manual = self.step0[manual_start:]
47
48 # --- Platform split + hard gate ---
49
50 def test_platform_split_present(self):
51 """Step 0 routes modal-capable hosts, prose hosts, and Grok Bot to
52 three distinct flows, in that order."""
53 self.assertIn("Platform split", self.step0)
54 self.assertIn("### Claude Code Modal Flow", self.step0)
55 self.assertIn("### Non-Modal Prose Flow", self.step0)
56 self.assertIn("### Grok Bot Prose Flow", self.step0)
57 split = self.step0[self.step0.index("Platform split"):self.step0.index("### Claude Code Modal Flow")]
58 self.assertIn("Grok Bot Prose Flow", split)
59 self.assertEqual(3, len([h for h in ("### Claude Code Modal Flow", "### Non-Modal Prose Flow", "### Grok Bot Prose Flow") if h in self.step0]))
60 self.assertLess(self.step0.index("### Non-Modal Prose Flow"), self.step0.index("### Grok Bot Prose Flow"))
61
62 def test_agents_md_names_three_step0_branches(self):
63 """AGENTS.md's onboarding rule and this contract move together."""
64 agents = AGENTS_MD.read_text(encoding="utf-8")
65 self.assertIn("Step 0 has THREE branches", agents)
66 self.assertNotIn("Step 0 has TWO branches", agents)
67 for name in ("Claude Code Modal Flow", "Non-Modal Prose Flow", "Grok Bot Prose Flow"):
68 self.assertIn(name, agents, name)
69
70 def test_grok_flow_is_prose_and_connector_first(self):
71 """The third branch has no modals, leads with the X connector, and
72 never routes through a browser-session step."""
73 self.assertNotIn("AskUserQuestion", self.grok)
74 self.assertNotIn("cookie", self.grok.lower())
75 self.assertLess(self.grok.index("search_posts_all"), self.grok.index("X_BEARER_TOKEN"))
76 self.assertIn("setup --store-key", self.grok)
77
78 def test_first_run_flows_do_not_invoke_preflight(self):
79 """Status and permission inspection are not a required first-run beat.
80 `--preflight` stays an opt-in inspector; Step 0 must not dump `.env`."""
81 self.assertNotIn("--preflight", self.modal)
82 self.assertNotIn("--preflight", self.prose)
83 self.assertNotIn("--preflight", self.grok)
84 self.assertIn("Do not run it as a required first-run step", self.step0)
85 self.assertIn("Do not print `.env` contents or credential values", self.step0)
86
87 def test_auto_setup_requires_effective_consent_before_skipping_the_prompt(self):
88 gates = (
89 (self.modal, "**If the user picks Auto setup:**", "Otherwise **call AskUserQuestion:**"),
90 (self.prose, "**2. Cookie consent (ask BEFORE reading anything).**", "Otherwise ask. Example:"),
91 )
92 for flow, start, prompt in gates:
93 with self.subTest(prompt=prompt):
94 gate = flow.split(start, 1)[1].split(prompt, 1)[0]
95 self.assertIn("--resolve-browser-consent", gate)
96 self.assertIn("command succeeds and stdout is exactly `granted`", gate)
97 self.assertIn("setup --use-recorded-browser-consent", gate)
98 self.assertNotIn("--allow-browser-cookies", gate)
99 self.assertNotIn("~/.config/last30days/.env", gate)
100
101 def test_first_run_gate_defers_to_step0_credential_sources(self):
102 """The cheap SETUP_COMPLETE grep is not itself a first-run verdict."""
103 start = self.text.index("**FIRST-RUN GATE")
104 gate = self.text[start:].split("\n## ", 1)[0].replace("**", "")
105 self.assertIn("FIRST_RUN_DETECTED", gate)
106 self.assertIn("A missing `.env` alone is not a first run", gate)
107 self.assertIn("That section decides first-run from every credential source", gate)
108
109 def test_root_first_run_gate_routes_to_setup_wizard(self):
110 """The wizard's own Step 0 gate is only read after this root route fires."""
111 start = self.text.index("**FIRST-RUN GATE")
112 gate = self.text[start:].split("\n## ", 1)[0]
113 first_run = next(
114 line for line in gate.splitlines() if line.startswith("- `FIRST_RUN_DETECTED`")
115 )
116 self.assertIn("read the setup-wizard reference through its root gate immediately", first_run)
117 self.assertIn("complete the applicable flow before topic research", first_run)
118 self.assertLess(gate.index("FIRST_RUN_DETECTED"), gate.index("Topic supplied: load the topic runbook"))
119
120 def test_root_consent_rules_hold_without_setup_wizard(self):
121 """Configured runs never load setup-wizard.md, so consent must stay in the root."""
122 start = self.text.index("**Onboarding consent is model-led and host-split.**")
123 consent = self.text[start:].split("\n\n", 1)[0]
124 self.assertIn("Ask before browser-cookie reads, and preserve refusal", consent)
125 self.assertIn("a skip or no answer is never consent", consent)
126 self.assertIn("All three host flows offer the ScrapeCreators signup on first run", consent)
127
128 def test_complete_does_not_treat_setup_stdout_as_source_list(self):
129 self.assertIn(
130 "Setup stdout is what this run installed, not the runtime source list",
131 self.prose,
132 )
133 self.assertIn(
134 "Setup stdout is what this run installed, not the runtime source list",
135 self.grok,
136 )
137
138 def test_hard_gate_step0_before_step1(self):
139 """The erosion-resistant gate that orphaned the wizard in #659 is restored."""
140 self.assertIn("ALWAYS execute Step 0 BEFORE Step 1", self.step0)
141
142 def test_waiting_topic_continues_after_x_decline_or_setup_skip(self):
143 """Declining optional X access must never strand the requested topic."""
144 self.assertIn("RESEARCH CONTINUATION OVERRIDE", self.step0)
145 self.assertIn("declining or skipping X must never stop", self.step0)
146 self.assertIn("research it now (`--no-browser-cookies` if Reddit got a no)", self.modal)
147 self.assertIn("research it now (`--no-browser-cookies` if Reddit got a no)", self.prose)
148 self.assertIn("a skip or no answer is never consent", self.step0)
149
150 def test_waiting_topic_defers_optional_prompts_and_x_retry(self):
151 self.assertIn("skip the ScrapeCreators offer", self.step0)
152 self.assertIn("Do not ask another X question in the same run", self.step0)
153 self.assertIn("Offer ONE retry only when no research topic is waiting", self.modal)
154 self.assertIn("Offer ONE retry only when no research topic is waiting", self.prose)
155
156 def test_deferred_onboarding_resumes_after_the_findings(self):
157 """Deferral is same-run only: SETUP_COMPLETE=true means later runs skip
158 Step 0, so a skip-X-with-topic run must itself resume the ScrapeCreators
159 offer after the findings or the offer is dropped forever."""
160 self.assertIn("RESUME the deferred onboarding in the SAME run", self.step0)
161 self.assertIn(
162 "this run is the only chance to make the offer", self.step0
163 )
164 # Both flows: Skip-for-now, Skip-X modal option, and the prose no-path
165 # all resume the deferred offer in the same run after the findings.
166 self.assertEqual(
167 2,
168 self.modal.count(
169 "then resume Step 4 (and Step 5 if a key is saved) in the same run"
170 ),
171 )
172 self.assertIn("then resume the deferred onboarding in the same run", self.prose)
173 # The resume never turns back into a second X consent ask.
174 self.assertIn("the resume never re-asks X/browser-cookie consent", self.step0)
175 self.assertIn("Do not re-ask cookie consent as part of the resume", self.prose)
176
177 def test_x_handle_resolution_and_plan_follow_active_sources(self):
178 research = reference_text("research-runbook")
179 self.assertIn("If `ACTIVE_SOURCES_LIST` contains `x`", research)
180 self.assertIn("every applicable source from `ACTIVE_SOURCES_LIST`", research)
181 self.assertIn("Preserve X whenever it is active", research)
182
183 def test_post_report_x_note_is_non_blocking(self):
184 synthesis = reference_text("synthesis")
185 for name, text in contract_documents().items():
186 self.assertNotIn("Just-in-time X unlock", text, name)
187 self.assertIn("Optional X omission", synthesis)
188 self.assertIn("finish the useful findings first", synthesis)
189
190 # --- Modal flow: the restored NUX, stages in order ---
191
192 def test_modal_flow_stage_order(self):
193 """Welcome -> setup modal -> cookie consent -> SC offer -> opt-in -> picker."""
194 anchors = [
195 "Welcome to /last30days!", # welcome pitch, embedded in the setup modal
196 "How would you like to set up?",
197 "your browser's x.com cookies", # cookie-consent modal
198 "Want to add TikTok and Instagram?", # SC offer
199 "Which ScrapeCreators sources?", # source opt-in
200 "What do you want to research first?", # topic picker
201 ]
202 idxs = [self.modal.find(a) for a in anchors]
203 for a, i in zip(anchors, idxs):
204 self.assertGreater(i, -1, f"modal flow missing stage anchor: {a!r}")
205 self.assertEqual(idxs, sorted(idxs), "modal flow stages are out of order")
206
207 def test_modal_uses_askuserquestion(self):
208 self.assertIn("AskUserQuestion", self.modal)
209
210 def test_cookie_consent_names_all_installed_clis(self):
211 """The cookie-consent modal must not frame X cookies as instead-of the CLIs,
212 and must name every installed CLI (not just 'YouTube + Digg') since auto-setup
213 installs all five regardless of the cookie choice."""
214 consent = self.modal[self.modal.find("your browser's x.com cookies"):]
215 consent = consent[: consent.find("Full Disk Access")] # bound to the consent modal
216 for cli in ("yt-dlp", "Digg", "arXiv", "Techmeme", "News RSS", "Yahoo Finance"):
217 self.assertIn(cli, consent, cli)
218 # The question and each option's description name the full list, so no
219 # choice hides an install.
220 full_list = "yt-dlp (YouTube), Digg, arXiv, Techmeme, News RSS, and Yahoo Finance"
221 self.assertIn(f"Auto setup installs the free CLIs either way - {full_list}.", self.modal)
222 self.assertEqual(3, consent.count(full_list))
223 self.assertNotIn("arXiv, and Techmeme", self.step0)
224 # The "skip X" option still installs the CLIs (not framed as X-or-CLIs).
225 self.assertIn("Skip X - just the CLIs", consent)
226
227 def test_github_option_advertises_auto_clipboard(self):
228 """The recommended GitHub option tells the user the code is auto-copied to
229 their clipboard, so they just paste it."""
230 self.assertIn("clipboard automatically", self.modal)
231
232 def test_modal_cookie_consent_before_setup(self):
233 consent = self.modal.find("your browser's x.com cookies")
234 setup = self.modal.find('last30days.py" setup --allow-browser-cookies')
235 self.assertGreater(consent, -1, "no cookie-consent modal in modal flow")
236 self.assertGreater(setup, -1, "no setup invocation after a fresh yes")
237 self.assertLess(consent, setup, "consent question must precede the fresh-consent invocation")
238
239 def test_topic_picker_skips_when_topic_supplied(self):
240 """The picker documents skipping when the user already gave a topic."""
241 self.assertIn("What do you want to research first?", self.modal)
242 self.assertIn("SKIP this picker", self.modal)
243
244 # --- Prose flow: same work, modal-free ---
245
246 def test_prose_flow_has_no_modals(self):
247 self.assertNotIn("AskUserQuestion", self.prose)
248
249 def test_prose_cookie_consent_before_setup(self):
250 consent = self.prose.find("Cookie consent")
251 setup = self.prose.find('last30days.py" setup')
252 self.assertGreater(consent, -1, "no cookie-consent step in prose flow")
253 self.assertGreater(setup, -1, "no setup invocation in prose flow")
254 self.assertLess(consent, setup, "cookie consent must precede setup in prose flow")
255
256 def test_prose_decline_uses_from_browser_off(self):
257 self.assertIn("FROM_BROWSER=off", self.prose)
258
259 # --- Full Disk Access remediation (both branches) ---
260
261 def test_full_disk_access_remediation_present(self):
262 self.assertIn("Permission denied reading Cookies.binarycookies", self.modal)
263 self.assertIn("Full Disk Access", self.modal)
264 self.assertIn("Permission denied reading Cookies.binarycookies", self.prose)
265 self.assertIn("Full Disk Access", self.prose)
266
267 def test_skip_path_writes_setup_complete(self):
268 """The 'Skip for now' setup choice must write SETUP_COMPLETE or the wizard loops."""
269 skip_idx = self.modal.find("If the user picks Skip for now")
270 self.assertGreater(skip_idx, -1, "no Skip-for-now handling in modal flow")
271 # The skip branch must persist the completion flag in its own paragraph.
272 skip_para = self.modal[skip_idx:skip_idx + 400]
273 self.assertIn("SETUP_COMPLETE=true", skip_para)
274
275 # --- ScrapeCreators signup + persisted edge case ---
276
277 def test_scrapecreators_signup_present_both_branches(self):
278 self.assertIn("setup --github", self.modal)
279 self.assertIn("setup --github", self.prose)
280
281 def test_persisted_false_edge_case_documented(self):
282 self.assertIn('"persisted": false', self.step0)
283
284 # --- Digg threaded alongside yt-dlp everywhere it appears ---
285
286 def test_digg_threaded_with_ytdlp(self):
287 self.assertIn("Digg", self.modal)
288 self.assertIn("Digg", self.prose)
289 self.assertIn("Digg", self.manual)
290 # The prose and Grok Bot flows run the same installs, so they name the
291 # same list.
292 self.assertIn("News RSS", self.prose)
293 self.assertIn("News RSS", self.grok)
294 self.assertIn("Yahoo Finance", self.prose)
295 self.assertIn("Yahoo Finance", self.grok)
296 # The Auto-setup modal option names every installed CLI, not just two.
297 self.assertIn("yt-dlp (YouTube), Digg, arXiv, Techmeme, News RSS, Yahoo Finance.", self.modal)
298
299 # --- Credit count = 10,000, no conflicting numbers in onboarding ---
300
301 def test_credit_count_is_10000(self):
302 self.assertIn("10,000 free calls", self.step0)
303 self.assertNotIn("1,000 free", self.step0)
304 self.assertNotIn("1000 free credit", self.step0)
305 self.assertNotIn("1000 credits", self.step0)
306 self.assertNotIn("100 free call", self.step0)
307
308 # --- Threads/Pinterest live ONLY in the Step 5 "Everything" opt-in ---
309
310 def _modal_step5(self):
311 start = self.modal.index("**Step 5:")
312 end = self.modal.index("**Step 6:", start)
313 return self.modal[start:end]
314
315 def _modal_before_step5(self):
316 # Welcome (Step 1) through the Step 4 ScrapeCreators offer.
317 return self.modal[: self.modal.index("**Step 5:")]
318
319 def test_threads_pinterest_only_in_step5_everything(self):
320 """Threads/Pinterest are offered in the Step 5 Everything tier, and
321
322 must NOT appear in the welcome or the Step 4 offer (where they would
323 read as default-on). They are opt-in via INCLUDE_SOURCES.
324 """
325 step5 = self._modal_step5()
326 self.assertIn("Threads", step5)
327 self.assertIn("Pinterest", step5)
328 before = self._modal_before_step5()
329 self.assertNotIn("Threads", before)
330 self.assertNotIn("Pinterest", before)
331
332 def test_offer_copy_names_comments_and_auto_enrichment(self):
333 """The Step 4 offer states comments are part of the default value and
334 describes the key's real Reddit/YouTube roles (Reddit search backfill
335 below the 5-item floor + yt-dlp transcript backstop), not rate-limit
336 escalation or SC Reddit comment enrichment on the free path."""
337 before = self._modal_before_step5()
338 self.assertIn("comments", before.lower())
339 self.assertIn("Reddit", before)
340 self.assertIn("YouTube", before)
341 self.assertIn("10,000 free calls", before)
342 # Floor-triggered search backfill with the 0 opt-out (not
343 # transport/rate-limit escalation, and no longer empty-only).
344 self.assertIn("fewer than 5 items", before)
345 self.assertIn("LAST30DAYS_REDDIT_SC_MIN_ITEMS=0", before)
346 self.assertIn("YouTube search below 3", before)
347 self.assertIn("LAST30DAYS_YT_SC_MIN_ITEMS=0", before)
348 self.assertIn("spends credits", before)
349 self.assertNotIn("returns no items", before)
350 self.assertNotIn("empty-path Reddit", before)
351 self.assertNotIn("when they hit rate limits", before)
352 # Free-path comments are shreddit; do not claim SC comment preference.
353 self.assertNotIn("prefers ScrapeCreators for Reddit", before)
354 self.assertNotIn("enriches Reddit comments", before)
355
356 def test_step5_does_not_claim_merged_reddit_auto_enrichment(self):
357 """Step 5 must not contradict Step 4 with 'public + ScrapeCreators' merge."""
358 step5 = self._modal_step5()
359 self.assertNotIn("public + ScrapeCreators", step5)
360 self.assertNotIn("Reddit auto-enrichment", step5)
361 self.assertIn("fewer than 5 items", step5)
362 self.assertNotIn("empty-only", step5)
363
364 def test_recommended_tier_writes_comments_by_default(self):
365 """Comments are the DEFAULT: the recommended option enables YouTube +
366 TikTok + Instagram comments (posts on -> comments on)."""
367 step5 = self._modal_step5()
368 self.assertIn(
369 "INCLUDE_SOURCES=tiktok,instagram,youtube_comments,tiktok_comments,instagram_comments",
370 step5,
371 )
372 # There is no posts-only tier.
373 self.assertIn("recommended", step5.lower())
374 self.assertIn("comments", step5.lower())
375
376 def test_everything_tier_writes_full_include_sources(self):
377 """The Everything option persists the full list incl. Threads + Pinterest."""
378 step5 = self._modal_step5()
379 self.assertIn(
380 "INCLUDE_SOURCES=tiktok,instagram,youtube_comments,tiktok_comments,instagram_comments,threads,pinterest",
381 step5,
382 )
383
384 # --- Chrome-first cookie scan (U2/U3) ---
385
386 def test_cookie_consent_leads_with_chrome(self):
387 """Both flows tell the user Chrome is checked first, with the Keychain cue."""
388 for slice_name, slice_text in (("modal", self.modal), ("prose", self.prose)):
389 self.assertIn("Chrome", slice_text, f"{slice_name} cookie copy omits Chrome")
390 self.assertIn("Always Allow", slice_text, f"{slice_name} omits the Keychain cue")
391
392 def test_cookie_consent_explains_future_reads_before_the_answer(self):
393 prompts = (
394 self.modal.split('Question: "Auto setup', 1)[1].split("Options (", 1)[0],
395 self.prose.split("Otherwise ask. Example:", 1)[1].split("**Wait for the answer.**", 1)[0],
396 )
397 for prompt in prompts:
398 with self.subTest(prompt=prompt):
399 self.assertIn("later research runs", prompt)
400 self.assertIn("browser names", prompt)
401 self.assertIn("may prompt again", prompt)
402 self.assertIn("Always Allow", prompt)
403 self.assertIn("BROWSER_CONSENT=false", prompt)
404 self.assertIn("FROM_BROWSER=off", prompt)
405 self.assertIn("On macOS", prompt)
406 self.assertIn("Windows and Linux", prompt)
407 self.assertIn("Windows Firefox", prompt)
408
409 def test_cookie_persistence_contract_matches_each_host_flow(self):
410 for flow in (self.modal, self.prose):
411 with self.subTest(flow=flow[:30]):
412 self.assertIn("complete cookies", flow)
413 self.assertIn("comma-separated", flow)
414 self.assertIn("never saves cookie values", flow)
415 self.assertNotIn("one-time macOS Keychain prompt", flow)
416 self.assertNotIn("only when it is Firefox or Safari", flow)
417 self.assertNotIn("only a Firefox/Safari winner", flow)
418 self.assertNotIn("Chrome never re-", flow)
419
420 def test_browser_permission_remediation_keeps_chromium_first(self):
421 """Browser permission guidance does not change consented scan order."""
422 self.assertNotIn("scan your browser (Firefox/Safari)", self.modal)
423 self.assertIn("X cookie access was permission denied", self.modal)
424 self.assertIn("X cookie access was permission denied", self.prose)
425 self.assertIn("AUTH_TOKEN and CT0", self.modal)
426
427 def test_welcome_embedded_in_modal(self):
428 """The welcome pitch lives INSIDE the setup modal (the only always-visible
429 surface), not as a separate message/command that Claude Code folds away.
430 The engine --welcome command is kept for the non-modal prose flow."""
431 # Pitch is in the modal question.
432 self.assertIn("Welcome to /last30days!", self.modal)
433 self.assertIn("How would you like to set up?", self.modal)
434 # The modal flow explicitly does NOT run a separate --welcome command.
435 self.assertIn("Do NOT run a separate `--welcome`", self.modal)
436 # The non-modal flow still uses the engine welcome command.
437 self.assertIn('last30days.py" --welcome', self.prose)
438
439 def test_stocktwits_surfaced_as_conditional(self):
440 """StockTwits is advertised in the engine welcome as a ticker/crypto-gated
441 source (welcome text moved out of SKILL.md into the engine)."""
442 self.assertIn("StockTwits", setup_wizard.render_welcome())
443
444 # --- Honest GitHub device-code copy (U4/U7) ---
445
446 def test_no_false_instant_gh_promise(self):
447 """The '~2 seconds - no browser' claim (a nonexistent code path) is gone."""
448 self.assertNotIn("~2 seconds - no browser", self.step0)
449 self.assertNotIn("Registers via GitHub CLI in ~2 seconds", self.step0)
450
451 def test_device_code_surfacing_orchestration_present(self):
452 """Both flows use the deterministic two-command split (start returns the
453 code fast, then poll) instead of a background-and-surface spinner."""
454 self.assertIn("setup --github-start", self.modal)
455 self.assertIn("setup --github-poll", self.modal)
456 self.assertIn("setup --github-start", self.prose)
457 self.assertIn("setup --github-poll", self.prose)
458
459 def test_already_registered_status_handled(self):
460 self.assertIn("already_registered", self.modal)
461 self.assertIn("already_registered", self.prose)
462
463 # --- Welcome must render before the modal (U1) ---
464
465 def test_welcome_pitch_is_in_the_modal_question(self):
466 """The welcome pitch names the core sources inside the modal question, so
467 the user sees it without expanding folded tool output. The old skip-prone
468 'IMMEDIATELY call AskUserQuestion' wording stays gone."""
469 # Pitch names the core sources right in the modal.
470 for source in ("Reddit", "X,", "YouTube", "TikTok"):
471 self.assertIn(source, self.modal, source)
472 self.assertNotIn("Then IMMEDIATELY call AskUserQuestion", self.modal)
473
474 # --- Device code surfaced with a clipboard-paste hint (U3) ---
475
476 def test_device_code_clipboard_paste_instruction(self):
477 """The GitHub flow tells the user the code is on their clipboard to paste,
478
479 and makes surfacing the code a required step (the bug the user hit).
480 """
481 self.assertIn("on your clipboard", self.modal)
482 # Surfacing the code is a required, explicit step in the new split flow.
483 self.assertIn("SHOW THE CODE", self.modal)
484 self.assertIn("just paste", self.modal)
485
486 # --- Honest 'authorized but no key' branch, distinct from auth-failed (U4) ---
487
488 def test_authorized_but_no_key_branch_present(self):
489 """A key-fetch failure after successful auth is handled honestly (likely
490
491 an already-linked account), not lumped into 'auth didn't complete'.
492 """
493 for slice_name, slice_text in (("modal", self.modal), ("prose", self.prose)):
494 self.assertIn("Authorized but failed to fetch API key", slice_text, slice_name)
495 self.assertIn("already linked", slice_text, slice_name)
496
497 def test_upstream_profile_error_branch_distinct_from_already_linked(self):
498 """A ScrapeCreators /profile 5xx must not be diagnosed as already-linked (#882)."""
499 for slice_name, slice_text in (("modal", self.modal), ("prose", self.prose)):
500 self.assertIn("ScrapeCreators profile failed", slice_text, slice_name)
501 self.assertIn("upstream_error", slice_text, slice_name)
502 self.assertIn("server error", slice_text, slice_name)
503 # Guidance forbids the already-linked misdiagnosis on this path.
504 self.assertIn("do **NOT** say", slice_text, slice_name)
505 self.assertIn("already linked", slice_text, slice_name)
506
507 # --- Legacy guarantees retained ---
508
509 def test_old_silent_wizard_instruction_removed(self):
510 for document in contract_documents().values():
511 self.assertNotIn("Follow the wizard's prompts end-to-end", document)
512
513 def test_consent_is_conversational_contract_documented(self):
514 self.assertIn("You are the conversational driver", self.step0)
515 self.assertIn("consent happens HERE, in chat", self.step0)
516 self.assertIn("gate each subprocess call on the answer", self.step0)
517 self.assertIn("non-interactive subprocess", self.step0)
518
519
520 # --- Reddit session offer (U6) ---
521
522 def _gate_script(self):
523 gate = self.text.split("**FIRST-RUN GATE", 1)[1].split("**Onboarding consent", 1)[0]
524 return gate.split("```bash\n", 1)[1].split("```", 1)[0]
525
526 def _run_gate(self, env_lines, host=None):
527 import os
528 import subprocess
529 import tempfile
530
531 with tempfile.TemporaryDirectory() as home:
532 if env_lines is not None:
533 config = Path(home) / ".config" / "last30days"
534 config.mkdir(parents=True)
535 (config / ".env").write_text("".join(f"{line}\n" for line in env_lines))
536 env = {"HOME": home, "PATH": os.environ.get("PATH", "/usr/bin:/bin")}
537 if host:
538 env["LAST30DAYS_HOST"] = host
539 out = subprocess.run(
540 ["bash", "-c", self._gate_script()], env=env, capture_output=True, text=True, check=False,
541 )
542 return out.stdout.strip()
543
544 def test_gate_offers_reddit_session_once_to_returning_users(self):
545 self.assertEqual(self._run_gate(None), "FIRST_RUN_DETECTED")
546 self.assertEqual(self._run_gate(["BROWSER_CONSENT=true"]), "FIRST_RUN_DETECTED")
547 self.assertEqual(self._run_gate(["SETUP_COMPLETE=true"]), "REDDIT_OFFER")
548 # Either answer writes the offered marker, so the offer never repeats.
549 for answer in ("true", "false"):
550 lines = ["SETUP_COMPLETE=true", "REDDIT_SESSION_OFFERED=true", f"REDDIT_BROWSER_CONSENT={answer}"]
551 self.assertEqual(self._run_gate(lines), "1")
552 # Skipping X saved BROWSER_CONSENT=false; that user still gets the Reddit offer once.
553 self.assertEqual(self._run_gate(["SETUP_COMPLETE=true", "BROWSER_CONSENT=false"]), "REDDIT_OFFER")
554 # FROM_BROWSER=off and a Grok Bot host never get the offer.
555 self.assertEqual(self._run_gate(["SETUP_COMPLETE=true", "FROM_BROWSER=off"]), "1")
556 self.assertEqual(self._run_gate(["SETUP_COMPLETE=true"], host="grok-bot"), "1")
557
558 def test_reddit_offer_records_the_answer_once(self):
559 import tempfile
560
561 with tempfile.TemporaryDirectory() as tmp:
562 env_path = Path(tmp) / ".env"
563 result = setup_wizard.run_reddit_session_setup({}, env_path, consent=False)
564 self.assertEqual(result["status"], "declined")
565 text = env_path.read_text()
566 self.assertIn("REDDIT_SESSION_OFFERED=true", text)
567 self.assertIn("REDDIT_BROWSER_CONSENT=false", text)
568
569 def test_reddit_question_is_its_own_consent_with_the_account_risk(self):
570 offer = reference_text("reddit-session")
571 question = offer.split("Question text (reproduce it verbatim):", 1)[1].split("\n- Modal hosts", 1)[0]
572 self.assertIn("Separate from any X access", question)
573 self.assertIn("reddit.com login cookie", question)
574 self.assertIn("acts as your own Reddit account", question)
575 self.assertIn("may breach Reddit's terms", question)
576 self.assertIn("REDDIT_BROWSER_CONSENT=false", question)
577 self.assertIn("never the cookie value", question)
578 self.assertIn("X consent never implies it", offer)
579 self.assertIn("A skip, an unrelated reply or no answer is a no", offer)
580 self.assertIn("setup --reddit-session", offer)
581 self.assertIn("setup --no-reddit-session", offer)
582 self.assertIn("never ask this question", offer.split("\n\n", 2)[1])
583 self.assertIn("REDDIT_SESSION_OFFERED=true", offer)
584
585 def test_reddit_offer_comes_after_the_x_answer_in_both_flows(self):
586 hook = "take the root Reddit session offer route"
587 modal_yes = self.modal.index('"Yes - X cookies + all CLIs"')
588 modal_reddit = self.modal.index(hook, modal_yes)
589 self.assertLess(modal_reddit, self.modal.index('"Skip X - just the CLIs"'))
590 self.assertLess(modal_reddit, self.modal.index("**Step 4"))
591 prose_yes = self.prose.index("On **yes** → run")
592 prose_reddit = self.prose.index(hook, prose_yes)
593 self.assertLess(prose_reddit, self.prose.index("On **no** → run"))
594 self.assertIn("as its own step", self.prose)
595 self.assertIn("separate yes/no", self.prose)
596 # Never folded into the X question itself.
597 x_question = self.prose.split("Otherwise ask. Example:", 1)[1].split("**Wait for the answer.**", 1)[0]
598 self.assertNotIn("reddit", x_question.lower())
599
600 def test_grok_bot_flow_never_offers_the_reddit_session(self):
601 self.assertNotIn("cookie", self.grok.lower())
602 self.assertNotIn("reddit-session", self.grok)
603 self.assertNotIn("Reddit session offer", self.grok)
604
605
606 @pytest.mark.parametrize(
607 ("global_settings", "project_settings", "process_settings", "expected"),
608 [
609 pytest.param("BROWSER_CONSENT=false", "", {}, "not-granted", id="custom-global-refusal"),
610 pytest.param("BROWSER_CONSENT=YES", "", {}, "granted", id="prior-affirmative"),
611 pytest.param("", "", {}, "not-granted", id="no-recorded-consent"),
612 pytest.param(
613 "BROWSER_CONSENT=true\nLAST30DAYS_TRUST_PROJECT_CONFIG=1",
614 "BROWSER_CONSENT=false",
615 {},
616 "not-granted",
617 id="trusted-project-refusal",
618 ),
619 pytest.param(
620 "BROWSER_CONSENT=true",
621 "BROWSER_CONSENT=false\nLAST30DAYS_TRUST_PROJECT_CONFIG=1",
622 {},
623 "granted",
624 id="untrusted-project-refusal-is-ignored",
625 ),
626 pytest.param(
627 "BROWSER_CONSENT=true",
628 "",
629 {"BROWSER_CONSENT": "false"},
630 "not-granted",
631 id="process-refusal",
632 ),
633 pytest.param(
634 "BROWSER_CONSENT=true",
635 "",
636 {"FROM_BROWSER": "off"},
637 "not-granted",
638 id="browser-access-veto",
639 ),
640 pytest.param(
641 "BROWSER_CONSENT=true",
642 "",
643 {"BROWSER_CONSENT": "${user_config.consent}"},
644 "granted",
645 id="placeholder-falls-back",
646 ),
647 ],
648 )
649 def test_resolve_browser_consent_reads_only_configuration(
650 monkeypatch, tmp_path, capsys, global_settings, project_settings, process_settings, expected,
651 ):
652 default_config = Path.home() / ".config" / "last30days" / ".env"
653 default_config.write_text("BROWSER_CONSENT=true\n", encoding="utf-8")
654 config_dir = tmp_path / "active"
655 config_dir.mkdir()
656 global_file = config_dir / ".env"
657 global_file.write_text(global_settings, encoding="utf-8")
658 global_file.chmod(0o600)
659 monkeypatch.setenv("LAST30DAYS_CONFIG_DIR", str(config_dir))
660 monkeypatch.setattr(env, "CONFIG_FILE", global_file)
661 project_dir = tmp_path / "project" / ".claude"
662 project_dir.mkdir(parents=True)
663 project_file = project_dir / "last30days.env"
664 project_file.write_text(project_settings, encoding="utf-8")
665 project_file.chmod(0o600)
666 monkeypatch.chdir(project_dir.parent)
667 for name, value in process_settings.items():
668 monkeypatch.setenv(name, value)
669 monkeypatch.setattr(env, "get_config", lambda **_: pytest.fail("loaded provider credentials"))
670
671 parser = last30days.build_parser()
672 args, extra = parser.parse_known_args(["--resolve-browser-consent"])
673 assert last30days._main(parser, args, extra) == 0
674 assert capsys.readouterr().out == f"{expected}\n"
675 assert global_file.read_text(encoding="utf-8") == global_settings
676 assert project_file.read_text(encoding="utf-8") == project_settings
677
678
679 if __name__ == "__main__":
680 unittest.main()
681
681 lines PYTHON