Skip to content

fix: abort operation #629

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Jun 12, 2025
Merged

fix: abort operation #629

merged 9 commits into from
Jun 12, 2025

Conversation

amhsirak
Copy link
Member

@amhsirak amhsirak commented Jun 4, 2025

Summary by CodeRabbit

  • New Features

    • Users can now abort runs that are in either "running" or "queued" status directly from the interface.
  • Bug Fixes

    • Improved error handling and messaging when aborting runs, providing clearer feedback for unauthorized access, missing runs, or invalid run states.
    • Added handling for browser limits by queuing runs with active browser IDs when available.
  • Refactor

    • Updated abort handler functions to require additional context (run ID, robot name, browser ID) for more precise operations.
    • Enhanced code formatting and consistency across run-related components and endpoints.
  • Chores

    • Removed the unused Dockerfile for backend containerization.

@amhsirak amhsirak marked this pull request as draft June 4, 2025 12:42
Copy link

coderabbitai bot commented Jun 4, 2025

Walkthrough

This update removes the server Dockerfile and refactors several frontend and backend files to improve code formatting, error handling, and function signatures. The abort run logic is enhanced to provide more detailed responses and status updates. Several React component props and handler signatures are updated to require additional arguments for aborting runs.

Changes

Files/Groups Change Summary
server/Dockerfile Deleted the Dockerfile for the Node.js backend with Playwright.
server/src/routes/storage.ts Refactored code formatting, improved error handling, especially in abort run endpoint, and enhanced logging.
src/components/run/ColapsibleRow.tsx, src/components/run/Runs.tsx,
src/components/run/RunsTable.tsx, src/pages/MainPage.tsx Updated abortRunHandler prop/function signatures to require runId, robotName, and browserId; updated Data interface.
src/components/run/RunContent.tsx Modified stop button logic to show for both 'running' and 'queued' statuses.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant UI (React)
    participant Backend (API)
    participant DB

    User->>UI (React): Click "Abort Run" (with runId, robotName, browserId)
    UI (React)->>Backend (API): POST /runs/abort/:id (with identifiers)
    Backend (API)->>DB: Update run status to 'aborting'
    alt Run is queued
        Backend (API)->>DB: Set status to 'aborted', add finished timestamp and log
        Backend (API)->>UI (React): Respond with abort job ID and success
    else Run is running
        Backend (API)->>Abort Queue: Add abort job
        Backend (API)->>UI (React): Respond with abort job ID and success
    end
    UI (React)->>User: Show notification (success or error)
Loading

Possibly related PRs

Suggested reviewers

  • amhsirak

Poem

A Dockerfile hops away,
While aborts now know what to say.
With run, robot, and browser in tow,
The UI and backend both now know.
Refactored code, clean and spry—
The bunnies cheer as tests go by!
🐇✨

✨ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

@amhsirak amhsirak marked this pull request as ready for review June 5, 2025 19:22
@amhsirak amhsirak requested a review from RohitR311 June 5, 2025 19:23
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: 0

🔭 Outside diff range comments (1)
src/components/run/RunContent.tsx (1)

36-36: ⚠️ Potential issue

Critical: Function signature inconsistency.

The abortRunHandler function signature here shows () => void, but according to the changes in other files (Runs.tsx, ColapsibleRow.tsx, RunsTable.tsx), it should be (runId: string, robotName: string, browserId: string) => void. This inconsistency will cause TypeScript compilation errors.

Apply this fix:

-  abortRunHandler: () => void,
+  abortRunHandler: (runId: string, robotName: string, browserId: string) => void,

You'll also need to update the usage in the component to pass the required parameters.

🧹 Nitpick comments (1)
server/src/routes/storage.ts (1)

153-157: Consider using optional chaining for safer property access.

The static analysis tool suggests using optional chaining to improve safety when accessing nested properties.

Apply this diff to use optional chaining:

