Skip to content

fix: Better github agent view#347

Merged
adityachoudhari26 merged 1 commit intomainfrom
better-github-agent-view
Feb 27, 2025
Merged

fix: Better github agent view#347
adityachoudhari26 merged 1 commit intomainfrom
better-github-agent-view

Conversation

@adityachoudhari26
Copy link
Copy Markdown
Member

@adityachoudhari26 adityachoudhari26 commented Feb 27, 2025

Summary by CodeRabbit

  • New Features

    • Introduced a new configuration interface for managing GitHub-based deployment settings, enabling repository and workflow selection along with custom Git reference inputs.
    • Updated the job agent form to dynamically present configuration options tailored to different agent types for a smoother user experience.
  • Chores

    • Enhanced backend repository fetching to support both organization and individual user accounts.
    • Improved error handling and permission checks for job agent access.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Feb 27, 2025

Walkthrough

This pull request introduces a new React component, DeploymentJobAgentGithubConfig, to manage GitHub deployment job configurations. The changes update the job agent configuration UI in JobAgentSection.tsx to conditionally render components based on the selected agent type. API endpoints are modified to dynamically fetch repositories based on owner type, and a new GitHub router procedure is added for job agents. In addition, relevant permission enums and job agent type enumerations in the validators have been updated.

Changes

File(s) Change Summary
apps/webservice/src/app/[workspaceSlug]/…/DeploymentJobAgentGithubConfig.tsx Added a new React component to handle GitHub deployment job configurations with TRPC queries and popover interactions.
apps/webservice/src/app/[workspaceSlug]/…/JobAgentSection.tsx Updated job agent configuration rendering: removed the generic component, added conditional renders for Kubernetes, GitHub, and script configurations, and adjusted spacing.
packages/api/src/router/github.ts
packages/api/src/router/job.ts
Modified API routes: updated getRepos to accept a type parameter, enhanced error handling, and added a new github router with a protected byId procedure for GitHub job agents.
packages/validators/src/auth/index.ts
packages/validators/src/jobs/agents/index.ts
packages/validators/src/jobs/index.ts
Updated validators: added a new JobAgentGet permission, introduced a new JobAgentType enum, and removed the old job agent type enum, with export adjustments.

Sequence Diagram(s)

sequenceDiagram
  participant U as User
  participant JAS as JobAgentSection
  participant DGC as DeploymentJobAgentGithubConfig
  participant API as TRPC API
  participant GB as GitHub Router

  U->>JAS: Selects job agent configuration
  JAS->>DGC: Render GitHub config (if type = GithubApp)
  DGC->>API: Fetch GitHub agent & repos via TRPC query
  API->>GB: Process GitHub request with agent ID
  GB-->>API: Return agent details and repositories
  API-->>DGC: Provide data
  DGC->>U: Display GitHub configuration UI
Loading
sequenceDiagram
  participant API as TRPC API
  participant GR as GitHub Router
  participant GRF as getRepos Function
  participant Org as listForOrg
  participant UserRepo as listForUser

  API->>GR: Request repositories (includes owner and type)
  GR->>GRF: Call getRepos(page, history, token, owner, type)
  alt type == "organization"
    GRF->>Org: Fetch org repositories
    Org-->>GRF: Return repositories
  else type == "user"
    GRF->>UserRepo: Fetch user repositories
    UserRepo-->>GRF: Return repositories
  end
  GRF-->>GR: Return repository list
  GR-->>API: Deliver updated repository list
Loading

Possibly related PRs

Suggested reviewers

  • zacharyblasczyk

Poem

I'm a little bunny, hopping through our code,
New GitHub configs bloom on each branch loaded,
Deployment agents prance with TRPC in flight,
Logical paths align in the soft coding light,
With carrots and commits, our efforts explode,
Celebrating change in every line I behold!

✨ Finishing Touches
  • 📝 Generate Docstrings

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.
  • @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.

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
Copy Markdown
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

🧹 Nitpick comments (5)
packages/api/src/router/job.ts (1)

566-576: Add defensive check for installationId in agent config.

The code assumes agent.config.installationId exists and can be converted to a number. Consider adding a type check or validation to handle cases where the config structure might be different than expected.

+        if (!agent.config?.installationId) {
+          throw new TRPCError({
+            code: "BAD_REQUEST",
+            message: "GitHub app configuration is missing installation ID",
+          });
+        }
+
         const ghEntity = await ctx.db
           .select()
           .from(schema.githubEntity)
           .where(
             eq(
               schema.githubEntity.installationId,
               Number(agent.config.installationId),
             ),
           )
           .then(takeFirstOrNull);
apps/webservice/src/app/[workspaceSlug]/(appv2)/systems/[systemSlug]/(raw)/deployments/[deploymentSlug]/(sidebar)/workflow/JobAgentSection.tsx (1)

61-92: Well-implemented conditional rendering for job agent configs

The new approach of conditionally rendering different configuration components based on the job agent type is clean and maintainable. Consider adding a default case to handle unknown agent types.

              {selectedJobAgent?.type.startsWith("exec-") && (
                <JobAgentScriptConfig
                  type={
                    selectedJobAgent.type.startsWith(JobAgentType.ExecWindows)
                      ? "powershell"
                      : "shell"
                  }
                  {...field}
                />
              )}
+              {selectedJobAgent && 
+               !selectedJobAgent.type.startsWith("exec-") && 
+               selectedJobAgent.type !== JobAgentType.KubernetesJob && 
+               selectedJobAgent.type !== JobAgentType.GithubApp && (
+                <span className="text-sm text-muted-foreground">
+                  Configuration not available for this agent type
+                </span>
+              )}
apps/webservice/src/app/[workspaceSlug]/(appv2)/systems/[systemSlug]/(raw)/deployments/[deploymentSlug]/(sidebar)/workflow/DeploymentJobAgentGithubConfig.tsx (3)

34-44: Add error handling for failed data fetching

While loading states are handled, there's no explicit error handling for failed queries. Consider adding error states to inform users when API calls fail.

  const { data: githubAgent, isLoading: isGithubAgentLoading } =
    api.job.agent.github.byId.useQuery(jobAgentId);
  const { data: repos, isLoading: isReposLoading } =
    api.github.entities.repos.list.useQuery(
      {
        installationId: githubAgent?.ghEntity.installationId ?? 0,
        owner: githubAgent?.ghEntity.slug ?? "",
        workspaceId: githubAgent?.workspaceId ?? "",
      },
      { enabled: githubAgent != null },
    );
+
+ // Add error handling
+ if (repos === undefined && !isReposLoading) {
+   return (
+     <div className="flex w-96 items-center justify-center gap-2 text-red-500">
+       <span>Failed to load repositories. Please try again.</span>
+     </div>
+   );
+ }

189-199: Add validation for the Git reference field

Consider adding basic validation for the Git reference input to prevent invalid inputs that could cause workflow failures.

        <div className="flex flex-col gap-2">
          <Label className="font-medium">Git reference</Label>
          <Input
            placeholder="(uses repositories default if not set)"
            value={value.ref ?? ""}
+           pattern="^[a-zA-Z0-9_\-./]+$"
+           title="Valid Git references: branch names, tag names, or commit hashes"
            onChange={(e) => {
              const ref = e.target.value === "" ? null : e.target.value;
              onChange({ ...value, ref });
            }}
          />
+         <span className="text-xs text-muted-foreground">
+           Enter branch name, tag name, or commit hash
+         </span>
        </div>

110-113: Consider clearing related fields when repo changes

When a user selects a new repository, the workflow selection may become invalid. Consider resetting the workflowId when a new repo is selected.

                          onSelect={(currentValue) => {
-                           onChange({ ...value, repo: currentValue });
+                           onChange({ ...value, repo: currentValue, workflowId: undefined });
                            setRepoOpen(false);
+                           setWorkflowOpen(true); // Optionally open workflow selector immediately
                          }}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 05dbae7 and 39399b5.

