Skip to content

feat: media timelines - #1885

Merged
dangeredwolf merged 7 commits into
mainfrom
media-timelines
Mar 29, 2026
Merged

dangeredwolf merged 7 commits into
mainfrom
media-timelines

Conversation

@dangeredwolf

@dangeredwolf dangeredwolf commented Mar 29, 2026 •

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • New Features

    • Added a profile media endpoint to retrieve a user’s photos and videos with pagination.
    • Added an option to include replies when fetching profile timelines.
  • Improvements

    • Broadened timeline handling so media, photo, video and replies timelines are recognized and returned consistently.
  • Tests

    • Added tests covering the profile media endpoint and the new timeline variants.

@dangeredwolf dangeredwolf self-assigned this Mar 29, 2026
@coderabbitai

coderabbitai Bot commented Mar 29, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 801229db-8784-412e-a2da-32b6210a65e4

📥 Commits

Reviewing files that changed from the base of the PR and between d773960 and d45a5ab.

📒 Files selected for processing (1)
  • src/providers/twitter/graphql/queries.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/providers/twitter/graphql/queries.ts

📝 Walkthrough

Walkthrough

Added new profile/media GraphQL queries and validators, extended profile timeline types, implemented a profile media API + route (/2/profile/{handle}/media), added optional with_replies handling to profile statuses, updated tests/mocks, and re-enabled a runtime GraphQL response log. (50 words)

Changes

Cohort / File(s) Summary
GraphQL queries
src/providers/twitter/graphql/queries.ts
Renamed shared feature set to userTweetsTimelineFeatures; updated UserTweetsQuery to use it. Added UserMediaQuery, ProfileWithRepliesTimelineQuery, and UserTweetsAndRepliesQuery exports with corresponding feature/variable sets.
Validators & extractors
src/providers/twitter/graphql/validators.ts
Added validateUserMediaTimelineResponse, validateProfileWithRepliesTimelineResponse, validateProfileUserPhotoTimelineResponse, validateProfileUserVideoTimelineResponse, and getProfilePhotoTimelineInstructions. Extended getProfileStatusesTimelineInstructions to include replies/video/media timeline paths.
API logic
src/providers/twitter/userStatuses.ts
Updated profileStatusesAPI to accept withReplies and switch orchestration between profile timeline variants; added new profileMediaAPI that resolves userId, executes UserMediaQuery, validates response, extracts instructions, processes timeline, builds statuses, and returns results/cursor.
Routing & OpenAPI
src/realms/api/router.ts, src/realms/api/routes.ts, src/realms/api/routes/twitter.ts
Registered profileMediaV2Route in OpenAPI; added profileMediaV2Route definition and profileMediaAPIRequest handler; added with_replies query param to profile statuses route; profileStatusesAPIRequest now derives and passes withReplies.
Types
src/types/vendor/twitter.d.ts
Extended TwitterProfileTimelineResponse to include optional profile_with_replies_timeline_v2, profile_user_photo_timeline, profile_user_video_timeline, and profile_user_media_timeline shapes (id/timeline/instructions).
Tests & mocks
test/api.profileMedia.test.ts, test/profileStatusesInstructions.test.ts, test/helpers/harness.ts
Added tests for /2/profile/{handle}/media (200/404/pagination); expanded validator tests for new timeline shapes; unified mock loading so UserTweets/UserMedia use same harness branch.
Logging
src/providers/twitter/fetch.ts
Re-enabled console.log of GraphQL response before returning from twitterFetch.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Client/API Request
    participant Router as API Router
    participant Provider as profileMediaAPI
    participant GraphQL as GraphQL Orchestrator
    participant Validator as Response Validator
    participant Processor as Timeline Processor
    participant Builder as Status Builder

    Client->>Router: GET /2/profile/{handle}/media
    Router->>Provider: profileMediaAPI(handle, count, cursor)
    Provider->>Provider: resolve userId from handle
    Provider->>GraphQL: execute UserMediaQuery
    GraphQL-->>Provider: timeline response
    Provider->>Validator: validateUserMediaTimelineResponse(response)
    Validator-->>Provider: validation result
    Provider->>Processor: getProfileStatusesTimelineInstructions(response)
    Processor-->>Provider: TimelineInstruction[]
    Provider->>Processor: processTimelineInstructions(instructions)
    Processor-->>Provider: statuses + cursors
    Provider->>Builder: buildAPITwitterStatus per status
    Builder-->>Provider: built status objects
    Provider-->>Router: { code, results[], cursor }
    Router-->>Client: HTTP response (status = code) + JSON
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🐰 I hopped through timelines, nibbling on tags,

Fetching media, replies, and cursored flags.
Validators sniffed every instruction and trace,
Routes and tests lined up in tidy embrace—
A little rabbit PR, bounding into place.

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: media timelines' directly corresponds to the primary changes: adding UserMediaQuery, profileMediaAPI, and new media-related timeline functionality throughout the codebase.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

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

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.

@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

🧹 Nitpick comments (2)
src/providers/twitter/graphql/queries.ts (1)

610-663: Consider reusing userTweetsFeatures to reduce duplication.

The userMediaFeatures object is nearly identical to userTweetsFeatures (lines 554-592), differing only in the omission of tweet_awards_web_tipping_enabled. If this difference is intentional (captured from Twitter's actual Media tab requests), this is fine. Otherwise, consider reusing the existing feature set.

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

In `@src/providers/twitter/graphql/queries.ts` around lines 610 - 663, Duplicate
feature flags exist between userMediaFeatures and userTweetsFeatures; either
reuse the existing userTweetsFeatures or make the one intentional omission
explicit. Update the UserMediaQuery construction to reference userTweetsFeatures
(or a shared const like baseUserFeatures) and then override or delete the
tweet_awards_web_tipping_enabled flag if needed; locate and modify the
userMediaFeatures constant and the UserMediaQuery.features assignment so it
reuses userTweetsFeatures (or a merged object) rather than duplicating nearly
identical flags.
src/providers/twitter/userStatuses.ts (1)

120-311: Consider extracting shared timeline API logic.

The three new functions (profileMediaAPI, profilePhotosAPI, profileUserVideosAPI) share significant structural similarity:

  1. Resolve userId from handle
  2. Execute GraphQL orchestrator
  3. Extract instructions
  4. Process timeline instructions
  5. Build statuses with error handling
  6. Return results with cursors

A shared helper could reduce duplication:

♻️ Example refactor sketch
const executeTimelineAPI = async (
  handleOrId: ProfileHandleOrId,
  c: Context,
  config: {
    key: string;
    query: GraphQLQuery;
    validator: (r: unknown) => boolean;
    extractInstructions: (r: unknown) => TimelineInstruction[] | undefined;
    variables: Record<string, unknown>;
  }
): Promise<APISearchResults> => {
  const userId = handleOrId.type === 'userId'
    ? handleOrId.value
    : await getTwitterUserRestIdByScreenName(c, handleOrId.value);
  if (!userId) {
    return { code: 404, results: [], cursor: { top: null, bottom: null } };
  }

  const results = await graphQLOrchestrator(c, [{
    key: config.key,
    required: true,
    query: config.query,
    validator: config.validator,
    variables: { ...config.variables, userId, rest_id: userId }
  }]);

  // ... shared processing logic
};
🤖 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 120 - 311, Extract the
duplicated timeline flow into a helper (e.g. executeTimelineAPI) that takes
(handleOrId: ProfileHandleOrId, c: Context, config: { key, query, validator,
extractInstructions, variables? }) and implements: resolving userId (reuse
getTwitterUserRestIdByScreenName), calling graphQLOrchestrator with provided
key/query/validator/variables, checking success and logging errors, calling the
provided extractInstructions (or default getProfileStatusesTimelineInstructions
/ getProfilePhotoTimelineInstructions), processing the instructions with
processTimelineInstructions, building statuses via buildAPITwitterStatus with
the same try/catch pattern, filtering out null/FetchResults, and returning the
APISearchResults with top/bottom cursors; then replace profileMediaAPI,
profilePhotosAPI and profileUserVideosAPI to call executeTimelineAPI with the
appropriate config (key: 'media'|'photos'|'videos', queries
UserMediaQuery|ProfileUserPhotoTimelineQuery|ProfileUserVideoTimelineQuery,
validators
validateUserTweetsTimeline|validateProfileUserPhotoTimelineResponse|validateProfileUserVideoTimelineResponse,
and extractInstructions mapping to getProfileStatusesTimelineInstructions or
getProfilePhotoTimelineInstructions) so their bodies only prepare config and
forward the call.
🤖 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/userStatuses.ts`:
- Around line 134-156: getProfileStatusesTimelineInstructions currently lacks
handling for the profile_user_media_timeline shape returned by UserMediaQuery,
which causes it to return undefined and the caller to send a 404; update
getProfileStatusesTimelineInstructions to detect and return instructions when
asProfile.data.user_result_by_rest_id.result.profile_user_media_timeline.timeline.instructions
is an array (insert this check after the existing video-path handler and before
the final return undefined) so the profile media timeline path is handled the
same way as the other timeline shapes.

In `@src/realms/api/routes/twitter.ts`:
- Line 114: The code falls back to an undocumented camelCase query param by
calling c.req.query('withReplies') when computing const withReplies =
isParamTruthy(...), so either explicitly document the alias or remove the
fallback; fix by (A) adding a documented query parameter named "withReplies" to
the route's OpenAPI/schema alongside "with_replies" (so the alias is supported)
or (B) remove the c.req.query('withReplies') fallback and only read the
documented "with_replies" param; update any validation/handlers that rely on
isParamTruthy and the withReplies constant accordingly.

---

Nitpick comments:
In `@src/providers/twitter/graphql/queries.ts`:
- Around line 610-663: Duplicate feature flags exist between userMediaFeatures
and userTweetsFeatures; either reuse the existing userTweetsFeatures or make the
one intentional omission explicit. Update the UserMediaQuery construction to
reference userTweetsFeatures (or a shared const like baseUserFeatures) and then
override or delete the tweet_awards_web_tipping_enabled flag if needed; locate
and modify the userMediaFeatures constant and the UserMediaQuery.features
assignment so it reuses userTweetsFeatures (or a merged object) rather than
duplicating nearly identical flags.

In `@src/providers/twitter/userStatuses.ts`:
- Around line 120-311: Extract the duplicated timeline flow into a helper (e.g.
executeTimelineAPI) that takes (handleOrId: ProfileHandleOrId, c: Context,
config: { key, query, validator, extractInstructions, variables? }) and
implements: resolving userId (reuse getTwitterUserRestIdByScreenName), calling
graphQLOrchestrator with provided key/query/validator/variables, checking
success and logging errors, calling the provided extractInstructions (or default
getProfileStatusesTimelineInstructions / getProfilePhotoTimelineInstructions),
processing the instructions with processTimelineInstructions, building statuses
via buildAPITwitterStatus with the same try/catch pattern, filtering out
null/FetchResults, and returning the APISearchResults with top/bottom cursors;
then replace profileMediaAPI, profilePhotosAPI and profileUserVideosAPI to call
executeTimelineAPI with the appropriate config (key: 'media'|'photos'|'videos',
queries
UserMediaQuery|ProfileUserPhotoTimelineQuery|ProfileUserVideoTimelineQuery,
validators
validateUserTweetsTimeline|validateProfileUserPhotoTimelineResponse|validateProfileUserVideoTimelineResponse,
and extractInstructions mapping to getProfileStatusesTimelineInstructions or
getProfilePhotoTimelineInstructions) so their bodies only prepare config and
forward the call.
🪄 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: b138c1d5-58a4-478e-afbf-a0b13d8a428a

📥 Commits

Reviewing files that changed from the base of the PR and between 75517be and e353979.

📒 Files selected for processing (12)
  • src/providers/twitter/graphql/queries.ts
  • src/providers/twitter/graphql/validators.ts
  • src/providers/twitter/userStatuses.ts
  • src/realms/api/router.ts
  • src/realms/api/routes.ts
  • src/realms/api/routes/twitter.ts
  • src/types/vendor/twitter.d.ts
  • test/api.profileMedia.test.ts
  • test/api.profilePhotos.test.ts
  • test/api.profileVideos.test.ts
  • test/helpers/harness.ts
  • test/profileStatusesInstructions.test.ts

Comment thread src/providers/twitter/userStatuses.ts Resolved
Comment thread src/realms/api/routes/twitter.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.

♻️ Duplicate comments (1)
src/realms/api/routes/twitter.ts (1)

107-107: ⚠️ Potential issue | 🟡 Minor

Undocumented camelCase parameter fallback should be addressed.

The fallback to c.req.query('withReplies') provides a camelCase alias that isn't documented in the OpenAPI schema. Looking at src/realms/api/routes.ts:28-36, the aboutAccountQuery pattern explicitly documents both snake_case and camelCase variants. Either:

  1. Document withReplies as an alias in the route schema (like aboutAccount)
  2. Remove the fallback if it's not intentionally supported
Option 1: Document the alias in routes.ts
      cursor: z
        .string()
        .optional()
        .openapi({ description: 'Pagination cursor from prior response' }),
      with_replies: z.string().optional().openapi({
        description:
          'If truthy (`1`, `true`, `yes`, `on`, or empty), include replies using alternate upstream timelines'
-      })
+      }),
+      withReplies: z.string().optional().openapi({
+        description: 'Alias for with_replies'
+      })
Option 2: Remove undocumented fallback
-  const withReplies = isParamTruthy(query.with_replies ?? c.req.query('withReplies'));
+  const withReplies = isParamTruthy(query.with_replies);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/realms/api/routes/twitter.ts` at line 107, The code uses a camelCase
fallback when building withReplies: "const withReplies =
isParamTruthy(query.with_replies ?? c.req.query('withReplies'))" which isn't
documented; either add the camelCase alias to the route schema (update the
aboutAccountQuery schema to include "withReplies" alongside "with_replies") so
the OpenAPI/docs match the runtime, or remove the undocumented fallback and read
only query.with_replies (i.e., replace the nullish-coalescing fallback so
withReplies = isParamTruthy(query.with_replies)); update references to
isParamTruthy, withReplies, and aboutAccountQuery accordingly.
🧹 Nitpick comments (1)
src/providers/twitter/userStatuses.ts (1)

116-179: Consider extracting shared logic to reduce duplication.

profileMediaAPI and profileStatusesAPI share nearly identical patterns for:

  • User ID resolution (lines 122-128 vs 29-35)
  • Error handling in buildAPITwitterStatus mapping (lines 158-169 vs 93-104)
  • Response construction (lines 171-178 vs 106-113)

This could be refactored into a shared helper, but given the minor differences in orchestrator configuration, deferring is acceptable.

🤖 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 116 - 179,
profileMediaAPI and profileStatusesAPI duplicate user ID resolution,
status-building error handling, and response construction; extract three
helpers: 1) a userId resolver that wraps getTwitterUserRestIdByScreenName (used
by profileMediaAPI/profileStatusesAPI) to return the 404 result shape when
missing, 2) a safeBuildStatuses utility that maps statuses ->
buildAPITwitterStatus with try/catch and returns typed APITwitterStatus[]
(filtering out nulls/FetchResults), and 3) a small response-builder that
assembles { code, results, cursor } given builtStatuses and cursors from
processTimelineInstructions/getProfileStatusesTimelineInstructions; replace the
duplicated blocks in profileMediaAPI and profileStatusesAPI to call these
helpers to keep orchestrator-specific logic intact.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@src/realms/api/routes/twitter.ts`:
- Line 107: The code uses a camelCase fallback when building withReplies: "const
withReplies = isParamTruthy(query.with_replies ?? c.req.query('withReplies'))"
which isn't documented; either add the camelCase alias to the route schema
(update the aboutAccountQuery schema to include "withReplies" alongside
"with_replies") so the OpenAPI/docs match the runtime, or remove the
undocumented fallback and read only query.with_replies (i.e., replace the
nullish-coalescing fallback so withReplies = isParamTruthy(query.with_replies));
update references to isParamTruthy, withReplies, and aboutAccountQuery
accordingly.

---

Nitpick comments:
In `@src/providers/twitter/userStatuses.ts`:
- Around line 116-179: profileMediaAPI and profileStatusesAPI duplicate user ID
resolution, status-building error handling, and response construction; extract
three helpers: 1) a userId resolver that wraps getTwitterUserRestIdByScreenName
(used by profileMediaAPI/profileStatusesAPI) to return the 404 result shape when
missing, 2) a safeBuildStatuses utility that maps statuses ->
buildAPITwitterStatus with try/catch and returns typed APITwitterStatus[]
(filtering out nulls/FetchResults), and 3) a small response-builder that
assembles { code, results, cursor } given builtStatuses and cursors from
processTimelineInstructions/getProfileStatusesTimelineInstructions; replace the
duplicated blocks in profileMediaAPI and profileStatusesAPI to call these
helpers to keep orchestrator-specific logic intact.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 7a81c0fa-dd1e-49ca-ba7f-073038969b51

📥 Commits

Reviewing files that changed from the base of the PR and between e353979 and f79b9a4.

📒 Files selected for processing (10)
  • src/providers/twitter/fetch.ts
  • src/providers/twitter/graphql/queries.ts
  • src/providers/twitter/graphql/validators.ts
  • src/providers/twitter/userStatuses.ts
  • src/realms/api/router.ts
  • src/realms/api/routes.ts
  • src/realms/api/routes/twitter.ts
  • src/types/vendor/twitter.d.ts
  • test/helpers/harness.ts
  • test/profileStatusesInstructions.test.ts
✅ Files skipped from review due to trivial changes (4)
  • src/providers/twitter/fetch.ts
  • src/realms/api/router.ts
  • test/helpers/harness.ts
  • test/profileStatusesInstructions.test.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/types/vendor/twitter.d.ts
  • src/providers/twitter/graphql/validators.ts
  • src/providers/twitter/graphql/queries.ts

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

♻️ Duplicate comments (1)
src/realms/api/routes/twitter.ts (1)

124-124: ⚠️ Potential issue | 🟡 Minor

Undocumented camelCase query alias is still accepted.

c.req.query('withReplies') is still used as a fallback, but only with_replies is documented in the query schema. Either document withReplies explicitly or remove the fallback to avoid silent API surface drift.

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

In `@src/realms/api/routes/twitter.ts` at line 124, The code silently accepts an
undocumented camelCase query alias; update the handling for the with_replies
query parameter by removing the fallback to the camelCase form to avoid API
surface drift: change the initialization of withReplies (the const withReplies =
isParamTruthy(...)) to only read the documented query key (with_replies) via
c.req.query('with_replies') (or the existing query object), and remove the
c.req.query('withReplies') fallback, or alternatively add explicit
documentation/validation for the camelCase alias in your query schema if you
intend to support it.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@src/realms/api/routes/twitter.ts`:
- Line 124: The code silently accepts an undocumented camelCase query alias;
update the handling for the with_replies query parameter by removing the
fallback to the camelCase form to avoid API surface drift: change the
initialization of withReplies (the const withReplies = isParamTruthy(...)) to
only read the documented query key (with_replies) via
c.req.query('with_replies') (or the existing query object), and remove the
c.req.query('withReplies') fallback, or alternatively add explicit
documentation/validation for the camelCase alias in your query schema if you
intend to support it.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 8bbaec78-47e3-4efe-acfc-61040d092080

📥 Commits

Reviewing files that changed from the base of the PR and between f79b9a4 and d773960.

📒 Files selected for processing (3)
  • src/realms/api/router.ts
  • src/realms/api/routes.ts
  • src/realms/api/routes/twitter.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/realms/api/router.ts
  • src/realms/api/routes.ts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant