Repository navigation
Twitter Article UI - #1702
Twitter Article UI#1702
Conversation
|
Note Other AI code review bot(s) detectedCodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review. 📝 WalkthroughWalkthroughAdds end-to-end Twitter article support: detection, HTML rendering, link wrapping, media extraction/conversion, Instant View integration, router route additions, helper/type updates, i18n key changes, and updated test fixtures. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor Client
participant Router
participant Conversation as Conversation.ts
participant Processor as Processor.ts
participant Activity as Activity.ts
participant Article as Article Helper
Client->>Router: GET /:handle/:endpoint(status|article)/:id
Router->>Conversation: constructTwitterThread(req)
Conversation->>Processor: fetch TweetResultByIds
Processor-->>Conversation: status (may lack article blocks)
alt status lacks article blocks
Conversation->>Processor: fetch TweetResultByRestId
Processor-->>Conversation: enriched status with article content
Conversation->>Conversation: rebuild APITwitterStatus
end
Conversation->>Activity: handleActivity(status)
Activity->>Activity: getStatusText(status) → { text, articleMedia }
alt article present
Activity->>Article: renderArticleToHtml(articleContent)
Article-->>Activity: { html, collectedMedia }
Activity->>Activity: convertArticleMediaToAttachment() & merge into media_attachments
end
Activity-->>Client: Return activity payload (content, attachments, meta/IV data)
Estimated Code Review Effort🎯 4 (Complex) | ⏱️ ~55 minutes Possibly related PRs
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 inconclusive)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 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.
This is the final PR Bugbot will review for you during this billing cycle
Your free Bugbot reviews will reset on January 20
Details
You are on the Bugbot Free tier. On this plan, Bugbot will review limited PRs each billing cycle.
To receive Bugbot reviews on all of your PRs, visit the Cursor dashboard to activate Pro and start your 14-day free trial.
There was a problem hiding this comment.
Actionable comments posted: 4
♻️ Duplicate comments (1)
src/embed/status.ts (1)
34-67: Duplicate code: Same function exists ininstantview.ts.As noted in the
instantview.tsreview, thisisArticleOnlyTweetfunction is duplicated. Extract to a shared location.
🧹 Nitpick comments (6)
src/helpers/utils.ts (1)
95-108: Consider renamingunwraptoshouldWrapfor clarity.The variable name
unwrapis misleading since it determines whether the URL should be wrapped, not unwrapped. Settingunwrap = truemeans "wrap this URL", which is counterintuitive.Also, note that the hostname check uses exact match, so subdomains like
mobile.twitter.comorwww.x.comwould be wrapped. If this is intentional, it's fine; otherwise, consider usingendsWith()for suffix matching.🔎 Suggested rename for clarity
export const wrapForeignLinks = (url: string, apiHost: string): string => { - let unwrap = false; + let shouldWrap = false; const whitelistedDomains = ['twitter.com', 'x.com', 't.me', 'telegram.me', 'bsky.app']; try { const urlObj = new URL(url); if (!whitelistedDomains.includes(urlObj.hostname)) { - unwrap = true; + shouldWrap = true; } } catch (_e) { - unwrap = true; + shouldWrap = true; } - return unwrap ? `https://${apiHost}/2/hit?url=${encodeURIComponent(url)}` : url; + return shouldWrap ? `https://${apiHost}/2/hit?url=${encodeURIComponent(url)}` : url; };src/providers/twitter/conversation.ts (1)
575-594: LGTM! Consider adding error logging for failed re-fetch.The re-fetch logic correctly handles cases where the initial fetch doesn't include full article content blocks. The defensive checks are good. However, it might be helpful to log when the re-fetch fails to aid debugging.
🔎 Optional: Add logging for failed re-fetch
const articleResponse = await fetchByRestId(id, c); if (articleResponse?.data?.tweetResult?.result) { const rebuiltStatus = await buildAPITwitterStatus( c, articleResponse.data.tweetResult.result as GraphQLTwitterStatus, language, null, legacyAPI ); if (rebuiltStatus && !(rebuiltStatus as FetchResults)?.status) { status = rebuiltStatus as APITwitterStatus; } + } else { + console.log('Article re-fetch returned no result'); }src/render/instantview.ts (1)
19-46: Duplicate code:isArticleOnlyTweetis defined in bothinstantview.tsandstatus.ts.This function is duplicated verbatim in
src/embed/status.ts(lines 34-67). Consider extracting it to a shared utility file (e.g.,src/helpers/article.ts) to maintain DRY principles and ensure consistent behavior.🔎 Suggested extraction to shared utility
Move
isArticleOnlyTweettosrc/helpers/article.tsand import it in both files:// In src/helpers/article.ts, add: export const isArticleOnlyTweet = (status: APITwitterStatus): boolean => { if (!status.article) { return false; } const text = status.text.trim(); if (!text) { return true; } const articleUrlPattern = /^https?:\/\/(x\.com|twitter\.com)\/i\/article\/\d+\/?$/; const tcoPattern = /^https?:\/\/t\.co\/\w+$/; if (articleUrlPattern.test(text) || tcoPattern.test(text)) { return true; } if (text === status.article.title) { return true; } return false; };Then import and use it in both
instantview.tsandstatus.ts.src/embed/activity.ts (1)
30-113: Consider extracting shared media conversion logic.The
convertArticleMediaToAttachmentfunction duplicates some logic present in the switch statement at lines 520-578 (for regular media). Both handle image/video conversion with similar patterns (size multiplier calculation, redirect workaround). Consider extracting common logic to reduce duplication.Additionally, the hardcoded ID
'114163769487684704'used elsewhere for regular media attachments could be added here for consistency, or better yet, both could generate unique IDs.src/helpers/article.ts (2)
11-11: Consider makingDISCORD_ARTICLE_MAX_LENGTHconfigurable or documenting the value.The hardcoded value of 10000 should ideally be documented with rationale (Discord's embed limit?) or made configurable via constants.
-const DISCORD_ARTICLE_MAX_LENGTH = 10000; +/** + * Maximum article content length for Discord embeds. + * Discord has limits on embed content size; this ensures articles don't exceed them. + */ +const DISCORD_ARTICLE_MAX_LENGTH = 10000;
376-395: Embedded tweet rendering uses Twitter's old domain.The tweet embed uses
twitter.comin the URL (https://twitter.com/i/status/${tweetId}). For consistency with the rest of the codebase which usesx.com, consider updating this.🔎 Suggested fix
if (options.renderInlineMedia) { // For Telegram: use Twitter's embed format which Instant View will process - const tweetEmbed = `<blockquote class="twitter-tweet"><a href="https://twitter.com/i/status/${tweetId}">Tweet</a></blockquote>`; + const tweetEmbed = `<blockquote class="twitter-tweet"><a href="https://x.com/i/status/${tweetId}">Tweet</a></blockquote>`;
📜 Review details
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (17)
i18n/en/resources.jsoni18n/resources.jsonsrc/embed/activity.tssrc/embed/status.tssrc/helpers/article.tssrc/helpers/linkFixer.tssrc/helpers/utils.tssrc/providers/twitter/conversation.tssrc/providers/twitter/processor.tssrc/realms/twitter/router.tssrc/render/instantview.tssrc/types/types.d.tssrc/types/vendor/twitter.d.tstest/mocks/AboutAccountQuery/x.jsontest/mocks/TweetResultByRestId/1964084223871971826.jsontest/mocks/TweetResultsByRestIds/1964084223871971826.jsontest/mocks/UserResultByScreenName/x.json
💤 Files with no reviewable changes (1)
- test/mocks/AboutAccountQuery/x.json
🧰 Additional context used
🧬 Code graph analysis (6)
src/providers/twitter/conversation.ts (2)
src/providers/twitter/processor.ts (1)
buildAPITwitterStatus(24-602)src/realms/api/routes/twitter.ts (2)
c(20-31)c(7-18)
src/helpers/article.ts (2)
src/types/vendor/twitter.d.ts (5)
TwitterApiMedia(849-854)TwitterArticleContentBlock(913-928)TwitterApiImage(856-867)TwitterApiVideo(869-906)TwitterArticleContentState(908-911)src/helpers/utils.ts (3)
wrapForeignLinks(95-109)sanitizeText(1-7)truncateWithEllipsis(18-33)
test/mocks/TweetResultsByRestIds/1964084223871971826.json (1)
test/api.status.test.ts (1)
result(46-85)
src/render/instantview.ts (3)
src/constants.ts (1)
Constants(1-83)src/helpers/article.ts (1)
renderArticleToHtml(470-559)src/helpers/utils.ts (1)
sanitizeText(1-7)
src/embed/status.ts (2)
src/types/vendor/twitter.d.ts (1)
TwitterApiImage(856-867)src/helpers/utils.ts (1)
sanitizeText(1-7)
src/embed/activity.ts (5)
src/types/vendor/twitter.d.ts (3)
TwitterApiMedia(849-854)TwitterApiImage(856-867)TwitterApiVideo(869-906)src/types/types.d.ts (1)
ActivityMediaAttachment(379-402)src/experiments.ts (1)
experimentCheck(67-72)src/constants.ts (1)
Constants(1-83)src/helpers/article.ts (2)
renderArticleToHtml(470-559)DISCORD_ARTICLE_MAX_LENGTH(561-561)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: Cursor Bugbot
🔇 Additional comments (17)
test/mocks/UserResultByScreenName/x.json (1)
1-120: Formatting changes are cosmetic and have no impact.The JSON structure and data remain unchanged; only whitespace and array formatting have been adjusted.
test/mocks/TweetResultByRestId/1964084223871971826.json (1)
1-1102: LGTM - Formatting normalization for test mock.The changes are formatting adjustments (converting multi-line arrays to single-line inline arrays) with no logical changes to the mock data structure.
i18n/en/resources.json (1)
61-62: LGTM - New article indicator translation.The
articleIndicatorkey follows the established pattern matchingthreadIndicatorwith consistent formatting (emoji + label + branding placeholder).src/helpers/linkFixer.ts (1)
12-14: LGTM - Extended URL pattern for x.com support.The regex correctly handles both
x.comandtwitter.comdomains for the internal web status URL pattern, ensuring consistent behavior after Twitter's rebranding.src/realms/twitter/router.ts (1)
53-86: LGTM - Article endpoint routing support.The route patterns are consistently updated to support the
articleendpoint alongsidestatus(es)?. All route variants (root, i/web, handle-prefixed, with language, with media type) are properly covered.test/mocks/TweetResultsByRestIds/1964084223871971826.json (1)
3-1102: LGTM - Mock structure aligned with batch API response format.The structural change from
tweetResult: { result }totweetResult: [ { result } ]correctly matches theTweetResultsByRestIdsResponsetype which expects an array. All required community and user data for existing tests is preserved.src/types/types.d.ts (1)
6-11: LGTM - Import reorganization for article type support.The multi-line import format improves readability and correctly includes
TwitterArticleContentStateneeded for the article content type definitions.src/types/vendor/twitter.d.ts (1)
956-966: LGTM - TWEET variant for article entity map.The new
TWEETvariant follows the established discriminated union pattern forTwitterArticleEntityMapEntry, enabling proper typing for embedded tweet references within article content.i18n/resources.json (1)
39-39: LGTM - Article indicator added to translation resources.The
articleIndicatorkey is properly added with consistent formatting matching other indicator translations.src/render/instantview.ts (1)
211-213: LGTM!Good refactor to centralize the
wrapForeignLinkslogic by delegating to the utility function.src/embed/activity.ts (1)
140-156: LGTM! Article rendering integration.The article rendering integration properly returns both the rendered HTML text and collected media for subsequent processing. The title prepending with the 📰 emoji provides good visual distinction.
src/embed/status.ts (2)
591-603: LGTM! Article cover image handling for Open Graph.The code correctly uses the article cover image for
og:imagewhen it's an article-only tweet without regular media. The embed card type is appropriately set tosummary_large_imagefor better preview rendering.
629-634: Potential XSS: Verifypreview_textis sanitized.The
preview_textfrom the article is assigned to thetextvariable which is used inog:description. WhilesanitizeTextis applied tonewTextat line 627, thepreview_textassigned at line 633 replaces it after sanitization occurs earlier.Looking at line 627,
sanitizeText(newText)is applied first, but then line 633 setstext = sanitizeText(twitterStatus.article.preview_text)which correctly sanitizes. This is fine.src/helpers/article.ts (4)
50-105: LGTM! Clean inline link collection.The function properly handles mentions, URLs, hashtags, and cashtags with appropriate link generation. The reverse sorting for safe replacement is a good technique.
220-223: Potential issue: HTML detection regex may have false positives.The regex
/<[^>]+>/to detect HTML tags could match legitimate text content like"x < y > z"if it somehow appeared unsanitized. However, since this is checking text that may already contain rendered media HTML, this should be acceptable. Just be aware of edge cases.
294-344: LGTM! Media entity handling.The media rendering logic properly handles both inline rendering for Telegram (with actual HTML elements) and collection for Discord. The MP4 variant filtering to exclude m3u8 playlists is a good catch.
470-559: LGTM! Main rendering function.The
renderArticleToHtmlfunction properly handles:
- List grouping with
flushList- Truncation checks at appropriate boundaries
- Media collection
- The
wasTruncatedflag for downstream handling
| if (status.legacy.entities?.urls) { | ||
| status.legacy.entities.urls = status.legacy.entities.urls.filter( | ||
| url => url.expanded_url.match(/^http:\/\/x\.com\/i\/article\/\w+/g) === null | ||
| ); | ||
| } |
There was a problem hiding this comment.
Bug: Regex only matches http:// but article URLs are typically https://.
The regex pattern /^http:\/\/x\.com\/i\/article\/\w+/g only matches http:// URLs, but Twitter/X article URLs are typically served over https://. This means the filter won't remove the intended article URLs.
🔎 Proposed fix
if (status.legacy.entities?.urls) {
status.legacy.entities.urls = status.legacy.entities.urls.filter(
- url => url.expanded_url.match(/^http:\/\/x\.com\/i\/article\/\w+/g) === null
+ url => url.expanded_url.match(/^https?:\/\/x\.com\/i\/article\/\w+/g) === null
);
}🤖 Prompt for AI Agents
In src/providers/twitter/processor.ts around lines 83 to 87, the filter's regex
only matches "http://" article URLs so it misses typical "https://" X article
links; update the pattern to accept both http and https (and optionally allow a
leading "www.") and remove the global flag — e.g. use a case-insensitive pattern
like ^https?:\/\/(www\.)?x\.com\/i\/article\/\w+ and use match/test accordingly
so article URLs are properly filtered out.
There was a problem hiding this comment.
Addressed this in a comment above the line:
Yes this uses http:// not https://. Don't know why. Hesitant to also include https because we just want to get rid of the extraneous article url at the end, not eliminate all article urls
There was a problem hiding this comment.
@dangeredwolf, thank you for the clarification! I appreciate you adding the comment to document this behavior. If the Twitter API is indeed returning article URLs with http:// in the expanded_url field (even though the actual URLs are served over https://), then your regex is correctly targeting what the API actually returns.
Your concern about being selective—only filtering the extraneous auto-appended article URL rather than all article references—makes perfect sense. If you've tested this with real API responses and confirmed it works as intended, then the implementation is appropriate for the specific behavior you're handling.
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
src/embed/activity.ts (2)
524-524: Hard-coded media IDs break the deduplication logic.All regular media attachments use the same hard-coded ID
'114163769487684704'(lines 524, 558, etc.), while article attachments use actualmedia.media_idvalues. The deduplication logic at lines 581-584 creates a Set of existing IDs, but since all regular media share the same ID, it can't effectively detect duplicates between regular and article media.This undermines the deduplication fix from commit 3897e04 mentioned in the previous review.
🔎 Proposed fix
Use unique identifiers for all media attachments. Consider:
- Using a hash of the media URL as the ID
- Using the actual media ID from the source if available
- Generating sequential IDs (e.g.,
${statusId}_${index})Example for photos:
case 'photo': const image = media as APIPhoto; return { - id: '114163769487684704', + id: image.id || `${statusId}_photo_${index}`, type: 'image',Similar changes would be needed for videos and external media.
Also applies to: 558-558, 581-584
544-551: Extract duplicate size multiplier logic into a shared helper function.The size multiplier logic is duplicated between lines 59-68 (in
convertArticleMediaToAttachment) and lines 544-551 (inhandleActivity). This violates the DRY principle and means the bug mentioned in the earlier comment exists in both places.🔎 Proposed refactor
Create a helper function:
const calculateSizeMultiplier = (width: number, height: number): number => { if ((width > 1920 || height > 1920) && width >= 400 && height >= 400) { return 0.5; } else if (width < 400 || height < 400) { return 2; } return 1; };Then use it in both places:
- let sizeMultiplier = 1; - - if (video.width > 1920 || video.height > 1920) { - sizeMultiplier = 0.5; - } - if (video.width < 400 || video.height < 400) { - sizeMultiplier = 2; - } + const sizeMultiplier = calculateSizeMultiplier(video.width, video.height);
🧹 Nitpick comments (2)
src/embed/activity.ts (2)
58-58: Consider selecting video variants by quality rather than using the first one.Currently, the code takes
variants?.[0]without sorting by quality or bitrate. For better user experience, consider sorting variants by quality (e.g., preferring higher bitrate or resolution) before selecting one.
433-436: Remove redundant?? undefinedoperators.Optional chaining (
?.) already returnsundefinedfor nullish values, making?? undefinedredundant. These lines can be simplified.🔎 Proposed simplification
- avatar: thread.status.author.avatar_url ?? undefined, - avatar_static: thread.status.author.avatar_url ?? undefined, - header: thread.status.author.banner_url ?? undefined, - header_static: thread.status.author.banner_url ?? undefined, + avatar: thread.status.author.avatar_url, + avatar_static: thread.status.author.avatar_url, + header: thread.status.author.banner_url, + header_static: thread.status.author.banner_url,
📜 Review details
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
src/embed/activity.tssrc/providers/twitter/processor.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/providers/twitter/processor.ts
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-03-20T22:06:37.031Z
Learnt from: dangeredwolf
Repo: FxEmbed/FxEmbed PR: 1203
File: src/helpers/branding.ts:2-2
Timestamp: 2025-03-20T22:06:37.031Z
Learning: In the FxEmbed codebase, branding.json is not committed to the repository but is generated at build time by copying from branding.default.json. The import statements correctly reference branding.json as that's the file that will exist at runtime.
Applied to files:
src/embed/activity.ts
🔇 Additional comments (2)
src/embed/activity.ts (2)
27-28: LGTM!The imports are appropriate for the article handling feature.
395-398: LGTM!The article media extraction and conversion logic is clean and correctly handles the StatusTextResult destructuring and null filtering.
Also applies to: 456-459
| let sizeMultiplier = 1; | ||
| const width = video.original_info.width; | ||
| const height = video.original_info.height; | ||
|
|
||
| if (width > 1920 || height > 1920) { | ||
| sizeMultiplier = 0.5; | ||
| } | ||
| if (width < 400 || height < 400) { | ||
| sizeMultiplier = 2; | ||
| } |
There was a problem hiding this comment.
Fix the size multiplier logic to handle both dimensions correctly.
The current implementation has independent conditions that can overwrite each other. For example, a 3000×300 video would:
- Set
sizeMultiplier = 0.5(width > 1920) - Immediately overwrite it to
sizeMultiplier = 2(height < 400)
This results in incorrect sizing for edge-case aspect ratios. Consider using else if or combining conditions with logical operators to prevent overwriting.
🔎 Proposed fix
let sizeMultiplier = 1;
const width = video.original_info.width;
const height = video.original_info.height;
- if (width > 1920 || height > 1920) {
+ if ((width > 1920 || height > 1920) && width >= 400 && height >= 400) {
sizeMultiplier = 0.5;
- }
- if (width < 400 || height < 400) {
+ } else if (width < 400 || height < 400) {
sizeMultiplier = 2;
}Note: The same issue exists in lines 546-551 in the main media handling flow and should be fixed there as well.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| let sizeMultiplier = 1; | |
| const width = video.original_info.width; | |
| const height = video.original_info.height; | |
| if (width > 1920 || height > 1920) { | |
| sizeMultiplier = 0.5; | |
| } | |
| if (width < 400 || height < 400) { | |
| sizeMultiplier = 2; | |
| } | |
| let sizeMultiplier = 1; | |
| const width = video.original_info.width; | |
| const height = video.original_info.height; | |
| if ((width > 1920 || height > 1920) && width >= 400 && height >= 400) { | |
| sizeMultiplier = 0.5; | |
| } else if (width < 400 || height < 400) { | |
| sizeMultiplier = 2; | |
| } |
🤖 Prompt for AI Agents
In src/embed/activity.ts around lines 59 to 68, the sizeMultiplier logic uses
independent ifs that can overwrite each other for mixed-dimension videos; change
it so the large-dimension rule wins (e.g., if either width or height > 1920 set
sizeMultiplier = 0.5, else if either width or height < 400 set sizeMultiplier =
2) or combine the conditions with logical operators to avoid overwriting (use if
(...) { sizeMultiplier = 0.5 } else if (...) { sizeMultiplier = 2 }); apply the
same fix at the duplicate site around lines 546-551 in the main media handling
flow.
There was a problem hiding this comment.
It is a pretty negligible issue since:
- Not all clients even respect video width/height as it is
- Very few videos actually lie outside typical aspect ratios, such as 16:9, 16:10, 4:3, and portrait equivalents
Therefore, I decided i don't care
There was a problem hiding this comment.
@dangeredwolf, understood! That's a fair practical consideration—if clients don't reliably respect these dimensions and the edge cases are rare, it makes sense to prioritize other work. Thanks for the clarification!
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/embed/activity.ts (1)
153-153: Consider validating article title before use.While the code checks for
twitterStatus.articleexistence at line 145, it doesn't validate thatarticle.titleis present before using it in the formatted string. An article with a missing or empty title could result in awkward formatting like<b>📰 </b>.🔎 Proposed fix
- text = `<b>📰 ${twitterStatus.article.title}</b>${articleResult.html}`; + const title = twitterStatus.article.title || i18next.t('untitledArticle'); + text = `<b>📰 ${title}</b>${articleResult.html}`;
📜 Review details
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/embed/activity.ts
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-03-20T22:06:37.031Z
Learnt from: dangeredwolf
Repo: FxEmbed/FxEmbed PR: 1203
File: src/helpers/branding.ts:2-2
Timestamp: 2025-03-20T22:06:37.031Z
Learning: In the FxEmbed codebase, branding.json is not committed to the repository but is generated at build time by copying from branding.default.json. The import statements correctly reference branding.json as that's the file that will exist at runtime.
Applied to files:
src/embed/activity.ts
🧬 Code graph analysis (1)
src/embed/activity.ts (5)
src/types/vendor/twitter.d.ts (3)
TwitterApiMedia(849-854)TwitterApiImage(856-867)TwitterApiVideo(869-906)src/types/types.d.ts (1)
ActivityMediaAttachment(379-402)src/experiments.ts (1)
experimentCheck(67-72)src/constants.ts (1)
Constants(1-83)src/helpers/article.ts (2)
renderArticleToHtml(470-559)DISCORD_ARTICLE_MAX_LENGTH(561-561)
🔇 Additional comments (4)
src/embed/activity.ts (4)
395-398: LGTM: Clean article media extraction.The destructuring of
statusResultcleanly separates the status text from article media, making the subsequent integration straightforward and maintainable.
456-458: LGTM: Article media conversion with proper filtering.The map-filter pattern correctly converts article media to attachments and removes any
nullresults from unrecognized media types. The type assertion is appropriate after filtering.
580-583: LGTM: Deduplication correctly implemented.The deduplication logic properly creates a
Setof existing media IDs and filters out article attachments that would be duplicates. This addresses the concern from the previous review.
607-609: LGTM: Appropriate fallback for article-only media.The fallback logic correctly handles the case where a tweet has article media but no regular media attachments, ensuring article media is still displayed.
| media.media_info.__typename === 'ApiGif' | ||
| ) { | ||
| const video = media.media_info as TwitterApiVideo; | ||
| const videoUrl = video.video_info?.variants?.[0]?.url || video.media_url_https; |
There was a problem hiding this comment.
Add fallback validation for video URL.
The fallback chain video.video_info?.variants?.[0]?.url || video.media_url_https may result in undefined if both the variants array is empty and media_url_https is missing. Consider adding explicit validation or a default placeholder URL to prevent downstream issues when constructing the attachment.
🔎 Proposed fix
- const videoUrl = video.video_info?.variants?.[0]?.url || video.media_url_https;
+ const videoUrl = video.video_info?.variants?.[0]?.url || video.media_url_https || '';
+ if (!videoUrl) {
+ console.warn('Missing video URL for media', media.media_id);
+ return null;
+ }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const videoUrl = video.video_info?.variants?.[0]?.url || video.media_url_https; | |
| const videoUrl = video.video_info?.variants?.[0]?.url || video.media_url_https || ''; | |
| if (!videoUrl) { | |
| console.warn('Missing video URL for media', media.media_id); | |
| return null; | |
| } |
🤖 Prompt for AI Agents
In src/embed/activity.ts around line 58, the expression const videoUrl =
video.video_info?.variants?.[0]?.url || video.media_url_https can still yield
undefined when variants is empty and media_url_https is missing; update the code
to explicitly validate the chosen URL before using it: check that
video.video_info?.variants is a non-empty array and that the variant[0].url is a
non-empty string, otherwise check video.media_url_https, and if neither is
present either assign a safe placeholder URL or skip/omit creating the
attachment (and log/warn) so downstream code never receives undefined.
There was a problem hiding this comment.
It would be a bit nonsensical for the twitter API to give us a video but not populate any media information, don't you think?
There was a problem hiding this comment.
@dangeredwolf You're absolutely right—if the Twitter API is returning a video media entity, it should indeed include the necessary URL information. My suggestion was overly defensive for a scenario that shouldn't occur in practice. Thanks for the clarification!
| let sizeMultiplier = 1; | ||
| const width = video.original_info.width; | ||
| const height = video.original_info.height; | ||
|
|
||
| if (width > 1920 || height > 1920) { | ||
| sizeMultiplier = 0.5; | ||
| } | ||
| if (width < 400 || height < 400) { | ||
| sizeMultiplier = 2; | ||
| } |
There was a problem hiding this comment.
It is a pretty negligible issue since:
- Not all clients even respect video width/height as it is
- Very few videos actually lie outside typical aspect ratios, such as 16:9, 16:10, 4:3, and portrait equivalents
Therefore, I decided i don't care
| media.media_info.__typename === 'ApiGif' | ||
| ) { | ||
| const video = media.media_info as TwitterApiVideo; | ||
| const videoUrl = video.video_info?.variants?.[0]?.url || video.media_url_https; |
There was a problem hiding this comment.
It would be a bit nonsensical for the twitter API to give us a video but not populate any media information, don't you think?
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (1)
src/embed/activity.ts (1)
63-68: Size multiplier conditions can still overwrite each other.This was flagged in a past review: a 3000×300 video would set
sizeMultiplier = 0.5(width > 1920), then immediately overwrite tosizeMultiplier = 2(height < 400). Consider usingelse ifto prevent this:if (width > 1920 || height > 1920) { sizeMultiplier = 0.5; - } - if (width < 400 || height < 400) { + } else if (width < 400 || height < 400) { sizeMultiplier = 2; }The same issue exists at lines 547-552.
🧹 Nitpick comments (2)
src/providers/twitter/conversation.ts (1)
575-594: Comment mentions singular API but code uses plural endpoint.Line 580 says "re-fetching with TweetResultByRestId" but the actual call at line 581 is
fetchByRestIds([id], c)(plural). This is a minor documentation inconsistency. Consider updating the comment to match the actual API being called:- console.log('Article lacks content blocks, re-fetching with TweetResultByRestId...'); + console.log('Article lacks content blocks, re-fetching with TweetResultsByRestIds...');The fallback logic itself is correct—if the rebuild fails, the original status is preserved.
src/render/instantview.ts (1)
19-46:isArticleOnlyTweetis duplicated insrc/embed/status.ts.This function has nearly identical logic in
src/embed/status.ts(lines 34-67). Consider extracting it to a shared helper (e.g.,src/helpers/article.tsorsrc/helpers/utils.ts) to avoid maintaining the same logic in two places.
📜 Review details
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
src/embed/activity.tssrc/embed/status.tssrc/helpers/article.tssrc/providers/twitter/conversation.tssrc/render/instantview.ts
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-03-20T22:06:37.031Z
Learnt from: dangeredwolf
Repo: FxEmbed/FxEmbed PR: 1203
File: src/helpers/branding.ts:2-2
Timestamp: 2025-03-20T22:06:37.031Z
Learning: In the FxEmbed codebase, branding.json is not committed to the repository but is generated at build time by copying from branding.default.json. The import statements correctly reference branding.json as that's the file that will exist at runtime.
Applied to files:
src/embed/activity.ts
🧬 Code graph analysis (3)
src/providers/twitter/conversation.ts (1)
src/providers/twitter/processor.ts (1)
buildAPITwitterStatus(24-604)
src/embed/status.ts (2)
src/types/vendor/twitter.d.ts (1)
TwitterApiImage(856-867)src/helpers/utils.ts (1)
sanitizeText(1-7)
src/render/instantview.ts (3)
src/constants.ts (1)
Constants(1-83)src/helpers/article.ts (1)
renderArticleToHtml(470-559)src/helpers/utils.ts (1)
sanitizeText(1-7)
🔇 Additional comments (12)
src/render/instantview.ts (2)
332-360: Article rendering integration looks good.The article rendering for Telegram IV correctly:
- Uses
fullRenderer: truefor inline media- Handles cover media (image-only is acceptable per prior discussion)
- Properly constructs the article HTML block with cover and content
435-460: Good UX for article-only tweets.The heading hierarchy correctly prioritizes the article title as the main heading while preserving author information in a secondary heading. Removing the "View full thread" link for article-only tweets makes sense since articles are standalone content.
src/embed/status.ts (2)
629-634: OG title/description override is correctly scoped to Telegram.The condition
articleOnly && twitterStatus.article && isTelegramensures the article title and preview text are only used for Telegram bots, matching the commit message "fix: only override article og:title on telegram". This prevents breaking previews on other platforms.
591-614: Article cover media handling is well-structured.The no-media branch correctly prioritizes article cover images over the default avatar, with proper type checking via
__typename === 'ApiImage'. Theembed_cardis appropriately set tosummary_large_imagefor articles with cover media.src/embed/activity.ts (2)
140-158: Provider check correctly guards Twitter-specific article access.The condition
status.provider === DataProvider.Twitterat line 144 properly guards the article-specific logic, addressing the past review concern about accessing Twitter-specific fields on non-Twitter statuses.
581-585: Deduplication logic is correctly implemented.The approach of building a
Setof existing IDs and filtering article attachments before pushing prevents duplicate media, as confirmed in a past review.src/helpers/article.ts (6)
1-24: Well-structured interfaces and imports.The interface definitions are clear and well-documented.
ArticleRenderOptionsproperly distinguishes between Telegram (fullRenderer: true) and Discord (fullRenderer: false) rendering modes.
45-105: Link collection is comprehensive and correctly ordered.The function handles all Twitter-specific link types (mentions, URLs, hashtags, cashtags) and correctly sorts them in reverse order for safe string replacement. The optional
apiHostparameter for Telegram link wrapping is a clean approach.
107-263: Event-based style/link processing is well-designed.The approach of converting style/link ranges to events and processing them in position order correctly handles overlapping ranges. The HTML detection at line 220 (
/<[^>]+>/.test(segment.text)) prevents double-sanitization of inline media tags. Link transitions are properly managed with balanced open/close tags.
265-465: Block rendering handles all entity types correctly.The function properly differentiates between Telegram (inline media, tweet embeds) and Discord (media collection, tweet skipping) rendering. Key highlights:
- Video variant filtering to MP4 only (lines 313-314) is correct
- Code blocks preserve language for syntax highlighting (line 359)
- Atomic blocks without media are correctly handled (lines 445-447)
536-541: Known limitation: HTML truncation may produce malformed markup.As acknowledged in past reviews,
truncateWithEllipsison HTML content may cut through tags. Per maintainer's assessment, this is acceptable since the actual platform limits are more restrictive and the HTML is converted to markdown anyway, so worst case is some stray markdown syntax.
470-559: Clean public API with well-organized structure.The
renderArticleToHtmlfunction provides a clear entry point with well-defined options and result structure. The list grouping logic correctly handles transitions between ordered and unordered lists, and theflushListhelper keeps the main loop clean.
Implements #867
Supported fully in Telegram Instant View and mostly works on Discord

Note
Introduces end-to-end support for Twitter Articles across embeds and APIs.
renderArticleToHtmlhelper to parse article content (styles, links, media, code, embedded tweets) and collect mediaactivity.ts: detects articles, renders HTML (Discord-limited), and converts article media tomedia_attachmentsinstantview.ts: renders article title/body/cover inline, updates site indicator toarticleIndicator, improves link wrappingstatus.ts: article-aware previews (image/title/description), better OG tags and card selectionarticleendpointswrapForeignLinks;linkFixerrecognizes x.com pathsarticleIndicatorstringsTWEETentity support in article entity mapWritten by Cursor Bugbot for commit 3897e04. This will update automatically on new commits. Configure here.
Summary by CodeRabbit
✏️ Tip: You can customize this high-level summary in your review settings.