Skip to content
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

feat: show confirmation modal for deleting robots and runs #319

Open
wants to merge 7 commits into
base: develop
Choose a base branch
from

Conversation

AmitChauhan63390
Copy link
Contributor

@AmitChauhan63390 AmitChauhan63390 commented Jan 4, 2025

Summary by CodeRabbit

  • New Features

    • Added confirmation dialog for deleting runs and recordings.
    • Enhanced localization support with new UI strings for deletion confirmation in multiple languages.
    • Improved error handling for recording and run management.
  • Bug Fixes

    • Refined error notifications for recording and run operations.
  • Documentation

    • Updated localization files with more comprehensive user interface text.

Copy link

coderabbitai bot commented Jan 4, 2025

Walkthrough

This pull request introduces comprehensive updates across multiple files, focusing on enhancing user interface localization and interaction. The changes primarily involve restructuring the English localization JSON file, adding new sections for various functionalities, and implementing confirmation dialogs for deletion actions in both the Recordings and Runs tables. The modifications aim to improve user experience by providing clearer feedback, more robust error handling, and additional safety measures when performing critical actions.

Changes

File Change Summary
public/locales/en.json Comprehensive restructuring of localization strings, adding new sections for recording, browser, interpretation, runs table, navbar, and language menu
public/locales/de.json Added "delete_confirmation" section under "recordingtable" with localized strings for deletion confirmation
public/locales/es.json Added "delete_confirmation" section under "recordingtable" with localized strings for deletion confirmation
public/locales/ja.json Added "delete_confirmation" section under "recordingtable" with localized strings for deletion confirmation
public/locales/zh.json Added "delete_confirmation" section under "recordingtable" with localized strings for deletion confirmation
src/components/robot/RecordingsTable.tsx Enhanced error handling, added confirmation dialog for deletions, standardized code formatting
src/components/run/RunsTable.tsx Implemented delete confirmation dialog with new state management and interaction methods

Sequence Diagram

sequenceDiagram
    participant User
    participant UI
    participant DeleteDialog
    participant Backend

    User->>UI: Initiate Delete Action
    UI->>DeleteDialog: Open Confirmation Dialog
    DeleteDialog->>User: Prompt Confirmation
    User->>DeleteDialog: Confirm Deletion
    DeleteDialog->>Backend: Send Delete Request
    Backend-->>UI: Delete Confirmation
    UI->>User: Show Success Notification
Loading

Poem

🐰 A Rabbit's Localization Delight

In JSON's realm, new strings take flight,
Dialogs dance with delete's might,
Confirmations bloom so bright,
Code refined with rabbit's insight,
User experience shining light! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.

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. (Beta)
  • @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: 1

🧹 Nitpick comments (4)
src/components/molecules/RunsTable.tsx (2)

132-138: Potential improvement for selective item deletion
Currently, calling setRows([]) removes all rows briefly before re-fetching them. This can cause unnecessary flicker and overhead if only one run needs to be deleted. Consider directly removing the specific run from rows prior to re-fetching to maintain a smoother UX.

  const handleDeleteConfirm = () => {
-   setRows([]);
+   setRows((prevRows) => prevRows.filter((r) => r.id !== runToDelete?.id));
    notify('success', t('runstable.notifications.delete_success'));
    fetchRuns();
    setDeleteDialogOpen(false);
    setRunToDelete(null);
  };

228-250: Hard-coded text in dialog title
Currently, "Delete Run" is hard-coded. For localization synergy, consider using something like t('runstable.delete_confirmation.title') if that exists. This will further align with the approach seen in RecordingsTable.

 <DialogTitle id="alert-dialog-title">
-  Delete Run
+  {t('runstable.delete_confirmation.title', 'Delete Run')}
 </DialogTitle>
src/components/molecules/RecordingsTable.tsx (2)

156-156: Use optional chaining here
The static analysis hint suggests using optional chaining. In line 156, you can safely check if recording?.recording_meta exists before accessing it, preventing potential runtime errors.

- if (recording && recording.recording_meta) {
+ if (recording?.recording_meta) {
🧰 Tools
🪛 Biome (1.9.4)

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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


371-388: Delete recording flow
Deletion logic is triggered inline. While this works, you might consider a dedicated confirmation dialog—similar to the OptionsButton approach—for consistency. Right now, line 385 ensures errors are reported, which is good.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c132f27 and 1d7f9ed.

📒 Files selected for processing (3)
  • public/locales/en.json (1 hunks)
  • src/components/molecules/RecordingsTable.tsx (7 hunks)
  • src/components/molecules/RunsTable.tsx (5 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/components/molecules/RecordingsTable.tsx

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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (11)
src/components/molecules/RunsTable.tsx (5)

12-16: Imports for Material-UI Dialog components
These imports properly introduce the required Material-UI dialog components.


88-89: Use of new state for dialog management
deleteDialogOpen and runToDelete are sensible additions for tracking deletion state and which run is to be removed.


127-130: Method rename and usage
handleDeleteClick cleanly shifts deletion logic into a confirmation-based flow. This readably sets runToDelete and opens the dialog.


140-142: Graceful dialog close
handleDeleteCancel properly resets state when the user cancels the deletion, preserving consistency.


204-204: Delegation to handleDeleteClick
Linking handleDelete to handleDeleteClick(row) is consistent, ensuring each row triggers the Dialog.

src/components/molecules/RecordingsTable.tsx (2)

178-184: Robust error handling
Catching errors on stopRecording(browserId) is beneficial. Kudos for adding user-facing notifications here, enhancing clarity when a recording fails to stop.


Line range hint 548-586: Enhanced confirmation flow in OptionsButton
This approach includes a separate confirmation dialog for deletion, ensuring user safeguards. The interplay with checkRunsForRecording is well-handled, but if the user has many runs, you might consider a loading state or a direct approach to gracefully handle the asynchronous checks.

public/locales/en.json (4)

46-51: Addition of delete confirmation strings
Including "delete_confirmation" fosters improved user interaction by clarifying irreversible deletion steps. Good approach for multi-lingual support.


62-74: Updates to runstable notifications
Providing distinct success and fail notifications helps thoroughly convey the system state to users.


156-173: List extraction and pagination instructions
These localized strings thoroughly guide users in setting pagination and list extraction limits. This is valuable for user education.


Line range hint 568-580: Detailed error and success messages
Comprehensive error notifications, especially referencing variables (e.g. {{message}}), ensure clarity for debugging. Keep verifying placeholders to avoid mismatches.

Comment on lines 566 to 587
const handleDeleteConfirm = async () => {
try {
checkRunsForRecording(recordingName).then((result: boolean) => {
if (result) {
notify('warning', t('recordingtable.notifications.delete_warning'));
setDeleteDialogOpen(false);
}
})




// Only proceed with deletion if there are no runs
handleDelete();
setDeleteDialogOpen(false);
notify("success", t("recordingtable.notifications.delete_success"));
} catch (error) {
console.error('Error during deletion:', error);
notify("error", t("recordingtable.notifications.delete_error"));
setDeleteDialogOpen(false);
}
};
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Race condition in deletion logic needs to be fixed

The verification reveals a serious race condition in the deletion logic. The code calls handleDelete() immediately after starting the checkRunsForRecording promise, without waiting for its result. This means:

  1. The deletion will always proceed regardless of whether there are associated runs
  2. The comment "Only proceed with deletion if there are no runs" is incorrect as the code doesn't enforce this condition
  3. The warning notification about existing runs may appear after the deletion is already completed

Here's what needs to be fixed:

  • Move the handleDelete() call inside the .then() block
  • Only call it when result is false (no runs exist)
  • Use proper async/await syntax instead of mixing with .then()
🔗 Analysis chain

Conditionally skipping actual delete
Your logic at lines 568–580 could skip the actual removal if runs are associated. As a follow-up, consider placing that skip logic inside or after the promise’s .then block, clarifying if the code still calls handleDelete() once checkRunsForRecording returns true.

  const handleDeleteConfirm = async () => {
    try {
      checkRunsForRecording(recordingName).then((result: boolean) => {
        if (result) {
          notify('warning', t('recordingtable.notifications.delete_warning'));
          setDeleteDialogOpen(false);
-         // Potentially still calls handleDelete() below
+         return; // ensure we skip the actual delete if runs exist
        }
      });
      handleDelete();
      ...

Let me gather more information about the code to verify the concern.


Let me search for the actual handleDelete implementation in the RecordingsTable component since the one found is from a different component.


Let me search for the actual delete operation in the file.

🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Search for handleDeleteConfirm implementation and its related functions
ast-grep --pattern 'const handleDeleteConfirm = async () => {
  $$$
}'

# Also search for checkRunsForRecording function to understand its implementation
ast-grep --pattern 'const checkRunsForRecording = $_'

# Search for handleDelete implementation
ast-grep --pattern 'const handleDelete = $_'

Length of output: 3090


Script:

#!/bin/bash
# Search for handleDelete in RecordingsTable.tsx
rg "const handleDelete" src/components/molecules/RecordingsTable.tsx -A 5

Length of output: 528


Script:

#!/bin/bash
# Search for delete-related operations in RecordingsTable.tsx
rg "delete" src/components/molecules/RecordingsTable.tsx -B 2 -A 5

Length of output: 3346

@amhsirak amhsirak added the Type: Enhancement Improvements to existing features label Jan 5, 2025
@amhsirak amhsirak changed the title Confirmation modal feat: show confirmation modal for deleting recordings and runs Jan 5, 2025
Copy link
Member

@amhsirak amhsirak left a comment

Choose a reason for hiding this comment

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

@RohitR311 resolve conflicts

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

♻️ Duplicate comments (1)
src/components/molecules/RecordingsTable.tsx (1)

559-580: ⚠️ Potential issue

Race condition in deletion logic still needs to be fixed

The current implementation still has a race condition where handleDelete() is called before the checkRunsForRecording promise resolves.

Apply this fix to resolve the race condition:

 const handleDeleteConfirm = async () => {
   try {
-    checkRunsForRecording(recordingName).then((result: boolean) => {
-     if (result) {
-       notify('warning', t('recordingtable.notifications.delete_warning'));
-       setDeleteDialogOpen(false);
-     }
-    })
-    
-    // Only proceed with deletion if there are no runs
-    handleDelete();
+    const hasRuns = await checkRunsForRecording(recordingName);
+    if (hasRuns) {
+      notify('warning', t('recordingtable.notifications.delete_warning'));
+      setDeleteDialogOpen(false);
+      return;
+    }
+    
+    await handleDelete();
     setDeleteDialogOpen(false);
     notify("success", t("recordingtable.notifications.delete_success"));
   } catch (error) {
🧹 Nitpick comments (3)
src/components/molecules/RecordingsTable.tsx (3)

144-167: Enhance error handling with specific error messages

The error handling is good, but could be more informative for better debugging and user experience.

 catch (error) {
-   notify('error', 'Error fetching recordings.');
+   const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
+   notify('error', `Error fetching recordings: ${errorMessage}`);
    console.error('Error fetching recordings: ', error);
-   // Don't continue setting rows after an error
-   setRows([]);
 }

Also applies to: 171-177

🧰 Tools
🪛 Biome (1.9.4)

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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


148-156: Use optional chaining for safer property access

The current implementation could throw if recording is undefined.

-recordings.map((recording: any, index: number) => {
-  if (recording && recording.recording_meta) {
+recordings.map((recording: any, index: number) => {
+  if (recording?.recording_meta) {
🧰 Tools
🪛 Biome (1.9.4)

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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


661-669: Consider moving styles to a separate file

The modal style object should be moved to a separate styles file for better maintainability and reusability.

Consider creating a new file src/styles/modal.styles.ts:

export const modalStyle = {
  top: "50%",
  left: "50%",
  transform: "translate(-50%, -50%)",
  width: "30%",
  backgroundColor: "background.paper",
  p: 4,
  height: "fit-content",
  display: "block",
  padding: "20px",
};
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1d7f9ed and 044001d.

📒 Files selected for processing (1)
  • src/components/molecules/RecordingsTable.tsx (7 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/components/molecules/RecordingsTable.tsx

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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (1)
src/components/molecules/RecordingsTable.tsx (1)

633-655: Well-implemented confirmation dialog!

Great job implementing the confirmation dialog with proper accessibility attributes and internationalization support.

@RohitR311 RohitR311 requested a review from amhsirak January 13, 2025 06:47
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

🧹 Nitpick comments (3)
src/components/robot/RecordingsTable.tsx (3)

144-167: Enhance error handling in fetchRecordings.

The error handling could be more specific to help users understand and resolve issues.

Apply this enhancement:

  try {
    const recordings = await getStoredRecordings();
    if (recordings) {
      const parsedRows: Data[] = [];
      recordings.map((recording: any, index: number) => {
        if (recording && recording.recording_meta) {
          parsedRows.push({
            id: index,
            ...recording.recording_meta,
            content: recording.recording,
          });
        }
      });
      setRecordings(parsedRows.map((recording) => recording.name));
      setRows(parsedRows);
    } else {
      console.log("No recordings found.");
    }
  }
  catch (error) {
-    notify('error', 'Error fetching recordings.');
+    notify('error', t('recordingtable.notifications.fetch_error'));
     console.error('Error fetching recordings: ', error);
  }
🧰 Tools
🪛 Biome (1.9.4)

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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


634-656: Enhance dialog accessibility.

While the dialog implementation is good, it could benefit from some accessibility improvements.

Apply these enhancements:

  <Dialog
    open={deleteDialogOpen}
    onClose={handleDeleteCancel}
    aria-labelledby="alert-dialog-title"
    aria-describedby="alert-dialog-description"
+   role="alertdialog"
  >
    <DialogTitle id="alert-dialog-title">
      {t('recordingtable.delete_confirmation.title')}
    </DialogTitle>
    <DialogContent>
      <DialogContentText id="alert-dialog-description">
        {t('recordingtable.delete_confirmation.message', { name: recordingName })}
      </DialogContentText>
    </DialogContent>
    <DialogActions>
      <Button 
+       aria-label={t('recordingtable.delete_confirmation.cancel')}
        onClick={handleDeleteCancel} 
        color="primary"
      >
        {t('recordingtable.delete_confirmation.cancel')}
      </Button>
      <Button 
+       aria-label={t('recordingtable.delete_confirmation.confirm')}
        onClick={handleDeleteConfirm} 
        color="error" 
        autoFocus
      >
        {t('recordingtable.delete_confirmation.confirm')}
      </Button>
    </DialogActions>
  </Dialog>

147-156: Improve type safety in recordings mapping.

The code uses any type and could benefit from proper typing and optional chaining.

Apply these improvements:

- recordings.map((recording: any, index: number) => {
-   if (recording && recording.recording_meta) {
-     parsedRows.push({
-       id: index,
-       ...recording.recording_meta,
-       content: recording.recording,
-     });
-   }
- });
+ interface RecordingData {
+   recording_meta: {
+     name: string;
+     createdAt: string;
+     updatedAt: string;
+     params: string[];
+   };
+   recording: WorkflowFile;
+ }
+ 
+ recordings.map((recording: RecordingData, index: number) => {
+   if (recording?.recording_meta) {
+     parsedRows.push({
+       id: index,
+       ...recording.recording_meta,
+       content: recording.recording,
+     });
+   }
+ });
🧰 Tools
🪛 Biome (1.9.4)

[error] 149-149: 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 044001d and 07f4221.

📒 Files selected for processing (2)
  • src/components/robot/RecordingsTable.tsx (8 hunks)
  • src/components/run/RunsTable.tsx (5 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/components/robot/RecordingsTable.tsx

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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (5)
src/components/run/RunsTable.tsx (4)

12-17: LGTM! Well-organized imports.

The new Material-UI dialog-related imports are properly organized and grouped with other Material-UI imports.


89-90: LGTM! Well-structured state management.

The state variables are well-typed and follow React conventions. The naming clearly indicates their purpose.


213-213: LGTM! Proper event handler binding.

The handleDelete prop correctly passes the row data to the new dialog system.


141-147: Verify deletion API implementation.

The deletion confirmation UI is in place, but the actual deletion logic needs to be implemented. Please ensure that:

  1. The backend API for run deletion is implemented and documented
  2. The frontend properly handles all possible API response statuses
  3. The deletion operation is atomic and handles concurrent modifications

Let's verify the API implementation:

src/components/robot/RecordingsTable.tsx (1)

Line range hint 1-75: LGTM! Interface and import changes align with the PR objective.

The additions of Dialog-related imports and the recordingName property to OptionsButtonProps are appropriate for implementing the confirmation modal feature.

Comment on lines +136 to +151
const handleDeleteClick = (row: Data) => {
setRunToDelete(row);
setDeleteDialogOpen(true);
};

const handleDeleteConfirm = () => {
setRows([]);
notify('success', t('runstable.notifications.delete_success'));
fetchRuns();
setDeleteDialogOpen(false);
setRunToDelete(null);
};

const handleDeleteCancel = () => {
setDeleteDialogOpen(false);
setRunToDelete(null);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling and improve state management.

The handler functions have several issues that need to be addressed:

  1. handleDeleteConfirm clears all rows unnecessarily before fetching new data
  2. Missing error handling for the deletion operation
  3. The actual deletion logic is not implemented

Consider this implementation:

 const handleDeleteConfirm = async () => {
+  try {
+    if (!runToDelete) return;
+    
+    // TODO: Implement the actual deletion API call
+    // await deleteRun(runToDelete.runId);
+    
     notify('success', t('runstable.notifications.delete_success'));
-    setRows([]);
     await fetchRuns();
+  } catch (error) {
+    notify('error', t('runstable.notifications.delete_error'));
+  } finally {
     setDeleteDialogOpen(false);
     setRunToDelete(null);
+  }
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const handleDeleteClick = (row: Data) => {
setRunToDelete(row);
setDeleteDialogOpen(true);
};
const handleDeleteConfirm = () => {
setRows([]);
notify('success', t('runstable.notifications.delete_success'));
fetchRuns();
setDeleteDialogOpen(false);
setRunToDelete(null);
};
const handleDeleteCancel = () => {
setDeleteDialogOpen(false);
setRunToDelete(null);
const handleDeleteClick = (row: Data) => {
setRunToDelete(row);
setDeleteDialogOpen(true);
};
const handleDeleteConfirm = async () => {
try {
if (!runToDelete) return;
// TODO: Implement the actual deletion API call
// await deleteRun(runToDelete.runId);
notify('success', t('runstable.notifications.delete_success'));
await fetchRuns();
} catch (error) {
notify('error', t('runstable.notifications.delete_error'));
} finally {
setDeleteDialogOpen(false);
setRunToDelete(null);
}
};
const handleDeleteCancel = () => {
setDeleteDialogOpen(false);
setRunToDelete(null);

Comment on lines +237 to +259
<Dialog
open={deleteDialogOpen}
onClose={handleDeleteCancel}
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description"
>
<DialogTitle id="alert-dialog-title">
Delete Run
</DialogTitle>
<DialogContent>
<DialogContentText id="alert-dialog-description">
Are you sure you want to delete the run "{runToDelete?.name}"? This action cannot be undone.
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={handleDeleteCancel} color="primary">
Cancel
</Button>
<Button onClick={handleDeleteConfirm} color="error" autoFocus>
Delete
</Button>
</DialogActions>
</Dialog>
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve accessibility and internationalization.

The Dialog component needs improvements in several areas:

  1. Hard-coded strings should use translations
  2. Missing aria-label on the Delete button
  3. Dialog content could be more descriptive

Apply these improvements:

 <Dialog
   open={deleteDialogOpen}
   onClose={handleDeleteCancel}
   aria-labelledby="alert-dialog-title"
   aria-describedby="alert-dialog-description"
 >
   <DialogTitle id="alert-dialog-title">
-    Delete Run
+    {t('runstable.delete_dialog.title', 'Delete Run')}
   </DialogTitle>
   <DialogContent>
     <DialogContentText id="alert-dialog-description">
-      Are you sure you want to delete the run "{runToDelete?.name}"? This action cannot be undone.
+      {t('runstable.delete_dialog.description', 'Are you sure you want to delete the run "{{name}}"? This action cannot be undone and all associated data will be permanently removed.', { name: runToDelete?.name })}
     </DialogContentText>
   </DialogContent>
   <DialogActions>
     <Button onClick={handleDeleteCancel} color="primary">
-      Cancel
+      {t('common.cancel', 'Cancel')}
     </Button>
     <Button 
       onClick={handleDeleteConfirm} 
       color="error" 
+      aria-label={t('runstable.delete_dialog.delete_aria', 'Delete run {{name}}', { name: runToDelete?.name })}
       autoFocus
     >
-      Delete
+      {t('common.delete', 'Delete')}
     </Button>
   </DialogActions>
 </Dialog>
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
<Dialog
open={deleteDialogOpen}
onClose={handleDeleteCancel}
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description"
>
<DialogTitle id="alert-dialog-title">
Delete Run
</DialogTitle>
<DialogContent>
<DialogContentText id="alert-dialog-description">
Are you sure you want to delete the run "{runToDelete?.name}"? This action cannot be undone.
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={handleDeleteCancel} color="primary">
Cancel
</Button>
<Button onClick={handleDeleteConfirm} color="error" autoFocus>
Delete
</Button>
</DialogActions>
</Dialog>
<Dialog
open={deleteDialogOpen}
onClose={handleDeleteCancel}
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description"
>
<DialogTitle id="alert-dialog-title">
{t('runstable.delete_dialog.title', 'Delete Run')}
</DialogTitle>
<DialogContent>
<DialogContentText id="alert-dialog-description">
{t('runstable.delete_dialog.description', 'Are you sure you want to delete the run "{{name}}"? This action cannot be undone and all associated data will be permanently removed.', { name: runToDelete?.name })}
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={handleDeleteCancel} color="primary">
{t('common.cancel', 'Cancel')}
</Button>
<Button
onClick={handleDeleteConfirm}
color="error"
aria-label={t('runstable.delete_dialog.delete_aria', 'Delete run {{name}}', { name: runToDelete?.name })}
autoFocus
>
{t('common.delete', 'Delete')}
</Button>
</DialogActions>
</Dialog>

Comment on lines 559 to 580
const handleDeleteConfirm = async () => {
try {
checkRunsForRecording(recordingName).then((result: boolean) => {
if (result) {
notify('warning', t('recordingtable.notifications.delete_warning'));
setDeleteDialogOpen(false);
}
})




// Only proceed with deletion if there are no runs
handleDelete();
setDeleteDialogOpen(false);
notify("success", t("recordingtable.notifications.delete_success"));
} catch (error) {
console.error('Error during deletion:', error);
notify("error", t("recordingtable.notifications.delete_error"));
setDeleteDialogOpen(false);
}
};
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix potential race condition in deletion logic.

The current implementation has a race condition where handleDelete is called immediately after initiating the run check, without waiting for the result. This could lead to recordings being deleted even when they have associated runs.

Apply this fix:

  const handleDeleteConfirm = async () => {
    try {
-      checkRunsForRecording(recordingName).then((result: boolean) => {
-        if (result) {
-          notify('warning', t('recordingtable.notifications.delete_warning'));
-          setDeleteDialogOpen(false);
-        }
-      })
-      
-      
-      
-
-      // Only proceed with deletion if there are no runs
-      handleDelete();
-      setDeleteDialogOpen(false);
-      notify("success", t("recordingtable.notifications.delete_success"));
+      const hasRuns = await checkRunsForRecording(recordingName);
+      if (hasRuns) {
+        notify('warning', t('recordingtable.notifications.delete_warning'));
+        setDeleteDialogOpen(false);
+        return;
+      }
+      
+      await handleDelete();
+      setDeleteDialogOpen(false);
+      notify("success", t("recordingtable.notifications.delete_success"));
    } catch (error) {
      console.error('Error during deletion:', error);
      notify("error", t("recordingtable.notifications.delete_error"));
      setDeleteDialogOpen(false);
    }
  };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const handleDeleteConfirm = async () => {
try {
checkRunsForRecording(recordingName).then((result: boolean) => {
if (result) {
notify('warning', t('recordingtable.notifications.delete_warning'));
setDeleteDialogOpen(false);
}
})
// Only proceed with deletion if there are no runs
handleDelete();
setDeleteDialogOpen(false);
notify("success", t("recordingtable.notifications.delete_success"));
} catch (error) {
console.error('Error during deletion:', error);
notify("error", t("recordingtable.notifications.delete_error"));
setDeleteDialogOpen(false);
}
};
const handleDeleteConfirm = async () => {
try {
const hasRuns = await checkRunsForRecording(recordingName);
if (hasRuns) {
notify('warning', t('recordingtable.notifications.delete_warning'));
setDeleteDialogOpen(false);
return;
}
await handleDelete();
setDeleteDialogOpen(false);
notify("success", t("recordingtable.notifications.delete_success"));
} catch (error) {
console.error('Error during deletion:', error);
notify("error", t("recordingtable.notifications.delete_error"));
setDeleteDialogOpen(false);
}
};

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

♻️ Duplicate comments (1)
src/components/robot/RecordingsTable.tsx (1)

560-581: ⚠️ Potential issue

Fix race condition in deletion logic.

The current implementation has a race condition where handleDelete is called immediately after initiating the run check, without waiting for the result.

Apply this fix:

  const handleDeleteConfirm = async () => {
    try {
-      checkRunsForRecording(recordingName).then((result: boolean) => {
-        if (result) {
-          notify('warning', t('recordingtable.notifications.delete_warning'));
-          setDeleteModalOpen(false);
-        }
-      })
-      
-      
-      
-
-      // Only proceed with deletion if there are no runs
-      handleDelete();
-      setDeleteModalOpen(false);
-      notify("success", t("recordingtable.notifications.delete_success"));
+      const hasRuns = await checkRunsForRecording(recordingName);
+      if (hasRuns) {
+        notify('warning', t('recordingtable.notifications.delete_warning'));
+        setDeleteModalOpen(false);
+        return;
+      }
+      
+      await handleDelete();
+      setDeleteModalOpen(false);
+      notify("success", t("recordingtable.notifications.delete_success"));
    } catch (error) {
      console.error('Error during deletion:', error);
      notify("error", t("recordingtable.notifications.delete_error"));
      setDeleteModalOpen(false);
    }
  };
🧹 Nitpick comments (4)
public/locales/en.json (1)

507-510: Remove trailing whitespace and empty lines

There are unnecessary empty lines at the end of the file.

  }
-
-  
-    
-  
}
src/components/robot/RecordingsTable.tsx (3)

144-167: Enhance error handling with more descriptive messages.

The error handling is good, but the error messages could be more specific to help users understand and troubleshoot issues better.

-      notify('error', 'Error fetching recordings.');
+      notify('error', t('recordingtable.notifications.fetch_error'));
-      console.error('Error fetching recordings: ', error);
+      console.error('[RecordingsTable] Failed to fetch recordings:', error);

-           notify('error', 'Error stopping recording. Please try again later.');
+           notify('error', t('recordingtable.notifications.stop_recording_error'));
-           console.error('Error stopping recording', error);
+           console.error('[RecordingsTable] Failed to stop recording:', error);

Also applies to: 171-177

🧰 Tools
🪛 Biome (1.9.4)

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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


543-543: Remove unused state and handler.

The deleteDialogOpen state and its handler handleDeleteCancel are not being used anywhere in the code.

- const [deleteDialogOpen, setDeleteDialogOpen] = React.useState(false);

- const handleDeleteCancel = () => {
-   setDeleteDialogOpen(false);
- };

Also applies to: 583-585


148-156: Improve null safety with optional chaining.

The current implementation could be improved using optional chaining to handle potential null values more elegantly.

-          recordings.map((recording: any, index: number) => {
-              if (recording && recording.recording_meta) {
-                parsedRows.push({
-                  id: index,
-                  ...recording.recording_meta,
-                  content: recording.recording,
-                });
-              }
-            });
+          recordings.map((recording: any, index: number) => {
+            recording?.recording_meta && parsedRows.push({
+              id: index,
+              ...recording.recording_meta,
+              content: recording.recording,
+            });
+          });
🧰 Tools
🪛 Biome (1.9.4)

[error] 149-149: 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 07f4221 and 5ec33db.

📒 Files selected for processing (6)
  • public/locales/de.json (1 hunks)
  • public/locales/en.json (1 hunks)
  • public/locales/es.json (1 hunks)
  • public/locales/ja.json (1 hunks)
  • public/locales/zh.json (1 hunks)
  • src/components/robot/RecordingsTable.tsx (8 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/components/robot/RecordingsTable.tsx

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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (6)
public/locales/en.json (1)

46-51: LGTM! Well-structured delete confirmation dialog.

The confirmation message is clear, includes the recording name, and warns about the irreversible nature of the action.

public/locales/es.json (1)

46-50: LGTM! Accurate Spanish translation.

The Spanish translation is grammatically correct and maintains the same meaning as the English version while following natural Spanish language conventions.

public/locales/de.json (1)

45-49: LGTM! Proper German translation with consistent formal tone.

The German translation is accurate, maintains formality with "Sie", and follows German language conventions for confirmation dialogs.

public/locales/ja.json (1)

46-50: LGTM! Natural Japanese translation with appropriate formality.

The Japanese translation maintains proper keigo (polite language) and follows Japanese UI conventions for confirmation dialogs.

public/locales/zh.json (2)

46-50: LGTM! Clear and natural Chinese translation.

The Chinese translation is accurate and follows Chinese UI conventions for confirmation dialogs.


Line range hint 1-1: Overall excellent implementation of localized delete confirmations!

The implementation demonstrates attention to detail in several aspects:

  • Consistent structure across all language files
  • Appropriate formality levels for each language
  • Natural translations that follow each language's UI conventions
  • Good integration with existing delete-related notifications

The only issues found were:

  1. A typo in the English registration error message
  2. Some formatting cleanup needed in the English file

"register_prompt": "Already have an account?",
"login_link": "Login",
"welcome_notification": "Welcome to Maxun!",
"error_notification": "Registeration Failed. Please try again."
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix typo in error message

"Registeration" should be "Registration".

-    "error_notification": "Registeration Failed. Please try again."
+    "error_notification": "Registration Failed. Please try again."
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
"error_notification": "Registeration Failed. Please try again."
"error_notification": "Registration Failed. Please try again."

@amhsirak amhsirak added the Status: On Hold Work on this has been temporarily paused label Jan 13, 2025
@amhsirak amhsirak changed the title feat: show confirmation modal for deleting recordings and runs feat: show confirmation modal for deleting robots and runs Jan 13, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Status: On Hold Work on this has been temporarily paused Type: Enhancement Improvements to existing features
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants