Skip to content

Run page links to tasks & replay run modal improvements #1364

New issue

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

By clicking “No 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? No Sign in to your account

Merged
merged 20 commits into from
Sep 27, 2024

Conversation

samejr
Copy link
Member

@samejr samejr commented Sep 26, 2024

The run inspector now has links to the parent and root tasks
CleanShot 2024-09-26 at 14 08 15@2x

Batchtrigger() spans now display the triggered runs in a table in the inspector
CleanShot 2024-09-26 at 14 08 03@2x

A more subtle "Root" badge
CleanShot 2024-09-26 at 14 10 43@2x

Added a description to the Replay modal panel
CleanShot 2024-09-26 at 14 03 58@2x

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new "extra-small" variant for badges, enhancing component flexibility.
    • Added a new custom hook, useReplaceSearchParams, for managing URL search parameters.
    • Enhanced display of triggered runs with a structured table format in the UI.
    • Added a new Story component for rendering static and sticky header tables.
  • Improvements

    • Streamlined logging output for function calls, improving clarity.
    • Updated UI components for better alignment and spacing, including modifications to the ReplayRunDialog and TaskRunsTable.
    • Added new relationships in data structures for SpanPresenter and RunPresenter, enhancing the information available.
  • Bug Fixes

    • Removed unnecessary email reply parsing functionality to simplify email handling.
  • Chores

    • Added indices to the database schema for optimized query performance.

Copy link

changeset-bot bot commented Sep 26, 2024

🦋 Changeset detected

Latest commit: 50d5680

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 4 packages
Name Type
@trigger.dev/sdk Patch
@trigger.dev/build Patch
@trigger.dev/core Patch
trigger.dev Patch

Not sure what this means? Click here to learn what changesets are.

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

Copy link
Contributor

coderabbitai bot commented Sep 26, 2024

Walkthrough

The changes encompass various updates across multiple components and files, primarily focusing on logging behavior, user interface enhancements, and the introduction of new hooks and properties. Key modifications include the removal of accessory attributes from logging in the trigger functions, the addition of a new "extra-small" badge variant, and the introduction of a new hook for managing search parameters. Additionally, there are updates to data structures in presenters and the database schema to improve the handling of task runs and spans.

Changes

File Path Change Summary
.changeset/three-olives-love.md Summary of changes including logging behavior adjustments and the addition of a new badge variant.
apps/webapp/app/components/primitives/Badge.tsx Added "extra-small" variant to the Badge component.
apps/webapp/app/components/primitives/Table.tsx Modified class names and styles for table elements, added rowHoverStyle prop to TableCell.
apps/webapp/app/components/runs/v3/ReplayRunDialog.tsx Modified dialog layout, added new imports, and adjusted styling for components.
apps/webapp/app/components/runs/v3/TaskRunsTable.tsx Changed header label and enhanced task identifier display with a conditional badge.
apps/webapp/app/hooks/useReplaceLocation.ts Removed the useReplaceLocation hook.
apps/webapp/app/hooks/useReplaceSearchParams.ts Introduced a new hook for managing search parameters.
apps/webapp/app/presenters/v3/RunListPresenter.server.ts Added rootTaskRunId property to the data structure returned by the presenter.
apps/webapp/app/presenters/v3/RunPresenter.server.ts Enhanced RunPresenter to include new fields for rootTaskRun.
apps/webapp/app/presenters/v3/SpanPresenter.server.ts Expanded relationships in the SpanPresenter to include rootTaskRun and parentTaskRun.
apps/webapp/app/routes/.../route.tsx Updated handling of search parameters, integrated new hooks, and adjusted component props for better data management.
packages/database/prisma/migrations/.../migration.sql Created an index on the parentSpanId column in the TaskRun table.
packages/database/prisma/schema.prisma Added an index on the parentSpanId field in the TaskRun model.
references/v3-catalog/src/trigger/email.tsx Removed the parseEmailReplyTask function.
references/v3-catalog/src/trigger/taskHierarchy.ts Modified the invocation of batchTrigger to send two identical payloads instead of one.

Possibly related PRs

  • feat: Run metadata #1357: This PR introduces the ability to attach metadata to task runs, which is directly related to the changes in the main PR that modifies logging behavior and payload structures in the trigger and batchTrigger functions.

Suggested reviewers

  • ericallam

🐰 In the meadow where the changes bloom,
A badge grows small, dispelling gloom.
Logs now shine with clarity bright,
As tasks take flight in the soft moonlight.
With hooks anew and spans in view,
The code hops forward, fresh and true! 🌼


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 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
Contributor

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

🧹 Outside diff range and nitpick comments (9)
packages/database/prisma/migrations/20240926110455_add_parent_span_id_index_to_the_task_run_table/migration.sql (1)

1-2: LGTM! Consider the following points for optimal performance.

The addition of this index on the parentSpanId column of the TaskRun table is a good optimization step. The use of CONCURRENTLY and IF NOT EXISTS demonstrates thoughtful consideration for production environments and idempotent migrations.

While this change is approved, please consider the following points to ensure optimal performance:

  1. Evaluate the impact on write performance, especially if there are frequent inserts or updates to the TaskRun table.
  2. Monitor the size of the index and its impact on database storage.
  3. Analyze query patterns to confirm that this index will indeed be beneficial for your most common queries.
  4. Consider implementing a monitoring strategy to track the usage and effectiveness of this index over time.

These considerations will help ensure that the index provides the intended performance benefits without introducing unexpected issues.

.changeset/three-olives-love.md (1)

1-5: LGTM! Consider adding more context about the impact.

The changeset file is correctly formatted and provides a clear description of the change. This update aligns well with the PR objectives of improving the run inspector and enhancing the overall user experience.

Consider adding a brief note about how this change impacts the user experience. For example:

 ---
 "@trigger.dev/sdk": patch
 ---
 
-Removed the inline-code accessory from the logs when calling trigger or batchTrigger from a run
+Removed the inline-code accessory from the logs when calling trigger or batchTrigger from a run.
+This change simplifies the log output, making it easier for users to read and understand the execution flow.
apps/webapp/app/hooks/useReplaceSearchParams.ts (1)

4-22: Consider adding TypeScript types for improved type safety.

To enhance type safety and improve developer experience, consider adding explicit return type for the hook and type for the replaceSearchParam function:

import { URLSearchParams } from 'url';

type ReplaceSearchParamFunction = (key: string, value?: string) => void;

export function useReplaceSearchParams(): {
  searchParams: URLSearchParams;
  setSearchParams: React.Dispatch<React.SetStateAction<URLSearchParams>>;
  replaceSearchParam: ReplaceSearchParamFunction;
} {
  // ... existing implementation ...
}

This addition will provide better type inference and catch potential type-related errors early in the development process.

apps/webapp/app/presenters/v3/RunPresenter.server.ts (1)

152-152: LGTM: Consistent inclusion of rootTaskRun, with a refactoring suggestion

The addition of rootTaskRun to the returned run object here is consistent with the earlier change and ensures the data is included in all code paths. This supports the PR's objective of enhancing task hierarchy navigation.

Consider refactoring the method to have a single return statement or a common object construction for the run data. This could improve maintainability by reducing duplication and ensuring consistency across different code paths.

apps/webapp/app/components/runs/v3/ReplayRunDialog.tsx (1)

153-166: LGTM: Improved button layout and styling.

The changes to the button layout and styling enhance the form's usability and visual appeal:

  • Addition of a Cancel button improves user control.
  • Smaller button variants create a more compact look.
  • Justified layout improves visual balance.

Consider adding an aria-label to the Cancel button to improve accessibility:

- <Button variant="tertiary/small">Cancel</Button>
+ <Button variant="tertiary/small" aria-label="Cancel replay">Cancel</Button>
apps/webapp/app/presenters/v3/RunListPresenter.server.ts (1)

Line range hint 171-341: Overall implementation of rootTaskRunId looks good. Consider adding documentation.

The addition of rootTaskRunId to the RunListPresenter is well-implemented and consistent across the return type, SQL query, and mapping function. This change aligns with the PR objectives and will enable better navigation within the task hierarchy.

Consider adding a brief comment explaining the purpose of rootTaskRunId in the context of task hierarchy navigation. This would improve code maintainability and help future developers understand the significance of this field.

apps/webapp/app/components/runs/v3/TaskRunsTable.tsx (1)

282-287: LGTM: Enhanced task identifier display with root task indication

The changes to the task identifier cell are well-implemented:

  1. The flex layout ensures proper alignment of the identifier and badge.
  2. The conditional rendering of the "Root" badge provides valuable information at a glance.
  3. Using the "extra-small" variant for the badge is a good choice for space efficiency.

Consider adding an aria-label to the badge for improved accessibility. For example:

-    {run.rootTaskRunId === null ? <Badge variant="extra-small">Root</Badge> : null}
+    {run.rootTaskRunId === null ? <Badge variant="extra-small" aria-label="Root task">Root</Badge> : null}

This change will help screen readers provide more context about the badge's purpose.

apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.v3.$projectParam.runs.electric.$runParam/route.tsx (1)

Line range hint 1-1148: Consider refactoring for improved maintainability

While the changes made are improvements, it's worth noting that this file is quite large and complex. Consider breaking it down into smaller, more manageable components or modules. This could improve readability, maintainability, and make future changes easier to implement and review.

Some suggestions:

  1. Extract the TasksTreeView and TimelineView into separate files.
  2. Consider creating a separate file for utility functions and hooks used in this component.
  3. If possible, split the main Page component into smaller, more focused components.
apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.v3.$projectParam.runs.$runParam/route.tsx (1)

258-258: Simplify nullish coalescing operator

The searchParams.get("span") method returns string | null, so using ?? undefined is redundant. Consider simplifying the assignment.

Apply this diff to simplify the code:

-      const selectedSpanId = searchParams.get("span") ?? undefined;
+      const selectedSpanId = searchParams.get("span");
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between a0c7592 and 3953e8b.

📒 Files selected for processing (17)
  • .changeset/three-olives-love.md (1 hunks)
  • apps/webapp/app/components/primitives/Badge.tsx (1 hunks)
  • apps/webapp/app/components/runs/v3/ReplayRunDialog.tsx (6 hunks)
  • apps/webapp/app/components/runs/v3/TaskRunsTable.tsx (3 hunks)
  • apps/webapp/app/hooks/useReplaceLocation.ts (0 hunks)
  • apps/webapp/app/hooks/useReplaceSearchParams.ts (1 hunks)
  • apps/webapp/app/presenters/v3/RunListPresenter.server.ts (3 hunks)
  • apps/webapp/app/presenters/v3/RunPresenter.server.ts (3 hunks)
  • apps/webapp/app/presenters/v3/SpanPresenter.server.ts (3 hunks)
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.v3.$projectParam.runs.$runParam/route.tsx (12 hunks)
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.v3.$projectParam.runs.electric.$runParam/route.tsx (3 hunks)
  • apps/webapp/app/routes/resources.orgs.$organizationSlug.projects.v3.$projectParam.runs.$runParam.spans.$spanParam/route.tsx (6 hunks)
  • packages/database/prisma/migrations/20240926110455_add_parent_span_id_index_to_the_task_run_table/migration.sql (1 hunks)
  • packages/database/prisma/schema.prisma (1 hunks)
  • packages/trigger-sdk/src/v3/shared.ts (0 hunks)
  • references/v3-catalog/src/trigger/email.tsx (0 hunks)
  • references/v3-catalog/src/trigger/taskHierarchy.ts (1 hunks)
💤 Files not reviewed due to no reviewable changes (3)
  • apps/webapp/app/hooks/useReplaceLocation.ts
  • packages/trigger-sdk/src/v3/shared.ts
  • references/v3-catalog/src/trigger/email.tsx
🔇 Additional comments (23)
apps/webapp/app/hooks/useReplaceSearchParams.ts (1)

1-2: LGTM: Imports are correctly defined and used.

The necessary hooks and functions are imported from the appropriate libraries.

references/v3-catalog/src/trigger/taskHierarchy.ts (1)

20-23: Verify the intent of doubling the payload in batchTrigger call.

The change in the batchTrigger call now sends two identical payload objects instead of one. This modification raises several concerns:

  1. Inconsistency: This change is not reflected in other similar batchTrigger calls within the file (e.g., in childTask and grandChildTask).
  2. Functionality: This alteration could potentially double the number of child tasks triggered.
  3. Performance: If unintended, this change might lead to unnecessary resource usage.

Could you please clarify if this change is intentional? If not, consider reverting to the previous implementation:

-        await childTask.batchTrigger([
-          { payload: { useWaits, useBatch } },
-          { payload: { useWaits, useBatch } },
-        ]);
+        await childTask.batchTrigger([{ payload: { useWaits, useBatch } }]);

If the change is intentional, please provide context on why it's only applied to this specific batchTrigger call and not to others in the file. Additionally, consider updating the other batchTrigger calls for consistency if this new behavior is desired throughout the task hierarchy.

apps/webapp/app/presenters/v3/RunPresenter.server.ts (3)

40-46: LGTM: Addition of rootTaskRun aligns with PR objectives

The inclusion of the rootTaskRun property with selected fields (friendlyId, taskIdentifier, spanId) enhances the data structure to support improved navigation within the task hierarchy. This change directly contributes to the PR's goal of adding links to parent and root tasks in the run inspector.


90-90: LGTM: Consistent inclusion of rootTaskRun in the output

The addition of rootTaskRun to the returned run object ensures that the newly queried data is properly included in the presenter's output. This change is consistent with the earlier modification and supports the PR's objective of enhancing task hierarchy navigation.


Line range hint 1-172: Summary: Changes successfully implement rootTaskRun support

The modifications to RunPresenter.server.ts consistently implement support for rootTaskRun data, aligning well with the PR objectives to enhance navigation within the task hierarchy. The changes are well-integrated and don't introduce any apparent issues.

A minor suggestion for improvement would be to consider refactoring the method to reduce duplication in the run object construction, which could enhance maintainability.

Overall, the implementation effectively supports the new feature of linking to parent and root tasks in the run inspector.

apps/webapp/app/components/runs/v3/ReplayRunDialog.tsx (6)

1-1: LGTM: New imports added for UI enhancements.

The new imports for DialogClose and Paragraph are correctly added and align with the UI changes in the component.

Also applies to: 12-12


24-24: LGTM: DialogContent max-width adjusted for better UI.

The max-width change from md:max-w-3xl to md:max-w-xl makes the dialog more compact, which aligns with the PR objectives of improving the Replay modal panel.


100-103: LGTM: Informative description added to Replay modal.

The new Paragraph component adds valuable context about the replay functionality, enhancing user understanding. This aligns well with the PR objective of improving the Replay modal panel with a description.


105-105: LGTM: Improved JSON editor container layout.

Adding a minimum height (min-h-40) to the JSON editor container ensures a reasonable viewing area, enhancing the user experience when editing payloads.


132-133: LGTM: Select component styling refined.

The Select component's variant change to tertiary/small and padding adjustment to pl-1 create a more compact and refined look, consistent with the UI improvements outlined in the PR objectives.


Line range hint 1-166: Summary: Excellent improvements to the ReplayRunDialog component.

The changes in this file significantly enhance the ReplayRunDialog component, aligning perfectly with the PR objectives:

  1. The dialog's layout and styling have been refined for a more compact and modern look.
  2. An informative description has been added to provide context about the replay functionality.
  3. The JSON editor's container has been improved for better usability.
  4. Button layout and styling have been updated for improved user interaction.

These changes collectively contribute to a more intuitive and user-friendly interface for replaying runs. Great work on improving the overall user experience!

apps/webapp/app/presenters/v3/RunListPresenter.server.ts (3)

171-171: LGTM: Addition of rootTaskRunId to the return type.

The addition of rootTaskRunId: string | null to the return type is consistent with the PR objectives and correctly allows for null values. This change will enable better navigation within the task hierarchy.


196-196: LGTM: Addition of rootTaskRunId to the SQL query.

The SQL query has been correctly updated to select the rootTaskRunId from the TaskRun table. The alias used matches the property name in the return type, ensuring consistency in the data structure.


341-341: LGTM: Addition of rootTaskRunId to the returned object.

The rootTaskRunId is correctly added to the returned object in the mapping function. The property name is consistent with the return type and SQL query, and the value is appropriately passed through without transformation.

apps/webapp/app/components/runs/v3/TaskRunsTable.tsx (2)

44-44: LGTM: New import for Badge component

The addition of the Badge import is appropriate for the new functionality being introduced. It follows good practices by using a relative import path for internal components.


127-127: LGTM: Improved table header label

Changing the header from "Task ID" to "Task" is a good improvement. It's more concise and better represents the column's content, which now includes both the task identifier and potentially a "Root" badge.

apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.v3.$projectParam.runs.electric.$runParam/route.tsx (3)

67-67: LGTM: Improved URL parameter handling

The switch from useReplaceLocation to useReplaceSearchParams is a good change. It provides more specific and efficient handling of search parameters in the URL.


1148-1148: LGTM: Improved spacing for Callout component

The addition of the "mt-2" class to the Callout component is a good styling improvement. It adds a top margin, which will help visually separate the Callout from the content above it, enhancing the overall layout.


263-264: LGTM: Simplified search parameter handling

The use of useReplaceSearchParams and direct access to searchParams simplifies the code and makes it more maintainable. This is a good improvement.

Please verify that this change doesn't affect any other parts of the application that might have depended on the previous getSpanId function. Run the following script to check for any remaining usage of getSpanId:

✅ Verification successful

Verified: No residual usage of getSpanId detected

All usages of getSpanId have been successfully removed from the codebase, ensuring that the refactoring does not impact other parts of the application.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining usage of getSpanId function
rg "getSpanId\(" --type typescript --type tsx

Length of output: 82


Script:

#!/bin/bash
# Search for any remaining usage of getSpanId function in .ts and .tsx files
rg "getSpanId\(" -g "*.ts" -g "*.tsx"

Length of output: 39

packages/database/prisma/schema.prisma (1)

1785-1785: Approved: Index addition will improve query performance

The addition of an index on the parentSpanId field in the TaskRun model is a good optimization. This will likely improve the performance of queries that filter, sort, or join on the parentSpanId, which can be particularly beneficial when dealing with hierarchical task structures or analyzing task relationships.

Consider the following implications:

  1. Positive: Faster read operations involving the parentSpanId.
  2. Negative: Slightly increased storage requirements and potentially slower write operations due to index maintenance.

Given that this is the only change in a large schema file, it appears to be a targeted performance optimization. Ensure that this change aligns with your application's query patterns and performance requirements.

apps/webapp/app/presenters/v3/SpanPresenter.server.ts (2)

135-149: LGTM: Relationships rootTaskRun and parentTaskRun added to the query selection.

