fix: enhance API snippet generation with file upload support and consistent authentication#9018
Conversation
Add proper two-step file upload support for API code generation: - Detect file tweaks in ChatInput (string), File/VideoFile (path/file_path) - Generate step-based cURL commands with separate copy buttons - Fix ChatInput to use correct /api/v1/run endpoint with tweaks structure - Update JavaScript and Python generators with proper endpoints and payloads - Support dynamic node IDs and processedPayload values - Implement step parsing UI for cURL with proper formatting Co-Authored-By: Automagik Genie <genie@namastex.ai>
Replace browser-based FormData approach with native Node.js http module - Use built-in fs, http, and path modules instead of browser APIs - Manually construct multipart/form-data payloads - Add proper error handling and HTTP request helpers - Support both ChatInput and File/VideoFile upload scenarios - Maintain authentication header support Co-Authored-By: Automagik Genie <genie@namastex.ai>
…URL snippets File/VideoFile components were missing the required payload fields when generating cURL commands, causing flows to fail execution. Added the missing fields to match the working pattern used in Chat Input components. Co-Authored-By: Automagik Genie <genie@namastex.ai>
…cript File component snippets File/VideoFile components were missing the required payload fields in Python and JavaScript generators, matching the fix applied to cURL snippets. Co-Authored-By: Automagik Genie <genie@namastex.ai>
File components require the 'path' field from v2 upload response as an array, not 'file_id'. Updated all three generators: - Changed file_id to file_path variable extraction - Changed "file_id": value to "path": [value] in tweaks - Updated placeholder text for consistency This fixes the "No files to process" error in File components. Co-Authored-By: Automagik Genie <genie@namastex.ai>
- Fixed UI parsing to handle multiple file components correctly - Consolidated upload steps into single step with multiple commands - All file components (ChatInput, File, VideoFile) now work additively - Simplified UI to show only 2 steps: uploads and execution - Improved scrolling for better debugging experience - Removed debug console.log statements
…istent authentication - Add multi-step file upload handling for ChatInput, File, and VideoFile components - Implement automatic session ID generation using UUIDs across all snippets - Ensure API key is always required in generated code (Python, JavaScript, cURL) - Remove unused isAuth parameter from code generation logic - Add comprehensive unit tests for file detection and code generation - Support both Unix/Linux and PowerShell platforms for cURL commands
|
Important Review skippedAuto incremental reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the You can disable this status message by setting the WalkthroughThis update introduces multi-step file upload support to the API code generation utilities and the API code tab UI. It adds logic to detect file-related tweaks, generates stepwise code for Python, JavaScript, and cURL that first uploads files and then executes the main API call, and updates the UI to display and allow copying of these segmented code steps. Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant CodeTabUI
participant CodeGenUtil
participant FileUploadAPI
participant MainAPI
User->>CodeTabUI: Selects API code tab
CodeTabUI->>CodeGenUtil: Request code for flow (with payload)
CodeGenUtil->>CodeGenUtil: Detect file tweaks in payload
alt No file tweaks
CodeGenUtil->>CodeTabUI: Return single-step code
else File tweaks present
CodeGenUtil->>CodeTabUI: Return multi-step code (step markers)
User->>CodeTabUI: Clicks "Copy Step 1"
CodeTabUI->>User: Copy file upload step to clipboard
User->>CodeTabUI: Clicks "Copy Step 2"
CodeTabUI->>User: Copy main API call step to clipboard
end
Suggested labels
Suggested reviewers
✨ Finishing Touches🧪 Generate unit tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
Documentation and Community
|
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (3)
src/frontend/src/modals/apiModal/codeTabs/code-tabs.tsx (2)
38-38: Consider extracting the copy feedback timeout as a constant.The 2-second timeout is hardcoded in multiple places. Consider extracting it for maintainability.
Add a constant at the top of the component:
+const COPY_FEEDBACK_TIMEOUT_MS = 2000; + export default function APITabsComponent() {Then use it in the timeouts:
- }, 2000); + }, COPY_FEEDBACK_TIMEOUT_MS);Also applies to: 118-140
209-331: Consider extracting step rendering into separate components for better maintainability.The current implementation has deeply nested conditionals and duplicated code. Consider refactoring for clarity.
Extract the step rendering logic into separate components:
const StepCodeBlock = ({ step, stepNumber, title, code, language, dark, showLineNumbers = true, onCopy, isCopied }: StepCodeBlockProps) => ( <div className={stepNumber === 2 ? "flex flex-1 flex-col overflow-hidden" : ""}> <h4 className="mb-2 text-sm font-medium">{title}</h4> <div className="relative flex h-full w-full"> <Button variant="ghost" size="icon" onClick={onCopy} data-testid={`btn-copy-step${stepNumber}`} className="!hover:bg-foreground group absolute right-4 top-2 z-10 select-none" > {isCopied ? ( <IconComponent name="Check" className="h-5 w-5 text-muted-foreground" /> ) : ( <IconComponent name="Copy" className="!h-5 !w-5 text-muted-foreground" /> )} </Button> <SyntaxHighlighter showLineNumbers={showLineNumbers} wrapLongLines={true} language={language} style={dark ? oneDark : oneLight} className="!mt-0 h-full w-full overflow-scroll !rounded-b-md border border-border text-left !custom-scroll" > {code} </SyntaxHighlighter> </div> </div> );This would simplify the main render logic and reduce duplication.
src/frontend/src/modals/apiModal/utils/get-js-api-code.tsx (1)
92-92: Clarify placeholder filenames with comments.The generated code uses placeholder filenames that users need to replace with actual file paths. Consider adding comments to make this clearer.
Update the generated code to include clarifying comments:
- const { payload: chatPayload${index + 1}, boundary: chatBoundary${index + 1} } = createFormData('your_image_${index + 1}.jpg'); + const { payload: chatPayload${index + 1}, boundary: chatBoundary${index + 1} } = createFormData('your_image_${index + 1}.jpg'); // Replace with your actual file path- const { payload: filePayload${index + 1}, boundary: fileBoundary${index + 1} } = createFormData('your_file_${index + 1}.pdf'); + const { payload: filePayload${index + 1}, boundary: fileBoundary${index + 1} } = createFormData('your_file_${index + 1}.pdf'); // Replace with your actual file pathAlso applies to: 124-124
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (6)
src/frontend/src/modals/apiModal/codeTabs/code-tabs.tsx(3 hunks)src/frontend/src/modals/apiModal/utils/__tests__/api-snippet-generation.test.ts(1 hunks)src/frontend/src/modals/apiModal/utils/detect-file-tweaks.ts(1 hunks)src/frontend/src/modals/apiModal/utils/get-curl-code.tsx(4 hunks)src/frontend/src/modals/apiModal/utils/get-js-api-code.tsx(2 hunks)src/frontend/src/modals/apiModal/utils/get-python-api-code.tsx(3 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
src/frontend/**/*.{ts,tsx}
Instructions used from:
Sources:
📄 CodeRabbit Inference Engine
- .cursor/rules/frontend_development.mdc
src/frontend/**/*.{ts,tsx,js,jsx,css,scss}
Instructions used from:
Sources:
📄 CodeRabbit Inference Engine
- .cursor/rules/frontend_development.mdc
src/frontend/src/**/__tests__/**/*.test.{ts,tsx}
Instructions used from:
Sources:
📄 CodeRabbit Inference Engine
- .cursor/rules/frontend_development.mdc
src/frontend/src/**/__tests__/**/*.{test,spec}.{ts,tsx}
Instructions used from:
Sources:
📄 CodeRabbit Inference Engine
- .cursor/rules/frontend_development.mdc
{src/backend/tests/**/*.py,src/frontend/**/*.test.{ts,tsx,js,jsx},src/frontend/**/*.spec.{ts,tsx,js,jsx},tests/**/*.py}
Instructions used from:
Sources:
📄 CodeRabbit Inference Engine
- .cursor/rules/testing.mdc
src/frontend/**/*.@(test|spec).{ts,tsx,js,jsx}
Instructions used from:
Sources:
📄 CodeRabbit Inference Engine
- .cursor/rules/testing.mdc
🧠 Learnings (5)
src/frontend/src/modals/apiModal/utils/__tests__/api-snippet-generation.test.ts (11)
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-06-30T14:41:58.849Z
Learning: Applies to src/frontend/**/*.@(test|spec).{ts,tsx,js,jsx} : Frontend tests should be well-documented with clear descriptions of test purpose and expected behavior.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-06-30T14:41:58.849Z
Learning: Applies to {src/backend/tests/**/*.py,src/frontend/**/*.test.{ts,tsx,js,jsx},src/frontend/**/*.spec.{ts,tsx,js,jsx},tests/**/*.py} : Complex test setups should be commented, and mock usage should be documented within the test code.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-06-30T14:41:58.849Z
Learning: Applies to {src/backend/tests/**/*.py,src/frontend/**/*.test.{ts,tsx,js,jsx},src/frontend/**/*.spec.{ts,tsx,js,jsx},tests/**/*.py} : Create comprehensive unit tests for all new components.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-06-30T14:41:58.849Z
Learning: Applies to src/frontend/**/*.@(test|spec).{ts,tsx,js,jsx} : Frontend tests should mock external dependencies and APIs appropriately.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-06-30T14:41:58.849Z
Learning: Applies to src/frontend/**/*.@(test|spec).{ts,tsx,js,jsx} : Frontend tests should validate input/output behavior and component state changes.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-06-30T14:41:58.849Z
Learning: Applies to {src/backend/tests/**/*.py,src/frontend/**/*.test.{ts,tsx,js,jsx},src/frontend/**/*.spec.{ts,tsx,js,jsx},tests/**/*.py} : Validate input/output behavior in tests.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-06-30T14:41:58.849Z
Learning: Applies to {src/backend/tests/**/*.py,src/frontend/**/*.test.{ts,tsx,js,jsx},src/frontend/**/*.spec.{ts,tsx,js,jsx},tests/**/*.py} : Mock external dependencies appropriately in tests.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-06-30T14:41:58.849Z
Learning: Applies to src/frontend/**/*.@(test|spec).{ts,tsx,js,jsx} : Frontend tests should cover both sync and async code paths, including error handling and edge cases.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-06-30T14:41:58.849Z
Learning: Applies to {src/backend/tests/**/*.md,tests/**/*.md} : If unit tests are incomplete, create a Markdown file with manual testing steps in the same directory as the unit tests, using the same filename as the component but with a '.md' extension.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-06-30T14:41:58.849Z
Learning: Applies to {src/backend/tests/**/*.py,src/frontend/**/*.test.{ts,tsx,js,jsx},src/frontend/**/*.spec.{ts,tsx,js,jsx},tests/**/*.py} : Expected behaviors should be explicitly stated in test docstrings or comments.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-06-30T14:41:58.849Z
Learning: Applies to {src/backend/tests/**/*.py,src/frontend/**/*.test.{ts,tsx,js,jsx},src/frontend/**/*.spec.{ts,tsx,js,jsx},tests/**/*.py} : Test both sync and async code paths in components.
src/frontend/src/modals/apiModal/codeTabs/code-tabs.tsx (4)
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/frontend_development.mdc:0-0
Timestamp: 2025-06-30T14:40:29.510Z
Learning: Applies to src/frontend/src/{components,hooks}/**/*.{ts,tsx} : Implement dark mode support in components and hooks where needed.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/frontend_development.mdc:0-0
Timestamp: 2025-06-30T14:40:29.510Z
Learning: Applies to src/frontend/**/*.{ts,tsx} : Use React 18 with TypeScript for all UI components and frontend logic.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/frontend_development.mdc:0-0
Timestamp: 2025-06-23T12:46:42.048Z
Learning: Use Zustand for state management in React components within the frontend; stores should expose both state and setter functions, and be imported via hooks (e.g., useMyStore).
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/frontend_development.mdc:0-0
Timestamp: 2025-06-23T12:46:42.048Z
Learning: Custom React Flow node types should be implemented as memoized components, using Handle components for connection points and supporting optional icons and labels.
src/frontend/src/modals/apiModal/utils/get-python-api-code.tsx (1)
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-06-30T14:41:58.849Z
Learning: Applies to {src/backend/tests/**/*.py,tests/**/*.py} : Use predefined JSON flows and utility functions for flow testing (e.g., 'create_flow', 'build_flow', 'get_build_events', 'consume_and_assert_stream').
src/frontend/src/modals/apiModal/utils/detect-file-tweaks.ts (1)
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/frontend_development.mdc:0-0
Timestamp: 2025-06-30T14:40:29.510Z
Learning: Applies to src/frontend/src/{components,hooks}/**/*.{ts,tsx} : Implement dark mode support in components and hooks where needed.
src/frontend/src/modals/apiModal/utils/get-js-api-code.tsx (1)
Learnt from: ogabrielluiz
PR: langflow-ai/langflow#0
File: :0-0
Timestamp: 2025-06-26T19:43:18.260Z
Learning: In langflow custom components, the `module_name` parameter is now propagated through template building functions to add module metadata and code hashes to frontend nodes for better component tracking and debugging.
🧬 Code Graph Analysis (1)
src/frontend/src/modals/apiModal/utils/get-curl-code.tsx (1)
src/frontend/src/modals/apiModal/utils/detect-file-tweaks.ts (5)
hasFileTweaks(2-18)hasChatInputFiles(21-29)getAllChatInputNodeIds(61-72)getAllFileNodeIds(75-92)getNonFileTypeTweaks(95-117)
🪛 Gitleaks (8.26.0)
src/frontend/src/modals/apiModal/utils/get-curl-code.tsx
143-146: Discovered a potential authorization token provided in a curl command header, which could compromise the curl accessed resource.
(curl-auth-header)
164-167: Discovered a potential authorization token provided in a curl command header, which could compromise the curl accessed resource.
(curl-auth-header)
⏰ 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: autofix
🔇 Additional comments (11)
src/frontend/src/modals/apiModal/utils/detect-file-tweaks.ts (3)
1-18: LGTM! Well-structured file detection utility.The function correctly identifies all file-related fields with proper type checking and early returns for performance.
20-29: LGTM! Clean functional implementation.Good use of
Array.some()for a concise and readable check.
31-117: LGTM! Consistent and robust implementation across all utility functions.All functions follow a consistent pattern with proper type checking and edge case handling. The separation of concerns between different file types (ChatInput vs File/VideoFile) is well-designed.
src/frontend/src/modals/apiModal/codeTabs/code-tabs.tsx (1)
142-156: LGTM! Clean step parsing implementation.The regex-based parsing correctly extracts step markers and handles both multi-step and single-step code.
src/frontend/src/modals/apiModal/utils/__tests__/api-snippet-generation.test.ts (1)
1-275: Excellent test coverage! Well-structured and comprehensive test suite.The tests cover all utility functions and code generation scenarios with clear descriptions and good edge case coverage. The organization using describe blocks makes the test suite easy to navigate.
src/frontend/src/modals/apiModal/utils/get-python-api-code.tsx (2)
1-68: LGTM! Clean separation of file and non-file upload logic.The function properly detects file uploads and delegates to appropriate code generation paths.
70-131: LGTM! Comprehensive file upload handling for different component types.The code correctly handles both ChatInput (v1 API) and File/VideoFile (v2 API) uploads with appropriate path transformations.
src/frontend/src/modals/apiModal/utils/get-curl-code.tsx (3)
1-67: LGTM! Well-documented function with proper platform detection.The function signature and platform detection logic are clear and comprehensive.
73-116: LGTM! Platform-specific implementations are correct.Good handling of session ID generation differences between Unix and PowerShell.
195-236: LGTM! Well-structured multi-step output with clear markers.The step markers enable proper UI parsing and the platform-specific formatting is maintained. The API key placeholders are appropriate for example code.
src/frontend/src/modals/apiModal/utils/get-js-api-code.tsx (1)
190-252: Well-structured async code with proper error handling.The generated Node.js code has excellent structure with:
- Proper helper functions for multipart form data and HTTP requests
- Comprehensive error handling with try-catch
- Correct Content-Length calculations for both Buffer and JSON payloads
- Clear step-by-step execution flow
|
Tip For best results, initiate chat on the files or code changes. A summary of the changes CodeRabbit can apply:
|
Yeah. I was questioning this as well. I'll probably remove it |
- Replace dynamic session_id generation with a placeholder "YOUR_SESSION_ID_HERE" for both Unix and PowerShell environments. - Update tests to reflect the change, ensuring they check for the new session_id placeholder instead of UUID generation commands. - Enhance clarity in generated curl commands and maintain consistency across different platforms.
…y and maintainability 🔧 (frontend): refactor codeTabs component to add support for auto login feature 🔧 (frontend): refactor api-snippet-generation test to include tests for API key authentication 🔧 (frontend): refactor get-curl-code, get-js-api-code, and get-python-api-code to conditionally include API key based on shouldDisplayApiKey parameter
🎯 Summary
This PR enhances the API snippet generation feature to properly handle file uploads and ensures consistent authentication across all code snippets. It addresses several bugs and inconsistencies in the generated API code.
🐛 Problems Fixed
Hardcoded session ID
session_id: "user_1", Python/cURL had noneInconsistent API key handling
isAuthparameterNo file upload support
✨ New Features
1. Multi-Step File Upload Support
When flows contain file components (ChatInput with files, File, or VideoFile), the API modal now generates:
2. Language-Specific File Upload Implementation
requests.post()withfiles={"file": f}for multipart uploadshttpmodule with customcreateFormData()helper for multipart/form-data-F "file=@filename"flag for both Unix and PowerShell variantsEach implementation properly handles the response to extract file paths (
file_pathfrom v1,pathfrom v2) and injects them into the flow execution payload.3. Improved Code Organization
🔧 Technical Implementation
New File:
detect-file-tweaks.ts(117 lines)Helper functions to detect and handle file-related tweaks:
hasFileTweaks()- Detects any file componentsgetAllChatInputNodeIds()- Gets nodes using v1 upload APIgetAllFileNodeIds()- Gets nodes using v2 upload APIgetNonFileTypeTweaks()- Filters out file tweaks for final payloadUpdated Files
code-tabs.tsx- Removed unusedisAuthparameter, added multi-step UI renderingget-curl-code.tsx- Added file upload logic with step markersget-js-api-code.tsx- Native Node.js implementation with form data handlingget-python-api-code.tsx- Python requests with multipart file uploads📋 Testing
🎨 UI/UX Changes
Single-Step Display (No Files)
Multi-Step Display (With Files)
📝 Code Quality Improvements
Testing Instructions
Files Changed: 6 files (+604, -289)
Summary by CodeRabbit
New Features
Bug Fixes
Tests