Skip to content

Twitter Article UI - #1702

Merged
dangeredwolf merged 13 commits into
mainfrom
article-ui
Dec 28, 2025
Merged

dangeredwolf merged 13 commits into
mainfrom
article-ui

Conversation

@dangeredwolf

@dangeredwolf dangeredwolf commented Dec 27, 2025 •

Copy link
Copy Markdown
Member

Implements #867

Supported fully in Telegram Instant View and mostly works on Discord
Screenshot 2025-12-27 at 05 05 55


Note

Introduces end-to-end support for Twitter Articles across embeds and APIs.

  • New renderArticleToHtml helper to parse article content (styles, links, media, code, embedded tweets) and collect media
  • activity.ts: detects articles, renders HTML (Discord-limited), and converts article media to media_attachments
  • instantview.ts: renders article title/body/cover inline, updates site indicator to articleIndicator, improves link wrapping
  • status.ts: article-aware previews (image/title/description), better OG tags and card selection
  • Routing: extend Twitter routes to include article endpoints
  • Provider: re-fetch tweet via RestId when article blocks are missing; strip extraneous article URLs in processor
  • Utilities: centralize wrapForeignLinks; linkFixer recognizes x.com paths
  • i18n: add articleIndicator strings
  • Types: add TWEET entity support in article entity map
  • Tests: add mocks for article/tweet/user scenarios

Written by Cursor Bugbot for commit 3897e04. This will update automatically on new commits. Configure here.

Summary by CodeRabbit

  • New Features
    • Full article support: rendered article HTML, preview/truncation, cover media and article attachments in embeds and Instant View.
  • Bug Fixes
    • Better external link handling and proxying, cleaner article URL filtering, improved media merge/de-duplication, and reduced verbose logging.
  • Localization
    • Added article indicator translation; removed obsolete GIF indicator.
  • Tests
    • Updated and normalized JSON test fixtures and mocks.

✏️ Tip: You can customize this high-level summary in your review settings.

@dangeredwolf dangeredwolf self-assigned this Dec 27, 2025
@coderabbitai

coderabbitai Bot commented Dec 27, 2025 •

Copy link
Copy Markdown
Contributor

Note

Other AI code review bot(s) detected

CodeRabbit 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.

📝 Walkthrough

Walkthrough

Adds 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

Cohort / File(s) Summary
Article rendering & utilities
src/helpers/article.ts, src/helpers/utils.ts
New renderArticleToHtml converts Twitter article content to HTML (Telegram/Discord modes), collects media, supports truncation; exports DISCORD_ARTICLE_MAX_LENGTH. Added wrapForeignLinks(url, apiHost) to proxy non-whitelisted links.
Embed activity processing
src/embed/activity.ts
getStatusText now returns StatusTextResult { text, articleMedia }; added convertArticleMediaToAttachment; merges article attachments into media_attachments with dedupe and fallback; safer avatar/header handling.
Embed status & Instant View
src/embed/status.ts, src/render/instantview.ts
Added isArticleOnlyTweet and article-aware meta/OG selection; integrates renderArticleToHtml and article cover into IV output; adjusts headings/siteName and IV header behavior for articles.
Router updates
src/realms/twitter/router.ts
Adds article to route patterns (alongside status(es)), including i/web, language and media variants — broadens accepted endpoints while preserving handlers.
Twitter fetching / processor
src/providers/twitter/conversation.ts, src/providers/twitter/processor.ts
conversation.ts may re-fetch via RestId when article blocks are missing and rebuild status; processor.ts filters legacy /i/article/ URLs and removes verbose article debug logs.
Types
src/types/vendor/twitter.d.ts, src/types/types.d.ts
Added TWEET variant to TwitterArticleEntityMapEntry; minor import formatting changes.
Internationalization
i18n/en/resources.json, i18n/resources.json
Added articleIndicator: "📰 Article • {brandingName}"; removed gifIndicator.
Helpers: link fixer
src/helpers/linkFixer.ts
URL clearing regex extended to match both twitter.com and x.com /i/web/status/<id> patterns.
Providers: conversation/processor
src/providers/twitter/conversation.ts, src/providers/twitter/processor.ts
Conversation may re-fetch article content; processor filters article URL noise and silences extra logs.
Tests / Mocks
test/mocks/* (e.g., test/mocks/TweetResultsByRestIds/..., test/mocks/*/*.json)
Formatting and structural changes to fixtures; large rework of one TweetResults mock to a slimmer structure with updated extended_entities and media metadata.
Minor / Formatting
src/types/types.d.ts, test/mocks/AboutAccountQuery/x.json, test/mocks/UserResultByScreenName/x.json, test/mocks/TweetResultByRestId/...
Import reformatting and newline/spacing normalization in mocks and small JSON edits.

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)
Loading

Estimated Code Review Effort

🎯 4 (Complex) | ⏱️ ~55 minutes

Possibly related PRs

Poem

🐰 I dug up an article, shiny and neat,

HTML crumbs and media to eat.
I wrap stray links and stitch each thread,
Pack images and captions snug in my bed.
Hop, render, deliver — papers complete.

Pre-merge checks and finishing touches

❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Title check ❓ Inconclusive The title 'Twitter Article UI' is vague and generic, using non-descriptive terms that don't convey the specific technical implementation details of the changeset. Consider using a more specific title that highlights the core technical change, such as 'Add article rendering support to Twitter embeds' or 'Implement end-to-end Twitter article content rendering'.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch article-ui

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.

Comment thread src/helpers/article.ts Fixed
Comment thread src/helpers/article.ts Fixed
Comment thread src/render/instantview.ts Fixed
Comment thread src/render/instantview.ts Fixed
Comment thread src/render/instantview.ts Fixed
Comment thread src/render/instantview.ts Fixed

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

Comment thread src/providers/twitter/processor.ts Resolved
Comment thread src/helpers/article.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: 4

♻️ Duplicate comments (1)
src/embed/status.ts (1)

34-67: Duplicate code: Same function exists in instantview.ts.

As noted in the instantview.ts review, this isArticleOnlyTweet function is duplicated. Extract to a shared location.

🧹 Nitpick comments (6)
src/helpers/utils.ts (1)

95-108: Consider renaming unwrap to shouldWrap for clarity.

The variable name unwrap is misleading since it determines whether the URL should be wrapped, not unwrapped. Setting unwrap = true means "wrap this URL", which is counterintuitive.

Also, note that the hostname check uses exact match, so subdomains like mobile.twitter.com or www.x.com would be wrapped. If this is intentional, it's fine; otherwise, consider using endsWith() 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: isArticleOnlyTweet is defined in both instantview.ts and status.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 isArticleOnlyTweet to src/helpers/article.ts and 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.ts and status.ts.

src/embed/activity.ts (1)

30-113: Consider extracting shared media conversion logic.

The convertArticleMediaToAttachment function 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 making DISCORD_ARTICLE_MAX_LENGTH configurable 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.com in the URL (https://twitter.com/i/status/${tweetId}). For consistency with the rest of the codebase which uses x.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

📥 Commits

Reviewing files that changed from the base of the PR and between 37a8109 and 347b888.

📒 Files selected for processing (17)
  • i18n/en/resources.json
  • i18n/resources.json
  • src/embed/activity.ts
  • src/embed/status.ts
  • src/helpers/article.ts
  • src/helpers/linkFixer.ts
  • src/helpers/utils.ts
  • src/providers/twitter/conversation.ts
  • src/providers/twitter/processor.ts
  • src/realms/twitter/router.ts
  • src/render/instantview.ts
  • src/types/types.d.ts
  • src/types/vendor/twitter.d.ts
  • test/mocks/AboutAccountQuery/x.json
  • test/mocks/TweetResultByRestId/1964084223871971826.json
  • test/mocks/TweetResultsByRestIds/1964084223871971826.json
  • test/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 articleIndicator key follows the established pattern matching threadIndicator with 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.com and twitter.com domains 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 article endpoint alongside status(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 } to tweetResult: [ { result } ] correctly matches the TweetResultsByRestIdsResponse type 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 TwitterArticleContentState needed for the article content type definitions.

src/types/vendor/twitter.d.ts (1)

956-966: LGTM - TWEET variant for article entity map.

The new TWEET variant follows the established discriminated union pattern for TwitterArticleEntityMapEntry, enabling proper typing for embedded tweet references within article content.

i18n/resources.json (1)

39-39: LGTM - Article indicator added to translation resources.

The articleIndicator key is properly added with consistent formatting matching other indicator translations.

src/render/instantview.ts (1)

211-213: LGTM!

Good refactor to centralize the wrapForeignLinks logic 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:image when it's an article-only tweet without regular media. The embed card type is appropriately set to summary_large_image for better preview rendering.


629-634: Potential XSS: Verify preview_text is sanitized.

The preview_text from the article is assigned to the text variable which is used in og:description. While sanitizeText is applied to newText at line 627, the preview_text assigned at line 633 replaces it after sanitization occurs earlier.

Looking at line 627, sanitizeText(newText) is applied first, but then line 633 sets text = 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 renderArticleToHtml function properly handles:

  • List grouping with flushList
  • Truncation checks at appropriate boundaries
  • Media collection
  • The wasTruncated flag for downstream handling

Comment thread src/embed/activity.ts Resolved
Comment thread src/helpers/article.ts Resolved
Comment on lines +83 to +87
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
);
}

@coderabbitai coderabbitai Bot Dec 27, 2025 •

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.

⚠️ Potential issue | 🟠 Major

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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

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.

@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.

Comment thread src/render/instantview.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: 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 actual media.media_id values. 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:

  1. Using a hash of the media URL as the ID
  2. Using the actual media ID from the source if available
  3. 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 (in handleActivity). 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 ?? undefined operators.

Optional chaining (?.) already returns undefined for nullish values, making ?? undefined redundant. 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

📥 Commits

Reviewing files that changed from the base of the PR and between 347b888 and 1fe5d82.

📒 Files selected for processing (2)
  • src/embed/activity.ts
  • src/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

Comment thread src/embed/activity.ts
Comment on lines +59 to +68
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;
}

@coderabbitai coderabbitai Bot Dec 28, 2025 •

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.

⚠️ Potential issue | 🟠 Major

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:

  1. Set sizeMultiplier = 0.5 (width > 1920)
  2. 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.

Suggested change
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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

It is a pretty negligible issue since:

  1. Not all clients even respect video width/height as it is
  2. 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

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.

@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!

Comment thread src/embed/activity.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

🧹 Nitpick comments (1)
src/embed/activity.ts (1)

153-153: Consider validating article title before use.

While the code checks for twitterStatus.article existence at line 145, it doesn't validate that article.title is 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

📥 Commits

Reviewing files that changed from the base of the PR and between 1fe5d82 and 5dc0f99.

📒 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 statusResult cleanly 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 null results from unrecognized media types. The type assertion is appropriate after filtering.


580-583: LGTM: Deduplication correctly implemented.

The deduplication logic properly creates a Set of 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.

Comment thread src/embed/activity.ts
media.media_info.__typename === 'ApiGif'
) {
const video = media.media_info as TwitterApiVideo;
const videoUrl = video.video_info?.variants?.[0]?.url || video.media_url_https;

@coderabbitai coderabbitai Bot Dec 28, 2025 •

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.

⚠️ Potential issue | 🟡 Minor

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.

Suggested change
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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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?

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.

@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!

@dangeredwolf dangeredwolf left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

lgtm

Comment thread src/embed/activity.ts Resolved
Comment thread src/embed/activity.ts
Comment on lines +59 to +68
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;
}

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

It is a pretty negligible issue since:

  1. Not all clients even respect video width/height as it is
  2. 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

Comment thread src/embed/activity.ts
media.media_info.__typename === 'ApiGif'
) {
const video = media.media_info as TwitterApiVideo;
const videoUrl = video.video_info?.variants?.[0]?.url || video.media_url_https;

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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?

@dangeredwolf
dangeredwolf merged commit 93fff14 into main Dec 28, 2025

@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: 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 to sizeMultiplier = 2 (height < 400). Consider using else if to 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: isArticleOnlyTweet is duplicated in src/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.ts or src/helpers/utils.ts) to avoid maintaining the same logic in two places.

📜 Review details

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6ce1c43 and 1863ea5.

📒 Files selected for processing (5)
  • src/embed/activity.ts
  • src/embed/status.ts
  • src/helpers/article.ts
  • src/providers/twitter/conversation.ts
  • src/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: true for 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 && isTelegram ensures 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'. The embed_card is appropriately set to summary_large_image for articles with cover media.

src/embed/activity.ts (2)

140-158: Provider check correctly guards Twitter-specific article access.

The condition status.provider === DataProvider.Twitter at 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 Set of 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. ArticleRenderOptions properly 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 apiHost parameter 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, truncateWithEllipsis on 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 renderArticleToHtml function 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 the flushList helper keeps the main loop clean.

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.

2 participants