📒 Files selected for processing (7)
  • apps/webservice/src/app/[workspaceSlug]/(appv2)/systems/[systemSlug]/(raw)/deployments/[deploymentSlug]/(sidebar)/workflow/DeploymentJobAgentGithubConfig.tsx (1 hunks)
  • apps/webservice/src/app/[workspaceSlug]/(appv2)/systems/[systemSlug]/(raw)/deployments/[deploymentSlug]/(sidebar)/workflow/JobAgentSection.tsx (3 hunks)
  • packages/api/src/router/github.ts (4 hunks)
  • packages/api/src/router/job.ts (4 hunks)
  • packages/validators/src/auth/index.ts (1 hunks)
  • packages/validators/src/jobs/agents/index.ts (1 hunks)
  • packages/validators/src/jobs/index.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.{ts,tsx}`: **Note on Error Handling:** Avoid strict en...

**/*.{ts,tsx}: Note on Error Handling:
Avoid strict enforcement of try/catch blocks. Code may use early returns, Promise chains (.then().catch()), or other patterns for error handling. These are acceptable as long as they maintain clarity and predictability.

  • packages/validators/src/auth/index.ts
  • packages/validators/src/jobs/index.ts
  • packages/validators/src/jobs/agents/index.ts
  • packages/api/src/router/github.ts
  • apps/webservice/src/app/[workspaceSlug]/(appv2)/systems/[systemSlug]/(raw)/deployments/[deploymentSlug]/(sidebar)/workflow/DeploymentJobAgentGithubConfig.tsx
  • packages/api/src/router/job.ts
  • apps/webservice/src/app/[workspaceSlug]/(appv2)/systems/[systemSlug]/(raw)/deployments/[deploymentSlug]/(sidebar)/workflow/JobAgentSection.tsx
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Typecheck
  • GitHub Check: Lint
  • GitHub Check: build (linux/amd64)
🔇 Additional comments (13)
packages/validators/src/jobs/agents/index.ts (1)

1-5: Enum looks good for job agent types.

The enum definition is clear and follows best practices with descriptive string literals.

packages/validators/src/auth/index.ts (1)

33-33: Permission addition for job agent retrieval.

The new JobAgentGet permission correctly follows the established naming convention and is properly placed in the enum structure.

packages/validators/src/jobs/index.ts (1)

2-2: New module export for job agents.

This export statement correctly makes the job agent types available from the main jobs module.

packages/api/src/router/job.ts (2)

538-586: GitHub router implementation looks good with proper error handling.

The new router implementation correctly implements the necessary error handling and data fetching logic for GitHub job agents.


560-565: Verify agent type check is robust for all case scenarios.

The current check verifies if the agent type matches String(JobAgentType.GithubApp). This approach works but consider using a direct comparison against the enum value for better type safety.

-        if (agent.type !== String(JobAgentType.GithubApp))
+        if (agent.type !== JobAgentType.GithubApp)
packages/api/src/router/github.ts (4)

128-128: Good addition of type parameter

Adding the type parameter to distinguish between organizations and users enhances the flexibility of the getRepos function.


130-149: Improved repository fetching with conditional logic

The implementation correctly handles both organization and user repositories by conditionally calling the appropriate GitHub API method.


192-209: Enhanced error handling for entity retrieval

Good improvement in error handling by explicitly checking if the entity exists and throwing a proper error with a meaningful message.


226-226: Valid usage of entity type

You're correctly passing the entity type to the getRepos function, ensuring that the right repositories are fetched.

apps/webservice/src/app/[workspaceSlug]/(appv2)/systems/[systemSlug]/(raw)/deployments/[deploymentSlug]/(sidebar)/workflow/JobAgentSection.tsx (2)

12-18: Good modularization of job agent configurations

The updated imports reflect a better separation of concerns by using specialized components for different job agent types.


46-46: Improved spacing for better readability

Changing from space-y-3 to space-y-6 provides more vertical space between elements, improving the form's readability.

apps/webservice/src/app/[workspaceSlug]/(appv2)/systems/[systemSlug]/(raw)/deployments/[deploymentSlug]/(sidebar)/workflow/DeploymentJobAgentGithubConfig.tsx (2)

26-30: Well-structured component props

The component props are well-defined and provide a clean interface for integration with the parent component.


102-132: Good handling of loading and empty states

The component properly handles loading states and empty data scenarios, providing clear feedback to the user.

@adityachoudhari26 adityachoudhari26 merged commit 803618f into main Feb 27, 2025
8 checks passed
@adityachoudhari26 adityachoudhari26 deleted the better-github-agent-view branch February 27, 2025 21:51
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.

1 participant