The inclusion of rootTaskRun and parentTaskRun in the select clause is appropriate for retrieving necessary related data.


299-307: LGTM: Relationships object correctly constructed with root and parent.

The relationships object is properly assembled, handling optional rootTaskRun and parentTaskRun, and accurately determining if the root is also the parent via the isParent flag.

apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.v3.$projectParam.runs.$runParam/route.tsx (1)

965-973: Ensure consistent type definitions in ShowParentLink

The ShowParentLink function signature correctly includes runFriendlyId, spanId, and isRoot. Ensure that spanId being optional is handled appropriately throughout the component to prevent potential undefined errors.

Comment on lines +4 to +22
export function useReplaceSearchParams() {
const [searchParams, setSearchParams] = useSearchParams();

const replaceSearchParam = useCallback(
(key: string, value?: string) => {
setSearchParams((s) => {
if (value) {
s.set(key, value);
} else {
s.delete(key);
}
return s;
});
},
[searchParams]
);

return { searchParams, setSearchParams, replaceSearchParam };
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

LGTM: Well-implemented custom hook with a minor optimization suggestion.

The useReplaceSearchParams hook is well-implemented, providing a clean API for managing search parameters. The use of useCallback for memoization is a good practice. However, there's a minor optimization that can be made:

Consider removing searchParams from the useCallback dependency array:

  const replaceSearchParam = useCallback(
    (key: string, value?: string) => {
      setSearchParams((s) => {
        if (value) {
          s.set(key, value);
        } else {
          s.delete(key);
        }
        return s;
      });
    },
-   [searchParams]
+   [setSearchParams]
  );

This change is safe because setSearchParams always provides the most up-to-date searchParams object, and removing searchParams from the dependency array can prevent unnecessary re-renders.

📝 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
export function useReplaceSearchParams() {
const [searchParams, setSearchParams] = useSearchParams();
const replaceSearchParam = useCallback(
(key: string, value?: string) => {
setSearchParams((s) => {
if (value) {
s.set(key, value);
} else {
s.delete(key);
}
return s;
});
},
[searchParams]
);
return { searchParams, setSearchParams, replaceSearchParam };
}
export function useReplaceSearchParams() {
const [searchParams, setSearchParams] = useSearchParams();
const replaceSearchParam = useCallback(
(key: string, value?: string) => {
setSearchParams((s) => {
if (value) {
s.set(key, value);
} else {
s.delete(key);
}
return s;
});
},
[setSearchParams]
);
return { searchParams, setSearchParams, replaceSearchParam };
}

Comment on lines +333 to +350
const triggeredRuns = await this._replica.taskRun.findMany({
select: {
friendlyId: true,
taskIdentifier: true,
spanId: true,
createdAt: true,
number: true,
lockedToVersion: {
select: {
version: true,
},
},
},
where: {
parentSpanId: spanId,
},
});

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Potential performance issue: Consider implementing pagination or limiting the results for triggeredRuns.

Fetching all triggeredRuns without a limit might lead to performance issues if there are many triggered runs associated with a span. To prevent potential delays or excessive memory usage, it's advisable to implement pagination or set a reasonable limit on the number of results returned.

Apply this diff to add a limit to the query:

        const triggeredRuns = await this._replica.taskRun.findMany({
          select: {
            friendlyId: true,
            taskIdentifier: true,
            spanId: true,
            createdAt: true,
            number: true,
            lockedToVersion: {
              select: {
                version: true,
              },
            },
          },
          where: {
            parentSpanId: spanId,
          },
+         take: 100, // Limit the results to 100
        });

Alternatively, consider adding pagination parameters to the query to allow clients to request specific ranges of results.

📝 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 triggeredRuns = await this._replica.taskRun.findMany({
select: {
friendlyId: true,
taskIdentifier: true,
spanId: true,
createdAt: true,
number: true,
lockedToVersion: {
select: {
version: true,
},
},
},
where: {
parentSpanId: spanId,
},
});
const triggeredRuns = await this._replica.taskRun.findMany({
select: {
friendlyId: true,
taskIdentifier: true,
spanId: true,
createdAt: true,
number: true,
lockedToVersion: {
select: {
version: true,
},
},
},
where: {
parentSpanId: spanId,
},
take: 100, // Limit the results to 100
});

Comment on lines 323 to 358
<Table className="w-full">
<TableHeader>
<TableRow>
<TableHeaderCell>Run #</TableHeaderCell>
<TableHeaderCell>Task</TableHeaderCell>
<TableHeaderCell>Version</TableHeaderCell>
<TableHeaderCell>Created at</TableHeaderCell>
</TableRow>
</TableHeader>
<TableBody>
{span.triggeredRuns.map((run) => {
const path = v3RunSpanPath(
organization,
project,
{ friendlyId: run.friendlyId },
{ spanId: run.spanId }
);
return (
<TableRow key={run.friendlyId}>
<TableCell to={path} actionClassName="py-1.5">
{run.number}
</TableCell>
<TableCell to={path} actionClassName="py-1.5">
{run.taskIdentifier}
</TableCell>
<TableCell to={path} actionClassName="py-1.5">
{run.lockedToVersion?.version ?? "–"}
</TableCell>
<TableCell to={path} actionClassName="py-1.5">
<DateTime date={run.createdAt} />
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider using TaskRunsTable component for consistency and code reuse

You've manually created a table to display the triggered runs. Since there is an existing TaskRunsTable component, consider using it to maintain consistency across the application and reduce code duplication.

Comment on lines +494 to +561
<Property.Item>
<Property.Label>Root & Parent</Property.Label>
<Property.Value>
<TextLink
to={v3RunSpanPath(
organization,
project,
{
friendlyId: run.relationships.root.friendlyId,
},
{ spanId: run.relationships.root.spanId }
)}
className="group flex flex-wrap items-center gap-x-1 gap-y-0"
>
{run.relationships.root.taskIdentifier}
<span className="break-all text-text-dimmed transition-colors group-hover:text-text-bright/80">
({run.relationships.root.friendlyId})
</span>
</TextLink>
</Property.Value>
</Property.Item>
) : (
<>
<Property.Item>
<Property.Label>Root</Property.Label>
<Property.Value>
<TextLink
to={v3RunSpanPath(
organization,
project,
{
friendlyId: run.relationships.root.friendlyId,
},
{ spanId: run.relationships.root.spanId }
)}
className="group flex flex-wrap items-center gap-x-1 gap-y-0"
>
{run.relationships.root.taskIdentifier}
<span className="break-all text-text-dimmed transition-colors group-hover:text-text-bright/80">
({run.relationships.root.friendlyId})
</span>
</TextLink>
</Property.Value>
</Property.Item>
{run.relationships.parent ? (
<Property.Item>
<Property.Label>Parent</Property.Label>
<Property.Value>
<TextLink
to={v3RunSpanPath(
organization,
project,
{
friendlyId: run.relationships.parent.friendlyId,
},
{ spanId: run.relationships.parent.spanId }
)}
className="group flex flex-wrap items-center gap-x-1 gap-y-0"
>
{run.relationships.parent.taskIdentifier}
<span className="break-all text-text-dimmed transition-colors group-hover:text-text-bright/80">
({run.relationships.parent.friendlyId})
</span>
</TextLink>
</Property.Value>
</Property.Item>
) : null}
</>
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Refactor duplicated code for rendering root and parent links

The code for rendering the root and parent links is duplicated. To enhance maintainability and reduce redundancy, consider extracting the repeated code into a reusable component or function.

Here's an example of how you might refactor the code:

function RelationshipLink({ label, relationship }) {
  return (
    <Property.Item>
      <Property.Label>{label}</Property.Label>
      <Property.Value>
        <TextLink
          to={v3RunSpanPath(
            organization,
            project,
            { friendlyId: relationship.friendlyId },
            { spanId: relationship.spanId }
          )}
          className="group flex flex-wrap items-center gap-x-1 gap-y-0"
        >
          {relationship.taskIdentifier}
          <span className="break-all text-text-dimmed transition-colors group-hover:text-text-bright/80">
            ({relationship.friendlyId})
          </span>
        </TextLink>
      </Property.Value>
    </Property.Item>
  );
}

Then you can use it like this:

{run.relationships.root && (
  run.relationships.root.isParent ? (
    <RelationshipLink label="Root & Parent" relationship={run.relationships.root} />
  ) : (
    <>
      <RelationshipLink label="Root" relationship={run.relationships.root} />
      {run.relationships.parent && (
        <RelationshipLink label="Parent" relationship={run.relationships.parent} />
      )}
    </>
  )
)}

Comment on lines +522 to +529
{rootRun ? (
<ShowParentLink
runFriendlyId={rootRun.friendlyId}
isRoot={true}
spanId={rootRun.spanId}
/>
) : parentRunFriendlyId ? (
<ShowParentLink runFriendlyId={parentRunFriendlyId} isRoot={false} />
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Simplify nested ternary operator for better readability

The nested ternary operator in this JSX block reduces readability and can be difficult to maintain. Consider refactoring it into a more readable format using an if-else statement or a self-invoking function.

Apply this diff to refactor the conditional rendering:

-                  {rootRun ? (
-                    <ShowParentLink
-                      runFriendlyId={rootRun.friendlyId}
-                      isRoot={true}
-                      spanId={rootRun.spanId}
-                    />
-                  ) : parentRunFriendlyId ? (
-                    <ShowParentLink runFriendlyId={parentRunFriendlyId} isRoot={false} />
-                  ) : (
-                    <Paragraph variant="small" className="flex-1 text-charcoal-500">
-                      This is the root task
-                    </Paragraph>
-                  )}
+                  {(() => {
+                    if (rootRun) {
+                      return (
+                        <ShowParentLink
+                          runFriendlyId={rootRun.friendlyId}
+                          isRoot={true}
+                          spanId={rootRun.spanId}
+                        />
+                      );
+                    } else if (parentRunFriendlyId) {
+                      return (
+                        <ShowParentLink runFriendlyId={parentRunFriendlyId} isRoot={false} />
+                      );
+                    } else {
+                      return (
+                        <Paragraph variant="small" className="flex-1 text-charcoal-500">
+                          This is the root task
+                        </Paragraph>
+                      );
+                    }
+                  })()}
📝 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
{rootRun ? (
<ShowParentLink
runFriendlyId={rootRun.friendlyId}
isRoot={true}
spanId={rootRun.spanId}
/>
) : parentRunFriendlyId ? (
<ShowParentLink runFriendlyId={parentRunFriendlyId} isRoot={false} />
{(() => {
if (rootRun) {
return (
<ShowParentLink
runFriendlyId={rootRun.friendlyId}
isRoot={true}
spanId={rootRun.spanId}
/>
);
} else if (parentRunFriendlyId) {
return (
<ShowParentLink runFriendlyId={parentRunFriendlyId} isRoot={false} />
);
} else {
return (
<Paragraph variant="small" className="flex-1 text-charcoal-500">
This is the root task
</Paragraph>
);
}
})()}

Copy link

pkg-pr-new bot commented Sep 26, 2024

pnpm add https://pkg.pr.new/triggerdotdev/trigger.dev/@trigger.dev/build@1364
pnpm add https://pkg.pr.new/triggerdotdev/trigger.dev@1364
pnpm add https://pkg.pr.new/triggerdotdev/trigger.dev/@trigger.dev/core@1364
pnpm add https://pkg.pr.new/triggerdotdev/trigger.dev/@trigger.dev/sdk@1364

commit: 50d5680

Copy link
Member

@matt-aitken matt-aitken left a comment

Choose a reason for hiding this comment

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

Other than making the table scrolling nicer, this is great 👍

Copy link
Contributor

@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 and nitpick comments (4)
apps/webapp/app/routes/storybook.table/route.tsx (3)

20-37: LGTM: Static table implementation is correct and efficient.

The static table is well-structured and uses the Table components correctly. The use of Array.from() to generate rows is an efficient approach.

Consider adding an aria-label to the <Table> component for improved accessibility. For example:

- <Table>
+ <Table aria-label="Static table example">

44-61: LGTM: Sticky header table implementation is correct and consistent.

The sticky header table is well-implemented, using the containerClassName prop to enable scrolling when the content exceeds the max-height. The structure is consistent with the static table, which is good for maintainability.

For consistency with the previous suggestion, consider adding an aria-label to this <Table> component as well:

- <Table containerClassName="max-h-[11.5rem]">
+ <Table containerClassName="max-h-[11.5rem]" aria-label="Sticky header table example">

13-65: LGTM: Overall component structure is well-organized.

The Story component has a clean layout structure using flexbox, with appropriate spacing and organization. The use of semantic headers and explanatory paragraphs provides good context for each table example.

The component name "Story" might be a bit ambiguous without context. Consider renaming it to something more descriptive of its purpose, such as TableExamples or TableStorybook. Alternatively, add a comment explaining the purpose of this component in the context of Storybook:

+// This component showcases different table variants for Storybook documentation
 export default function Story() {
   // ...
 }
apps/webapp/app/routes/storybook/route.tsx (1)

91-94: LGTM! Consider using a plural form for the slug.

The addition of the "Tables" story entry is consistent with the existing structure and maintains the alphabetical order within the stories array.

For consistency with other entries, consider using the plural form "tables" for the slug:

 {
   name: "Tables",
-  slug: "table",
+  slug: "tables",
 },
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between ae9adb5 and ba60cb6.

📒 Files selected for processing (4)
  • apps/webapp/app/components/primitives/Table.tsx (5 hunks)
  • apps/webapp/app/routes/resources.orgs.$organizationSlug.projects.v3.$projectParam.runs.$runParam.spans.$spanParam/route.tsx (6 hunks)
  • apps/webapp/app/routes/storybook.table/route.tsx (1 hunks)
  • apps/webapp/app/routes/storybook/route.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/webapp/app/routes/resources.orgs.$organizationSlug.projects.v3.$projectParam.runs.$runParam.spans.$spanParam/route.tsx
🔇 Additional comments (6)
apps/webapp/app/routes/storybook.table/route.tsx (1)

1-11: LGTM: Imports are appropriate and follow best practices.

The imports are well-organized and include all necessary components for the Story component. The naming conventions follow React best practices, and there are no unused imports.

apps/webapp/app/components/primitives/Table.tsx (5)

25-25: LGTM. Verify visual impact of removing row dividers.

The removal of the "divide-y" class from the table element looks good. This change will eliminate the vertical dividers between table rows, potentially creating a cleaner look.

Please verify that this change aligns with the intended design and doesn't negatively impact the table's visual hierarchy.


43-46: Great improvements to the TableHeader component!

The changes to the TableHeader component significantly enhance both its functionality and visual appeal:

  1. Sticky positioning improves usability for long tables.
  2. Added dividers and background color improve visual separation.
  3. Rounded top corners add a polished look.
  4. The pseudo-element border provides a subtle separation between header and body.

These updates will contribute to a better user experience and a more polished UI.


62-65: Good addition for handling large datasets. Verify scrolling behavior.

Adding the "overflow-y-auto" class to the tbody element is a good approach for handling tables with many rows. This allows vertical scrolling within the table body when the content exceeds the available space.

Please ensure that:

  1. A parent container with a fixed height is set to enable the scrolling behavior.
  2. The scrolling works as expected in different browsers and screen sizes.
  3. The user experience is smooth when interacting with large datasets.

147-147: LGTM. Verify visual consistency without gradient background.

The removal of the gradient background from the stickyStyles constant simplifies the styling of sticky elements. This change aligns with a cleaner, more modern design approach.

Please ensure that:

  1. The removal of the gradient background doesn't negatively impact the visual hierarchy or readability of the table.
  2. This change is consistent with other UI elements in the application.
  3. The sticky elements are still visually distinct from non-sticky elements.

189-189: Improved hover effect for better visual feedback.

Changing the hover effect class from "bg-charcoal-900" to "bg-charcoal-800" is a good improvement. This update:

  1. Slightly lightens the background color of table cells on hover.
  2. Likely provides better contrast and visibility.
  3. Enhances the visual feedback for interactive table cells.

These small details contribute to a more polished and responsive user interface.

@ericallam
Copy link
Member

Does the batchTrigger table link to the triggered runs?

@samejr
Copy link
Member Author

samejr commented Sep 27, 2024

Does the batchTrigger table link to the triggered runs?

Yep

CleanShot.2024-09-27.at.08.59.25.mp4

Copy link
Contributor

@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 and nitpick comments (1)
apps/webapp/app/components/primitives/Table.tsx (1)

144-150: Improved customization for table row hover effects.

The introduction of the rowHoverStyle prop and rowHoverStyles constant enhances the flexibility of defining hover effects for table rows. This allows for more nuanced control over the table's interactive appearance, with options for default, dimmed, and bright hover styles.

The implementation correctly integrates these new features into the TableCell component.

Consider adding documentation or comments explaining the usage and options for the new rowHoverStyle prop to improve developer experience when using this component.

Additionally, note that the stickyStyles constant has been simplified. Ensure this doesn't negatively impact the appearance of sticky cells in various scenarios.

Also applies to: 154-154, 168-168, 199-199

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between ba60cb6 and 50d5680.

📒 Files selected for processing (2)
  • apps/webapp/app/components/primitives/Table.tsx (6 hunks)
  • apps/webapp/app/routes/resources.orgs.$organizationSlug.projects.v3.$projectParam.runs.$runParam.spans.$spanParam/route.tsx (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/webapp/app/routes/resources.orgs.$organizationSlug.projects.v3.$projectParam.runs.$runParam.spans.$spanParam/route.tsx
🔇 Additional comments (3)
apps/webapp/app/components/primitives/Table.tsx (3)

25-25: Verify the removal of row dividers from the table.

The "divide-y" class has been removed from the table element. This change will remove the visual separation between table rows.

Please confirm if this is intentional and aligns with the updated design. If not, consider re-adding the class or using an alternative method for row separation.


43-46: Improved table header styling and functionality.

The changes to the TableHeader component enhance both its appearance and functionality:

  1. Sticky positioning keeps the header visible during scrolling.
  2. Background color distinguishes the header from the body.
  3. A subtle separator line is added at the bottom of the header.

These improvements contribute to better visual hierarchy and user experience.


62-65: Enhanced table body scrolling capability.

The addition of the "overflow-y-auto" class to the TableBody component allows for vertical scrolling within the table body when content exceeds the container's height. This improvement helps in handling large datasets more efficiently.

Please verify that this new scrolling behavior doesn't conflict with any existing scrolling at the table or page level, ensuring a smooth user experience across different screen sizes and content volumes.

@samejr samejr merged commit 4906fe9 into main Sep 27, 2024
9 checks passed
@samejr samejr deleted the run-page-additional-data branch September 27, 2024 11:14
No Sign up for free to join this conversation on GitHub. Already have an account? No Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants