Skip to content

Conversation

@DenisovAV
Copy link
Contributor

@DenisovAV DenisovAV commented Aug 30, 2025

Fixes #291

Summary

  • Fixed TypeScript 'in' operator errors when response.body is ReadableStream
  • Added proper type checking before using 'in' operator on response.body
  • Resolves streaming failures in Node.js environments

Changes

  • Updated src/github_llms.ts lines 1205, 1213, 1215, 1219
  • Added type guard: (typeof response.body === 'object' && response.body && "choices" in response.body)

Test plan

  • Verified streaming responses work with ReadableStream bodies
  • Ensured existing object-based responses still work
  • Tested in Node.js Firebase Functions environment

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Improved robustness when handling unexpected or malformed API responses, preventing crashes and ensuring graceful fallbacks.
    • Default behavior now returns empty content and zero token counts when response data is missing or invalid.
  • Reliability
    • Non-streaming responses now handle edge cases more safely, aligning behavior with the already resilient streaming path.

The 'in' operator fails when response.body is not a plain object (e.g., ReadableStream in Node.js).
Added proper type checking before using the 'in' operator to prevent runtime errors.

This resolves issues with streaming responses that contain ReadableStream bodies instead of plain objects.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
@DenisovAV DenisovAV requested a review from xavidop as a code owner August 30, 2025 22:52
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 30, 2025

Walkthrough

Adds runtime type guards before using the "in" operator on response.body in src/github_llms.ts, ensuring it’s an object before accessing choices and usage. Defaults to empty content and zero tokens when absent or non-object. Affects final response construction in the non-streaming path; streaming processing unchanged.

Changes

Cohort / File(s) Summary
Response body guards
src/github_llms.ts
Replace direct "in" checks on response.body with object-and-non-null guards for choices and usage; fall back to empty content and zero tokens when absent. No changes to streaming event handling.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as Caller
  participant GM as githubModel
  participant GH as GitHub API

  C->>GM: request()
  GM->>GH: fetch()
  GH-->>GM: response { body }
  alt body is object with choices/usage
    GM->>GM: Access body.choices / body.usage
    GM-->>C: result(message, tokens)
  else body missing / non-object
    GM->>GM: Fallback to empty message and zero tokens
    GM-->>C: result(defaults)
  end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Assessment against linked issues

Objective Addressed Explanation
Add guards before using "in" on response.body to prevent errors when it’s a ReadableStream (#291)

Assessment against linked issues: Out-of-scope changes

(no out-of-scope changes identified)

Poem

I twitched my ears at streams that flow,
Where “in” would trip on what I’d know—
Now cautious paws check types just right,
Empty nests and token light.
With safer hops in code I gleam,
No tumbles in the data stream. 🐇✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Caution

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

⚠️ Outside diff range comments (2)
src/github_llms.ts (2)

1154-1161: Bug: deleting “falsy” values drops legitimate zeros (e.g., temperature/top_p = 0)

The cleanup removes valid config values of 0. Only strip undefined/null or empty arrays.

-  for (const key in body.body) {
-    if (
-      !body.body[key] ||
-      (Array.isArray(body.body[key]) && !body.body[key].length)
-    )
-      delete body.body[key];
-  }
+  for (const [k, v] of Object.entries(body.body)) {
+    if (
+      v === undefined ||
+      v === null ||
+      (Array.isArray(v) && v.length === 0)
+    ) {
+      delete (body.body as any)[k];
+    }
+  }

1112-1114: MIME type typo: should be "text/plain"

Using "plain/text" will never match and can select the wrong response_format.

-  const textMode =
-    request.output?.format === "text" ||
-    request.output?.contentType === "plain/text";
+  const textMode =
+    request.output?.format === "text" ||
+    request.output?.contentType === "text/plain";
🧹 Nitpick comments (6)
src/github_llms.ts (6)

1205-1210: Good guard; also verify choices is an array with elements to avoid undefined access

Strengthen the condition so we don’t index into a non-array or empty array.

-          (typeof response.body === 'object' && response.body && "choices" in response.body)
+          (typeof response.body === 'object'
+            && response.body
+            && "choices" in response.body
+            && Array.isArray((response.body as any).choices)
+            && (response.body as any).choices.length > 0)
             ? fromGithubChoice(
-                response.body.choices[0],
+                (response.body as any).choices[0],
                 request.output?.format === "json",
               ).message
             : { role: "model", content: [] },

1213-1213: Always return numbers for inputTokens

Coalesce undefined to 0 so callers don’t receive undefined.

-            (typeof response.body === 'object' && response.body && "usage" in response.body) ? response.body.usage?.prompt_tokens : 0,
+            (typeof response.body === 'object' && response.body && "usage" in response.body) ? (response.body.usage?.prompt_tokens ?? 0) : 0,

1215-1217: Always return numbers for outputTokens

-            (typeof response.body === 'object' && response.body && "usage" in response.body)
-              ? response.body.usage?.completion_tokens
-              : 0,
+            (typeof response.body === 'object' && response.body && "usage" in response.body)
+              ? (response.body.usage?.completion_tokens ?? 0)
+              : 0,

1219-1219: Always return numbers for totalTokens

-            (typeof response.body === 'object' && response.body && "usage" in response.body) ? response.body.usage?.total_tokens : 0,
+            (typeof response.body === 'object' && response.body && "usage" in response.body) ? (response.body.usage?.total_tokens ?? 0) : 0,

355-359: Version string typo: “Instructt”

-    versions: ["Llama-4-Scout-17B-16E-Instructt"],
+    versions: ["Llama-4-Scout-17B-16E-Instruct"],

515-517: Model name typo: “24111” → “2411”

The ref’s name includes an extra “1”.

-  name: "github/Mistral-large-24111",
+  name: "github/Mistral-large-2411",
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between c9e6f9e and e033ef9.

📒 Files selected for processing (1)
  • src/github_llms.ts (1 hunks)

@xavidop xavidop merged commit 1971456 into xavidop:main Aug 30, 2025
5 checks passed
@github-actions
Copy link

🎉 This PR is included in version 1.15.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Streaming fails with 'Cannot use in operator' error in Node.js

2 participants