Repository navigation
feat: Use cached Grok translations for Twitter provider - #1899
Conversation
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughAdds 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
Sequence DiagramsequenceDiagram
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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
profileMediaAPIPaginateddoes not accept or forward thelanguageparameter.Both
profileMediaAPIandprofileStatusesAPIsupport thelanguageparameter, but the pagination wrapperprofileMediaAPIPaginated(likeprofileStatusesAPIPaginated) doesn't expose it. Consider addinglanguage?: stringto 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
profileStatusesAPIPaginatedandprofileMediaAPIPaginateddo not support thelanguageparameter.Both base functions (
profileStatusesAPIandprofileMediaAPI) accept an optionallanguageparameter used for setting request headers viabuildLanguageHeaders, 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
languageparameter.🤖 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 ofthreadAPIProvider—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
📒 Files selected for processing (11)
src/helpers/language.tssrc/providers/twitter/conversation.tssrc/providers/twitter/graphql/features.tssrc/providers/twitter/graphql/orchestrator.tssrc/providers/twitter/graphql/request.tssrc/providers/twitter/processor.tssrc/providers/twitter/search.tssrc/providers/twitter/userStatuses.tssrc/realms/api/routes.tssrc/realms/api/routes/twitter.tssrc/types/vendor/twitter.d.ts
There was a problem hiding this comment.
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 | 🟡 MinorAlign
manualTranslationFallbackparameter with conversation handling in thread building.The thread status building at line 977 calls
buildAPITwitterStatus(c, status, language, author, false)with 5 arguments, defaultingmanualTranslationFallbacktotrue. In contrast,constructTwitterConversationexplicitly passesfalsefor this parameter (lines 1029, 1063, 1086). Per the function's documentation comment,manualTranslationFallback=falseis intended for contexts including "conversation" to restrict translation to GraphQL inline only. Consider updating line 977 to explicitly passfalsefor 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
📒 Files selected for processing (8)
src/helpers/language.tssrc/providers/twitter/conversation.tssrc/providers/twitter/fetch.tssrc/providers/twitter/graphql/features.tssrc/providers/twitter/processor.tssrc/providers/twitter/search.tssrc/providers/twitter/userStatuses.tssrc/realms/twitter/routes/feed.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/helpers/language.ts
Summary by CodeRabbit
New Features
Behavior Changes