Skip to content

Conversation

@RohitR311
Copy link
Collaborator

@RohitR311 RohitR311 commented May 1, 2025

Summary by CodeRabbit

  • New Features

    • Enabled editing and saving of multiple scrape list limits within a robot workflow.
    • The interface now dynamically detects and displays input fields for all scrape list limits, allowing users to modify each individually.
  • Bug Fixes

    • Improved validation when updating recordings to ensure at least one relevant field is present.
  • Refactor

    • Streamlined the process for updating target URLs and batch updating limits in workflows for better reliability and flexibility.

@RohitR311 RohitR311 added Type: Bug Something isn't working Type: Enhancement Improvements to existing features labels May 1, 2025
@coderabbitai
Copy link

coderabbitai bot commented May 1, 2025

Walkthrough

This change extends the ability to update robot workflow "limits" from a single value to multiple values, enabling batch updates at arbitrary workflow positions. The API, backend route, and frontend UI are all updated to support this. The backend now accepts an array of limit updates, applies them to the workflow, and persists them. The frontend dynamically detects all relevant limits in a workflow, displays corresponding input fields, and sends all changes together. Validation is updated to require at least one of several fields, and the process for updating the workflow's target URL is refactored for clarity and efficiency.

Changes

File(s) Change Summary
server/src/routes/storage.ts Refactored the PUT /recordings/:id endpoint to handle an array of limits updates instead of a single limit, include credentials in validation, and update the workflow and target URL logic for batch and targeted updates.
src/api/storage.ts Updated the updateRecording function signature to accept a limits array (with indices and values) instead of a single limit, aligning the API with the new backend and frontend expectations.
src/components/robot/RobotEdit.tsx Added detection and rendering of multiple scrape list limits in the workflow, enabling editing and saving of multiple limits. Refactored state, handlers, and payload to support an array of limit updates with their respective indices.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant RobotEditModal
    participant API
    participant Backend

    User->>RobotEditModal: Open robot edit modal
    RobotEditModal->>RobotEditModal: Detect all scrapeList limits in workflow
    User->>RobotEditModal: Edit multiple limit fields
    User->>RobotEditModal: Click Save
    RobotEditModal->>API: updateRecording(id, { name, limits[], ... })
    API->>Backend: PUT /recordings/:id (with limits[])
    Backend->>Backend: Validate and apply all limits to workflow
    Backend->>Backend: Update workflow and other fields
    Backend-->>API: Success response
    API-->>RobotEditModal: Success
    RobotEditModal-->>User: Update UI/close modal
Loading

Possibly related PRs

  • feat: edit robot target url #485: Adds and handles a single targetUrl update in the workflow, overlapping with this PR's refactored and extended target URL and limits update logic.

Suggested labels

Type: Feature

Suggested reviewers

  • amhsirak

Poem

In the warren of code, a rabbit did see,
Many limits to set, not just one, but three!
With nimble paws, it hopped through the flow,
Updating each field, making changes just so.
Now robots can scurry with limits galore—
This bunny approves, and is ready for more!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

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.
    • Generate unit testing code for this file.
    • 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. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai 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

Documentation and Community

  • 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

@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: 3

🔭 Outside diff range comments (1)
server/src/routes/storage.ts (1)

346-347: ⚠️ Potential issue

Response may return stale data

robot was fetched before the Robot.update(...) call (line 338). Consequently the response might not include the freshly updated workflow or metadata. Return the updatedRobot instance instead.

-return res.status(200).json({ message: 'Robot updated successfully', robot });
+return res.status(200).json({ message: 'Robot updated successfully', robot: updatedRobot });
🧹 Nitpick comments (4)
src/api/storage.ts (1)

31-36: Prefer an exported, reusable type for the limits payload

limits is now appearing in several layers (frontend, API-client, backend). Duplicating the inline {pairIndex, actionIndex, argIndex, limit} literal in every file invites drift. Consider extracting a dedicated TypeScript interface (e.g. ScrapeListLimitPayload) in a shared location (types.ts) and importing it here and in the React layer so that a change in one place is picked up everywhere by the compiler.

server/src/routes/storage.ts (1)

258-262: Validation message uses the wrong field name

The error message mentions "target_url", but the field expected in the request body is targetUrl. This may confuse API consumers.

-return res.status(400).json({ error: 'Either "name", "limits", "credentials" or "target_url" must be provided.' });
+return res.status(400).json({ error: 'Either "name", "limits", "credentials" or "targetUrl" must be provided.' });
src/components/robot/RobotEdit.tsx (2)

136-160: findScrapeListLimits overlooks non-zero arg indices

The current scan only inspects action.args[0]. If a future workflow places the limit inside another argument (e.g. index 1 for an options object) it will be ignored. Iterating over all args increases robustness.

-                if (action.action === 'scrapeList' && action.args && action.args.length > 0) {
-                    const arg = action.args[0];
+                if (action.action === 'scrapeList' && Array.isArray(action.args)) {
+                    action.args.forEach((arg, argIndex) => {
+                        if (arg && typeof arg === 'object' && 'limit' in arg) {
+                            limits.push({ pairIndex, actionIndex, argIndex, currentLimit: arg.limit });
+                        }
+                    });
                     ...

323-351: State updates risk stale closures

setScrapeListLimits is invoked inside the functional update of setRobot. Because React batches state updates, prev inside setScrapeListLimits could reference an outdated array when many quick edits occur. Safer pattern:

setRobot(prev => { ... });
setScrapeListLimits(prevLimits => prevLimits.map(...));

Trigger the two updates separately to avoid nested-state pitfalls.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 60176fe and 24f3d50.

📒 Files selected for processing (3)
  • server/src/routes/storage.ts (3 hunks)
  • src/api/storage.ts (1 hunks)
  • src/components/robot/RobotEdit.tsx (7 hunks)

Comment on lines 276 to 299
if (targetUrl) {
const updatedWorkflow = robot.recording.workflow.map((step) => {
if (step.where?.url && step.where.url !== "about:blank") {
step.where.url = targetUrl;
}

step.what.forEach((action) => {
const updatedWorkflow = [...robot.recording.workflow];

for (let i = updatedWorkflow.length - 1; i >= 0; i--) {
const step = updatedWorkflow[i];
for (let j = 0; j < step.what.length; j++) {
const action = step.what[j];
if (action.action === "goto" && action.args?.length) {
action.args[0] = targetUrl;
}
});

return step;
});

robot.set('recording', { ...robot.recording, workflow: updatedWorkflow });
robot.changed('recording', true);
action.args[0] = targetUrl;
if (step.where?.url && step.where.url !== "about:blank") {
step.where.url = targetUrl;
}

robot.set('recording', { ...robot.recording, workflow: updatedWorkflow });
robot.changed('recording', true);
i = -1;
break;
}
}
}
}

await robot.save();
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Multiple persistence calls & brittle loop-breaking logic

  1. The workflow is mutated, robot.set(...) is called and await robot.save() (line 299), then later a second Robot.update(...) call is executed (line 338). Two round-trips to the DB are unnecessary and risk race conditions if another request updates the same record in between.

  2. Breaking out of the outer loop via i = -1 is error-prone and non-idiomatic. A labeled break or early‐return would be clearer.

A cleaner approach is to:
• Mutate updatedWorkflow in memory,
• Build the single updates object (including the updated workflow and optionally recording_meta.name),
• Call Robot.update(...) once.

-            robot.set('recording', { ...robot.recording, workflow: updatedWorkflow });
-            robot.changed('recording', true);
-            i = -1;
-            break;
+            foundGoto = true;
+            break outer;

…and remove the earlier robot.save() entirely.

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +307 to 321
if (limits && Array.isArray(limits) && limits.length > 0) {
for (const limitInfo of limits) {
const { pairIndex, actionIndex, argIndex, limit } = limitInfo;

const pair = workflow[pairIndex];
if (!pair || !pair.what) continue;

const action = pair.what[actionIndex];
if (!action || !action.args) continue;

const arg = action.args[argIndex];
if (!arg || typeof arg !== 'object') continue;

(arg as { limit: number }).limit = limit;
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Missing sanitisation for user-supplied limit values

limit is written straight into the workflow without any bounds-checking. A malicious caller could set an arbitrarily large (or negative) number and later crash the interpreter.

-        (arg as { limit: number }).limit = limit;
+        const capped = Math.max(1, Math.min(5, Number(limit))); // 5 is the upper-bound used elsewhere
+        (arg as { limit: number }).limit = capped;

Add explicit Number.isFinite checks and return 400 on invalid input.

Comment on lines +438 to +470
const renderScrapeListLimitFields = () => {
if (scrapeListLimits.length === 0) return null;

return (
<>
<Typography variant="body1" style={{ marginBottom: '20px' }}>
{t('List Limits')}
</Typography>

{scrapeListLimits.map((limitInfo, index) => (
<TextField
key={`limit-${limitInfo.pairIndex}-${limitInfo.actionIndex}`}
label={`${t('List Limit')} ${index + 1}`}
type="number"
value={limitInfo.currentLimit || ''}
onChange={(e) => {
const value = parseInt(e.target.value, 10);
if (value >= 1) {
handleLimitChange(
limitInfo.pairIndex,
limitInfo.actionIndex,
limitInfo.argIndex,
value
);
}
}}
inputProps={{ min: 1 }}
style={{ marginBottom: '20px' }}
/>
))}
</>
);
};
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

parseInt / empty input edge case & non-unique React keys

  1. Clearing a limit field yields parseInt('', 10) → NaN, which fails the value >= 1 guard and leaves the UI stuck on the old value. Provide explicit empty-string handling.

  2. The key omits argIndex; two limits on different args of the same action would collide.

-const value = parseInt(e.target.value, 10);
-if (value >= 1) {
+const raw = e.target.value;
+const parsed = Number(raw);
+if (raw === '') {
+  handleLimitChange(..., 1); // or omit the update and show validation
+} else if (!Number.isNaN(parsed) && parsed >= 1) {
+  handleLimitChange(..., parsed);
 }
 ...
-key={`limit-${limitInfo.pairIndex}-${limitInfo.actionIndex}`}
+key={`limit-${limitInfo.pairIndex}-${limitInfo.actionIndex}-${limitInfo.argIndex}`}

Committable suggestion skipped: line range outside the PR's diff.

@amhsirak amhsirak merged commit 5e404f8 into develop May 6, 2025
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Type: Bug Something isn't working Type: Enhancement Improvements to existing features

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants