Skip to content

feat: Add dashboard duplication feature - #1257

Closed
teeohhem wants to merge 3 commits into
mainfrom
claude/issue-1253-20251009-1437
Closed

teeohhem wants to merge 3 commits into
mainfrom
claude/issue-1253-20251009-1437

Conversation

@teeohhem

Copy link
Copy Markdown
Contributor

Add ability to duplicate dashboards from the options dropdown menu.

Closes #1253

Changes

  • Backend: Add duplicateDashboard controller function
  • Backend: Add POST /dashboards/:id/duplicate API endpoint
  • Frontend: Add useDuplicateDashboard hook
  • Frontend: Add "Duplicate Dashboard" option to menu dropdown

Generated with Claude Code

Add ability to duplicate dashboards from the options dropdown menu.
This creates a copy of the dashboard with all tiles, tags, and filters.

Changes:
- Backend: Add duplicateDashboard controller function
- Backend: Add POST /dashboards/:id/duplicate API endpoint
- Frontend: Add useDuplicateDashboard hook
- Frontend: Add "Duplicate Dashboard" option to menu dropdown

Closes #1253

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

Co-Authored-By: Tom Alexander <teeohhem@users.noreply.github.com>
@changeset-bot

changeset-bot Bot commented Oct 10, 2025 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 288c1d7

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@vercel

vercel Bot commented Oct 10, 2025 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
hyperdx-v2-oss-app Ready Ready Preview Comment Oct 10, 2025 2:30pm

@teeohhem

Copy link
Copy Markdown
Contributor Author

@claude lintiing is failing .Please run yarn run lint and fix the errors

@claude

claude Bot commented Oct 10, 2025 •

Copy link
Copy Markdown

Claude finished @teeohhem's task —— View job


Linting Issue Fixed ✓

  • Read changed files to understand the code
  • Identify linting issues
  • Fix unused import in dashboards.ts
  • Commit and push fixes

Fixed: Removed unused groupBy import from packages/api/src/routers/api/dashboards.ts:6

The linting error has been resolved and pushed to the branch.


View Job Run • Branch: claude/issue-1253-20251009-1437

@claude

claude Bot commented Oct 10, 2025

Copy link
Copy Markdown

Code Review Summary

Thank you for implementing the dashboard duplication feature! The implementation follows good patterns from the codebase, but I have identified one critical bug and several recommendations for improvement.


Critical Issue: Alert Conflicts with Duplicated Tiles

Severity: High
Location: packages/api/src/controllers/dashboard.ts:206-215

When duplicating a dashboard, the tile IDs are preserved from the original dashboard. This creates a serious problem: alerts associated with tiles in the original dashboard will conflict with alerts in the duplicated dashboard because they share the same tile IDs.

Since alerts are keyed by tileId (see packages/api/src/controllers/alerts.ts), duplicating a dashboard with alerts will cause:

  1. Alert creation to fail or overwrite existing alerts
  2. Both dashboards to share the same alerts
  3. Unexpected behavior when modifying alerts on either dashboard

Solution: Regenerate tile IDs when duplicating by mapping over tiles and creating new IDs with randomUUID() from the crypto module.


Missing Test Coverage

Location: packages/api/src/routers/api/tests/dashboard.test.ts

The PR lacks test coverage for the new duplication feature. Based on the existing test patterns, you should add:

  1. Basic duplication test - verify new dashboard with different ID and regenerated tile IDs
  2. Alert duplication test (critical) - verify both dashboards have their own alerts with different tile IDs
  3. 404 test - verify 404 when duplicating non-existent dashboard

Code Quality & Best Practices

1. Redundant Dashboard Lookup (packages/api/src/routers/api/dashboards.ts:102)

The router already fetches the dashboard to check if it exists, but duplicateDashboard fetches it again.

Recommendation: Remove the check from the router and let the controller return null instead of throwing an error. This matches the pattern used in updateDashboard (line 149-159).

2. Missing Import in Frontend

The ContactSupportText component is used but not imported in packages/app/src/DBDashboardPage.tsx:962.


Performance Considerations

The implementation is efficient and follows existing patterns:

  • Single database query to fetch original dashboard
  • Reuses createDashboard which handles alert creation
  • Proper cache invalidation in frontend

Security Analysis

Status: Secure ✅

  • Proper team-based isolation via teamId filter
  • Authentication middleware (getNonNullUserWithTeam)
  • Input validation via Zod schema (objectIdSchema)
  • User context passed for audit trail

Frontend UX Feedback

The UX flow looks good:

  • Clear menu option with copy icon
  • Success notification with navigation to new dashboard
  • Error handling with support contact info
  • Follows Mantine UI patterns

Minor suggestion: Consider adding a loading state while duplicating to provide visual feedback.


Action Items

Must Fix:

  1. ⚠️ Regenerate tile IDs in duplicateDashboard to prevent alert conflicts
  2. 📝 Add test coverage for duplication (especially alert handling)
  3. 🔧 Add missing ContactSupportText import

Should Fix:
4. Remove redundant dashboard fetch in router
5. Change error handling to return null instead of throwing (matches codebase patterns)

Nice to Have:
6. Add loading state during duplication
7. Consider adding integration test for duplicate + modify workflow


Great work overall! The architecture and patterns are solid. Once the tile ID issue is fixed and tests are added, this will be ready to merge. 🚀

Co-authored-by: Tom Alexander <teeohhem@users.noreply.github.com>
@github-actions

github-actions Bot commented Oct 10, 2025 •

Copy link
Copy Markdown
Contributor

E2E Test Results

✅ All tests passed • 25 passed • 3 skipped • 190s

Status Count
✅ Passed 25
❌ Failed 0
⚠️ Flaky 0
⏭️ Skipped 3

View full report →

@claude

claude Bot commented Oct 10, 2025

Copy link
Copy Markdown

Code Review: Dashboard Duplication Feature

Great work on implementing the dashboard duplication feature! The code is well-structured and follows the project's patterns. Here's my detailed feedback:

✅ Strengths

  1. Follows Established Patterns: The implementation properly uses the existing controller/router/hook architecture
  2. Proper Team Isolation: Correctly validates team ownership before duplication
  3. Alert Handling: Leverages createDashboard() which automatically handles alert duplication via createOrUpdateDashboardAlerts()
  4. Good UX: Clear naming convention (Copy), success/error notifications, and automatic navigation to duplicated dashboard
  5. Type Safety: Properly typed throughout with TypeScript and Zod validation
  6. Query Cache Management: Correctly invalidates React Query cache on success

🔍 Issues & Recommendations

1. Missing Test Coverage (High Priority)

The PR lacks tests for the new duplication endpoint. Based on packages/api/src/routers/api/__tests__/dashboard.test.ts, you should add tests covering:

  • Basic duplication functionality (verify name, tiles, tags, filters copied)
  • Alert duplication (verify alerts are created for duplicated dashboard)
  • 404 error handling for non-existent dashboards
  • Team isolation (ensure users cannot duplicate other teams' dashboards)

2. Redundant Dashboard Fetch (Medium Priority)

In packages/api/src/routers/api/dashboards.ts:101-105, you fetch the dashboard to check if it exists, but duplicateDashboard() also fetches it at line 194. This results in a redundant database query. Consider removing the check in the router and letting the controller handle the 404 response.

3. Tile ID Collision Risk (Low Priority)

The current implementation preserves the original tile IDs when duplicating. While tile IDs are scoped to dashboards, this could cause confusion if users expect completely independent tiles. However, since alerts are properly duplicated with new IDs via createDashboard(), this is likely acceptable. Just something to be aware of.

4. Potential Name Collision (Low Priority)

Multiple duplications result in "Dashboard Name (Copy)", "Dashboard Name (Copy) (Copy)", etc. Consider using a counter or timestamp for clearer naming, though the current approach is acceptable.

🔒 Security

✅ Properly validates team ownership - no security concerns

⚡ Performance

✅ No performance issues. Single DB query is efficient.

📝 Code Quality

  • ✅ Follows TypeScript best practices per CLAUDE.md
  • ✅ Consistent with codebase patterns
  • ✅ Good error handling
  • ✅ Proper use of Mantine UI components
  • ⚠️ Missing documentation comments (consider adding JSDoc to duplicateDashboard())

🎯 Recommendations Priority

  1. Must Have: Add test coverage
  2. Should Have: Remove redundant dashboard fetch
  3. Nice to Have: Address tile ID and name collision concerns

Great feature addition overall! 🎉

@teeohhem

Copy link
Copy Markdown
Contributor Author

@claude still one linting error

    962:61  error  Insert `{'·'}⏎·····························`  prettier/prettier
  
  ✖ 1 problem (1 error, 0 warnings)
    1 error and 0 warnings potentially fixable with the `--fix` option.
    ```
    
 Also please add test coverage and fix the tile id duplication you pointed out in the most recent code review

@claude

claude Bot commented Oct 10, 2025 •

Copy link
Copy Markdown

Claude finished @teeohhem's task —— View job


All fixes completed ✓

  • Read affected files to understand current implementation
  • Fix prettier linting error in DBDashboardPage.tsx
  • Fix tile ID duplication bug by regenerating tile IDs
  • Add comprehensive test coverage for dashboard duplication
  • Commit and push changes

Summary of Changes

1. Fixed Prettier Linting Error (packages/app/src/DBDashboardPage.tsx:962)

  • Added missing space before <ContactSupportText /> component

2. Fixed Tile ID Duplication Bug (packages/api/src/controllers/dashboard.ts:206-210)

  • Imported randomUUID from crypto module
  • Regenerate all tile IDs when duplicating dashboards to prevent alert conflicts
  • This ensures both dashboards have independent alerts with their own tile IDs

3. Added Comprehensive Test Coverage (packages/api/src/routers/api/__tests__/dashboard.test.ts:363-456)

  • Test 1: Basic duplication functionality
    • Verifies dashboard name is appended with "(Copy)"
    • Verifies tiles, tags, and filters are copied
    • Verifies dashboard and tile IDs are regenerated (not same as original)
  • Test 2: 404 error handling for non-existent dashboards
  • Test 3: Alert duplication with new tile IDs
    • Verifies alerts are created for duplicated dashboard
    • Verifies all tile IDs are unique between original and duplicated dashboards
    • Verifies alert settings (threshold values) are preserved

All changes have been committed and pushed to the branch. The CI pipeline will verify linting and run the new tests.


View Job Run • Branch: claude/issue-1253-20251009-1437

…est coverage

- Fix prettier formatting error in DBDashboardPage.tsx
- Regenerate tile IDs when duplicating dashboards to prevent alert conflicts
- Add comprehensive test coverage for dashboard duplication:
  - Test basic duplication functionality
  - Test 404 error handling for non-existent dashboards
  - Test alert duplication with new tile IDs

Co-authored-by: Tom Alexander <teeohhem@users.noreply.github.com>

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

Co-Authored-By: Claude <noreply@anthropic.com>
@claude

claude Bot commented Oct 10, 2025

Copy link
Copy Markdown

Pull Request Review: Dashboard Duplication Feature

Great work on implementing the dashboard duplication feature! The implementation is solid and follows the codebase patterns well. Here's my detailed feedback:


✅ Strengths

  1. Excellent test coverage - Comprehensive tests covering:

    • Basic duplication
    • Alert preservation and regeneration
    • Error handling (404 cases)
    • Tile ID regeneration verification
  2. Proper alert handling - Regenerating tile IDs prevents alert conflicts, which is critical for the system's integrity

  3. Consistent with codebase patterns - Follows existing controller/router/hook patterns established in the codebase

  4. Good UX - Clear success/error notifications and automatic navigation to the duplicated dashboard


🐛 Potential Issues

Critical: Race Condition in Alert Creation

// packages/api/src/controllers/dashboard.ts:212-222
const newDashboard = await createDashboard(
  teamId,
  {
    name: `${dashboardData.name} (Copy)`,
    tiles: tilesWithNewIds,
    tags: dashboardData.tags,
    filters: dashboardData.filters,
  },
  userId,
);

Issue: The createDashboard function calls createOrUpdateDashboardAlerts internally (line 130-135), which will attempt to create alerts for tiles with alert configurations. However, when duplicating a dashboard, the alert data is embedded in tile.config.alert, which may contain MongoDB ObjectId references or document instances from the original dashboard.

Potential Problem: If the alert objects contain _id fields from the original dashboard, this could cause:

  1. Alert ID conflicts
  2. Incorrect alert-tile associations
  3. Potential validation errors

Recommendation: Strip alert metadata before duplication:

const tilesWithNewIds = dashboardData.tiles.map(tile => {
  const newTile = {
    ...tile,
    id: randomUUID(),
  };
  
  // If tile has alert config, strip metadata fields
  if (newTile.config?.alert) {
    const { _id, createdAt, updatedAt, ...alertData } = newTile.config.alert;
    newTile.config.alert = alertData;
  }
  
  return newTile;
});

Missing Field: Query from getDashboard

// packages/api/src/controllers/dashboard.ts:195-202
const originalDashboard = await Dashboard.findOne({
  _id: dashboardId,
  team: teamId,
});

Issue: You're using Dashboard.findOne directly, but other parts of the code use getDashboard which merges alert data into tiles. This inconsistency could cause:

  1. Alert data not being properly included in duplication
  2. Different behavior compared to other dashboard operations

Recommendation: Use getDashboard for consistency:

export async function duplicateDashboard(
  dashboardId: string,
  teamId: ObjectId,
  userId?: ObjectId,
) {
  const originalDashboard = await getDashboard(dashboardId, teamId);

  if (originalDashboard == null) {
    throw new Error('Dashboard not found');
  }

  // Rest of the implementation...
}

🔒 Security Considerations

  1. ✅ Team isolation is properly enforced - All queries include team filtering
  2. ✅ Authentication middleware is in place via getNonNullUserWithTeam(req)
  3. ✅ Input validation using Zod schemas for route parameters

🎯 Performance Considerations

  1. Minor optimization opportunity: The duplicate operation could be wrapped in a transaction if using MongoDB transactions to ensure atomicity between dashboard creation and alert creation

  2. Frontend navigation: The immediate router.push after success is good UX and prevents stale data issues


🧪 Test Coverage Assessment

Strong test coverage with these scenarios:

  • ✅ Basic duplication
  • ✅ Non-existent dashboard (404)
  • ✅ Tile ID regeneration verification
  • ✅ Alert duplication with new tile IDs
  • ✅ Alert settings preservation

Consider adding:

  • Test for duplicating dashboards with no alerts (edge case)
  • Test for dashboards with empty tiles array
  • Test for very long dashboard names (potential truncation issues)

📝 Code Quality & Style

  1. ✅ Follows TypeScript best practices - Proper typing, no any usage
  2. ✅ Consistent with CLAUDE.md guidelines - Uses Mantine UI, follows controller patterns
  3. ✅ Clear naming conventions - Function and variable names are descriptive
  4. ✅ Proper error handling - Returns 404 for missing dashboards

Minor style note: Consider extracting the tile ID regeneration logic into a helper function for reusability:

function regenerateTileIds(tiles: Tile[]): Tile[] {
  return tiles.map(tile => ({
    ...tile,
    id: randomUUID(),
  }));
}

🎨 Frontend Implementation

Good practices:

  • ✅ Uses TanStack Query for server state management
  • ✅ Proper mutation callbacks (onSuccess/onError)
  • ✅ Query invalidation after success
  • ✅ User-friendly notifications
  • ✅ Uses Mantine components (Menu, notifications)

Suggestion: Consider adding loading state during duplication:

<Menu.Item
  leftSection={<i className="bi bi-copy" />}
  disabled={duplicateDashboard.isPending}
  onClick={/* ... */}
>
  {duplicateDashboard.isPending ? 'Duplicating...' : 'Duplicate Dashboard'}
</Menu.Item>

🚀 Recommendations Summary

Must fix:

  1. Use getDashboard instead of Dashboard.findOne for consistency
  2. Strip alert metadata fields to prevent ID conflicts

Should consider:

  1. Add loading state indicator in the UI
  2. Extract tile ID regeneration into a helper function
  3. Add edge case tests (empty tiles, no alerts)

Nice to have:

  1. Transaction support for atomicity
  2. Test for long dashboard names

📊 Overall Assessment

Rating: 8.5/10

This is a well-implemented feature with excellent test coverage and proper adherence to the codebase patterns. The main concerns are around potential alert metadata conflicts and consistency in using the getDashboard helper. Once those are addressed, this will be production-ready.

The feature successfully addresses issue #1253 and provides a valuable enhancement to the dashboard management capabilities. Great job! 🎉

This branch was successfully deployed

1 active deployment
Preview — 288c1d79 Deployed Oct 10, 2025 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Duplicate Dashboards

1 participant