c11a6bbfd2
* feat(github): add issue watcher with task creation and auto-cleanup
Add a GitHub Issue Watcher feature that polls for new issues matching
configurable filters and automatically creates tasks for them. This
complements the existing PR Review Watcher with the same patterns.
Backend:
- Issue watch CRUD (models, store, service, controller, WS handlers)
- Poller integration with configurable intervals
- Event-driven task creation via orchestrator
- Repository resolution and worktree support for issue tasks
- Auto-cleanup of tasks for closed issues (CleanupClosedIssueTasks)
- GetIssueState client method across all implementations
- Default branch auto-detection from cloned repo HEAD
Frontend:
- Issue watch settings UI (table, dialog, placeholders)
- Issue link icon on task cards (green circle-dot)
- API client, store slice, and hook for issue watches
- SSR and WS hydration of issue metadata
* fix: resolve golangci-lint errors (goconst, nestif, dupl) and prettier formatting
* fix(github): fix issue watch update shape, trigger key, and label quoting
- httpUpdateIssueWatch now returns the full IssueWatch object instead of
{updated:true} so the frontend store correctly refreshes after edits
- httpTriggerIssueWatch returns new_issues_found to match TriggerIssueResponse
type; was returning new_issues so the toast count was always 0
- buildIssueFilter uses conditional quoting instead of fmt.Sprintf %q to
avoid Go escape sequences in GitHub search qualifiers
Co-authored-by: João Salavisa <undefined@users.noreply.github.com>
* fix: resolve eslint warnings (max-lines-per-function, no-nested-ternary)
* test(github): add issue watcher tests and fix review feedback
- Add TestInterpolateIssuePrompt (4 cases: empty/all/none/partial)
- Add TestCreateIssueTask (3 cases: skip/reserve+assign/release on fail)
- Add TestShouldDeleteIssueTask (4 cases: open/closed+sessions/closed/error)
- Fix WS response key new_issues -> new_issues_found
- Fix fmt.Printf -> fmt.Fprintf(os.Stderr) in store.go
- Add CleanupClosedIssueTasks call in WS trigger handler
* fix: address PR review feedback and CI failures
- Split test files to fix revive file-length-limit (service_test.go,
event_handlers_github_test.go)
- Add session checker guard in CleanupClosedIssueTasks
- Normalize poll intervals on UpdateIssueWatch
- Add cleanup call in TriggerAllIssueChecks loop
- Log cleanup errors in controller and WS handler
- Prefer refs/remotes/origin/HEAD in detectGitDefaultBranch
- Add aria-label to issue task icon
- Fix TypeScript type errors: add linkedIssues to GitHubSlice,
fix hook exports, remove invalid imports
* fix: split test files exceeding revive limit and clean up minor issues
- Split service_test.go (883→779 lines): move TestTriggerPRSync_* to
service_pr_sync_test.go
- Split event_handlers_github_test.go (806→677 lines): move
TestCreateReviewTask_* and helpers to event_handlers_github_review_test.go
- Remove redundant s.taskSessionChecker nil-check inside shouldDeleteIssueTask
(early guard at CleanupClosedIssueTasks already ensures it is non-nil)
- Remove unreachable dead guard in detectAndPersistDefaultBranch
(repo.DefaultBranch is always "" at that call site)
- Fix bogus #0 issue badge in task-session-sidebar.tsx when issueNumber is absent
Co-authored-by: João Salavisa <undefined@users.noreply.github.com>
* fix: address Claude review — poll clamp and prompt injection
- Handle v <= 0 in UpdateIssueWatch poll interval (fall back to default)
- Remove {{issue.body}} from default template to prevent prompt injection
- Update test expected output for new default template
* fix: remove {{issue.body}} from frontend DEFAULT_ISSUE_WATCH_PROMPT
Mirrors the backend fix — the UI pre-fills the prompt so the backend
fallback was never reached. The placeholder stays in
ISSUE_WATCH_PLACEHOLDERS for explicit opt-in.
* feat(github): add isIssueWatch sidebar filter dimension
Add isIssueWatch boolean to KanbanState, TaskSwitcherItem, and sidebar
filter registry — mirroring the isPRReview pattern. Issue-watch tasks
(created from issue_watch_id in metadata) can now be explicitly filtered
in the sidebar, just like PR review tasks.
Files changed:
- sidebar-view-types: add isIssueWatch dimension
- filter-dimension-registry: add Issue watch filter meta
- apply-view: add isIssueWatch extractor
- kanban types: add isIssueWatch field
- TaskSwitcherItem: add isIssueWatch field
- use-all-workflow-snapshots: derive isIssueWatch from metadata
- ssr/mapper: derive isIssueWatch from metadata
- task-session-sidebar: pass isIssueWatch, extract helpers to fix complexity
* fix: correct deleteIssueWatch response type to match backend
Backend httpDeleteIssueWatch returns {"deleted": true}; the frontend
type was { success: boolean } — a mismatch with no functional impact
(return value is ignored) but wrong per TypeScript contract.
Co-authored-by: João Salavisa <undefined@users.noreply.github.com>
* refactor: extract metadata helpers to shared lib/metadata-utils.ts
- Move isPRReviewFromMetadata, isIssueWatchFromMetadata, and
issueFieldsFromMetadata to a shared module to eliminate duplicate
definitions (sonarjs/no-identical-functions).
- Fix deleteIssueWatch response type: { success: boolean } -> { deleted: boolean }
to match the actual backend response.
* style: fix prettier formatting
* test(web): add tests for isIssueWatch filter dimension and metadata-utils
Co-authored-by: João Salavisa <undefined@users.noreply.github.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
* style: fix prettier formatting in test files
* fix(github): cascade-delete issue watch tasks on watch deletion and add isPRReview to SSR mapper
- DeleteIssueWatch now wraps in a transaction and deletes related
github_issue_watch_tasks rows before removing the watch; prevents
orphaned dedup rows accumulating after a watch is deleted
- snapshotToState in mapper.ts now also sets isPRReview from metadata,
matching the mapping already done in use-all-workflow-snapshots.ts
Co-authored-by: João Salavisa <undefined@users.noreply.github.com>
* style: extract duplicate string constant in metadata-utils test
* style: extract repeated WS error strings into constants in handlers.go
goconst min-occurrences: 3 — 'invalid payload' (6x) and 'id required' (4x)
both exceed the threshold. Extract to package-level constants.
Co-authored-by: João Salavisa <undefined@users.noreply.github.com>
* style: extract repeated issue key strings into constants in event_handlers_github.go
goconst min-occurrences: 3 — 'issue_number' (9x) and 'issue_watch_id' (5x)
both newly introduced in this PR exceed the threshold.
Co-authored-by: João Salavisa <undefined@users.noreply.github.com>
* style: fix prettier formatting in metadata-utils test
---------
Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
Co-authored-by: João Salavisa <undefined@users.noreply.github.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
443 lines
19 KiB
Go
443 lines
19 KiB
Go
package github
|
|
|
|
import (
|
|
"context"
|
|
"strings"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"go.uber.org/zap"
|
|
|
|
"github.com/kandev/kandev/internal/common/logger"
|
|
ws "github.com/kandev/kandev/pkg/websocket"
|
|
)
|
|
|
|
const (
|
|
errMsgInvalidPayload = "invalid payload"
|
|
errMsgIDRequired = "id required"
|
|
)
|
|
|
|
// RegisterRoutes registers HTTP and WebSocket routes for GitHub integration.
|
|
func RegisterRoutes(router *gin.Engine, dispatcher *ws.Dispatcher, svc *Service, log *logger.Logger) {
|
|
ctrl := NewController(svc, log)
|
|
ctrl.RegisterHTTPRoutes(router)
|
|
registerWSHandlers(dispatcher, svc, log)
|
|
}
|
|
|
|
// RegisterMockRoutes registers mock control endpoints if the GitHub client is a MockClient.
|
|
// This is a no-op when the underlying client is not a MockClient.
|
|
func RegisterMockRoutes(router *gin.Engine, svc *Service, log *logger.Logger) {
|
|
mock, ok := svc.Client().(*MockClient)
|
|
if !ok {
|
|
return
|
|
}
|
|
ctrl := NewMockController(mock, svc.TestStore(), svc.TestEventBus(), log)
|
|
ctrl.RegisterRoutes(router)
|
|
log.Info("registered GitHub mock control endpoints")
|
|
}
|
|
|
|
func registerWSHandlers(dispatcher *ws.Dispatcher, svc *Service, log *logger.Logger) {
|
|
dispatcher.RegisterFunc(ws.ActionGitHubStatus, wsStatus(svc, log))
|
|
dispatcher.RegisterFunc(ws.ActionGitHubTaskPRsList, wsListTaskPRs(svc, log))
|
|
dispatcher.RegisterFunc(ws.ActionGitHubTaskPRGet, wsGetTaskPR(svc, log))
|
|
dispatcher.RegisterFunc(ws.ActionGitHubPRFeedbackGet, wsGetPRFeedback(svc, log))
|
|
dispatcher.RegisterFunc(ws.ActionGitHubReviewWatchesList, wsListReviewWatches(svc, log))
|
|
dispatcher.RegisterFunc(ws.ActionGitHubReviewWatchCreate, wsCreateReviewWatch(svc, log))
|
|
dispatcher.RegisterFunc(ws.ActionGitHubReviewWatchUpdate, wsUpdateReviewWatch(svc, log))
|
|
dispatcher.RegisterFunc(ws.ActionGitHubReviewWatchDelete, wsDeleteReviewWatch(svc, log))
|
|
dispatcher.RegisterFunc(ws.ActionGitHubReviewTrigger, wsTriggerReviewWatch(svc, log))
|
|
dispatcher.RegisterFunc(ws.ActionGitHubReviewTriggerAll, wsTriggerAllReviewChecks(svc, log))
|
|
dispatcher.RegisterFunc(ws.ActionGitHubPRWatchesList, wsListPRWatches(svc, log))
|
|
dispatcher.RegisterFunc(ws.ActionGitHubPRWatchDelete, wsDeletePRWatch(svc, log))
|
|
dispatcher.RegisterFunc(ws.ActionGitHubPRFilesGet, wsGetPRFiles(svc, log))
|
|
dispatcher.RegisterFunc(ws.ActionGitHubPRCommitsGet, wsGetPRCommits(svc, log))
|
|
dispatcher.RegisterFunc(ws.ActionGitHubTaskPRSync, wsSyncTaskPR(svc, log))
|
|
dispatcher.RegisterFunc(ws.ActionGitHubStats, wsGetStats(svc, log))
|
|
|
|
// Issue watch handlers
|
|
dispatcher.RegisterFunc(ws.ActionGitHubIssueWatchesList, wsListIssueWatches(svc, log))
|
|
dispatcher.RegisterFunc(ws.ActionGitHubIssueWatchCreate, wsCreateIssueWatch(svc, log))
|
|
dispatcher.RegisterFunc(ws.ActionGitHubIssueWatchUpdate, wsUpdateIssueWatch(svc, log))
|
|
dispatcher.RegisterFunc(ws.ActionGitHubIssueWatchDelete, wsDeleteIssueWatch(svc, log))
|
|
dispatcher.RegisterFunc(ws.ActionGitHubIssueTrigger, wsTriggerIssueWatch(svc, log))
|
|
dispatcher.RegisterFunc(ws.ActionGitHubIssueTriggerAll, wsTriggerAllIssueChecks(svc, log))
|
|
}
|
|
|
|
// parseMap parses the WS message payload into a map for simple field lookups.
|
|
// Returns the map and any parse error. A nil map is replaced with an empty map.
|
|
func parseMap(msg *ws.Message) (map[string]interface{}, error) {
|
|
var m map[string]interface{}
|
|
err := msg.ParsePayload(&m)
|
|
if m == nil {
|
|
m = make(map[string]interface{})
|
|
}
|
|
return m, err
|
|
}
|
|
|
|
// wsWithField returns a WS handler that parses a single named string field from
|
|
// the payload and passes it to serviceFn, returning the result as the response.
|
|
func wsWithField(field string, serviceFn func(ctx context.Context, val string) (interface{}, error)) func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
payload, parseErr := parseMap(msg)
|
|
if parseErr != nil {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "invalid payload: "+parseErr.Error(), nil)
|
|
}
|
|
val, _ := payload[field].(string)
|
|
if val == "" {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, field+" required", nil)
|
|
}
|
|
result, err := serviceFn(ctx, val)
|
|
if err != nil {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, err.Error(), nil)
|
|
}
|
|
return ws.NewResponse(msg.ID, msg.Action, result)
|
|
}
|
|
}
|
|
|
|
// wsDeleteByID returns a WS handler that parses an "id" field from the payload
|
|
// and calls deleteFn. Used by both wsDeletePRWatch and wsDeleteReviewWatch.
|
|
func wsDeleteByID(deleteFn func(ctx context.Context, id string) error) func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
payload, parseErr := parseMap(msg)
|
|
if parseErr != nil {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "invalid payload: "+parseErr.Error(), nil)
|
|
}
|
|
id, _ := payload["id"].(string)
|
|
if id == "" {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, errMsgIDRequired, nil)
|
|
}
|
|
if err := deleteFn(ctx, id); err != nil {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, err.Error(), nil)
|
|
}
|
|
return ws.NewResponse(msg.ID, msg.Action, map[string]bool{"deleted": true})
|
|
}
|
|
}
|
|
|
|
// wsUpdateByPayload builds a WS handler that parses an ID + typed request from
|
|
// the payload and delegates to updateFn.
|
|
func wsUpdateByPayload[T any](updateFn func(ctx context.Context, id string, req *T) error) func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
idHolder := struct {
|
|
ID string `json:"id"`
|
|
}{}
|
|
if err := msg.ParsePayload(&idHolder); err != nil {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, errMsgInvalidPayload, nil)
|
|
}
|
|
if idHolder.ID == "" {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, errMsgIDRequired, nil)
|
|
}
|
|
var req T
|
|
if err := msg.ParsePayload(&req); err != nil {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, errMsgInvalidPayload, nil)
|
|
}
|
|
if err := updateFn(ctx, idHolder.ID, &req); err != nil {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, err.Error(), nil)
|
|
}
|
|
return ws.NewResponse(msg.ID, msg.Action, map[string]bool{"updated": true})
|
|
}
|
|
}
|
|
|
|
// wsTriggerAllByWorkspace builds a WS handler that extracts workspace_id from
|
|
// the payload, calls the given trigger function, and returns the count under the
|
|
// specified response key.
|
|
func wsTriggerAllByWorkspace(
|
|
responseKey string,
|
|
triggerFn func(ctx context.Context, workspaceID string) (int, error),
|
|
) func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
payload, parseErr := parseMap(msg)
|
|
if parseErr != nil {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "invalid payload: "+parseErr.Error(), nil)
|
|
}
|
|
workspaceID, _ := payload["workspace_id"].(string)
|
|
if workspaceID == "" {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "workspace_id required", nil)
|
|
}
|
|
count, err := triggerFn(ctx, workspaceID)
|
|
if err != nil {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, err.Error(), nil)
|
|
}
|
|
return ws.NewResponse(msg.ID, msg.Action, map[string]int{responseKey: count})
|
|
}
|
|
}
|
|
|
|
func wsStatus(svc *Service, _ *logger.Logger) func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
status, err := svc.GetStatus(ctx)
|
|
if err != nil {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, err.Error(), nil)
|
|
}
|
|
return ws.NewResponse(msg.ID, msg.Action, status)
|
|
}
|
|
}
|
|
|
|
func wsListTaskPRs(svc *Service, log *logger.Logger) func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
payload, parseErr := parseMap(msg)
|
|
if parseErr != nil {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "invalid payload: "+parseErr.Error(), nil)
|
|
}
|
|
taskIDsStr, _ := payload["task_ids"].(string)
|
|
if taskIDsStr == "" {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "task_ids required", nil)
|
|
}
|
|
taskIDs := strings.Split(taskIDsStr, ",")
|
|
result, err := svc.ListTaskPRs(ctx, taskIDs)
|
|
if err != nil {
|
|
log.Error("ws: list task PRs failed", zap.Error(err))
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, err.Error(), nil)
|
|
}
|
|
return ws.NewResponse(msg.ID, msg.Action, result)
|
|
}
|
|
}
|
|
|
|
func wsGetTaskPR(svc *Service, _ *logger.Logger) func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
payload, parseErr := parseMap(msg)
|
|
if parseErr != nil {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "invalid payload: "+parseErr.Error(), nil)
|
|
}
|
|
taskID, _ := payload["task_id"].(string)
|
|
if taskID == "" {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "task_id required", nil)
|
|
}
|
|
tp, err := svc.GetTaskPR(ctx, taskID)
|
|
if err != nil {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, err.Error(), nil)
|
|
}
|
|
if tp == nil {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeNotFound, "no PR for task", nil)
|
|
}
|
|
return ws.NewResponse(msg.ID, msg.Action, tp)
|
|
}
|
|
}
|
|
|
|
func wsSyncTaskPR(svc *Service, _ *logger.Logger) func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
return wsWithField("task_id", func(ctx context.Context, taskID string) (interface{}, error) {
|
|
return svc.TriggerPRSync(ctx, taskID)
|
|
})
|
|
}
|
|
|
|
func wsGetPRFeedback(svc *Service, _ *logger.Logger) func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
payload, parseErr := parseMap(msg)
|
|
if parseErr != nil {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "invalid payload: "+parseErr.Error(), nil)
|
|
}
|
|
owner, _ := payload["owner"].(string)
|
|
repo, _ := payload["repo"].(string)
|
|
numberF, _ := payload["number"].(float64)
|
|
number := int(numberF)
|
|
if owner == "" || repo == "" || number == 0 {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "owner, repo, number required", nil)
|
|
}
|
|
feedback, err := svc.GetPRFeedback(ctx, owner, repo, number)
|
|
if err != nil {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, err.Error(), nil)
|
|
}
|
|
return ws.NewResponse(msg.ID, msg.Action, feedback)
|
|
}
|
|
}
|
|
|
|
func wsListReviewWatches(svc *Service, _ *logger.Logger) func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
return wsWithField("workspace_id", func(ctx context.Context, workspaceID string) (interface{}, error) {
|
|
watches, err := svc.ListReviewWatches(ctx, workspaceID)
|
|
return watches, err
|
|
})
|
|
}
|
|
|
|
func wsCreateReviewWatch(svc *Service, _ *logger.Logger) func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
var req CreateReviewWatchRequest
|
|
if err := msg.ParsePayload(&req); err != nil {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, errMsgInvalidPayload, nil)
|
|
}
|
|
rw, err := svc.CreateReviewWatch(ctx, &req)
|
|
if err != nil {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, err.Error(), nil)
|
|
}
|
|
return ws.NewResponse(msg.ID, msg.Action, rw)
|
|
}
|
|
}
|
|
|
|
func wsUpdateReviewWatch(svc *Service, _ *logger.Logger) func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
return wsUpdateByPayload(func(ctx context.Context, id string, req *UpdateReviewWatchRequest) error {
|
|
return svc.UpdateReviewWatch(ctx, id, req)
|
|
})
|
|
}
|
|
|
|
func wsDeleteReviewWatch(svc *Service, _ *logger.Logger) func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
return wsDeleteByID(svc.DeleteReviewWatch)
|
|
}
|
|
|
|
func wsTriggerReviewWatch(svc *Service, _ *logger.Logger) func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
payload, parseErr := parseMap(msg)
|
|
if parseErr != nil {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "invalid payload: "+parseErr.Error(), nil)
|
|
}
|
|
id, _ := payload["id"].(string)
|
|
if id == "" {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, errMsgIDRequired, nil)
|
|
}
|
|
watch, err := svc.GetReviewWatch(ctx, id)
|
|
if err != nil {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, err.Error(), nil)
|
|
}
|
|
if watch == nil {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeNotFound, "review watch not found", nil)
|
|
}
|
|
newPRs, err := svc.CheckReviewWatch(ctx, watch)
|
|
if err != nil {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, err.Error(), nil)
|
|
}
|
|
return ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{"new_prs": len(newPRs), "prs": newPRs})
|
|
}
|
|
}
|
|
|
|
func wsTriggerAllReviewChecks(svc *Service, _ *logger.Logger) func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
return wsTriggerAllByWorkspace("new_prs_found", svc.TriggerAllReviewChecks)
|
|
}
|
|
|
|
func wsListPRWatches(svc *Service, _ *logger.Logger) func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
watches, err := svc.ListActivePRWatches(ctx)
|
|
if err != nil {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, err.Error(), nil)
|
|
}
|
|
return ws.NewResponse(msg.ID, msg.Action, watches)
|
|
}
|
|
}
|
|
|
|
func wsDeletePRWatch(svc *Service, _ *logger.Logger) func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
return wsDeleteByID(svc.DeletePRWatch)
|
|
}
|
|
|
|
func wsGetStats(svc *Service, _ *logger.Logger) func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
var req PRStatsRequest
|
|
if err := msg.ParsePayload(&req); err != nil {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, errMsgInvalidPayload, nil)
|
|
}
|
|
stats, err := svc.GetPRStats(ctx, &req)
|
|
if err != nil {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, err.Error(), nil)
|
|
}
|
|
return ws.NewResponse(msg.ID, msg.Action, stats)
|
|
}
|
|
}
|
|
|
|
// parsePRParams extracts owner, repo, and number from a WS message payload.
|
|
// Returns a non-nil error response message if the payload is invalid or required fields are missing.
|
|
func parsePRParams(msg *ws.Message) (string, string, int, *ws.Message) {
|
|
payload, parseErr := parseMap(msg)
|
|
if parseErr != nil {
|
|
resp, _ := ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, errMsgInvalidPayload, nil)
|
|
return "", "", 0, resp
|
|
}
|
|
owner, _ := payload["owner"].(string)
|
|
repo, _ := payload["repo"].(string)
|
|
numberF, _ := payload["number"].(float64)
|
|
number := int(numberF)
|
|
if owner == "" || repo == "" || number == 0 {
|
|
resp, _ := ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "owner, repo, number required", nil)
|
|
return "", "", 0, resp
|
|
}
|
|
return owner, repo, number, nil
|
|
}
|
|
|
|
func wsGetPRFiles(svc *Service, _ *logger.Logger) func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
owner, repo, number, errResp := parsePRParams(msg)
|
|
if errResp != nil {
|
|
return errResp, nil
|
|
}
|
|
files, err := svc.GetPRFiles(ctx, owner, repo, number)
|
|
if err != nil {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, err.Error(), nil)
|
|
}
|
|
return ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{"files": files})
|
|
}
|
|
}
|
|
|
|
func wsGetPRCommits(svc *Service, _ *logger.Logger) func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
owner, repo, number, errResp := parsePRParams(msg)
|
|
if errResp != nil {
|
|
return errResp, nil
|
|
}
|
|
commits, err := svc.GetPRCommits(ctx, owner, repo, number)
|
|
if err != nil {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, err.Error(), nil)
|
|
}
|
|
return ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{"commits": commits})
|
|
}
|
|
}
|
|
|
|
// --- Issue watch WS handlers ---
|
|
|
|
func wsListIssueWatches(svc *Service, _ *logger.Logger) func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
return wsWithField("workspace_id", func(ctx context.Context, workspaceID string) (interface{}, error) {
|
|
return svc.ListIssueWatches(ctx, workspaceID)
|
|
})
|
|
}
|
|
|
|
func wsCreateIssueWatch(svc *Service, _ *logger.Logger) func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
var req CreateIssueWatchRequest
|
|
if err := msg.ParsePayload(&req); err != nil {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, errMsgInvalidPayload, nil)
|
|
}
|
|
iw, err := svc.CreateIssueWatch(ctx, &req)
|
|
if err != nil {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, err.Error(), nil)
|
|
}
|
|
return ws.NewResponse(msg.ID, msg.Action, iw)
|
|
}
|
|
}
|
|
|
|
func wsUpdateIssueWatch(svc *Service, _ *logger.Logger) func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
return wsUpdateByPayload(func(ctx context.Context, id string, req *UpdateIssueWatchRequest) error {
|
|
return svc.UpdateIssueWatch(ctx, id, req)
|
|
})
|
|
}
|
|
|
|
func wsDeleteIssueWatch(svc *Service, _ *logger.Logger) func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
return wsDeleteByID(svc.DeleteIssueWatch)
|
|
}
|
|
|
|
func wsTriggerIssueWatch(svc *Service, log *logger.Logger) func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
return func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
payload, parseErr := parseMap(msg)
|
|
if parseErr != nil {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "invalid payload: "+parseErr.Error(), nil)
|
|
}
|
|
id, _ := payload["id"].(string)
|
|
if id == "" {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, errMsgIDRequired, nil)
|
|
}
|
|
watch, err := svc.GetIssueWatch(ctx, id)
|
|
if err != nil {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, err.Error(), nil)
|
|
}
|
|
if watch == nil {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeNotFound, "issue watch not found", nil)
|
|
}
|
|
newIssues, err := svc.CheckIssueWatch(ctx, watch)
|
|
if err != nil {
|
|
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, err.Error(), nil)
|
|
}
|
|
for _, issue := range newIssues {
|
|
svc.publishNewIssueEvent(ctx, watch, issue)
|
|
}
|
|
cleaned, cleanErr := svc.CleanupClosedIssueTasks(ctx, watch)
|
|
if cleanErr != nil {
|
|
log.Warn("cleanup closed issue tasks failed", zap.String("watch_id", id), zap.Error(cleanErr))
|
|
}
|
|
return ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{"new_issues_found": len(newIssues), "issues": newIssues, "cleaned": cleaned})
|
|
}
|
|
}
|
|
|
|
func wsTriggerAllIssueChecks(svc *Service, _ *logger.Logger) func(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
|
return wsTriggerAllByWorkspace("new_issues_found", svc.TriggerAllIssueChecks)
|
|
}
|