123b2f6eed
* feat(backend): accept github_url in task creation and clone on launch Add github_url field to task creation DTO and propagate through HTTP/WS handlers and service layer. When a task is created with a GitHub URL instead of a local repository, the service resolves (or creates) the repository record via FindOrCreateRepository and triggers a clone/fetch via repoclone.Cloner during executor pre-flight. Wire RepoCloner into the orchestrator executor so remote repositories are fetched before the agent process starts. On resume, RepoUpdater performs a fetch to ensure the worktree is up-to-date. * feat(backend): add GitHub branches endpoint for remote repos Add ListRepoBranches to the GitHub client interface (GHClient, PATClient, NoopClient, MockClient) and expose it via GET /api/v1/github/repos/:owner/:repo/branches. The mock controller gains POST /api/v1/github/mock/branches for seeding branch data in E2E tests. * feat(web): add GitHub URL input to task create dialog Add a toggle in the task create dialog that switches between the existing repository selector and a free-text GitHub URL input. When a valid GitHub URL is entered (owner/repo parsed), branches are fetched from the new backend endpoint and auto-selected. The dialog state, effects, validation, and submit logic are extended to support the github_url flow alongside the existing repository flow. * test(e2e): add tests for task creation from GitHub URL Add E2E tests verifying: - Full flow: toggle to GitHub URL mode, enter URL, create task, verify agent runs and completes in session view - Toggle behavior: switching between GitHub URL and repository selector modes updates UI correctly * fix(web): dynamic URL input sizing and extract RepoSourceInput Replace fixed-width GitHub URL input with size-based auto-sizing (matching InlineTaskName pattern). Extract RepoSourceInput component from DialogHeaderContent to stay within cyclomatic complexity limits. Add testId prop to Combobox and wire it to ExecutorProfileSelector for E2E test targeting. * test(e2e): add worktree executor test and fix GitHub URL repo seeding Update GitHub URL E2E tests to pre-seed a repository with GitHub provider info pointing to the local git repo, avoiding actual clone attempts during task creation. Add test for GitHub URL task creation with worktree executor type, verifying the full flow including executor profile selection. Extend ApiClient with listExecutors and provider fields on createRepository for test seeding. * fix(backend): use protocol-aware clone URL for provider-backed repos The ensureRepoCloned function was hardcoding HTTPS clone URLs via repositoryCloneURL(), but the user's git setup may require SSH. Add BuildCloneURL to the RepoCloner interface so the executor uses the Cloner's configured protocol (SSH/HTTPS) instead of always generating HTTPS URLs. Falls back to HTTPS if BuildCloneURL fails. This fixes workspace loading issues (terminal, file tree) for cloned repos when the user has SSH-only authentication configured. * test(e2e): enhance GitHub URL test with terminal and changes panel verification * feat(web): add inline validation for GitHub URL input - Show inline error for invalid URL format (not matching github.com/owner/repo) - Show inline error when repository is not found or not accessible - Mock client returns error for unknown repos (matches real GitHub API) - E2E tests for invalid URL, nonexistent repo, and error-clearing on valid input * fix(web): fix GitHub URL branch auto-select and E2E test stability - Pick branch by name (main/master) for GitHub URL mode instead of using selectPreferredBranch which returns origin-prefixed names - Add test timeout for worktree executor test - Use shorter filename in terminal test to avoid xterm line-wrap issues * fix(web): fix GitHub URL dialog polish and wrong-repo bug UI fixes: - Align toggle button text with dropdown text content (pl-3) - Match GitHub URL input height to dropdown trigger (min-h-9) - Position error text absolutely to prevent layout shift - Remove redundant toast on repo-not-found (inline error suffices) Bug fix: - Prevent repo auto-select from overriding GitHub URL mode by guarding useRepositoryAutoSelectEffect with useGitHubUrl - Reorder getRepositoriesPayload to check useGitHubUrl first, preventing stale repositoryId from winning over the GitHub URL Add E2E test verifying correct repo usage across consecutive tasks. * fix(web): fix dialog height mismatch and error text overlap - Use exact h-9 on GitHub URL input to match dropdown trigger height - Move error text from absolute-positioned overlay to inline next to the toggle button, preventing overlap while keeping layout stable * fix(web): make GitHub URL input auto-size to content Reduce minimum size from 30 to 20 and shorten placeholder so the "/ task-name" sits closer to the URL text, matching the dropdown's compact w-auto behavior. * fix(web): polish GitHub URL input sizing, floating error, and placeholder color - Match input height (h-7) and padding (px-2) to Combobox trigger button - Size input width to exactly fit placeholder text - Show validation error as floating popover below input instead of inline - Keep placeholder text grey even when input has error state - Extract useGitHubUrlState hook to fix max-lines-per-function lint * fix(backend): return proper HTTP status codes from GitHub branches endpoint Add GitHubAPIError type to distinguish upstream GitHub API status codes. The branches endpoint now returns 404 (not 500) for non-existent repos, which the logging middleware correctly logs as DEBUG instead of ERROR. * feat(web): show error toast when a task session fails to start Add session failure notification plumbing: WS handler detects FAILED state with error_message, pushes to Zustand store, and a global bridge component shows an error toast via the ToastProvider. Also adds data-testid attributes to toast elements and types error_message on the session state changed payload. * style: fix prettier formatting in task-create-dialog and related files * fix(web): extract ToastList component to fix max-lines-per-function lint * fix: address code review feedback for GitHub URL task creation - Preserve 403 status instead of collapsing to 401 in branches endpoint - Use clone-generic error instead of remote-docker-specific in ensureRepoCloned - Trim whitespace in GitHub URL validation (backend + frontend) - Add GitHubURL field to wsUpdateTask path - Fix DefaultBranch mapping to prefer repoInput.DefaultBranch over BaseBranch - Clear githubBranchesLoading on early-return paths to prevent stuck state - Gate GitHub branch loading by mode to avoid false loading states - Encode owner/repo in API path for special characters - Add aria-label, aria-invalid, aria-errormessage for accessibility * fix(e2e): improve diff-update test stability with fresh locator and longer timeout * fix(backend): add --paginate flag to gh api branches call for repos with >100 branches * fix: address second round of code review feedback - Add pagination support to PATClient.ListRepoBranches for repos with >100 branches - Validate owner/repo in mock controller addBranches endpoint - Use aria-describedby instead of aria-errormessage for broader AT support - Add aria-live region to toast container for screen reader announcements - Assert absence of FIRST_MODIFICATION in diff-update E2E test * fix(backend): downgrade HTTP request logger from error to warn for 4xx/5xx responses * fix: address third round of code review feedback - Validate repositoryID/localPath in UpdateRepositoryLocalPath - Copy slices in mock client to prevent external mutation - Extract GitHub header constants and shared setter in PATClient - Redact clone URL from logs to prevent credential leaks - Guard against persisting empty localPath after clone - Show fallback toast message when FAILED state has no error_message
308 lines
14 KiB
Go
308 lines
14 KiB
Go
// Package github provides GitHub integration for Kandev, including PR monitoring,
|
|
// review queue management, and CI/check status tracking.
|
|
package github
|
|
|
|
import "time"
|
|
|
|
// PR represents a GitHub Pull Request.
|
|
type PR struct {
|
|
Number int `json:"number"`
|
|
Title string `json:"title"`
|
|
URL string `json:"url"`
|
|
HTMLURL string `json:"html_url"`
|
|
State string `json:"state"` // open, closed, merged
|
|
HeadBranch string `json:"head_branch"`
|
|
HeadSHA string `json:"head_sha"`
|
|
BaseBranch string `json:"base_branch"`
|
|
AuthorLogin string `json:"author_login"`
|
|
RepoOwner string `json:"repo_owner"`
|
|
RepoName string `json:"repo_name"`
|
|
Body string `json:"body"`
|
|
Draft bool `json:"draft"`
|
|
Mergeable bool `json:"mergeable"`
|
|
Additions int `json:"additions"`
|
|
Deletions int `json:"deletions"`
|
|
RequestedReviewers []RequestedReviewer `json:"requested_reviewers"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
UpdatedAt time.Time `json:"updated_at"`
|
|
MergedAt *time.Time `json:"merged_at,omitempty"`
|
|
ClosedAt *time.Time `json:"closed_at,omitempty"`
|
|
}
|
|
|
|
// RequestedReviewer represents a pending reviewer request on a PR.
|
|
type RequestedReviewer struct {
|
|
Login string `json:"login"`
|
|
Type string `json:"type"` // user, team
|
|
}
|
|
|
|
// PRReview represents a review on a PR.
|
|
type PRReview struct {
|
|
ID int64 `json:"id"`
|
|
Author string `json:"author"`
|
|
AuthorAvatar string `json:"author_avatar"`
|
|
State string `json:"state"` // APPROVED, CHANGES_REQUESTED, COMMENTED, PENDING, DISMISSED
|
|
Body string `json:"body"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
}
|
|
|
|
// PRComment represents a review comment on specific code.
|
|
type PRComment struct {
|
|
ID int64 `json:"id"`
|
|
Author string `json:"author"`
|
|
AuthorAvatar string `json:"author_avatar"`
|
|
AuthorIsBot bool `json:"author_is_bot"`
|
|
Body string `json:"body"`
|
|
Path string `json:"path"`
|
|
Line int `json:"line"`
|
|
Side string `json:"side"` // LEFT, RIGHT
|
|
CommentType string `json:"comment_type"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
UpdatedAt time.Time `json:"updated_at"`
|
|
InReplyTo *int64 `json:"in_reply_to,omitempty"`
|
|
}
|
|
|
|
// CheckRun represents a CI check result.
|
|
type CheckRun struct {
|
|
Name string `json:"name"`
|
|
Source string `json:"source"` // check_run, status_context
|
|
Status string `json:"status"` // queued, in_progress, completed
|
|
Conclusion string `json:"conclusion"` // success, failure, neutral, cancelled, timed_out, action_required, skipped
|
|
HTMLURL string `json:"html_url"`
|
|
Output string `json:"output"`
|
|
StartedAt *time.Time `json:"started_at,omitempty"`
|
|
CompletedAt *time.Time `json:"completed_at,omitempty"`
|
|
}
|
|
|
|
// PRFeedback aggregates all feedback for a PR (fetched live from GitHub).
|
|
type PRFeedback struct {
|
|
PR *PR `json:"pr"`
|
|
Reviews []PRReview `json:"reviews"`
|
|
Comments []PRComment `json:"comments"`
|
|
Checks []CheckRun `json:"checks"`
|
|
HasIssues bool `json:"has_issues"`
|
|
}
|
|
|
|
// PRWatch tracks active PR monitoring (session → PR).
|
|
type PRWatch struct {
|
|
ID string `json:"id" db:"id"`
|
|
SessionID string `json:"session_id" db:"session_id"`
|
|
TaskID string `json:"task_id" db:"task_id"`
|
|
Owner string `json:"owner" db:"owner"`
|
|
Repo string `json:"repo" db:"repo"`
|
|
PRNumber int `json:"pr_number" db:"pr_number"`
|
|
Branch string `json:"branch" db:"branch"`
|
|
LastCheckedAt *time.Time `json:"last_checked_at,omitempty" db:"last_checked_at"`
|
|
LastCommentAt *time.Time `json:"last_comment_at,omitempty" db:"last_comment_at"`
|
|
LastCheckStatus string `json:"last_check_status" db:"last_check_status"`
|
|
CreatedAt time.Time `json:"created_at" db:"created_at"`
|
|
UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
|
|
}
|
|
|
|
// TaskPR associates a PR with a task.
|
|
type TaskPR struct {
|
|
ID string `json:"id" db:"id"`
|
|
TaskID string `json:"task_id" db:"task_id"`
|
|
Owner string `json:"owner" db:"owner"`
|
|
Repo string `json:"repo" db:"repo"`
|
|
PRNumber int `json:"pr_number" db:"pr_number"`
|
|
PRURL string `json:"pr_url" db:"pr_url"`
|
|
PRTitle string `json:"pr_title" db:"pr_title"`
|
|
HeadBranch string `json:"head_branch" db:"head_branch"`
|
|
BaseBranch string `json:"base_branch" db:"base_branch"`
|
|
AuthorLogin string `json:"author_login" db:"author_login"`
|
|
State string `json:"state" db:"state"` // open, closed, merged
|
|
ReviewState string `json:"review_state" db:"review_state"` // approved, changes_requested, pending, ""
|
|
ChecksState string `json:"checks_state" db:"checks_state"` // success, failure, pending, ""
|
|
ReviewCount int `json:"review_count" db:"review_count"`
|
|
PendingReviewCount int `json:"pending_review_count" db:"pending_review_count"`
|
|
CommentCount int `json:"comment_count" db:"comment_count"`
|
|
Additions int `json:"additions" db:"additions"`
|
|
Deletions int `json:"deletions" db:"deletions"`
|
|
CreatedAt time.Time `json:"created_at" db:"created_at"`
|
|
MergedAt *time.Time `json:"merged_at,omitempty" db:"merged_at"`
|
|
ClosedAt *time.Time `json:"closed_at,omitempty" db:"closed_at"`
|
|
LastSyncedAt *time.Time `json:"last_synced_at,omitempty" db:"last_synced_at"`
|
|
UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
|
|
}
|
|
|
|
// RepoFilter identifies a GitHub repository for review watch filtering.
|
|
type RepoFilter struct {
|
|
Owner string `json:"owner"`
|
|
Name string `json:"name"`
|
|
}
|
|
|
|
// ReviewScope controls which GitHub search qualifier is used for review-requested PRs.
|
|
const (
|
|
// ReviewScopeUser matches only PRs where the user is explicitly requested
|
|
// (user-review-requested:@me).
|
|
ReviewScopeUser = "user"
|
|
// ReviewScopeUserAndTeams matches PRs requested from the user or any of their teams
|
|
// (review-requested:@me). This is the default for backwards compatibility.
|
|
ReviewScopeUserAndTeams = "user_and_teams"
|
|
)
|
|
|
|
// ReviewWatch configures periodic polling for PRs needing the user's review.
|
|
// Repos holds the list of repositories to monitor. An empty list means all repos.
|
|
type ReviewWatch struct {
|
|
ID string `json:"id" db:"id"`
|
|
WorkspaceID string `json:"workspace_id" db:"workspace_id"`
|
|
WorkflowID string `json:"workflow_id" db:"workflow_id"`
|
|
WorkflowStepID string `json:"workflow_step_id" db:"workflow_step_id"`
|
|
Repos []RepoFilter `json:"repos" db:"-"`
|
|
ReposJSON string `json:"-" db:"repos"`
|
|
AgentProfileID string `json:"agent_profile_id" db:"agent_profile_id"`
|
|
ExecutorProfileID string `json:"executor_profile_id" db:"executor_profile_id"`
|
|
Prompt string `json:"prompt" db:"prompt"`
|
|
ReviewScope string `json:"review_scope" db:"review_scope"`
|
|
CustomQuery string `json:"custom_query" db:"custom_query"`
|
|
Enabled bool `json:"enabled" db:"enabled"`
|
|
PollIntervalSeconds int `json:"poll_interval_seconds" db:"poll_interval_seconds"`
|
|
LastPolledAt *time.Time `json:"last_polled_at,omitempty" db:"last_polled_at"`
|
|
CreatedAt time.Time `json:"created_at" db:"created_at"`
|
|
UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
|
|
}
|
|
|
|
// ReviewPRTask records which PRs have already had tasks created (deduplication).
|
|
type ReviewPRTask struct {
|
|
ID string `json:"id" db:"id"`
|
|
ReviewWatchID string `json:"review_watch_id" db:"review_watch_id"`
|
|
RepoOwner string `json:"repo_owner" db:"repo_owner"`
|
|
RepoName string `json:"repo_name" db:"repo_name"`
|
|
PRNumber int `json:"pr_number" db:"pr_number"`
|
|
PRURL string `json:"pr_url" db:"pr_url"`
|
|
TaskID string `json:"task_id" db:"task_id"`
|
|
CreatedAt time.Time `json:"created_at" db:"created_at"`
|
|
}
|
|
|
|
// GitHubOrg represents a GitHub organization the authenticated user belongs to.
|
|
type GitHubOrg struct {
|
|
Login string `json:"login"`
|
|
AvatarURL string `json:"avatar_url"`
|
|
}
|
|
|
|
// GitHubRepo represents a GitHub repository (lightweight, for autocomplete).
|
|
type GitHubRepo struct {
|
|
FullName string `json:"full_name"`
|
|
Owner string `json:"owner"`
|
|
Name string `json:"name"`
|
|
Private bool `json:"private"`
|
|
}
|
|
|
|
// RepoBranch represents a branch in a GitHub repository.
|
|
type RepoBranch struct {
|
|
Name string `json:"name"`
|
|
}
|
|
|
|
// GitHubStatus represents GitHub connection status.
|
|
type GitHubStatus struct {
|
|
Authenticated bool `json:"authenticated"`
|
|
Username string `json:"username"`
|
|
AuthMethod string `json:"auth_method"` // "gh_cli", "pat", "none"
|
|
Diagnostics *AuthDiagnostics `json:"diagnostics,omitempty"`
|
|
}
|
|
|
|
// AuthDiagnostics captures the output of gh auth status for troubleshooting.
|
|
type AuthDiagnostics struct {
|
|
Command string `json:"command"`
|
|
Output string `json:"output"`
|
|
ExitCode int `json:"exit_code"`
|
|
}
|
|
|
|
// CreateReviewWatchRequest is the request body for creating a review watch.
|
|
type CreateReviewWatchRequest struct {
|
|
WorkspaceID string `json:"workspace_id"`
|
|
WorkflowID string `json:"workflow_id"`
|
|
WorkflowStepID string `json:"workflow_step_id"`
|
|
Repos []RepoFilter `json:"repos"`
|
|
AgentProfileID string `json:"agent_profile_id"`
|
|
ExecutorProfileID string `json:"executor_profile_id"`
|
|
Prompt string `json:"prompt"`
|
|
ReviewScope string `json:"review_scope"`
|
|
CustomQuery string `json:"custom_query"`
|
|
PollIntervalSeconds int `json:"poll_interval_seconds"`
|
|
}
|
|
|
|
// UpdateReviewWatchRequest is the request body for updating a review watch.
|
|
type UpdateReviewWatchRequest struct {
|
|
WorkflowID *string `json:"workflow_id,omitempty"`
|
|
WorkflowStepID *string `json:"workflow_step_id,omitempty"`
|
|
Repos *[]RepoFilter `json:"repos,omitempty"`
|
|
AgentProfileID *string `json:"agent_profile_id,omitempty"`
|
|
ExecutorProfileID *string `json:"executor_profile_id,omitempty"`
|
|
Prompt *string `json:"prompt,omitempty"`
|
|
ReviewScope *string `json:"review_scope,omitempty"`
|
|
CustomQuery *string `json:"custom_query,omitempty"`
|
|
Enabled *bool `json:"enabled,omitempty"`
|
|
PollIntervalSeconds *int `json:"poll_interval_seconds,omitempty"`
|
|
}
|
|
|
|
// PRFeedbackEvent is published to the event bus when a PR has new feedback.
|
|
type PRFeedbackEvent struct {
|
|
SessionID string `json:"session_id"`
|
|
TaskID string `json:"task_id"`
|
|
PRNumber int `json:"pr_number"`
|
|
Owner string `json:"owner"`
|
|
Repo string `json:"repo"`
|
|
NewComments int `json:"new_comments"`
|
|
ChecksChanged bool `json:"checks_changed"`
|
|
NewCheckStatus string `json:"new_check_status"`
|
|
NewReviewState string `json:"new_review_state"`
|
|
}
|
|
|
|
// NewReviewPREvent is published when a new PR needing review is found.
|
|
type NewReviewPREvent struct {
|
|
ReviewWatchID string `json:"review_watch_id"`
|
|
WorkspaceID string `json:"workspace_id"`
|
|
WorkflowID string `json:"workflow_id"`
|
|
WorkflowStepID string `json:"workflow_step_id"`
|
|
AgentProfileID string `json:"agent_profile_id"`
|
|
ExecutorProfileID string `json:"executor_profile_id"`
|
|
Prompt string `json:"prompt"`
|
|
PR *PR `json:"pr"`
|
|
}
|
|
|
|
// PRStatsRequest defines filters for PR stats queries.
|
|
type PRStatsRequest struct {
|
|
WorkspaceID string `json:"workspace_id"`
|
|
StartDate *time.Time `json:"start_date,omitempty"`
|
|
EndDate *time.Time `json:"end_date,omitempty"`
|
|
}
|
|
|
|
// PRStats holds aggregated PR analytics.
|
|
type PRStats struct {
|
|
TotalPRsCreated int `json:"total_prs_created"`
|
|
TotalPRsReviewed int `json:"total_prs_reviewed"`
|
|
TotalComments int `json:"total_comments"`
|
|
CIPassRate float64 `json:"ci_pass_rate"`
|
|
ApprovalRate float64 `json:"approval_rate"`
|
|
AvgTimeToMergeHours float64 `json:"avg_time_to_merge_hours"`
|
|
PRsByDay []DailyCount `json:"prs_by_day"`
|
|
}
|
|
|
|
// PRFile represents a file changed in a pull request.
|
|
type PRFile struct {
|
|
Filename string `json:"filename"`
|
|
Status string `json:"status"` // added, removed, modified, renamed, copied, changed, unchanged
|
|
Additions int `json:"additions"`
|
|
Deletions int `json:"deletions"`
|
|
Patch string `json:"patch,omitempty"`
|
|
OldPath string `json:"old_path,omitempty"`
|
|
}
|
|
|
|
// PRCommitInfo represents a commit in a pull request.
|
|
type PRCommitInfo struct {
|
|
SHA string `json:"sha"`
|
|
Message string `json:"message"`
|
|
AuthorLogin string `json:"author_login"`
|
|
AuthorDate string `json:"author_date"`
|
|
Additions int `json:"additions"`
|
|
Deletions int `json:"deletions"`
|
|
FilesChanged int `json:"files_changed"`
|
|
}
|
|
|
|
// DailyCount holds a date and count for chart data.
|
|
type DailyCount struct {
|
|
Date string `json:"date"`
|
|
Count int `json:"count"`
|
|
}
|