fix(github): scope PR CI automation switches per linked PR (#2512)

Co-authored-by: ayattara <alassane.yattara@savoirfairelinux.com>
Co-authored-by: Carlos Florencio <carlosmflorencio@gmail.com>
This commit is contained in:
Alassane
2026-08-12 13:36:11 -04:00
committed by GitHub
parent 76ccc667ce
commit 7855a4e087
41 changed files with 2803 additions and 790 deletions
@@ -396,6 +396,10 @@ func (c *Controller) writeTaskCIOptionsError(ctx *gin.Context, err error, operat
ctx.JSON(http.StatusNotFound, gin.H{"error": "task not found"})
return
}
if errors.Is(err, ErrTaskPRNotLinked) {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if writeGitHubOperationalAuthError(ctx, err) {
return
}
@@ -417,6 +421,18 @@ func parseTaskCIOptionsPatch(ctx *gin.Context) (TaskCIOptionsPatch, error) {
var patch TaskCIOptionsPatch
for key, value := range raw {
switch key {
case "repository_id":
var repositoryID string
if err := json.Unmarshal(value, &repositoryID); err != nil {
return TaskCIOptionsPatch{}, err
}
patch.RepositoryID = &repositoryID
case "pr_number":
var prNumber int
if err := json.Unmarshal(value, &prNumber); err != nil {
return TaskCIOptionsPatch{}, err
}
patch.PRNumber = &prNumber
case "auto_fix_enabled":
var enabled bool
if err := json.Unmarshal(value, &enabled); err != nil {
@@ -1202,6 +1202,121 @@ func TestHttpTaskCIOptions_DefaultAndPatch(t *testing.T) {
}
}
// TestHttpPatchTaskCIOptions_TargetsOnePRWithoutAffectingSibling covers AC6:
// a PATCH naming one linked PR's repository_id/pr_number sets the switch for
// that PR only; a second linked PR's row is unchanged.
func TestHttpPatchTaskCIOptions_TargetsOnePRWithoutAffectingSibling(t *testing.T) {
router, store := setupControllerStoreTest(t)
ctx := context.Background()
for _, prNumber := range []int{1, 2} {
if err := store.CreateTaskPR(ctx, &TaskPR{
TaskID: "task-1", RepositoryID: "repo-1",
Owner: "acme", Repo: "widget", PRNumber: prNumber,
State: "open", CreatedAt: time.Now().UTC(),
}); err != nil {
t.Fatalf("seed task pr #%d: %v", prNumber, err)
}
}
body := bytes.NewBufferString(`{"repository_id":"repo-1","pr_number":1,"auto_fix_enabled":true}`)
req := httptest.NewRequest(http.MethodPatch, "/api/v1/github/tasks/task-1/ci-options", body)
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
}
opts1, err := store.GetTaskPRAutomationOptions(ctx, "task-1", "repo-1", 1)
if err != nil {
t.Fatalf("get PR 1 options: %v", err)
}
if !opts1.AutoFixEnabled {
t.Fatalf("PR 1 auto_fix_enabled = false, want true")
}
opts2, err := store.GetTaskPRAutomationOptions(ctx, "task-1", "repo-1", 2)
if err != nil {
t.Fatalf("get PR 2 options: %v", err)
}
if opts2.AutoFixEnabled {
t.Fatalf("PR 2 auto_fix_enabled = true, want unaffected false")
}
}
// TestHttpPatchTaskCIOptions_UnlinkedPRReturns400AndWritesNothing covers AC8.
func TestHttpPatchTaskCIOptions_UnlinkedPRReturns400AndWritesNothing(t *testing.T) {
router, store := setupControllerStoreTest(t)
ctx := context.Background()
if err := store.CreateTaskPR(ctx, &TaskPR{
TaskID: "task-1", RepositoryID: "repo-1",
Owner: "acme", Repo: "widget", PRNumber: 1,
State: "open", CreatedAt: time.Now().UTC(),
}); err != nil {
t.Fatalf("seed task pr: %v", err)
}
body := bytes.NewBufferString(`{"repository_id":"repo-1","pr_number":999,"auto_fix_enabled":true,"auto_fix_prompt_override":"must-not-persist"}`)
req := httptest.NewRequest(http.MethodPatch, "/api/v1/github/tasks/task-1/ci-options", body)
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusBadRequest {
t.Fatalf("expected 400, got %d: %s", w.Code, w.Body.String())
}
opts, err := store.GetTaskPRAutomationOptions(ctx, "task-1", "repo-1", 999)
if err != nil {
t.Fatalf("get unlinked PR options: %v", err)
}
if opts.AutoFixEnabled {
t.Fatal("PATCH for an unlinked PR wrote a row instead of writing nothing")
}
taskOptions, err := store.GetTaskCIOptions(ctx, "task-1")
if err != nil {
t.Fatalf("get task options: %v", err)
}
if taskOptions.AutoFixPromptOverride != nil {
t.Fatalf("invalid PR identity partially updated task options: %+v", taskOptions)
}
}
// TestHttpPatchTaskCIOptions_PartialPRIdentityRejected pins the client error
// for a patch that supplies only one side of the PR identity.
func TestHttpPatchTaskCIOptions_PartialPRIdentityRejected(t *testing.T) {
for name, body := range map[string]string{
"repository only": `{"repository_id":"repo-1","auto_fix_enabled":true}`,
"PR number only": `{"pr_number":1,"auto_fix_enabled":true}`,
} {
t.Run(name, func(t *testing.T) {
router, store := setupControllerStoreTest(t)
ctx := context.Background()
if err := store.CreateTaskPR(ctx, &TaskPR{
TaskID: "task-1", RepositoryID: "repo-1",
Owner: "acme", Repo: "widget", PRNumber: 1,
State: "open", CreatedAt: time.Now().UTC(),
}); err != nil {
t.Fatalf("seed task pr: %v", err)
}
req := httptest.NewRequest(http.MethodPatch, "/api/v1/github/tasks/task-1/ci-options", bytes.NewBufferString(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusBadRequest {
t.Fatalf("expected 400, got %d: %s", w.Code, w.Body.String())
}
opts, err := store.GetTaskPRAutomationOptions(ctx, "task-1", "repo-1", 1)
if err != nil {
t.Fatalf("get PR options: %v", err)
}
if opts.AutoFixEnabled {
t.Fatal("partial identity patch wrote a row instead of writing nothing")
}
})
}
}
func TestHttpTaskCIOptions_DeniesForeignWorkspaceReadAndUpdate(t *testing.T) {
store := newTestStore(t)
log := newControllerTestLogger()
+5
View File
@@ -51,6 +51,11 @@ var ErrInvalidToken = errors.New("invalid token")
// transient upstream blip.
var ErrRepoNotResolvable = errors.New("github: repository not resolvable")
// ErrTaskPRNotLinked is returned by UpdateTaskCIOptions when the patch names
// a repository_id/pr_number that is not currently linked to the task. HTTP
// callers translate this into a 400 rather than a generic 500.
var ErrTaskPRNotLinked = errors.New("PR is not linked to this task")
// errStoreUnavailable is returned from service methods when no Store is
// wired (Provide can return a Service with store == nil when the SQLite
// repos aren't configured). Returning a typed error instead of nil-
+77 -10
View File
@@ -447,26 +447,46 @@ type TaskPR struct {
}
// TaskCIOptions stores task-level PR automation preferences.
//
// The five automation switches below (AutoFixEnabled, AutoMergeEnabled,
// PromptOnReviewRequested, PromptOnMerged, PromptOnClosed) are legacy: they
// are no longer written by UpdateTaskCIOptions and are read only by the
// one-time pr_scope_migrated_at fan-out migration
// (migrateTaskCIOptionsToPRScope). The per-PR source of truth is
// TaskPRAutomationOptions / github_task_pr_automation_options. Genuinely
// task-level fields (AutoFixPromptOverride, ReviewReviewerLogin) remain here.
type TaskCIOptions struct {
TaskID string `json:"task_id" db:"task_id"`
AutoFixEnabled bool `json:"auto_fix_enabled" db:"auto_fix_enabled"`
AutoMergeEnabled bool `json:"auto_merge_enabled" db:"auto_merge_enabled"`
AutoFixEnabled bool `json:"-" db:"auto_fix_enabled"`
AutoMergeEnabled bool `json:"-" db:"auto_merge_enabled"`
AutoFixPromptOverride *string `json:"auto_fix_prompt_override,omitempty" db:"auto_fix_prompt_override"`
PromptOnReviewRequested bool `json:"prompt_on_review_requested" db:"prompt_on_review_requested"`
PromptOnMerged bool `json:"prompt_on_merged" db:"prompt_on_merged"`
PromptOnClosed bool `json:"prompt_on_closed" db:"prompt_on_closed"`
PromptOnReviewRequested bool `json:"-" db:"prompt_on_review_requested"`
PromptOnMerged bool `json:"-" db:"prompt_on_merged"`
PromptOnClosed bool `json:"-" db:"prompt_on_closed"`
ReviewReviewerLogin string `json:"review_reviewer_login" db:"review_reviewer_login"`
// Lifecycle override columns remain only to read and clear legacy rows during
// the additive schema migration. They are not part of the update or API model.
ReviewPromptOverride *string `json:"-" db:"review_prompt_override"`
MergedPromptOverride *string `json:"-" db:"merged_prompt_override"`
ClosedPromptOverride *string `json:"-" db:"closed_prompt_override"`
CreatedAt time.Time `json:"created_at" db:"created_at"`
UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
ReviewPromptOverride *string `json:"-" db:"review_prompt_override"`
MergedPromptOverride *string `json:"-" db:"merged_prompt_override"`
ClosedPromptOverride *string `json:"-" db:"closed_prompt_override"`
// PRScopeMigratedAt guards the one-time fan-out of the legacy booleans
// above onto github_task_pr_automation_options. Nil means "not yet
// migrated"; non-nil means the fan-out already ran for this task and
// must never re-run (it would silently re-enable a switch a user has
// since turned off for a specific PR).
PRScopeMigratedAt *time.Time `json:"-" db:"pr_scope_migrated_at"`
CreatedAt time.Time `json:"created_at" db:"created_at"`
UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
}
// TaskCIOptionsPatch is a partial update for task CI automation options.
// RepositoryID/PRNumber optionally target one linked PR for the five
// automation switches; when both are nil the switches fan out to every PR
// currently linked to the task. AutoFixPromptOverride and ReviewReviewerLogin
// are always task-level regardless of PR identity.
type TaskCIOptionsPatch struct {
RepositoryID *string
PRNumber *int
AutoFixEnabled *bool
AutoMergeEnabled *bool
AutoFixPromptOverride *string
@@ -483,7 +503,53 @@ func (p TaskCIOptionsPatch) HasAny() bool {
p.ReviewReviewerLogin != nil
}
// PRAutomationPatch extracts the per-PR automation switch fields.
func (p TaskCIOptionsPatch) PRAutomationPatch() TaskPRAutomationOptionsPatch {
return TaskPRAutomationOptionsPatch{
AutoFixEnabled: p.AutoFixEnabled,
AutoMergeEnabled: p.AutoMergeEnabled,
PromptOnReviewRequested: p.PromptOnReviewRequested,
PromptOnMerged: p.PromptOnMerged,
PromptOnClosed: p.PromptOnClosed,
}
}
// TaskPRAutomationOptions stores per-PR automation switches, keyed by
// (task_id, repository_id, pr_number). This is the source of truth for the
// five CI/lifecycle automation switches; TaskCIOptions keeps only the
// genuinely task-level fields (prompt override, reviewer login).
type TaskPRAutomationOptions struct {
TaskID string `json:"task_id" db:"task_id"`
RepositoryID string `json:"repository_id" db:"repository_id"`
PRNumber int `json:"pr_number" db:"pr_number"`
AutoFixEnabled bool `json:"auto_fix_enabled" db:"auto_fix_enabled"`
AutoMergeEnabled bool `json:"auto_merge_enabled" db:"auto_merge_enabled"`
PromptOnReviewRequested bool `json:"prompt_on_review_requested" db:"prompt_on_review_requested"`
PromptOnMerged bool `json:"prompt_on_merged" db:"prompt_on_merged"`
PromptOnClosed bool `json:"prompt_on_closed" db:"prompt_on_closed"`
CreatedAt time.Time `json:"created_at" db:"created_at"`
UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
}
// TaskPRAutomationOptionsPatch is a partial update for one PR's automation switches.
type TaskPRAutomationOptionsPatch struct {
AutoFixEnabled *bool
AutoMergeEnabled *bool
PromptOnReviewRequested *bool
PromptOnMerged *bool
PromptOnClosed *bool
}
// HasAny reports whether the patch contains at least one requested field change.
func (p TaskPRAutomationOptionsPatch) HasAny() bool {
return p.AutoFixEnabled != nil || p.AutoMergeEnabled != nil ||
p.PromptOnReviewRequested != nil || p.PromptOnMerged != nil || p.PromptOnClosed != nil
}
// TaskCIOptionsResponse is the HTTP shape for task CI automation options.
// The top-level automation booleans are an aggregate over PROptions ("every
// linked PR has this switch enabled, and at least one PR is linked") kept for
// MCP/API read compatibility; PROptions is the per-PR source of truth.
type TaskCIOptionsResponse struct {
TaskID string `json:"task_id"`
AutoFixEnabled bool `json:"auto_fix_enabled"`
@@ -501,6 +567,7 @@ type TaskCIOptionsResponse struct {
EffectiveClosedPrompt string `json:"-"`
UpdatedAt time.Time `json:"updated_at"`
PRStates []*TaskCIPRAutomationState `json:"pr_states"`
PROptions []*TaskPRAutomationOptions `json:"pr_options"`
// WorkspaceID is routing metadata for workspace-scoped WebSocket delivery.
// It stays JSON-visible because NATS-backed event buses round-trip payloads.
WorkspaceID string `json:"workspace_id,omitempty"`
@@ -8,6 +8,10 @@ import (
promptcfg "github.com/kandev/kandev/config/prompts"
)
// errTaskPRIdentityIncomplete signals a patch that set exactly one of
// repository_id/pr_number instead of both or neither.
var errTaskPRIdentityIncomplete = fmt.Errorf("%w: repository_id and pr_number must both be set", ErrTaskPRNotLinked)
// GetTaskCIOptionsResponse returns task CI automation options plus effective prompt text.
func (s *Service) GetTaskCIOptionsResponse(ctx context.Context, taskID string) (*TaskCIOptionsResponse, error) {
if s.store == nil {
@@ -28,7 +32,12 @@ func (s *Service) GetTaskCIOptionsResponse(ctx context.Context, taskID string) (
return response, err
}
// UpdateTaskCIOptions updates task CI automation options and returns the response shape.
// UpdateTaskCIOptions updates task CI automation options and returns the
// response shape. patch.RepositoryID/PRNumber optionally target one linked
// PR for the five automation switches; omitted identity fans the switches
// out to every PR currently linked to the task (unchanged behavior for
// existing MCP callers). AutoFixPromptOverride and ReviewReviewerLogin are
// always applied task-level regardless of PR identity.
func (s *Service) UpdateTaskCIOptions(ctx context.Context, taskID string, patch TaskCIOptionsPatch) (*TaskCIOptionsResponse, error) {
if s.store == nil {
return nil, errStoreUnavailable
@@ -37,10 +46,32 @@ func (s *Service) UpdateTaskCIOptions(ctx context.Context, taskID string, patch
if err != nil {
return nil, err
}
if (patch.RepositoryID == nil) != (patch.PRNumber == nil) {
return nil, errTaskPRIdentityIncomplete
}
prPatch := patch.PRAutomationPatch()
var targets []*TaskPR
if patch.RepositoryID != nil || prPatch.HasAny() {
targets, err = s.resolveTaskPRAutomationTargets(ctx, taskID, patch.RepositoryID, patch.PRNumber)
if err != nil {
return nil, err
}
}
if err := s.populateReviewReviewer(ctx, taskID, &patch); err != nil {
return nil, err
}
opts, err := s.store.UpdateTaskCIOptions(ctx, taskID, patch)
reviewerChanged, err := s.taskPRReviewerChanged(ctx, taskID, patch.ReviewReviewerLogin)
if err != nil {
return nil, err
}
var opts *TaskCIOptions
if prPatch.HasAny() {
opts, err = s.store.UpdateTaskCIOptionsWithPRAutomation(
ctx, taskID, patch, targets, prPatch, reviewerChanged,
)
} else {
opts, err = s.store.UpdateTaskCIOptions(ctx, taskID, patch)
}
if err != nil {
return nil, err
}
@@ -80,6 +111,43 @@ func (s *Service) resolveAuthorizedTaskWorkspace(ctx context.Context, taskID str
return workspaceID, nil
}
// taskPRReviewerChanged compares the newly resolved task-level reviewer
// login (if the patch is setting one) against the value already stored, so
// callers can re-baseline review-request checkpoints precisely when the
// connected account actually changed.
func (s *Service) taskPRReviewerChanged(ctx context.Context, taskID string, newLogin *string) (bool, error) {
if newLogin == nil {
return false, nil
}
previous, err := s.store.GetTaskCIOptions(ctx, taskID)
if err != nil {
return false, err
}
return !strings.EqualFold(previous.ReviewReviewerLogin, strings.TrimSpace(*newLogin)), nil
}
// resolveTaskPRAutomationTargets resolves which linked PR(s) a patch
// applies to. Nil identity fans out to every linked PR (AC7); a named
// identity that isn't currently linked is rejected with ErrTaskPRNotLinked
// (AC8) rather than silently creating an orphan automation row.
func (s *Service) resolveTaskPRAutomationTargets(
ctx context.Context, taskID string, repositoryID *string, prNumber *int,
) ([]*TaskPR, error) {
prs, err := s.store.ListTaskPRsByTask(ctx, taskID)
if err != nil {
return nil, err
}
if repositoryID == nil && prNumber == nil {
return prs, nil
}
for _, pr := range prs {
if pr.RepositoryID == *repositoryID && pr.PRNumber == *prNumber {
return []*TaskPR{pr}, nil
}
}
return nil, fmt.Errorf("%w: repository_id=%s pr_number=%d", ErrTaskPRNotLinked, *repositoryID, *prNumber)
}
func (s *Service) populateReviewReviewer(
ctx context.Context,
taskID string,
@@ -88,23 +156,58 @@ func (s *Service) populateReviewReviewer(
if patch.PromptOnReviewRequested == nil {
return nil
}
if !*patch.PromptOnReviewRequested {
empty := ""
patch.ReviewReviewerLogin = &empty
if *patch.PromptOnReviewRequested {
resolved, err := s.resolveTaskPRAutomationClient(ctx, taskID)
if err != nil {
return err
}
login, err := resolved.Client.GetAuthenticatedUser(ctx)
if err != nil {
return fmt.Errorf("resolve authenticated reviewer: %w", err)
}
patch.ReviewReviewerLogin = &login
return nil
}
resolved, err := s.resolveTaskPRAutomationClient(ctx, taskID)
// Disabling review-request on the target PR(s) only blanks the shared
// task-level reviewer login when no other linked PR still depends on
// it — otherwise this would silently break that PR's automation.
stillNeeded, err := s.anyOtherPRHasReviewRequestEnabled(ctx, taskID, patch.RepositoryID, patch.PRNumber)
if err != nil {
return err
}
login, err := resolved.Client.GetAuthenticatedUser(ctx)
if err != nil {
return fmt.Errorf("resolve authenticated reviewer: %w", err)
if stillNeeded {
return nil
}
patch.ReviewReviewerLogin = &login
empty := ""
patch.ReviewReviewerLogin = &empty
return nil
}
func (s *Service) anyOtherPRHasReviewRequestEnabled(
ctx context.Context, taskID string, excludeRepositoryID *string, excludePRNumber *int,
) (bool, error) {
fanOut := excludeRepositoryID == nil && excludePRNumber == nil
options, err := s.taskPRAutomationOptionsList(ctx, taskID)
if err != nil {
return false, err
}
for _, opt := range options {
if !opt.PromptOnReviewRequested {
continue
}
if fanOut {
// The fan-out disable targets every linked PR, so nothing
// survives with the switch on regardless of stored state.
continue
}
if opt.RepositoryID == *excludeRepositoryID && opt.PRNumber == *excludePRNumber {
continue
}
return true, nil
}
return false, nil
}
// GetTaskCIPRState returns per-PR CI automation state, or nil.
func (s *Service) GetTaskCIPRState(ctx context.Context, taskID, repositoryID string, prNumber int) (*TaskCIPRAutomationState, error) {
if s.store == nil {
@@ -180,12 +283,20 @@ func (s *Service) IsReviewRequestedForLogin(
return false, nil
}
// HasEnabledTaskPRAgentPrompts reports whether any PR linked to the task has
// a lifecycle prompt switch enabled. Checks the per-PR table, not the legacy
// task row, so a task with mixed per-PR configuration is still detected.
func (s *Service) HasEnabledTaskPRAgentPrompts(ctx context.Context, taskID string) (bool, error) {
opts, err := s.store.GetTaskCIOptions(ctx, taskID)
options, err := s.taskPRAutomationOptionsList(ctx, taskID)
if err != nil {
return false, err
}
return opts.PromptOnReviewRequested || opts.PromptOnMerged || opts.PromptOnClosed, nil
for _, opt := range options {
if opt.PromptOnReviewRequested || opt.PromptOnMerged || opt.PromptOnClosed {
return true, nil
}
}
return false, nil
}
func (s *Service) SetTaskPRReviewRequestState(
@@ -274,7 +385,7 @@ func (s *Service) RecordTaskPRLifecyclePrompt(ctx context.Context, prompt TaskPR
func (s *Service) ShouldHoldTerminalPRWatch(
ctx context.Context, taskID, repositoryID string, prNumber int, state string,
) (bool, error) {
opts, err := s.store.GetTaskCIOptions(ctx, taskID)
opts, err := s.store.GetTaskPRAutomationOptions(ctx, taskID, repositoryID, prNumber)
if err != nil {
return false, err
}
@@ -295,30 +406,145 @@ func (s *Service) buildTaskCIOptionsResponse(ctx context.Context, opts *TaskCIOp
if err != nil {
return nil, err
}
prOptions, err := s.taskPRAutomationOptionsList(ctx, opts.TaskID)
if err != nil {
return nil, err
}
effectivePrompt, usingDefault := s.effectiveCIAutoFixPrompt(ctx, opts)
reviewPrompt := effectiveTaskPRPrompt("pr-review-requested")
mergedPrompt := effectiveTaskPRPrompt("pr-merged-final")
closedPrompt := effectiveTaskPRPrompt("pr-closed-final")
aggregate := aggregateTaskPRAutomationOptions(prOptions)
return &TaskCIOptionsResponse{
TaskID: opts.TaskID,
AutoFixEnabled: opts.AutoFixEnabled,
AutoMergeEnabled: opts.AutoMergeEnabled,
AutoFixEnabled: aggregate.autoFixEnabled,
AutoMergeEnabled: aggregate.autoMergeEnabled,
AutoFixPromptOverride: opts.AutoFixPromptOverride,
AutoFixMaxRounds: TaskCIAutoFixMaxRounds,
EffectiveAutoFixPrompt: effectivePrompt,
UsingDefaultPrompt: usingDefault,
PromptOnReviewRequested: opts.PromptOnReviewRequested,
PromptOnMerged: opts.PromptOnMerged,
PromptOnClosed: opts.PromptOnClosed,
PromptOnReviewRequested: aggregate.promptOnReviewRequested,
PromptOnMerged: aggregate.promptOnMerged,
PromptOnClosed: aggregate.promptOnClosed,
ReviewReviewerLogin: opts.ReviewReviewerLogin,
EffectiveReviewPrompt: reviewPrompt,
EffectiveMergedPrompt: mergedPrompt,
EffectiveClosedPrompt: closedPrompt,
UpdatedAt: opts.UpdatedAt,
PRStates: prStates,
PROptions: prOptions,
}, nil
}
// taskPRAutomationOptionsList returns one entry per PR currently linked to
// the task (AC5), synthesizing all-off defaults for a linked PR that has no
// stored row yet — mirroring the placeholder pattern in taskCIPRStates.
func (s *Service) taskPRAutomationOptionsList(ctx context.Context, taskID string) ([]*TaskPRAutomationOptions, error) {
stored, err := s.store.ListTaskPRAutomationOptions(ctx, taskID)
if err != nil {
return nil, err
}
prs, err := s.store.ListTaskPRsByTask(ctx, taskID)
if err != nil {
return nil, err
}
allPRs, err := s.store.ListTaskPRsByTaskIncludingDetached(ctx, taskID)
if err != nil {
return nil, err
}
merged := mergeTaskPRRows(stored, prs,
func(opt *TaskPRAutomationOptions) string { return taskCIPRStateKey(opt.RepositoryID, opt.PRNumber) },
func(pr *TaskPR) *TaskPRAutomationOptions {
return &TaskPRAutomationOptions{TaskID: taskID, RepositoryID: pr.RepositoryID, PRNumber: pr.PRNumber}
},
)
active := make(map[string]struct{}, len(prs))
for _, pr := range prs {
active[taskCIPRStateKey(pr.RepositoryID, pr.PRNumber)] = struct{}{}
}
detached := make(map[string]struct{})
for _, pr := range allPRs {
if pr.DetachedAt != nil {
detached[taskCIPRStateKey(pr.RepositoryID, pr.PRNumber)] = struct{}{}
}
}
filtered := make([]*TaskPRAutomationOptions, 0, len(prs))
for _, option := range merged {
key := taskCIPRStateKey(option.RepositoryID, option.PRNumber)
if _, ok := detached[key]; ok {
continue
}
if _, ok := active[key]; ok {
filtered = append(filtered, option)
continue
}
// Keep legacy/single-repo option rows that predate a durable TaskPR
// association. Only a matching detached association is excluded.
if _, known := detached[key]; !known {
filtered = append(filtered, option)
}
}
return filtered, nil
}
// mergeTaskPRRows overlays stored per-PR rows onto every PR currently linked
// to the task, synthesizing a default row (via makeDefault) for a linked PR
// with no stored row yet, and keeping any stored row for a PR no longer
// linked (e.g. detached) at the end. Task CI state keeps those historical rows
// for diagnostics, while task automation options filters them before exposing
// aggregates or lifecycle eligibility. Shared by taskCIPRStates and
// taskPRAutomationOptionsList, which differ only in row type.
func mergeTaskPRRows[T any](stored []T, prs []*TaskPR, keyOf func(T) string, makeDefault func(*TaskPR) T) []T {
byKey := make(map[string]T, len(stored))
for _, row := range stored {
byKey[keyOf(row)] = row
}
out := make([]T, 0, max(len(prs), len(stored)))
seen := make(map[string]struct{}, len(prs))
for _, pr := range prs {
key := taskCIPRStateKey(pr.RepositoryID, pr.PRNumber)
if row, ok := byKey[key]; ok {
out = append(out, row)
} else {
out = append(out, makeDefault(pr))
}
seen[key] = struct{}{}
}
for _, row := range stored {
if _, ok := seen[keyOf(row)]; !ok {
out = append(out, row)
}
}
return out
}
type taskPRAutomationAggregate struct {
autoFixEnabled, autoMergeEnabled bool
promptOnReviewRequested, promptOnMerged, promptOnClosed bool
}
// aggregateTaskPRAutomationOptions reports a switch as "enabled" only when
// every linked PR has it on and at least one PR is linked — the top-level
// booleans answer "did my task-wide enable take", kept for MCP/API read
// compatibility (R3). Prefer PROptions for anything PR-specific.
func aggregateTaskPRAutomationOptions(options []*TaskPRAutomationOptions) taskPRAutomationAggregate {
if len(options) == 0 {
return taskPRAutomationAggregate{}
}
agg := taskPRAutomationAggregate{
autoFixEnabled: true, autoMergeEnabled: true,
promptOnReviewRequested: true, promptOnMerged: true, promptOnClosed: true,
}
for _, opt := range options {
agg.autoFixEnabled = agg.autoFixEnabled && opt.AutoFixEnabled
agg.autoMergeEnabled = agg.autoMergeEnabled && opt.AutoMergeEnabled
agg.promptOnReviewRequested = agg.promptOnReviewRequested && opt.PromptOnReviewRequested
agg.promptOnMerged = agg.promptOnMerged && opt.PromptOnMerged
agg.promptOnClosed = agg.promptOnClosed && opt.PromptOnClosed
}
return agg
}
func effectiveTaskPRPrompt(name string) string {
return promptcfg.Get(name)
}
@@ -342,36 +568,18 @@ func (s *Service) taskCIPRStates(ctx context.Context, taskID string) ([]*TaskCIP
if err != nil {
return nil, err
}
byKey := make(map[string]*TaskCIPRAutomationState, len(stored))
for _, state := range stored {
byKey[taskCIPRStateKey(state.RepositoryID, state.PRNumber)] = state
}
prs, err := s.store.ListTaskPRsByTask(ctx, taskID)
if err != nil {
return nil, err
}
out := make([]*TaskCIPRAutomationState, 0, max(len(prs), len(stored)))
seen := make(map[string]struct{}, len(prs))
for _, pr := range prs {
key := taskCIPRStateKey(pr.RepositoryID, pr.PRNumber)
if state, ok := byKey[key]; ok {
out = append(out, state)
} else {
out = append(out, &TaskCIPRAutomationState{
TaskID: taskID,
RepositoryID: pr.RepositoryID,
PRNumber: pr.PRNumber,
})
}
seen[key] = struct{}{}
}
for _, state := range stored {
key := taskCIPRStateKey(state.RepositoryID, state.PRNumber)
if _, ok := seen[key]; !ok {
out = append(out, state)
}
}
return out, nil
return mergeTaskPRRows(stored, prs,
func(state *TaskCIPRAutomationState) string {
return taskCIPRStateKey(state.RepositoryID, state.PRNumber)
},
func(pr *TaskPR) *TaskCIPRAutomationState {
return &TaskCIPRAutomationState{TaskID: taskID, RepositoryID: pr.RepositoryID, PRNumber: pr.PRNumber}
},
), nil
}
func taskCIPRStateKey(repositoryID string, prNumber int) string {
@@ -232,6 +232,54 @@ func TestServiceTaskCIPRStatesMergesStoredAndCurrentPRs(t *testing.T) {
}
}
func TestServiceTaskCIOptionsExcludeDetachedPRAutomation(t *testing.T) {
store := newTestStore(t)
svc := NewService(&stubClient{}, "pat", nil, store, nil, testLogger(t))
ctx := context.Background()
now := time.Now().UTC()
active := &TaskPR{
TaskID: "task-1", RepositoryID: "repo-1", Owner: "acme", Repo: "widget",
PRNumber: 1, State: "open", CreatedAt: now,
}
detached := &TaskPR{
TaskID: "task-1", RepositoryID: "repo-1", Owner: "acme", Repo: "widget",
PRNumber: 2, State: "open", CreatedAt: now.Add(time.Second),
}
for _, pr := range []*TaskPR{active, detached} {
if err := store.CreateTaskPR(ctx, pr); err != nil {
t.Fatalf("create PR #%d: %v", pr.PRNumber, err)
}
}
if _, transitioned, err := store.DetachTaskPR(ctx, detached.ID); err != nil || !transitioned {
t.Fatalf("detach PR #%d: transitioned=%v err=%v", detached.PRNumber, transitioned, err)
}
enabled := true
if _, err := store.UpdateTaskPRAutomationOptions(ctx, "task-1", "repo-1", detached.PRNumber,
TaskPRAutomationOptionsPatch{PromptOnMerged: &enabled}, false); err != nil {
t.Fatalf("enable detached PR automation: %v", err)
}
response, err := svc.GetTaskCIOptionsResponse(ctx, "task-1")
if err != nil {
t.Fatalf("get task CI options: %v", err)
}
if len(response.PROptions) != 1 || response.PROptions[0].PRNumber != active.PRNumber {
t.Fatalf("PR options = %+v, want only active PR #%d", response.PROptions, active.PRNumber)
}
if response.AutoFixEnabled || response.AutoMergeEnabled || response.PromptOnMerged {
t.Fatalf("detached automation affected task aggregate: %+v", response)
}
hasEnabled, err := svc.HasEnabledTaskPRAgentPrompts(ctx, "task-1")
if err != nil {
t.Fatalf("check enabled lifecycle prompts: %v", err)
}
if hasEnabled {
t.Fatal("detached lifecycle automation kept the task eligible for PR automation")
}
}
func TestServiceTaskPRAgentAutomationHelpers(t *testing.T) {
store := newTestStore(t)
client := NewMockClient()
@@ -373,8 +421,15 @@ func TestServiceUpdateTaskCIOptionsResolvesReviewerForWorkspacelessTaskPR(t *tes
if err != nil {
t.Fatalf("get options: %v", err)
}
if !options.PromptOnReviewRequested || options.ReviewReviewerLogin != "reviewer-a" {
t.Fatalf("options = %+v, want review prompt bound to reviewer-a", options)
if options.ReviewReviewerLogin != "reviewer-a" {
t.Fatalf("options = %+v, want reviewer login reviewer-a", options)
}
prOptions, err := store.GetTaskPRAutomationOptions(ctx, "task-1", "repo-1", 42)
if err != nil {
t.Fatalf("get PR options: %v", err)
}
if !prOptions.PromptOnReviewRequested {
t.Fatalf("PR options = %+v, want prompt_on_review_requested=true", prOptions)
}
}
@@ -509,10 +564,13 @@ func TestServiceTerminalWatchReenableKeepsOtherEventAccepted(t *testing.T) {
ctx := context.Background()
enabled := true
disabled := false
if _, err := store.UpdateTaskCIOptions(ctx, "task-1", TaskCIOptionsPatch{
PromptOnMerged: &enabled, PromptOnClosed: &enabled,
}); err != nil {
t.Fatalf("enable terminal prompts: %v", err)
if _, err := store.UpdateTaskPRAutomationOptions(ctx, "task-1", "repo-merged", 1,
TaskPRAutomationOptionsPatch{PromptOnMerged: &enabled}, false); err != nil {
t.Fatalf("enable merged prompt: %v", err)
}
if _, err := store.UpdateTaskPRAutomationOptions(ctx, "task-1", "repo-closed", 2,
TaskPRAutomationOptionsPatch{PromptOnClosed: &enabled}, false); err != nil {
t.Fatalf("enable closed prompt: %v", err)
}
for _, prompt := range []TaskPRLifecyclePrompt{
{TaskID: "task-1", RepositoryID: "repo-merged", PRNumber: 1, Event: "merged", ObservedState: prStateMerged},
@@ -522,10 +580,12 @@ func TestServiceTerminalWatchReenableKeepsOtherEventAccepted(t *testing.T) {
t.Fatalf("record terminal prompt: %v", err)
}
}
if _, err := store.UpdateTaskCIOptions(ctx, "task-1", TaskCIOptionsPatch{PromptOnMerged: &disabled}); err != nil {
if _, err := store.UpdateTaskPRAutomationOptions(ctx, "task-1", "repo-merged", 1,
TaskPRAutomationOptionsPatch{PromptOnMerged: &disabled}, false); err != nil {
t.Fatalf("disable merged prompt: %v", err)
}
if _, err := store.UpdateTaskCIOptions(ctx, "task-1", TaskCIOptionsPatch{PromptOnMerged: &enabled}); err != nil {
if _, err := store.UpdateTaskPRAutomationOptions(ctx, "task-1", "repo-merged", 1,
TaskPRAutomationOptionsPatch{PromptOnMerged: &enabled}, false); err != nil {
t.Fatalf("re-enable merged prompt: %v", err)
}
@@ -92,9 +92,8 @@ func TestShouldDeleteReviewTask_AutoPolicy_LifecyclePromptPreserves(t *testing.T
Number: 99, State: prStateMerged, RepoOwner: "acme", RepoName: "widget",
})
enabled := true
if _, err := store.UpdateTaskCIOptions(ctx, "task-99", TaskCIOptionsPatch{
PromptOnMerged: &enabled,
}); err != nil {
if _, err := store.UpdateTaskPRAutomationOptions(ctx, "task-99", "", 99,
TaskPRAutomationOptionsPatch{PromptOnMerged: &enabled}, false); err != nil {
t.Fatalf("enable merged prompt: %v", err)
}
svc.taskSessionChecker = &recordingSessionChecker{}
@@ -112,9 +111,8 @@ func TestShouldDeleteReviewTask_AutoPolicy_LifecyclePromptPreservesWithoutSessio
Number: 99, State: prStateMerged, RepoOwner: "acme", RepoName: "widget",
})
enabled := true
if _, err := store.UpdateTaskCIOptions(ctx, "task-99", TaskCIOptionsPatch{
PromptOnMerged: &enabled,
}); err != nil {
if _, err := store.UpdateTaskPRAutomationOptions(ctx, "task-99", "", 99,
TaskPRAutomationOptionsPatch{PromptOnMerged: &enabled}, false); err != nil {
t.Fatalf("enable merged prompt: %v", err)
}
svc.taskSessionChecker = nil
+401 -32
View File
@@ -367,10 +367,29 @@ const createTablesSQL = `
review_prompt_override TEXT,
merged_prompt_override TEXT,
closed_prompt_override TEXT,
pr_scope_migrated_at DATETIME,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL
);
-- Per-PR automation switches. Source of truth for the five automation
-- switches (AutoFixEnabled, AutoMergeEnabled, PromptOnReviewRequested,
-- PromptOnMerged, PromptOnClosed) formerly stored task-wide on
-- github_task_ci_options. See migrateTaskCIOptionsToPRScope.
CREATE TABLE IF NOT EXISTS github_task_pr_automation_options (
task_id TEXT NOT NULL,
repository_id TEXT NOT NULL DEFAULT '',
pr_number INTEGER NOT NULL,
auto_fix_enabled BOOLEAN NOT NULL DEFAULT 0,
auto_merge_enabled BOOLEAN NOT NULL DEFAULT 0,
prompt_on_review_requested BOOLEAN NOT NULL DEFAULT 0,
prompt_on_merged BOOLEAN NOT NULL DEFAULT 0,
prompt_on_closed BOOLEAN NOT NULL DEFAULT 0,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL,
PRIMARY KEY (task_id, repository_id, pr_number)
);
CREATE TABLE IF NOT EXISTS github_task_ci_pr_state (
task_id TEXT NOT NULL,
repository_id TEXT NOT NULL DEFAULT '',
@@ -526,6 +545,9 @@ func (s *Store) initSchemaUpgrades() error {
if err := s.addTaskPRAgentAutomationColumns(); err != nil {
return err
}
if err := s.addPRScopeMigrationColumn(); err != nil {
return err
}
if err := s.addGitHubAuthFlowExpectationColumns(); err != nil {
return err
}
@@ -565,6 +587,9 @@ func (s *Store) initSchemaData(legacyUpgrade bool) error {
if err := s.backfillPRWatchesRepositoryID(); err != nil {
return fmt.Errorf("backfill github_pr_watches.repository_id: %w", err)
}
if err := s.migrateTaskCIOptionsToPRScope(); err != nil {
return fmt.Errorf("migrate task CI options to PR scope: %w", err)
}
if err := s.backfillGitHubWorkspaceOwnership(); err != nil {
return err
}
@@ -576,6 +601,83 @@ func (s *Store) initSchemaData(legacyUpgrade bool) error {
return nil
}
// migrateTaskCIOptionsToPRScope seeds github_task_pr_automation_options rows
// from each pre-upgrade github_task_ci_options row's legacy booleans, fanning
// each task's values out onto every github_task_prs row currently linked to
// it. Guarded by pr_scope_migrated_at, stamped in the same transaction as the
// fan-out insert: without the marker, replaying this on every boot would
// re-enable a switch a user has since turned off for one PR (R2), and a PR
// linked to the task after migration would incorrectly inherit the legacy
// value instead of starting all-off (AC17) via ON CONFLICT DO NOTHING alone.
func (s *Store) migrateTaskCIOptionsToPRScope() error {
type legacyOptions struct {
taskID string
autoFix, autoMerge, promptReview, promptMerged, promptClosed bool
}
rows, err := s.db.Query(`
SELECT task_id, auto_fix_enabled, auto_merge_enabled, prompt_on_review_requested,
prompt_on_merged, prompt_on_closed
FROM github_task_ci_options
WHERE pr_scope_migrated_at IS NULL`)
if err != nil {
return fmt.Errorf("list unmigrated task CI options: %w", err)
}
var legacy []legacyOptions
for rows.Next() {
var row legacyOptions
if err := rows.Scan(
&row.taskID, &row.autoFix, &row.autoMerge, &row.promptReview, &row.promptMerged, &row.promptClosed,
); err != nil {
_ = rows.Close()
return fmt.Errorf("scan unmigrated task CI options: %w", err)
}
legacy = append(legacy, row)
}
if err := rows.Err(); err != nil {
return fmt.Errorf("iterate unmigrated task CI options: %w", err)
}
if err := rows.Close(); err != nil {
return fmt.Errorf("close unmigrated task CI options rows: %w", err)
}
for _, row := range legacy {
if err := s.fanOutTaskCIOptionsToPRScope(
row.taskID, row.autoFix, row.autoMerge, row.promptReview, row.promptMerged, row.promptClosed,
); err != nil {
return err
}
}
return nil
}
func (s *Store) fanOutTaskCIOptionsToPRScope(
taskID string, autoFix, autoMerge, promptReview, promptMerged, promptClosed bool,
) error {
tx, err := s.db.Beginx()
if err != nil {
return err
}
defer func() { _ = tx.Rollback() }()
now := time.Now().UTC()
if _, err := tx.Exec(`
INSERT INTO github_task_pr_automation_options (
task_id, repository_id, pr_number, auto_fix_enabled, auto_merge_enabled,
prompt_on_review_requested, prompt_on_merged, prompt_on_closed, created_at, updated_at
)
SELECT task_id, repository_id, pr_number, ?, ?, ?, ?, ?, ?, ?
FROM github_task_prs
WHERE task_id = ? AND detached_at IS NULL
ON CONFLICT(task_id, repository_id, pr_number) DO NOTHING`,
autoFix, autoMerge, promptReview, promptMerged, promptClosed, now, now, taskID); err != nil {
return fmt.Errorf("fan out task CI options for %s: %w", taskID, err)
}
if _, err := tx.Exec(
`UPDATE github_task_ci_options SET pr_scope_migrated_at = ? WHERE task_id = ?`, now, taskID,
); err != nil {
return fmt.Errorf("stamp pr_scope_migrated_at for %s: %w", taskID, err)
}
return tx.Commit()
}
func (s *Store) clearLifecyclePromptOverrides() error {
_, err := s.db.Exec(`
UPDATE github_task_ci_options
@@ -1023,6 +1125,24 @@ func (s *Store) addTaskCIRoundColumns() error {
return nil
}
// addPRScopeMigrationColumn adds the marker column that guards the one-time
// fan-out of legacy task-level automation switches onto per-PR rows (see
// migrateTaskCIOptionsToPRScope). Column-precheck idiom, mirroring
// addTaskCIRoundColumns.
func (s *Store) addPRScopeMigrationColumn() error {
cols, err := s.tableColumns("github_task_ci_options")
if err != nil {
return fmt.Errorf("read github_task_ci_options columns: %w", err)
}
if _, ok := cols["pr_scope_migrated_at"]; ok {
return nil
}
if _, err := s.db.Exec(`ALTER TABLE github_task_ci_options ADD COLUMN pr_scope_migrated_at DATETIME`); err != nil {
return fmt.Errorf("add github_task_ci_options.pr_scope_migrated_at: %w", err)
}
return nil
}
// tableColumns returns the set of column names declared on `table`. Cheap
// SQLite PRAGMA lookup; used by addWatchSelfHealColumns to skip ALTERs on a
// fresh install whose createTablesSQL already includes the columns. Mirrors
@@ -1586,6 +1706,23 @@ func (s *Store) ListTaskPRsByTask(ctx context.Context, taskID string) ([]*TaskPR
return out, nil
}
// ListTaskPRsByTaskIncludingDetached returns every PR association for a task,
// including detached tombstones. Callers that expose active task surfaces
// should use ListTaskPRsByTask; this variant is for cleanup of state keyed by
// an association that may have been detached.
func (s *Store) ListTaskPRsByTaskIncludingDetached(ctx context.Context, taskID string) ([]*TaskPR, error) {
var prs []TaskPR
if err := s.ro.SelectContext(ctx, &prs,
`SELECT `+taskPRColumns+` FROM github_task_prs WHERE task_id = ? ORDER BY created_at ASC`, taskID); err != nil {
return nil, err
}
out := make([]*TaskPR, 0, len(prs))
for i := range prs {
out = append(out, &prs[i])
}
return out, nil
}
// DetachTaskPR marks an association as removed from active task surfaces while
// retaining the row so automatic PR discovery cannot silently resurrect it.
// The bool return reports whether this call performed the transition.
@@ -1871,20 +2008,69 @@ func (s *Store) mutateTaskCIPRState(
// UpdateTaskCIOptions applies a partial update to task CI automation options.
func (s *Store) UpdateTaskCIOptions(ctx context.Context, taskID string, patch TaskCIOptionsPatch) (*TaskCIOptions, error) {
writeCtx := context.WithoutCancel(ctx)
now := time.Now().UTC()
tx, err := s.db.BeginTxx(writeCtx, nil)
if err != nil {
return nil, err
}
defer func() { _ = tx.Rollback() }()
version, err := s.advanceTaskCIOptionsVersion(writeCtx, tx, taskID, now)
if err := s.updateTaskCIOptionsTx(writeCtx, tx, taskID, patch); err != nil {
return nil, err
}
if err := tx.Commit(); err != nil {
return nil, err
}
return s.GetTaskCIOptions(writeCtx, taskID)
}
// UpdateTaskCIOptionsWithPRAutomation applies a task update and all selected
// per-PR switch updates in one transaction. The service resolves and
// validates targets before calling this method, so a rejected identity cannot
// leave task-level fields or a subset of fan-out rows persisted.
func (s *Store) UpdateTaskCIOptionsWithPRAutomation(
ctx context.Context,
taskID string,
patch TaskCIOptionsPatch,
targets []*TaskPR,
prPatch TaskPRAutomationOptionsPatch,
reviewerChanged bool,
) (*TaskCIOptions, error) {
writeCtx := context.WithoutCancel(ctx)
tx, err := s.db.BeginTxx(writeCtx, nil)
if err != nil {
return nil, err
}
var previous TaskCIOptions
if err := tx.GetContext(writeCtx, &previous, `SELECT * FROM github_task_ci_options WHERE task_id = ?`, taskID); err != nil {
defer func() { _ = tx.Rollback() }()
if err := s.updateTaskCIOptionsTx(writeCtx, tx, taskID, patch); err != nil {
return nil, err
}
for _, target := range targets {
if target == nil {
continue
}
if err := s.updateTaskPRAutomationOptionsTx(
writeCtx, tx, taskID, target.RepositoryID, target.PRNumber, prPatch, reviewerChanged,
); err != nil {
return nil, err
}
}
if err := tx.Commit(); err != nil {
return nil, err
}
return s.GetTaskCIOptions(writeCtx, taskID)
}
func (s *Store) updateTaskCIOptionsTx(
ctx context.Context, tx *sqlx.Tx, taskID string, patch TaskCIOptionsPatch,
) error {
now := time.Now().UTC()
version, err := s.advanceTaskCIOptionsVersion(ctx, tx, taskID, now)
if err != nil {
return err
}
var previous TaskCIOptions
if err := tx.GetContext(ctx, &previous, `SELECT * FROM github_task_ci_options WHERE task_id = ?`, taskID); err != nil {
return err
}
autoFixSet, autoFixValue := boolPatchValue(patch.AutoFixEnabled)
autoMergeSet, autoMergeValue := boolPatchValue(patch.AutoMergeEnabled)
reviewSet, reviewValue := boolPatchValue(patch.PromptOnReviewRequested)
@@ -1896,7 +2082,7 @@ func (s *Store) UpdateTaskCIOptions(ctx context.Context, taskID string, patch Ta
reviewerChanged := reviewerLoginSet && !strings.EqualFold(
previous.ReviewReviewerLogin, normalizedString(patch.ReviewReviewerLogin),
)
if _, err := tx.ExecContext(writeCtx, `
if _, err := tx.ExecContext(ctx, `
UPDATE github_task_ci_options SET
auto_fix_enabled = CASE WHEN ? THEN ? ELSE auto_fix_enabled END,
auto_merge_enabled = CASE WHEN ? THEN ? ELSE auto_merge_enabled END,
@@ -1911,17 +2097,9 @@ func (s *Store) UpdateTaskCIOptions(ctx context.Context, taskID string, patch Ta
reviewSet, reviewValue, mergedSet, mergedValue, closedSet, closedValue,
reviewerLoginSet, normalizedString(patch.ReviewReviewerLogin),
version, taskID); err != nil {
return nil, err
return err
}
if err := applyTaskCIOptionResets(
writeCtx, tx, taskID, version, previous, patch, reviewerChanged,
); err != nil {
return nil, err
}
if err := tx.Commit(); err != nil {
return nil, err
}
return s.GetTaskCIOptions(writeCtx, taskID)
return applyTaskCIOptionResets(ctx, tx, taskID, version, previous, patch, reviewerChanged)
}
func applyTaskCIOptionResets(
@@ -1934,7 +2112,7 @@ func applyTaskCIOptionResets(
reviewerChanged bool,
) error {
if shouldResetAutoFix(patch.AutoFixEnabled, previous.AutoFixEnabled) {
if err := resetTaskCIAutoFixState(ctx, tx, taskID, now); err != nil {
if err := resetTaskCIAutoFixStateForTask(ctx, tx, taskID, now); err != nil {
return err
}
}
@@ -1949,29 +2127,17 @@ func applyTaskCIOptionResets(
}
}
if shouldResetTerminalPrompt(patch.PromptOnMerged, previous.PromptOnMerged) {
if err := resetTaskCITerminalCheckpoint(ctx, tx, taskID, "merged", now); err != nil {
if err := resetTaskCITerminalCheckpointForTask(ctx, tx, taskID, "merged", now); err != nil {
return err
}
}
if shouldResetTerminalPrompt(patch.PromptOnClosed, previous.PromptOnClosed) {
return resetTaskCITerminalCheckpoint(ctx, tx, taskID, "closed", now)
return resetTaskCITerminalCheckpointForTask(ctx, tx, taskID, "closed", now)
}
return nil
}
func shouldResetAutoFix(patchValue *bool, wasEnabled bool) bool {
return patchValue != nil && *patchValue && !wasEnabled
}
func shouldResetReviewRequests(patchValue *bool, wasEnabled, reviewerChanged bool) bool {
return patchValue != nil && *patchValue && (!wasEnabled || reviewerChanged)
}
func shouldResetTerminalPrompt(patchValue *bool, wasEnabled bool) bool {
return patchValue != nil && *patchValue && !wasEnabled
}
func resetTaskCIAutoFixState(
func resetTaskCIAutoFixStateForTask(
ctx context.Context,
tx *sqlx.Tx,
taskID string,
@@ -1991,7 +2157,7 @@ func resetTaskCIAutoFixState(
return err
}
func resetTaskCITerminalCheckpoint(
func resetTaskCITerminalCheckpointForTask(
ctx context.Context,
tx *sqlx.Tx,
taskID, state string,
@@ -2009,6 +2175,209 @@ func resetTaskCITerminalCheckpoint(
return err
}
// GetTaskPRAutomationOptions returns one PR's automation switches, or disabled defaults.
func (s *Store) GetTaskPRAutomationOptions(
ctx context.Context, taskID, repositoryID string, prNumber int,
) (*TaskPRAutomationOptions, error) {
var opts TaskPRAutomationOptions
err := s.ro.GetContext(ctx, &opts,
`SELECT * FROM github_task_pr_automation_options WHERE task_id = ? AND repository_id = ? AND pr_number = ?`,
taskID, repositoryID, prNumber)
if errors.Is(err, sql.ErrNoRows) {
now := time.Now().UTC()
return &TaskPRAutomationOptions{
TaskID: taskID, RepositoryID: repositoryID, PRNumber: prNumber,
CreatedAt: now, UpdatedAt: now,
}, nil
}
return &opts, err
}
// ListTaskPRAutomationOptions returns every stored per-PR automation row for a task.
func (s *Store) ListTaskPRAutomationOptions(ctx context.Context, taskID string) ([]*TaskPRAutomationOptions, error) {
var rows []TaskPRAutomationOptions
if err := s.ro.SelectContext(ctx, &rows,
`SELECT * FROM github_task_pr_automation_options WHERE task_id = ? ORDER BY repository_id ASC, pr_number ASC`,
taskID); err != nil {
return nil, err
}
out := make([]*TaskPRAutomationOptions, 0, len(rows))
for i := range rows {
out = append(out, &rows[i])
}
return out, nil
}
// UpdateTaskPRAutomationOptions applies a partial update to one PR's
// automation switches, upserting the row if absent. reviewerChanged mirrors
// the task-wide reviewer rebind: the caller resolves it once (comparing the
// patch's task-level ReviewReviewerLogin against the previously stored
// value) and passes it into every PR targeted by the same update, so a
// changed connected account re-baselines the review-request checkpoint even
// when the switch itself did not change value.
func (s *Store) UpdateTaskPRAutomationOptions(
ctx context.Context, taskID, repositoryID string, prNumber int,
patch TaskPRAutomationOptionsPatch, reviewerChanged bool,
) (*TaskPRAutomationOptions, error) {
writeCtx := context.WithoutCancel(ctx)
tx, err := s.db.BeginTxx(writeCtx, nil)
if err != nil {
return nil, err
}
defer func() { _ = tx.Rollback() }()
if err := s.updateTaskPRAutomationOptionsTx(
writeCtx, tx, taskID, repositoryID, prNumber, patch, reviewerChanged,
); err != nil {
return nil, err
}
if err := tx.Commit(); err != nil {
return nil, err
}
return s.GetTaskPRAutomationOptions(writeCtx, taskID, repositoryID, prNumber)
}
func (s *Store) updateTaskPRAutomationOptionsTx(
ctx context.Context,
tx *sqlx.Tx,
taskID, repositoryID string,
prNumber int,
patch TaskPRAutomationOptionsPatch,
reviewerChanged bool,
) error {
now := time.Now().UTC()
if _, err := tx.ExecContext(ctx, `
INSERT INTO github_task_pr_automation_options (
task_id, repository_id, pr_number, auto_fix_enabled, auto_merge_enabled,
prompt_on_review_requested, prompt_on_merged, prompt_on_closed, created_at, updated_at
) VALUES (?, ?, ?, 0, 0, 0, 0, 0, ?, ?)
ON CONFLICT(task_id, repository_id, pr_number) DO NOTHING`,
taskID, repositoryID, prNumber, now, now); err != nil {
return err
}
var previous TaskPRAutomationOptions
if err := tx.GetContext(ctx, &previous,
`SELECT * FROM github_task_pr_automation_options WHERE task_id = ? AND repository_id = ? AND pr_number = ?`,
taskID, repositoryID, prNumber); err != nil {
return err
}
autoFixSet, autoFixValue := boolPatchValue(patch.AutoFixEnabled)
autoMergeSet, autoMergeValue := boolPatchValue(patch.AutoMergeEnabled)
reviewSet, reviewValue := boolPatchValue(patch.PromptOnReviewRequested)
mergedSet, mergedValue := boolPatchValue(patch.PromptOnMerged)
closedSet, closedValue := boolPatchValue(patch.PromptOnClosed)
if _, err := tx.ExecContext(ctx, `
UPDATE github_task_pr_automation_options SET
auto_fix_enabled = CASE WHEN ? THEN ? ELSE auto_fix_enabled END,
auto_merge_enabled = CASE WHEN ? THEN ? ELSE auto_merge_enabled END,
prompt_on_review_requested = CASE WHEN ? THEN ? ELSE prompt_on_review_requested END,
prompt_on_merged = CASE WHEN ? THEN ? ELSE prompt_on_merged END,
prompt_on_closed = CASE WHEN ? THEN ? ELSE prompt_on_closed END,
updated_at = ?
WHERE task_id = ? AND repository_id = ? AND pr_number = ?`,
autoFixSet, autoFixValue, autoMergeSet, autoMergeValue,
reviewSet, reviewValue, mergedSet, mergedValue, closedSet, closedValue,
now, taskID, repositoryID, prNumber); err != nil {
return err
}
if err := applyTaskPRAutomationOptionResets(
ctx, tx, taskID, repositoryID, prNumber, now, previous, patch, reviewerChanged,
); err != nil {
return err
}
return nil
}
func applyTaskPRAutomationOptionResets(
ctx context.Context,
tx *sqlx.Tx,
taskID, repositoryID string,
prNumber int,
now time.Time,
previous TaskPRAutomationOptions,
patch TaskPRAutomationOptionsPatch,
reviewerChanged bool,
) error {
if shouldResetAutoFix(patch.AutoFixEnabled, previous.AutoFixEnabled) {
if err := resetTaskCIAutoFixState(ctx, tx, taskID, repositoryID, prNumber, now); err != nil {
return err
}
}
if shouldResetReviewRequests(
patch.PromptOnReviewRequested, previous.PromptOnReviewRequested, reviewerChanged,
) {
if _, err := tx.ExecContext(ctx, `
UPDATE github_task_ci_pr_state
SET review_request_initialized = 0, last_review_requested = 0, updated_at = ?
WHERE task_id = ? AND repository_id = ? AND pr_number = ?`,
now, taskID, repositoryID, prNumber); err != nil {
return err
}
}
if shouldResetTerminalPrompt(patch.PromptOnMerged, previous.PromptOnMerged) {
if err := resetTaskCITerminalCheckpoint(ctx, tx, taskID, repositoryID, prNumber, "merged", now); err != nil {
return err
}
}
if shouldResetTerminalPrompt(patch.PromptOnClosed, previous.PromptOnClosed) {
return resetTaskCITerminalCheckpoint(ctx, tx, taskID, repositoryID, prNumber, "closed", now)
}
return nil
}
func shouldResetAutoFix(patchValue *bool, wasEnabled bool) bool {
return patchValue != nil && *patchValue && !wasEnabled
}
func shouldResetReviewRequests(patchValue *bool, wasEnabled, reviewerChanged bool) bool {
return patchValue != nil && *patchValue && (!wasEnabled || reviewerChanged)
}
func shouldResetTerminalPrompt(patchValue *bool, wasEnabled bool) bool {
return patchValue != nil && *patchValue && !wasEnabled
}
func resetTaskCIAutoFixState(
ctx context.Context,
tx *sqlx.Tx,
taskID, repositoryID string,
prNumber int,
now time.Time,
) error {
_, err := tx.ExecContext(ctx, `
UPDATE github_task_ci_pr_state
SET auto_fix_round_count = 0,
last_fix_signature = '',
last_fix_checkpoint_json = '',
last_fix_enqueued_at = NULL,
last_fix_session_id = NULL,
last_error = CASE WHEN auto_fix_exhausted_at IS NOT NULL THEN NULL ELSE last_error END,
auto_fix_exhausted_at = NULL,
updated_at = ?
WHERE task_id = ? AND repository_id = ? AND pr_number = ?`, now, taskID, repositoryID, prNumber)
return err
}
func resetTaskCITerminalCheckpoint(
ctx context.Context,
tx *sqlx.Tx,
taskID, repositoryID string,
prNumber int,
state string,
now time.Time,
) error {
_, err := tx.ExecContext(ctx, `
UPDATE github_task_ci_pr_state
SET last_observed_pr_state = '',
last_lifecycle_event = '',
last_lifecycle_prompt_at = NULL,
last_lifecycle_session_id = NULL,
updated_at = ?
WHERE task_id = ? AND repository_id = ? AND pr_number = ?
AND (last_observed_pr_state = ? OR last_lifecycle_event = ?)`,
now, taskID, repositoryID, prNumber, state, state)
return err
}
// RebindTaskPRReviewer atomically updates the task's authenticated reviewer
// login and quietly resets only its review-request baselines when it changes.
func (s *Store) RebindTaskPRReviewer(ctx context.Context, taskID, login string) (bool, error) {
@@ -18,6 +18,7 @@ func TestStoreTaskPRAgentAutomationSchema(t *testing.T) {
"review_prompt_override",
"merged_prompt_override",
"closed_prompt_override",
"pr_scope_migrated_at",
},
"github_task_ci_pr_state": {
"review_request_initialized",
@@ -27,6 +28,18 @@ func TestStoreTaskPRAgentAutomationSchema(t *testing.T) {
"last_lifecycle_prompt_at",
"last_lifecycle_session_id",
},
"github_task_pr_automation_options": {
"task_id",
"repository_id",
"pr_number",
"auto_fix_enabled",
"auto_merge_enabled",
"prompt_on_review_requested",
"prompt_on_merged",
"prompt_on_closed",
"created_at",
"updated_at",
},
} {
got, err := store.tableColumns(table)
if err != nil {
@@ -40,6 +53,23 @@ func TestStoreTaskPRAgentAutomationSchema(t *testing.T) {
}
}
// TestStoreTaskPRAutomationOptionsSchemaReplay confirms initSchema can run
// twice against the same database without error — the fresh-DB CREATE TABLE
// and the idempotent ADD COLUMN/fan-out migration must both tolerate replay.
func TestStoreTaskPRAutomationOptionsSchemaReplay(t *testing.T) {
store := newTestStore(t)
if err := store.initSchema(false); err != nil {
t.Fatalf("replay schema migration: %v", err)
}
got, err := store.tableColumns("github_task_pr_automation_options")
if err != nil {
t.Fatalf("tableColumns: %v", err)
}
if _, ok := got["auto_fix_enabled"]; !ok {
t.Fatal("github_task_pr_automation_options.auto_fix_enabled is missing after replay")
}
}
func TestStoreTaskPRAgentAutomationMigrationClearsLifecyclePromptOverrides(t *testing.T) {
store := newTestStore(t)
ctx := context.Background()
@@ -197,15 +227,23 @@ func TestStoreRebindTaskPRReviewerQuietlyResetsReviewBaselines(t *testing.T) {
}
}
func TestStoreTaskCIOptionsReenableTerminalPromptResetsOnlyMatchingCheckpoint(t *testing.T) {
// TestStoreTaskPRAutomationOptionsReenableTerminalPromptResetsOnlyMatchingCheckpoint
// covers AC11/AC12-adjacent PR-scoping: re-enabling the merged-prompt switch
// on repo-merged/1 must reset only that PR's checkpoint, not repo-closed/2's
// — both because the reset predicate is keyed by observed state ("merged"
// vs "closed") and because it is now scoped to the specific PR.
func TestStoreTaskPRAutomationOptionsReenableTerminalPromptResetsOnlyMatchingCheckpoint(t *testing.T) {
store := newTestStore(t)
ctx := context.Background()
enabled := true
disabled := false
if _, err := store.UpdateTaskCIOptions(ctx, "task-1", TaskCIOptionsPatch{
PromptOnMerged: &enabled, PromptOnClosed: &enabled,
}); err != nil {
t.Fatalf("enable terminal prompts: %v", err)
if _, err := store.UpdateTaskPRAutomationOptions(ctx, "task-1", "repo-merged", 1,
TaskPRAutomationOptionsPatch{PromptOnMerged: &enabled}, false); err != nil {
t.Fatalf("enable merged prompt for repo-merged/1: %v", err)
}
if _, err := store.UpdateTaskPRAutomationOptions(ctx, "task-1", "repo-closed", 2,
TaskPRAutomationOptionsPatch{PromptOnClosed: &enabled}, false); err != nil {
t.Fatalf("enable closed prompt for repo-closed/2: %v", err)
}
for _, prompt := range []TaskPRLifecyclePrompt{
{TaskID: "task-1", RepositoryID: "repo-merged", PRNumber: 1, Event: "merged", ObservedState: "merged"},
@@ -215,10 +253,12 @@ func TestStoreTaskCIOptionsReenableTerminalPromptResetsOnlyMatchingCheckpoint(t
t.Fatalf("seed terminal checkpoint: %v", err)
}
}
if _, err := store.UpdateTaskCIOptions(ctx, "task-1", TaskCIOptionsPatch{PromptOnMerged: &disabled}); err != nil {
if _, err := store.UpdateTaskPRAutomationOptions(ctx, "task-1", "repo-merged", 1,
TaskPRAutomationOptionsPatch{PromptOnMerged: &disabled}, false); err != nil {
t.Fatalf("disable merged prompt: %v", err)
}
if _, err := store.UpdateTaskCIOptions(ctx, "task-1", TaskCIOptionsPatch{PromptOnMerged: &enabled}); err != nil {
if _, err := store.UpdateTaskPRAutomationOptions(ctx, "task-1", "repo-merged", 1,
TaskPRAutomationOptionsPatch{PromptOnMerged: &enabled}, false); err != nil {
t.Fatalf("re-enable merged prompt: %v", err)
}
@@ -234,10 +274,14 @@ func TestStoreTaskCIOptionsReenableTerminalPromptResetsOnlyMatchingCheckpoint(t
t.Fatalf("get closed state: %v", err)
}
if closed.LastObservedPRState != "closed" || closed.LastLifecycleEvent != "closed" {
t.Fatalf("closed checkpoint changed while re-enabling merged: %+v", closed)
t.Fatalf("closed checkpoint changed while re-enabling merged on a different PR: %+v", closed)
}
}
// TestStoreTaskCIOptions_DefaultAndUpdate covers the genuinely task-level
// fields still owned by github_task_ci_options: AutoFixPromptOverride. The
// five automation switches moved to per-PR scope — see
// TestStoreTaskPRAutomationOptions_DefaultAndUpdate.
func TestStoreTaskCIOptions_DefaultAndUpdate(t *testing.T) {
store := newTestStore(t)
ctx := context.Background()
@@ -249,37 +293,65 @@ func TestStoreTaskCIOptions_DefaultAndUpdate(t *testing.T) {
if got.TaskID != "task-1" {
t.Fatalf("TaskID=%q, want task-1", got.TaskID)
}
if got.AutoFixEnabled || got.AutoMergeEnabled {
t.Fatalf("default options should be disabled, got %+v", got)
}
if got.AutoFixPromptOverride != nil {
t.Fatalf("default prompt override should be nil, got %q", *got.AutoFixPromptOverride)
}
override := "Fix only the new CI feedback."
updated, err := store.UpdateTaskCIOptions(ctx, "task-1", TaskCIOptionsPatch{
AutoFixEnabled: boolPtr(true),
AutoFixPromptOverride: &override,
})
if err != nil {
t.Fatalf("update options: %v", err)
}
if updated.AutoFixPromptOverride == nil || *updated.AutoFixPromptOverride != override {
t.Fatalf("override=%v, want %q", updated.AutoFixPromptOverride, override)
}
clearOverride := ""
updated, err = store.UpdateTaskCIOptions(ctx, "task-1", TaskCIOptionsPatch{
AutoFixPromptOverride: &clearOverride,
})
if err != nil {
t.Fatalf("second update options: %v", err)
}
if updated.AutoFixPromptOverride != nil {
t.Fatalf("override should be cleared, got %q", *updated.AutoFixPromptOverride)
}
}
// TestStoreTaskPRAutomationOptions_DefaultAndUpdate covers the per-PR
// automation switches, keyed by (task_id, repository_id, pr_number).
func TestStoreTaskPRAutomationOptions_DefaultAndUpdate(t *testing.T) {
store := newTestStore(t)
ctx := context.Background()
got, err := store.GetTaskPRAutomationOptions(ctx, "task-1", "repo-1", 1)
if err != nil {
t.Fatalf("get default options: %v", err)
}
if got.TaskID != "task-1" || got.RepositoryID != "repo-1" || got.PRNumber != 1 {
t.Fatalf("identity = %+v, want task-1/repo-1/1", got)
}
if got.AutoFixEnabled || got.AutoMergeEnabled {
t.Fatalf("default options should be disabled, got %+v", got)
}
updated, err := store.UpdateTaskPRAutomationOptions(ctx, "task-1", "repo-1", 1,
TaskPRAutomationOptionsPatch{AutoFixEnabled: boolPtr(true)}, false)
if err != nil {
t.Fatalf("update options: %v", err)
}
if !updated.AutoFixEnabled {
t.Fatalf("AutoFixEnabled=false, want true")
}
if updated.AutoMergeEnabled {
t.Fatalf("AutoMergeEnabled=true, want unchanged default false")
}
if updated.AutoFixPromptOverride == nil || *updated.AutoFixPromptOverride != override {
t.Fatalf("override=%v, want %q", updated.AutoFixPromptOverride, override)
}
enableMerge := true
clearOverride := ""
updated, err = store.UpdateTaskCIOptions(ctx, "task-1", TaskCIOptionsPatch{
AutoMergeEnabled: &enableMerge,
AutoFixPromptOverride: &clearOverride,
})
updated, err = store.UpdateTaskPRAutomationOptions(ctx, "task-1", "repo-1", 1,
TaskPRAutomationOptionsPatch{AutoMergeEnabled: &enableMerge}, false)
if err != nil {
t.Fatalf("second update options: %v", err)
}
@@ -289,8 +361,23 @@ func TestStoreTaskCIOptions_DefaultAndUpdate(t *testing.T) {
if !updated.AutoMergeEnabled {
t.Fatalf("AutoMergeEnabled=false, want true")
}
if updated.AutoFixPromptOverride != nil {
t.Fatalf("override should be cleared, got %q", *updated.AutoFixPromptOverride)
// A different PR on the same task starts independently disabled (AC1/AC2).
other, err := store.GetTaskPRAutomationOptions(ctx, "task-1", "repo-1", 2)
if err != nil {
t.Fatalf("get other PR options: %v", err)
}
if other.AutoFixEnabled || other.AutoMergeEnabled {
t.Fatalf("other PR should be independently disabled, got %+v", other)
}
// Same PR number in a different repository is independent (AC4).
otherRepo, err := store.GetTaskPRAutomationOptions(ctx, "task-1", "repo-2", 1)
if err != nil {
t.Fatalf("get other repo options: %v", err)
}
if otherRepo.AutoFixEnabled || otherRepo.AutoMergeEnabled {
t.Fatalf("same PR number in a different repo should be independent, got %+v", otherRepo)
}
}
@@ -408,11 +495,13 @@ func TestStoreTaskCIPRState_MarkExhaustedAndResetOnReenable(t *testing.T) {
}
disabled := false
if _, err := store.UpdateTaskCIOptions(ctx, "task-1", TaskCIOptionsPatch{AutoFixEnabled: &disabled}); err != nil {
if _, err := store.UpdateTaskPRAutomationOptions(ctx, "task-1", "repo-1", 42,
TaskPRAutomationOptionsPatch{AutoFixEnabled: &disabled}, false); err != nil {
t.Fatalf("disable auto-fix: %v", err)
}
enabled := true
if _, err := store.UpdateTaskCIOptions(ctx, "task-1", TaskCIOptionsPatch{AutoFixEnabled: &enabled}); err != nil {
if _, err := store.UpdateTaskPRAutomationOptions(ctx, "task-1", "repo-1", 42,
TaskPRAutomationOptionsPatch{AutoFixEnabled: &enabled}, false); err != nil {
t.Fatalf("re-enable auto-fix: %v", err)
}
state, err = store.GetTaskCIPRState(ctx, "task-1", "repo-1", 42)
@@ -462,4 +551,204 @@ func TestStoreTaskCIPRState_RefreshCheckpointClearsPromptDispatchMetadata(t *tes
}
}
// seedLegacyTaskCIOptions inserts a pre-migration github_task_ci_options row
// directly, bypassing UpdateTaskCIOptions (which no longer writes the five
// legacy boolean columns), to simulate a database from before per-PR scoping.
func seedLegacyTaskCIOptions(t *testing.T, store *Store, taskID string, autoFix, autoMerge bool) {
t.Helper()
now := time.Now().UTC()
if _, err := store.db.Exec(`
INSERT INTO github_task_ci_options (task_id, auto_fix_enabled, auto_merge_enabled, created_at, updated_at)
VALUES (?, ?, ?, ?, ?)`,
taskID, autoFix, autoMerge, now, now); err != nil {
t.Fatalf("seed legacy task CI options: %v", err)
}
}
// TestStoreMigrateTaskCIOptionsToPRScope_FansOutToLinkedPRs covers AC14: a
// pre-upgrade task row with two linked PRs yields, after one boot, two
// per-PR rows each matching the legacy booleans.
func TestStoreMigrateTaskCIOptionsToPRScope_FansOutToLinkedPRs(t *testing.T) {
store := newTestStore(t)
ctx := context.Background()
now := time.Now().UTC()
seedLegacyTaskCIOptions(t, store, "task-1", true, false)
if err := store.CreateTaskPR(ctx, &TaskPR{
TaskID: "task-1", RepositoryID: "repo-1", Owner: "o", Repo: "r", PRNumber: 1, CreatedAt: now,
}); err != nil {
t.Fatalf("seed PR 1: %v", err)
}
if err := store.CreateTaskPR(ctx, &TaskPR{
TaskID: "task-1", RepositoryID: "repo-1", Owner: "o", Repo: "r", PRNumber: 2, CreatedAt: now,
}); err != nil {
t.Fatalf("seed PR 2: %v", err)
}
if err := store.initSchema(false); err != nil {
t.Fatalf("replay schema migration: %v", err)
}
for _, prNumber := range []int{1, 2} {
opts, err := store.GetTaskPRAutomationOptions(ctx, "task-1", "repo-1", prNumber)
if err != nil {
t.Fatalf("get PR %d options: %v", prNumber, err)
}
if !opts.AutoFixEnabled || opts.AutoMergeEnabled {
t.Fatalf("PR %d options = %+v, want auto_fix_enabled=true auto_merge_enabled=false", prNumber, opts)
}
}
migrated, err := store.GetTaskCIOptions(ctx, "task-1")
if err != nil {
t.Fatalf("get task options: %v", err)
}
if migrated.PRScopeMigratedAt == nil {
t.Fatal("pr_scope_migrated_at was not stamped")
}
}
func TestStoreMigrateTaskCIOptionsToPRScope_SkipsDetachedPRs(t *testing.T) {
store := newTestStore(t)
ctx := context.Background()
now := time.Now().UTC()
seedLegacyTaskCIOptions(t, store, "task-1", true, true)
active := &TaskPR{
TaskID: "task-1", RepositoryID: "repo-1", Owner: "o", Repo: "r", PRNumber: 1, CreatedAt: now,
}
detached := &TaskPR{
TaskID: "task-1", RepositoryID: "repo-1", Owner: "o", Repo: "r", PRNumber: 2, CreatedAt: now.Add(time.Second),
}
for _, pr := range []*TaskPR{active, detached} {
if err := store.CreateTaskPR(ctx, pr); err != nil {
t.Fatalf("seed PR #%d: %v", pr.PRNumber, err)
}
}
if _, transitioned, err := store.DetachTaskPR(ctx, detached.ID); err != nil || !transitioned {
t.Fatalf("detach PR #%d: transitioned=%v err=%v", detached.PRNumber, transitioned, err)
}
if err := store.initSchema(false); err != nil {
t.Fatalf("replay schema migration: %v", err)
}
activeOptions, err := store.GetTaskPRAutomationOptions(ctx, "task-1", "repo-1", active.PRNumber)
if err != nil {
t.Fatalf("get active PR options: %v", err)
}
if !activeOptions.AutoFixEnabled || !activeOptions.AutoMergeEnabled {
t.Fatalf("active PR options = %+v, want legacy switches enabled", activeOptions)
}
detachedOptions, err := store.GetTaskPRAutomationOptions(ctx, "task-1", "repo-1", detached.PRNumber)
if err != nil {
t.Fatalf("get detached PR options: %v", err)
}
if detachedOptions.AutoFixEnabled || detachedOptions.AutoMergeEnabled {
t.Fatalf("detached PR inherited legacy switches: %+v", detachedOptions)
}
}
// TestStoreMigrateTaskCIOptionsToPRScope_Idempotent covers AC15: replaying
// the migration on an already-migrated database changes no per-PR row.
func TestStoreMigrateTaskCIOptionsToPRScope_Idempotent(t *testing.T) {
store := newTestStore(t)
ctx := context.Background()
now := time.Now().UTC()
seedLegacyTaskCIOptions(t, store, "task-1", true, false)
if err := store.CreateTaskPR(ctx, &TaskPR{
TaskID: "task-1", RepositoryID: "repo-1", Owner: "o", Repo: "r", PRNumber: 1, CreatedAt: now,
}); err != nil {
t.Fatalf("seed PR: %v", err)
}
if err := store.initSchema(false); err != nil {
t.Fatalf("first replay: %v", err)
}
before, err := store.GetTaskPRAutomationOptions(ctx, "task-1", "repo-1", 1)
if err != nil {
t.Fatalf("get options after first replay: %v", err)
}
if err := store.initSchema(false); err != nil {
t.Fatalf("second replay: %v", err)
}
after, err := store.GetTaskPRAutomationOptions(ctx, "task-1", "repo-1", 1)
if err != nil {
t.Fatalf("get options after second replay: %v", err)
}
if !after.UpdatedAt.Equal(before.UpdatedAt) {
t.Fatalf("updated_at changed on replay: before=%v after=%v", before.UpdatedAt, after.UpdatedAt)
}
}
// TestStoreMigrateTaskCIOptionsToPRScope_DoesNotReenableUserDisabled covers
// AC16: once migrated, a user's deliberate per-PR disable must survive a
// later boot even though the stale legacy row still says "enabled".
func TestStoreMigrateTaskCIOptionsToPRScope_DoesNotReenableUserDisabled(t *testing.T) {
store := newTestStore(t)
ctx := context.Background()
now := time.Now().UTC()
seedLegacyTaskCIOptions(t, store, "task-1", true, false)
if err := store.CreateTaskPR(ctx, &TaskPR{
TaskID: "task-1", RepositoryID: "repo-1", Owner: "o", Repo: "r", PRNumber: 1, CreatedAt: now,
}); err != nil {
t.Fatalf("seed PR: %v", err)
}
if err := store.initSchema(false); err != nil {
t.Fatalf("first boot migration: %v", err)
}
disabled := false
if _, err := store.UpdateTaskPRAutomationOptions(ctx, "task-1", "repo-1", 1,
TaskPRAutomationOptionsPatch{AutoFixEnabled: &disabled}, false); err != nil {
t.Fatalf("user disables auto-fix: %v", err)
}
if err := store.initSchema(false); err != nil {
t.Fatalf("second boot: %v", err)
}
opts, err := store.GetTaskPRAutomationOptions(ctx, "task-1", "repo-1", 1)
if err != nil {
t.Fatalf("get options: %v", err)
}
if opts.AutoFixEnabled {
t.Fatal("auto-fix was re-enabled by a replayed migration after the user turned it off")
}
}
// TestStoreMigrateTaskCIOptionsToPRScope_NewlyLinkedPRStartsAllOff covers
// AC17: a PR linked to the task after migration has already run starts with
// all five switches off rather than inheriting the stale legacy value.
func TestStoreMigrateTaskCIOptionsToPRScope_NewlyLinkedPRStartsAllOff(t *testing.T) {
store := newTestStore(t)
ctx := context.Background()
now := time.Now().UTC()
seedLegacyTaskCIOptions(t, store, "task-1", true, true)
if err := store.CreateTaskPR(ctx, &TaskPR{
TaskID: "task-1", RepositoryID: "repo-1", Owner: "o", Repo: "r", PRNumber: 1, CreatedAt: now,
}); err != nil {
t.Fatalf("seed PR 1: %v", err)
}
if err := store.initSchema(false); err != nil {
t.Fatalf("boot migration: %v", err)
}
// PR 2 links to the task only after the fan-out migration already ran.
if err := store.CreateTaskPR(ctx, &TaskPR{
TaskID: "task-1", RepositoryID: "repo-1", Owner: "o", Repo: "r", PRNumber: 2, CreatedAt: now,
}); err != nil {
t.Fatalf("seed PR 2: %v", err)
}
opts, err := store.GetTaskPRAutomationOptions(ctx, "task-1", "repo-1", 2)
if err != nil {
t.Fatalf("get options: %v", err)
}
if opts.AutoFixEnabled || opts.AutoMergeEnabled {
t.Fatalf("newly linked PR should start all-off, got %+v", opts)
}
}
func boolPtr(v bool) *bool { return &v }
@@ -3,6 +3,7 @@ package handlers
import (
"context"
"encoding/json"
"errors"
"github.com/kandev/kandev/internal/events"
"github.com/kandev/kandev/internal/events/bus"
@@ -53,6 +54,8 @@ func (h *Handlers) handleUpdateTaskPRAutomation(ctx context.Context, msg *ws.Mes
}
var req struct {
TaskID string `json:"task_id"`
RepositoryID *string `json:"repository_id"`
PRNumber *int `json:"pr_number"`
AutoFixEnabled *bool `json:"auto_fix_enabled"`
AutoMergeEnabled *bool `json:"auto_merge_enabled"`
AutoFixPromptOverride *string `json:"auto_fix_prompt_override"`
@@ -67,6 +70,8 @@ func (h *Handlers) handleUpdateTaskPRAutomation(ctx context.Context, msg *ws.Mes
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "task_id is required", nil)
}
patch := github.TaskCIOptionsPatch{
RepositoryID: req.RepositoryID,
PRNumber: req.PRNumber,
AutoFixEnabled: req.AutoFixEnabled,
AutoMergeEnabled: req.AutoMergeEnabled,
AutoFixPromptOverride: req.AutoFixPromptOverride,
@@ -82,6 +87,9 @@ func (h *Handlers) handleUpdateTaskPRAutomation(ctx context.Context, msg *ws.Mes
}
options, err := h.taskPRAutomation.UpdateTaskCIOptions(ctx, req.TaskID, patch)
if err != nil {
if errors.Is(err, github.ErrTaskPRNotLinked) {
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, err.Error(), nil)
}
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to update PR automation options: "+err.Error(), nil)
}
if h.eventBus != nil {
@@ -27,6 +27,96 @@ func (s *recordingTaskPRAutomationService) UpdateTaskCIOptions(
return &github.TaskCIOptionsResponse{}, nil
}
// recordingTaskPRAutomationServiceWithErr optionally returns a fixed error
// from UpdateTaskCIOptions, for exercising error-code mapping.
type recordingTaskPRAutomationServiceWithErr struct {
recordingTaskPRAutomationService
err error
}
func (s *recordingTaskPRAutomationServiceWithErr) UpdateTaskCIOptions(
ctx context.Context, taskID string, patch github.TaskCIOptionsPatch,
) (*github.TaskCIOptionsResponse, error) {
if s.err != nil {
s.calls++
s.patch = patch
return nil, s.err
}
return s.recordingTaskPRAutomationService.UpdateTaskCIOptions(ctx, taskID, patch)
}
// TestHandleUpdateTaskPRAutomationOmittedIdentityFansOut covers AC23: no
// repository_id/pr_number in the payload leaves both nil on the patch, which
// the service treats as a fan-out to every linked PR (unchanged behavior for
// agents written before per-PR scoping).
func TestHandleUpdateTaskPRAutomationOmittedIdentityFansOut(t *testing.T) {
automation := &recordingTaskPRAutomationService{}
h := &Handlers{taskPRAutomation: automation, logger: testLogger(t).WithFields()}
msg := makeWSMessage(t, ws.ActionMCPUpdateTaskPRAutomation, map[string]any{
"task_id": "task-current",
"auto_fix_enabled": true,
})
response, err := h.handleUpdateTaskPRAutomation(context.Background(), msg)
require.NoError(t, err)
assert.Equal(t, ws.MessageTypeResponse, response.Type)
assert.Equal(t, 1, automation.calls)
assert.Nil(t, automation.patch.RepositoryID)
assert.Nil(t, automation.patch.PRNumber)
}
// TestHandleUpdateTaskPRAutomationWithIdentityTargetsOnePR covers AC24: a
// payload naming repository_id/pr_number reaches the service as PR identity
// on the patch, targeting one linked PR only.
func TestHandleUpdateTaskPRAutomationWithIdentityTargetsOnePR(t *testing.T) {
automation := &recordingTaskPRAutomationService{}
h := &Handlers{taskPRAutomation: automation, logger: testLogger(t).WithFields()}
msg := makeWSMessage(t, ws.ActionMCPUpdateTaskPRAutomation, map[string]any{
"task_id": "task-current",
"repository_id": "repo-1",
"pr_number": 42,
"auto_merge_enabled": true,
})
response, err := h.handleUpdateTaskPRAutomation(context.Background(), msg)
require.NoError(t, err)
assert.Equal(t, ws.MessageTypeResponse, response.Type)
require.NotNil(t, automation.patch.RepositoryID)
assert.Equal(t, "repo-1", *automation.patch.RepositoryID)
require.NotNil(t, automation.patch.PRNumber)
assert.Equal(t, 42, *automation.patch.PRNumber)
}
// TestHandleUpdateTaskPRAutomationMapsUnlinkedPRToValidationError covers the
// MCP-side error mapping for ErrTaskPRNotLinked (HTTP's AC8 equivalent).
func TestHandleUpdateTaskPRAutomationMapsUnlinkedPRToValidationError(t *testing.T) {
for name, identity := range map[string]map[string]any{
"repository only": {"repository_id": "repo-1"},
"PR number only": {"pr_number": 999},
} {
t.Run(name, func(t *testing.T) {
automation := &recordingTaskPRAutomationServiceWithErr{err: github.ErrTaskPRNotLinked}
h := &Handlers{taskPRAutomation: automation, logger: testLogger(t).WithFields()}
payload := map[string]any{
"task_id": "task-current",
"auto_fix_enabled": true,
}
for key, value := range identity {
payload[key] = value
}
msg := makeWSMessage(t, ws.ActionMCPUpdateTaskPRAutomation, payload)
response, err := h.handleUpdateTaskPRAutomation(context.Background(), msg)
require.NoError(t, err)
assert.Equal(t, ws.MessageTypeError, response.Type)
assert.Contains(t, string(response.Payload), "PR is not linked to this task")
})
}
}
func TestHandleUpdateTaskPRAutomationRejectsLifecyclePromptOverrides(t *testing.T) {
automation := &recordingTaskPRAutomationService{}
h := &Handlers{taskPRAutomation: automation, logger: testLogger(t).WithFields()}
+15 -3
View File
@@ -838,17 +838,29 @@ If the child has no live execution, the call succeeds idempotently with status="
func (s *Server) registerPRAutomationTools() {
s.mcpServer.AddTool(
mcp.NewToolWithRawSchema("get_task_pr_automation_kandev",
"Get the current task's GitHub PR automation settings, including lifecycle notification switches.",
"Get the current task's GitHub PR automation settings, including lifecycle notification switches. "+
"The five automation switches are scoped per linked PR; pr_options carries one entry per PR "+
"(repository_id, pr_number, and the five booleans). The top-level booleans are an aggregate "+
"that reports true only when every linked PR has that switch on and at least one PR is linked "+
"— use them to check whether a task-wide enable fully took, and use pr_options for anything "+
"PR-specific.",
json.RawMessage(`{"type":"object","properties":{}}`),
),
s.wrapHandler("get_task_pr_automation_kandev", s.getTaskPRAutomationHandler()),
)
s.mcpServer.AddTool(
mcp.NewTool("update_task_pr_automation_kandev",
mcp.WithDescription("Update this task's PR automation options (auto-fix, auto-merge, and lifecycle notifications)."),
mcp.WithDescription(
"Update this task's PR automation options (auto-fix, auto-merge, and lifecycle notifications). "+
"The five switches are scoped per linked PR: pass both repository_id and pr_number to target "+
"one linked PR, or omit both to apply the change to every PR currently linked to the task "+
"(unchanged default behavior). auto_fix_prompt_override applies task-wide regardless of PR identity.",
),
mcp.WithString("repository_id", mcp.Description("Target one linked PR's repository_id; must be paired with pr_number. Omit both to apply to every linked PR.")),
mcp.WithNumber("pr_number", mcp.Description("Target one linked PR's number; must be paired with repository_id. Omit both to apply to every linked PR.")),
mcp.WithBoolean("auto_fix_enabled", mcp.Description("Enable or disable auto-fix when CI checks fail")),
mcp.WithBoolean("auto_merge_enabled", mcp.Description("Enable or disable auto-merge when PR passes all checks")),
mcp.WithString("auto_fix_prompt_override", mcp.Description("Custom prompt for auto-fix (empty string clears the override)")),
mcp.WithString("auto_fix_prompt_override", mcp.Description("Custom prompt for auto-fix (empty string clears the override). Task-wide; not affected by repository_id/pr_number.")),
mcp.WithBoolean("prompt_on_review_requested", mcp.Description("Prompt this task's agent when a review is requested for the authenticated user")),
mcp.WithBoolean("prompt_on_merged", mcp.Description("Prompt this task's agent once when the linked PR becomes merged")),
mcp.WithBoolean("prompt_on_closed", mcp.Description("Prompt this task's agent once when the linked PR becomes closed without merge")),
@@ -201,9 +201,7 @@ func (s *Service) handleTaskPRUpdated(ctx context.Context, event *bus.Event) err
func (s *Service) handleTaskCIOptionsUpdated(ctx context.Context, event *bus.Event) error {
options, ok := event.Data.(*github.TaskCIOptionsResponse)
if !ok || options == nil || event.Source == ciAutomationStateEventSource ||
(!options.AutoFixEnabled && !options.AutoMergeEnabled &&
!options.PromptOnReviewRequested && !options.PromptOnMerged && !options.PromptOnClosed) ||
s.githubService == nil {
!anyTaskPRAutomationEnabled(options) || s.githubService == nil {
return nil
}
detachedCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), ciAutomationDetachedTimeout)
@@ -219,6 +217,34 @@ func (s *Service) handleTaskCIOptionsUpdated(ctx context.Context, event *bus.Eve
return nil
}
// anyTaskPRAutomationEnabled reports whether any linked PR has at least one
// automation switch on. Per-PR scoping means the task-wide aggregate on
// options can be false (mixed configuration across PRs) while individual
// PRs still need this update's PR sync — so this checks the per-PR array
// rather than the aggregated top-level booleans. Falls back to the top-level
// booleans when PROptions is empty (e.g. a caller that built the response by
// hand without per-PR data), matching resolvePRScopedCIOptions's same
// graceful-degradation pattern rather than silently swallowing the event.
func anyTaskPRAutomationEnabled(options *github.TaskCIOptionsResponse) bool {
if options == nil {
return false
}
if len(options.PROptions) == 0 {
return options.AutoFixEnabled || options.AutoMergeEnabled ||
options.PromptOnReviewRequested || options.PromptOnMerged || options.PromptOnClosed
}
for _, opt := range options.PROptions {
if opt == nil {
continue
}
if opt.AutoFixEnabled || opt.AutoMergeEnabled ||
opt.PromptOnReviewRequested || opt.PromptOnMerged || opt.PromptOnClosed {
return true
}
}
return false
}
func (s *Service) recordTaskCIOptionsSyncError(ctx context.Context, taskID string, synced []*github.TaskPR, syncErr error) {
syncedKeys := make(map[ciAutomationTaskPRSyncKey]struct{}, len(synced))
for _, pr := range synced {
@@ -79,6 +79,7 @@ func (s *Service) handleTaskPRCIAutomationWithRefresh(ctx context.Context, pr *g
s.logger.Debug("load CI automation options failed", zap.String("task_id", pr.TaskID), zap.Error(err))
return nil
}
options = resolvePRScopedCIOptions(options, pr)
freshlySynced := ciAutomationHasFreshPRStatus(pr)
if refresh && (options.AutoFixEnabled || options.AutoMergeEnabled) {
refreshed, synced, syncErr := s.refreshTaskPRForCIAutomation(ctx, pr)
@@ -116,6 +117,30 @@ func (s *Service) handleTaskPRCIAutomationWithRefresh(ctx context.Context, pr *g
return nil
}
// resolvePRScopedCIOptions overlays this PR's own automation switches onto a
// copy of the task-scoped response, so the auto-fix, auto-merge, and
// lifecycle-prompt automation below acts on this PR's per-PR configuration
// instead of the task-wide aggregate. Task-level fields (reviewer login,
// effective prompts, prompt override) are left as returned.
func resolvePRScopedCIOptions(options *github.TaskCIOptionsResponse, pr *github.TaskPR) *github.TaskCIOptionsResponse {
if options == nil || pr == nil {
return options
}
scoped := *options
for _, opt := range options.PROptions {
if opt == nil || opt.RepositoryID != pr.RepositoryID || opt.PRNumber != pr.PRNumber {
continue
}
scoped.AutoFixEnabled = opt.AutoFixEnabled
scoped.AutoMergeEnabled = opt.AutoMergeEnabled
scoped.PromptOnReviewRequested = opt.PromptOnReviewRequested
scoped.PromptOnMerged = opt.PromptOnMerged
scoped.PromptOnClosed = opt.PromptOnClosed
break
}
return &scoped
}
func (s *Service) handleTaskPRLifecycleAutomation(ctx context.Context, pr *github.TaskPR, options *github.TaskCIOptionsResponse) {
if !options.PromptOnReviewRequested && !options.PromptOnMerged && !options.PromptOnClosed {
return
@@ -0,0 +1,107 @@
package orchestrator
import (
"testing"
"github.com/kandev/kandev/internal/github"
)
func TestResolvePRScopedCIOptions(t *testing.T) {
override := "task prompt"
options := &github.TaskCIOptionsResponse{
TaskID: "task-1",
AutoFixEnabled: true,
AutoMergeEnabled: true,
PromptOnReviewRequested: true,
PromptOnMerged: true,
PromptOnClosed: true,
ReviewReviewerLogin: "reviewer",
AutoFixPromptOverride: &override,
EffectiveAutoFixPrompt: "effective prompt",
PROptions: []*github.TaskPRAutomationOptions{
{
RepositoryID: "repo-1", PRNumber: 1,
AutoFixEnabled: false, AutoMergeEnabled: false,
PromptOnReviewRequested: false, PromptOnMerged: false, PromptOnClosed: false,
},
{
RepositoryID: "repo-2", PRNumber: 2,
AutoFixEnabled: true, AutoMergeEnabled: false,
PromptOnReviewRequested: true, PromptOnMerged: false, PromptOnClosed: true,
},
},
}
pr := &github.TaskPR{TaskID: "task-1", RepositoryID: "repo-1", PRNumber: 1}
got := resolvePRScopedCIOptions(options, pr)
if got == options {
t.Fatal("resolver returned the input response instead of a scoped copy")
}
if got.AutoFixEnabled || got.AutoMergeEnabled || got.PromptOnReviewRequested || got.PromptOnMerged || got.PromptOnClosed {
t.Fatalf("scoped switches = %+v, want PR #1 values", got)
}
if got.ReviewReviewerLogin != options.ReviewReviewerLogin ||
got.AutoFixPromptOverride != options.AutoFixPromptOverride ||
got.EffectiveAutoFixPrompt != options.EffectiveAutoFixPrompt {
t.Fatalf("task-level fields changed during scoping: got=%+v want=%+v", got, options)
}
missing := resolvePRScopedCIOptions(options, &github.TaskPR{TaskID: "task-1", RepositoryID: "repo-3", PRNumber: 3})
if !missing.AutoFixEnabled || !missing.AutoMergeEnabled || !missing.PromptOnReviewRequested || !missing.PromptOnMerged || !missing.PromptOnClosed {
t.Fatal("missing PR row did not preserve the task aggregate fallback")
}
withNil := *options
withNil.PROptions = append([]*github.TaskPRAutomationOptions{nil}, options.PROptions...)
if scoped := resolvePRScopedCIOptions(&withNil, &github.TaskPR{RepositoryID: "repo-2", PRNumber: 2}); !scoped.AutoFixEnabled {
t.Fatal("nil PR option entry prevented matching row resolution")
}
if resolvePRScopedCIOptions(nil, pr) != nil || resolvePRScopedCIOptions(options, nil) != options {
t.Fatal("nil input handling changed")
}
}
func TestAnyTaskPRAutomationEnabled(t *testing.T) {
for _, test := range []struct {
name string
options *github.TaskCIOptionsResponse
want bool
}{
{
name: "mixed per PR options",
options: &github.TaskCIOptionsResponse{PROptions: []*github.TaskPRAutomationOptions{
{RepositoryID: "repo-1", PRNumber: 1},
{RepositoryID: "repo-2", PRNumber: 2, AutoMergeEnabled: true},
}},
want: true,
},
{
name: "all off",
options: &github.TaskCIOptionsResponse{PROptions: []*github.TaskPRAutomationOptions{
{RepositoryID: "repo-1", PRNumber: 1},
{RepositoryID: "repo-2", PRNumber: 2},
}},
want: false,
},
{
name: "empty per PR options falls back to aggregate",
options: &github.TaskCIOptionsResponse{AutoFixEnabled: true},
want: true,
},
{
name: "nil entry is skipped",
options: &github.TaskCIOptionsResponse{PROptions: []*github.TaskPRAutomationOptions{nil}},
want: false,
},
{
name: "nil response",
options: nil,
want: false,
},
} {
t.Run(test.name, func(t *testing.T) {
if got := anyTaskPRAutomationEnabled(test.options); got != test.want {
t.Fatalf("anyTaskPRAutomationEnabled() = %v, want %v", got, test.want)
}
})
}
}
@@ -1,522 +1,19 @@
"use client";
import { useCallback, useEffect, useState, type ReactNode } from "react";
import { IconChevronDown, IconEdit, IconInfoCircle, IconRefresh } from "@tabler/icons-react";
import { Button } from "@kandev/ui/button";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@kandev/ui/collapsible";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@kandev/ui/dialog";
import { Label } from "@kandev/ui/label";
import { Popover, PopoverContent, PopoverTrigger } from "@kandev/ui/popover";
import { Switch } from "@kandev/ui/switch";
import { Textarea } from "@kandev/ui/textarea";
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
import { useCallback, useState } from "react";
import { useToast } from "@/components/toast-provider";
import { useTaskCIAutomationOptions } from "@/hooks/domains/github/use-task-ci-options";
import { useResponsiveBreakpoint } from "@/hooks/use-responsive-breakpoint";
import { autoFixRoundForState, findCIAutomationStateForPR } from "@/lib/github/ci-automation";
import type {
TaskCIAutomationOptions,
TaskCIAutomationPatch,
TaskCIPRAutomationState,
TaskPR,
} from "@/lib/types/github";
import { Trans, useTranslation } from "react-i18next";
const PR_FEEDBACK_PLACEHOLDER = "{{pr.feedback}}";
function CIAutomationInfoButton() {
const { t } = useTranslation();
return (
<Tooltip>
<TooltipTrigger asChild>
<Button
type="button"
variant="ghost"
size="icon"
className="h-6 w-6 cursor-help text-muted-foreground hover:text-foreground"
aria-label={t("github:explainCiAutomationOptions")}
>
<IconInfoCircle className="h-3.5 w-3.5" />
</Button>
</TooltipTrigger>
<TooltipContent side="top" align="end" className="max-w-[280px] text-xs leading-relaxed">
{t("github:watchesThisTaskSLinkedPull")}
</TooltipContent>
</Tooltip>
);
}
function insertPRFeedbackPlaceholder(prompt: string) {
if (prompt.includes(PR_FEEDBACK_PLACEHOLDER)) return prompt;
const trimmedEnd = prompt.trimEnd();
if (!trimmedEnd) return PR_FEEDBACK_PLACEHOLDER;
return `${trimmedEnd}\n\n${PR_FEEDBACK_PLACEHOLDER}`;
}
function CIAutomationPromptDialog({
open,
prompt,
saving,
onPromptChange,
onClose,
onSave,
onReset,
}: {
open: boolean;
prompt: string;
saving: boolean;
onPromptChange: (value: string) => void;
onClose: () => void;
onSave: () => void;
onReset: () => void;
}) {
const { t } = useTranslation();
const trimmed = prompt.trim();
return (
<Dialog open={open} onOpenChange={(next) => !next && onClose()}>
<DialogContent className="sm:max-w-2xl">
<DialogHeader>
<DialogTitle>{t("github:autoFixPrompt")}</DialogTitle>
<DialogDescription>
<Trans
i18nKey="github:autoFixPromptDescription"
values={{ placeholder: PR_FEEDBACK_PLACEHOLDER }}
>
<code
data-testid="ci-auto-fix-pr-feedback-placeholder"
className="rounded bg-muted px-1 py-0.5 text-[11px]"
/>
</Trans>
</DialogDescription>
</DialogHeader>
<div className="flex flex-col gap-3">
<div className="flex flex-wrap items-center justify-between gap-2">
<Label htmlFor="task-ci-auto-fix-prompt" className="text-xs">
{t("github:taskAutoFixPrompt")}
</Label>
<div className="flex shrink-0 flex-wrap items-center justify-end gap-2">
<Button
type="button"
variant="ghost"
size="sm"
className="h-7 cursor-pointer px-2 text-xs"
onClick={() => onPromptChange(insertPRFeedbackPlaceholder(prompt))}
>
{t("github:insertPrFeedback")}
</Button>
<a
href="/settings/prompts"
className="cursor-pointer text-xs text-primary hover:underline"
onClick={(e) => e.stopPropagation()}
>
{t("github:editDefaultPrompt")}
</a>
</div>
</div>
<div
data-testid="ci-auto-fix-pr-feedback-help"
className="rounded-md border border-border/70 bg-muted/30 p-3 text-xs leading-relaxed text-muted-foreground"
>
<p>{t("github:thePlaceholderInsertsTheCurrentPr")}</p>
<p className="mt-2">{t("github:omitThePlaceholderIfYouWant")}</p>
</div>
<Textarea
id="task-ci-auto-fix-prompt"
value={prompt}
onChange={(event) => onPromptChange(event.target.value)}
rows={10}
className="max-h-[50vh] min-h-48 resize-y font-mono text-xs"
/>
</div>
<DialogFooter>
<Button variant="ghost" className="cursor-pointer" disabled={saving} onClick={onClose}>
{t("common:cancel")}
</Button>
<Button variant="outline" className="cursor-pointer" disabled={saving} onClick={onReset}>
{t("github:useDefault")}
</Button>
<Button
className="cursor-pointer"
disabled={saving || trimmed.length === 0}
onClick={onSave}
>
{t("github:savePrompt")}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
function CIAutomationRow({
id,
label,
checked,
disabled,
onCheckedChange,
help,
describedBy,
}: {
id: string;
label: string;
checked: boolean;
disabled: boolean;
onCheckedChange: (checked: boolean) => void;
help?: ReactNode;
describedBy?: string;
}) {
const { isFinePointer, isMobile } = useResponsiveBreakpoint();
const minHeight = isMobile || !isFinePointer ? "min-h-11" : "min-h-7";
return (
<div className={`flex items-center justify-between gap-3 px-1 ${minHeight}`}>
<div className="flex min-w-0 flex-1 items-center gap-1.5">
<Label htmlFor={id} className="min-w-0 cursor-pointer text-xs leading-5">
{label}
</Label>
{help}
</div>
<Switch
id={id}
aria-label={label}
aria-describedby={describedBy}
checked={checked}
disabled={disabled}
onCheckedChange={onCheckedChange}
/>
</div>
);
}
function CIAutomationErrorRow({
error,
loading,
onRetry,
}: {
error: string;
loading: boolean;
onRetry: () => void;
}) {
const { t } = useTranslation();
return (
<div
role="alert"
className="flex items-center justify-between gap-2 px-1 text-[11px] text-destructive"
>
<span className="min-w-0 flex-1 truncate">{error}</span>
<Button
type="button"
variant="ghost"
size="sm"
className="h-6 cursor-pointer gap-1 px-2 text-[11px]"
disabled={loading}
onClick={onRetry}
>
<IconRefresh className={`h-3 w-3 ${loading ? "animate-spin" : ""}`} />
{t("github:retry")}
</Button>
</div>
);
}
function CIAutomationHelpButton({
ariaLabel,
testId,
children,
}: {
ariaLabel: string;
testId: string;
children: ReactNode;
}) {
const { isFinePointer } = useResponsiveBreakpoint();
const [open, setOpen] = useState(false);
const trigger = (
<Button
type="button"
variant="ghost"
size="icon"
data-testid={testId}
className="h-5 w-5 cursor-help text-muted-foreground hover:text-foreground"
aria-label={ariaLabel}
>
<IconInfoCircle className="h-3.5 w-3.5" />
</Button>
);
if (!isFinePointer) {
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>{trigger}</PopoverTrigger>
<PopoverContent
side="top"
align="start"
portal={false}
className="max-w-[280px] text-xs leading-relaxed"
>
{children}
</PopoverContent>
</Popover>
);
}
return (
<Tooltip>
<TooltipTrigger asChild>{trigger}</TooltipTrigger>
<TooltipContent side="top" align="start" className="max-w-[280px] text-xs leading-relaxed">
{children}
</TooltipContent>
</Tooltip>
);
}
function CIAutoFixRoundHelpButton({
state,
maxRounds,
}: {
state: TaskCIPRAutomationState | undefined;
maxRounds: number | null | undefined;
}) {
const { t } = useTranslation();
const round = autoFixRoundForState(state, maxRounds);
return (
<CIAutomationHelpButton
testId="ci-auto-fix-round-help"
ariaLabel={t("github:explainAutoFixRounds")}
>
<span data-testid="ci-auto-fix-round-explanation">
{t("github:autoFixRoundExplanation", { current: round.current, max: round.max })}
</span>
</CIAutomationHelpButton>
);
}
function PRAgentPromptRows({
taskId,
options,
disabled,
patchOption,
}: {
taskId: string;
options: TaskCIAutomationOptions | null;
disabled: boolean;
patchOption: (patch: TaskCIAutomationPatch) => void;
}) {
const { t } = useTranslation();
const terminalHelpID = `task-pr-terminal-help-${taskId}`;
const terminalHelp = "Wake the agent when review work ends. Choose either or both outcomes.";
return (
<>
<ReviewRequestedPromptRow
taskId={taskId}
options={options}
disabled={disabled}
patchOption={patchOption}
/>
<span id={terminalHelpID} className="sr-only">
{terminalHelp}
</span>
<CIAutomationRow
id={`task-pr-merged-prompt-${taskId}`}
label={t("github:prMerged")}
describedBy={terminalHelpID}
checked={Boolean(options?.prompt_on_merged)}
disabled={disabled}
onCheckedChange={(checked) => patchOption({ prompt_on_merged: checked })}
help={
<CIAutomationHelpButton
testId="ci-pr-terminal-help"
ariaLabel={t("github:explainFinalPrStateNotifications")}
>
{terminalHelp}
</CIAutomationHelpButton>
}
/>
<CIAutomationRow
id={`task-pr-closed-prompt-${taskId}`}
label={t("github:prClosedWithoutMerging")}
describedBy={terminalHelpID}
checked={Boolean(options?.prompt_on_closed)}
disabled={disabled}
onCheckedChange={(checked) => patchOption({ prompt_on_closed: checked })}
/>
</>
);
}
function PREventsSection({
taskId,
options,
disabled,
patchOption,
}: {
taskId: string;
options: TaskCIAutomationOptions | null;
disabled: boolean;
patchOption: (patch: TaskCIAutomationPatch) => void;
}) {
const { t } = useTranslation();
const { isFinePointer, isMobile } = useResponsiveBreakpoint();
const [open, setOpen] = useState(false);
const lifecycleEnabled = Boolean(
options?.prompt_on_review_requested || options?.prompt_on_merged || options?.prompt_on_closed,
);
const minHeight = isMobile || !isFinePointer ? "min-h-11" : "min-h-7";
useEffect(() => {
if (lifecycleEnabled) setOpen(true);
}, [lifecycleEnabled]);
return (
<Collapsible open={open} onOpenChange={setOpen}>
<CollapsibleTrigger asChild>
<Button
type="button"
variant="ghost"
size="sm"
data-testid="ci-pr-events-trigger"
data-legacy-testid="ci-review-follow-up-trigger"
aria-label={t("github:togglePrEventPromptAutomation")}
className={`w-full cursor-pointer justify-between px-1 text-xs text-muted-foreground ${minHeight}`}
>
{t("github:prEvents")}
<IconChevronDown
aria-hidden="true"
className={`h-3.5 w-3.5 transition-transform ${open ? "rotate-180" : ""}`}
/>
</Button>
</CollapsibleTrigger>
<CollapsibleContent className="flex flex-col gap-1">
<PRAgentPromptRows
taskId={taskId}
options={options}
disabled={disabled}
patchOption={patchOption}
/>
</CollapsibleContent>
</Collapsible>
);
}
function ReviewRequestedPromptRow({
taskId,
options,
disabled,
patchOption,
}: {
taskId: string;
options: TaskCIAutomationOptions | null;
disabled: boolean;
patchOption: (patch: TaskCIAutomationPatch) => void;
}) {
const { t } = useTranslation();
const helpID = `task-pr-review-requested-prompt-${taskId}-description`;
const help = "Wake the agent for any new request, including re-review after changes.";
return (
<>
<span id={helpID} className="sr-only">
{help}
</span>
<CIAutomationRow
id={`task-pr-review-requested-prompt-${taskId}`}
label={t("github:yourReviewIsRequested")}
describedBy={helpID}
checked={Boolean(options?.prompt_on_review_requested)}
disabled={disabled}
onCheckedChange={(checked) => patchOption({ prompt_on_review_requested: checked })}
help={
<CIAutomationHelpButton
testId="ci-review-requested-help"
ariaLabel={t("github:explainReviewRequestNotifications")}
>
{help}
</CIAutomationHelpButton>
}
/>
</>
);
}
function CIAutomationHeader({
disabled,
onEditPrompt,
}: {
disabled: boolean;
onEditPrompt: () => void;
}) {
const { t } = useTranslation();
return (
<div className="flex items-center justify-between gap-2 px-1">
<div className="text-xs font-medium text-foreground">{t("github:automation")}</div>
<div className="flex items-center gap-1">
<CIAutomationInfoButton />
<Button
type="button"
variant="ghost"
size="icon"
className="h-6 w-6 cursor-pointer text-muted-foreground hover:text-foreground"
aria-label={t("github:editAutoFixPromptForThis")}
disabled={disabled}
onClick={onEditPrompt}
>
<IconEdit className="h-3.5 w-3.5" />
</Button>
</div>
</div>
);
}
function CIAutomationOptionRows({
pr,
options,
disabled,
patchOption,
automationState,
}: {
pr: TaskPR;
options: TaskCIAutomationOptions | null;
disabled: boolean;
patchOption: (patch: TaskCIAutomationPatch) => void;
automationState: TaskCIPRAutomationState | undefined;
}) {
const { t } = useTranslation();
return (
<>
<CIAutomationRow
id={`task-ci-auto-fix-${pr.task_id}`}
label={t("github:autoFixCiAndAddressComments")}
checked={Boolean(options?.auto_fix_enabled)}
disabled={disabled}
onCheckedChange={(checked) => patchOption({ auto_fix_enabled: checked })}
help={
options?.auto_fix_enabled ? (
<CIAutoFixRoundHelpButton
state={automationState}
maxRounds={options.auto_fix_max_rounds}
/>
) : null
}
/>
<CIAutomationRow
id={`task-ci-auto-merge-${pr.task_id}`}
label={t("github:autoMergeWhenReady")}
checked={Boolean(options?.auto_merge_enabled)}
disabled={disabled}
onCheckedChange={(checked) => patchOption({ auto_merge_enabled: checked })}
/>
<PREventsSection
taskId={pr.task_id}
options={options}
disabled={disabled}
patchOption={patchOption}
/>
</>
);
}
import {
findCIAutomationStateForPR,
findPRAutomationOptionsForPR,
} from "@/lib/github/ci-automation";
import type { TaskCIAutomationPatch, TaskPR } from "@/lib/types/github";
import { CIAutomationPromptDialog } from "@/components/github/pr-ci-automation-prompt-dialog";
import {
CIAutomationErrorRow,
CIAutomationHeader,
CIAutomationOptionRows,
} from "@/components/github/pr-ci-automation-rows";
export function PRCIAutomationControls({ pr }: { pr: TaskPR }) {
const { options, loading, saving, error, refresh, update, resetPrompt } =
@@ -525,6 +22,7 @@ export function PRCIAutomationControls({ pr }: { pr: TaskPR }) {
const [promptOpen, setPromptOpen] = useState(false);
const [promptDraft, setPromptDraft] = useState("");
const automationState = findCIAutomationStateForPR(options?.pr_states, pr);
const prOptions = findPRAutomationOptionsForPR(options?.pr_options, pr);
const openPromptEditor = useCallback(() => {
setPromptDraft(options?.auto_fix_prompt_override ?? options?.effective_auto_fix_prompt ?? "");
@@ -538,13 +36,23 @@ export function PRCIAutomationControls({ pr }: { pr: TaskPR }) {
[toast],
);
// The five automation switches are scoped to this PR; every patch from the
// switch rows below carries this PR's identity so the backend applies it
// to this PR only instead of fanning out to every linked PR.
const patchOption = useCallback(
(patch: TaskCIAutomationPatch) => {
Promise.resolve(update(patch)).catch(() => reportError("Failed to update CI automation."));
const scoped: TaskCIAutomationPatch = {
...patch,
repository_id: pr.repository_id ?? "",
pr_number: pr.pr_number,
};
Promise.resolve(update(scoped)).catch(() => reportError("Failed to update CI automation."));
},
[reportError, update],
[pr, reportError, update],
);
// The auto-fix prompt override stays task-level (applies to every linked
// PR), so this patch intentionally omits PR identity.
const savePrompt = useCallback(() => {
const value = promptDraft.trim();
if (!value) return;
@@ -569,10 +77,11 @@ export function PRCIAutomationControls({ pr }: { pr: TaskPR }) {
data-testid="pr-ci-automation-controls"
className="flex flex-col gap-1 border-t border-border/50 pt-2"
>
<CIAutomationHeader disabled={!options} onEditPrompt={openPromptEditor} />
<CIAutomationHeader pr={pr} disabled={!options} onEditPrompt={openPromptEditor} />
<CIAutomationOptionRows
pr={pr}
options={options}
prOptions={prOptions}
autoFixMaxRounds={options?.auto_fix_max_rounds}
disabled={disabled}
patchOption={patchOption}
automationState={automationState}
@@ -0,0 +1,124 @@
"use client";
import { Button } from "@kandev/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@kandev/ui/dialog";
import { Label } from "@kandev/ui/label";
import { Textarea } from "@kandev/ui/textarea";
import AppLink from "@/components/routing/app-link";
import { Trans, useTranslation } from "react-i18next";
const PR_FEEDBACK_PLACEHOLDER = "{{pr.feedback}}";
function insertPRFeedbackPlaceholder(prompt: string) {
if (prompt.includes(PR_FEEDBACK_PLACEHOLDER)) return prompt;
const trimmedEnd = prompt.trimEnd();
if (!trimmedEnd) return PR_FEEDBACK_PLACEHOLDER;
return `${trimmedEnd}\n\n${PR_FEEDBACK_PLACEHOLDER}`;
}
/**
* Auto-fix prompt override editor. This override remains task-level (it
* applies to every linked PR's auto-fix prompt) even though the auto-fix
* enable/disable switch itself is now per-PR.
*/
export function CIAutomationPromptDialog({
open,
prompt,
saving,
onPromptChange,
onClose,
onSave,
onReset,
}: {
open: boolean;
prompt: string;
saving: boolean;
onPromptChange: (value: string) => void;
onClose: () => void;
onSave: () => void;
onReset: () => void;
}) {
const { t } = useTranslation();
const trimmed = prompt.trim();
return (
<Dialog open={open} onOpenChange={(next) => !next && onClose()}>
<DialogContent className="sm:max-w-2xl">
<DialogHeader>
<DialogTitle>{t("github:autoFixPrompt")}</DialogTitle>
<DialogDescription>
<Trans
i18nKey="github:autoFixPromptDescription"
values={{ placeholder: PR_FEEDBACK_PLACEHOLDER }}
>
<code
data-testid="ci-auto-fix-pr-feedback-placeholder"
className="rounded bg-muted px-1 py-0.5 text-[11px]"
/>
</Trans>
</DialogDescription>
</DialogHeader>
<div className="flex flex-col gap-3">
<div className="flex flex-wrap items-center justify-between gap-2">
<Label htmlFor="task-ci-auto-fix-prompt" className="text-xs">
{t("github:taskAutoFixPrompt")}
</Label>
<div className="flex shrink-0 flex-wrap items-center justify-end gap-2">
<Button
type="button"
variant="ghost"
size="sm"
className="h-7 cursor-pointer px-2 text-xs"
onClick={() => onPromptChange(insertPRFeedbackPlaceholder(prompt))}
>
{t("github:insertPrFeedback")}
</Button>
<AppLink
href="/settings/prompts"
className="cursor-pointer text-xs text-primary hover:underline"
onClick={(e) => e.stopPropagation()}
>
{t("github:editDefaultPrompt")}
</AppLink>
</div>
</div>
<div
data-testid="ci-auto-fix-pr-feedback-help"
className="rounded-md border border-border/70 bg-muted/30 p-3 text-xs leading-relaxed text-muted-foreground"
>
<p>{t("github:thePlaceholderInsertsTheCurrentPr")}</p>
<p className="mt-2">{t("github:omitThePlaceholderIfYouWant")}</p>
</div>
<Textarea
id="task-ci-auto-fix-prompt"
value={prompt}
onChange={(event) => onPromptChange(event.target.value)}
rows={10}
className="max-h-[50vh] min-h-48 resize-y font-mono text-xs"
/>
</div>
<DialogFooter>
<Button variant="ghost" className="cursor-pointer" disabled={saving} onClick={onClose}>
{t("common:cancel")}
</Button>
<Button variant="outline" className="cursor-pointer" disabled={saving} onClick={onReset}>
{t("github:useDefault")}
</Button>
<Button
className="cursor-pointer"
disabled={saving || trimmed.length === 0}
onClick={onSave}
>
{t("github:savePrompt")}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,419 @@
"use client";
import { useEffect, useState, type ReactNode } from "react";
import { IconChevronDown, IconEdit, IconInfoCircle, IconRefresh } from "@tabler/icons-react";
import { Button } from "@kandev/ui/button";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@kandev/ui/collapsible";
import { Label } from "@kandev/ui/label";
import { Popover, PopoverContent, PopoverTrigger } from "@kandev/ui/popover";
import { Switch } from "@kandev/ui/switch";
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
import { useResponsiveBreakpoint } from "@/hooks/use-responsive-breakpoint";
import { autoFixRoundForState } from "@/lib/github/ci-automation";
import type {
TaskCIAutomationPatch,
TaskCIPRAutomationState,
TaskPR,
TaskPRAutomationOptions,
} from "@/lib/types/github";
import { useTranslation } from "react-i18next";
/**
* Element-id scope unique per (task, repository, PR) so simultaneously
* mounted PR tabs in MultiPRCIPopover never share a Switch id/htmlFor pair.
*/
export function prAutomationScopeKey(pr: TaskPR): string {
return `${pr.task_id}-${pr.repository_id ?? "none"}-${pr.pr_number}`;
}
export function CIAutomationInfoButton() {
const { t } = useTranslation();
return (
<Tooltip>
<TooltipTrigger asChild>
<Button
type="button"
variant="ghost"
size="icon"
className="h-6 w-6 cursor-help text-muted-foreground hover:text-foreground"
aria-label={t("github:explainCiAutomationOptions")}
>
<IconInfoCircle className="h-3.5 w-3.5" />
</Button>
</TooltipTrigger>
<TooltipContent side="top" align="end" className="max-w-[280px] text-xs leading-relaxed">
{t("github:watchesThisTaskSLinkedPull")}
</TooltipContent>
</Tooltip>
);
}
export function CIAutomationRow({
id,
label,
checked,
disabled,
onCheckedChange,
help,
describedBy,
}: {
id: string;
label: string;
checked: boolean;
disabled: boolean;
onCheckedChange: (checked: boolean) => void;
help?: ReactNode;
describedBy?: string;
}) {
const { isFinePointer, isMobile } = useResponsiveBreakpoint();
const minHeight = isMobile || !isFinePointer ? "min-h-11" : "min-h-7";
return (
<div className={`flex items-center justify-between gap-3 px-1 ${minHeight}`}>
<div className="flex min-w-0 flex-1 items-center gap-1.5">
<Label htmlFor={id} className="min-w-0 cursor-pointer text-xs leading-5">
{label}
</Label>
{help}
</div>
<Switch
id={id}
aria-label={label}
aria-describedby={describedBy}
checked={checked}
disabled={disabled}
onCheckedChange={onCheckedChange}
/>
</div>
);
}
export function CIAutomationErrorRow({
error,
loading,
onRetry,
}: {
error: string;
loading: boolean;
onRetry: () => void;
}) {
const { t } = useTranslation();
return (
<div
role="alert"
className="flex items-center justify-between gap-2 px-1 text-[11px] text-destructive"
>
<span className="min-w-0 flex-1 truncate">{error}</span>
<Button
type="button"
variant="ghost"
size="sm"
className="h-6 cursor-pointer gap-1 px-2 text-[11px]"
disabled={loading}
onClick={onRetry}
>
<IconRefresh className={`h-3 w-3 ${loading ? "animate-spin" : ""}`} />
{t("github:retry")}
</Button>
</div>
);
}
export function CIAutomationHelpButton({
ariaLabel,
testId,
children,
}: {
ariaLabel: string;
testId: string;
children: ReactNode;
}) {
const { isFinePointer } = useResponsiveBreakpoint();
const [open, setOpen] = useState(false);
const trigger = (
<Button
type="button"
variant="ghost"
size="icon"
data-testid={testId}
className="h-5 w-5 cursor-help text-muted-foreground hover:text-foreground"
aria-label={ariaLabel}
>
<IconInfoCircle className="h-3.5 w-3.5" />
</Button>
);
if (!isFinePointer) {
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>{trigger}</PopoverTrigger>
<PopoverContent
side="top"
align="start"
portal={false}
className="max-w-[280px] text-xs leading-relaxed"
>
{children}
</PopoverContent>
</Popover>
);
}
return (
<Tooltip>
<TooltipTrigger asChild>{trigger}</TooltipTrigger>
<TooltipContent side="top" align="start" className="max-w-[280px] text-xs leading-relaxed">
{children}
</TooltipContent>
</Tooltip>
);
}
function CIAutoFixRoundHelpButton({
state,
maxRounds,
}: {
state: TaskCIPRAutomationState | undefined;
maxRounds: number | null | undefined;
}) {
const { t } = useTranslation();
const round = autoFixRoundForState(state, maxRounds);
return (
<CIAutomationHelpButton
testId="ci-auto-fix-round-help"
ariaLabel={t("github:explainAutoFixRounds")}
>
<span data-testid="ci-auto-fix-round-explanation">
{t("github:autoFixRoundExplanation", { current: round.current, max: round.max })}
</span>
</CIAutomationHelpButton>
);
}
function PRAgentPromptRows({
scopeKey,
prOptions,
disabled,
patchOption,
}: {
scopeKey: string;
prOptions: TaskPRAutomationOptions;
disabled: boolean;
patchOption: (patch: TaskCIAutomationPatch) => void;
}) {
const { t } = useTranslation();
const terminalHelpID = `task-pr-terminal-help-${scopeKey}`;
const terminalHelp = t("github:wakeAgentOnTerminalPrState");
return (
<>
<ReviewRequestedPromptRow
scopeKey={scopeKey}
prOptions={prOptions}
disabled={disabled}
patchOption={patchOption}
/>
<span id={terminalHelpID} className="sr-only">
{terminalHelp}
</span>
<CIAutomationRow
id={`task-pr-merged-prompt-${scopeKey}`}
label={t("github:prMerged")}
describedBy={terminalHelpID}
checked={prOptions.prompt_on_merged}
disabled={disabled}
onCheckedChange={(checked) => patchOption({ prompt_on_merged: checked })}
help={
<CIAutomationHelpButton
testId="ci-pr-terminal-help"
ariaLabel={t("github:explainFinalPrStateNotifications")}
>
{terminalHelp}
</CIAutomationHelpButton>
}
/>
<CIAutomationRow
id={`task-pr-closed-prompt-${scopeKey}`}
label={t("github:prClosedWithoutMerging")}
describedBy={terminalHelpID}
checked={prOptions.prompt_on_closed}
disabled={disabled}
onCheckedChange={(checked) => patchOption({ prompt_on_closed: checked })}
/>
</>
);
}
export function ReviewFollowUpSection({
scopeKey,
prOptions,
disabled,
patchOption,
}: {
scopeKey: string;
prOptions: TaskPRAutomationOptions;
disabled: boolean;
patchOption: (patch: TaskCIAutomationPatch) => void;
}) {
const { t } = useTranslation();
const { isFinePointer, isMobile } = useResponsiveBreakpoint();
const [open, setOpen] = useState(false);
const lifecycleEnabled =
prOptions.prompt_on_review_requested ||
prOptions.prompt_on_merged ||
prOptions.prompt_on_closed;
const minHeight = isMobile || !isFinePointer ? "min-h-11" : "min-h-7";
useEffect(() => {
if (lifecycleEnabled) setOpen(true);
}, [lifecycleEnabled]);
return (
<Collapsible open={open} onOpenChange={setOpen}>
<CollapsibleTrigger asChild>
<Button
type="button"
variant="ghost"
size="sm"
data-testid="ci-review-follow-up-trigger"
aria-label={t("github:toggleReviewFollowUpAutomation")}
className={`w-full cursor-pointer justify-between px-1 text-xs text-muted-foreground ${minHeight}`}
>
{t("github:reviewFollowUp")}
<IconChevronDown
aria-hidden="true"
className={`h-3.5 w-3.5 transition-transform ${open ? "rotate-180" : ""}`}
/>
</Button>
</CollapsibleTrigger>
<CollapsibleContent className="flex flex-col gap-1">
<PRAgentPromptRows
scopeKey={scopeKey}
prOptions={prOptions}
disabled={disabled}
patchOption={patchOption}
/>
</CollapsibleContent>
</Collapsible>
);
}
function ReviewRequestedPromptRow({
scopeKey,
prOptions,
disabled,
patchOption,
}: {
scopeKey: string;
prOptions: TaskPRAutomationOptions;
disabled: boolean;
patchOption: (patch: TaskCIAutomationPatch) => void;
}) {
const { t } = useTranslation();
const helpID = `task-pr-review-requested-prompt-${scopeKey}-description`;
const help = t("github:wakeAgentOnReviewRequest");
return (
<>
<span id={helpID} className="sr-only">
{help}
</span>
<CIAutomationRow
id={`task-pr-review-requested-prompt-${scopeKey}`}
label={t("github:yourReviewIsRequested")}
describedBy={helpID}
checked={prOptions.prompt_on_review_requested}
disabled={disabled}
onCheckedChange={(checked) => patchOption({ prompt_on_review_requested: checked })}
help={
<CIAutomationHelpButton
testId="ci-review-requested-help"
ariaLabel={t("github:explainReviewRequestNotifications")}
>
{help}
</CIAutomationHelpButton>
}
/>
</>
);
}
export function CIAutomationHeader({
pr,
disabled,
onEditPrompt,
}: {
pr: TaskPR;
disabled: boolean;
onEditPrompt: () => void;
}) {
const { t } = useTranslation();
return (
<div className="flex items-center justify-between gap-2 px-1">
<div className="flex min-w-0 flex-col">
<div className="text-xs font-medium text-foreground">{t("github:automation")}</div>
<div className="truncate text-[11px] text-muted-foreground">
{t("github:automationForPr", { number: pr.pr_number })}
</div>
</div>
<div className="flex shrink-0 items-center gap-1">
<CIAutomationInfoButton />
<Button
type="button"
variant="ghost"
size="icon"
className="h-6 w-6 cursor-pointer text-muted-foreground hover:text-foreground"
aria-label={t("github:editAutoFixPromptForThis")}
disabled={disabled}
onClick={onEditPrompt}
>
<IconEdit className="h-3.5 w-3.5" />
</Button>
</div>
</div>
);
}
export function CIAutomationOptionRows({
pr,
prOptions,
autoFixMaxRounds,
disabled,
patchOption,
automationState,
}: {
pr: TaskPR;
prOptions: TaskPRAutomationOptions;
autoFixMaxRounds: number | null | undefined;
disabled: boolean;
patchOption: (patch: TaskCIAutomationPatch) => void;
automationState: TaskCIPRAutomationState | undefined;
}) {
const { t } = useTranslation();
const scopeKey = prAutomationScopeKey(pr);
return (
<>
<CIAutomationRow
id={`task-ci-auto-fix-${scopeKey}`}
label={t("github:autoFixCiAndAddressComments")}
checked={prOptions.auto_fix_enabled}
disabled={disabled}
onCheckedChange={(checked) => patchOption({ auto_fix_enabled: checked })}
help={
prOptions.auto_fix_enabled ? (
<CIAutoFixRoundHelpButton state={automationState} maxRounds={autoFixMaxRounds} />
) : null
}
/>
<CIAutomationRow
id={`task-ci-auto-merge-${scopeKey}`}
label={t("github:autoMergeWhenReady")}
checked={prOptions.auto_merge_enabled}
disabled={disabled}
onCheckedChange={(checked) => patchOption({ auto_merge_enabled: checked })}
/>
<ReviewFollowUpSection
scopeKey={scopeKey}
prOptions={prOptions}
disabled={disabled}
patchOption={patchOption}
/>
</>
);
}
@@ -52,25 +52,52 @@ vi.mock("@/hooks/domains/github/use-task-ci-options", () => ({
import { PRCIPopover } from "./pr-ci-popover";
import { MultiPRCIPopover } from "./multi-pr-ci-popover";
const AUTO_FIX_LABEL = "Auto-fix CI and address comments";
const AUTO_MERGE_LABEL = "Auto-merge when ready";
const MERGED_PROMPT_LABEL = "PR merged";
const CLOSED_PROMPT_LABEL = "PR closed without merging";
const REVIEW_REQUEST_PROMPT_LABEL = "Your review is requested";
const PR_EVENTS_TRIGGER = "ci-pr-events-trigger";
const REVIEW_FOLLOW_UP_TRIGGER = "ci-review-follow-up-trigger";
const REMOVE_FIRST_PR_LABEL = "Remove r #1 from task";
const BACKEND_UNAVAILABLE = "backend unavailable";
// The five automation switches are per-PR; pr_options defaults to one entry
// for makePR()'s default identity (task-1 / repository_id "" / #1) mirroring
// whichever top-level switch overrides the caller passed, so existing
// `makeOptions({ prompt_on_merged: true })`-style overrides still drive the
// rendered switch state without every call site building pr_options by hand.
function makeOptions(overrides: Partial<TaskCIAutomationOptions> = {}): TaskCIAutomationOptions {
return {
const base = {
task_id: "task-1",
auto_fix_enabled: false,
auto_merge_enabled: false,
auto_fix_prompt_override: null,
effective_auto_fix_prompt: "Default CI fix prompt",
using_default_prompt: true,
prompt_on_review_requested: false,
prompt_on_merged: false,
prompt_on_closed: false,
updated_at: "2026-06-18T10:00:00Z",
pr_states: [],
...overrides,
};
return {
...base,
pr_options: overrides.pr_options ?? [
{
task_id: base.task_id,
repository_id: "",
pr_number: 1,
auto_fix_enabled: base.auto_fix_enabled,
auto_merge_enabled: base.auto_merge_enabled,
prompt_on_review_requested: base.prompt_on_review_requested,
prompt_on_merged: base.prompt_on_merged,
prompt_on_closed: base.prompt_on_closed,
created_at: "",
updated_at: "",
},
],
};
}
function makePR(overrides: Partial<TaskPR> = {}): TaskPR {
@@ -118,6 +145,21 @@ function renderPopover() {
);
}
function makePROption(prNumber: number, enabled: boolean) {
return {
task_id: "task-1",
repository_id: "",
pr_number: prNumber,
auto_fix_enabled: enabled,
auto_merge_enabled: enabled,
prompt_on_review_requested: false,
prompt_on_merged: false,
prompt_on_closed: false,
created_at: "",
updated_at: "",
};
}
function resetHookMocks() {
hookMocks.error = null;
hookMocks.options = null;
@@ -141,27 +183,33 @@ describe("PRCIPopover automation toggles", () => {
renderPopover();
expect(screen.getByLabelText("Explain CI automation options")).not.toBeNull();
fireEvent.click(screen.getByLabelText("Auto-fix CI and address comments"));
fireEvent.click(screen.getByLabelText("Auto-merge when ready"));
fireEvent.click(screen.getByTestId(PR_EVENTS_TRIGGER));
fireEvent.click(screen.getByLabelText(AUTO_FIX_LABEL));
fireEvent.click(screen.getByLabelText(AUTO_MERGE_LABEL));
fireEvent.click(screen.getByTestId(REVIEW_FOLLOW_UP_TRIGGER));
fireEvent.click(screen.getByLabelText(REVIEW_REQUEST_PROMPT_LABEL));
fireEvent.click(screen.getByLabelText(MERGED_PROMPT_LABEL));
fireEvent.click(screen.getByLabelText(CLOSED_PROMPT_LABEL));
expect(hookMocks.updateMock).toHaveBeenCalledWith({ auto_fix_enabled: true });
expect(hookMocks.updateMock).toHaveBeenCalledWith({ auto_merge_enabled: true });
expect(hookMocks.updateMock).toHaveBeenCalledWith({ prompt_on_review_requested: true });
expect(hookMocks.updateMock).toHaveBeenCalledWith({ prompt_on_merged: true });
expect(hookMocks.updateMock).toHaveBeenCalledWith({ prompt_on_closed: true });
// Every switch patch carries this PR's identity so the backend applies
// the change to this PR only, instead of fanning out to every linked PR.
const identity = { repository_id: "", pr_number: 1 };
expect(hookMocks.updateMock).toHaveBeenCalledWith({ ...identity, auto_fix_enabled: true });
expect(hookMocks.updateMock).toHaveBeenCalledWith({ ...identity, auto_merge_enabled: true });
expect(hookMocks.updateMock).toHaveBeenCalledWith({
...identity,
prompt_on_review_requested: true,
});
expect(hookMocks.updateMock).toHaveBeenCalledWith({ ...identity, prompt_on_merged: true });
expect(hookMocks.updateMock).toHaveBeenCalledWith({ ...identity, prompt_on_closed: true });
});
it("keeps PR events collapsed until opened while auto-fix and auto-merge stay primary", () => {
it("keeps review follow-up collapsed until opened while auto-fix and auto-merge stay primary", () => {
renderPopover();
const trigger = screen.getByTestId(PR_EVENTS_TRIGGER);
const trigger = screen.getByTestId(REVIEW_FOLLOW_UP_TRIGGER);
expect(trigger.getAttribute("aria-expanded")).toBe("false");
expect(screen.getByLabelText("Auto-fix CI and address comments")).not.toBeNull();
expect(screen.getByLabelText("Auto-merge when ready")).not.toBeNull();
expect(screen.getByLabelText(AUTO_FIX_LABEL)).not.toBeNull();
expect(screen.getByLabelText(AUTO_MERGE_LABEL)).not.toBeNull();
expect(screen.queryByLabelText(REVIEW_REQUEST_PROMPT_LABEL)).toBeNull();
expect(screen.queryByLabelText(MERGED_PROMPT_LABEL)).toBeNull();
expect(screen.queryByLabelText(CLOSED_PROMPT_LABEL)).toBeNull();
@@ -173,12 +221,12 @@ describe("PRCIPopover automation toggles", () => {
expect(screen.getByLabelText(CLOSED_PROMPT_LABEL)).not.toBeNull();
expect(
screen.getByLabelText(REVIEW_REQUEST_PROMPT_LABEL).getAttribute("aria-describedby"),
).toBe("task-pr-review-requested-prompt-task-1-description");
).toBe("task-pr-review-requested-prompt-task-1-none-1-description");
expect(screen.getByLabelText(MERGED_PROMPT_LABEL).getAttribute("aria-describedby")).toBe(
"task-pr-terminal-help-task-1",
"task-pr-terminal-help-task-1-none-1",
);
expect(screen.getByLabelText(CLOSED_PROMPT_LABEL).getAttribute("aria-describedby")).toBe(
"task-pr-terminal-help-task-1",
"task-pr-terminal-help-task-1-none-1",
);
expect(
screen.getByText("Wake the agent for any new request, including re-review after changes."),
@@ -190,30 +238,30 @@ describe("PRCIPopover automation toggles", () => {
expect(screen.getByTestId("ci-pr-terminal-help")).not.toBeNull();
});
it("opens PR events when lifecycle automation is enabled", () => {
it("opens review follow-up when lifecycle automation is enabled", () => {
hookMocks.options = makeOptions({ prompt_on_merged: true });
renderPopover();
expect(screen.getByTestId(PR_EVENTS_TRIGGER).getAttribute("aria-expanded")).toBe("true");
expect(screen.getByTestId(REVIEW_FOLLOW_UP_TRIGGER).getAttribute("aria-expanded")).toBe("true");
expect(screen.getByLabelText(MERGED_PROMPT_LABEL)).not.toBeNull();
});
it("keeps the PR events trigger compact for desktop and touch-sized otherwise", () => {
it("keeps the review follow-up trigger compact for desktop and touch-sized otherwise", () => {
renderPopover();
const desktopTrigger = screen.getByTestId(PR_EVENTS_TRIGGER);
const desktopTrigger = screen.getByTestId(REVIEW_FOLLOW_UP_TRIGGER);
expect(desktopTrigger.classList.contains("min-h-7")).toBe(true);
expect(desktopTrigger.classList.contains("min-h-11")).toBe(false);
cleanup();
responsiveMock.isMobile = true;
renderPopover();
expect(screen.getByTestId(PR_EVENTS_TRIGGER).classList.contains("min-h-11")).toBe(true);
expect(screen.getByTestId(REVIEW_FOLLOW_UP_TRIGGER).classList.contains("min-h-11")).toBe(true);
cleanup();
responsiveMock.isMobile = false;
responsiveMock.isFinePointer = false;
renderPopover();
expect(screen.getByTestId(PR_EVENTS_TRIGGER).classList.contains("min-h-11")).toBe(true);
expect(screen.getByTestId(REVIEW_FOLLOW_UP_TRIGGER).classList.contains("min-h-11")).toBe(true);
});
});
@@ -252,7 +300,7 @@ describe("PRCIPopover automation status", () => {
expect(screen.getByRole("alert").textContent).toContain(
"No promptable task session is available.",
);
fireEvent.click(screen.getByTestId(PR_EVENTS_TRIGGER));
fireEvent.click(screen.getByTestId(REVIEW_FOLLOW_UP_TRIGGER));
expect(screen.getByLabelText(REVIEW_REQUEST_PROMPT_LABEL)).not.toBeNull();
expect(screen.queryByLabelText(/edit.*review/i)).toBeNull();
});
@@ -292,6 +340,38 @@ describe("PRCIPopover automation status", () => {
expect(onOpenDetailPanel).toHaveBeenCalledWith(expect.objectContaining({ id: "b" }));
expect(screen.queryByText("Open PR details")).toBeNull();
});
it("keeps each linked PR's automation switches independent across tabs (AC1-AC3)", () => {
hookMocks.options = makeOptions({
pr_options: [makePROption(1, true), makePROption(2, false)],
});
render(
<TooltipProvider>
<StateProvider>
<ToastProvider>
<MultiPRCIPopover
prs={[
makePR({ id: "a", pr_number: 1, pr_title: "First PR" }),
makePR({ id: "b", pr_number: 2, pr_title: "Second PR" }),
]}
enabled={true}
/>
</ToastProvider>
</StateProvider>
</TooltipProvider>,
);
const checkedState = () => [
screen.getByLabelText(AUTO_FIX_LABEL).getAttribute("aria-checked"),
screen.getByLabelText(AUTO_MERGE_LABEL).getAttribute("aria-checked"),
];
// PR #1's tab is selected by default (worst status) — its switches are on.
expect(checkedState()).toEqual(["true", "true"]);
// Switching to PR #2's tab shows its own, independently off, state.
fireEvent.click(screen.getByTestId("pr-popover-tab-o-r-2"));
expect(checkedState()).toEqual(["false", "false"]);
});
});
describe("MultiPRCIPopover unlink", () => {
@@ -23,6 +23,7 @@ function makeOptions(overrides: Partial<TaskCIAutomationOptions> = {}): TaskCIAu
using_default_prompt: true,
updated_at: "2026-08-10T10:00:00Z",
pr_states: [],
pr_options: [],
...overrides,
};
}
@@ -81,11 +82,37 @@ describe("AutomationFlagBadges", () => {
);
});
it("derives the same task-wide PR events for single and multiple PR chips", () => {
it("derives the same enabled PR events for single and multiple PR chips", () => {
const options = makeOptions({
prompt_on_review_requested: true,
prompt_on_merged: true,
prompt_on_closed: true,
pr_options: [
{
task_id: "task-1",
repository_id: "repo-1",
pr_number: 42,
auto_fix_enabled: false,
auto_merge_enabled: false,
prompt_on_review_requested: true,
prompt_on_merged: true,
prompt_on_closed: true,
created_at: "",
updated_at: "",
},
{
task_id: "task-1",
repository_id: "repo-1",
pr_number: 43,
auto_fix_enabled: false,
auto_merge_enabled: false,
prompt_on_review_requested: true,
prompt_on_merged: true,
prompt_on_closed: true,
created_at: "",
updated_at: "",
},
],
});
const single = automationForPR(options, PR);
@@ -2,7 +2,11 @@
import type { TFunction } from "i18next";
import { useTranslation } from "react-i18next";
import { autoFixRoundForState, findCIAutomationStateForPR } from "@/lib/github/ci-automation";
import {
autoFixRoundForState,
findCIAutomationStateForPR,
findPRAutomationOptionsForPR,
} from "@/lib/github/ci-automation";
import type { AutoFixRoundInfo } from "@/lib/github/ci-automation";
import type { TaskCIAutomationOptions, TaskPR } from "@/lib/types/github";
@@ -31,12 +35,24 @@ export function automationForPR(
options: TaskCIAutomationOptions | null | undefined,
pr: TaskPR,
): AutomationFlags {
const prOptions = options?.pr_options
? findPRAutomationOptionsForPR(options.pr_options, pr)
: null;
const flags = prOptions
? {
autoFix: prOptions.auto_fix_enabled,
autoMerge: prOptions.auto_merge_enabled,
promptOnReviewRequested: prOptions.prompt_on_review_requested,
promptOnMerged: prOptions.prompt_on_merged,
promptOnClosed: prOptions.prompt_on_closed,
}
: taskWideAutomationFlags(options);
return {
...taskWideAutomationFlags(options),
autoFixRound: options?.auto_fix_enabled
...flags,
autoFixRound: (prOptions ? prOptions.auto_fix_enabled : options?.auto_fix_enabled)
? autoFixRoundForState(
findCIAutomationStateForPR(options.pr_states, pr),
options.auto_fix_max_rounds,
findCIAutomationStateForPR(options?.pr_states, pr),
options?.auto_fix_max_rounds,
)
: null,
};
@@ -46,16 +62,37 @@ export function automationForPRs(
options: TaskCIAutomationOptions | null | undefined,
prs: TaskPR[],
): AutomationFlags {
const roundInfos = options?.auto_fix_enabled
? prs.map((pr) =>
autoFixRoundForState(
findCIAutomationStateForPR(options.pr_states, pr),
options.auto_fix_max_rounds,
),
)
: [];
if (!options?.pr_options) {
const roundInfos = options?.auto_fix_enabled
? prs.map((pr) =>
autoFixRoundForState(
findCIAutomationStateForPR(options.pr_states, pr),
options.auto_fix_max_rounds,
),
)
: [];
return {
...taskWideAutomationFlags(options),
autoFixRound: pickAttentionRound(roundInfos),
};
}
const perPR = prs.map((pr) => findPRAutomationOptionsForPR(options.pr_options, pr));
const roundInfos = perPR
.map((prOptions, index) =>
prOptions.auto_fix_enabled
? autoFixRoundForState(
findCIAutomationStateForPR(options.pr_states, prs[index]),
options.auto_fix_max_rounds,
)
: null,
)
.filter((round): round is AutoFixRoundInfo => round !== null);
return {
...taskWideAutomationFlags(options),
autoFix: perPR.some((prOptions) => prOptions.auto_fix_enabled),
autoMerge: perPR.some((prOptions) => prOptions.auto_merge_enabled),
promptOnReviewRequested: perPR.some((prOptions) => prOptions.prompt_on_review_requested),
promptOnMerged: perPR.some((prOptions) => prOptions.prompt_on_merged),
promptOnClosed: perPR.some((prOptions) => prOptions.prompt_on_closed),
autoFixRound: pickAttentionRound(roundInfos),
};
}
@@ -94,8 +94,11 @@ function makePR(overrides: Partial<TaskPR> = {}): TaskPR {
};
}
// auto_fix_enabled is per-PR; pr_options defaults to one entry matching
// makePR()'s identity (task-1 / repository_id "" / #42) so overrides like
// `makeCIOptions({ auto_fix_enabled: true })` still drive the rendered chip.
function makeCIOptions(overrides: Partial<TaskCIAutomationOptions> = {}): TaskCIAutomationOptions {
return {
const base = {
task_id: "task-1",
auto_fix_enabled: false,
auto_merge_enabled: false,
@@ -107,6 +110,23 @@ function makeCIOptions(overrides: Partial<TaskCIAutomationOptions> = {}): TaskCI
pr_states: [],
...overrides,
};
return {
...base,
pr_options: overrides.pr_options ?? [
{
task_id: base.task_id,
repository_id: "",
pr_number: 42,
auto_fix_enabled: base.auto_fix_enabled,
auto_merge_enabled: base.auto_merge_enabled,
prompt_on_review_requested: false,
prompt_on_merged: false,
prompt_on_closed: false,
created_at: "",
updated_at: "",
},
],
};
}
function makeCIPrState(roundCount: number, exhausted = false) {
@@ -0,0 +1,70 @@
import type { TaskCIAutomationOptions, TaskPR } from "@/lib/types/github";
export function makeTestPR(overrides: Partial<TaskPR> = {}): TaskPR {
return {
id: "pr-id",
task_id: "task-1",
owner: "acme",
repo: "demo",
pr_number: 42,
pr_url: "https://github.com/acme/demo/pull/42",
pr_title: "Test PR",
head_branch: "feat",
base_branch: "main",
author_login: "alice",
state: "open",
review_state: "approved",
checks_state: "success",
mergeable_state: "clean",
review_count: 1,
pending_review_count: 0,
comment_count: 0,
unresolved_review_threads: 0,
checks_total: 2,
checks_passing: 2,
additions: 0,
deletions: 0,
created_at: "",
merged_at: null,
closed_at: null,
last_synced_at: null,
updated_at: "",
...overrides,
};
}
// auto_fix_enabled/auto_merge_enabled are per-PR; pr_options mirrors them
// into one entry matching makeTestPR()'s identity (task-1/""/42) so overrides
// like `makeTestCIOptions({ auto_fix_enabled: true })` still drive the chip.
export function makeTestCIOptions(
overrides: Partial<TaskCIAutomationOptions> = {},
): TaskCIAutomationOptions {
const autoFix = overrides.auto_fix_enabled ?? false;
const autoMerge = overrides.auto_merge_enabled ?? false;
return {
task_id: "task-1",
auto_fix_enabled: autoFix,
auto_merge_enabled: autoMerge,
auto_fix_prompt_override: null,
effective_auto_fix_prompt: "Default CI fix prompt",
using_default_prompt: true,
updated_at: "2026-06-18T10:00:00Z",
auto_fix_max_rounds: 10,
pr_states: [],
pr_options: [
{
task_id: "task-1",
repository_id: "",
pr_number: 42,
auto_fix_enabled: autoFix,
auto_merge_enabled: autoMerge,
prompt_on_review_requested: false,
prompt_on_merged: false,
prompt_on_closed: false,
created_at: "",
updated_at: "",
},
],
...overrides,
};
}
@@ -6,8 +6,12 @@ import { StateProvider } from "@/components/state-provider";
import { ToastProvider } from "@/components/toast-provider";
import { PRStatusChip, aggregateChipStatus } from "./pr-status-chip";
import { PR_CI_DESKTOP_POPOVER_SCROLL_CLASS } from "./pr-ci-popover";
import {
makeTestCIOptions as makeCIOptions,
makeTestPR as makePR,
} from "./pr-status-chip.test-fixtures";
import type { AppState } from "@/lib/state/store";
import type { TaskCIAutomationOptions, TaskPR } from "@/lib/types/github";
import type { TaskPR } from "@/lib/types/github";
const AUTO_FIX_BADGE_TESTID = "pr-status-auto-fix-chip";
@@ -51,6 +55,7 @@ vi.mock("@/lib/api/domains/github-api", async (importOriginal) => {
using_default_prompt: true,
updated_at: "2026-06-18T10:00:00Z",
pr_states: [],
pr_options: [],
}),
listWorkspaceTaskPRs: vi.fn().mockResolvedValue({ task_prs: {} }),
};
@@ -70,53 +75,6 @@ function renderWithStore(initialState: Partial<AppState> | undefined, ui: ReactN
);
}
function makePR(overrides: Partial<TaskPR> = {}): TaskPR {
return {
id: "pr-id",
task_id: "task-1",
owner: "acme",
repo: "demo",
pr_number: 42,
pr_url: "https://github.com/acme/demo/pull/42",
pr_title: "Test PR",
head_branch: "feat",
base_branch: "main",
author_login: "alice",
state: "open",
review_state: "approved",
checks_state: "success",
mergeable_state: "clean",
review_count: 1,
pending_review_count: 0,
comment_count: 0,
unresolved_review_threads: 0,
checks_total: 2,
checks_passing: 2,
additions: 0,
deletions: 0,
created_at: "",
merged_at: null,
closed_at: null,
last_synced_at: null,
updated_at: "",
...overrides,
};
}
function makeCIOptions(overrides: Partial<TaskCIAutomationOptions> = {}): TaskCIAutomationOptions {
return {
task_id: "task-1",
auto_fix_enabled: false,
auto_merge_enabled: false,
auto_fix_prompt_override: null,
effective_auto_fix_prompt: testConstants.defaultCIFixPrompt,
using_default_prompt: true,
updated_at: "2026-06-18T10:00:00Z",
pr_states: [],
...overrides,
};
}
beforeEach(() => {
responsiveMock.breakpoint = "desktop";
responsiveMock.isFinePointer = true;
@@ -190,10 +190,10 @@ test.describe("PR CI automation options", () => {
popover.getByRole("switch", { name: "Auto-fix CI and address comments" }),
).toBeVisible();
await expect(popover.getByRole("switch", { name: "Auto-merge when ready" })).toBeVisible();
const prEvents = popover.getByTestId("ci-pr-events-trigger");
await expect(prEvents).toHaveAttribute("aria-expanded", "false");
await prEvents.click();
await expect(prEvents).toHaveAttribute("aria-expanded", "true");
const reviewFollowUp = popover.getByTestId("ci-review-follow-up-trigger");
await expect(reviewFollowUp).toHaveAttribute("aria-expanded", "false");
await reviewFollowUp.click();
await expect(reviewFollowUp).toHaveAttribute("aria-expanded", "true");
await expect(popover.getByRole("switch", { name: "Your review is requested" })).toBeVisible();
await expect(popover.getByRole("switch", { name: "PR merged" })).toBeVisible();
await expect(popover.getByRole("switch", { name: "PR closed without merging" })).toBeVisible();
@@ -257,7 +257,6 @@ test.describe("PR CI automation options", () => {
.poll(async () => apiClient.getTaskCIAutomationOptions(taskId))
.toMatchObject({ auto_fix_prompt_override: null });
await testPage.reload();
const reloaded = await openTask(testPage, taskId);
await expect(
reloaded.prTopbarPopover().getByRole("switch", {
@@ -269,6 +268,89 @@ test.describe("PR CI automation options", () => {
).toBeChecked();
});
test("desktop popover keeps two linked PRs' automation switches independent", async ({
testPage,
apiClient,
seedData,
}) => {
test.setTimeout(120_000);
const taskId = await seedTaskWithPR(apiClient, seedData, "CI automation independence");
const secondPRNumber = PR_NUMBER + 1;
await apiClient.mockGitHubAssociateTaskPR({
task_id: taskId,
workspace_id: seedData.workspaceId,
owner: OWNER,
repo: REPO,
pr_number: secondPRNumber,
pr_url: `https://github.com/${OWNER}/${REPO}/pull/${secondPRNumber}`,
pr_title: "Second PR",
head_branch: "feat/second",
base_branch: "main",
author_login: "test-user",
state: "open",
review_state: "approved",
checks_state: "success",
});
const session = await openTask(testPage, taskId);
const popover = session.prTopbarPopover();
// Pin the tab to PR #144 explicitly: the default tab tracks live
// "worst status" data and can otherwise flip between clicks as
// background PR sync updates check status.
await popover.getByRole("tab", { name: `${REPO} #${PR_NUMBER}` }).click();
await expect(
popover.getByRole("switch", { name: "Auto-fix CI and address comments" }),
).toBeVisible();
await popover.getByRole("switch", { name: "Auto-fix CI and address comments" }).click();
await popover.getByRole("switch", { name: "Auto-merge when ready" }).click();
await expect
.poll(async () => apiClient.getTaskCIAutomationOptions(taskId))
.toMatchObject({
pr_options: expect.arrayContaining([
expect.objectContaining({
pr_number: PR_NUMBER,
auto_fix_enabled: true,
auto_merge_enabled: true,
}),
expect.objectContaining({
pr_number: secondPRNumber,
auto_fix_enabled: false,
auto_merge_enabled: false,
}),
]),
});
// The second PR's tab must show its own, independently off, state.
await popover.getByRole("tab", { name: `${REPO} #${secondPRNumber}` }).click();
await expect(
popover.getByRole("switch", { name: "Auto-fix CI and address comments" }),
).not.toBeChecked();
await expect(popover.getByRole("switch", { name: "Auto-merge when ready" })).not.toBeChecked();
// Reload: independence must persist across a full page load. Select each
// tab explicitly — the default tab tracks live "worst status" data (real
// CI automation may have altered it), so it is not a stable signal here.
await testPage.reload();
const reloaded = await openTask(testPage, taskId);
const reloadedPopover = reloaded.prTopbarPopover();
await reloadedPopover.getByRole("tab", { name: `${REPO} #${PR_NUMBER}` }).click();
await expect(
reloadedPopover.getByRole("switch", { name: "Auto-fix CI and address comments" }),
).toBeChecked();
await expect(
reloadedPopover.getByRole("switch", { name: "Auto-merge when ready" }),
).toBeChecked();
await reloadedPopover.getByRole("tab", { name: `${REPO} #${secondPRNumber}` }).click();
await expect(
reloadedPopover.getByRole("switch", { name: "Auto-fix CI and address comments" }),
).not.toBeChecked();
await expect(
reloadedPopover.getByRole("switch", { name: "Auto-merge when ready" }),
).not.toBeChecked();
});
test("desktop popover shows the selected PR lifecycle delivery error", async ({
testPage,
apiClient,
@@ -279,7 +361,7 @@ test.describe("PR CI automation options", () => {
const session = await openTask(testPage, taskId);
const popover = session.prTopbarPopover();
await popover.getByTestId("ci-pr-events-trigger").click();
await popover.getByTestId("ci-review-follow-up-trigger").click();
await expect(popover.getByRole("switch", { name: "Your review is requested" })).toBeVisible();
await expect(popover.getByRole("alert")).toContainText(
"Lifecycle prompt could not be delivered to a task session.",
@@ -5,7 +5,7 @@ import type { SeedData } from "../../fixtures/test-base";
const OWNER = "acme";
const REPO = "demo";
const PR_NUMBER = 145;
const PR_NUMBER = 144;
const PR_URL = `https://github.com/${OWNER}/${REPO}/pull/${PR_NUMBER}`;
function manyRunningChecks(count: number) {
@@ -121,11 +121,11 @@ test.describe("mobile PR CI automation options", () => {
drawer.getByRole("switch", { name: "Auto-fix CI and address comments" }),
).toBeVisible();
await expect(drawer.getByRole("switch", { name: "Auto-merge when ready" })).toBeVisible();
const prEvents = drawer.getByTestId("ci-pr-events-trigger");
await expect(prEvents).toHaveAttribute("aria-expanded", "false");
await expect(prEvents).toHaveCSS("min-height", "44px");
await prEvents.tap();
await expect(prEvents).toHaveAttribute("aria-expanded", "true");
const reviewFollowUp = drawer.getByTestId("ci-review-follow-up-trigger");
await expect(reviewFollowUp).toHaveAttribute("aria-expanded", "false");
await expect(reviewFollowUp).toHaveCSS("min-height", "44px");
await reviewFollowUp.tap();
await expect(reviewFollowUp).toHaveAttribute("aria-expanded", "true");
await expect(drawer.getByRole("switch", { name: "Your review is requested" })).toBeVisible();
await expect(drawer.getByRole("switch", { name: "PR merged" })).toBeVisible();
await expect(drawer.getByRole("switch", { name: "PR closed without merging" })).toBeVisible();
@@ -178,6 +178,57 @@ test.describe("mobile PR CI automation options", () => {
);
});
test("drawer keeps two linked PRs' automation switches independent", async ({
testPage,
apiClient,
seedData,
}) => {
test.setTimeout(120_000);
const taskId = await seedTaskWithPR(apiClient, seedData, "CI automation mobile independence");
const secondPRNumber = PR_NUMBER + 1;
await apiClient.mockGitHubAssociateTaskPR({
task_id: taskId,
workspace_id: seedData.workspaceId,
owner: OWNER,
repo: REPO,
pr_number: secondPRNumber,
pr_url: `https://github.com/${OWNER}/${REPO}/pull/${secondPRNumber}`,
pr_title: "Second PR",
head_branch: "feat/second",
base_branch: "main",
author_login: "test-user",
state: "open",
review_state: "approved",
checks_state: "success",
});
await testPage.goto(`/t/${taskId}`);
const session = new SessionPage(testPage);
await session.waitForLoad();
await session.tapPRStatusChip();
const drawer = session.prStatusChipDrawer();
await drawer.getByRole("tab", { name: `${REPO} #${PR_NUMBER}` }).tap();
await expect(
drawer.getByRole("switch", { name: "Auto-fix CI and address comments" }),
).toBeVisible();
await drawer.getByRole("switch", { name: "Auto-fix CI and address comments" }).tap();
await expect
.poll(async () => apiClient.getTaskCIAutomationOptions(taskId))
.toMatchObject({
pr_options: expect.arrayContaining([
expect.objectContaining({ pr_number: PR_NUMBER, auto_fix_enabled: true }),
expect.objectContaining({ pr_number: secondPRNumber, auto_fix_enabled: false }),
]),
});
await drawer.getByRole("tab", { name: `${REPO} #${secondPRNumber}` }).tap();
await expect(
drawer.getByRole("switch", { name: "Auto-fix CI and address comments" }),
).not.toBeChecked();
});
test("drawer contains lifecycle errors without horizontal document overflow", async ({
testPage,
apiClient,
@@ -197,7 +248,7 @@ test.describe("mobile PR CI automation options", () => {
await session.tapPRStatusChip();
const drawer = session.prStatusChipDrawer();
await drawer.getByTestId("ci-pr-events-trigger").tap();
await drawer.getByTestId("ci-review-follow-up-trigger").tap();
await expect(drawer.getByRole("switch", { name: "Your review is requested" })).toBeVisible();
await expect(drawer.getByRole("alert")).toContainText(
"Lifecycle prompt could not be delivered to a task session.",
+2
View File
@@ -1406,6 +1406,8 @@ export const i18nGuardFiles = [
"components/github/my-github/use-pr-statuses.ts",
"components/github/pr-checks-section.tsx",
"components/github/pr-ci-automation-controls.tsx",
"components/github/pr-ci-automation-prompt-dialog.tsx",
"components/github/pr-ci-automation-rows.tsx",
"components/github/pr-ci-popover.tsx",
"components/github/pr-comments-section.tsx",
"components/github/pr-detail-panel.tsx",
@@ -30,6 +30,7 @@ function makeOptions(overrides: Partial<TaskCIAutomationOptions> = {}): TaskCIAu
using_default_prompt: true,
updated_at: "2026-06-18T10:00:00Z",
pr_states: [],
pr_options: [],
...overrides,
};
}
+61 -2
View File
@@ -3,17 +3,39 @@ import {
autoFixRoundForState,
clampAutoFixRound,
findCIAutomationStateForPR,
findPRAutomationOptionsForPR,
normalizeAutoFixMaxRounds,
} from "./ci-automation";
import type { TaskCIPRAutomationState, TaskPR } from "@/lib/types/github";
import type { TaskCIPRAutomationState, TaskPR, TaskPRAutomationOptions } from "@/lib/types/github";
function makePR(repositoryID: string, prNumber = 42): TaskPR {
function makePR(repositoryID: string, prNumber = 42, taskID = "task-1"): TaskPR {
return {
task_id: taskID,
repository_id: repositoryID,
pr_number: prNumber,
} as TaskPR;
}
function makePRAutomationOptions(
repositoryID: string,
prNumber: number,
overrides: Partial<TaskPRAutomationOptions> = {},
): TaskPRAutomationOptions {
return {
task_id: "task-1",
repository_id: repositoryID,
pr_number: prNumber,
auto_fix_enabled: false,
auto_merge_enabled: false,
prompt_on_review_requested: false,
prompt_on_merged: false,
prompt_on_closed: false,
created_at: "",
updated_at: "",
...overrides,
};
}
function makeState(
repositoryID: string,
prNumber: number,
@@ -58,6 +80,43 @@ describe("CI automation helpers", () => {
});
});
it("finds PR automation options by repository id and PR number, independent of other PRs", () => {
const options = [
makePRAutomationOptions("repo-1", 1, { auto_fix_enabled: true }),
makePRAutomationOptions("repo-1", 2, { auto_fix_enabled: false }),
makePRAutomationOptions("repo-2", 1, { auto_merge_enabled: true }),
];
expect(findPRAutomationOptionsForPR(options, makePR("repo-1", 1))).toBe(options[0]);
expect(findPRAutomationOptionsForPR(options, makePR("repo-1", 2))).toBe(options[1]);
// Same PR number, different repository — must not collide with repo-1's entry.
expect(findPRAutomationOptionsForPR(options, makePR("repo-2", 1))).toBe(options[2]);
});
it("returns all-off defaults for a PR with no stored automation row", () => {
const options = [makePRAutomationOptions("repo-1", 1, { auto_fix_enabled: true })];
const result = findPRAutomationOptionsForPR(options, makePR("repo-1", 99, "task-9"));
expect(result).toEqual({
task_id: "task-9",
repository_id: "repo-1",
pr_number: 99,
auto_fix_enabled: false,
auto_merge_enabled: false,
prompt_on_review_requested: false,
prompt_on_merged: false,
prompt_on_closed: false,
created_at: "",
updated_at: "",
});
});
it("returns all-off defaults when pr_options is undefined", () => {
expect(findPRAutomationOptionsForPR(undefined, makePR("repo-1", 1)).auto_fix_enabled).toBe(
false,
);
});
it("normalizes max rounds and clamps current rounds", () => {
expect(normalizeAutoFixMaxRounds(undefined)).toBe(10);
expect(normalizeAutoFixMaxRounds(null)).toBe(10);
+36 -1
View File
@@ -1,7 +1,42 @@
import type { TaskCIPRAutomationState, TaskPR } from "@/lib/types/github";
import type { TaskCIPRAutomationState, TaskPR, TaskPRAutomationOptions } from "@/lib/types/github";
const DEFAULT_AUTO_FIX_MAX_ROUNDS = 10;
export const DISABLED_PR_AUTOMATION_OPTIONS: Omit<
TaskPRAutomationOptions,
"task_id" | "repository_id" | "pr_number" | "created_at" | "updated_at"
> = {
auto_fix_enabled: false,
auto_merge_enabled: false,
prompt_on_review_requested: false,
prompt_on_merged: false,
prompt_on_closed: false,
};
/**
* Selects the given PR's own automation switches out of the task-scoped
* pr_options array. Falls back to all-off defaults when the PR has no
* stored row yet (never enabled), mirroring findCIAutomationStateForPR.
*/
export function findPRAutomationOptionsForPR(
options: TaskPRAutomationOptions[] | undefined,
pr: TaskPR,
): TaskPRAutomationOptions {
const repositoryID = pr.repository_id ?? "";
const found = options?.find(
(option) => option.pr_number === pr.pr_number && option.repository_id === repositoryID,
);
if (found) return found;
return {
task_id: pr.task_id,
repository_id: repositoryID,
pr_number: pr.pr_number,
created_at: "",
updated_at: "",
...DISABLED_PR_AUTOMATION_OPTIONS,
};
}
export type AutoFixRoundInfo = {
current: number;
max: number;
@@ -57,6 +57,7 @@ function makeCIOptions(overrides: Partial<TaskCIAutomationOptions> = {}): TaskCI
using_default_prompt: true,
updated_at: "2026-06-18T10:00:00Z",
pr_states: [],
pr_options: [],
...overrides,
};
}
+21
View File
@@ -286,6 +286,22 @@ export type TaskCIPRAutomationState = {
updated_at: string;
};
// TaskPRAutomationOptions holds the five automation switches for one linked
// PR. This is the per-PR source of truth; the aggregated booleans on
// TaskCIAutomationOptions only report "every linked PR has this on".
export type TaskPRAutomationOptions = {
task_id: string;
repository_id: string;
pr_number: number;
auto_fix_enabled: boolean;
auto_merge_enabled: boolean;
prompt_on_review_requested: boolean;
prompt_on_merged: boolean;
prompt_on_closed: boolean;
created_at: string;
updated_at: string;
};
export type TaskCIAutomationOptions = {
task_id: string;
workspace_id?: string;
@@ -301,9 +317,14 @@ export type TaskCIAutomationOptions = {
review_reviewer_login?: string;
updated_at: string;
pr_states: TaskCIPRAutomationState[];
pr_options: TaskPRAutomationOptions[];
};
export type TaskCIAutomationPatch = {
// Target one linked PR's automation switches; omit both to apply the
// switches to every PR currently linked to the task.
repository_id?: string;
pr_number?: number;
auto_fix_enabled?: boolean;
auto_merge_enabled?: boolean;
auto_fix_prompt_override?: string | null;
+2
View File
@@ -37,6 +37,7 @@ describe("registerGitHubHandlers CI options", () => {
using_default_prompt: true,
updated_at: updatedAt,
pr_states: prStates,
pr_options: [],
});
handler({ payload: options(NEWER_UPDATED_AT, true) } as Parameters<typeof handler>[0]);
@@ -79,6 +80,7 @@ describe("registerGitHubHandlers CI options", () => {
using_default_prompt: true,
updated_at: INITIAL_UPDATED_AT,
pr_states: [],
pr_options: [],
};
const updated: TaskCIAutomationOptions = {
...initial,
+5
View File
@@ -55,6 +55,7 @@
"automaticallyCreateTasksWhenNewGithub": "Automatically create tasks when new GitHub issues match your criteria.",
"automaticallyCreateTasksWhenNewPull": "Automatically create tasks when new pull requests need your review.",
"automation": "Automation",
"automationForPr": "Applies to PR #{{number}} only",
"available": "Available",
"availablePlaceholders": "Available placeholders:",
"avgTimeToMerge": "Avg Time to Merge",
@@ -387,6 +388,7 @@
"prApproved": "PR approved",
"prClosedWithoutMerging": "PR closed without merging",
"prEvents": "PR events",
"reviewFollowUp": "Review follow-up",
"prMerged": "PR merged",
"prTaskStatusCi": "CI",
"prTaskStatusMerge": "Merge",
@@ -530,6 +532,7 @@
"titleIssues": "Issues",
"titlePullRequests": "Pull requests",
"togglePrEventPromptAutomation": "Toggle PR event prompt automation",
"toggleReviewFollowUpAutomation": "Toggle review follow-up automation",
"typeACustomQueryFirst": "Type a custom query first",
"typeOwnerRepoToSearch": "Type {{format}} to search",
"unableToLoadTheCurrentTask": "Unable to load the current task access setting.",
@@ -551,6 +554,8 @@
"viewPermissions": "View permissions",
"viewPullRequestOnGithub": "View pull request on GitHub",
"waitingOnBranchProtection": "Waiting on branch protection",
"wakeAgentOnReviewRequest": "Wake the agent for any new request, including re-review after changes.",
"wakeAgentOnTerminalPrState": "Wake the agent when review work ends. Choose either or both outcomes.",
"watchesThisTaskSLinkedPull": "Watches this task's linked pull request during the 1 minute PR refresh loop. Auto-fix queues task prompts for newly observed feedback, auto-merge waits for the PR to be ready, and the notification switches wake the task's agent when the workspace's connected GitHub account is requested for review or the PR reaches a terminal state. Review requests silently baseline the account's current request state before notifying on a later request.",
"webhook": "Webhook",
"webhookSecret": "Webhook secret",
+5
View File
@@ -55,6 +55,7 @@
"automaticallyCreateTasksWhenNewGithub": "Àũţōḿàţĩćàĺĺŷ ćŕēàţē ţàśķś ŵĥēń ńēŵ ĜĩţĤũƀ ĩśśũēś ḿàţćĥ ŷōũŕ ćŕĩţēŕĩà.",
"automaticallyCreateTasksWhenNewPull": "Àũţōḿàţĩćàĺĺŷ ćŕēàţē ţàśķś ŵĥēń ńēŵ ƥũĺĺ ŕēqũēśţś ńēēď ŷōũŕ ŕēvĩēŵ.",
"automation": "Àũţōḿàţĩōń",
"automationForPr": "Àƥƥĺĩēś ţō ƤŔ #{{number}} ōńĺŷ",
"available": "Àvàĩĺàƀĺē",
"availablePlaceholders": "Àvàĩĺàƀĺē ƥĺàćēĥōĺďēŕś:",
"avgTimeToMerge": "Àvĝ Ţĩḿē ţō Ḿēŕĝē",
@@ -387,6 +388,7 @@
"prApproved": "ƤŔ àƥƥŕōvēď",
"prClosedWithoutMerging": "ƤŔ ćĺōśēď ŵĩţĥōũţ ḿēŕĝĩńĝ",
"prEvents": "ƤŔ ēvēńţś",
"reviewFollowUp": "Ŕēvĩēŵ ƒōĺĺōŵ-ũƥ",
"prMerged": "ƤŔ ḿēŕĝēď",
"prTaskStatusCi": "ĆĨ",
"prTaskStatusMerge": "Ḿēŕĝē",
@@ -530,6 +532,7 @@
"titleIssues": "Ĩśśũēś",
"titlePullRequests": "Ƥũĺĺ ŕēqũēśţś",
"togglePrEventPromptAutomation": "Ţōĝĝĺē ƤŔ ēvēńţ ƥŕōḿƥţ àũţōḿàţĩōń",
"toggleReviewFollowUpAutomation": "Ţōĝĝĺē ŕēvĩēŵ ƒōĺĺōŵ-ũƥ àũţōḿàţĩōń",
"typeACustomQueryFirst": "Ţŷƥē à ćũśţōḿ qũēŕŷ ƒĩŕśţ",
"typeOwnerRepoToSearch": "Ţŷƥē {{format}} ţō śēàŕćĥ",
"unableToLoadTheCurrentTask": "Ũńàƀĺē ţō ĺōàď ţĥē ćũŕŕēńţ ţàśķ àććēśś śēţţĩńĝ.",
@@ -551,6 +554,8 @@
"viewPermissions": "Vĩēŵ ƥēŕḿĩśśĩōńś",
"viewPullRequestOnGithub": "Vĩēŵ ƥũĺĺ ŕēqũēśţ ōń ĜĩţĤũƀ",
"waitingOnBranchProtection": "Ŵàĩţĩńĝ ōń ƀŕàńćĥ ƥŕōţēćţĩōń",
"wakeAgentOnReviewRequest": "Ŵàķē ţĥē àĝēńţ ƒōŕ àńŷ ńēŵ ŕēqũēśţ, ĩńćĺũďĩńĝ ŕē-ŕēvĩēŵ àƒţēŕ ćĥàńĝēś.",
"wakeAgentOnTerminalPrState": "Ŵàķē ţĥē àĝēńţ ŵĥēń ŕēvĩēŵ ŵōŕķ ēńďś. Ćĥōōśē ēĩţĥēŕ ōŕ ƀōţĥ ōũţćōḿēś.",
"watchesThisTaskSLinkedPull": "Ŵàţćĥēś ţĥĩś ţàśķ'ś ĺĩńķēď ƥũĺĺ ŕēqũēśţ ďũŕĩńĝ ţĥē 1 ḿĩńũţē ƤŔ ŕēƒŕēśĥ ĺōōƥ. Àũţō-ƒĩx qũēũēś ţàśķ ƥŕōḿƥţś ƒōŕ ńēŵĺŷ ōƀśēŕvēď ƒēēďƀàćķ, àũţō-ḿēŕĝē ŵàĩţś ƒōŕ ţĥē ƤŔ ţō ƀē ŕēàďŷ, àńď ţĥē ńōţĩƒĩćàţĩōń śŵĩţćĥēś ŵàķē ţĥē ţàśķ'ś àĝēńţ ŵĥēń ţĥē ŵōŕķśƥàćē'ś ćōńńēćţēď ĜĩţĤũƀ àććōũńţ ĩś ŕēqũēśţēď ƒōŕ ŕēvĩēŵ ōŕ ţĥē ƤŔ ŕēàćĥēś à ţēŕḿĩńàĺ śţàţē. Ŕēvĩēŵ ŕēqũēśţś śĩĺēńţĺŷ ƀàśēĺĩńē ţĥē àććōũńţ'ś ćũŕŕēńţ ŕēqũēśţ śţàţē ƀēƒōŕē ńōţĩƒŷĩńĝ ōń à ĺàţēŕ ŕēqũēśţ.",
"webhook": "Ŵēƀĥōōķ",
"webhookSecret": "Ŵēƀĥōōķ śēćŕēţ",
@@ -143,7 +143,20 @@ error.
## Consequences
- PR automation has one task-level control plane for users and agents.
- ~~PR automation has one task-level control plane for users and agents.~~
**Superseded (2026-08-10):** the five automation switches
(`auto_fix_enabled`, `auto_merge_enabled`, `prompt_on_review_requested`,
`prompt_on_merged`, `prompt_on_closed`) are now scoped per linked PR —
`github_task_pr_automation_options`, keyed `(task_id, repository_id,
pr_number)` — because a task with multiple linked PRs (e.g. one repo's
feature branch and its backport) needs independent auto-fix/auto-merge
configuration per PR, and users editing one PR's tab in the multi-PR
popover were confused to see the same values change on every other tab
for the task. `auto_fix_prompt_override` and the resolved reviewer login
remain the one task-level control plane described below; only the five
boolean switches moved. MCP callers that omit PR identity keep today's
fan-out-to-every-linked-PR behavior. See `docs/specs/ui/ci-pr-automation.md`
and the GitLab MR automation follow-up for the mirrored change.
- Lifecycle evaluation runs inside the single CI automation pass — one goroutine
and one in-flight map handle auto-fix, auto-merge, and lifecycle for a PR.
- Lifecycle rows remain durable until executor acceptance, so restart recovery
+1 -1
View File
@@ -63,7 +63,7 @@ Released builds can lag this page. Check **Settings > System > About** or `kande
| Structured chat, tool activity, files, integrated PTYs, and session lifecycle | Dependency-bound | Panel availability follows the task environment, agent protocol, executor, and viewport. A terminal needs a materialized task environment. |
| Changes and cumulative Review | Supported | Supports staged, unstaged, commit, multi-repository, and initialized direct/nested submodule views; repository-scoped paths, persisted reviewed hashes, stale detection, and anchored comments are implemented. Unavailable submodules retain their parent gitlink. Discard is destructive and permanent, and submodule pull requests remain separate repository workflows. |
| Agent-authored code walkthrough | Dependency-bound | One saved walkthrough per task is supported through task MCP. A new walkthrough replaces the old one; anchors can drift, and the backend does not prove that referenced file content is still current. |
| GitHub pull-request review, checks, merge, and task PR automation | Dependency-bound | Requires GitHub credentials and repository permissions. GitHub-only task-level controls apply to every linked PR and can auto-fix feedback, auto-merge, and notify agents when their review is requested or when a PR merges or closes. Lifecycle messages are factual, immutable server-owned templates with only a canonical PR URL as dynamic content. Review-request matching uses the task workspace's connected GitHub account and a quiet baseline; delivery uses an existing task session or queue and never creates a new session. Azure has a create-PR path only; other Git hosts do not get the full task PR panel. |
| GitHub pull-request review, checks, merge, and task PR automation | Dependency-bound | Requires GitHub credentials and repository permissions. GitHub-only controls, scoped independently per linked PR, can auto-fix feedback, auto-merge, and notify agents when their review is requested or when a PR merges or closes. Lifecycle messages are factual, immutable server-owned templates with only a canonical PR URL as dynamic content. Review-request matching uses the task workspace's connected GitHub account and a quiet baseline; delivery uses an existing task session or queue and never creates a new session. Azure has a create-PR path only; other Git hosts do not get the full task PR panel. |
| GitLab merge-request review and task MR automation | Dependency-bound | Requires GitLab credentials and project permissions. Task-level controls can auto-fix pipeline/discussion feedback, auto-merge, and notify agents when their review is requested (assignment as a reviewer, since GitLab has no distinct review-request event), or when a linked MR merges or closes. Auto-fix is capped at 10 rounds per MR; auto-merge requires GitLab's own merge-readiness verdict plus Kandev's own gates (open, not draft, pipeline passing, no unresolved discussions). Lifecycle messages are factual, immutable server-owned templates with only a canonical MR URL as dynamic content, delivered through the same durable queue as GitHub's. |
| Share a session snapshot as a secret GitHub Gist | Dependency-bound | Requires GitHub auth and a structured session outside `CREATED`/`STARTING`. The viewing URL is rendered through `gist.githack.com`; unlisted URLs and heuristic redaction are not access control or exhaustive secret detection. Payloads are capped and shares can be revoked. |
| Quick Chat | Dependency-bound | Requires an agent profile. Repository-backed chats use isolated Kandev worktrees; closing deletes the ephemeral task permanently. Chats older than seven days are swept at startup and every 24 hours unless their session is `RUNNING` or `IDLE`. |
+1 -1
View File
@@ -294,7 +294,7 @@ Repository scope, authentication, and watch filters are workspace-specific. Repo
### Automate a linked pull request
For a task with linked GitHub pull requests, open the PR status control above the task chat input. The automation controls are task-level booleans: **Auto-fix CI & address comments**, **Auto-merge when ready**, **Your review is requested**, **PR merged**, and **PR closed without merging**. Enabling any control applies it to every PR linked to that task; Kandev tracks delivery and deduplication separately for each linked PR.
For a task with linked GitHub pull requests, open the PR status control above the task chat input. The automation controls, **Auto-fix CI & address comments**, **Auto-merge when ready**, **Your review is requested**, **PR merged**, and **PR closed without merging**, are scoped to whichever linked PR's tab is selected. Enabling a control for one linked PR does not enable it for the task's other linked PRs; Kandev tracks delivery and deduplication separately for each linked PR. The saved auto-fix prompt override applies to every linked PR.
This is a GitHub-only lifecycle feature. Kandev reuses the existing lightweight task PR poller, which checks watched linked PRs roughly once per minute; it does not add a separate scheduler. Saving enabled options also evaluates the task's current linked PRs without waiting for the next poll.
+2
View File
@@ -244,6 +244,8 @@ Open **PR events** for three notification controls:
Lifecycle messages only report the observed event and canonical PR URL; the task workflow and agent context decide what to do next. The repair prompt comes from the built-in `ci-auto-fix` saved prompt and can be overridden for the task. These controls currently operate on GitHub-linked PRs, require the GitHub integration and repository permissions, and do not bypass provider policy. Azure PR creation returns a URL but does not supply the same linked checks, review, or automation panel. See [Integrations](integrations.md).
When a task has more than one linked PR, each PR's tab in the automation popover controls that PR only. Enabling auto-fix or a review notification for one linked PR does not turn it on for the task's other linked PRs. The saved auto-fix prompt override is the one exception: it applies to every linked PR.
</details>
### GitLab MR automation
+7 -4
View File
@@ -108,13 +108,16 @@ workflows are not usable end to end.
switches — `Auto-fix CI and address comments` and `Auto-merge when ready` —
above a collapsible `Review follow-up` group holding the three lifecycle
notification switches (`Your review is requested`, `MR merged`, `MR closed
without merging`) introduced for MR lifecycle notifications. All five
switches are task-level and apply to every linked MR; auto-fix and auto-merge
additionally track per-MR round/attempt state. See "Automation (lifecycle,
without merging`) introduced for MR lifecycle notifications. These switches
currently use task-level settings, so changing one linked MR's control also
affects the task's other linked MRs. Per-MR switch scoping, including
per-MR round/attempt state and identity-aware `PATCH`/MCP updates, is tracked
in the "Scope GitLab MR automation switches per MR" follow-up task. The
auto-fix prompt override remains task-level. See "Automation (lifecycle,
auto-fix, auto-merge)" below.
- `Auto-fix CI and address comments` sends or queues an agent prompt when a
linked MR's pipeline has a new or changed failing job, or a new or changed
unresolved discussion note, capped at 10 accepted rounds per task/MR.
unresolved discussion note, capped at 10 accepted rounds per task.
`Auto-merge when ready` merges a linked MR only when it is open, not a
draft, its pipeline succeeded, it has zero unresolved discussions, and
GitLab's own merge-readiness verdict agrees.
+122 -30
View File
@@ -12,28 +12,35 @@ Users can already see pull request CI/review status above the task chat input,
but acting on a red PR still requires repeatedly noticing the failure, prompting
the agent, and deciding when it is safe to merge. A review task can also go
idle after submitting a review and miss a later re-review request, merge, or
close. Users and task agents need one task-level control plane that keeps a
linked PR moving throughout its lifecycle.
close. Users and task agents need automation controls that keep a linked PR
moving throughout its lifecycle, configured independently per linked PR so a
task with several open PRs does not force the same setting onto all of them.
Decision: [ADR-0051](../../decisions/0051-pr-agent-notifications-extend-task-pr-automation.md).
Decision: [ADR-0051](../../decisions/0051-pr-agent-notifications-extend-task-pr-automation.md)
(the task-level control plane for the five switches was superseded by per-PR
scoping; see that ADR's Consequences section).
## What
- The PR CI popover above the chat input shows five task-level automation controls:
- The PR CI popover above the chat input shows five automation controls,
scoped to the selected linked PR:
- `Auto-fix CI & address comments`
- `Auto-merge when ready`
- `Your review is requested`
- `PR merged`
- `PR closed without merging`
- The automation section states which PR the controls apply to (the PR number,
interpolated into localized copy), since a task can have several linked PRs
each with independent settings.
- The automation section includes an info icon or equivalent help affordance that explains what each control watches, how often Kandev checks watched PRs, how feedback snapshots prevent duplicate prompts, and how auto-merge decides readiness.
- The same controls are available anywhere the task PR CI popover is rendered, including the normal chat input status bar and passthrough toolbar surfaces.
- The shared desktop popover and mobile drawer keep auto-fix and auto-merge in
the primary automation list. The three agent lifecycle prompt switches live
together in a collapsed `PR events` section.
- `PR events` is presentation only. Its switches retain the same
task-wide behavior and remain reachable on desktop and mobile. When any of
its three options is enabled, the section opens so active automation is not
concealed.
together in a collapsed `Review follow-up` section.
- `Review follow-up` is presentation only. Its switches are per-PR like the
rest of the automation section and remain reachable on desktop and mobile.
When any of its three options is enabled for the selected PR, the section
opens so active automation is not concealed.
- Lifecycle switches stay compact single-line rows. Their explanations live in
on-demand help affordances (hover tooltip on fine pointers, tap popover on
touch) and screen-reader descriptions, not inline copy: the review-request
@@ -132,9 +139,16 @@ Decision: [ADR-0051](../../decisions/0051-pr-agent-notifications-extend-task-pr-
- If a task has no custom auto-fix prompt, Kandev uses a built-in default prompt named `ci-auto-fix`.
- The default `ci-auto-fix` prompt is editable from Settings > Prompts like other built-in prompts.
- Emptying or resetting the task prompt override returns the task to the default `ci-auto-fix` prompt.
- For tasks with multiple linked PRs, the controls are task-level and apply to
every linked PR. Dedupe, last-attempt, review-request, and terminal state are
tracked per linked PR.
- For tasks with multiple linked PRs, each of the five automation switches is
scoped per linked PR: `(task_id, repository_id, pr_number)`. Enabling a
switch in one PR's tab has no effect on any other linked PR's switches. A
`PATCH` that omits PR identity fans the requested change out to every
currently linked PR (unchanged behavior for MCP callers that predate
per-PR scoping); a newly linked PR always starts with all five switches
off. `auto_fix_prompt_override` and `review_reviewer_login` remain
task-level — one prompt override and one resolved reviewer identity apply
to every linked PR. Dedupe, last-attempt, review-request, and terminal
state are tracked per linked PR, as before.
- Kandev checks watched PRs through the existing lightweight PR watch poller, which runs once per minute. Automation wakeups sync the latest lightweight PR state before evaluating gates. When auto-fix is enabled, Kandev fetches full PR feedback so failing checks, requested changes, unresolved threads, and human PR conversation comments can trigger deduped prompts even when the persisted lightweight row was stale. Auto-fix waits until all PR checks have finished before sending or queueing a prompt, so the agent receives the final check set and current comments in one pass. Bot-authored PR conversation comments without failed checks or unresolved review threads are treated as non-actionable status chatter and do not send an agent prompt.
- Lightweight PR status sync counts unresolved review threads across every page
returned by GitHub. A connection's `totalCount` indicates that more threads
@@ -189,22 +203,41 @@ Decision: [ADR-0051](../../decisions/0051-pr-agent-notifications-extend-task-pr-
`github_task_ci_options`
- `task_id` string, primary key. References the Kandev task that owns the controls.
- `auto_fix_enabled` boolean, default `false`.
- `auto_merge_enabled` boolean, default `false`.
- `task_id` string, primary key. References the Kandev task that owns the
task-level controls.
- `auto_fix_prompt_override` string nullable. `NULL` or empty means use the default `ci-auto-fix` prompt.
- `prompt_on_review_requested` boolean, default `false`.
- `prompt_on_merged` boolean, default `false`.
- `prompt_on_closed` boolean, default `false`.
- `review_reviewer_login` string, default `""`. Bound to the current connected
GitHub login when review-requested prompting is enabled and rebound when that
authenticated identity changes.
GitHub login when review-requested prompting is enabled for any linked PR,
and rebound when that authenticated identity changes.
- `auto_fix_enabled`, `auto_merge_enabled`, `prompt_on_review_requested`,
`prompt_on_merged`, `prompt_on_closed` columns remain on this table for
migration purposes only: they are read once by the additive
`pr_scope_migrated_at`-guarded fan-out into `github_task_pr_automation_options`
and are never read or written after that. Their current source of truth is
the per-PR table below.
- `pr_scope_migrated_at` timestamp nullable. Guards the one-time fan-out so it
never re-runs and re-enables a switch a user has since turned off for one PR.
- Legacy `review_prompt_override`, `merged_prompt_override`, and
`closed_prompt_override` nullable columns remain only for additive migration
compatibility. Startup clears persisted values and runtime ignores them.
- `created_at` timestamp.
- `updated_at` timestamp.
`github_task_pr_automation_options`
- Primary key: `task_id`, `repository_id`, `pr_number`. Source of truth for
the five automation switches, one row per linked PR.
- `auto_fix_enabled` boolean, default `false`.
- `auto_merge_enabled` boolean, default `false`.
- `prompt_on_review_requested` boolean, default `false`.
- `prompt_on_merged` boolean, default `false`.
- `prompt_on_closed` boolean, default `false`.
- `created_at` timestamp.
- `updated_at` timestamp.
- A PR with no row here (never configured) behaves as all-off; the response
and UI synthesize an all-off placeholder rather than requiring one row per
linked PR to exist up front.
`github_task_ci_pr_state`
- Primary key: `task_id`, `repository_id`, `pr_number`.
@@ -274,10 +307,30 @@ Response:
"last_merge_attempt_at": null,
"last_error": null
}
],
"pr_options": [
{
"task_id": "task-123",
"repository_id": "repo-123",
"pr_number": 42,
"auto_fix_enabled": false,
"auto_merge_enabled": false,
"prompt_on_review_requested": false,
"prompt_on_merged": false,
"prompt_on_closed": false,
"created_at": "2026-06-18T00:00:00Z",
"updated_at": "2026-06-18T00:00:00Z"
}
]
}
```
`pr_options` carries one entry per PR currently linked to the task — the
per-PR source of truth. The five top-level booleans are an aggregate kept for
MCP/API read compatibility: `true` only when every linked PR has that switch
on and at least one PR is linked, so they answer "did my task-wide enable
take" rather than any one PR's state.
```http
PATCH /tasks/:taskId/ci-options
```
@@ -286,6 +339,8 @@ Request fields are partial:
```json
{
"repository_id": "repo-123",
"pr_number": 42,
"auto_fix_enabled": true,
"auto_merge_enabled": false,
"prompt_on_review_requested": true,
@@ -295,17 +350,29 @@ Request fields are partial:
}
```
`auto_fix_prompt_override: null` or an empty string clears the task override.
The response shape matches `GET`. Lifecycle override fields are rejected.
`repository_id` and `pr_number` are optional but must both be present or both
absent. When present, they target the five automation switches at that one
linked PR only; naming a `(repository_id, pr_number)` pair that is not
currently linked to the task returns `400` and writes nothing. When absent,
the five switches fan out to every PR currently linked to the task (unchanged
behavior for callers written before per-PR scoping). `auto_fix_prompt_override`
and the resolved reviewer login (set implicitly when
`prompt_on_review_requested` changes) always apply task-wide regardless of PR
identity. `auto_fix_prompt_override: null` or an empty string clears the task
override. The response shape matches `GET`. Lifecycle override fields are
rejected.
Task-mode MCP exposes current-task-only tools:
- `get_task_pr_automation_kandev`
- `update_task_pr_automation_kandev`
The MCP connection supplies the task ID. Update is partial and accepts auto-fix,
auto-merge, the three lifecycle booleans, and the auto-fix prompt override; it
cannot target another task. Lifecycle override fields are rejected.
The MCP connection supplies the task ID. Update is partial and accepts the
same optional `repository_id`/`pr_number` PR-identity pair as the HTTP PATCH,
auto-fix, auto-merge, the three lifecycle booleans, and the auto-fix prompt
override; it cannot target another task. Omitting PR identity fans the
switches out to every linked PR, preserving pre-per-PR-scoping agent
behavior. Lifecycle override fields are rejected.
Optional websocket notification:
@@ -316,9 +383,9 @@ Optional websocket notification:
## State machine
Task CI automation options:
Per-PR automation switches (state applies independently to each linked PR):
- `disabled`: all five automation switches are false. PR watch events update UI only.
- `disabled`: all five automation switches are false for this PR. PR watch events update UI only.
- `auto_fix_enabled`: Kandev evaluates actionable PR feedback immediately when enabled, when CI automation options are saved while it remains enabled, and on later PR watch events.
- `auto_merge_enabled`: Kandev evaluates PR merge readiness immediately when enabled, when CI automation options are saved while it remains enabled, and on later PR watch events.
- `both_enabled`: Kandev evaluates both paths. Auto-fix does not merge; auto-merge merges only after readiness conditions are satisfied.
@@ -512,7 +579,31 @@ Auto-merge cycle for one task/PR:
- **GIVEN** auto-merge is enabled and the PR has passing checks, required reviews, no unresolved threads, and clean mergeability, **WHEN** the PR watch poll observes the ready state, **THEN** Kandev merges the PR with the existing backend merge-method selection.
- **GIVEN** auto-merge is enabled but the PR is a draft or has requested changes, pending required review, failing checks, unresolved threads, or dirty mergeability, **WHEN** the PR watch poll observes the state, **THEN** Kandev does not merge.
- **GIVEN** auto-merge attempted a ready-state merge and GitHub rejected it, **WHEN** the same ready state is observed again, **THEN** Kandev does not retry until the readiness signature changes.
- **GIVEN** a task has two open linked PRs, **WHEN** the user enables either automation control, **THEN** both PRs are eligible for automation and each PR records its own last-fix and last-merge state.
- **GIVEN** a task has two open linked PRs, **WHEN** the user enables an
automation control from the first PR's tab, **THEN** only that PR becomes
eligible for automation; the second PR's tab shows the control unchanged,
and each PR records its own last-fix and last-merge state.
- **GIVEN** a task has two linked PRs in different repositories with the same
PR number, **WHEN** the user enables a switch for one, **THEN** the other's
switch is unaffected, because switch identity is
`(task_id, repository_id, pr_number)`.
- **GIVEN** a task has two linked PRs, **WHEN** an agent calls
`update_task_pr_automation_kandev` naming one PR's `repository_id` and
`pr_number`, **THEN** only that PR's switches change.
- **GIVEN** a task has two linked PRs, **WHEN** an agent calls
`update_task_pr_automation_kandev` without `repository_id`/`pr_number`,
**THEN** the requested switch changes on every currently linked PR.
- **GIVEN** a task has two linked PRs, **WHEN** the user disables auto-fix on
one PR while it stays enabled on the other, **THEN** re-enabling it on the
first PR resets only that PR's `auto_fix_round_count`, exhaustion, and fix
checkpoint; the second PR's checkpoint is unchanged.
- **GIVEN** a task's automation was configured before per-PR scoping shipped,
**WHEN** the backend boots for the first time after upgrade, **THEN** every
PR linked to that task at boot time inherits the legacy task-level values,
and a PR linked to the task afterward starts with all five switches off.
- **GIVEN** a task's automation was already migrated to per-PR scoping and a
user has since turned a switch off for one PR, **WHEN** the backend boots
again, **THEN** that PR's switch remains off — the migration never replays.
- **GIVEN** review-request prompting is enabled while the connected GitHub user
is already requested, **WHEN** Kandev first evaluates the PR, **THEN** it
records a quiet baseline and does not prompt.
@@ -593,7 +684,8 @@ Auto-merge cycle for one task/PR:
- Selecting a destination workflow step for a lifecycle event. Lifecycle
notifications prompt the task in its current workflow step; event-to-step
routing is a follow-up feature.
- Per-PR automation toggles in the first version.
- Per-PR auto-fix **prompt overrides**. `auto_fix_prompt_override` remains
task-level; only the five boolean switches are per-PR.
- Per-user automation preferences.
- Merge-method selection UI. Auto-merge uses the existing backend default merge-method selection.
- Team-level review-request matching. The first version tracks the
@@ -601,7 +693,7 @@ Auto-merge cycle for one task/PR:
- Creating a replacement task session when the existing task has no promptable
session.
- Configuring lifecycle prompt text. The lifecycle templates are intentionally
immutable and server-owned; only the three task-level booleans are exposed.
immutable and server-owned; only the three per-PR booleans are exposed.
- Streaming CI logs into the chat or popover.
- Editing GitHub branch protection, review rules, or workflow files directly from the automation controls.
- GitLab merge request automation.