-  if (run.serializableOutput && run.serializableOutput['item-0']) {
-    formattedRun.data = run.serializableOutput['item-0'];
-  } else if (run.binaryOutput && run.binaryOutput['item-0']) {
-    formattedRun.screenshot = run.binaryOutput['item-0'];
+  if (run.serializableOutput?.['item-0']) {
+    formattedRun.data = run.serializableOutput['item-0'];
+  } else if (run.binaryOutput?.['item-0']) {
+    formattedRun.screenshot = run.binaryOutput['item-0'];
🧰 Tools
🪛 Biome (1.9.4)

[error] 153-153: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 155-155: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c6a1d82 and a23f2f7.

📒 Files selected for processing (7)
  • server/Dockerfile (0 hunks)
  • server/src/routes/storage.ts (13 hunks)
  • src/components/run/ColapsibleRow.tsx (2 hunks)
  • src/components/run/RunContent.tsx (2 hunks)
  • src/components/run/Runs.tsx (1 hunks)
  • src/components/run/RunsTable.tsx (2 hunks)
  • src/pages/MainPage.tsx (2 hunks)
💤 Files with no reviewable changes (1)
  • server/Dockerfile
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/pages/MainPage.tsx (1)
src/api/storage.ts (1)
  • notifyAboutAbort (187-199)
🪛 Biome (1.9.4)
server/src/routes/storage.ts

[error] 153-153: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 155-155: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (10)
src/components/run/RunContent.tsx (1)

444-449: Good enhancement: Allow aborting queued runs.

Expanding the condition to include 'queued' status is a logical improvement that allows users to abort runs before they start executing.

src/components/run/Runs.tsx (1)

7-7: LGTM: Function signature correctly updated.

The abortRunHandler signature now properly requires the three parameters needed for enhanced abort functionality: runId, robotName, and browserId.

src/components/run/ColapsibleRow.tsx (2)

36-36: LGTM: Function signature correctly updated.

The abortRunHandler signature properly matches the enhanced abort functionality requiring runId, robotName, and browserId parameters.


62-64: LGTM: Correct implementation of enhanced abort handler.

The function correctly passes the required three parameters from the row data: runId, name (as robotName), and browserId.

src/components/run/RunsTable.tsx (2)

56-56: LGTM: Added browserId property for enhanced abort functionality.

The browserId field addition to the Data interface is necessary to support the enhanced abort handler that requires browser identification.


69-69: LGTM: Function signature correctly updated.

The abortRunHandler signature properly matches the enhanced abort functionality requiring runId, robotName, and browserId parameters.

src/pages/MainPage.tsx (2)

52-63: LGTM! Improved function signature and self-containment.

The updated abortRunHandler signature with explicit parameters (runId, robotName, browserId) makes the function more self-contained and less dependent on component state. Using the passed robotName parameter instead of runningRecordingName state improves consistency, and adding setRerenderRuns(true) ensures proper UI updates after the abort operation.


160-160: Simplified prop passing aligns with function signature change.

The direct passing of abortRunHandler function is consistent with the updated signature that now accepts the required parameters (runId, robotName, browserId) that will be provided by the Runs component.

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

890-949: Excellent enhancement of abort endpoint with comprehensive validation and error handling.

The updated abort endpoint significantly improves functionality with:

  1. Proper authorization: Validates user authentication and run ownership
  2. Status validation: Only allows aborting runs with 'running' or 'queued' status
  3. Differentiated handling: Queued runs are immediately marked as 'aborted', while running runs are queued for proper termination
  4. Comprehensive error responses: Returns appropriate HTTP status codes and detailed error messages
  5. Improved logging: Better tracking of abort operations

The implementation correctly handles the edge case where queued runs don't need complex termination logic and can be immediately aborted.


171-249: Approve code formatting improvements in handleWorkflowActions function.

The reformatting of the handleWorkflowActions function significantly improves readability while maintaining the same business logic for credential injection and workflow processing.

@amhsirak amhsirak added the Type: Bug Something isn't working label Jun 5, 2025
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: 1

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

608-670: ⚠️ Potential issue

Syntax error – double else chain makes the file uncompilable

A second else appears immediately after a complete if/else block, which produces a parser error (Expected a statement here; unreachable code).
Nothing after the first return res.send({...}) can be reached, so the active-browser reuse branch never runs.

-    } else {
-      const browserId = uuid(); 
-
-      return res.send({...});
-    } else {
-      const browserId = getActiveBrowserIdByState(req.user.id, "run")
-
-      return res.send({...});
-    }
+    } else {
+      // Try to reuse an active browser first; if none, fall back to a random UUID
+      const browserId =
+        getActiveBrowserIdByState(req.user.id, 'run') ?? uuid();
+
+      await Run.create({ … });
+
+      return res.send({
+        browserId,
+        runId,
+        robotMetaId: recording.recording_meta.id,
+        queued: true,
+      });
+    }

Remove the first queued branch or merge the two paths as shown. Without this fix the server will fail to start.

🧰 Tools
🪛 Biome (1.9.4)

[error] 633-633: Expected a statement but instead found 'else'.

Expected a statement here.

(parse)


[error] 634-669: This code is unreachable

(lint/correctness/noUnreachable)

🧹 Nitpick comments (3)
server/src/routes/storage.ts (3)

993-1004: Minor: missing await-safety around queue creation

pgBoss.createQueue returns a promise; failures inside it are already caught, but any rejection in createQueue before send would currently be swallowed. Wrap both calls in a single try/await block (or keep as is but add its own try/catch).


139-157: Use optional chaining for brevity

Static-analysis correctly flags the nested checks; optional chaining reduces noise:

-  if (run.serializableOutput && run.serializableOutput['item-0']) {
-    formattedRun.data = run.serializableOutput['item-0'];
-  } else if (run.binaryOutput && run.binaryOutput['item-0']) {
-    formattedRun.screenshot = run.binaryOutput['item-0'];
+  if (run.serializableOutput?.['item-0']) {
+    formattedRun.data = run.serializableOutput['item-0'];
+  } else if (run.binaryOutput?.['item-0']) {
+    formattedRun.screenshot = run.binaryOutput['item-0'];
   }
🧰 Tools
🪛 Biome (1.9.4)

[error] 153-153: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 155-155: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


25-61: Deep-clone with JSON.stringify drops non-serialisable fields

processWorkflowActions uses JSON.parse(JSON.stringify(workflow)). If a workflow ever contains functions, Dates, or circular refs they will be silently lost or crash. Consider structuredClone (Node 18+) or lodash.cloneDeep for safer cloning.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a23f2f7 and 65472e0.

📒 Files selected for processing (3)
  • server/src/routes/storage.ts (11 hunks)
  • src/components/run/RunContent.tsx (2 hunks)
  • src/pages/MainPage.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/components/run/RunContent.tsx
  • src/pages/MainPage.tsx
🧰 Additional context used
🪛 Biome (1.9.4)
server/src/routes/storage.ts

[error] 153-153: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 155-155: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 633-633: Expected a statement but instead found 'else'.

Expected a statement here.

(parse)


[error] 634-669: This code is unreachable

(lint/correctness/noUnreachable)

Comment on lines +970 to +989
if (!['running', 'queued'].includes(run.status)) {
return res.status(400).send({
error: `Cannot abort run with status: ${run.status}`
});
}

await run.update({
status: 'aborting'
});

if (run.status === 'queued') {
await run.update({
status: 'aborted',
finishedAt: new Date().toLocaleString(),
log: 'Run aborted while queued'
});

return res.send({ success: true, message: 'Queued run aborted' });
}

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Logic bug – run.status is inspected after you mutate it

await run.update({ status: 'aborting' }) mutates the instance, so the subsequent

if (run.status === 'queued') {  }

can never be true. Capture the original status before the update:

-    await run.update({ status: 'aborting' });
-    if (run.status === 'queued') {
+    const previousStatus = run.status as string;
+    await run.update({ status: 'aborting' });
+    if (previousStatus === 'queued') {

Without this, queued runs are never marked aborted, and no response is sent to the client.

🤖 Prompt for AI Agents
In server/src/routes/storage.ts around lines 970 to 989, the code updates
run.status to 'aborting' before checking if the original status was 'queued',
causing the condition to never be true. To fix this, store the original
run.status in a variable before the update call, then use that variable in the
subsequent if condition to correctly handle queued runs and send the appropriate
response.

@amhsirak amhsirak merged commit c8b00eb into develop Jun 12, 2025
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
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants