Skip to content

feat: Use cached Grok translations for Twitter provider - #1899

Merged
dangeredwolf merged 8 commits into
mainfrom
auto-translate
Apr 1, 2026
Merged

dangeredwolf merged 8 commits into
mainfrom
auto-translate

Conversation

@dangeredwolf

@dangeredwolf dangeredwolf commented Apr 1, 2026 •

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • New Features

    • Optional lang query parameter accepted across status, thread, conversation, search, profile, feed endpoints.
    • Requests now include validated language-aware headers when a language is provided.
    • Auto-translation features enabled by default for richer inline translation behavior.
  • Behavior Changes

    • Inline translations are preferred and applied when available; fallback translations run only when inline translation is absent and can be disabled per request.
    • Target languages are normalized before comparison; callers can override request headers.

@coderabbitai

coderabbitai Bot commented Apr 1, 2026 •

Copy link
Copy Markdown
Contributor

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 9d428b0a-a1da-429a-8de8-7a1afa50d454

📥 Commits

Reviewing files that changed from the base of the PR and between b06fae7 and adb38c2.

📒 Files selected for processing (1)
  • src/providers/twitter/processor.ts

📝 Walkthrough

Walkthrough

Adds optional per-request language header support and language propagation across Twitter GraphQL calls, thread/search/profile APIs, and route schemas; enables inline Grok translation handling in status processing and updates feature flags and types for Grok translation payloads.

Changes

Cohort / File(s) Summary
Language Helper
src/helpers/language.ts
Added exported buildLanguageHeaders(language) to validate/normalize input and return x-twitter-client-language header or undefined.
GraphQL infra & request plumbing
src/providers/twitter/graphql/orchestrator.ts, src/providers/twitter/graphql/request.ts
Added optional headers?: Record<string,string> to orchestrator/method/request interfaces; added mergeRequestHeaders(); merged/forwarded headers through method selection and into graphqlRequest → twitterFetch.
GraphQL features flags
src/providers/twitter/graphql/features.ts
Switched several Grok/translation and iOS translation feature flags from false to true.
Fetch layer header precedence
src/providers/twitter/fetch.ts
Reordered header spread so per-request _headers override Constants.BASE_HEADERS while preserving explicit Authorization.
Conversation & fetch APIs
src/providers/twitter/conversation.ts
Added optional language?: string to multiple exported fetch/construct functions; use buildLanguageHeaders(language) when calling orchestrator/graphql; threaded language through pagination, single-status fetches, article re-fetch, and status construction.
Search & User timelines
src/providers/twitter/search.ts, src/providers/twitter/userStatuses.ts
Extended searchAPI and profile timeline/article/media APIs (and paginated wrappers) with optional language?; pass headers: buildLanguageHeaders(language) to GraphQL calls and thread language into buildAPITwitterStatus.
Status processing & translation
src/providers/twitter/processor.ts
Applied inline Grok translation from grok_translated_post_with_availability when matching destination language; normalize language comparisons; gate manual Grok/Polyglot/LLM fallbacks behind manualTranslationFallback and !didTranslate; propagate nested Grok availability to top-level status.
Types
src/types/vendor/twitter.d.ts
Added GrokTranslatedPostWithAvailability type and optional grok_translated_post_with_availability fields on GraphQLTwitterStatus and nested tweet.
Routes & schemas
src/realms/api/routes.ts, src/realms/api/routes/twitter.ts, src/realms/twitter/routes/feed.ts
Added lang query schema and integrated into multiple routes; route handlers now read query.lang and forward it to provider functions; feed parsing extracts lang and propagates into paginated feed calls.

Sequence Diagram

sequenceDiagram
    autonumber
    actor Client
    participant Routes as "API Routes\n(routes/twitter.ts / routes)"
    participant Provider as "Twitter Provider\n(conversation/search/userStatuses)"
    participant Orchestrator as "GraphQL Orchestrator\n(orchestrator.ts)"
    participant Request as "GraphQL Request\n(request.ts)"
    participant Fetch as "twitterFetch / fetch.ts"
    participant Processor as "Status Processor\n(processor.ts)"

    Client->>Routes: GET /2/status/{id}?lang=es
    Routes->>Provider: constructTwitterThread(id, c, ..., language='es')
    Provider->>Orchestrator: graphQLOrchestrator({..., headers: buildLanguageHeaders('es')})
    Orchestrator->>Request: graphqlRequest({query, variables, headers: mergedHeaders})
    Request->>Fetch: twitterFetch(..., { headers: { Authorization, ...BASE_HEADERS, 'x-twitter-client-language': 'es' } })
    Fetch-->>Request: GraphQL response
    Request-->>Orchestrator: response
    Orchestrator-->>Provider: response
    Provider->>Processor: buildAPITwitterStatus(status, language='es')
    Processor->>Processor: Check grok_translated_post_with_availability\nmatch(destination_language == 'es')
    alt inline grok available & matches
        Processor->>Processor: Apply inline translation (provider: grok_inline)
    else
        Processor->>Processor: Run manual fallback translations (if enabled)
    end
    Processor-->>Provider: APITwitterStatus
    Provider-->>Routes: Thread/Conversation payload
    Routes-->>Client: JSON response
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • feat: media timelines #1885 — Modifies src/providers/twitter/userStatuses.ts and profileStatusesAPI; directly overlaps with signature and status-construction changes.
  • Improved graphql client #1290 — Introduced/refactored GraphQL fetching abstractions that this PR extends with per-request header propagation.
  • Twitter Article UI #1702 — Adjusts conversation/thread construction and article re-fetch logic; intersects with language/thread parameter threading.

Poem

🐰 I nibble headers in the night, a language tucked in paw,
I stitch Grok whispers into threads, so translations hop, hurrah!
Routes carry my tiny note across each GraphQL stream,
Tweets now sing in many tongues — a rabbit's quiet dream. ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 28.57% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title 'Use cached Grok translations for Twitter provider' accurately captures the main feature: leveraging cached Grok translations from GraphQL responses. The summary shows significant work integrating Grok translation payloads, feature flags, language headers, and translation pipeline updates across multiple files.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch auto-translate

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@dangeredwolf dangeredwolf changed the title feat: support twitter auto grok translation feat: Use cached Grok translations for Twitter provider Apr 1, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/providers/twitter/userStatuses.ts (2)

373-383: ⚠️ Potential issue | 🟡 Minor

profileMediaAPIPaginated does not accept or forward the language parameter.

Both profileMediaAPI and profileStatusesAPI support the language parameter, but the pagination wrapper profileMediaAPIPaginated (like profileStatusesAPIPaginated) doesn't expose it. Consider adding language?: string to the function signature and forwarding it to the underlying API call for API consistency.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/providers/twitter/userStatuses.ts` around lines 373 - 383, Add an
optional language parameter to profileMediaAPIPaginated and forward it into the
paginated calls: change the signature of profileMediaAPIPaginated to accept
language?: string, then pass that language through to profileMediaAPI inside the
paginateAndMerge callback (i.e., profileMediaAPI(handleOrId,
PROFILE_STATUSES_FEED_PER_PAGE, cursor, c, language)). This mirrors how
profileStatusesAPIPaginated exposes language and keeps API consistency with
profileMediaAPI; ensure types/signatures and any callers are updated
accordingly.

213-225: ⚠️ Potential issue | 🟡 Minor

profileStatusesAPIPaginated and profileMediaAPIPaginated do not support the language parameter.

Both base functions (profileStatusesAPI and profileMediaAPI) accept an optional language parameter used for setting request headers via buildLanguageHeaders, but their paginated wrappers do not expose this parameter. The feed routes that call these paginated functions also do not extract or forward language information, making language support incomplete for feed endpoints.

If language translation support is intended for feed endpoints, both paginated functions should accept and forward the language parameter.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/providers/twitter/userStatuses.ts` around lines 213 - 225, The paginated
wrappers profileStatusesAPIPaginated (and similarly profileMediaAPIPaginated)
currently omit the optional language parameter; update their signatures to
accept language?: string and forward that argument into the underlying calls to
profileStatusesAPI (and profileMediaAPI) inside paginateAndMerge so the
buildLanguageHeaders path is exercised; also update any feed route callers to
extract the language from the request (where feed endpoints build or pass
language today) and pass it through to these paginated functions so
language-aware headers are applied end-to-end.
🧹 Nitpick comments (2)
src/providers/twitter/conversation.ts (2)

686-686: Remove debug log before merging.

This console.log('language', language) statement appears to be debug output that will pollute production logs.

🧹 Remove debug statement
 export const constructTwitterThread = async (
   id: string,
   processThread = false,
   c: Context,
   language: string | undefined,
   legacyAPI = false
 ): Promise<SocialThread> => {
-  console.log('language', language);
 
   // Fetch status using orchestrator with appropriate method prioritization
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/providers/twitter/conversation.ts` at line 686, Remove the leftover debug
statement console.log('language', language) in
src/providers/twitter/conversation.ts; find the usage inside the function
handling language detection (search for the variable language or the surrounding
function where that line appears) and either delete the console.log or replace
it with a proper logging call (e.g., processLogger.debug or logger.debug) if
retaining the info is needed in debug-level logs; ensure no other stray
console.log calls remain in that function.

1108-1118: Remove or clarify the purpose of threadAPIProvider—it's an unused export.

This function is exported but never imported anywhere in the codebase. The v2 API routes (threadV2Route, statusV2Route, etc.) already support language parameters through Zod validation. If this endpoint is not actively used, consider removing it; otherwise, clarify its intended use and add language support to align with the v2 API pattern.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/providers/twitter/conversation.ts` around lines 1108 - 1118,
threadAPIProvider is an exported but unused endpoint; either remove this export
or update it to match v2 route patterns: if removing, delete the
threadAPIProvider function and any related references (keep
constructTwitterThread and Constants.API_RESPONSE_HEADERS untouched); if
keeping, clarify its purpose and add language support consistent with v2 by
accepting a language param from the request (e.g., c.req.query or Zod
validation) and passing it into constructTwitterThread, and ensure headers are
applied via Constants.API_RESPONSE_HEADERS and the JSON response status uses
processedResponse.code as before; update documentation/comments to state why
this separate provider exists.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/helpers/language.ts`:
- Around line 5-8: Trim and canonicalize the incoming language string before
building the header: first verify typeof language === 'string', then trim
whitespace and lowercase it (e.g. const cleaned =
language.trim().toLowerCase()), reject empty/whitespace-only cleaned values by
returning undefined, then pass cleaned into normalizeLanguage and return the
header { 'x-twitter-client-language': normalizeLanguage(cleaned) }; refer to
normalizeLanguage and the 'x-twitter-client-language' header to locate the
change.

In `@src/providers/twitter/graphql/request.ts`:
- Around line 21-22: The comment notes that GraphQL request headers passed via
the headers?: Record<string,string> option are meant to be merged last but are
being overwritten because src/providers/twitter/fetch.ts builds the final
headers as { ..._headers, Authorization: ..., ...Constants.BASE_HEADERS } and
Constants.BASE_HEADERS hardcodes x-twitter-client-language:'en'; to fix, change
the merge order in the code that constructs the final header map (in the
function that builds twitterFetch headers) so that Constants.BASE_HEADERS are
spread first, then Authorization, then _headers (or otherwise ensure _headers
overrides BASE_HEADERS), or remove x-twitter-client-language from BASE_HEADERS
and set it only when no explicit header is provided; update any similar merges
(the other occurrence referenced at lines 39-42) to follow the same precedence.

In `@src/providers/twitter/processor.ts`:
- Around line 714-729: The decision to bail out of translation is still
comparing raw language to status.legacy.lang, which can miss aliases normalized
by normalizeLanguage (normalizedTarget) and cause non-canonical target_lang;
update the earlier translate/no-translate check to compare
normalizeLanguage(language) (i.e., normalizedTarget) against
normalizeLanguage(status.legacy?.lang || '') so aliases like "jp"→"ja" are
handled consistently, and ensure when you set apiStatus.translation.target_lang
you use the normalizedTarget (or normalizeLanguage(language)) rather than the
raw language string so target_lang is canonical.

---

Outside diff comments:
In `@src/providers/twitter/userStatuses.ts`:
- Around line 373-383: Add an optional language parameter to
profileMediaAPIPaginated and forward it into the paginated calls: change the
signature of profileMediaAPIPaginated to accept language?: string, then pass
that language through to profileMediaAPI inside the paginateAndMerge callback
(i.e., profileMediaAPI(handleOrId, PROFILE_STATUSES_FEED_PER_PAGE, cursor, c,
language)). This mirrors how profileStatusesAPIPaginated exposes language and
keeps API consistency with profileMediaAPI; ensure types/signatures and any
callers are updated accordingly.
- Around line 213-225: The paginated wrappers profileStatusesAPIPaginated (and
similarly profileMediaAPIPaginated) currently omit the optional language
parameter; update their signatures to accept language?: string and forward that
argument into the underlying calls to profileStatusesAPI (and profileMediaAPI)
inside paginateAndMerge so the buildLanguageHeaders path is exercised; also
update any feed route callers to extract the language from the request (where
feed endpoints build or pass language today) and pass it through to these
paginated functions so language-aware headers are applied end-to-end.

---

