| 1 |
"""Terminal UI utilities for last30days skill.""" |
| 2 |
|
| 3 |
import sys |
| 4 |
import time |
| 5 |
import threading |
| 6 |
import random |
| 7 |
from typing import Optional |
| 8 |
|
| 9 |
from . import log |
| 10 |
from .render import _skill_version |
| 11 |
|
| 12 |
# Check if we're in a real terminal (not captured by Claude Code) |
| 13 |
try: |
| 14 |
IS_TTY = bool(sys.stderr is not None and sys.stderr.isatty()) |
| 15 |
except OSError: |
| 16 |
IS_TTY = False |
| 17 |
|
| 18 |
|
| 19 |
def _stderr_supports_utf8(stream=None) -> bool: |
| 20 |
"""Return False when stderr declares a non-UTF encoding (e.g. cp1252, ascii).""" |
| 21 |
target = sys.stderr if stream is None else stream |
| 22 |
encoding = getattr(target, "encoding", None) |
| 23 |
if not isinstance(encoding, str) or not encoding: |
| 24 |
return True |
| 25 |
normalized = encoding.lower().replace("_", "-") |
| 26 |
return normalized in ("utf-8", "utf8", "utf-16", "utf16", "utf-32", "utf32") or normalized.startswith("utf-") |
| 27 |
|
| 28 |
|
| 29 |
def _write_stderr(text: str, *, flush: bool = True) -> None: |
| 30 |
log.safe_stderr_write(text, flush=flush) |
| 31 |
|
| 32 |
# ANSI color codes |
| 33 |
class Colors: |
| 34 |
PURPLE = '\033[95m' |
| 35 |
BLUE = '\033[94m' |
| 36 |
CYAN = '\033[96m' |
| 37 |
GREEN = '\033[92m' |
| 38 |
YELLOW = '\033[93m' |
| 39 |
RED = '\033[91m' |
| 40 |
BOLD = '\033[1m' |
| 41 |
DIM = '\033[2m' |
| 42 |
RESET = '\033[0m' |
| 43 |
|
| 44 |
|
| 45 |
BANNER = f"""{Colors.PURPLE}{Colors.BOLD} |
| 46 |
██╗ █████╗ ███████╗████████╗██████╗ ██████╗ ██████╗ █████╗ ██╗ ██╗███████╗ |
| 47 |
██║ ██╔══██╗██╔════╝╚══██╔══╝╚════██╗██╔═████╗██╔══██╗██╔══██╗╚██╗ ██╔╝██╔════╝ |
| 48 |
██║ ███████║███████╗ ██║ █████╔╝██║██╔██║██║ ██║███████║ ╚████╔╝ ███████╗ |
| 49 |
██║ ██╔══██║╚════██║ ██║ ╚═══██╗████╔╝██║██║ ██║██╔══██║ ╚██╔╝ ╚════██║ |
| 50 |
███████╗██║ ██║███████║ ██║ ██████╔╝╚██████╔╝██████╔╝██║ ██║ ██║ ███████║ |
| 51 |
╚══════╝╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝ |
| 52 |
{Colors.RESET}{Colors.DIM} 30 days of research. 30 seconds of work.{Colors.RESET} |
| 53 |
""" |
| 54 |
|
| 55 |
MINI_BANNER = f"""{Colors.PURPLE}{Colors.BOLD}/last30days{Colors.RESET} {Colors.DIM}· researching...{Colors.RESET}""" |
| 56 |
|
| 57 |
# Fun status messages for each phase |
| 58 |
REDDIT_MESSAGES = [ |
| 59 |
"Diving into Reddit threads...", |
| 60 |
"Scanning subreddits for gold...", |
| 61 |
"Reading what Redditors are saying...", |
| 62 |
"Exploring the front page of the internet...", |
| 63 |
"Finding the good discussions...", |
| 64 |
"Upvoting mentally...", |
| 65 |
"Scrolling through comments...", |
| 66 |
] |
| 67 |
|
| 68 |
X_MESSAGES = [ |
| 69 |
"Checking what X is buzzing about...", |
| 70 |
"Reading the timeline...", |
| 71 |
"Finding the hot takes...", |
| 72 |
"Scanning tweets and threads...", |
| 73 |
"Discovering trending insights...", |
| 74 |
"Following the conversation...", |
| 75 |
"Reading between the posts...", |
| 76 |
] |
| 77 |
|
| 78 |
ENRICHING_MESSAGES = [ |
| 79 |
"Getting the juicy details...", |
| 80 |
"Fetching engagement metrics...", |
| 81 |
"Reading top comments...", |
| 82 |
"Extracting insights...", |
| 83 |
"Analyzing discussions...", |
| 84 |
] |
| 85 |
|
| 86 |
YOUTUBE_MESSAGES = [ |
| 87 |
"Searching YouTube for videos...", |
| 88 |
"Finding relevant video content...", |
| 89 |
"Scanning YouTube channels...", |
| 90 |
"Discovering video discussions...", |
| 91 |
"Fetching transcripts...", |
| 92 |
] |
| 93 |
|
| 94 |
TIKTOK_MESSAGES = [ |
| 95 |
"Searching TikTok for trending videos...", |
| 96 |
"Finding what's viral on TikTok...", |
| 97 |
"Scanning TikTok for relevant content...", |
| 98 |
] |
| 99 |
|
| 100 |
INSTAGRAM_MESSAGES = [ |
| 101 |
"Searching Instagram Reels...", |
| 102 |
"Finding what's trending on Instagram...", |
| 103 |
"Scanning Instagram for relevant reels...", |
| 104 |
] |
| 105 |
|
| 106 |
HN_MESSAGES = [ |
| 107 |
"Searching Hacker News...", |
| 108 |
"Scanning HN front page stories...", |
| 109 |
"Finding technical discussions...", |
| 110 |
"Discovering developer conversations...", |
| 111 |
] |
| 112 |
|
| 113 |
POLYMARKET_MESSAGES = [ |
| 114 |
"Checking prediction markets...", |
| 115 |
"Finding what people are betting on...", |
| 116 |
"Scanning Polymarket for odds...", |
| 117 |
"Discovering prediction markets...", |
| 118 |
] |
| 119 |
|
| 120 |
PROCESSING_MESSAGES = [ |
| 121 |
"Crunching the data...", |
| 122 |
"Scoring and ranking...", |
| 123 |
"Finding patterns...", |
| 124 |
"Removing duplicates...", |
| 125 |
"Organizing findings...", |
| 126 |
] |
| 127 |
|
| 128 |
WEB_ONLY_MESSAGES = [ |
| 129 |
"Searching the web...", |
| 130 |
"Finding blogs and docs...", |
| 131 |
"Crawling news sites...", |
| 132 |
"Discovering tutorials...", |
| 133 |
] |
| 134 |
|
| 135 |
SOURCE_COMPLETION_ORDER = [ |
| 136 |
"reddit", |
| 137 |
"x", |
| 138 |
"youtube", |
| 139 |
"tiktok", |
| 140 |
"instagram", |
| 141 |
"hackernews", |
| 142 |
"devto", |
| 143 |
"v2ex", |
| 144 |
"juejin", |
| 145 |
"bluesky", |
| 146 |
"truthsocial", |
| 147 |
"polymarket", |
| 148 |
"grounding", |
| 149 |
"xiaohongshu", |
| 150 |
"digg", |
| 151 |
"arxiv", |
| 152 |
"techmeme", |
| 153 |
"news_rss", |
| 154 |
"trustpilot", |
| 155 |
"amazon", |
| 156 |
"meta_ads", |
| 157 |
] |
| 158 |
|
| 159 |
SOURCE_COMPLETION_META = { |
| 160 |
"reddit": ("Reddit", "thread", "threads", Colors.YELLOW), |
| 161 |
"x": ("X", "post", "posts", Colors.CYAN), |
| 162 |
"youtube": ("YouTube", "video", "videos", Colors.RED), |
| 163 |
"tiktok": ("TikTok", "video", "videos", Colors.PURPLE), |
| 164 |
"instagram": ("Instagram", "reel", "reels", Colors.PURPLE), |
| 165 |
"hackernews": ("HN", "story", "stories", Colors.YELLOW), |
| 166 |
"devto": ("dev.to", "article", "articles", Colors.GREEN), |
| 167 |
"v2ex": ("V2EX", "topic", "topics", Colors.GREEN), |
| 168 |
"juejin": ("Juejin", "article", "articles", Colors.BLUE), |
| 169 |
"bluesky": ("Bluesky", "post", "posts", Colors.BLUE), |
| 170 |
"truthsocial": ("Truth Social", "post", "posts", Colors.CYAN), |
| 171 |
"polymarket": ("Polymarket", "market", "markets", Colors.GREEN), |
| 172 |
"grounding": ("Web", "result", "results", Colors.GREEN), |
| 173 |
"xiaohongshu": ("Xiaohongshu", "post", "posts", Colors.RED), |
| 174 |
"digg": ("Digg", "cluster", "clusters", Colors.YELLOW), |
| 175 |
"arxiv": ("arXiv", "paper", "papers", Colors.RED), |
| 176 |
"techmeme": ("Techmeme", "headline", "headlines", Colors.CYAN), |
| 177 |
"news_rss": ("News RSS", "story", "stories", Colors.CYAN), |
| 178 |
"trustpilot": ("Trustpilot", "review", "reviews", Colors.GREEN), |
| 179 |
"amazon": ("Amazon", "product", "products", Colors.YELLOW), |
| 180 |
"meta_ads": ("Meta Ads", "creative", "creatives", Colors.BLUE), |
| 181 |
} |
| 182 |
|
| 183 |
|
| 184 |
def _completion_sources(source_counts: dict[str, int], display_sources: list[str] | None) -> list[str]: |
| 185 |
requested = list(dict.fromkeys(display_sources or [])) |
| 186 |
if not requested: |
| 187 |
requested = [source for source, count in source_counts.items() if count] |
| 188 |
if not requested and source_counts: |
| 189 |
requested = list(source_counts) |
| 190 |
|
| 191 |
candidate_set = set(requested) | set(source_counts) |
| 192 |
ordered = [source for source in SOURCE_COMPLETION_ORDER if source in candidate_set] |
| 193 |
for source in requested + list(source_counts): |
| 194 |
if source in candidate_set and source not in ordered: |
| 195 |
ordered.append(source) |
| 196 |
return ordered |
| 197 |
|
| 198 |
|
| 199 |
def _format_completion_part(source: str, count: int, tty: bool) -> str: |
| 200 |
label, singular, plural, color = SOURCE_COMPLETION_META.get( |
| 201 |
source, |
| 202 |
(source.replace("_", " ").title(), "result", "results", Colors.RESET), |
| 203 |
) |
| 204 |
unit = singular if count == 1 else plural |
| 205 |
if tty: |
| 206 |
return f"{color}{label}:{Colors.RESET} {count} {unit}" |
| 207 |
return f"{label}: {count} {unit}" |
| 208 |
|
| 209 |
def _build_nux_message(diag: dict = None) -> str: |
| 210 |
"""Build conversational NUX message with dynamic source status.""" |
| 211 |
available = set((diag or {}).get("available_sources", [])) |
| 212 |
if diag: |
| 213 |
reddit = "✓" if "reddit" in available else "✗" |
| 214 |
x = "✓" if "x" in available else "✗" |
| 215 |
youtube = "✓" if "youtube" in available else "✗" |
| 216 |
web = "✓" if "grounding" in available else "✗" |
| 217 |
status_line = f"Reddit {reddit}, X {x}, YouTube {youtube}, Web {web}" |
| 218 |
else: |
| 219 |
status_line = "YouTube ✓, Web ✓, Reddit ✗, X ✗" |
| 220 |
|
| 221 |
return f""" |
| 222 |
I just researched that for you. Here's what I've got right now: |
| 223 |
|
| 224 |
{status_line} |
| 225 |
|
| 226 |
More sources means better research, but it works fine as-is. You can unlock more for free - log into x.com in your browser for X, and run `brew install yt-dlp` for YouTube transcripts. That gives you Reddit (with comments), X, YouTube, HN, and Polymarket - all free. |
| 227 |
|
| 228 |
Some examples of what you can do: |
| 229 |
- "last30 what are people saying about Figma" |
| 230 |
- "last30 watch my biggest competitor every week" |
| 231 |
- "last30 watch AI video tools monthly" |
| 232 |
- "last30 what have you found about AI video?" |
| 233 |
|
| 234 |
Just start with "last30" and talk to me like normal. |
| 235 |
""" |
| 236 |
|
| 237 |
# Shorter promo for single missing key |
| 238 |
PROMO_SINGLE_KEY = { |
| 239 |
"reddit": "\n💡 Unlock TikTok and Instagram with SCRAPECREATORS_API_KEY - 10,000 free calls, no CC - scrapecreators.com\n", |
| 240 |
"x": "\n💡 Unlock X: log into x.com in your browser, then re-run. " |
| 241 |
"Firefox works on all platforms. Safari works on macOS (detected automatically). " |
| 242 |
"Chrome, Brave, Edge, Arc, Dia, Vivaldi, Opera, or Chromium on macOS require " |
| 243 |
"FROM_BROWSER=auto in .env (Keychain dialog). On Windows only Firefox is supported. " |
| 244 |
"Or add AUTH_TOKEN/CT0 or XAI_API_KEY.\n", |
| 245 |
"web": "\n💡 You can unlock native grounded web search with BRAVE_API_KEY or SERPER_API_KEY.\n", |
| 246 |
} |
| 247 |
|
| 248 |
# Bird auth help (for local users with vendored Bird CLI) |
| 249 |
BIRD_AUTH_HELP = f""" |
| 250 |
{Colors.YELLOW}Bird authentication failed.{Colors.RESET} |
| 251 |
|
| 252 |
To fix this: |
| 253 |
1. Add AUTH_TOKEN and CT0 to ~/.config/last30days/.env, or to trusted .claude/last30days.env with LAST30DAYS_TRUST_PROJECT_CONFIG=1 |
| 254 |
2. Or set XAI_API_KEY for the xAI fallback backend |
| 255 |
""" |
| 256 |
|
| 257 |
BIRD_AUTH_HELP_PLAIN = """ |
| 258 |
Bird authentication failed. |
| 259 |
|
| 260 |
To fix this: |
| 261 |
1. Add AUTH_TOKEN and CT0 to ~/.config/last30days/.env, or to trusted .claude/last30days.env with LAST30DAYS_TRUST_PROJECT_CONFIG=1 |
| 262 |
2. Or set XAI_API_KEY for the xAI fallback backend |
| 263 |
""" |
| 264 |
|
| 265 |
# Spinner frames |
| 266 |
SPINNER_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'] |
| 267 |
ASCII_SPINNER_FRAMES = ['|', '/', '-', '\\'] |
| 268 |
DOTS_FRAMES = [' ', '. ', '.. ', '...'] |
| 269 |
|
| 270 |
|
| 271 |
class Spinner: |
| 272 |
"""Animated spinner for long-running operations.""" |
| 273 |
|
| 274 |
def __init__(self, message: str = "Working", color: str = Colors.CYAN, quiet: bool = False): |
| 275 |
self.message = message |
| 276 |
self.color = color |
| 277 |
self.running = False |
| 278 |
self.thread: Optional[threading.Thread] = None |
| 279 |
self.frame_idx = 0 |
| 280 |
self.shown_static = False |
| 281 |
self.quiet = quiet # Suppress non-TTY start message (still shows ✓ completion) |
| 282 |
|
| 283 |
def _spin(self): |
| 284 |
frames = SPINNER_FRAMES if _stderr_supports_utf8() else ASCII_SPINNER_FRAMES |
| 285 |
while self.running: |
| 286 |
frame = frames[self.frame_idx % len(frames)] |
| 287 |
_write_stderr(f"\r{self.color}{frame}{Colors.RESET} {self.message} ") |
| 288 |
self.frame_idx += 1 |
| 289 |
time.sleep(0.08) |
| 290 |
|
| 291 |
def start(self): |
| 292 |
self.running = True |
| 293 |
if IS_TTY: |
| 294 |
# Real terminal - animate |
| 295 |
self.thread = threading.Thread(target=self._spin, daemon=True) |
| 296 |
self.thread.start() |
| 297 |
else: |
| 298 |
# Not a TTY (Claude Code) - just print once |
| 299 |
if not self.shown_static and not self.quiet: |
| 300 |
prefix = "⏳" if _stderr_supports_utf8() else "->" |
| 301 |
_write_stderr(f"{prefix} {self.message}\n") |
| 302 |
self.shown_static = True |
| 303 |
|
| 304 |
def update(self, message: str): |
| 305 |
self.message = message |
| 306 |
if not IS_TTY and not self.shown_static: |
| 307 |
# Print update in non-TTY mode |
| 308 |
prefix = "⏳" if _stderr_supports_utf8() else "->" |
| 309 |
_write_stderr(f"{prefix} {message}\n") |
| 310 |
|
| 311 |
def stop(self, final_message: str = ""): |
| 312 |
self.running = False |
| 313 |
if self.thread: |
| 314 |
self.thread.join(timeout=0.2) |
| 315 |
if IS_TTY: |
| 316 |
# Clear the line in real terminal |
| 317 |
_write_stderr("\r" + " " * 80 + "\r", flush=not final_message) |
| 318 |
if final_message: |
| 319 |
ok_glyph = "✓" if _stderr_supports_utf8() else "[ok]" |
| 320 |
_write_stderr(f"{ok_glyph} {final_message}\n") |
| 321 |
|
| 322 |
|
| 323 |
class ProgressDisplay: |
| 324 |
"""Progress display for research phases.""" |
| 325 |
|
| 326 |
def __init__(self, topic: str, show_banner: bool = True): |
| 327 |
self.topic = topic |
| 328 |
self.spinner: Optional[Spinner] = None |
| 329 |
self.start_time = time.time() |
| 330 |
|
| 331 |
if show_banner: |
| 332 |
self._show_banner() |
| 333 |
|
| 334 |
def _show_banner(self): |
| 335 |
utf8 = _stderr_supports_utf8() |
| 336 |
if IS_TTY: |
| 337 |
banner = ( |
| 338 |
MINI_BANNER |
| 339 |
if utf8 |
| 340 |
else f"{Colors.PURPLE}{Colors.BOLD}/last30days{Colors.RESET} {Colors.DIM}- researching...{Colors.RESET}" |
| 341 |
) |
| 342 |
_write_stderr( |
| 343 |
banner + "\n" |
| 344 |
+ f"{Colors.DIM}Topic: {Colors.RESET}{Colors.BOLD}{self.topic}{Colors.RESET}\n\n" |
| 345 |
) |
| 346 |
else: |
| 347 |
# Simple text for non-TTY |
| 348 |
sep = "·" if utf8 else "-" |
| 349 |
_write_stderr(f"/last30days {sep} researching: {self.topic}\n") |
| 350 |
|
| 351 |
def start_reddit(self): |
| 352 |
msg = random.choice(REDDIT_MESSAGES) |
| 353 |
self.spinner = Spinner(f"{Colors.YELLOW}Reddit{Colors.RESET} {msg}", Colors.YELLOW) |
| 354 |
self.spinner.start() |
| 355 |
|
| 356 |
def end_reddit(self, count: int): |
| 357 |
if self.spinner: |
| 358 |
self.spinner.stop(f"{Colors.YELLOW}Reddit{Colors.RESET} Found {count} threads") |
| 359 |
|
| 360 |
def start_reddit_enrich(self, current: int, total: int): |
| 361 |
if self.spinner: |
| 362 |
self.spinner.stop() |
| 363 |
msg = random.choice(ENRICHING_MESSAGES) |
| 364 |
self.spinner = Spinner(f"{Colors.YELLOW}Reddit{Colors.RESET} [{current}/{total}] {msg}", Colors.YELLOW) |
| 365 |
self.spinner.start() |
| 366 |
|
| 367 |
def update_reddit_enrich(self, current: int, total: int): |
| 368 |
if self.spinner: |
| 369 |
msg = random.choice(ENRICHING_MESSAGES) |
| 370 |
self.spinner.update(f"{Colors.YELLOW}Reddit{Colors.RESET} [{current}/{total}] {msg}") |
| 371 |
|
| 372 |
def end_reddit_enrich(self): |
| 373 |
if self.spinner: |
| 374 |
self.spinner.stop(f"{Colors.YELLOW}Reddit{Colors.RESET} Enriched with engagement data") |
| 375 |
|
| 376 |
def start_x(self): |
| 377 |
msg = random.choice(X_MESSAGES) |
| 378 |
self.spinner = Spinner(f"{Colors.CYAN}X{Colors.RESET} {msg}", Colors.CYAN) |
| 379 |
self.spinner.start() |
| 380 |
|
| 381 |
def end_x(self, count: int): |
| 382 |
if self.spinner: |
| 383 |
self.spinner.stop(f"{Colors.CYAN}X{Colors.RESET} Found {count} posts") |
| 384 |
|
| 385 |
def start_youtube(self): |
| 386 |
msg = random.choice(YOUTUBE_MESSAGES) |
| 387 |
self.spinner = Spinner(f"{Colors.RED}YouTube{Colors.RESET} {msg}", Colors.RED) |
| 388 |
self.spinner.start() |
| 389 |
|
| 390 |
def end_youtube(self, count: int): |
| 391 |
if self.spinner: |
| 392 |
self.spinner.stop(f"{Colors.RED}YouTube{Colors.RESET} Found {count} videos") |
| 393 |
|
| 394 |
def start_tiktok(self): |
| 395 |
msg = random.choice(TIKTOK_MESSAGES) |
| 396 |
self.spinner = Spinner(f"{Colors.PURPLE}TikTok{Colors.RESET} {msg}", Colors.PURPLE) |
| 397 |
self.spinner.start() |
| 398 |
|
| 399 |
def end_tiktok(self, count: int): |
| 400 |
if self.spinner: |
| 401 |
self.spinner.stop(f"{Colors.PURPLE}TikTok{Colors.RESET} Found {count} videos") |
| 402 |
|
| 403 |
def start_instagram(self): |
| 404 |
msg = random.choice(INSTAGRAM_MESSAGES) |
| 405 |
self.spinner = Spinner(f"{Colors.PURPLE}Instagram{Colors.RESET} {msg}", Colors.PURPLE) |
| 406 |
self.spinner.start() |
| 407 |
|
| 408 |
def end_instagram(self, count: int): |
| 409 |
if self.spinner: |
| 410 |
self.spinner.stop(f"{Colors.PURPLE}Instagram{Colors.RESET} Found {count} reels") |
| 411 |
|
| 412 |
def start_hackernews(self): |
| 413 |
msg = random.choice(HN_MESSAGES) |
| 414 |
self.spinner = Spinner(f"{Colors.YELLOW}HN{Colors.RESET} {msg}", Colors.YELLOW, quiet=True) |
| 415 |
self.spinner.start() |
| 416 |
|
| 417 |
def end_hackernews(self, count: int): |
| 418 |
if self.spinner: |
| 419 |
self.spinner.stop(f"{Colors.YELLOW}HN{Colors.RESET} Found {count} stories") |
| 420 |
|
| 421 |
def start_polymarket(self): |
| 422 |
msg = random.choice(POLYMARKET_MESSAGES) |
| 423 |
self.spinner = Spinner(f"{Colors.GREEN}Polymarket{Colors.RESET} {msg}", Colors.GREEN, quiet=True) |
| 424 |
self.spinner.start() |
| 425 |
|
| 426 |
def end_polymarket(self, count: int): |
| 427 |
if self.spinner: |
| 428 |
self.spinner.stop(f"{Colors.GREEN}Polymarket{Colors.RESET} Found {count} markets") |
| 429 |
|
| 430 |
def start_processing(self): |
| 431 |
msg = random.choice(PROCESSING_MESSAGES) |
| 432 |
self.spinner = Spinner(f"{Colors.PURPLE}Processing{Colors.RESET} {msg}", Colors.PURPLE) |
| 433 |
self.spinner.start() |
| 434 |
|
| 435 |
def end_processing(self): |
| 436 |
if self.spinner: |
| 437 |
self.spinner.stop() |
| 438 |
|
| 439 |
def show_complete( |
| 440 |
self, |
| 441 |
reddit_count: int = 0, |
| 442 |
x_count: int = 0, |
| 443 |
youtube_count: int = 0, |
| 444 |
hn_count: int = 0, |
| 445 |
pm_count: int = 0, |
| 446 |
tiktok_count: int = 0, |
| 447 |
ig_count: int = 0, |
| 448 |
*, |
| 449 |
source_counts: dict[str, int] | None = None, |
| 450 |
display_sources: list[str] | None = None, |
| 451 |
): |
| 452 |
elapsed = time.time() - self.start_time |
| 453 |
if source_counts is None: |
| 454 |
source_counts = { |
| 455 |
"reddit": reddit_count, |
| 456 |
"x": x_count, |
| 457 |
"youtube": youtube_count, |
| 458 |
"tiktok": tiktok_count, |
| 459 |
"instagram": ig_count, |
| 460 |
"hackernews": hn_count, |
| 461 |
"polymarket": pm_count, |
| 462 |
} |
| 463 |
if display_sources is None: |
| 464 |
display_sources = [source for source, count in source_counts.items() if count] |
| 465 |
if not display_sources: |
| 466 |
display_sources = ["reddit", "x"] |
| 467 |
|
| 468 |
ordered_sources = _completion_sources(source_counts, display_sources) |
| 469 |
parts = [ |
| 470 |
_format_completion_part(source, source_counts.get(source, 0), tty=IS_TTY) |
| 471 |
for source in ordered_sources |
| 472 |
] |
| 473 |
ok_glyph = "✓" if _stderr_supports_utf8() else "[ok]" |
| 474 |
if IS_TTY: |
| 475 |
_write_stderr( |
| 476 |
f"\n{Colors.GREEN}{Colors.BOLD}{ok_glyph} Research complete{Colors.RESET} " |
| 477 |
f"{Colors.DIM}({elapsed:.1f}s){Colors.RESET}\n" |
| 478 |
+ " " + " ".join(parts) |
| 479 |
+ "\n\n" |
| 480 |
) |
| 481 |
else: |
| 482 |
_write_stderr(f"{ok_glyph} Research complete ({elapsed:.1f}s) - {', '.join(parts)}\n") |
| 483 |
|
| 484 |
def show_cached(self, age_hours: float = None): |
| 485 |
if age_hours is not None: |
| 486 |
age_str = f" ({age_hours:.1f}h old)" |
| 487 |
else: |
| 488 |
age_str = "" |
| 489 |
bolt = "⚡" if _stderr_supports_utf8() else "*" |
| 490 |
_write_stderr(f"{Colors.GREEN}{bolt}{Colors.RESET} {Colors.DIM}Using cached results{age_str} - use --refresh for fresh data{Colors.RESET}\n\n") |
| 491 |
|
| 492 |
def show_error(self, message: str): |
| 493 |
err_glyph = "✗" if _stderr_supports_utf8() else "[x]" |
| 494 |
_write_stderr(f"{Colors.RED}{err_glyph} Error:{Colors.RESET} {message}\n") |
| 495 |
|
| 496 |
def start_web_only(self): |
| 497 |
"""Show web-only mode indicator.""" |
| 498 |
msg = random.choice(WEB_ONLY_MESSAGES) |
| 499 |
self.spinner = Spinner(f"{Colors.GREEN}Web{Colors.RESET} {msg}", Colors.GREEN) |
| 500 |
self.spinner.start() |
| 501 |
|
| 502 |
def end_web_only(self): |
| 503 |
"""End web-only spinner.""" |
| 504 |
if self.spinner: |
| 505 |
self.spinner.stop(f"{Colors.GREEN}Web{Colors.RESET} assistant will search the web") |
| 506 |
|
| 507 |
def show_web_only_complete(self): |
| 508 |
"""Show completion for web-only mode.""" |
| 509 |
elapsed = time.time() - self.start_time |
| 510 |
ok_glyph = "✓" if _stderr_supports_utf8() else "[ok]" |
| 511 |
if IS_TTY: |
| 512 |
_write_stderr( |
| 513 |
f"\n{Colors.GREEN}{Colors.BOLD}{ok_glyph} Ready for web search{Colors.RESET} " |
| 514 |
f"{Colors.DIM}({elapsed:.1f}s){Colors.RESET}\n" |
| 515 |
f" {Colors.GREEN}Web:{Colors.RESET} assistant will search blogs, docs & news\n\n" |
| 516 |
) |
| 517 |
else: |
| 518 |
_write_stderr(f"{ok_glyph} Ready for web search ({elapsed:.1f}s)\n") |
| 519 |
|
| 520 |
def show_promo(self, missing: str = "both", diag: dict = None): |
| 521 |
"""Show NUX / promotional message for missing API keys. |
| 522 |
|
| 523 |
Args: |
| 524 |
missing: 'both', 'all', 'reddit', or 'x' - which keys are missing |
| 525 |
diag: Optional diagnostics dict for dynamic source status |
| 526 |
""" |
| 527 |
text = "" |
| 528 |
if missing in ("both", "all"): |
| 529 |
text = _build_nux_message(diag) |
| 530 |
elif missing in PROMO_SINGLE_KEY: |
| 531 |
text = PROMO_SINGLE_KEY[missing] |
| 532 |
if text: |
| 533 |
if not _stderr_supports_utf8(): |
| 534 |
text = text.replace("✓", "[ok]").replace("✗", "[x]").replace("💡", "Tip:") |
| 535 |
_write_stderr(text) |
| 536 |
|
| 537 |
def show_bird_auth_help(self): |
| 538 |
"""Show Bird authentication help.""" |
| 539 |
if IS_TTY: |
| 540 |
_write_stderr(BIRD_AUTH_HELP) |
| 541 |
else: |
| 542 |
_write_stderr(BIRD_AUTH_HELP_PLAIN) |
| 543 |
|
| 544 |
|
| 545 |
def show_diagnostic_banner(diag: dict): |
| 546 |
"""Show pre-flight source status banner when sources are missing. |
| 547 |
|
| 548 |
Args: |
| 549 |
diag: Dict from pipeline.diagnose() with available_sources, x_backend, |
| 550 |
bird status, provider availability, and native web backend info. |
| 551 |
""" |
| 552 |
available_sources = set(diag.get("available_sources") or []) |
| 553 |
has_reddit = "reddit" in available_sources |
| 554 |
has_scrapecreators = diag.get("has_scrapecreators", False) |
| 555 |
has_x = "x" in available_sources |
| 556 |
has_youtube = "youtube" in available_sources |
| 557 |
has_web = "grounding" in available_sources |
| 558 |
has_xiaohongshu = "xiaohongshu" in available_sources |
| 559 |
x_backend = diag.get("x_backend") |
| 560 |
native_web_backend = diag.get("native_web_backend") |
| 561 |
|
| 562 |
# If everything is available, no banner needed |
| 563 |
if has_reddit and has_x and has_youtube and has_web: |
| 564 |
return |
| 565 |
|
| 566 |
lines = [] |
| 567 |
utf8 = _stderr_supports_utf8() |
| 568 |
ok_mark = "✅" if utf8 else "[ok]" |
| 569 |
err_mark = "❌" if utf8 else "[x]" |
| 570 |
warn_mark = "⚡" if utf8 else "[!]" |
| 571 |
dash = "—" if utf8 else "-" |
| 572 |
branch = "└─" if utf8 else "->" |
| 573 |
top = "┌─────────────────────────────────────────────────────┐" if utf8 else "+-----------------------------------------------------+" |
| 574 |
bot = "└─────────────────────────────────────────────────────┘" if utf8 else "+-----------------------------------------------------+" |
| 575 |
bar = "│" if utf8 else "|" |
| 576 |
|
| 577 |
if IS_TTY: |
| 578 |
lines.append(f"{Colors.DIM}{top}{Colors.RESET}") |
| 579 |
_header = f"/last30days v{_skill_version()} - Source Status" |
| 580 |
lines.append(f"{Colors.DIM}{bar}{Colors.RESET} {Colors.BOLD}{_header}{Colors.RESET}{' ' * (52 - len(_header))}{Colors.DIM}{bar}{Colors.RESET}") |
| 581 |
lines.append(f"{Colors.DIM}{bar}{Colors.RESET} {Colors.DIM}{bar}{Colors.RESET}") |
| 582 |
|
| 583 |
# Reddit |
| 584 |
if has_reddit and has_scrapecreators: |
| 585 |
lines.append(f"{Colors.DIM}{bar}{Colors.RESET} {Colors.GREEN}{ok_mark} Reddit{Colors.RESET} {dash} full threads with comments {Colors.DIM}{bar}{Colors.RESET}") |
| 586 |
elif has_reddit: |
| 587 |
lines.append(f"{Colors.DIM}{bar}{Colors.RESET} {Colors.GREEN}{ok_mark} Reddit{Colors.RESET} {dash} public threads (titles + scores) {Colors.DIM}{bar}{Colors.RESET}") |
| 588 |
else: |
| 589 |
lines.append(f"{Colors.DIM}{bar}{Colors.RESET} {Colors.RED}{err_mark} Reddit{Colors.RESET} {dash} unavailable {Colors.DIM}{bar}{Colors.RESET}") |
| 590 |
|
| 591 |
# X/Twitter |
| 592 |
if has_x: |
| 593 |
username = diag.get("bird_username", "") |
| 594 |
label = f"Bird ({username})" if x_backend == "bird" and username else str(x_backend or "xai").upper() |
| 595 |
lines.append(f"{Colors.DIM}{bar}{Colors.RESET} {Colors.GREEN}{ok_mark} X/Twitter{Colors.RESET} {dash} {label} {Colors.DIM}{bar}{Colors.RESET}") |
| 596 |
else: |
| 597 |
lines.append(f"{Colors.DIM}{bar}{Colors.RESET} {Colors.RED}{err_mark} X/Twitter{Colors.RESET} {dash} No X auth or fallback key {Colors.DIM}{bar}{Colors.RESET}") |
| 598 |
if diag.get("bird_installed"): |
| 599 |
lines.append(f"{Colors.DIM}{bar}{Colors.RESET} {branch} Add AUTH_TOKEN/CT0 or XAI_API_KEY {Colors.DIM}{bar}{Colors.RESET}") |
| 600 |
else: |
| 601 |
lines.append(f"{Colors.DIM}{bar}{Colors.RESET} {branch} Needs Node.js 22+ (Bird is bundled) {Colors.DIM}{bar}{Colors.RESET}") |
| 602 |
|
| 603 |
# YouTube |
| 604 |
if has_youtube: |
| 605 |
lines.append(f"{Colors.DIM}{bar}{Colors.RESET} {Colors.GREEN}{ok_mark} YouTube{Colors.RESET} {dash} yt-dlp found {Colors.DIM}{bar}{Colors.RESET}") |
| 606 |
else: |
| 607 |
lines.append(f"{Colors.DIM}{bar}{Colors.RESET} {Colors.RED}{err_mark} YouTube{Colors.RESET} {dash} yt-dlp not installed {Colors.DIM}{bar}{Colors.RESET}") |
| 608 |
lines.append(f"{Colors.DIM}{bar}{Colors.RESET} {branch} Fix: brew install yt-dlp (free) {Colors.DIM}{bar}{Colors.RESET}") |
| 609 |
|
| 610 |
# Xiaohongshu (only show when configured) |
| 611 |
if has_xiaohongshu: |
| 612 |
lines.append(f"{Colors.DIM}{bar}{Colors.RESET} {Colors.GREEN}{ok_mark} Xiaohongshu{Colors.RESET} {dash} API connected + logged in {Colors.DIM}{bar}{Colors.RESET}") |
| 613 |
|
| 614 |
# Web |
| 615 |
if has_web: |
| 616 |
backend = native_web_backend or "native" |
| 617 |
lines.append(f"{Colors.DIM}{bar}{Colors.RESET} {Colors.GREEN}{ok_mark} Web{Colors.RESET} {dash} {backend} API {Colors.DIM}{bar}{Colors.RESET}") |
| 618 |
else: |
| 619 |
lines.append(f"{Colors.DIM}{bar}{Colors.RESET} {Colors.YELLOW}{warn_mark} Web{Colors.RESET} {dash} Add BRAVE_API_KEY or SERPER_API_KEY {Colors.DIM}{bar}{Colors.RESET}") |
| 620 |
|
| 621 |
lines.append(f"{Colors.DIM}{bar}{Colors.RESET} {Colors.DIM}{bar}{Colors.RESET}") |
| 622 |
lines.append(f"{Colors.DIM}{bar}{Colors.RESET} Config: {Colors.BOLD}~/.config/last30days/.env{Colors.RESET} {Colors.DIM}{bar}{Colors.RESET}") |
| 623 |
lines.append(f"{Colors.DIM}{bot}{Colors.RESET}") |
| 624 |
else: |
| 625 |
# Plain text for non-TTY (Claude Code / Codex) |
| 626 |
lines.append(top) |
| 627 |
_header_plain = f"/last30days v{_skill_version()} - Source Status" |
| 628 |
lines.append(f"{bar} {_header_plain}{' ' * (52 - len(_header_plain))}{bar}") |
| 629 |
lines.append(f"{bar} {bar}") |
| 630 |
|
| 631 |
if has_reddit and has_scrapecreators: |
| 632 |
lines.append(f"{bar} {ok_mark} Reddit {dash} full threads with comments {bar}") |
| 633 |
elif has_reddit: |
| 634 |
lines.append(f"{bar} {ok_mark} Reddit {dash} public threads (titles + scores) {bar}") |
| 635 |
else: |
| 636 |
lines.append(f"{bar} {err_mark} Reddit {dash} unavailable {bar}") |
| 637 |
|
| 638 |
if has_x: |
| 639 |
lines.append(f"{bar} {ok_mark} X/Twitter {dash} available {bar}") |
| 640 |
else: |
| 641 |
lines.append(f"{bar} {err_mark} X/Twitter {dash} No X auth or fallback key {bar}") |
| 642 |
if diag.get("bird_installed"): |
| 643 |
lines.append(f"{bar} {branch} Add AUTH_TOKEN/CT0 or XAI_API_KEY {bar}") |
| 644 |
else: |
| 645 |
lines.append(f"{bar} {branch} Needs Node.js 22+ (Bird is bundled) {bar}") |
| 646 |
|
| 647 |
if has_youtube: |
| 648 |
lines.append(f"{bar} {ok_mark} YouTube {dash} yt-dlp found {bar}") |
| 649 |
else: |
| 650 |
lines.append(f"{bar} {err_mark} YouTube {dash} yt-dlp not installed {bar}") |
| 651 |
lines.append(f"{bar} {branch} Fix: brew install yt-dlp (free) {bar}") |
| 652 |
|
| 653 |
if has_xiaohongshu: |
| 654 |
lines.append(f"{bar} {ok_mark} Xiaohongshu {dash} API connected + logged in {bar}") |
| 655 |
|
| 656 |
if has_web: |
| 657 |
backend = native_web_backend or "native" |
| 658 |
lines.append(f"{bar} {ok_mark} Web {dash} {backend} API available{' ' * max(0, 13 - len(backend))}{bar}") |
| 659 |
else: |
| 660 |
lines.append(f"{bar} {warn_mark} Web {dash} Add BRAVE_API_KEY or SERPER_API_KEY {bar}") |
| 661 |
|
| 662 |
lines.append(f"{bar} {bar}") |
| 663 |
lines.append(f"{bar} Config: ~/.config/last30days/.env {bar}") |
| 664 |
lines.append(bot) |
| 665 |
|
| 666 |
_write_stderr("\n".join(lines) + "\n\n") |
| 667 |
|
| 668 |
|
| 669 |
def print_phase(phase: str, message: str): |
| 670 |
"""Print a phase message.""" |
| 671 |
colors = { |
| 672 |
"reddit": Colors.YELLOW, |
| 673 |
"x": Colors.CYAN, |
| 674 |
"process": Colors.PURPLE, |
| 675 |
"done": Colors.GREEN, |
| 676 |
"error": Colors.RED, |
| 677 |
} |
| 678 |
color = colors.get(phase, Colors.RESET) |
| 679 |
arrow = "▸" if _stderr_supports_utf8() else "->" |
| 680 |
_write_stderr(f"{color}{arrow}{Colors.RESET} {message}\n") |
| 681 |
|