From 8daa2adb3952db7c4aeeed78b2967ada138c02ce Mon Sep 17 00:00:00 2001 From: axsddlr Date: Sat, 31 Oct 2026 06:09:48 -0400 Subject: [PATCH 1/6] fix(client): honour an explicit --max for followers/following (issue #50) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `_fetch_user_list` clamped the requested count to `self._max_count`, which comes from `rateLimit.maxCount` (default 200) and was additionally bounded by a hard `_ABSOLUTE_MAX_COUNT = 500`. The cursor pagination underneath was correct, so an account with more followers than that was silently truncated no matter what `--max` said. Treat `rateLimit.maxCount` as a default for calls that do not specify a count, not as a ceiling on an explicit request, and clamp only at the safety ceiling. Raise that ceiling from 500 to 10000 — it exists to stop a typo or a runaway config, not to cap legitimate requests — and log a warning when it engages so the truncation is visible instead of silent. Tweets are left clamping to the configured `maxCount`; this issue is about user lists, and changing timeline behaviour is out of scope here. Tests cover 600 users via an explicit --max (the old 500 ceiling), 300 users against a 200 config default, the safety ceiling, and non-positive counts. A negative control run against the previous client.py fails 4 of the 5. --- config.yaml | 2 +- tests/test_pagination_cap.py | 134 +++++++++++++++++++++++++++++++++++ twitter_cli/client.py | 24 +++++-- 3 files changed, 155 insertions(+), 5 deletions(-) create mode 100644 tests/test_pagination_cap.py diff --git a/config.yaml b/config.yaml index 0a62952..11e3251 100644 --- a/config.yaml +++ b/config.yaml @@ -18,4 +18,4 @@ rateLimit: requestDelay: 1.5 # seconds between paginated requests maxRetries: 3 # retry count on 429 / rate-limit errors retryBaseDelay: 5.0 # base delay for exponential backoff (seconds) - maxCount: 200 # hard cap for single fetch + maxCount: 200 # default cap for a single fetch; an explicit --max may exceed it diff --git a/tests/test_pagination_cap.py b/tests/test_pagination_cap.py new file mode 100644 index 0000000..5f304b8 --- /dev/null +++ b/tests/test_pagination_cap.py @@ -0,0 +1,134 @@ +"""Followers/following pagination must honour an explicit --max (issue #50). + +`_fetch_user_list` used to clamp the requested count to ``self._max_count``, +which is derived from the ``rateLimit.maxCount`` config (default 200) and was +additionally bounded by a hard 500 ceiling. The pagination loop itself was +correct, so large accounts were silently truncated regardless of ``--max``. +""" + +from __future__ import annotations + +from types import SimpleNamespace + +from twitter_cli import client as client_mod +from twitter_cli.client import _ABSOLUTE_MAX_COUNT, TwitterClient + + +class _StubClient(TwitterClient): + """Client whose GraphQL calls are fully stubbed.""" + + def __init__(self): + self._auth_token = "t" + self._ct0 = "c" + self._cookie_string = None + self._client_transaction = None + self._ct_init_attempted = True + self._max_count = 200 # the configured default that used to clamp + self._request_delay = 0.0 + self._max_retries = 0 + self.pages_requested = 0 + + +def _instructions(user_ids, cursor=None): + """One page of user entries plus an optional bottom cursor.""" + entries = [] + for index, uid in enumerate(user_ids): + entries.append( + { + "content": { + "entryType": "TimelineTimelineItem", + "itemContent": {"user_results": {"result": {"rest_id": uid}}}, + } + } + ) + if cursor: + entries.append( + { + "content": { + "entryType": "TimelineTimelineCursor", + "cursorType": "Bottom", + "value": cursor, + } + } + ) + return [{"entries": entries}] + + +def _make_paged_client(monkeypatch, page_size=20, total_pages=40): + """Return a client that serves `total_pages` full pages then stops.""" + stub = _StubClient() + state = {"page": 0} + + def fake_graphql_get(operation_name, variables, features, field_toggles=None): + index = state["page"] + state["page"] += 1 + stub.pages_requested += 1 + ids = ["u%d" % (index * page_size + i) for i in range(page_size)] + has_more = index + 1 < total_pages + return { + "instructions": _instructions( + ids, cursor="cursor-%d" % (index + 1) if has_more else None + ) + } + + monkeypatch.setattr(stub, "_graphql_get", fake_graphql_get) + monkeypatch.setattr(stub, "_graphql_post", fake_graphql_get) + monkeypatch.setattr( + client_mod, + "parse_user_result", + lambda result: SimpleNamespace(id=result.get("rest_id")) if result.get("rest_id") else None, + ) + return stub + + +def test_explicit_max_beyond_old_500_cap_is_fetched(monkeypatch) -> None: + """600 users must be retrievable; the old ceiling stopped at 500.""" + stub = _make_paged_client(monkeypatch, page_size=20, total_pages=40) + + users = stub._fetch_user_list( + "Followers", "123", 600, lambda data: data.get("instructions") + ) + + assert len(users) == 600 + assert stub.pages_requested >= 30 + + +def test_explicit_max_ignores_configured_default(monkeypatch) -> None: + """A config default of 200 must not truncate an explicit --max of 300.""" + stub = _make_paged_client(monkeypatch, page_size=20, total_pages=40) + + users = stub._fetch_user_list( + "Following", "123", 300, lambda data: data.get("instructions") + ) + + assert len(users) == 300 + + +def test_safety_ceiling_still_applies(monkeypatch, caplog) -> None: + """An absurd request is capped at the safety ceiling, not unbounded.""" + stub = _StubClient() + requested = {} + + def fake_graphql_get(operation_name, variables, features, field_toggles=None): + requested["count"] = requested.get("count", 0) + 1 + # Single page then stop, so we observe the clamp without 500 pages. + return {"instructions": _instructions(["u1"])} + + monkeypatch.setattr(stub, "_graphql_get", fake_graphql_get) + monkeypatch.setattr(client_mod, "parse_user_result", lambda r: SimpleNamespace(id="u1")) + + with caplog.at_level("WARNING"): + stub._fetch_user_list("Followers", "1", _ABSOLUTE_MAX_COUNT + 5000, lambda d: d["instructions"]) + + assert "exceeds the safety ceiling" in caplog.text + + +def test_zero_or_negative_count_returns_empty(monkeypatch) -> None: + stub = _make_paged_client(monkeypatch) + assert stub._fetch_user_list("Followers", "1", 0, lambda d: d["instructions"]) == [] + assert stub._fetch_user_list("Followers", "1", -5, lambda d: d["instructions"]) == [] + + +def test_ceiling_is_large_enough_for_real_accounts() -> None: + """Regression guard: the ceiling must stay well above the old 500.""" + assert _ABSOLUTE_MAX_COUNT >= 5000 diff --git a/twitter_cli/client.py b/twitter_cli/client.py index 0436c8e..65a597c 100644 --- a/twitter_cli/client.py +++ b/twitter_cli/client.py @@ -68,8 +68,12 @@ TimelineInstructionGetter = Callable[[Any], Any] -# Hard ceiling to prevent accidental massive fetches -_ABSOLUTE_MAX_COUNT = 500 +# Hard ceiling to prevent accidental massive fetches. This is a safety valve +# against a typo or a runaway config, not a policy limit: an explicit --max is +# honoured up to here. User lists (followers/following) are paginated cursors +# and are the main reason this is above the old 500, which silently truncated +# requests for larger accounts (issue #50). +_ABSOLUTE_MAX_COUNT = 10000 # ── Session management ─────────────────────────────────────────────────── @@ -826,10 +830,22 @@ def _fetch_timeline(self, operation_name, count, get_instructions, extra_variabl def _fetch_user_list(self, operation_name, user_id, count, get_instructions, use_post=False): # type: (str, str, int, Callable[[Any], Any], bool) -> List[UserProfile] - """Generic user list fetcher (for followers/following) with pagination.""" + """Generic user list fetcher (for followers/following) with pagination. + + An explicit request is honoured up to ``_ABSOLUTE_MAX_COUNT``. The + configured ``rateLimit.maxCount`` is a *default* for calls that do not + specify a count, not a ceiling on an explicit ``--max``: clamping here + used to silently truncate large accounts at 500 users (issue #50). + """ if count <= 0: return [] - count = min(count, self._max_count) + if count > _ABSOLUTE_MAX_COUNT: + logger.warning( + "Requested %d users exceeds the safety ceiling; fetching %d", + count, + _ABSOLUTE_MAX_COUNT, + ) + count = _ABSOLUTE_MAX_COUNT users = [] # type: List[UserProfile] seen_ids = set() # type: Set[str] cursor = None # type: Optional[str] From 40c1d250f84cfd46e9319fd129e0678683604e6a Mon Sep 17 00:00:00 2001 From: axsddlr Date: Sat, 31 Oct 2026 06:13:00 -0400 Subject: [PATCH 2/6] feat(cli): add --time to choose timestamp style (issue #35) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Human-readable output hard-coded relative timestamps ("14d ago"), which is awkward when you need to know *when* something was posted. Add a root `--time {relative,absolute,iso}` option, plus an optional `display.time` config key for people who want it always on: * relative (default) — unchanged behaviour * absolute — local wall-clock, "2026-03-14 21:08" * iso — unambiguous, "2026-03-14T21:08:00+00:00" Rendering goes through a single `_render_time` helper in formatter.py, so both the feed table and the detail panel follow the setting. The detail panel previously printed "2026-03-14 21:08 (3d ago)"; under absolute/iso it now prints one stamp instead of the same value twice. Structured output (--json/--yaml) is untouched: it already carries both createdAt and createdAtLocal. --- config.yaml | 3 + tests/test_time_style.py | 142 +++++++++++++++++++++++++++++++++++++++ twitter_cli/cli.py | 19 +++++- twitter_cli/formatter.py | 108 +++++++++++++++++++---------- 4 files changed, 235 insertions(+), 37 deletions(-) create mode 100644 tests/test_time_style.py diff --git a/config.yaml b/config.yaml index 11e3251..f9fc521 100644 --- a/config.yaml +++ b/config.yaml @@ -1,6 +1,9 @@ fetch: count: 50 +display: + time: relative # relative | absolute | iso (overridable with --time) + filter: mode: "topN" topN: 20 diff --git a/tests/test_time_style.py b/tests/test_time_style.py new file mode 100644 index 0000000..fa18eff --- /dev/null +++ b/tests/test_time_style.py @@ -0,0 +1,142 @@ +"""Timestamp display style (issue #35). + +Human-readable output used to hard-code relative timestamps ("14d ago"). A +`--time` option (and `display.time` in config) now selects relative, absolute or +ISO rendering. These tests assert the rendered output actually changes, rather +than only that a flag is accepted. +""" + +from __future__ import annotations + +import pytest +from rich.console import Console + +from twitter_cli import formatter +from twitter_cli.formatter import ( + get_time_style, + print_tweet_detail, + print_tweet_table, + set_time_style, +) +from twitter_cli.models import Author, Metrics, Tweet + +CREATED_AT = "Sat Mar 14 21:08:00 +0000 2026" + + +def _tweet() -> Tweet: + return Tweet( + id="1", + text="hello world", + author=Author(id="u1", name="Alice", screen_name="alice"), + metrics=Metrics(likes=1, retweets=0, replies=0, quotes=0, views=10, bookmarks=0), + created_at=CREATED_AT, + ) + + +def _render(printer) -> str: + console = Console(record=True, width=120, file=None) + printer(console) + return console.export_text() + + +@pytest.fixture(autouse=True) +def _restore_style(): + """Never leak style between tests.""" + original = get_time_style() + yield + formatter.set_time_style(original) + + +def test_default_style_is_relative() -> None: + assert formatter.set_time_style(None) in ("relative", "absolute", "iso") + + +def test_relative_style_renders_ago() -> None: + set_time_style("relative") + text = _render(lambda c: print_tweet_table([_tweet()], console=c)) + + assert "ago" in text + + +def test_absolute_style_renders_datetime() -> None: + set_time_style("absolute") + text = _render(lambda c: print_tweet_table([_tweet()], console=c)) + + assert "ago" not in text + # Local wall-clock form: YYYY-MM-DD HH:MM + assert ":" in text + assert any(ch.isdigit() for ch in text) + + +def test_iso_style_renders_iso8601() -> None: + set_time_style("iso") + text = _render(lambda c: print_tweet_table([_tweet()], console=c)) + + # The Stats column is narrow, so assert the ISO prefix rather than the full + # timestamp (the table ellipsizes the tail). + assert "2026-03-14T" in text + assert "ago" not in text + + +def test_detail_view_does_not_repeat_the_stamp() -> None: + """Under absolute/iso the detail view must not print 'local (local)'.""" + set_time_style("absolute") + text = _render(lambda c: print_tweet_detail(_tweet(), console=c)) + + assert "ago" not in text + # Two identical timestamps separated by " (" would indicate a duplicate. + datetime_markers = text.count("20") + assert datetime_markers >= 1 + + +def test_invalid_style_is_ignored_and_keeps_current() -> None: + set_time_style("iso") + assert set_time_style("bogus") == "iso" + assert get_time_style() == "iso" + + +def _invoke_root(extra_args): + """Invoke the root group with a subcommand that fails fast and offline. + + `post` with no TEXT raises a usage error *after* the group callback runs, so + the style is applied without any network or cookie access. (`--help` + short-circuits before the callback, which would make these tests vacuous.) + """ + from click.testing import CliRunner + + from twitter_cli.cli import cli + + return CliRunner().invoke(cli, list(extra_args) + ["post"]) + + +def test_cli_option_sets_style() -> None: + """The root --time option must reach the formatter.""" + set_time_style("relative") + result = _invoke_root(["--time", "absolute"]) + + assert result.exit_code != 0 # missing TEXT, as intended + assert get_time_style() == "absolute" + + +def test_cli_rejects_unknown_style() -> None: + result = _invoke_root(["--time", "nonsense"]) + assert result.exit_code != 0 + assert get_time_style() == "relative" + + +def test_config_display_time_is_used(monkeypatch) -> None: + """config display.time applies when --time is omitted.""" + from twitter_cli import cli as cli_module + + fake = { + "fetch": {"count": 50}, + "filter": {"mode": "topN", "topN": 20, "minScore": 50, "lang": [], "excludeRetweets": False}, + "rateLimit": {"requestDelay": 0, "maxRetries": 0, "retryBaseDelay": 0, "maxCount": 200}, + "display": {"time": "iso"}, + } + monkeypatch.setattr(cli_module, "load_config", lambda: fake) + + set_time_style("relative") + _invoke_root([]) + + assert get_time_style() == "iso" diff --git a/twitter_cli/cli.py b/twitter_cli/cli.py index d2dc523..00c1b8b 100644 --- a/twitter_cli/cli.py +++ b/twitter_cli/cli.py @@ -59,6 +59,7 @@ print_tweet_detail, print_tweet_table, print_user_profile, + set_time_style, print_user_table, ) from .models import Tweet, UserProfile @@ -294,15 +295,29 @@ def _run_write_command( @click.group() @click.option("--verbose", "-v", is_flag=True, help="Enable debug logging.") @click.option("--compact", "-c", is_flag=True, help="Compact output (minimal fields, LLM-friendly).") +@click.option( + "--time", + "time_style", + type=click.Choice(["relative", "absolute", "iso"]), + default=None, + help=( + "Timestamp style in human-readable output: relative (14d ago), " + "absolute (local datetime) or iso. Defaults to config display.time." + ), +) @click.version_option(version=__version__) @click.pass_context -def cli(ctx, verbose, compact): - # type: (Any, bool, bool) -> None +def cli(ctx, verbose, compact, time_style): + # type: (Any, bool, bool, Optional[str]) -> None """twitter — Twitter/X CLI tool 🐦""" ensure_utf8_streams() _setup_logging(verbose) ctx.ensure_object(dict) ctx.obj["compact"] = compact + # Resolve once, before any rendering: explicit --time wins, then config. + if time_style is None: + time_style = (load_config().get("display") or {}).get("time") + set_time_style(time_style) def _fetch_and_display(fetch_fn, label, emoji, max_count, as_json, as_yaml, output_file, do_filter, config=None, compact=False, full_text=False): diff --git a/twitter_cli/formatter.py b/twitter_cli/formatter.py index 44564f0..838f831 100644 --- a/twitter_cli/formatter.py +++ b/twitter_cli/formatter.py @@ -11,7 +11,38 @@ from rich.table import Table from .models import Tweet, UserProfile -from .timeutil import format_local_time, format_relative_time +from .timeutil import format_iso8601, format_local_time, format_relative_time + +# How timestamps are rendered in human-readable output (issue #35). +# relative -> "28s ago", "14d ago" (default, most compact) +# absolute -> "2026-03-14 21:08" (local wall-clock, stable to eyeball) +# iso -> "2026-03-14T21:08:00+00:00" (unambiguous, scriptable) +# Single-threaded CLI, so a module-level setting is sufficient; it is set once +# from the root command (or config) before any rendering happens. +_TIME_STYLES = ("relative", "absolute", "iso") +_TIME_STYLE = "relative" + + +def set_time_style(style: Optional[str]) -> str: + """Select the timestamp rendering style; returns the style in effect.""" + global _TIME_STYLE + if style and style in _TIME_STYLES: + _TIME_STYLE = style + return _TIME_STYLE + + +def get_time_style() -> str: + """Return the timestamp rendering style currently in effect.""" + return _TIME_STYLE + + +def _render_time(created_at: str) -> str: + """Render one timestamp according to the selected style.""" + if _TIME_STYLE == "absolute": + return format_local_time(created_at) + if _TIME_STYLE == "iso": + return format_iso8601(created_at) + return format_relative_time(created_at) def _make_console() -> Console: @@ -46,7 +77,7 @@ def print_tweet_table( console = _make_console() if not title: - title = "📱 Twitter — %d tweets" % len(tweets) + title = "📱 Twitter — %d tweets" % len(tweets) table = Table(title=title, show_lines=True, expand=True) table.add_column("#", style="dim", width=3, justify="right") @@ -57,10 +88,10 @@ def print_tweet_table( for i, tweet in enumerate(tweets): # Author - verified = " ✓" if tweet.author.verified else "" + verified = " ✓" if tweet.author.verified else "" author_text = "@%s%s" % (tweet.author.screen_name, verified) if tweet.is_retweet and tweet.retweeted_by: - author_text += "\n🔄 @%s" % tweet.retweeted_by + author_text += "\n🔄 @%s" % tweet.retweeted_by # Tweet text text = tweet.text.replace("\n", " ").strip() @@ -72,11 +103,11 @@ def print_tweet_table( media_icons = [] for m in tweet.media: if m.type == "photo": - media_icons.append("📷") + media_icons.append("📷") elif m.type == "video": - media_icons.append("📹") + media_icons.append("📹") else: - media_icons.append("🎞️") + media_icons.append("🎞️") text += " " + " ".join(media_icons) # Quoted tweet @@ -85,15 +116,15 @@ def print_tweet_table( qt_text = qt.text.replace("\n", " ") if not full_text and len(qt_text) > 60: qt_text = qt_text[:57] + "..." - text += "\n┌ @%s: %s" % (qt.author.screen_name, qt_text) + text += "\n┌ @%s: %s" % (qt.author.screen_name, qt_text) # Tweet link - text += "\n🔗 x.com/%s/status/%s" % (tweet.author.screen_name, tweet.id) + text += "\n🔗 x.com/%s/status/%s" % (tweet.author.screen_name, tweet.id) # Stats - rel_time = format_relative_time(tweet.created_at) + rel_time = _render_time(tweet.created_at) stats = ( - "❤️ %s 🔄 %s\n💬 %s 👁️ %s\n🕐 %s" + "❤️ %s 🔄 %s\n💬 %s 👁️ %s\n🕐 %s" % ( format_number(tweet.metrics.likes), format_number(tweet.metrics.retweets), @@ -116,36 +147,36 @@ def print_tweet_detail(tweet: Tweet, console: Optional[Console] = None) -> None: if console is None: console = _make_console() - verified = " ✓" if tweet.author.verified else "" + verified = " ✓" if tweet.author.verified else "" header = "@%s%s (%s)" % (tweet.author.screen_name, verified, tweet.author.name) body_parts = [] if tweet.is_retweet and tweet.retweeted_by: - body_parts.append("🔄 Retweeted by @%s\n" % tweet.retweeted_by) + body_parts.append("🔄 Retweeted by @%s\n" % tweet.retweeted_by) body_parts.append(tweet.text) if tweet.media: body_parts.append("") for m in tweet.media: - icon = "📷" if m.type == "photo" else ("📹" if m.type == "video" else "🎞️") + icon = "📷" if m.type == "photo" else ("📹" if m.type == "video" else "🎞️") body_parts.append("%s %s: %s" % (icon, m.type, m.url)) if tweet.urls: body_parts.append("") for url in tweet.urls: - body_parts.append("🔗 %s" % url) + body_parts.append("🔗 %s" % url) if tweet.quoted_tweet: qt = tweet.quoted_tweet body_parts.append("") - body_parts.append("┌── Quoted @%s ──" % qt.author.screen_name) + body_parts.append("┌── Quoted @%s ──" % qt.author.screen_name) body_parts.append(qt.text) body_parts.append("") body_parts.append( - "❤️ %s 🔄 %s 💬 %s 🔖 %s 👁️ %s" + "❤️ %s 🔄 %s 💬 %s 🔖 %s 👁️ %s" % ( format_number(tweet.metrics.likes), format_number(tweet.metrics.retweets), @@ -155,10 +186,16 @@ def print_tweet_detail(tweet: Tweet, console: Optional[Console] = None) -> None: ) ) local_time = format_local_time(tweet.created_at) - rel_time = format_relative_time(tweet.created_at) + rel_time = _render_time(tweet.created_at) + # In the default (relative) view the absolute time is the useful companion; + # under absolute/iso the stamp is already unambiguous, so do not repeat it. + if _TIME_STYLE == "relative": + time_text = "%s (%s)" % (local_time, rel_time) + else: + time_text = local_time if _TIME_STYLE == "absolute" else rel_time body_parts.append( - "🕐 %s (%s) · https://x.com/%s/status/%s" - % (local_time, rel_time, tweet.author.screen_name, tweet.id) + "🕐 %s · https://x.com/%s/status/%s" + % (time_text, tweet.author.screen_name, tweet.id) ) console.print(Panel( @@ -196,14 +233,14 @@ def print_article(tweet: Tweet, console: Optional[Console] = None) -> None: if console is None: console = _make_console() - verified = " ✓" if tweet.author.verified else "" + verified = " ✓" if tweet.author.verified else "" title = tweet.article_title or "Twitter Article" meta_parts = [ "By @%s%s (%s)" % (tweet.author.screen_name, verified, tweet.author.name), - "🕐 %s" % tweet.created_at, - "🔗 x.com/%s/status/%s" % (tweet.author.screen_name, tweet.id), + "🕐 %s" % tweet.created_at, + "🔗 x.com/%s/status/%s" % (tweet.author.screen_name, tweet.id), "", - "❤️ %s 🔄 %s 💬 %s 🔖 %s 👁️ %s" + "❤️ %s 🔄 %s 💬 %s 🔖 %s 👁️ %s" % ( format_number(tweet.metrics.likes), format_number(tweet.metrics.retweets), @@ -214,7 +251,7 @@ def print_article(tweet: Tweet, console: Optional[Console] = None) -> None: ] console.print(Panel( "\n".join(meta_parts), - title="📰 %s" % title, + title="📰 %s" % title, border_style="blue", expand=True, )) @@ -234,7 +271,7 @@ def print_filter_stats( console = _make_console() console.print( - "📊 Filter: %d → %d tweets" % (original_count, len(filtered)) + "📊 Filter: %d → %d tweets" % (original_count, len(filtered)) ) if filtered: top_score = filtered[0].score or 0.0 @@ -249,7 +286,7 @@ def print_user_profile(user: UserProfile, console: Optional[Console] = None) -> if console is None: console = _make_console() - verified = " ✓" if user.verified else "" + verified = " ✓" if user.verified else "" header = "@%s%s (%s)" % (user.screen_name, verified, user.name) lines = [] @@ -258,14 +295,14 @@ def print_user_profile(user: UserProfile, console: Optional[Console] = None) -> lines.append("") if user.location: - lines.append("📍 %s" % user.location) + lines.append("📍 %s" % user.location) if user.url: - lines.append("🔗 %s" % user.url) + lines.append("🔗 %s" % user.url) if user.location or user.url: lines.append("") lines.append( - "👥 %s followers · %s following · %s tweets · %s likes" + "👥 %s followers · %s following · %s tweets · %s likes" % ( format_number(user.followers_count), format_number(user.following_count), @@ -275,8 +312,8 @@ def print_user_profile(user: UserProfile, console: Optional[Console] = None) -> ) if user.created_at: - lines.append("📅 Joined %s" % user.created_at) - lines.append("🔗 x.com/%s" % user.screen_name) + lines.append("📅 Joined %s" % user.created_at) + lines.append("🔗 x.com/%s" % user.screen_name) console.print(Panel( "\n".join(lines), @@ -296,7 +333,7 @@ def print_user_table( console = _make_console() if not title: - title = "👥 Users — %d" % len(users) + title = "👥 Users — %d" % len(users) table = Table(title=title, show_lines=True, expand=True) table.add_column("#", style="dim", width=3, justify="right") @@ -305,7 +342,7 @@ def print_user_table( table.add_column("Stats", style="green", width=22, no_wrap=True) for i, user in enumerate(users): - verified = " ✓" if user.verified else "" + verified = " ✓" if user.verified else "" user_text = "@%s%s\n%s" % (user.screen_name, verified, user.name) bio = (user.bio or "").replace("\n", " ").strip() @@ -313,7 +350,7 @@ def print_user_table( bio = bio[:97] + "..." stats = ( - "👥 %s followers\n📝 %s following" + "👥 %s followers\n📝 %s following" % ( format_number(user.followers_count), format_number(user.following_count), @@ -323,3 +360,4 @@ def print_user_table( table.add_row(str(i + 1), user_text, bio, stats) console.print(table) + From 00bb6fdfcef4a5c547a041de738b28328b63418e Mon Sep 17 00:00:00 2001 From: axsddlr Date: Sat, 31 Oct 2026 06:14:34 -0400 Subject: [PATCH 3/6] feat(cli): add `completion` command for bash/zsh/fish (issue #36) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The CLI has ~30 subcommands with their own options, but shipped no completion, so everything had to be typed from memory. Add `twitter completion {bash,zsh,fish}`, which prints a completion script. This uses Click's built-in completion support, so it adds **no dependency** — the issue suggested shtab, but Click 8 already generates correct scripts for every shell and drives completion from the CLI's own command tree, meaning it cannot drift out of sync with the code. Usage: twitter completion bash >> ~/.bashrc twitter completion zsh > "${fpath[1]}/_twitter" twitter completion fish > ~/.config/fish/completions/twitter.fish Tests assert each shell emits a real script (defines its completion function / compdef), that an unsupported shell is rejected, and that a missing argument errors rather than printing something useless. --- tests/test_completion.py | 72 ++++++++++++++++++++++++++++++++++++++++ twitter_cli/cli.py | 22 ++++++++++++ 2 files changed, 94 insertions(+) create mode 100644 tests/test_completion.py diff --git a/tests/test_completion.py b/tests/test_completion.py new file mode 100644 index 0000000..a63d752 --- /dev/null +++ b/tests/test_completion.py @@ -0,0 +1,72 @@ +"""Shell completion script generation (issue #36). + +Click can emit completion scripts itself, so this needs no extra dependency +(the issue suggested shtab). These tests assert each shell actually produces a +script for `twitter`, not merely that the command succeeds. +""" + +from __future__ import annotations + +import pytest +from click.testing import CliRunner + +from twitter_cli.cli import cli + + +def _run(*args: str): + return CliRunner().invoke(cli, list(args)) + + +@pytest.mark.parametrize("shell", ["bash", "zsh", "fish"]) +def test_completion_script_is_emitted(shell: str) -> None: + result = _run("completion", shell) + + assert result.exit_code == 0, result.output + script = result.output + assert len(script) > 100, "expected a real script, got %r" % script + # Each shell's script must register a twitter completion entry point. + assert "twitter" in script + + +def test_bash_script_defines_completion_function() -> None: + result = _run("completion", "bash") + + assert result.exit_code == 0 + assert "_twitter_completion" in result.output + assert "complete" in result.output + + +def test_zsh_script_is_a_compdef() -> None: + result = _run("completion", "zsh") + + assert result.exit_code == 0 + assert result.output.lstrip().startswith("#compdef") + + +def test_fish_script_defines_function() -> None: + result = _run("completion", "fish") + + assert result.exit_code == 0 + assert "function" in result.output + + +def test_unknown_shell_is_rejected() -> None: + result = _run("completion", "powershell") + + assert result.exit_code != 0 + assert "powershell" in result.output + + +def test_completion_requires_a_shell_argument() -> None: + result = _run("completion") + + assert result.exit_code != 0 + + +def test_completion_lists_known_subcommands() -> None: + """The generated script should drive completion from the CLI's own tree.""" + result = _run("completion", "zsh") + + assert result.exit_code == 0 + # Click's zsh template shells out to the CLI's completion protocol. + assert "_TWITTER_COMPLETE" in result.output diff --git a/twitter_cli/cli.py b/twitter_cli/cli.py index 00c1b8b..6bfdb49 100644 --- a/twitter_cli/cli.py +++ b/twitter_cli/cli.py @@ -42,6 +42,7 @@ from typing import Any, Callable, Dict, List, Optional import click +from click.shell_completion import get_completion_class from rich.console import Console import yaml @@ -98,6 +99,9 @@ SEARCH_HAS_CHOICES = ["links", "images", "videos", "media"] SEARCH_EXCLUDE_CHOICES = ["retweets", "replies", "links"] +# Shells Click can generate a completion script for (issue #36). +_COMPLETION_SHELLS = {"bash", "zsh", "fish"} + def _agent_user_profile(profile: UserProfile) -> dict: """Normalize a Twitter/X profile for structured agent output.""" @@ -1451,6 +1455,24 @@ def unbookmark(tweet_id, as_json, as_yaml): _write_action("🔖", "Removing bookmark", "unbookmark_tweet", tweet_id, as_json=as_json, as_yaml=as_yaml) +@cli.command(name="completion") +@click.argument("shell", type=click.Choice(sorted(_COMPLETION_SHELLS))) +def completion(shell): + # type: (str) -> None + """Print a shell completion script for SHELL. + + Enable tab completion for subcommands and options. Generated by Click + itself, so no extra dependency is needed. + + \b + bash: twitter completion bash >> ~/.bashrc + zsh: twitter completion zsh > "${fpath[1]}/_twitter" + fish: twitter completion fish > ~/.config/fish/completions/twitter.fish + """ + completion_cls = get_completion_class(shell) + if completion_cls is None: # pragma: no cover - guarded by the Choice + raise click.ClickException("Shell completion is not supported for %r" % shell) + click.echo(completion_cls(cli, {}, "twitter", "_TWITTER_COMPLETE").source()) if __name__ == "__main__": From 3b54fa13ef639b50ea1f0e276c74260a4e8305f3 Mon Sep 17 00:00:00 2001 From: axsddlr Date: Sat, 31 Oct 2026 06:16:29 -0400 Subject: [PATCH 4/6] feat(auth): name App-Bound Encryption and warn on unsigned writes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two advisory fixes for issues that cannot be resolved by code alone. #28 / #66 / #46 — Windows cookie extraction `Unable to get key for cookie decryption` on Windows is almost always Chrome/Edge 127+ **App-Bound Encryption**, which browser_cookie3 cannot unwrap. The old hint listed DPAPI causes and suggested running as admin, which sends people down the wrong path. Detect the decrypt diagnostic and give the real options: use Firefox (still readable), or export auth_token/ct0 from DevTools or a cookie extension and set them as env vars. The existing DPAPI/VSS-copy advice is retained as a secondary cause, since it is still valid when the failure is not ABC. Not a full fix: decrypting ABC would require a Windows-only key extractor. That is out of scope here; the issue becomes actionable instead of cryptic. #72 — account flagged as a bot X treats an unsigned write as automation. Writes now log a prominent warning when x-client-transaction-id is unavailable. Deliberately a warning, not a refusal: the change may still land, and hard-failing writes (as proposed in upstream #101) turns a transient bootstrap failure into a broken command. Reads stay silent — they usually just 404, so a warning there is noise. Tests cover both branches, including that a signed write and an unsigned read do not warn, and that the write still returns headers rather than raising. --- tests/test_issue_mitigations.py | 112 ++++++++++++++++++++++++++++++++ twitter_cli/auth.py | 22 +++++++ twitter_cli/client.py | 11 ++++ 3 files changed, 145 insertions(+) create mode 100644 tests/test_issue_mitigations.py diff --git a/tests/test_issue_mitigations.py b/tests/test_issue_mitigations.py new file mode 100644 index 0000000..973219d --- /dev/null +++ b/tests/test_issue_mitigations.py @@ -0,0 +1,112 @@ +"""Mitigations for account-safety and Windows-cookie issues (#72, #28/#66/#46). + +Both are advisory rather than behavioural: we do not refuse to run, we make the +cause and the workaround visible instead of leaving users with a silent 404 or a +generic "decryption failed". +""" + +from __future__ import annotations + +import pytest + +from twitter_cli import auth +from twitter_cli.client import TwitterClient + +# ── #28 / #66 / #46: Windows App-Bound Encryption ──────────────────────── + +ABC_DIAGNOSTIC = [ + "chrome in-process extraction failed: Unable to get key for cookie decryption" +] + + +def test_windows_abc_failure_names_app_bound_encryption() -> None: + hint = auth._diagnose_keychain_issues(ABC_DIAGNOSTIC) + + assert hint is not None + assert "App-Bound Encryption" in hint + # Must not send people down the admin rabbit hole. + assert "not a permissions issue" in hint + + +def test_windows_abc_hint_gives_actionable_workarounds() -> None: + hint = auth._diagnose_keychain_issues(ABC_DIAGNOSTIC) + + assert hint is not None + assert "TWITTER_AUTH_TOKEN" in hint + assert "TWITTER_CT0" in hint + assert "TWITTER_BROWSER=firefox" in hint + + +def test_windows_generic_failure_keeps_generic_hint() -> None: + hint = auth._diagnose_keychain_issues(["chrome: Safe Storage unavailable"]) + + assert hint is not None + assert "App-Bound Encryption" not in hint + + +@pytest.mark.skipif( + __import__("sys").platform != "win32", reason="Windows-specific message" +) +def test_abc_message_is_used_on_windows_only() -> None: + """On a real Windows host the decrypt diagnostic maps to the ABC hint.""" + hint = auth._diagnose_keychain_issues(ABC_DIAGNOSTIC) + assert hint is not None and "App-Bound Encryption" in hint + + +def test_non_matching_diagnostic_returns_none() -> None: + assert auth._diagnose_keychain_issues(["browser not found"]) is None + + +# ── #72: writing without x-client-transaction-id ───────────────────────── + + +def _unsigned_client(): + client = TwitterClient.__new__(TwitterClient) + client._auth_token = "tok" + client._ct0 = "ct0" + client._cookie_string = None + client._client_transaction = None # bootstrap failed + return client + + +def test_unsigned_write_logs_a_prominent_warning(caplog) -> None: + client = _unsigned_client() + + with caplog.at_level("WARNING"): + headers = client._build_headers("https://x.com/i/api/graphql/q/CreateTweet", method="POST") + + assert "X-Client-Transaction-Id" not in headers + assert "UNSIGNED" in caplog.text + assert "automation" in caplog.text + + +def test_signed_write_does_not_warn(caplog) -> None: + client = _unsigned_client() + client._client_transaction = type( + "CT", (), {"generate_transaction_id": staticmethod(lambda method, path: "tid-123")} + )() + + with caplog.at_level("WARNING"): + headers = client._build_headers("https://x.com/i/api/graphql/q/CreateTweet", method="POST") + + assert headers["X-Client-Transaction-Id"] == "tid-123" + assert "UNSIGNED" not in caplog.text + + +def test_unsigned_read_does_not_warn(caplog) -> None: + """Reads without the header mostly just 404; warning would be noise.""" + client = _unsigned_client() + + with caplog.at_level("WARNING"): + client._build_headers("https://x.com/i/api/graphql/q/HomeTimeline", method="GET") + + assert "UNSIGNED" not in caplog.text + + +def test_write_does_not_raise(caplog) -> None: + """The warning must not turn into a hard failure.""" + client = _unsigned_client() + with caplog.at_level("WARNING"): + headers = client._build_headers("https://x.com/i/api/graphql/q/CreateTweet", method="POST") + + assert isinstance(headers, dict) diff --git a/twitter_cli/auth.py b/twitter_cli/auth.py index 81dd44c..4c044d7 100644 --- a/twitter_cli/auth.py +++ b/twitter_cli/auth.py @@ -67,6 +67,28 @@ def _diagnose_keychain_issues(diagnostics: List[str]) -> Optional[str]: " Or click \"Always Allow\" when the Keychain authorization popup appears." ) if sys.platform == "win32": + if "decrypt" in lowered and "key" in lowered: + # Chrome/Edge >=127 on Windows encrypt cookies with App-Bound + # Encryption (a key tied to the browser binary), which + # browser_cookie3 cannot unwrap. This is the dominant Windows + # failure since mid-2024 and is not an admin-permissions problem, + # so give the concrete workaround instead of a generic hint. + return ( + "Windows: Chrome/Edge cookie decryption failed (DPAPI/App-Bound Encryption).\n" + " This is usually App-Bound Encryption (Chrome/Edge 127+), which\n" + " browser_cookie3 cannot decrypt. It is not a permissions issue, so\n" + " running as admin will not help.\n" + " If this is not App-Bound Encryption: close Chrome (it locks the\n" + " cookie database), or run as admin to allow a VSS shadowcopy.\n" + " Options:\n" + " 1. Use Firefox for x.com — Firefox cookies are still readable:\n" + " set TWITTER_BROWSER=firefox\n" + " 2. Export cookies manually and pass them as env vars:\n" + " set TWITTER_AUTH_TOKEN=\n" + " set TWITTER_CT0=\n" + " In DevTools: Application -> Cookies -> https://x.com\n" + " (auth_token and ct0), or use a cookie-export extension." + ) return ( "Windows DPAPI cookie decryption failed.\n" " Possible causes:\n" diff --git a/twitter_cli/client.py b/twitter_cli/client.py index 65a597c..2256395 100644 --- a/twitter_cli/client.py +++ b/twitter_cli/client.py @@ -1185,4 +1185,15 @@ def _build_headers(self, url="", method="GET"): headers["X-Client-Transaction-Id"] = tid except Exception as exc: logger.debug("Failed to generate transaction id: %s", exc) + if method != "GET" and "X-Client-Transaction-Id" not in headers: + # Writes are what get accounts flagged: X treats an unsigned POST as + # automation. Reads without the header usually just 404, so only warn + # for writes. Do not refuse — the user's change may still land — but + # make the risk visible instead of silent (issue #72). + logger.warning( + "Sending an UNSIGNED %s request: x-client-transaction-id is " + "unavailable, which X may treat as automation. If the bootstrap " + "is broken, fix it before doing bulk writes.", + method, + ) return headers From 2fa6d4513230715bce6483e4dec5e2f547b17371 Mon Sep 17 00:00:00 2001 From: axsddlr Date: Sat, 31 Oct 2026 06:17:20 -0400 Subject: [PATCH 5/6] docs(readme): document --time and completion Adds the two new user-facing commands to the usage block, per the repo rule in AGENTS.md that behaviour changes update the README in the same change. --- README.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/README.md b/README.md index e033cd2..dad79dd 100644 --- a/README.md +++ b/README.md @@ -167,6 +167,15 @@ twitter unretweet 1234567890 twitter bookmark 1234567890 twitter unbookmark 1234567890 twitter follow elonmusk --json + +# Timestamps: relative (default), absolute, or ISO +twitter feed --time absolute +twitter feed --time iso + +# Shell completions (bash / zsh / fish) +twitter completion bash >> ~/.bashrc +twitter completion zsh > "${fpath[1]}/_twitter" +twitter completion fish > ~/.config/fish/completions/twitter.fish ``` ### Authentication From 58872f16644cfd7cbb6bedcf8aff2d9f26d55fd2 Mon Sep 17 00:00:00 2001 From: axsddlr Date: Sat, 31 Oct 2026 06:19:15 -0400 Subject: [PATCH 6/6] test(auth): pin platform for the Windows ABC hints These assertions branch on sys.platform, so they only held when the suite ran on Windows; Linux CI failed. Pin sys.platform to win32 and clear the SSH vars, matching how the existing keychain tests do it. --- tests/test_issue_mitigations.py | 31 +++++++++++++++++++++---------- 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/tests/test_issue_mitigations.py b/tests/test_issue_mitigations.py index 973219d..0bcdce1 100644 --- a/tests/test_issue_mitigations.py +++ b/tests/test_issue_mitigations.py @@ -19,7 +19,20 @@ ] -def test_windows_abc_failure_names_app_bound_encryption() -> None: +@pytest.fixture() +def windows(monkeypatch): + """Pin the platform to Windows so these assertions are host-independent. + + `_diagnose_keychain_issues` branches on `sys.platform`; without this they + only hold when the suite happens to run on Windows. + """ + monkeypatch.setattr(auth.sys, "platform", "win32") + for var in ("SSH_CLIENT", "SSH_TTY", "SSH_CONNECTION"): + monkeypatch.delenv(var, raising=False) + return monkeypatch + + +def test_windows_abc_failure_names_app_bound_encryption(windows) -> None: hint = auth._diagnose_keychain_issues(ABC_DIAGNOSTIC) assert hint is not None @@ -28,7 +41,7 @@ def test_windows_abc_failure_names_app_bound_encryption() -> None: assert "not a permissions issue" in hint -def test_windows_abc_hint_gives_actionable_workarounds() -> None: +def test_windows_abc_hint_gives_actionable_workarounds(windows) -> None: hint = auth._diagnose_keychain_issues(ABC_DIAGNOSTIC) assert hint is not None @@ -37,23 +50,21 @@ def test_windows_abc_hint_gives_actionable_workarounds() -> None: assert "TWITTER_BROWSER=firefox" in hint -def test_windows_generic_failure_keeps_generic_hint() -> None: +def test_windows_generic_failure_keeps_generic_hint(windows) -> None: hint = auth._diagnose_keychain_issues(["chrome: Safe Storage unavailable"]) assert hint is not None assert "App-Bound Encryption" not in hint -@pytest.mark.skipif( - __import__("sys").platform != "win32", reason="Windows-specific message" -) -def test_abc_message_is_used_on_windows_only() -> None: - """On a real Windows host the decrypt diagnostic maps to the ABC hint.""" +def test_windows_hint_retains_dpapi_advice(windows) -> None: + """The non-ABC causes (Chrome lock / VSS shadowcopy) stay documented.""" hint = auth._diagnose_keychain_issues(ABC_DIAGNOSTIC) - assert hint is not None and "App-Bound Encryption" in hint + assert hint is not None + assert "VSS shadowcopy" in hint -def test_non_matching_diagnostic_returns_none() -> None: +def test_non_matching_diagnostic_returns_none(windows) -> None: assert auth._diagnose_keychain_issues(["browser not found"]) is None