From 0ad8dad2cb783543358427411643eb1cfb9c8af8 Mon Sep 17 00:00:00 2001 From: Stoner Date: Mon, 21 Sep 2026 16:43:23 +0800 Subject: [PATCH 1/2] fix: restore client transaction initialization --- pyproject.toml | 2 +- tests/test_client.py | 40 ++++++++++++++++++++++++++++++++++++++++ twitter_cli/client.py | 2 +- uv.lock | 8 ++++---- 4 files changed, 46 insertions(+), 6 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index de8f3dc..94fd3fa 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -25,7 +25,7 @@ dependencies = [ "rich>=13.0", "PyYAML>=6.0", "curl_cffi>=0.7", - "xclienttransaction>=1.0.1", + "xclienttransaction>=1.0.3", "beautifulsoup4>=4.12", ] diff --git a/tests/test_client.py b/tests/test_client.py index c1393d3..f4e2d2f 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -265,6 +265,46 @@ def test_handles_malformed_html(self): # ── TwitterClient._build_headers ───────────────────────────────────────── +# ClientTransaction initialization regression +class TestClientTransactionInitialization: + @patch("twitter_cli.client._update_features_from_html") + @patch("twitter_cli.client.ClientTransaction") + @patch("twitter_cli.client._gen_ct_headers", return_value={"User-Agent": "test"}) + @patch("twitter_cli.client._get_cffi_session") + def test_fetches_home_route_for_ondemand_bundle( + self, + mock_session, + mock_headers, + mock_transaction, + mock_update_features, + ): + home_html = ( + '' + ) + home_page = MagicMock(content=home_html.encode(), text=home_html) + ondemand_file = MagicMock(text="ondemand bundle") + mock_session.return_value.get.side_effect = [home_page, ondemand_file] + + client = TwitterClient.__new__(TwitterClient) + client._client_transaction = None + client._ct_init_attempted = False + client._load_ct_cache = MagicMock(return_value=False) + client._save_ct_cache = MagicMock() + + client._ensure_client_transaction() + + first_request = mock_session.return_value.get.call_args_list[0] + second_request = mock_session.return_value.get.call_args_list[1] + assert first_request.args[0] == "https://x.com/home" + assert second_request.args[0] == ( + "https://abs.twimg.com/responsive-web/client-web/" + "ondemand.s.0cc29d94ce9e97eea.js" + ) + assert client._client_transaction is mock_transaction.return_value + + +# Header construction tests class TestBuildHeaders: @patch("twitter_cli.client._get_cffi_session") @patch("twitter_cli.client._gen_ct_headers", return_value={}) diff --git a/twitter_cli/client.py b/twitter_cli/client.py index 0436c8e..d24f7d5 100644 --- a/twitter_cli/client.py +++ b/twitter_cli/client.py @@ -1104,7 +1104,7 @@ def _ensure_client_transaction(self): cffi_session = _get_cffi_session() ct_headers = _gen_ct_headers() home_page = cffi_session.get( - "https://x.com", headers=ct_headers, timeout=10, + "https://x.com/home", headers=ct_headers, timeout=10, ) home_page_response = bs4.BeautifulSoup(home_page.content, "html.parser") ondemand_url = get_ondemand_file_url(response=home_page_response) diff --git a/uv.lock b/uv.lock index 5c2ba17..6db82b2 100644 --- a/uv.lock +++ b/uv.lock @@ -641,7 +641,7 @@ requires-dist = [ { name = "rich", specifier = ">=13.0" }, { name = "ruff", marker = "extra == 'dev'", specifier = ">=0.8" }, { name = "types-pyyaml", marker = "extra == 'dev'", specifier = ">=6.0.12" }, - { name = "xclienttransaction", specifier = ">=1.0.1" }, + { name = "xclienttransaction", specifier = ">=1.0.3" }, ] provides-extras = ["dev"] @@ -677,12 +677,12 @@ wheels = [ [[package]] name = "xclienttransaction" -version = "1.0.1" +version = "1.0.3" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "beautifulsoup4" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/eb/c7/c841afe6759567cf29e36196dff65c935682b69ae38e986bd14e7decf74e/xclienttransaction-1.0.1.tar.gz", hash = "sha256:e4e032ff27e76ab927c0a7f57ad3630e06b7100c113bdf22b03cdde9584756f3", size = 9062, upload-time = "2025-10-09T10:38:31.485Z" } +sdist = { url = "https://files.pythonhosted.org/packages/1b/11/6f5a55df6d464fe6f839fe96c3863fa2338005ed8e83e89b0a9db5716b5a/xclienttransaction-1.0.3.tar.gz", hash = "sha256:1eeb5d48cec6a224189bbd8a6021c40486fa3aff650478672bccf82b3436cedc", size = 10609, upload-time = "2026-06-26T10:47:39.664Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/fe/b8/b953828e2f0f658f7f2d6354525728c9569c83937ebe4903f2391f02a702/xclienttransaction-1.0.1-py3-none-any.whl", hash = "sha256:0280e021129a38f8ee2ebede6406d4c065a599430bd4c8aa0c122f2e42f9f0f0", size = 10724, upload-time = "2025-10-09T10:38:30.098Z" }, + { url = "https://files.pythonhosted.org/packages/fa/a1/be735112ebe49916065e6f80017b93e92fc8880789c3f4f17380db7f531a/xclienttransaction-1.0.3-py3-none-any.whl", hash = "sha256:f73dd2a4b6856f98fa45f0cd26c9a0fdc0b2ceba0e79b5523cdf8aac7efc59fe", size = 10778, upload-time = "2026-06-26T10:47:38.401Z" }, ] From 2ec203eb29a66c60fe60b86b49ac1f7ffc766c63 Mon Sep 17 00:00:00 2001 From: Stoner Date: Tue, 29 Sep 2026 21:58:20 +0800 Subject: [PATCH 2/2] Expose upstream CreateTweet response on reply failure --- tests/test_cli.py | 39 +++++++++++++++++++++++++++ tests/test_client.py | 55 +++++++++++++++++++++++++++++++++++++++ twitter_cli/cli.py | 15 +++++++++-- twitter_cli/client.py | 47 ++++++++++++++++++++++++++------- twitter_cli/exceptions.py | 11 +++++++- 5 files changed, 155 insertions(+), 12 deletions(-) diff --git a/tests/test_cli.py b/tests/test_cli.py index 5c6c58a..f6fcd9a 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -9,6 +9,7 @@ import yaml from twitter_cli.cli import cli +from twitter_cli.exceptions import TwitterAPIError from twitter_cli.formatter import article_to_markdown, print_tweet_table from twitter_cli.models import Author, BookmarkFolder, Metrics, Tweet, UserProfile from twitter_cli.serialization import tweets_to_json @@ -542,6 +543,44 @@ def create_tweet(self, text: str, reply_to_id=None, media_ids=None) -> str: assert calls[0]["text"] == "Nice tweet!" +def test_cli_reply_failure_includes_upstream_response_only_in_structured_details(monkeypatch) -> None: + response_body = '{"data":{"create_tweet":{"errors":[{"message":"Rejected"}]}}}' + + class FakeClient: + def create_tweet(self, text: str, reply_to_id=None, media_ids=None) -> str: + raise TwitterAPIError( + 0, + "Twitter API: Rejected", + upstream_status_code=200, + upstream_response=response_body, + ) + + monkeypatch.setattr("twitter_cli.cli._get_client", lambda config=None, quiet=False: FakeClient()) + result = CliRunner().invoke(cli, ["reply", "12345", "Nice tweet!", "--json"]) + + assert result.exit_code == 1 + payload = json.loads(result.output) + assert payload["error"]["details"] == { + "action": "reply", + "replyTo": "12345", + "upstream": {"httpStatus": 200, "responseBody": response_body}, + } + assert response_body not in payload["error"]["message"] + + +def test_cli_post_failure_does_not_include_upstream_response(monkeypatch) -> None: + class FakeClient: + def create_tweet(self, text: str, reply_to_id=None, media_ids=None) -> str: + raise TwitterAPIError(0, "Rejected", upstream_response="private response") + + monkeypatch.setattr("twitter_cli.cli._get_client", lambda config=None, quiet=False: FakeClient()) + result = CliRunner().invoke(cli, ["post", "hello", "--json"]) + + assert result.exit_code == 1 + assert "upstream" not in json.loads(result.output)["error"]["details"] + assert "private response" not in result.output + + def test_cli_quote_command(monkeypatch) -> None: calls = [] diff --git a/tests/test_client.py b/tests/test_client.py index f4e2d2f..130b84a 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -7,6 +7,7 @@ from __future__ import annotations import copy +import json from unittest.mock import MagicMock, patch import pytest @@ -1275,6 +1276,17 @@ def test_is_runtime_error(self): err = TwitterAPIError(500, "Server error") assert isinstance(err, RuntimeError) + def test_preserves_upstream_diagnostics_without_changing_message(self): + err = TwitterAPIError( + 0, + "Failed to create tweet", + upstream_status_code=200, + upstream_response='{"errors":[{"message":"Rejected"}]}', + ) + assert str(err) == "Twitter API error (HTTP 0): Failed to create tweet" + assert err.upstream_status_code == 200 + assert err.upstream_response == '{"errors":[{"message":"Rejected"}]}' + class TestParseUserResult: def test_coerces_count_fields_to_int(self): @@ -1521,6 +1533,49 @@ def mock_graphql_post(operation_name, variables, features=None): assert result == "88" assert captured_body["media"]["media_entities"] == [] + def test_create_tweet_without_id_preserves_full_response(self): + client = TwitterClient.__new__(TwitterClient) + client._request_delay = 0 + response = {"data": {"create_tweet": {"tweet_results": {"result": {}}}}, "extra": [1, 2]} + client._graphql_post = lambda *args: response + + with pytest.raises(TwitterAPIError, match="response missing tweet ID") as caught: + client.create_tweet("test", reply_to_id="123") + + assert caught.value.upstream_status_code is None + assert json.loads(caught.value.upstream_response) == response + + +class TestApiRequestDiagnostics: + @patch("twitter_cli.client._get_cffi_session") + def test_http_error_preserves_full_body(self, mock_session): + response = MagicMock(status_code=403, text="x" * 600) + mock_session.return_value.get.return_value = response + client = TwitterClient.__new__(TwitterClient) + client._max_retries = 0 + client._build_headers = lambda **kwargs: {} + + with pytest.raises(TwitterAPIError) as caught: + client._api_request("https://x.com/test") + + assert caught.value.upstream_status_code == 403 + assert caught.value.upstream_response == "x" * 600 + assert "x" * 501 not in str(caught.value) + + @patch("twitter_cli.client._get_cffi_session") + def test_graphql_error_preserves_full_body_and_actual_http_status(self, mock_session): + body = '{"data":{"create_tweet":{"errors":[{"message":"Rejected","code":321}]}}}' + mock_session.return_value.post.return_value = MagicMock(status_code=200, text=body) + client = TwitterClient.__new__(TwitterClient) + client._max_retries = 0 + client._build_headers = lambda **kwargs: {} + + with pytest.raises(TwitterAPIError) as caught: + client._api_request("https://x.com/test", method="POST", body={}) + + assert caught.value.upstream_status_code == 200 + assert caught.value.upstream_response == body + # ── fetch_search uses POST ──────────────────────────────────────────────── diff --git a/twitter_cli/cli.py b/twitter_cli/cli.py index d2dc523..f1f4509 100644 --- a/twitter_cli/cli.py +++ b/twitter_cli/cli.py @@ -48,7 +48,7 @@ from . import __version__ from .auth import get_cookies from .cache import resolve_cached_tweet, save_tweet_cache -from .exceptions import TwitterError +from .exceptions import TwitterAPIError, TwitterError from .client import TwitterClient from .config import load_config from .filter import filter_tweets @@ -274,6 +274,7 @@ def _run_write_command( progress_lines: Optional[List[str]] = None, success_lines: Optional[List[str]] = None, error_details: Optional[Dict[str, Any]] = None, + include_upstream_response: bool = False, ) -> Optional[WritePayload]: mode = _structured_mode(as_json=as_json, as_yaml=as_yaml) try: @@ -281,7 +282,16 @@ def _run_write_command( _print_lines(progress_lines or [], mode) payload = operation(client) except (TwitterError, RuntimeError) as exc: - _handle_structured_runtime_error(exc, mode=mode, details=error_details) + details = error_details + if include_upstream_response and isinstance(exc, TwitterAPIError): + details = { + **(error_details or {}), + "upstream": { + "httpStatus": exc.upstream_status_code, + "responseBody": exc.upstream_response, + }, + } + _handle_structured_runtime_error(exc, mode=mode, details=details) return None if _emit_mode_payload(payload, mode): @@ -1223,6 +1233,7 @@ def operation(client: TwitterClient) -> WritePayload: progress_lines=["💬 Replying to %s..." % tweet_id], success_lines=["[green]✅ Reply posted![/green]"], error_details={"action": "reply", "replyTo": tweet_id}, + include_upstream_response=True, ) if payload and not _structured_mode(as_json=as_json, as_yaml=as_yaml): console.print("🔗 %s" % payload["url"]) diff --git a/twitter_cli/client.py b/twitter_cli/client.py index d24f7d5..b8fae05 100644 --- a/twitter_cli/client.py +++ b/twitter_cli/client.py @@ -585,9 +585,14 @@ def create_tweet(self, text, reply_to_id=None, media_ids=None): data = self._graphql_post("CreateTweet", variables, FEATURES) self._write_delay() result = _deep_get(data, "data", "create_tweet", "tweet_results", "result") - if result: - return result.get("rest_id", "") - raise TwitterAPIError(0, "Failed to create tweet") + tweet_id = result.get("rest_id") if isinstance(result, dict) else None + if isinstance(tweet_id, str) and tweet_id: + return tweet_id + raise TwitterAPIError( + 0, + "Failed to create tweet: response missing tweet ID", + upstream_response=json.dumps(data, ensure_ascii=False), + ) def delete_tweet(self, tweet_id): # type: (str) -> bool @@ -976,8 +981,14 @@ def _api_request(self, url, method="GET", body=None): time.sleep(wait) continue if status_code >= 400: - message = "Twitter API error %d: %s" % (status_code, response.text[:500]) - raise TwitterAPIError(status_code, message) + response_text = response.text + message = "Twitter API error %d: %s" % (status_code, response_text[:500]) + raise TwitterAPIError( + status_code, + message, + upstream_status_code=status_code, + upstream_response=response_text, + ) payload = response.text except TwitterAPIError: @@ -988,7 +999,12 @@ def _api_request(self, url, method="GET", body=None): try: parsed = json.loads(payload) except (json.JSONDecodeError, ValueError): - raise TwitterAPIError(0, "Twitter API returned invalid JSON") + raise TwitterAPIError( + 0, + "Twitter API returned invalid JSON", + upstream_status_code=status_code, + upstream_response=payload, + ) if isinstance(parsed, dict) and parsed.get("errors"): err_msg = parsed["errors"][0].get("message", "Unknown error") @@ -1007,9 +1023,17 @@ def _api_request(self, url, method="GET", body=None): # Provide user-friendly message if err_code in (348, 349): raise TwitterAPIError( - 429, "Rate limited: %s (try again later, recommended wait: 15+ minutes)" % err_msg + 429, + "Rate limited: %s (try again later, recommended wait: 15+ minutes)" % err_msg, + upstream_status_code=status_code, + upstream_response=payload, ) - raise TwitterAPIError(0, "Twitter API returned errors: %s" % err_msg) + raise TwitterAPIError( + 0, + "Twitter API returned errors: %s" % err_msg, + upstream_status_code=status_code, + upstream_response=payload, + ) # GraphQL write mutations return errors in data.errors (separate from top-level) if isinstance(parsed, dict) and "data" in parsed: @@ -1020,7 +1044,12 @@ def _api_request(self, url, method="GET", body=None): inner_errors = val["errors"] if inner_errors: inner_msg = inner_errors[0].get("message", "Unknown error") - raise TwitterAPIError(0, "Twitter API: %s" % inner_msg) + raise TwitterAPIError( + 0, + "Twitter API: %s" % inner_msg, + upstream_status_code=status_code, + upstream_response=payload, + ) return parsed diff --git a/twitter_cli/exceptions.py b/twitter_cli/exceptions.py index 75be7ac..bf2bb91 100644 --- a/twitter_cli/exceptions.py +++ b/twitter_cli/exceptions.py @@ -63,9 +63,18 @@ class InvalidInputError(TwitterError): class TwitterAPIError(TwitterError): """Raised on non-OK Twitter API responses with HTTP status + message.""" - def __init__(self, status_code: int, message: str): + def __init__( + self, + status_code: int, + message: str, + *, + upstream_status_code: int | None = None, + upstream_response: str | None = None, + ): self.status_code = status_code self.message = message + self.upstream_status_code = upstream_status_code + self.upstream_response = upstream_response # Derive error_code from HTTP status if status_code in (401, 403): self.error_code = "not_authenticated"