Nitpick comments:
In `@src/providers/twitter/conversation.ts`:
- Line 686: Remove the leftover debug statement console.log('language',
language) in src/providers/twitter/conversation.ts; find the usage inside the
function handling language detection (search for the variable language or the
surrounding function where that line appears) and either delete the console.log
or replace it with a proper logging call (e.g., processLogger.debug or
logger.debug) if retaining the info is needed in debug-level logs; ensure no
other stray console.log calls remain in that function.
- Around line 1108-1118: threadAPIProvider is an exported but unused endpoint;
either remove this export or update it to match v2 route patterns: if removing,
delete the threadAPIProvider function and any related references (keep
constructTwitterThread and Constants.API_RESPONSE_HEADERS untouched); if
keeping, clarify its purpose and add language support consistent with v2 by
accepting a language param from the request (e.g., c.req.query or Zod
validation) and passing it into constructTwitterThread, and ensure headers are
applied via Constants.API_RESPONSE_HEADERS and the JSON response status uses
processedResponse.code as before; update documentation/comments to state why
this separate provider exists.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: e1c140ee-951e-4315-b478-c6d46cee455d

📥 Commits

Reviewing files that changed from the base of the PR and between cb65dcf and 0acac0b.

📒 Files selected for processing (11)
  • src/helpers/language.ts
  • src/providers/twitter/conversation.ts
  • src/providers/twitter/graphql/features.ts
  • src/providers/twitter/graphql/orchestrator.ts
  • src/providers/twitter/graphql/request.ts
  • src/providers/twitter/processor.ts
  • src/providers/twitter/search.ts
  • src/providers/twitter/userStatuses.ts
  • src/realms/api/routes.ts
  • src/realms/api/routes/twitter.ts
  • src/types/vendor/twitter.d.ts

Comment thread src/helpers/language.ts Resolved
Comment thread src/providers/twitter/processor.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/providers/twitter/conversation.ts (1)

975-986: ⚠️ Potential issue | 🟡 Minor

Align manualTranslationFallback parameter with conversation handling in thread building.

The thread status building at line 977 calls buildAPITwitterStatus(c, status, language, author, false) with 5 arguments, defaulting manualTranslationFallback to true. In contrast, constructTwitterConversation explicitly passes false for this parameter (lines 1029, 1063, 1086). Per the function's documentation comment, manualTranslationFallback=false is intended for contexts including "conversation" to restrict translation to GraphQL inline only. Consider updating line 977 to explicitly pass false for consistency, unless there is a specific reason threads should permit manual translation fallback.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/providers/twitter/conversation.ts` around lines 975 - 986, The call to
buildAPITwitterStatus in the thread mapping uses five args but relies on the
default manualTranslationFallback (true); update that call to explicitly pass
false as the fifth argument (matching other uses in
constructTwitterConversation) so manualTranslationFallback is false for thread
statuses—locate the Promise.all block where
socialThread.thread?.push(builtStatus) is called and change the
buildAPITwitterStatus invocation to pass false for the manualTranslationFallback
parameter.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/providers/twitter/processor.ts`:
- Around line 783-798: The code sets didTranslate = true unconditionally after
attempting LLM translation; update the block in processor.ts (the branch that
calls translateStatusAI) so that didTranslate is only set to true when
translateAPI is non-null and contains translated_text (i.e., inside the same
success branch where apiStatus.translation is assigned). Locate the
translateStatusAI call and the apiStatus.translation assignment and move the
didTranslate = true into that success path so failed/null responses do not flip
didTranslate.

---

Outside diff comments:
In `@src/providers/twitter/conversation.ts`:
- Around line 975-986: The call to buildAPITwitterStatus in the thread mapping
uses five args but relies on the default manualTranslationFallback (true);
update that call to explicitly pass false as the fifth argument (matching other
uses in constructTwitterConversation) so manualTranslationFallback is false for
thread statuses—locate the Promise.all block where
socialThread.thread?.push(builtStatus) is called and change the
buildAPITwitterStatus invocation to pass false for the manualTranslationFallback
parameter.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 4b3f1a34-0d35-45bc-b2a6-3468dd4f3e9d

📥 Commits

Reviewing files that changed from the base of the PR and between 0acac0b and bde7b1c.

📒 Files selected for processing (8)
  • src/helpers/language.ts
  • src/providers/twitter/conversation.ts
  • src/providers/twitter/fetch.ts
  • src/providers/twitter/graphql/features.ts
  • src/providers/twitter/processor.ts
  • src/providers/twitter/search.ts
  • src/providers/twitter/userStatuses.ts
  • src/realms/twitter/routes/feed.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/helpers/language.ts

Comment thread src/providers/twitter/processor.ts Resolved
@dangeredwolf
dangeredwolf enabled auto-merge April 1, 2026 06:30
@dangeredwolf
dangeredwolf merged commit d6ad858 into main Apr 1, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant