feat(github): surface pull request merge queue status (#2928)

This commit is contained in:
Carlos Florêncio
2026-08-22 19:51:59 +00:00
committed by GitHub
parent 26ef699b00
commit 690a1ec3fe
51 changed files with 2306 additions and 166 deletions
@@ -47,6 +47,7 @@ func (r *githubTaskStatusSummaryPRReader) ListTaskStatusSummaryPullRequests(
ReviewState: pr.ReviewState,
ChecksState: pr.ChecksState,
MergeableState: pr.MergeableState,
MergeQueueState: pr.MergeQueueState,
UnresolvedReviewCount: pr.UnresolvedReviewThreads,
PendingReviewCount: pr.PendingReviewCount,
RequiredReviews: requiredReviews,
@@ -1,11 +1,37 @@
package backendapp
import (
"context"
"path/filepath"
"testing"
"time"
"github.com/jmoiron/sqlx"
"github.com/kandev/kandev/internal/db"
"github.com/kandev/kandev/internal/github"
)
func newStatusSummaryTestStore(t *testing.T) *github.Store {
t.Helper()
dbConn, err := db.OpenSQLite(filepath.Join(t.TempDir(), "github.db"))
if err != nil {
t.Fatalf("open db: %v", err)
}
sqlxDB := sqlx.NewDb(dbConn, "sqlite3")
t.Cleanup(func() { _ = sqlxDB.Close() })
if _, err := sqlxDB.Exec(`CREATE TABLE tasks (id TEXT PRIMARY KEY, workspace_id TEXT, archived_at DATETIME)`); err != nil {
t.Fatalf("create tasks table: %v", err)
}
if _, err := sqlxDB.Exec(`CREATE TABLE workspaces (id TEXT PRIMARY KEY)`); err != nil {
t.Fatalf("create workspaces table: %v", err)
}
store, err := github.NewStore(sqlxDB, sqlxDB)
if err != nil {
t.Fatalf("new store: %v", err)
}
return store
}
func TestTaskStatusSummaryPRKeyMatchesLiveEventIdentity(t *testing.T) {
tests := []struct {
name string
@@ -60,3 +86,31 @@ func TestTaskStatusRuntimeProvidersTreatNilOrchestratorAsAbsent(t *testing.T) {
t.Fatal("queued prompt counter should be nil without an orchestrator")
}
}
func TestGitHubTaskStatusSummaryPRReaderPreservesMergeQueueState(t *testing.T) {
ctx := context.Background()
store := newStatusSummaryTestStore(t)
queuePR := &github.TaskPR{
TaskID: "task-queue-summary", RepositoryID: "repo-queue-summary", PRNumber: 42,
PRURL: "https://example.test/42", State: "open", CreatedAt: time.Now().UTC(),
MergeQueueState: "queued",
}
if err := store.CreateTaskPR(ctx, queuePR); err != nil {
t.Fatalf("CreateTaskPR: %v", err)
}
reader := &githubTaskStatusSummaryPRReader{
gh: github.NewService(nil, "", nil, store, nil, nil),
}
result, err := reader.ListTaskStatusSummaryPullRequests(ctx, []string{queuePR.TaskID})
if err != nil {
t.Fatalf("ListTaskStatusSummaryPullRequests: %v", err)
}
inputs := result[queuePR.TaskID]
if len(inputs) != 1 {
t.Fatalf("summary inputs = %+v, want one input", inputs)
}
if inputs[0].MergeQueueState != queuePR.MergeQueueState {
t.Fatalf("MergeQueueState = %q, want %q", inputs[0].MergeQueueState, queuePR.MergeQueueState)
}
}
+57 -15
View File
@@ -183,9 +183,14 @@ type batchedPRResult struct {
// IsDraft is a pointer: AC-12a requires distinguishing an upstream
// response that omits or nulls isDraft from one that genuinely reports
// false, and a plain bool can't tell the two apart after decode.
IsDraft *bool `json:"isDraft"`
Mergeable string `json:"mergeable"`
MergeStatus string `json:"mergeStateStatus"`
IsDraft *bool `json:"isDraft"`
Mergeable string `json:"mergeable"`
MergeStatus string `json:"mergeStateStatus"`
MergeQueueEntry *struct {
State string `json:"state"`
Position *int `json:"position"`
EstimatedTimeToMerge *int `json:"estimatedTimeToMerge"`
} `json:"mergeQueueEntry"`
HeadRefName string `json:"headRefName"`
BaseRefName string `json:"baseRefName"`
HeadRefOid string `json:"headRefOid"`
@@ -413,6 +418,7 @@ func prFieldsBlock() string {
return `state title url isDraft mergeable mergeStateStatus ` +
`headRefName baseRefName headRefOid additions deletions changedFiles ` +
`author { login } mergedBy { login } autoMergeRequest { enabledAt } ` +
`mergeQueueEntry { state position estimatedTimeToMerge } ` +
`createdAt updatedAt mergedAt closedAt ` +
`reviews(last: 100) { nodes { state author { login } submittedAt } } ` +
`reviewRequests(first: 0) { totalCount } ` +
@@ -490,22 +496,58 @@ func convertBatchedPRResult(raw *batchedPRResult, owner, repo string, number int
}
}
closedByLogin, closureAttributionPopulated := closedEventActor(raw.TimelineItems.Nodes)
mergeQueueState, mergeQueuePosition, mergeQueueEstimate := convertMergeQueueEntry(raw.MergeQueueEntry)
return &PRStatus{
PR: pr,
ReviewState: reviewState,
ChecksState: checksState,
MergeableState: pr.MergeableState,
ReviewCount: countApprovedReviewerNodes(raw.Reviews.Nodes),
PendingReviewCount: raw.ReviewRequests.TotalCount,
ReviewCountsPopulated: true,
UnresolvedReviewThreads: unresolved,
UnresolvedReviewThreadsPopulated: true,
OutcomeFieldsPopulated: true,
ClosedByLogin: closedByLogin,
ClosureAttributionPopulated: closureAttributionPopulated,
PR: pr,
ReviewState: reviewState,
ChecksState: checksState,
MergeableState: pr.MergeableState,
ReviewCount: countApprovedReviewerNodes(raw.Reviews.Nodes),
PendingReviewCount: raw.ReviewRequests.TotalCount,
ReviewCountsPopulated: true,
UnresolvedReviewThreads: unresolved,
UnresolvedReviewThreadsPopulated: true,
OutcomeFieldsPopulated: true,
ClosedByLogin: closedByLogin,
ClosureAttributionPopulated: closureAttributionPopulated,
MergeQueueState: mergeQueueState,
MergeQueuePosition: mergeQueuePosition,
MergeQueueEstimatedTimeToMergeSeconds: mergeQueueEstimate,
mergeQueuePopulated: true,
}
}
func convertMergeQueueEntry(entry *struct {
State string `json:"state"`
Position *int `json:"position"`
EstimatedTimeToMerge *int `json:"estimatedTimeToMerge"`
}) (string, *int, *int) {
if entry == nil {
return "", nil, nil
}
return normalizeMergeQueueState(entry.State), positiveIntPtr(entry.Position), nonNegativeIntPtr(entry.EstimatedTimeToMerge)
}
func normalizeMergeQueueState(raw string) string {
return strings.ToLower(strings.TrimSpace(raw))
}
func positiveIntPtr(value *int) *int {
if value == nil || *value <= 0 {
return nil
}
copy := *value
return &copy
}
func nonNegativeIntPtr(value *int) *int {
if value == nil || *value < 0 {
return nil
}
copy := *value
return &copy
}
// closedEventActor extracts the closed-event actor's login from a
// `timelineItems(itemTypes: CLOSED_EVENT)` node list. Returns
// populated=false when there is no node or the node's actor is null (e.g. a
@@ -0,0 +1,77 @@
package github
import (
"encoding/json"
"strings"
"testing"
)
func TestPRFieldsBlockRequestsMergeQueueEntry(t *testing.T) {
block := prFieldsBlock()
if !strings.Contains(block, "mergeQueueEntry { state position estimatedTimeToMerge }") {
t.Fatalf("prFieldsBlock() = %s, want merge queue fields", block)
}
}
func TestConvertBatchedPRResultPreservesMergeQueueObservation(t *testing.T) {
tests := []struct {
name string
entry string
wantState string
wantPosition *int
wantEstimate *int
wantObserved bool
}{
{
name: "queued with metadata",
entry: `{"state":"QUEUED","position":3,"estimatedTimeToMerge":125}`,
wantState: "queued",
wantPosition: intPtr(3),
wantEstimate: intPtr(125),
wantObserved: true,
},
{
name: "active entry without estimate",
entry: `{"state":"MERGEABLE","position":1,"estimatedTimeToMerge":null}`,
wantState: "mergeable",
wantPosition: intPtr(1),
wantObserved: true,
},
{
name: "queue exit",
entry: `null`,
wantObserved: true,
},
{
name: "unknown future state",
entry: `{"state":"PAUSED","position":7,"estimatedTimeToMerge":60}`,
wantState: "paused",
wantPosition: intPtr(7),
wantEstimate: intPtr(60),
wantObserved: true,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
raw := &batchedPRResult{}
payload := []byte(`{"state":"OPEN","mergeQueueEntry":` + test.entry + `}`)
if err := json.Unmarshal(payload, raw); err != nil {
t.Fatalf("decode GraphQL payload: %v", err)
}
status := convertBatchedPRResult(raw, "owner", "repo", 42)
if status.MergeQueueState != test.wantState {
t.Errorf("MergeQueueState = %q, want %q", status.MergeQueueState, test.wantState)
}
if !intPtrEqual(status.MergeQueuePosition, test.wantPosition) {
t.Errorf("MergeQueuePosition = %v, want %v", status.MergeQueuePosition, test.wantPosition)
}
if !intPtrEqual(status.MergeQueueEstimatedTimeToMergeSeconds, test.wantEstimate) {
t.Errorf("MergeQueueEstimatedTimeToMergeSeconds = %v, want %v", status.MergeQueueEstimatedTimeToMergeSeconds, test.wantEstimate)
}
if status.mergeQueuePopulated != test.wantObserved {
t.Errorf("mergeQueuePopulated = %v, want %v", status.mergeQueuePopulated, test.wantObserved)
}
})
}
}
+47 -41
View File
@@ -604,29 +604,32 @@ func (c *MockController) addRepoFiles(ctx *gin.Context) {
// associateTaskPR endpoint. Pointer fields are optional — leave them nil
// to skip the corresponding TaskPR column update.
type associateTaskPRRequest struct {
TaskID string `json:"task_id"`
WorkspaceID string `json:"workspace_id,omitempty"`
RepositoryID string `json:"repository_id,omitempty"`
Owner string `json:"owner"`
Repo string `json:"repo"`
PRNumber int `json:"pr_number"`
PRURL string `json:"pr_url"`
PRTitle string `json:"pr_title"`
HeadBranch string `json:"head_branch"`
BaseBranch string `json:"base_branch"`
AuthorLogin string `json:"author_login"`
State string `json:"state"`
ReviewState string `json:"review_state"`
ChecksState string `json:"checks_state"`
MergeableState string `json:"mergeable_state"`
Additions int `json:"additions"`
Deletions int `json:"deletions"`
ReviewCount *int `json:"review_count,omitempty"`
PendingReviewCount *int `json:"pending_review_count,omitempty"`
RequiredReviews *int `json:"required_reviews,omitempty"`
ChecksTotal *int `json:"checks_total,omitempty"`
ChecksPassing *int `json:"checks_passing,omitempty"`
UnresolvedReviewThreads *int `json:"unresolved_review_threads,omitempty"`
TaskID string `json:"task_id"`
WorkspaceID string `json:"workspace_id,omitempty"`
RepositoryID string `json:"repository_id,omitempty"`
Owner string `json:"owner"`
Repo string `json:"repo"`
PRNumber int `json:"pr_number"`
PRURL string `json:"pr_url"`
PRTitle string `json:"pr_title"`
HeadBranch string `json:"head_branch"`
BaseBranch string `json:"base_branch"`
AuthorLogin string `json:"author_login"`
State string `json:"state"`
ReviewState string `json:"review_state"`
ChecksState string `json:"checks_state"`
MergeableState string `json:"mergeable_state"`
MergeQueueState string `json:"merge_queue_state"`
MergeQueuePosition *int `json:"merge_queue_position,omitempty"`
MergeQueueEstimatedTimeToMergeSeconds *int `json:"merge_queue_estimated_time_to_merge_seconds,omitempty"`
Additions int `json:"additions"`
Deletions int `json:"deletions"`
ReviewCount *int `json:"review_count,omitempty"`
PendingReviewCount *int `json:"pending_review_count,omitempty"`
RequiredReviews *int `json:"required_reviews,omitempty"`
ChecksTotal *int `json:"checks_total,omitempty"`
ChecksPassing *int `json:"checks_passing,omitempty"`
UnresolvedReviewThreads *int `json:"unresolved_review_threads,omitempty"`
}
// associateTaskPR directly creates (or replaces) a github_task_prs record for
@@ -669,24 +672,27 @@ func (c *MockController) associateTaskPR(ctx *gin.Context) {
// a TaskPR and applies the optional pointer fields when present.
func buildTaskPRFromRequest(req *associateTaskPRRequest, now time.Time) *TaskPR {
tp := &TaskPR{
TaskID: req.TaskID,
WorkspaceID: req.WorkspaceID,
RepositoryID: req.RepositoryID,
Owner: req.Owner,
Repo: req.Repo,
PRNumber: req.PRNumber,
PRURL: req.PRURL,
PRTitle: req.PRTitle,
HeadBranch: req.HeadBranch,
BaseBranch: req.BaseBranch,
AuthorLogin: req.AuthorLogin,
State: req.State,
ReviewState: req.ReviewState,
ChecksState: req.ChecksState,
MergeableState: req.MergeableState,
Additions: req.Additions,
Deletions: req.Deletions,
CreatedAt: now,
TaskID: req.TaskID,
WorkspaceID: req.WorkspaceID,
RepositoryID: req.RepositoryID,
Owner: req.Owner,
Repo: req.Repo,
PRNumber: req.PRNumber,
PRURL: req.PRURL,
PRTitle: req.PRTitle,
HeadBranch: req.HeadBranch,
BaseBranch: req.BaseBranch,
AuthorLogin: req.AuthorLogin,
State: req.State,
ReviewState: req.ReviewState,
ChecksState: req.ChecksState,
MergeableState: req.MergeableState,
MergeQueueState: req.MergeQueueState,
MergeQueuePosition: req.MergeQueuePosition,
MergeQueueEstimatedTimeToMergeSeconds: req.MergeQueueEstimatedTimeToMergeSeconds,
Additions: req.Additions,
Deletions: req.Deletions,
CreatedAt: now,
}
if req.ReviewCount != nil {
tp.ReviewCount = *req.ReviewCount
@@ -0,0 +1,18 @@
package github
import (
"testing"
"time"
)
func TestBuildTaskPRFromRequestCopiesMergeQueueStatus(t *testing.T) {
position := 9
estimate := 360
req := &associateTaskPRRequest{
TaskID: "task-queue-fixture", PRNumber: 42, State: "open",
MergeQueueState: "queued", MergeQueuePosition: &position,
MergeQueueEstimatedTimeToMergeSeconds: &estimate,
}
tp := buildTaskPRFromRequest(req, time.Now().UTC())
assertTaskPRMergeQueueFields(t, "mock fixture", tp, "queued", &position, &estimate)
}
+33 -23
View File
@@ -365,11 +365,15 @@ type PRStatus struct {
ReviewState string `json:"review_state"` // "approved", "changes_requested", "pending", ""
ChecksState string `json:"checks_state"` // "success", "failure", "pending", ""
MergeableState string `json:"mergeable_state"` // "clean", "blocked", "behind", "dirty", "has_hooks", "unstable", "draft", "unknown", ""
ReviewCount int `json:"review_count"`
PendingReviewCount int `json:"pending_review_count"`
RequiredReviews *int `json:"required_reviews,omitempty"` // nil when no branch protection rule found
ChecksTotal int `json:"checks_total"`
ChecksPassing int `json:"checks_passing"`
MergeQueueState string `json:"merge_queue_state"`
MergeQueuePosition *int `json:"merge_queue_position,omitempty"`
// A nil estimate is an observed absence when mergeQueuePopulated is true.
MergeQueueEstimatedTimeToMergeSeconds *int `json:"merge_queue_estimated_time_to_merge_seconds,omitempty"`
ReviewCount int `json:"review_count"`
PendingReviewCount int `json:"pending_review_count"`
RequiredReviews *int `json:"required_reviews,omitempty"` // nil when no branch protection rule found
ChecksTotal int `json:"checks_total"`
ChecksPassing int `json:"checks_passing"`
// ChecksPopulated reports whether the sync path actually computed
// ChecksTotal / ChecksPassing. The batched GraphQL poller doesn't (it
// only carries the rollup state), so SyncTaskPR uses this flag to
@@ -403,6 +407,9 @@ type PRStatus struct {
// closed-event actor with a non-empty login. REST and gh CLI single-PR
// syncs can never set this — they have no closing-actor field to read.
ClosureAttributionPopulated bool `json:"closure_attribution_populated,omitempty"`
// mergeQueuePopulated distinguishes a GraphQL observation (including a
// null mergeQueueEntry) from REST and gh CLI reads that have no queue data.
mergeQueuePopulated bool
}
// PRSearchPage is a paginated slice of PR search results, with the total
@@ -447,24 +454,27 @@ type PRWatch struct {
// repository this PR belongs to (multi-repo tasks can have one PR per repo).
// Empty for legacy rows persisted before multi-repo support.
type TaskPR struct {
ID string `json:"id" db:"id"`
WorkspaceID string `json:"workspace_id" db:"workspace_id"`
TaskID string `json:"task_id" db:"task_id"`
RepositoryID string `json:"repository_id,omitempty" db:"repository_id"`
Owner string `json:"owner" db:"owner"`
Repo string `json:"repo" db:"repo"`
PRNumber int `json:"pr_number" db:"pr_number"`
PRURL string `json:"pr_url" db:"pr_url"`
PRTitle string `json:"pr_title" db:"pr_title"`
HeadBranch string `json:"head_branch" db:"head_branch"`
BaseBranch string `json:"base_branch" db:"base_branch"`
AuthorLogin string `json:"author_login" db:"author_login"`
State string `json:"state" db:"state"` // open, closed, merged
ReviewState string `json:"review_state" db:"review_state"` // approved, changes_requested, pending, ""
ChecksState string `json:"checks_state" db:"checks_state"` // success, failure, pending, ""
MergeableState string `json:"mergeable_state" db:"mergeable_state"` // clean, blocked, behind, dirty, has_hooks, unstable, draft, unknown, ""
ReviewCount int `json:"review_count" db:"review_count"`
PendingReviewCount int `json:"pending_review_count" db:"pending_review_count"`
ID string `json:"id" db:"id"`
WorkspaceID string `json:"workspace_id" db:"workspace_id"`
TaskID string `json:"task_id" db:"task_id"`
RepositoryID string `json:"repository_id,omitempty" db:"repository_id"`
Owner string `json:"owner" db:"owner"`
Repo string `json:"repo" db:"repo"`
PRNumber int `json:"pr_number" db:"pr_number"`
PRURL string `json:"pr_url" db:"pr_url"`
PRTitle string `json:"pr_title" db:"pr_title"`
HeadBranch string `json:"head_branch" db:"head_branch"`
BaseBranch string `json:"base_branch" db:"base_branch"`
AuthorLogin string `json:"author_login" db:"author_login"`
State string `json:"state" db:"state"` // open, closed, merged
ReviewState string `json:"review_state" db:"review_state"` // approved, changes_requested, pending, ""
ChecksState string `json:"checks_state" db:"checks_state"` // success, failure, pending, ""
MergeableState string `json:"mergeable_state" db:"mergeable_state"` // clean, blocked, behind, dirty, has_hooks, unstable, draft, unknown, ""
MergeQueueState string `json:"merge_queue_state" db:"merge_queue_state"`
MergeQueuePosition *int `json:"merge_queue_position" db:"merge_queue_position"`
MergeQueueEstimatedTimeToMergeSeconds *int `json:"merge_queue_estimated_time_to_merge_seconds" db:"merge_queue_estimated_time_to_merge_seconds"`
ReviewCount int `json:"review_count" db:"review_count"`
PendingReviewCount int `json:"pending_review_count" db:"pending_review_count"`
// RequiredReviews is the branch protection's required_approving_review_count.
// Nil when no protection rule exists or the token lacks scope to read it.
RequiredReviews *int `json:"required_reviews,omitempty" db:"required_reviews"`
@@ -0,0 +1,99 @@
package github
import (
"context"
"testing"
"time"
)
func TestSyncTaskPRPersistsMergeQueueObservationAndPublishesChange(t *testing.T) {
svc, store, eventBus := setupSyncTest(t)
ctx := context.Background()
position := 3
estimate := 125
taskPR := &TaskPR{
TaskID: "task-queue-sync", Owner: "owner", Repo: "repo", PRNumber: 42,
PRURL: "https://example.test/42", PRTitle: "queued", State: "open",
MergeQueueState: "", CreatedAt: nowUTC(),
}
if err := store.CreateTaskPR(ctx, taskPR); err != nil {
t.Fatalf("seed TaskPR: %v", err)
}
status := &PRStatus{
PR: &PR{Number: 42, State: "open", RepoOwner: "owner", RepoName: "repo"},
MergeQueueState: "queued", MergeQueuePosition: &position,
MergeQueueEstimatedTimeToMergeSeconds: &estimate, mergeQueuePopulated: true,
}
if err := svc.SyncTaskPR(ctx, taskPR.TaskID, status); err != nil {
t.Fatalf("SyncTaskPR: %v", err)
}
got := mustGetTaskPR(t, store, ctx, taskPR.ID)
assertTaskPRMergeQueueFields(t, "SyncTaskPR", got, "queued", &position, &estimate)
if eventBus.publishedCount() != 1 {
t.Fatalf("published events = %d, want 1", eventBus.publishedCount())
}
}
func TestSyncTaskPRPreservesQueueOnQueueUnawareRead(t *testing.T) {
svc, store, _ := setupSyncTest(t)
ctx := context.Background()
position := 6
estimate := 240
taskPR := &TaskPR{
TaskID: "task-queue-preserve", Owner: "owner", Repo: "repo", PRNumber: 43,
PRURL: "https://example.test/43", PRTitle: "queued", State: "open",
MergeQueueState: "queued", MergeQueuePosition: &position,
MergeQueueEstimatedTimeToMergeSeconds: &estimate, CreatedAt: nowUTC(),
}
if err := store.CreateTaskPR(ctx, taskPR); err != nil {
t.Fatalf("seed TaskPR: %v", err)
}
if err := svc.SyncTaskPR(ctx, taskPR.TaskID, &PRStatus{
PR: &PR{Number: 43, State: "open", RepoOwner: "owner", RepoName: "repo"},
}); err != nil {
t.Fatalf("queue-unaware SyncTaskPR: %v", err)
}
assertTaskPRMergeQueueFields(t, "queue-unaware SyncTaskPR", mustGetTaskPR(t, store, ctx, taskPR.ID), "queued", &position, &estimate)
}
func TestSyncTaskPRClearsQueueOnAuthoritativeExitAndTerminalState(t *testing.T) {
tests := []struct {
name string
state string
}{
{name: "queue exit", state: "open"},
{name: "merged", state: "merged"},
{name: "closed", state: "closed"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
svc, store, _ := setupSyncTest(t)
ctx := context.Background()
position := 2
estimate := 60
taskPR := &TaskPR{
TaskID: "task-queue-clear-" + test.name, Owner: "owner", Repo: "repo", PRNumber: 44,
PRURL: "https://example.test/44", PRTitle: "queued", State: "open",
MergeQueueState: "queued", MergeQueuePosition: &position,
MergeQueueEstimatedTimeToMergeSeconds: &estimate, CreatedAt: nowUTC(),
}
if err := store.CreateTaskPR(ctx, taskPR); err != nil {
t.Fatalf("seed TaskPR: %v", err)
}
status := &PRStatus{
PR: &PR{Number: 44, State: test.state, RepoOwner: "owner", RepoName: "repo"},
}
if test.name == "queue exit" {
status.mergeQueuePopulated = true
}
if err := svc.SyncTaskPR(ctx, taskPR.TaskID, status); err != nil {
t.Fatalf("SyncTaskPR: %v", err)
}
assertTaskPRMergeQueueFields(t, test.name, mustGetTaskPR(t, store, ctx, taskPR.ID), "", nil, nil)
})
}
}
func nowUTC() time.Time {
return time.Now().UTC()
}
@@ -741,6 +741,8 @@ type taskPRSyncState struct {
unresolved, reviewCount, pendingReviewCount int
requiredReviews *int
baseBranch, mergeableState, state string
mergeQueueState string
mergeQueuePosition, mergeQueueEstimate *int
mergedAt, closedAt *time.Time
isDraft *bool
changedFiles *int
@@ -748,6 +750,26 @@ type taskPRSyncState struct {
autoMergeObservedAt *time.Time
}
func resolveTaskPRMergeQueueFields(tp *TaskPR, status *PRStatus) (string, *int, *int) {
var state string
var position, estimate *int
if tp != nil {
state = tp.MergeQueueState
position = tp.MergeQueuePosition
estimate = tp.MergeQueueEstimatedTimeToMergeSeconds
}
if status == nil || status.PR == nil {
return state, position, estimate
}
if strings.EqualFold(status.PR.State, prStateMerged) || strings.EqualFold(status.PR.State, prStateClosed) {
return "", nil, nil
}
if !status.mergeQueuePopulated {
return state, position, estimate
}
return normalizeMergeQueueState(status.MergeQueueState), positiveIntPtr(status.MergeQueuePosition), nonNegativeIntPtr(status.MergeQueueEstimatedTimeToMergeSeconds)
}
// resolveTaskPROutcomeFields applies the populated/preserve dance for the
// five outcome-attribution columns, split out of prepareTaskPRSyncState to
// keep that function's complexity within the repo's lint limits (see the
@@ -873,6 +895,7 @@ func (s *Service) prepareTaskPRSyncState(ctx context.Context, tp *TaskPR, status
if status.PR.Draft {
nextMergeableState = "draft"
}
mergeQueueState, mergeQueuePosition, mergeQueueEstimate := resolveTaskPRMergeQueueFields(tp, status)
nextState, nextMergedAt, nextClosedAt := resolveTerminalMergeState(tp, status.PR)
nextIsDraft, nextChangedFiles, nextMergedByLogin, nextClosedByLogin, nextAutoMergeObservedAt :=
resolveTaskPROutcomeFields(tp, status)
@@ -880,6 +903,7 @@ func (s *Service) prepareTaskPRSyncState(ctx context.Context, tp *TaskPR, status
checksTotal: nextChecksTotal, checksPassing: nextChecksPassing,
unresolved: nextUnresolved, reviewCount: nextReviewCount, pendingReviewCount: nextPendingReviewCount,
requiredReviews: nextRequiredReviews, baseBranch: nextBaseBranch, mergeableState: nextMergeableState,
mergeQueueState: mergeQueueState, mergeQueuePosition: mergeQueuePosition, mergeQueueEstimate: mergeQueueEstimate,
state: nextState, mergedAt: nextMergedAt, closedAt: nextClosedAt,
isDraft: nextIsDraft, changedFiles: nextChangedFiles,
mergedByLogin: nextMergedByLogin, closedByLogin: nextClosedByLogin,
@@ -899,6 +923,9 @@ func taskPRChangedFields(tp *TaskPR, status *PRStatus, next taskPRSyncState) []s
changed = appendChangedField(changed, "review_state", tp.ReviewState != status.ReviewState)
changed = appendChangedField(changed, "checks_state", tp.ChecksState != status.ChecksState)
changed = appendChangedField(changed, "mergeable_state", tp.MergeableState != next.mergeableState)
changed = appendChangedField(changed, "merge_queue_state", tp.MergeQueueState != next.mergeQueueState)
changed = appendChangedField(changed, "merge_queue_position", !intPtrEqual(tp.MergeQueuePosition, next.mergeQueuePosition))
changed = appendChangedField(changed, "merge_queue_estimated_time_to_merge_seconds", !intPtrEqual(tp.MergeQueueEstimatedTimeToMergeSeconds, next.mergeQueueEstimate))
changed = appendChangedField(changed, "review_count", tp.ReviewCount != next.reviewCount)
changed = appendChangedField(
changed,
@@ -969,6 +996,9 @@ func (s *Service) SyncTaskPR(ctx context.Context, taskID string, status *PRStatu
tp.ReviewState = status.ReviewState
tp.ChecksState = status.ChecksState
tp.MergeableState = next.mergeableState
tp.MergeQueueState = next.mergeQueueState
tp.MergeQueuePosition = next.mergeQueuePosition
tp.MergeQueueEstimatedTimeToMergeSeconds = next.mergeQueueEstimate
tp.ReviewCount = next.reviewCount
tp.PendingReviewCount = next.pendingReviewCount
tp.RequiredReviews = next.requiredReviews
+61 -12
View File
@@ -122,6 +122,9 @@ const createTablesSQL = `
review_state TEXT NOT NULL DEFAULT '',
checks_state TEXT NOT NULL DEFAULT '',
mergeable_state TEXT NOT NULL DEFAULT '',
merge_queue_state TEXT NOT NULL DEFAULT '',
merge_queue_position INTEGER,
merge_queue_estimated_time_to_merge_seconds INTEGER,
review_count INTEGER DEFAULT 0,
pending_review_count INTEGER DEFAULT 0,
required_reviews INTEGER,
@@ -593,6 +596,35 @@ func (s *Store) initSchemaUpgrades() error {
if err := s.addTaskPROutcomeColumns(); err != nil {
return err
}
if err := s.addTaskPRMergeQueueColumns(); err != nil {
return err
}
return nil
}
var taskPRMergeQueueColumnDDL = []struct {
name string
ddl string
}{
{"merge_queue_state", "TEXT NOT NULL DEFAULT ''"},
{"merge_queue_position", "INTEGER"},
{"merge_queue_estimated_time_to_merge_seconds", "INTEGER"},
}
func (s *Store) addTaskPRMergeQueueColumns() error {
columns, err := s.tableColumns("github_task_prs")
if err != nil {
return fmt.Errorf("read github_task_prs columns: %w", err)
}
for _, column := range taskPRMergeQueueColumnDDL {
if _, ok := columns[column.name]; ok {
continue
}
stmt := "ALTER TABLE github_task_prs ADD COLUMN " + column.name + " " + column.ddl
if _, err := s.db.Exec(stmt); err != nil && !dbutil.IsDuplicateColumnError(err) {
return fmt.Errorf("add github_task_prs.%s: %w", column.name, err)
}
}
return nil
}
@@ -1331,6 +1363,9 @@ func (s *Store) migratePRTablesForMultiRepo() error {
review_state TEXT NOT NULL DEFAULT '',
checks_state TEXT NOT NULL DEFAULT '',
mergeable_state TEXT NOT NULL DEFAULT '',
merge_queue_state TEXT NOT NULL DEFAULT '',
merge_queue_position INTEGER,
merge_queue_estimated_time_to_merge_seconds INTEGER,
review_count INTEGER DEFAULT 0,
pending_review_count INTEGER DEFAULT 0,
required_reviews INTEGER,
@@ -1361,13 +1396,15 @@ func (s *Store) migratePRTablesForMultiRepo() error {
`INSERT INTO github_task_prs_new (
id, workspace_id, task_id, repository_id, owner, repo, pr_number, pr_url, pr_title,
head_branch, base_branch, author_login, state, review_state, checks_state,
mergeable_state, review_count, pending_review_count, comment_count,
mergeable_state, merge_queue_state, merge_queue_position, merge_queue_estimated_time_to_merge_seconds,
review_count, pending_review_count, comment_count,
additions, deletions, created_at, merged_at, closed_at, last_synced_at, detached_at, updated_at,
is_draft, changed_files, merged_by_login, closed_by_login, auto_merge_observed_at
) SELECT
id, COALESCE(workspace_id, ''), task_id, COALESCE(repository_id, ''), owner, repo, pr_number, pr_url, pr_title,
head_branch, base_branch, author_login, state, review_state, checks_state,
mergeable_state, review_count, pending_review_count, comment_count,
mergeable_state, merge_queue_state, merge_queue_position, merge_queue_estimated_time_to_merge_seconds,
review_count, pending_review_count, comment_count,
additions, deletions, created_at, merged_at, closed_at, last_synced_at, detached_at, updated_at,
is_draft, changed_files, merged_by_login, closed_by_login, auto_merge_observed_at
FROM github_task_prs`,
@@ -1685,13 +1722,16 @@ func (s *Store) CreateTaskPR(ctx context.Context, tp *TaskPR) error {
tp.UpdatedAt = now
_, err := s.db.ExecContext(ctx, `
INSERT INTO github_task_prs (id, workspace_id, task_id, repository_id, owner, repo, pr_number, pr_url, pr_title, head_branch, base_branch, author_login,
state, review_state, checks_state, mergeable_state, review_count, pending_review_count, required_reviews, comment_count,
state, review_state, checks_state, mergeable_state, merge_queue_state, merge_queue_position, merge_queue_estimated_time_to_merge_seconds, review_count, pending_review_count, required_reviews, comment_count,
unresolved_review_threads, checks_total, checks_passing, additions, deletions,
created_at, merged_at, closed_at, last_synced_at, detached_at, updated_at,
is_draft, changed_files, merged_by_login, closed_by_login, auto_merge_observed_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
VALUES (
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
)`,
tp.ID, tp.WorkspaceID, tp.TaskID, tp.RepositoryID, tp.Owner, tp.Repo, tp.PRNumber, tp.PRURL, tp.PRTitle, tp.HeadBranch, tp.BaseBranch, tp.AuthorLogin,
tp.State, tp.ReviewState, tp.ChecksState, tp.MergeableState, tp.ReviewCount, tp.PendingReviewCount, tp.RequiredReviews, tp.CommentCount,
tp.State, tp.ReviewState, tp.ChecksState, tp.MergeableState, tp.MergeQueueState, tp.MergeQueuePosition, tp.MergeQueueEstimatedTimeToMergeSeconds, tp.ReviewCount, tp.PendingReviewCount, tp.RequiredReviews, tp.CommentCount,
tp.UnresolvedReviewThreads, tp.ChecksTotal, tp.ChecksPassing, tp.Additions, tp.Deletions,
tp.CreatedAt, tp.MergedAt, tp.ClosedAt, tp.LastSyncedAt, tp.DetachedAt, tp.UpdatedAt,
tp.IsDraft, tp.ChangedFiles, tp.MergedByLogin, tp.ClosedByLogin, tp.AutoMergeObservedAt)
@@ -1709,7 +1749,7 @@ func (s *Store) CreateTaskPR(ctx context.Context, tp *TaskPR) error {
// read working regardless of what the table has picked up beyond them.
const taskPRColumns = `id, workspace_id, task_id, repository_id, owner, repo, pr_number, pr_url,
pr_title, head_branch, base_branch, author_login, state, review_state, checks_state,
mergeable_state, review_count, pending_review_count, required_reviews, comment_count,
mergeable_state, merge_queue_state, merge_queue_position, merge_queue_estimated_time_to_merge_seconds, review_count, pending_review_count, required_reviews, comment_count,
unresolved_review_threads, checks_total, checks_passing, additions, deletions,
created_at, merged_at, closed_at, last_synced_at, detached_at, updated_at,
is_draft, changed_files, merged_by_login, closed_by_login, auto_merge_observed_at`
@@ -1718,7 +1758,7 @@ const taskPRColumns = `id, workspace_id, task_id, repository_id, owner, repo, pr
// `gtp` alias, for queries that join github_task_prs against another table.
const taskPRColumnsQualified = `gtp.id, gtp.workspace_id, gtp.task_id, gtp.repository_id, gtp.owner, gtp.repo,
gtp.pr_number, gtp.pr_url, gtp.pr_title, gtp.head_branch, gtp.base_branch, gtp.author_login,
gtp.state, gtp.review_state, gtp.checks_state, gtp.mergeable_state, gtp.review_count,
gtp.state, gtp.review_state, gtp.checks_state, gtp.mergeable_state, gtp.merge_queue_state, gtp.merge_queue_position, gtp.merge_queue_estimated_time_to_merge_seconds, gtp.review_count,
gtp.pending_review_count, gtp.required_reviews, gtp.comment_count, gtp.unresolved_review_threads,
gtp.checks_total, gtp.checks_passing, gtp.additions, gtp.deletions,
gtp.created_at, gtp.merged_at, gtp.closed_at, gtp.last_synced_at, gtp.detached_at, gtp.updated_at,
@@ -1883,16 +1923,18 @@ func (s *Store) RestoreTaskPR(ctx context.Context, taskID, repositoryID string,
isDraft, changedFiles, mergedByLogin, closedByLogin, autoMergeObservedAt :=
resolveTaskPROutcomeFields(&outgoing, status)
mergeQueueState, mergeQueuePosition, mergeQueueEstimate := resolveTaskPRMergeQueueFields(&outgoing, status)
if _, err := tx.ExecContext(ctx,
`UPDATE github_task_prs SET owner = ?, repo = ?, pr_url = ?, pr_title = ?,
head_branch = ?, base_branch = ?, author_login = ?, state = ?, mergeable_state = ?,
merge_queue_state = ?, merge_queue_position = ?, merge_queue_estimated_time_to_merge_seconds = ?,
additions = ?, deletions = ?, merged_at = ?, closed_at = ?, detached_at = NULL, updated_at = ?,
is_draft = ?, changed_files = ?, merged_by_login = ?, closed_by_login = ?,
auto_merge_observed_at = COALESCE(auto_merge_observed_at, ?)
WHERE task_id = ? AND repository_id = ? AND pr_number = ?`,
pr.RepoOwner, pr.RepoName, pr.HTMLURL, pr.Title, pr.HeadBranch, pr.BaseBranch, pr.AuthorLogin,
pr.State, pr.MergeableState, pr.Additions, pr.Deletions, pr.MergedAt, pr.ClosedAt, time.Now().UTC(),
pr.State, pr.MergeableState, mergeQueueState, mergeQueuePosition, mergeQueueEstimate, pr.Additions, pr.Deletions, pr.MergedAt, pr.ClosedAt, time.Now().UTC(),
isDraft, changedFiles, mergedByLogin, closedByLogin, autoMergeObservedAt,
taskID, repositoryID, pr.Number); err != nil {
return nil, err
@@ -2045,6 +2087,12 @@ func (s *Store) ReplaceTaskPR(ctx context.Context, tp *TaskPR, status *PRStatus)
}
tp.IsDraft, tp.ChangedFiles, tp.MergedByLogin, tp.ClosedByLogin, tp.AutoMergeObservedAt =
resolveTaskPROutcomeFields(outgoing, status)
queueSource := tp
if outgoing.ID != "" {
queueSource = outgoing
}
tp.MergeQueueState, tp.MergeQueuePosition, tp.MergeQueueEstimatedTimeToMergeSeconds =
resolveTaskPRMergeQueueFields(queueSource, status)
if tp.RepositoryID != "" {
if _, err := tx.ExecContext(ctx,
@@ -2063,13 +2111,13 @@ func (s *Store) ReplaceTaskPR(ctx context.Context, tp *TaskPR, status *PRStatus)
}
if _, err := tx.ExecContext(ctx, `
INSERT INTO github_task_prs (id, workspace_id, task_id, repository_id, owner, repo, pr_number, pr_url, pr_title, head_branch, base_branch, author_login,
state, review_state, checks_state, mergeable_state, review_count, pending_review_count, required_reviews, comment_count,
state, review_state, checks_state, mergeable_state, merge_queue_state, merge_queue_position, merge_queue_estimated_time_to_merge_seconds, review_count, pending_review_count, required_reviews, comment_count,
unresolved_review_threads, checks_total, checks_passing, additions, deletions,
created_at, merged_at, closed_at, last_synced_at, detached_at, updated_at,
is_draft, changed_files, merged_by_login, closed_by_login, auto_merge_observed_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
tp.ID, tp.WorkspaceID, tp.TaskID, tp.RepositoryID, tp.Owner, tp.Repo, tp.PRNumber, tp.PRURL, tp.PRTitle, tp.HeadBranch, tp.BaseBranch, tp.AuthorLogin,
tp.State, tp.ReviewState, tp.ChecksState, tp.MergeableState, tp.ReviewCount, tp.PendingReviewCount, tp.RequiredReviews, tp.CommentCount,
tp.State, tp.ReviewState, tp.ChecksState, tp.MergeableState, tp.MergeQueueState, tp.MergeQueuePosition, tp.MergeQueueEstimatedTimeToMergeSeconds, tp.ReviewCount, tp.PendingReviewCount, tp.RequiredReviews, tp.CommentCount,
tp.UnresolvedReviewThreads, tp.ChecksTotal, tp.ChecksPassing, tp.Additions, tp.Deletions,
tp.CreatedAt, tp.MergedAt, tp.ClosedAt, tp.LastSyncedAt, tp.DetachedAt, tp.UpdatedAt,
tp.IsDraft, tp.ChangedFiles, tp.MergedByLogin, tp.ClosedByLogin, tp.AutoMergeObservedAt); err != nil {
@@ -2124,6 +2172,7 @@ func (s *Store) UpdateTaskPR(ctx context.Context, tp *TaskPR) error {
tp.UpdatedAt = time.Now().UTC()
_, err := s.db.ExecContext(ctx, `
UPDATE github_task_prs SET state = ?, review_state = ?, checks_state = ?, mergeable_state = ?,
merge_queue_state = ?, merge_queue_position = ?, merge_queue_estimated_time_to_merge_seconds = ?,
review_count = ?, pending_review_count = ?, required_reviews = ?, comment_count = ?,
unresolved_review_threads = ?, checks_total = ?, checks_passing = ?,
additions = ?, deletions = ?, pr_title = ?, base_branch = ?,
@@ -2131,7 +2180,7 @@ func (s *Store) UpdateTaskPR(ctx context.Context, tp *TaskPR) error {
is_draft = ?, changed_files = ?, merged_by_login = ?, closed_by_login = ?,
auto_merge_observed_at = COALESCE(auto_merge_observed_at, ?)
WHERE id = ?`,
tp.State, tp.ReviewState, tp.ChecksState, tp.MergeableState,
tp.State, tp.ReviewState, tp.ChecksState, tp.MergeableState, tp.MergeQueueState, tp.MergeQueuePosition, tp.MergeQueueEstimatedTimeToMergeSeconds,
tp.ReviewCount, tp.PendingReviewCount, tp.RequiredReviews, tp.CommentCount,
tp.UnresolvedReviewThreads, tp.ChecksTotal, tp.ChecksPassing,
tp.Additions, tp.Deletions, tp.PRTitle, tp.BaseBranch,
@@ -0,0 +1,140 @@
package github
import (
"context"
"strings"
"testing"
"time"
)
var taskPRMergeQueueColumnNames = []string{
"merge_queue_state",
"merge_queue_position",
"merge_queue_estimated_time_to_merge_seconds",
}
func TestTaskPRMergeQueueSchemaIsReplayable(t *testing.T) {
store := newTestStore(t)
columns, err := store.tableColumns("github_task_prs")
if err != nil {
t.Fatalf("read github_task_prs columns: %v", err)
}
for _, name := range taskPRMergeQueueColumnNames {
if _, ok := columns[name]; !ok {
t.Errorf("github_task_prs is missing %q", name)
}
}
if err := store.initSchema(false); err != nil {
t.Fatalf("replay github schema: %v", err)
}
}
func TestTaskPRMergeQueueColumnsRoundTripEveryWritePath(t *testing.T) {
store := newTestStore(t)
ctx := context.Background()
position := 4
estimate := 125
now := time.Now().UTC().Truncate(time.Second)
seed := &TaskPR{
TaskID: "task-queue-columns", WorkspaceID: "workspace-queue-columns",
Owner: "owner", Repo: "repo", PRNumber: 42, PRURL: "https://example.test/42",
PRTitle: "queued", HeadBranch: "feature", BaseBranch: "main", State: "open",
MergeQueueState: "queued", MergeQueuePosition: &position,
MergeQueueEstimatedTimeToMergeSeconds: &estimate, CreatedAt: now,
}
if err := store.CreateTaskPR(ctx, seed); err != nil {
t.Fatalf("CreateTaskPR: %v", err)
}
assertTaskPRMergeQueueFields(t, "CreateTaskPR", mustGetTaskPR(t, store, ctx, seed.ID), "queued", &position, &estimate)
position = 5
estimate = 185
seed.MergeQueueState = "awaiting_checks"
if err := store.UpdateTaskPR(ctx, seed); err != nil {
t.Fatalf("UpdateTaskPR: %v", err)
}
assertTaskPRMergeQueueFields(t, "UpdateTaskPR", mustGetTaskPR(t, store, ctx, seed.ID), "awaiting_checks", &position, &estimate)
replacedPosition := 2
replacedEstimate := 60
replaced := &TaskPR{
TaskID: seed.TaskID, WorkspaceID: seed.WorkspaceID, Owner: seed.Owner, Repo: seed.Repo,
PRNumber: seed.PRNumber, PRURL: seed.PRURL, PRTitle: "replaced", HeadBranch: seed.HeadBranch,
BaseBranch: seed.BaseBranch, State: "open", CreatedAt: now,
MergeQueueState: "mergeable", MergeQueuePosition: &replacedPosition,
MergeQueueEstimatedTimeToMergeSeconds: &replacedEstimate,
}
if _, err := store.ReplaceTaskPR(ctx, replaced, &PRStatus{
PR: &PR{State: "open"},
MergeQueueState: "mergeable", MergeQueuePosition: &replacedPosition,
MergeQueueEstimatedTimeToMergeSeconds: &replacedEstimate, mergeQueuePopulated: true,
}); err != nil {
t.Fatalf("ReplaceTaskPR: %v", err)
}
assertTaskPRMergeQueueFields(t, "ReplaceTaskPR", mustGetTaskPR(t, store, ctx, replaced.ID), "mergeable", &replacedPosition, &replacedEstimate)
}
func TestTaskPRColumnListsIncludeMergeQueueColumns(t *testing.T) {
for _, name := range taskPRMergeQueueColumnNames {
if !strings.Contains(taskPRColumns, name) {
t.Errorf("taskPRColumns missing %q", name)
}
if !strings.Contains(taskPRColumnsQualified, "gtp."+name) {
t.Errorf("taskPRColumnsQualified missing %q", name)
}
}
}
func TestRestoreTaskPRPreservesMergeQueueFields(t *testing.T) {
store := newTestStore(t)
ctx := context.Background()
position := 3
estimate := 90
seed := &TaskPR{
TaskID: "task-queue-restore", WorkspaceID: "workspace-queue-restore",
Owner: "owner", Repo: "repo", PRNumber: 43, PRURL: "https://example.test/43",
PRTitle: "queued restore", State: "open", CreatedAt: time.Now().UTC(),
MergeQueueState: "awaiting_checks", MergeQueuePosition: &position,
MergeQueueEstimatedTimeToMergeSeconds: &estimate,
}
if err := store.CreateTaskPR(ctx, seed); err != nil {
t.Fatalf("CreateTaskPR: %v", err)
}
if _, changed, err := store.DetachTaskPR(ctx, seed.ID); err != nil || !changed {
t.Fatalf("DetachTaskPR: changed=%v err=%v", changed, err)
}
restored, err := store.RestoreTaskPR(ctx, seed.TaskID, seed.RepositoryID, &PRStatus{
PR: &PR{Number: seed.PRNumber, RepoOwner: seed.Owner, RepoName: seed.Repo, HTMLURL: seed.PRURL, Title: seed.PRTitle, State: "open"},
})
if err != nil {
t.Fatalf("RestoreTaskPR: %v", err)
}
assertTaskPRMergeQueueFields(t, "RestoreTaskPR", restored, seed.MergeQueueState, &position, &estimate)
}
func mustGetTaskPR(t *testing.T, store *Store, ctx context.Context, id string) *TaskPR {
t.Helper()
got, err := store.GetTaskPRByID(ctx, id)
if err != nil {
t.Fatalf("GetTaskPRByID: %v", err)
}
if got == nil {
t.Fatalf("TaskPR %q not found", id)
}
return got
}
func assertTaskPRMergeQueueFields(t *testing.T, name string, got *TaskPR, state string, position, estimate *int) {
t.Helper()
if got.MergeQueueState != state {
t.Errorf("%s: MergeQueueState = %q, want %q", name, got.MergeQueueState, state)
}
if !intPtrEqual(got.MergeQueuePosition, position) {
t.Errorf("%s: MergeQueuePosition = %v, want %v", name, got.MergeQueuePosition, position)
}
if !intPtrEqual(got.MergeQueueEstimatedTimeToMergeSeconds, estimate) {
t.Errorf("%s: MergeQueueEstimatedTimeToMergeSeconds = %v, want %v", name, got.MergeQueueEstimatedTimeToMergeSeconds, estimate)
}
}
@@ -29,6 +29,7 @@ const (
prStatePending = "pending"
prStateAwaiting = "awaiting_review"
prStateReady = "ready"
prStateQueued = "queued"
prStatePassing = "passing"
prStateNeutral = "neutral"
prStateOpen = "open"
@@ -0,0 +1,78 @@
package statussummary
import (
"context"
"testing"
"github.com/kandev/kandev/internal/events"
"github.com/kandev/kandev/internal/events/bus"
)
func TestQueuedPullRequestIsProjectedByLiveAndRestartPaths(t *testing.T) {
input := PullRequestInput{
Key: "repo-1#42", State: prStateOpen, Number: 42,
URL: "https://example.test/42", MergeQueueState: "queued",
ChecksState: prStateSuccess,
}
rebuilt := BuildFromAuthoritative(RebuildInput{PRObserved: true, PullRequests: []PullRequestInput{input}})
if rebuilt.PullRequest == nil || rebuilt.PullRequest.AggregateState != prStateQueued {
t.Fatalf("rebuilt pull request summary = %+v, want queued", rebuilt.PullRequest)
}
projector, store, _, _, _ := newProjectorTest(t)
if err := projector.HandleEvent(context.Background(), bus.NewEvent(events.GitHubTaskPRUpdated, "test", map[string]interface{}{
"task_id": "task-queue-live",
"repository_id": "repo-1",
"pr_number": 42,
"state": prStateOpen,
"pr_url": input.URL,
"merge_queue_state": "queued",
"checks_state": prStateSuccess,
})); err != nil {
t.Fatalf("live PR event: %v", err)
}
live := store.summary("task-queue-live")
if live == nil || live.PullRequest == nil || live.PullRequest.AggregateState != prStateQueued {
t.Fatalf("live pull request summary = %+v, want queued", live)
}
}
func TestQueuedPullRequestRanksBelowMoreAttentionWorthySibling(t *testing.T) {
got := BuildFromAuthoritative(RebuildInput{
PRObserved: true,
PullRequests: []PullRequestInput{
{Key: "queued", State: prStateOpen, Number: 1, MergeQueueState: "queued"},
{Key: "failed", State: prStateOpen, Number: 2, ChecksState: prStateFailure},
},
})
if got.PullRequest == nil || got.PullRequest.AggregateState != prStateFailure {
t.Fatalf("aggregate state = %+v, want failure over queued sibling", got.PullRequest)
}
}
func TestQueuedPullRequestTakesPrecedenceOverItsOtherNonTerminalStates(t *testing.T) {
got := BuildFromAuthoritative(RebuildInput{
PRObserved: true,
PullRequests: []PullRequestInput{{
Key: "queued", State: prStateOpen, Number: 1,
MergeQueueState: "queued", MergeableState: "dirty",
ReviewState: prStateChanges, ChecksState: prStateFailure,
}},
})
if got.PullRequest == nil || got.PullRequest.AggregateState != prStateQueued {
t.Fatalf("aggregate state = %+v, want queued", got.PullRequest)
}
}
func TestQueuedPullRequestTakesPrecedenceOverDraftMergeability(t *testing.T) {
got := BuildFromAuthoritative(RebuildInput{
PRObserved: true,
PullRequests: []PullRequestInput{{
Key: "queued", State: prStateOpen, Number: 1,
MergeQueueState: "queued", MergeableState: prStateDraft,
}},
})
if got.PullRequest == nil || got.PullRequest.AggregateState != prStateQueued {
t.Fatalf("aggregate state = %+v, want queued", got.PullRequest)
}
}
@@ -183,6 +183,7 @@ type pullRequestObservation struct {
reviewState string
checksState string
mergeableState string
mergeQueueState string
unresolvedReviewCount int
pendingReviewCount int
requiredReviews int
@@ -771,6 +771,7 @@ func (p *Projector) applyPREventLocked(state *projectionState, data map[string]i
reviewState: stringField(data, "review_state"),
checksState: stringField(data, "checks_state"),
mergeableState: stringField(data, "mergeable_state"),
mergeQueueState: stringField(data, "merge_queue_state"),
unresolvedReviewCount: intValueOrZero(data["unresolved_review_threads"]),
pendingReviewCount: intValueOrZero(data["pending_review_count"]),
checksTotal: intValueOrZero(data["checks_total"]),
@@ -25,6 +25,7 @@ func applyPullRequestInputs(state *projectionState, inputs []PullRequestInput) {
reviewState: input.ReviewState,
checksState: input.ChecksState,
mergeableState: input.MergeableState,
mergeQueueState: input.MergeQueueState,
unresolvedReviewCount: maxInt(input.UnresolvedReviewCount, 0),
pendingReviewCount: maxInt(input.PendingReviewCount, 0),
requiredReviews: maxInt(input.RequiredReviews, 0),
@@ -121,6 +122,12 @@ func pullRequestAggregateState(pr pullRequestObservation) string {
mergeable := strings.ToLower(strings.TrimSpace(pr.mergeableState))
checks := strings.ToLower(strings.TrimSpace(pr.checksState))
review := strings.ToLower(strings.TrimSpace(pr.reviewState))
if state == prStateMerged || state == prStateClosed {
return pullRequestLifecycleState(state, mergeable)
}
if strings.TrimSpace(pr.mergeQueueState) != "" {
return prStateQueued
}
if lifecycle := pullRequestLifecycleState(state, mergeable); lifecycle != "" {
return lifecycle
}
@@ -186,6 +193,8 @@ func pullRequestStateRank(state string) int {
return 70
case prStateReady:
return 60
case prStateQueued:
return 55
case prStatePassing:
return 50
case prStateDraft:
@@ -35,6 +35,7 @@ type PullRequestInput struct {
ReviewState string
ChecksState string
MergeableState string
MergeQueueState string
UnresolvedReviewCount int
PendingReviewCount int
RequiredReviews int
@@ -9,6 +9,8 @@ import type { PRFeedback, TaskPR } from "@/lib/types/github";
import { getPRFeedback } from "@/lib/api/domains/github-api";
import { PRDetailPanelComponent } from "./pr-detail-panel";
const BOT_COMMENTS_LABEL = "Bot comments (1)";
vi.mock("@/lib/api/domains/github-api", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/lib/api/domains/github-api")>();
return {
@@ -58,14 +60,14 @@ function makePR(overrides: Partial<TaskPR> = {}): TaskPR {
};
}
function makeFeedback(pr: TaskPR, botCommentBody: string): PRFeedback {
function makeFeedback(pr: TaskPR, botCommentBody: string, state = "open"): PRFeedback {
return {
pr: {
number: pr.pr_number,
title: pr.pr_title,
url: pr.pr_url,
html_url: pr.pr_url,
state: "open",
state,
head_branch: pr.head_branch,
base_branch: pr.base_branch,
author_login: pr.author_login,
@@ -161,8 +163,8 @@ describe("PRDetailPanelComponent — task switch on the singleton legacy panel",
const { getStoreApi } = renderPanel(taskState("task-1", "session-1", [pr1]));
// Task 1: expand the bot-comments disclosure.
await waitFor(() => expect(screen.getByText("Bot comments (1)")).toBeTruthy());
fireEvent.click(screen.getByText("Bot comments (1)"));
await waitFor(() => expect(screen.getByText(BOT_COMMENTS_LABEL)).toBeTruthy());
fireEvent.click(screen.getByText(BOT_COMMENTS_LABEL));
await waitFor(() => expect(screen.getByText("PR 1 bot comment")).toBeTruthy());
// Switch to a different task whose PR also has exactly one bot comment —
@@ -175,10 +177,24 @@ describe("PRDetailPanelComponent — task switch on the singleton legacy panel",
}));
});
await waitFor(() => expect(screen.getByText("Bot comments (1)")).toBeTruthy());
await waitFor(() => expect(screen.getByText(BOT_COMMENTS_LABEL)).toBeTruthy());
// Task 2's bot comment must stay collapsed by default, not inherit task 1's
// expanded disclosure state.
expect(screen.queryByText("PR 2 bot comment")).toBeNull();
expect(screen.queryByText("PR 1 bot comment")).toBeNull();
});
it("does not show a stale queue notice after live feedback closes the PR", async () => {
const pr = makePR({
merge_queue_state: "queued",
merge_queue_position: 2,
merge_queue_estimated_time_to_merge_seconds: 120,
});
vi.mocked(getPRFeedback).mockResolvedValue(makeFeedback(pr, "Closed PR", "closed"));
renderPanel(taskState("task-1", "session-1", [pr]));
await waitFor(() => expect(screen.getByText(BOT_COMMENTS_LABEL)).toBeTruthy());
expect(screen.queryByTestId("pr-merge-queue-status")).toBeNull();
});
});
+15 -9
View File
@@ -22,6 +22,7 @@ import { submitPRReview } from "@/lib/api/domains/github-pr-api";
import type { TaskPR, PRFeedback } from "@/lib/types/github";
import { PRMergeButton } from "./pr-merge-button";
import { PRMergeabilityNotice, buildConflictResolutionMessage } from "./pr-mergeability-notice";
import { hasActiveMergeQueueEntry, PRMergeQueueStatus } from "./pr-merge-queue-status";
import { usePRScopedReviewRequest } from "./use-pr-scoped-review-request";
// --- Dockview panel wrapper ---
@@ -426,6 +427,7 @@ export function PRDetailContent({ taskPR, sessionId }: { taskPR: TaskPR; session
const isDraft = feedback?.pr.draft ?? false;
const isMergeable = feedback?.pr.mergeable ?? true;
const mergeableState = feedback?.pr.mergeable_state ?? taskPR.mergeable_state;
const displayPR = { ...taskPR, state: liveState };
return (
<ChangeRequestDetail
@@ -449,15 +451,19 @@ export function PRDetailContent({ taskPR, sessionId }: { taskPR: TaskPR; session
</>
}
notice={
<PRMergeabilityNotice
state={mergeableState}
mergeable={isMergeable}
isDraft={isDraft}
prState={liveState}
baseBranch={taskPR.base_branch}
onResolveConflicts={onResolveConflicts}
resolveDisabled={conflictQueued}
/>
hasActiveMergeQueueEntry(displayPR) ? (
<PRMergeQueueStatus pr={displayPR} />
) : (
<PRMergeabilityNotice
state={mergeableState}
mergeable={isMergeable}
isDraft={isDraft}
prState={liveState}
baseBranch={taskPR.base_branch}
onResolveConflicts={onResolveConflicts}
resolveDisabled={conflictQueued}
/>
)
}
/>
);
@@ -0,0 +1,156 @@
import { afterEach, describe, expect, it } from "vitest";
import { cleanup, render } from "@testing-library/react";
import type { TaskPR } from "@/lib/types/github";
import { aggregatePRStatusColor, getPRStatusColor } from "./pr-task-icon";
import {
describeMergeQueueEstimate,
getMergeQueueSummaryStatus,
PRMergeQueueStatus,
} from "./pr-merge-queue-status";
const QUEUE_STATUS_TEST_ID = "pr-merge-queue-status";
function makePR(overrides: Partial<TaskPR> = {}): TaskPR {
return {
id: "id",
task_id: "task-1",
owner: "acme",
repo: "demo",
pr_number: 42,
pr_url: "",
pr_title: "Queued PR",
head_branch: "feature",
base_branch: "main",
author_login: "alice",
state: "open",
review_state: "",
checks_state: "success",
mergeable_state: "blocked",
review_count: 0,
pending_review_count: 0,
comment_count: 0,
unresolved_review_threads: 0,
checks_total: 1,
checks_passing: 1,
additions: 0,
deletions: 0,
created_at: "",
merged_at: null,
closed_at: null,
last_synced_at: null,
updated_at: "",
...overrides,
};
}
afterEach(() => cleanup());
describe("merge queue estimate formatting", () => {
it.each([
[undefined, { kind: "none" }],
[null, { kind: "none" }],
[0, { kind: "sub_minute" }],
[59, { kind: "sub_minute" }],
[60, { kind: "minutes", minutes: 1 }],
[61, { kind: "minutes", minutes: 2 }],
[3600, { kind: "minutes", minutes: 60 }],
])("describes %s seconds without exposing raw provider units", (seconds, expected) => {
expect(describeMergeQueueEstimate(seconds)).toEqual(expected);
});
});
describe("merge queue status", () => {
it.each([
["queued", "queue_queued"],
["awaiting_checks", "queue_awaiting_checks"],
["mergeable", "queue_mergeable"],
["unmergeable", "queue_unmergeable"],
["locked", "queue_locked"],
["future_state", "queue_queued"],
])("maps %s to %s", (state, expected) => {
expect(getMergeQueueSummaryStatus(state)).toBe(expected);
});
it("uses generic queued copy for a future provider state", () => {
const { getByTestId } = render(
<PRMergeQueueStatus pr={makePR({ merge_queue_state: "future_state" })} />,
);
expect(getByTestId(QUEUE_STATUS_TEST_ID).textContent).toContain("Merge queue: Queued");
});
it("renders queue state, one-based position, and an available estimate", () => {
const { getByTestId } = render(
<PRMergeQueueStatus
pr={makePR({
merge_queue_state: "queued",
merge_queue_position: 4,
merge_queue_estimated_time_to_merge_seconds: 61,
})}
/>,
);
const notice = getByTestId(QUEUE_STATUS_TEST_ID);
expect(notice.textContent).toContain("Merge queue: Queued");
expect(notice.textContent).toContain("Position 4");
expect(notice.textContent).toContain("2 minutes");
});
it("renders a localized sub-minute estimate", () => {
const { getByTestId } = render(
<PRMergeQueueStatus
pr={makePR({
merge_queue_state: "awaiting_checks",
merge_queue_position: 1,
merge_queue_estimated_time_to_merge_seconds: 59,
})}
/>,
);
expect(getByTestId(QUEUE_STATUS_TEST_ID).textContent).toContain("less than a minute");
});
it("renders nothing for an empty or terminal queue state", () => {
const empty = render(<PRMergeQueueStatus pr={makePR()} />);
expect(empty.queryByTestId(QUEUE_STATUS_TEST_ID)).toBeNull();
empty.unmount();
const terminal = render(
<PRMergeQueueStatus pr={makePR({ state: "closed", merge_queue_state: "queued" })} />,
);
expect(terminal.queryByTestId(QUEUE_STATUS_TEST_ID)).toBeNull();
});
it("keeps terminal colors ahead of a stale queue entry", () => {
expect(getPRStatusColor(makePR({ state: "merged", merge_queue_state: "queued" }))).toBe(
"text-purple-500",
);
expect(getPRStatusColor(makePR({ state: "closed", merge_queue_state: "queued" }))).toBe(
"text-red-500",
);
});
it("keeps queue color ahead of other non-terminal PR states", () => {
const overrides: Array<Partial<TaskPR>> = [
{ checks_state: "failure" },
{ review_state: "changes_requested" },
{ mergeable_state: "dirty" },
{ mergeable_state: "behind" },
{ mergeable_state: "draft" },
];
for (const override of overrides) {
expect(getPRStatusColor(makePR({ merge_queue_state: "queued", ...override }))).toBe(
"text-[#966600]",
);
}
});
it("lets a failing sibling outrank a queued PR in the aggregate", () => {
expect(
aggregatePRStatusColor([
makePR({ merge_queue_state: "queued" }),
makePR({ pr_number: 2, checks_state: "failure" }),
]),
).toBe("text-red-500");
});
});
@@ -0,0 +1,122 @@
"use client";
import { IconClockHour4 } from "@tabler/icons-react";
import { useTranslation } from "react-i18next";
import type { ChangeRequestTaskSummaryRowDetail } from "@/components/integrations/change-request-task-status-summary";
import type { TaskPR } from "@/lib/types/github";
export type MergeQueueSummaryStatus =
| "queue_queued"
| "queue_awaiting_checks"
| "queue_mergeable"
| "queue_unmergeable"
| "queue_locked";
export type MergeQueueEstimateDescription =
| { kind: "none" }
| { kind: "sub_minute" }
| { kind: "minutes"; minutes: number };
const KNOWN_QUEUE_STATES: Record<string, MergeQueueSummaryStatus> = {
queued: "queue_queued",
awaiting_checks: "queue_awaiting_checks",
mergeable: "queue_mergeable",
unmergeable: "queue_unmergeable",
locked: "queue_locked",
};
const QUEUE_STATE_LABEL_KEYS: Record<MergeQueueSummaryStatus, string> = {
queue_queued: "github:mergeQueueStateQueued",
queue_awaiting_checks: "github:mergeQueueStateAwaitingChecks",
queue_mergeable: "github:mergeQueueStateMergeable",
queue_unmergeable: "github:mergeQueueStateUnmergeable",
queue_locked: "github:mergeQueueStateLocked",
};
export function normalizeMergeQueueState(state: string | null | undefined): string {
return state?.trim().toLowerCase() ?? "";
}
export function getMergeQueueSummaryStatus(
state: string | null | undefined,
): MergeQueueSummaryStatus {
return KNOWN_QUEUE_STATES[normalizeMergeQueueState(state)] ?? "queue_queued";
}
export function describeMergeQueueEstimate(
seconds: number | null | undefined,
): MergeQueueEstimateDescription {
if (seconds == null || !Number.isFinite(seconds) || seconds < 0) {
return { kind: "none" };
}
if (seconds < 60) return { kind: "sub_minute" };
return { kind: "minutes", minutes: Math.ceil(seconds / 60) };
}
function validQueuePosition(position: number | null | undefined): number | null {
if (position == null || !Number.isInteger(position) || position < 1) return null;
return position;
}
export function getMergeQueueSummaryDetail(
position: number | null | undefined,
estimateSeconds: number | null | undefined,
): ChangeRequestTaskSummaryRowDetail | undefined {
const queuePosition = validQueuePosition(position);
const estimate = describeMergeQueueEstimate(estimateSeconds);
if (queuePosition != null) {
if (estimate.kind === "sub_minute") {
return {
key: "github:mergeQueuePositionAndSubMinuteEstimate",
values: { position: queuePosition },
};
}
if (estimate.kind === "minutes") {
return {
key: "github:mergeQueuePositionAndEstimate",
values: { position: queuePosition, count: estimate.minutes },
};
}
return { key: "github:mergeQueuePosition", values: { position: queuePosition } };
}
if (estimate.kind === "sub_minute") {
return { key: "github:mergeQueueSubMinuteEstimate" };
}
if (estimate.kind === "minutes") {
return { key: "github:mergeQueueEstimate", values: { count: estimate.minutes } };
}
return undefined;
}
export function hasActiveMergeQueueEntry(pr: Pick<TaskPR, "state" | "merge_queue_state">): boolean {
return pr.state === "open" && normalizeMergeQueueState(pr.merge_queue_state) !== "";
}
export function PRMergeQueueStatus({ pr }: { pr: TaskPR }) {
const { t } = useTranslation();
if (!hasActiveMergeQueueEntry(pr)) return null;
const status = getMergeQueueSummaryStatus(pr.merge_queue_state);
const stateLabel = t(QUEUE_STATE_LABEL_KEYS[status]);
const detail = getMergeQueueSummaryDetail(
pr.merge_queue_position,
pr.merge_queue_estimated_time_to_merge_seconds,
);
return (
<div
data-testid="pr-merge-queue-status"
className="flex items-start gap-1.5 px-1 py-1 text-xs text-[#966600]"
>
<IconClockHour4 className="mt-0.5 h-3.5 w-3.5 shrink-0" aria-hidden="true" />
<div className="min-w-0">
<div className="font-medium">{t("github:mergeQueueStatus", { state: stateLabel })}</div>
{detail && (
<p className="text-[11px] leading-snug text-muted-foreground">
{t(detail.key, detail.values)}
</p>
)}
</div>
</div>
);
}
@@ -9,6 +9,8 @@ import type { AppState } from "@/lib/state/store";
import type { MergeableState, TaskPR } from "@/lib/types/github";
const SESSION_ID = "sess-1";
const QUEUE_STATUS_TEST_ID = "pr-merge-queue-status";
const CONFLICT_BANNER_TEST_ID = "pr-conflict-banner";
function makePR(overrides: Partial<TaskPR> = {}): TaskPR {
return {
@@ -71,7 +73,7 @@ afterEach(() => cleanup());
describe("PRMergeabilityRow", () => {
it("shows the conflict banner with a Resolve conflicts CTA for a dirty PR", () => {
const { queryByTestId } = renderRow(makePR({ mergeable_state: "dirty" }));
expect(queryByTestId("pr-conflict-banner")).not.toBeNull();
expect(queryByTestId(CONFLICT_BANNER_TEST_ID)).not.toBeNull();
expect(queryByTestId("pr-resolve-conflicts-button")).not.toBeNull();
});
@@ -79,7 +81,7 @@ describe("PRMergeabilityRow", () => {
const { container, queryByTestId } = renderRow(
makePR({ mergeable_state: "blocked", checks_state: "failure" }),
);
expect(queryByTestId("pr-conflict-banner")).toBeNull();
expect(queryByTestId(CONFLICT_BANNER_TEST_ID)).toBeNull();
expect(queryByTestId("pr-blocked-note")).not.toBeNull();
expect(queryByTestId("pr-blocked-shield-icon")).not.toBeNull();
expect(container.textContent).toContain("Blocked by branch protection");
@@ -147,11 +149,49 @@ describe("PRMergeabilityRow", () => {
it("hides the Resolve conflicts CTA when there is no active session", () => {
const { queryByTestId } = renderRow(makePR({ mergeable_state: "dirty" }), null);
// Banner still surfaces the conflict, but the CTA needs a session to target.
expect(queryByTestId("pr-conflict-banner")).not.toBeNull();
expect(queryByTestId(CONFLICT_BANNER_TEST_ID)).not.toBeNull();
expect(queryByTestId("pr-resolve-conflicts-button")).toBeNull();
});
});
describe("PRMergeabilityRow queue state", () => {
it("replaces mergeability with queue state and metadata for an active entry", () => {
const { getByTestId, queryByTestId, container } = renderRow(
makePR({
merge_queue_state: "mergeable",
merge_queue_position: 2,
merge_queue_estimated_time_to_merge_seconds: 120,
mergeable_state: "dirty",
}),
);
expect(getByTestId(QUEUE_STATUS_TEST_ID)).not.toBeNull();
expect(container.textContent).toContain("Merge queue: Mergeable");
expect(container.textContent).toContain("Position 2");
expect(container.textContent).toContain("2 minutes");
expect(queryByTestId(CONFLICT_BANNER_TEST_ID)).toBeNull();
});
it("keeps queue state visible when position and estimate are absent", () => {
const { getByTestId, container } = renderRow(
makePR({ merge_queue_state: "locked", mergeable_state: "blocked" }),
);
expect(getByTestId(QUEUE_STATUS_TEST_ID)).not.toBeNull();
expect(container.textContent).toContain("Merge queue: Locked");
expect(container.textContent).not.toContain("Position");
});
it("does not show a stale queue entry after a terminal transition", () => {
const { queryByTestId, getByTestId } = renderRow(
makePR({ state: "merged", merge_queue_state: "queued" }),
);
expect(queryByTestId(QUEUE_STATUS_TEST_ID)).toBeNull();
expect(getByTestId("row-host").childElementCount).toBe(0);
});
});
describe("blockedReason", () => {
it("names the approval shortfall when required reviews aren't met", () => {
expect(blockedReason(makePR({ required_reviews: 2, review_count: 0 }), t)).toContain(
@@ -12,6 +12,7 @@ import {
import type { TaskPR } from "@/lib/types/github";
import { isPRAwaitingReview, isPRWaitingOnBranchProtection } from "./pr-task-icon";
import { PRMergeabilityNotice, buildConflictResolutionMessage } from "./pr-mergeability-notice";
import { hasActiveMergeQueueEntry, PRMergeQueueStatus } from "./pr-merge-queue-status";
import { useTranslation } from "react-i18next";
/**
@@ -78,6 +79,7 @@ function useResolveConflicts(pr: TaskPR): {
export function PRMergeabilityRow({ pr }: { pr: TaskPR }) {
const { t } = useTranslation();
const { onResolveConflicts, conflictQueued } = useResolveConflicts(pr);
if (hasActiveMergeQueueEntry(pr)) return <PRMergeQueueStatus pr={pr} />;
// "blocked" gets a richer note than the bare chip: it explains *why* the
// merge is gated. But when the block is only an outstanding requested review,
// stay silent — the review row above already conveys that and the
@@ -582,6 +582,37 @@ describe("aggregateChipStatus", () => {
const failing = makePR({ id: "fail", checks_state: "failure" });
expect(aggregateChipStatus([conflict, failing])).toBe("failed");
});
it("uses the dedicated queued chip status", () => {
expect(aggregateChipStatus([makePR({ merge_queue_state: "queued" })])).toBe("queued");
});
it("keeps queued status ahead of dirty mergeability", () => {
expect(
aggregateChipStatus([makePR({ merge_queue_state: "queued", mergeable_state: "dirty" })]),
).toBe("queued");
});
it("keeps queued status ahead of failure on the same PR", () => {
expect(
aggregateChipStatus([
makePR({
merge_queue_state: "queued",
checks_state: "failure",
review_state: "changes_requested",
}),
]),
).toBe("queued");
});
it("lets a failing sibling retain chip priority over a queued PR", () => {
expect(
aggregateChipStatus([
makePR({ merge_queue_state: "queued" }),
makePR({ pr_number: 2, checks_state: "failure" }),
]),
).toBe("failed");
});
});
describe("PRStatusChip — multiple PRs", () => {
+16 -1
View File
@@ -27,6 +27,7 @@ import {
isPRDraft,
isPRAwaitingReview,
isPRReadyToMerge,
isPRQueued,
isPRWaitingOnBranchProtection,
pickDefaultPR,
} from "@/components/github/pr-task-icon";
@@ -60,6 +61,7 @@ type ChipStatus =
| "behind"
| "draft"
| "waiting"
| "queued"
| "in_progress"
| "neutral";
type TriggerRef = { current: HTMLButtonElement | null };
@@ -83,13 +85,17 @@ function focusAfterCollapse(triggerRef?: TriggerRef) {
}
function chipStatus(pr: TaskPR): ChipStatus {
// Terminal PRs are filtered before this helper. For active PRs, queue
// membership is the authoritative non-terminal state, so stale failure,
// draft, or mergeability fields cannot override the queue indicator.
if (isPRQueued(pr)) return "queued";
if (pr.review_state === "changes_requested" || pr.checks_state === "failure") return "failed";
if (isPRDraft(pr)) return "draft";
// Merge conflicts / behind-base block the merge even when CI is green — the
// chip must never read as a passed check in that case. Mirrors
// getPRStatusColor + PRStatusIcon (dirty = red, behind = amber).
if (pr.mergeable_state === "dirty") return "conflict";
if (pr.mergeable_state === "behind") return "behind";
if (isPRDraft(pr)) return "draft";
// Pending checks / pending review must beat checks_state === "success" so a
// PR with all checks green but reviewers still outstanding renders as
// in-progress, not passed. Without this order, the chip flips to green the
@@ -114,6 +120,7 @@ const CHIP_STATUS_RANK: Record<ChipStatus, number> = {
conflict: 5,
blocked: 4,
behind: 3,
queued: 2.5,
draft: 0.5,
in_progress: 2,
waiting: 1.5,
@@ -450,6 +457,14 @@ function ChipStatusGlyph({ status }: { status: ChipStatus }) {
return <IconAlertTriangleFilled className="h-3.5 w-3.5 text-red-500" aria-hidden="true" />;
case "behind":
return <IconAlertTriangleFilled className="h-3.5 w-3.5 text-yellow-500" aria-hidden="true" />;
case "queued":
return (
<IconClock
data-testid="pr-status-glyph-queued"
className="h-3.5 w-3.5 text-[#966600]"
aria-hidden="true"
/>
);
case "draft":
return <IconPointFilled className="h-3.5 w-3.5 text-muted-foreground" aria-hidden="true" />;
case "blocked":
@@ -18,6 +18,7 @@ const RED_500 = "text-red-500";
const YELLOW_500 = "text-yellow-500";
const EMERALD_400 = "text-emerald-400";
const GREEN_500 = "text-green-500";
const QUEUED = "text-[#966600]";
const PURPLE_500 = "text-purple-500";
const MUTED_FOREGROUND = "text-muted-foreground";
@@ -60,12 +61,25 @@ describe("getPRAggregateStatusColor", () => {
["pending", YELLOW_500],
["awaiting_review", SKY_400],
["ready", EMERALD_400],
["queued", QUEUED],
["passing", GREEN_500],
["merged", PURPLE_500],
["open", MUTED_FOREGROUND],
])("maps %s to %s", (state, color) => {
expect(getPRAggregateStatusColor(state)).toBe(color);
});
it("uses the dedicated merge-queue color for an open queued PR", () => {
expect(
getPRStatusColor(
makePR({
merge_queue_state: "queued",
checks_state: "success",
mergeable_state: "blocked",
}),
),
).toBe(QUEUED);
});
});
describe("isPRReadyToMerge", () => {
@@ -20,6 +20,7 @@ const RED_500 = CHANGE_REQUEST_STATUS_COLORS.danger;
const YELLOW_500 = CHANGE_REQUEST_STATUS_COLORS.warning;
const SKY_400 = CHANGE_REQUEST_STATUS_COLORS.review;
const EMERALD_400 = CHANGE_REQUEST_STATUS_COLORS.ready;
const QUEUED = CHANGE_REQUEST_STATUS_COLORS.queued;
const GREEN_500 = CHANGE_REQUEST_STATUS_COLORS.passing;
/** Maps the task-level PR projection to the same visual language as live PRs. */
@@ -86,6 +87,14 @@ export function isPRDraft(pr: TaskPR): boolean {
return pr.state === "open" && pr.mergeable_state === "draft";
}
export function isPRQueued(pr: TaskPR): boolean {
return (
pr.state === "open" &&
typeof pr.merge_queue_state === "string" &&
pr.merge_queue_state.trim() !== ""
);
}
// CI passed but the PR is still waiting on human review (reviewers requested
// or pending review state). Distinct from yellow "CI running". An approved
// PR with extra reviewers still pending also counts — GitHub's
@@ -126,6 +135,10 @@ function openMergeBlockerColor(pr: TaskPR): string | null {
export function getPRStatusColor(pr: TaskPR): string {
if (pr.state === "merged") return PURPLE_500;
if (pr.state === "closed") return RED_500;
// An active queue entry is the authoritative non-terminal state. Queue
// membership must remain visible while provider checks or mergeability
// fields hydrate, even when those fields still describe an earlier state.
if (isPRQueued(pr)) return QUEUED;
if (pr.review_state === "changes_requested" || pr.checks_state === "failure") {
return RED_500;
}
@@ -134,3 +134,60 @@ describe("structured PR task status summary", () => {
expect(summary.rows).toEqual([{ kind: "merge", status: "draft", tone: "muted" }]);
});
});
describe("queued PR task status summaries", () => {
it("replaces mergeability with queue semantics and metadata", () => {
const summary = derivePRTaskStatusSummary(
makePR({
merge_queue_state: "awaiting_checks",
merge_queue_position: 3,
merge_queue_estimated_time_to_merge_seconds: 61,
mergeable_state: "dirty",
}),
false,
);
expect(summary.rows.at(-1)).toEqual({
kind: "merge",
status: "queue_awaiting_checks",
tone: "queued",
detail: {
key: "github:mergeQueuePositionAndEstimate",
values: { position: 3, count: 2 },
},
});
});
it("uses generic queued copy for an unknown provider enum", () => {
const summary = derivePRTaskStatusSummary(
makePR({
merge_queue_state: "future_provider_state",
merge_queue_position: 1,
}),
false,
);
expect(summary.rows.at(-1)).toEqual({
kind: "merge",
status: "queue_queued",
tone: "queued",
detail: {
key: "github:mergeQueuePosition",
values: { position: 1 },
},
});
});
it("does not surface queue metadata for a terminal PR", () => {
const summary = derivePRTaskStatusSummary(
makePR({
state: "merged",
merge_queue_state: "queued",
merge_queue_position: 1,
}),
false,
);
expect(summary.rows).not.toContainEqual(expect.objectContaining({ tone: "queued" }));
});
});
@@ -1,6 +1,11 @@
"use client";
import type { TaskPR } from "@/lib/types/github";
import {
getMergeQueueSummaryDetail,
getMergeQueueSummaryStatus,
hasActiveMergeQueueEntry,
} from "./pr-merge-queue-status";
import {
ChangeRequestTaskStatusSummary,
type ChangeRequestTaskStatusSummaryData,
@@ -53,6 +58,17 @@ function deriveCIRow(checksState: string): PRTaskSummaryRow | null {
function deriveMergeRow(pr: TaskPR, readyToMerge: boolean): PRTaskSummaryRow | null {
if (pr.state !== "open") return null;
if (hasActiveMergeQueueEntry(pr)) {
return {
kind: "merge",
status: getMergeQueueSummaryStatus(pr.merge_queue_state),
tone: "queued",
detail: getMergeQueueSummaryDetail(
pr.merge_queue_position,
pr.merge_queue_estimated_time_to_merge_seconds,
),
};
}
if (pr.mergeable_state === "draft") {
return { kind: "merge", status: "draft", tone: "muted" };
}
@@ -7,6 +7,7 @@ export const CHANGE_REQUEST_STATUS_COLORS = {
warning: "text-yellow-500",
review: "text-sky-400",
ready: "text-emerald-400",
queued: "text-[#966600]",
passing: "text-green-500",
} as const;
@@ -23,6 +24,8 @@ export function getChangeRequestAggregateStatusColor(state: string | null | unde
return CHANGE_REQUEST_STATUS_COLORS.review;
case "ready":
return CHANGE_REQUEST_STATUS_COLORS.ready;
case "queued":
return CHANGE_REQUEST_STATUS_COLORS.queued;
case "passing":
return CHANGE_REQUEST_STATUS_COLORS.passing;
case "draft":
@@ -39,6 +42,7 @@ export const CHANGE_REQUEST_STATUS_RANK: Readonly<Record<string, number>> = {
[CHANGE_REQUEST_STATUS_COLORS.warning]: 4,
[CHANGE_REQUEST_STATUS_COLORS.review]: 3,
[CHANGE_REQUEST_STATUS_COLORS.ready]: 2,
[CHANGE_REQUEST_STATUS_COLORS.queued]: 1.5,
[CHANGE_REQUEST_STATUS_COLORS.passing]: 1,
[CHANGE_REQUEST_STATUS_COLORS.merged]: 0,
[CHANGE_REQUEST_STATUS_COLORS.muted]: 0,
@@ -22,6 +22,7 @@ export type ChangeRequestTaskSummaryTone =
| "warning"
| "info"
| "merged"
| "queued"
| "muted";
export type ChangeRequestTaskSummaryStatus =
| "merged"
@@ -40,13 +41,24 @@ export type ChangeRequestTaskSummaryStatus =
| "blocked"
| "unresolved_discussions"
| "mergeable"
| "queue_queued"
| "queue_awaiting_checks"
| "queue_mergeable"
| "queue_unmergeable"
| "queue_locked"
| "raw";
export type ChangeRequestTaskSummaryRowDetail = {
key: string;
values?: Record<string, unknown>;
};
export type ChangeRequestTaskSummaryRow = {
kind: ChangeRequestTaskSummaryRowKind;
status: ChangeRequestTaskSummaryStatus;
tone: ChangeRequestTaskSummaryTone;
rawValue?: string;
detail?: ChangeRequestTaskSummaryRowDetail;
};
export type ChangeRequestTaskStatusSummaryData = {
@@ -81,6 +93,7 @@ const TONE_CLASSES: Record<ChangeRequestTaskSummaryTone, string> = {
warning: "text-amber-600 dark:text-amber-400",
info: "text-sky-600 dark:text-sky-400",
merged: "text-purple-600 dark:text-purple-400",
queued: "text-[#966600]",
muted: "text-muted-foreground",
};
@@ -101,6 +114,11 @@ const STATUS_LABEL_KEYS: Record<Exclude<ChangeRequestTaskSummaryStatus, "raw">,
blocked: "github:blocked",
unresolved_discussions: "github:blocked",
mergeable: "github:mergeable",
queue_queued: "github:mergeQueueStateQueued",
queue_awaiting_checks: "github:mergeQueueStateAwaitingChecks",
queue_mergeable: "github:mergeQueueStateMergeable",
queue_unmergeable: "github:mergeQueueStateUnmergeable",
queue_locked: "github:mergeQueueStateLocked",
};
const STATUS_ICONS: Record<ChangeRequestTaskSummaryStatus, TablerIcon> = {
@@ -120,6 +138,11 @@ const STATUS_ICONS: Record<ChangeRequestTaskSummaryStatus, TablerIcon> = {
blocked: IconAlertTriangle,
unresolved_discussions: IconAlertTriangle,
mergeable: IconGitMerge,
queue_queued: IconClockHour4,
queue_awaiting_checks: IconClockHour4,
queue_mergeable: IconClockHour4,
queue_unmergeable: IconClockHour4,
queue_locked: IconClockHour4,
raw: IconCircleDot,
};
@@ -144,6 +167,10 @@ function getStatusText(
return t(presentation.statusLabelKeys?.[row.status] ?? STATUS_LABEL_KEYS[row.status]);
}
function getDetailText(detail: ChangeRequestTaskSummaryRowDetail, t: TFunction): string {
return t(detail.key, detail.values);
}
function SummaryStatusIcon({ status }: { status: ChangeRequestTaskSummaryStatus }) {
const StatusIcon = STATUS_ICONS[status];
return <StatusIcon aria-hidden="true" className="size-3.5 shrink-0" />;
@@ -163,10 +190,22 @@ function SummaryRow({
className="grid grid-cols-[min-content_minmax(0,1fr)] items-start gap-x-3"
>
<span className="text-muted-foreground">{t(presentation.rowLabelKeys[row.kind])}</span>
<span className={cn("flex min-w-0 items-center gap-1.5 font-medium", TONE_CLASSES[row.tone])}>
<SummaryStatusIcon status={row.status} />
<span className="min-w-0 break-words">{getStatusText(row, presentation, t)}</span>
</span>
<div className="min-w-0">
<span
className={cn("flex min-w-0 items-center gap-1.5 font-medium", TONE_CLASSES[row.tone])}
>
<SummaryStatusIcon status={row.status} />
<span className="min-w-0 break-words">{getStatusText(row, presentation, t)}</span>
</span>
{row.detail && (
<span
data-testid={presentation.rowTestIdPrefix + "-" + row.kind + "-detail"}
className="mt-0.5 block text-[11px] leading-snug text-muted-foreground"
>
{getDetailText(row.detail, t)}
</span>
)}
</div>
</div>
);
}
+6
View File
@@ -1675,6 +1675,9 @@ export class ApiClient {
review_state?: string;
checks_state?: string;
mergeable_state?: string;
merge_queue_state?: string;
merge_queue_position?: number | null;
merge_queue_estimated_time_to_merge_seconds?: number | null;
additions?: number;
deletions?: number;
review_count?: number;
@@ -1718,6 +1721,9 @@ export class ApiClient {
review_state: string;
checks_state: string;
mergeable_state: string;
merge_queue_state?: string;
merge_queue_position?: number | null;
merge_queue_estimated_time_to_merge_seconds?: number | null;
review_count: number;
pending_review_count: number;
required_reviews?: number | null;
@@ -86,3 +86,103 @@ test("adds a GitHub PR to the merge queue from mobile Review", async ({
await merge.tap();
await expect(testPage.getByText("PR added to merge queue", { exact: true })).toBeVisible();
});
test("surfaces queued PR metadata in the mobile drawer and Review", async ({
testPage,
apiClient,
seedData,
prCapture,
}) => {
test.setTimeout(120_000);
await testPage.setViewportSize({ width: 393, height: 852 });
await apiClient.mockGitHubReset();
await apiClient.mockGitHubSetUser("maya-chen");
const task = await apiClient.createTaskWithAgent(
seedData.workspaceId,
"Ship resilient deployment controls",
seedData.agentProfileId,
{
description: "/e2e:simple-message",
workflow_id: seedData.workflowId,
workflow_step_id: seedData.startStepId,
repository_ids: [seedData.repositoryId],
},
);
await apiClient.mockGitHubAddRepos("northstar-labs", [
{
full_name: "northstar-labs/relay-console",
owner: "northstar-labs",
name: "relay-console",
},
]);
await apiClient.mockGitHubAssociateTaskPR({
task_id: task.id,
owner: "northstar-labs",
repo: "relay-console",
pr_number: 843,
pr_url: "https://github.com/northstar-labs/relay-console/pull/843",
pr_title: "Make deployment rollbacks deterministic",
head_branch: "feat/resilient-rollbacks",
base_branch: "main",
author_login: "maya-chen",
state: "open",
review_state: "approved",
checks_state: "success",
mergeable_state: "blocked",
merge_queue_state: "queued",
merge_queue_position: 2,
merge_queue_estimated_time_to_merge_seconds: 61,
review_count: 2,
pending_review_count: 0,
required_reviews: 2,
checks_total: 3,
checks_passing: 3,
});
await apiClient.mockGitHubSetMergeOutcome("northstar-labs", "relay-console", 843, "queued");
await testPage.goto(`/t/${task.id}`);
const session = new SessionPage(testPage);
await session.waitForLoad();
await testPage.reload();
await session.waitForLoad();
await session.tapPRStatusChip();
const drawer = session.prStatusChipPopoverInner();
await expect(drawer.getByTestId("pr-merge-queue-status")).toContainText("Queued");
await expect(drawer.getByTestId("pr-merge-queue-status")).toContainText("Position 2");
await expect(drawer.getByTestId("pr-merge-queue-status")).toContainText("2 minutes");
await prCapture.screenshot("mobile-pr-merge-queue-status", {
caption: "Mobile pull request queue status in the touch drawer",
});
await session.prStatusChipDrawerClose().tap();
await testPage.getByRole("button", { name: "Review", exact: true }).tap();
const panel = testPage.getByTestId("mobile-review-panel");
await apiClient.mockGitHubAssociateTaskPR({
task_id: task.id,
owner: "northstar-labs",
repo: "relay-console",
pr_number: 843,
pr_url: "https://github.com/northstar-labs/relay-console/pull/843",
pr_title: "Make deployment rollbacks deterministic",
head_branch: "feat/resilient-rollbacks",
base_branch: "main",
author_login: "maya-chen",
state: "open",
review_state: "approved",
checks_state: "success",
mergeable_state: "blocked",
merge_queue_state: "queued",
merge_queue_position: 2,
merge_queue_estimated_time_to_merge_seconds: 61,
review_count: 2,
pending_review_count: 0,
required_reviews: 2,
checks_total: 3,
checks_passing: 3,
});
const queueStatus = panel.getByTestId("pr-merge-queue-status");
await expect(queueStatus).toContainText("Queued");
await expect(queueStatus).toContainText("Position 2");
await expect(queueStatus).toContainText("2 minutes");
await assertNoDocumentHorizontalOverflow(testPage);
});
+108 -3
View File
@@ -21,21 +21,21 @@ test("adds an eligible GitHub PR to its merge queue", async ({ testPage, apiClie
repository_ids: [seedData.repositoryId],
},
);
await seedQueuedPR(apiClient, task.id);
await seedEligiblePR(apiClient, task.id);
await testPage.goto(`/t/${task.id}`);
const session = new SessionPage(testPage);
await session.waitForLoad();
await testPage.reload();
await session.waitForLoad();
await seedQueuedPR(apiClient, task.id);
await seedEligiblePR(apiClient, task.id);
await session.hoverPRTopbar();
const popover = session.prTopbarPopover();
const compactMerge = popover.getByRole("button", { name: "Merge PR" });
await expect(compactMerge).toBeVisible({ timeout: 15_000 });
await session.prDetailTab().click();
await seedQueuedPR(apiClient, task.id);
await seedEligiblePR(apiClient, task.id);
const detail = testPage.getByTestId("change-request-detail");
const merge = detail.getByRole("button", { name: "Merge PR" });
@@ -51,7 +51,112 @@ test("adds an eligible GitHub PR to its merge queue", async ({ testPage, apiClie
await expect(detail.getByTestId("pr-merge-button")).toHaveCount(0);
});
test("surfaces queued PR metadata across desktop status surfaces", async ({
testPage,
apiClient,
seedData,
prCapture,
}) => {
test.setTimeout(120_000);
await apiClient.mockGitHubReset();
await apiClient.mockGitHubSetUser("maya-chen");
const task = await apiClient.createTaskWithAgent(
seedData.workspaceId,
"Ship resilient deployment controls",
seedData.agentProfileId,
{
description: "/e2e:simple-message",
workflow_id: seedData.workflowId,
workflow_step_id: seedData.startStepId,
repository_ids: [seedData.repositoryId],
},
);
await seedQueuedPR(apiClient, task.id);
await testPage.goto(`/t/${task.id}`);
const session = new SessionPage(testPage);
await session.waitForLoad();
await testPage.reload();
await session.waitForLoad();
await seedQueuedPR(apiClient, task.id);
const taskIcon = testPage.getByTestId("pr-task-icon-" + task.id);
await expect(taskIcon).toBeVisible({ timeout: 15_000 });
await expect(taskIcon).toHaveClass(/text-\[#966600\]/);
await taskIcon.hover();
const taskSummary = testPage
.locator('[data-slot="tooltip-content"]:not([data-state="closed"])')
.getByTestId("pr-task-status-summary")
.first();
await expect(taskSummary).toBeVisible({ timeout: 5_000 });
await expect(taskSummary.getByTestId("pr-task-status-merge")).toContainText("Queued");
await expect(taskSummary.getByTestId("pr-task-status-merge-detail")).toContainText("Position 2");
await expect(taskSummary.getByTestId("pr-task-status-merge-detail")).toContainText("2 minutes");
await prCapture.screenshot("desktop-pr-merge-queue-status", {
caption: "Desktop pull request queue status with position and estimate",
});
await session.hoverPRTopbar();
const popover = session.prTopbarPopover();
await expect(popover.getByTestId("pr-merge-queue-status")).toContainText("Queued");
await expect(popover.getByTestId("pr-merge-queue-status")).toContainText("Position 2");
await expect(popover.getByTestId("pr-merge-queue-status")).toContainText("2 minutes");
await session.hoverPRChip();
const compactPopover = session.prChipPopover();
await expect(compactPopover.getByTestId("pr-merge-queue-status")).toContainText("Queued");
await expect(compactPopover.getByTestId("pr-merge-queue-status")).toContainText("Position 2");
await expect(compactPopover.getByTestId("pr-merge-queue-status")).toContainText("2 minutes");
// The default layout can reopen PR details as a dock tab or through the
// existing topbar affordance. Keep the display scenario independent from
// the preceding merge-action test's accepted-state layout.
const detailTab = session.prDetailTab();
if (await detailTab.isVisible()) {
await detailTab.click();
} else {
await session.prTopbarButton().click();
}
await seedQueuedPR(apiClient, task.id);
const detail = testPage.getByTestId("change-request-detail");
await expect(detail).toBeVisible({ timeout: 15_000 });
await expect(detail.getByTestId("pr-merge-queue-status")).toContainText("Queued");
await expect(detail.getByTestId("pr-merge-queue-status")).toContainText("Position 2");
await expect(detail.getByTestId("pr-merge-queue-status")).toContainText("2 minutes");
});
async function seedQueuedPR(apiClient: ApiClient, taskId: string) {
await apiClient.mockGitHubAddRepos(OWNER, [
{ full_name: `${OWNER}/${REPO}`, owner: OWNER, name: REPO },
]);
await apiClient.mockGitHubAssociateTaskPR({
task_id: taskId,
owner: OWNER,
repo: REPO,
pr_number: PR_NUMBER,
pr_url: `https://github.com/${OWNER}/${REPO}/pull/${PR_NUMBER}`,
pr_title: "Make deployment rollbacks deterministic",
head_branch: "feat/resilient-rollbacks",
base_branch: "main",
author_login: "maya-chen",
state: "open",
review_state: "approved",
checks_state: "success",
mergeable_state: "blocked",
merge_queue_state: "queued",
merge_queue_position: 2,
merge_queue_estimated_time_to_merge_seconds: 61,
review_count: 2,
pending_review_count: 0,
required_reviews: 2,
checks_total: 3,
checks_passing: 3,
});
await apiClient.mockGitHubSetMergeOutcome(OWNER, REPO, PR_NUMBER, "queued");
}
async function seedEligiblePR(apiClient: ApiClient, taskId: string) {
await apiClient.mockGitHubAddRepos(OWNER, [
{ full_name: `${OWNER}/${REPO}`, owner: OWNER, name: REPO },
]);
+16
View File
@@ -217,6 +217,16 @@ export type MergeableState =
| "unknown"
| "";
/** Normalized GitHub merge-queue entry states. Future provider values are
* retained as strings so the UI can use a generic queued presentation. */
export type MergeQueueState =
| "queued"
| "awaiting_checks"
| "mergeable"
| "unmergeable"
| "locked"
| (string & {});
export type TaskPR = {
id: string;
task_id: string;
@@ -254,6 +264,12 @@ export type TaskPR = {
closed_at: string | null;
last_synced_at: string | null;
updated_at: string;
/** Empty when GitHub did not return an active merge-queue entry. */
merge_queue_state?: MergeQueueState;
/** GitHub's one-based queue position, when available. */
merge_queue_position?: number | null;
/** GitHub's estimated time to merge in seconds, when available. */
merge_queue_estimated_time_to_merge_seconds?: number | null;
// The five PR-outcome-attribution fields below are always present on a
// real API/WS payload (the backend sends every key, never omits one) — the
// `?:` here follows this file's existing convention for nullable fields
+14 -1
View File
@@ -575,5 +575,18 @@
"failedToFetchPrFiles": "Failed to fetch PR files",
"failedToLoadCiAutomationOptions": "Failed to load CI automation options.",
"failedToSearchGitHub": "Failed to search GitHub",
"pullRequestNumbered": "Pull Request #{{number}}"
"pullRequestNumbered": "Pull Request #{{number}}",
"mergeQueueEstimate_one": "Estimated merge time: {{count}} minute.",
"mergeQueueEstimate_other": "Estimated merge time: {{count}} minutes.",
"mergeQueuePosition": "Position {{position}}",
"mergeQueuePositionAndEstimate_one": "Position {{position}}. Estimated merge time: {{count}} minute.",
"mergeQueuePositionAndEstimate_other": "Position {{position}}. Estimated merge time: {{count}} minutes.",
"mergeQueuePositionAndSubMinuteEstimate": "Position {{position}}. Estimated merge time: less than a minute.",
"mergeQueueStateAwaitingChecks": "Awaiting checks",
"mergeQueueStateLocked": "Locked",
"mergeQueueStateMergeable": "Mergeable",
"mergeQueueStateQueued": "Queued",
"mergeQueueStateUnmergeable": "Unmergeable",
"mergeQueueStatus": "Merge queue: {{state}}",
"mergeQueueSubMinuteEstimate": "Estimated merge time: less than a minute."
}
+14 -1
View File
@@ -575,5 +575,18 @@
"failedToFetchPrFiles": "Ƒàĩĺēď ţō ƒēţćĥ ƤŔ ƒĩĺēś",
"failedToLoadCiAutomationOptions": "Ƒàĩĺēď ţō ĺōàď ĆĨ àũţōḿàţĩōń ōƥţĩōńś.",
"failedToSearchGitHub": "Ƒàĩĺēď ţō śēàŕćĥ ĜĩţĤũƀ",
"pullRequestNumbered": "Ƥũĺĺ Ŕēqũēśţ #{{number}}"
"pullRequestNumbered": "Ƥũĺĺ Ŕēqũēśţ #{{number}}",
"mergeQueueEstimate_one": "Ēśţĩḿàţēď ḿēŕĝē ţĩḿē: {{count}} ḿĩńũţē.",
"mergeQueueEstimate_other": "Ēśţĩḿàţēď ḿēŕĝē ţĩḿē: {{count}} ḿĩńũţēś.",
"mergeQueuePosition": "Ƥōśĩţĩōń {{position}}",
"mergeQueuePositionAndEstimate_one": "Ƥōśĩţĩōń {{position}}. Ēśţĩḿàţēď ḿēŕĝē ţĩḿē: {{count}} ḿĩńũţē.",
"mergeQueuePositionAndEstimate_other": "Ƥōśĩţĩōń {{position}}. Ēśţĩḿàţēď ḿēŕĝē ţĩḿē: {{count}} ḿĩńũţēś.",
"mergeQueuePositionAndSubMinuteEstimate": "Ƥōśĩţĩōń {{position}}. Ēśţĩḿàţēď ḿēŕĝē ţĩḿē: ĺēśś ţĥàń à ḿĩńũţē.",
"mergeQueueStateAwaitingChecks": "Àŵàĩţĩńĝ ćĥēćķś",
"mergeQueueStateLocked": "Ĺōćķēď",
"mergeQueueStateMergeable": "Ḿēŕĝēàƀĺē",
"mergeQueueStateQueued": "Qũēũēď",
"mergeQueueStateUnmergeable": "Ũńḿēŕĝēàƀĺē",
"mergeQueueStatus": "Ḿēŕĝē qũēũē: {{state}}",
"mergeQueueSubMinuteEstimate": "Ēśţĩḿàţēď ḿēŕĝē ţĩḿē: ĺēśś ţĥàń à ḿĩńũţē."
}
+14 -1
View File
@@ -575,5 +575,18 @@
"timeAgoYears_other": "há {{count}}a",
"toggleReviewFollowUpAutomation": "Alternar a automação de seguimento da revisão",
"wakeAgentOnReviewRequest": "Acordar o agente para qualquer novo pedido, incluindo nova revisão após alterações.",
"wakeAgentOnTerminalPrState": "Acordar o agente quando o trabalho de revisão terminar. Escolha um dos resultados ou ambos."
"wakeAgentOnTerminalPrState": "Acordar o agente quando o trabalho de revisão terminar. Escolha um dos resultados ou ambos.",
"mergeQueueEstimate_one": "Tempo estimado até ao merge: {{count}} minuto.",
"mergeQueueEstimate_other": "Tempo estimado até ao merge: {{count}} minutos.",
"mergeQueuePosition": "Posição {{position}}",
"mergeQueuePositionAndEstimate_one": "Posição {{position}}. Tempo estimado até ao merge: {{count}} minuto.",
"mergeQueuePositionAndEstimate_other": "Posição {{position}}. Tempo estimado até ao merge: {{count}} minutos.",
"mergeQueuePositionAndSubMinuteEstimate": "Posição {{position}}. Tempo estimado até ao merge: menos de um minuto.",
"mergeQueueStateAwaitingChecks": "A aguardar verificações",
"mergeQueueStateLocked": "Bloqueado",
"mergeQueueStateMergeable": "Integrável",
"mergeQueueStateQueued": "Em fila",
"mergeQueueStateUnmergeable": "Não integrável",
"mergeQueueStatus": "Fila de merge: {{state}}",
"mergeQueueSubMinuteEstimate": "Tempo estimado até ao merge: menos de um minuto."
}
+14 -1
View File
@@ -575,5 +575,18 @@
"timeAgoWeeks_one": "{{count}} 周前",
"timeAgoWeeks_other": "{{count}} 周前",
"timeAgoYears_one": "{{count}} 年前",
"timeAgoYears_other": "{{count}} 年前"
"timeAgoYears_other": "{{count}} 年前",
"mergeQueueEstimate_one": "预计合并时间:{{count}} 分钟",
"mergeQueueEstimate_other": "预计合并时间:{{count}} 分钟",
"mergeQueuePosition": "位置 {{position}}",
"mergeQueuePositionAndEstimate_one": "位置 {{position}}。预计合并时间:{{count}} 分钟",
"mergeQueuePositionAndEstimate_other": "位置 {{position}}。预计合并时间:{{count}} 分钟",
"mergeQueuePositionAndSubMinuteEstimate": "位置 {{position}}。预计合并时间:少于一分钟",
"mergeQueueStateAwaitingChecks": "等待检查",
"mergeQueueStateLocked": "已锁定",
"mergeQueueStateMergeable": "可合并",
"mergeQueueStateQueued": "排队中",
"mergeQueueStateUnmergeable": "不可合并",
"mergeQueueStatus": "合并队列:{{state}}",
"mergeQueueSubMinuteEstimate": "预计合并时间:少于一分钟"
}
+14 -1
View File
@@ -575,5 +575,18 @@
"timeAgoWeeks_one": "{{count}} 周前",
"timeAgoWeeks_other": "{{count}} 周前",
"timeAgoYears_one": "{{count}} 年前",
"timeAgoYears_other": "{{count}} 年前"
"timeAgoYears_other": "{{count}} 年前",
"mergeQueueEstimate_one": "預計合併時間:{{count}} 分鐘",
"mergeQueueEstimate_other": "預計合併時間:{{count}} 分鐘",
"mergeQueuePosition": "位置 {{position}}",
"mergeQueuePositionAndEstimate_one": "位置 {{position}}。預計合併時間:{{count}} 分鐘",
"mergeQueuePositionAndEstimate_other": "位置 {{position}}。預計合併時間:{{count}} 分鐘",
"mergeQueuePositionAndSubMinuteEstimate": "位置 {{position}}。預計合併時間:少於一分鐘",
"mergeQueueStateAwaitingChecks": "等待檢查",
"mergeQueueStateLocked": "已鎖定",
"mergeQueueStateMergeable": "可合併",
"mergeQueueStateQueued": "排隊中",
"mergeQueueStateUnmergeable": "不可合併",
"mergeQueueStatus": "合併佇列:{{state}}",
"mergeQueueSubMinuteEstimate": "預計合併時間:少於一分鐘"
}
+14 -1
View File
@@ -575,5 +575,18 @@
"timeAgoWeeks_one": "{{count}} 周前",
"timeAgoWeeks_other": "{{count}} 周前",
"timeAgoYears_one": "{{count}} 年前",
"timeAgoYears_other": "{{count}} 年前"
"timeAgoYears_other": "{{count}} 年前",
"mergeQueueEstimate_one": "預計合併時間:{{count}} 分鐘",
"mergeQueueEstimate_other": "預計合併時間:{{count}} 分鐘",
"mergeQueuePosition": "位置 {{position}}",
"mergeQueuePositionAndEstimate_one": "位置 {{position}}。預計合併時間:{{count}} 分鐘",
"mergeQueuePositionAndEstimate_other": "位置 {{position}}。預計合併時間:{{count}} 分鐘",
"mergeQueuePositionAndSubMinuteEstimate": "位置 {{position}}。預計合併時間:少於一分鐘",
"mergeQueueStateAwaitingChecks": "等待檢查",
"mergeQueueStateLocked": "已鎖定",
"mergeQueueStateMergeable": "可合併",
"mergeQueueStateQueued": "排隊中",
"mergeQueueStateUnmergeable": "不可合併",
"mergeQueueStatus": "合併佇列:{{state}}",
"mergeQueueSubMinuteEstimate": "預計合併時間:少於一分鐘"
}
@@ -0,0 +1,208 @@
---
spec: docs/specs/github-pr-merge-queue/spec.md
created: 2026-08-22
status: done
---
# Implementation Plan: GitHub PR Merge Queue Status
## Overview
Extend the existing batched GitHub PR sync to observe and persist merge queue
state, position, and estimated merge duration, then carry the queued semantic
through the bounded task projection and the metadata through the existing PR
status surfaces. Reuse the current task indicator, compact popover/drawer, and
review detail compositions; no new polling path, endpoint, or queue-management
action is needed.
## Backend
### GitHub queue observation
- Update `apps/backend/internal/github/graphql.go` so `batchedPRResult` decodes
`mergeQueueEntry { state position estimatedTimeToMerge }`, `prFieldsBlock`
requests it for numbered and branch queries, and `convertBatchedPRResult`
normalizes the provider enum while retaining GitHub's one-based position and
optional estimate in seconds.
- Update `apps/backend/internal/github/models.go` so `PRStatus` carries the
normalized queue state, position, and estimate plus one internal populated
guard, and `TaskPR` carries the three persisted queue fields.
- Keep `newPRStatus` in `apps/backend/internal/github/client_helpers.go`
queue-unaware. Its populated guard remains false, so REST and `gh pr view`
feedback reads cannot erase a GraphQL observation.
### Persistence and synchronization
- Add `merge_queue_state TEXT NOT NULL DEFAULT ''`, nullable
`merge_queue_position INTEGER`, and nullable
`merge_queue_estimated_time_to_merge_seconds INTEGER` to the fresh
`github_task_prs` schema and the idempotent existing-database migration in
`apps/backend/internal/github/store.go`.
- Thread the field through `taskPRColumns`, `taskPRColumnsQualified`,
`CreateTaskPR`, `ReplaceTaskPR`, `RestoreTaskPR`, and `UpdateTaskPR` so every
association path round-trips the complete queue entry and schema replay
remains safe.
- Extend `taskPRSyncState`, `prepareTaskPRSyncState`,
`taskPRChangedFields`, and `SyncTaskPR` in
`apps/backend/internal/github/service_pr_watch.go`. A populated GraphQL
result atomically replaces the stored queue state, position, and estimate; an
unpopulated read preserves all three; and any merged or closed lifecycle
state clears all three.
- Extend `associateTaskPRRequest` and `buildTaskPRFromRequest` in
`apps/backend/internal/github/mock_controller.go` so E2E fixtures can seed a
queue state, position, and estimate and publish the normal
`github.task_pr.updated` event.
### Bounded task status
- Add merge queue state to the PR observation and rebuild input in
`apps/backend/internal/task/statussummary`, including live event projection,
restart rebuild, and aggregate-state derivation.
- Add `queued` to the bounded PR aggregate states with a rank between `ready`
and `passing`: a more attention-worthy sibling still wins for multi-PR
tasks, while a single queued PR retains the queue color.
- Pass `TaskPR.MergeQueueState` through
`apps/backend/internal/backendapp/status_summary_adapter.go` so restart
hydration and live events converge on the same aggregate state.
## Frontend
### Types and semantic color
- Add the normalized `MergeQueueState` union and all three TaskPR queue fields
to `apps/web/lib/types/github.ts`.
- Add the shared `queued` semantic to
`apps/web/components/integrations/change-request-task-status-color.ts`, using
the exact `text-[#966600]` GitHub merge-queue color. This color is distinct
from the current yellow CI-in-progress state. Add the same queued tone to the
shared task-summary presentation. Preserve the existing worst-status
aggregation for tasks with several open PRs.
- Update `apps/web/components/github/pr-task-icon.tsx` and
`apps/web/components/github/pr-status-chip.tsx` so an open queued PR exposes
the queue color/status and a dedicated glyph before non-terminal review,
check, and mergeability colors. Terminal states still win.
### Hover, compact status, and review detail
- Extend the shared summary-row data in
`apps/web/components/integrations/change-request-task-status-summary.tsx`
with an optional localized detail line. Use it from the merge row in
`apps/web/components/github/pr-task-status-summary.tsx` to show queue state,
one-based position, and the available estimate. Recognized values
distinguish queued, awaiting checks, mergeable, unmergeable, and locked;
unknown non-empty values use generic queued copy.
- Add a reusable queue-status notice under
`apps/web/components/github/` that formats position and GitHub's estimate in
localized minute/hour units. Values below 60 seconds use a localized
sub-minute label; larger values round up to the next whole minute. Render it
from `pr-mergeability-row.tsx` and `pr-detail-panel.tsx`. This places the same
queue information in the compact desktop popover, phone status drawer, and
full PR detail panel without creating another data fetch.
- Add queue labels, descriptions, position, and pluralized duration copy to all
five `apps/web/src/locales/*/github.json` catalogs. Generate `zh-hk` and
`zh-tw` with `pnpm run i18n:zh-hant`.
### Mobile design contract
- **Desktop outcome:** task and compact PR indicators use the queue color;
hover/popover content and PR detail show translated queue state, position,
and the available estimate.
- **Mobile entry points:** tap the existing composer PR status chip for its
drawer, or open the existing full-height Review destination.
- **Nearest shipped exemplars:** `PRStatusChipDrawer` contributes the inset,
internally scrolling status drawer; the existing mobile Review surface
contributes direct navigation and full-height review geometry.
- **Information hierarchy:** queue status replaces the mergeability line for
an active entry and sits below review/check information in compact status;
position and estimate form one subordinate metadata line. The detail notice
stays below the PR header and above review content.
- **Presentation and rationale:** retain the current drawer and direct Review
navigation because this is content-only status inside already established
surfaces, not a new temporary choice or primary destination.
- **Geometry and shared logic:** no scroll owner, safe-area, breakpoint, or
touch-target changes. Queue derivation, copy, and state are shared between
viewports; only the existing responsive wrappers differ.
## Tests
- **What:** GraphQL selection and decoding distinguish every known queue enum,
position, a present or absent estimated duration, `null`, and an unknown
future state. **File:**
`apps/backend/internal/github/graphql_merge_queue_status_test.go`. **How:** query snapshot and
table-driven conversion tests.
- **What:** sync atomically persists queue entry transitions and metadata,
preserves all fields across queue-unaware feedback reads, clears them on an
authoritative `null`, and clears them for terminal PRs. **File:**
`apps/backend/internal/github/service_pr_merge_queue_status_test.go`. **How:**
focused service tests against the real store.
- **What:** fresh schema, same-database replay, and every TaskPR write/read path
round-trip the complete queue entry. **Files:**
`apps/backend/internal/github/store_taskpr_schema_drift_test.go` and
`apps/backend/internal/github/store_merge_queue_status_test.go`. **How:** real
SQLite store tests.
- **What:** live projection and restart rebuild derive the same `queued`
aggregate and preserve multi-PR attention ranking. **Files:**
`apps/backend/internal/task/statussummary/projector_test.go`,
`apps/backend/internal/task/statussummary/rebuild_test.go`, and
`apps/backend/internal/backendapp/status_summary_adapter_test.go`. **How:**
table-driven projection and adapter tests.
- **What:** queue membership maps to `#966600` on the task icon and compact
chip. The hover merge row, compact queue notice, and detail notice show the
translated status and metadata. Terminal and non-queued states retain their
existing behavior.
**Files:**
`apps/web/components/github/pr-task-icon.test.ts`,
`pr-task-status-summary.test.ts`, `pr-status-chip.test.tsx`,
`pr-merge-queue-status.test.tsx`, `pr-mergeability-row.test.tsx`, and
`pr-detail-panel.test.tsx`. **How:** pure formatter and focused component
tests, including absent, sub-minute, minute, and hour estimate boundaries.
## E2E Tests
- **Scenario:** GIVEN an eligible queue-required PR, WHEN a desktop user
activates `Merge PR`, THEN the merge API returns `{"status":"queued"}`,
the success notification appears, and the accepted state suppresses the
duplicate action. **File:** the action test in
`apps/web/e2e/tests/pr/pr-merge-queue.spec.ts`.
- **Scenario:** GIVEN a linked open PR with an active merge queue entry, WHEN a
desktop user views the task and PR detail, THEN the task indicator has queued
semantics, its hover summary and compact popover show queue state, position,
and estimated merge duration, and the detail notice shows the same data.
**File:** the display test in
`apps/web/e2e/tests/pr/pr-merge-queue.spec.ts`.
- **Scenario:** GIVEN an eligible queue-required PR on a phone viewport, WHEN
the user opens Review and activates the action, THEN the queued notification
appears, the action target is at least 44px high, and the document has no
horizontal overflow. **File:** the action test in
`apps/web/e2e/tests/pr/mobile-pr-merge-queue.spec.ts`.
- **Scenario:** GIVEN the same queued PR on a phone viewport, WHEN the user
opens the PR status drawer and the Review destination, THEN both expose queue
status, position, and the available estimate without hover, and the document
retains no horizontal overflow. **File:** the display test in
`apps/web/e2e/tests/pr/mobile-pr-merge-queue.spec.ts`.
## Verification Results
Passed:
- `cd apps/backend && go test -tags fts5 ./internal/github/... ./internal/task/statussummary/... ./internal/backendapp` passed 2,193 tests across 3 packages. The focused RED run recorded the expected missing-contract compile failures, and the focused GREEN run passed the queue precedence tests.
- `cd apps/web && pnpm test -- components/github/pr-task-icon.test.ts components/github/pr-task-status-summary.test.ts components/github/pr-status-chip.test.tsx components/github/pr-merge-queue-status.test.tsx components/github/pr-mergeability-row.test.tsx components/github/pr-detail-panel.test.tsx` passed 160 tests across 6 files.
- `cd apps/web && pnpm run typecheck` and `cd apps/web && pnpm run lint` passed. `cd apps/web && pnpm run i18n:check` passed with 7,223 referenced keys, 8,779 English entries, 48 orphans, and all five required catalogs complete.
- `node scripts/validate-public-docs.test.mjs` passed 61 tests, and `node scripts/validate-public-docs.mjs` validated 41 published pages. `docs/public/integrations.md` documents queue state, position, and estimate surfaces.
- A fresh `cd apps/web && pnpm e2e:run tests/pr/pr-merge-queue.spec.ts` build completed the backend, Vite production bundle, and plugin. The final desktop run passed 2 tests, including the merge-action and queue-display scenarios, and `pnpm e2e:run --no-build --project mobile-chrome tests/pr/mobile-pr-merge-queue.spec.ts` passed 2 matching tests.
- Previously captured display assets remain valid: `apps/web/.pr-assets/pr-merge-queue--desktop-pr-merge-queue-status.png` and `apps/web/.pr-assets/mobile-pr-merge-queue--mobile-pr-merge-queue-status.png`. Both were inspected, compressed with the `pngquant-bin` fallback, and preserved for PR media publication; action coverage is behavioral and adds no capture asset.
- `cd apps/web && pnpm e2e:clean` removed E2E results, reports, PR assets, and shard logs. The E2E scenarios use mock GitHub state and created no external GitHub writes.
## Implementation Waves And Parallel Candidates
Wave 1:
- [x] [Task 01: Backend queue-state projection](task-01-backend-queue-state.md)
Wave 2:
- [x] [Task 02: Frontend queued PR status](task-02-frontend-queued-status.md)
Wave 3:
- [x] [Task 03: Responsive merge-queue E2E](task-03-responsive-merge-queue-e2e.md)
Execution is sequential in the primary conversation unless the user explicitly
authorizes subagents.
@@ -0,0 +1,95 @@
---
id: "01-backend-queue-state"
title: "Backend queue-state projection"
status: done
wave: 1
depends_on: []
plan: "plan.md"
spec: "../../specs/github-pr-merge-queue/spec.md"
---
# Task 01: Backend queue-state projection
## Acceptance
- Batched GitHub GraphQL status reads normalize `mergeQueueEntry.state` and
retain its one-based position and optional estimate in seconds, while
queue-unaware reads explicitly preserve the last complete observation.
- The three `github_task_prs` queue fields survive every TaskPR persistence
path, clear atomically on an authoritative queue exit or terminal lifecycle
state, and emit the normal task-PR update when any value changes.
- Live and restart-built bounded task summaries derive the same `queued`
aggregate state, including the existing multi-PR attention ordering.
## Verification
```bash
cd apps/backend && go test -tags fts5 ./internal/github/... ./internal/task/statussummary/... ./internal/backendapp
```
## Files likely touched
- `apps/backend/internal/github/models.go`
- `apps/backend/internal/github/graphql.go`
- `apps/backend/internal/github/client_helpers.go`
- `apps/backend/internal/github/store.go`
- `apps/backend/internal/github/service_pr_watch.go`
- `apps/backend/internal/github/mock_controller.go`
- `apps/backend/internal/github/graphql_merge_queue_status_test.go`
- `apps/backend/internal/github/service_pr_merge_queue_status_test.go`
- `apps/backend/internal/github/store_taskpr_schema_drift_test.go`
- `apps/backend/internal/github/store_merge_queue_status_test.go`
- `apps/backend/internal/task/statussummary/constants.go`
- `apps/backend/internal/task/statussummary/projector.go`
- `apps/backend/internal/task/statussummary/projector_events.go`
- `apps/backend/internal/task/statussummary/projector_pr.go`
- `apps/backend/internal/task/statussummary/rebuild.go`
- `apps/backend/internal/task/statussummary/projector_test.go`
- `apps/backend/internal/task/statussummary/rebuild_test.go`
- `apps/backend/internal/backendapp/status_summary_adapter.go`
- `apps/backend/internal/backendapp/status_summary_adapter_test.go`
## Dependencies
None.
## Parallelism
Sequential. This task owns the shared queue-state contract, schema, sync, and
bounded projection and queue metadata contract that later tasks consume.
## Inputs
- Spec sections: **Data Model**, **API Surface**, **State Machine**, **Failure
Modes**, and queue-status scenarios.
- Plan sections: **GitHub queue observation**, **Persistence and
synchronization**, and **Bounded task status**.
- Existing patterns: GraphQL populated guards on `PRStatus`, TaskPR explicit
column lists, and `mergeable_state` event/rebuild projection.
## Risks
- Treating a queue-unaware read as an authoritative empty value would cause
queued status to flicker or disappear when the detail panel refreshes.
- Missing one explicit TaskPR column/write path would break rollback-safe reads
or silently drop queue metadata on association replacement.
## Output contract
Report the summary, exact files changed, exact test command and result,
blockers, remaining risks, and synchronized task/plan status in this
conversation.
## Results
Passed:
- `cd apps/backend && go test -tags fts5 ./internal/github/... ./internal/task/statussummary/... ./internal/backendapp`
(2,193 tests passed across 3 packages, including terminal → queued
precedence and failing-sibling ranking).
- Focused RED run recorded the expected missing-contract compile failures before
implementation; the focused GREEN run passed 13 queue/projection tests.
No generated artifacts or external GitHub writes were produced. The trust
boundary remains GitHub's GraphQL `mergeQueueEntry`; queue-unaware REST and
`gh pr view` reads preserve the last observed queue fields.
@@ -0,0 +1,105 @@
---
id: "02-frontend-queued-status"
title: "Frontend queued PR status"
status: done
wave: 2
depends_on: ["01-backend-queue-state"]
plan: "plan.md"
spec: "../../specs/github-pr-merge-queue/spec.md"
---
# Task 02: Frontend queued PR status
## Acceptance
- Open queued PRs use GitHub's `#966600` merge-queue color for the task icon and
compact chip. Yellow remains the CI-in-progress color.
terminal PRs and more attention-worthy multi-PR siblings retain their
established priority.
- The task hover summary, compact desktop popover or phone drawer, and PR detail
notice show localized queue-state copy, one-based position, and the available
estimated merge duration without exposing raw GitHub values.
- All five locale catalogs, i18n checks, typecheck, and focused component tests
cover queued, queue-exit, unknown-enum, and terminal behavior.
- Terminal colors remain authoritative, then an active queue entry takes
precedence over other non-terminal failure, draft, dirty, or behind fields.
A failing sibling still outranks a queued sibling during multi-PR
aggregation, and future provider states use generic queued copy.
## Verification
```bash
cd apps && pnpm install --frozen-lockfile && pnpm --filter @kandev/web test -- components/github/pr-task-icon.test.ts components/github/pr-task-status-summary.test.ts components/github/pr-status-chip.test.tsx components/github/pr-merge-queue-status.test.tsx components/github/pr-mergeability-row.test.tsx components/github/pr-detail-panel.test.tsx && pnpm --filter @kandev/web i18n:check && pnpm --filter @kandev/web typecheck
```
## Files likely touched
- `apps/web/lib/types/github.ts`
- `apps/web/components/integrations/change-request-task-status-color.ts`
- `apps/web/components/integrations/change-request-task-status-summary.tsx`
- `apps/web/components/github/pr-task-icon.tsx`
- `apps/web/components/github/pr-task-status-summary.tsx`
- `apps/web/components/github/pr-status-chip.tsx`
- `apps/web/components/github/pr-merge-queue-status.tsx`
- `apps/web/components/github/pr-mergeability-row.tsx`
- `apps/web/components/github/pr-detail-panel.tsx`
- `apps/web/components/github/pr-task-icon.test.ts`
- `apps/web/components/github/pr-task-status-summary.test.ts`
- `apps/web/components/github/pr-status-chip.test.tsx`
- `apps/web/components/github/pr-merge-queue-status.test.tsx`
- `apps/web/components/github/pr-mergeability-row.test.tsx`
- `apps/web/components/github/pr-detail-panel.test.tsx`
- `apps/web/src/locales/en/github.json`
- `apps/web/src/locales/pt-pt/github.json`
- `apps/web/src/locales/zh-cn/github.json`
- `apps/web/src/locales/zh-hk/github.json`
- `apps/web/src/locales/zh-tw/github.json`
## Dependencies
Task 01 supplies the normalized TaskPR queue-entry contract and bounded `queued`
aggregate.
## Parallelism
Sequential. It consumes the backend contract and owns shared frontend status
helpers used by both E2E surfaces.
## Inputs
- Spec sections: **What**, **State Machine**, queue-status scenarios, and **Out
of Scope**.
- Plan sections: **Types and semantic color**, **Hover, compact status, and
review detail**, and **Mobile design contract**.
- Existing patterns: `getPRStatusColor`, `derivePRTaskStatusSummary`,
`PRMergeabilityRow`, `PRMergeabilityNotice`, and `PRStatusChipDrawer`.
## Risks
- Queue color precedence must not change merged or closed colors. Tests must
distinguish the exact `#966600` queue color from yellow CI-in-progress.
- The optional estimate must not suppress queue state or position when GitHub
returns it as null.
- Queue copy must remain available on coarse pointers through the drawer and
Review surface; a tooltip-only result would violate mobile parity.
## Output contract
Report the summary, exact files changed, exact commands and results, generated
locale changes, blockers, remaining risks, rendered verification evidence, and
synchronized task/plan status in this conversation.
## Results
Passed:
- Implemented the queued semantic, `#966600` color, localized queue metadata formatter, task summary detail row, compact status chip, drawer, and PR detail notice.
- `cd apps/web && pnpm test -- components/github/pr-task-icon.test.ts components/github/pr-task-status-summary.test.ts components/github/pr-status-chip.test.tsx components/github/pr-merge-queue-status.test.tsx components/github/pr-mergeability-row.test.tsx components/github/pr-detail-panel.test.tsx` passed 160 tests across 6 files.
- `cd apps/web && pnpm run typecheck` passed. `cd apps/web && pnpm run lint` passed with no warnings or errors. `cd apps/web && pnpm run i18n:check` passed with 7,223 referenced keys, 8,779 English entries, 48 orphans, and complete `pt-pt`, `zh-cn`, `zh-hk`, and `zh-tw` catalogs.
- Added queue keys to English, Portuguese, Simplified Chinese, Traditional Chinese, and pseudo catalogs. `pnpm run i18n:zh-hant` reached its existing unrelated `agents:dynamicProfileSettings` residual; the namespace-specific `convert-zh-cn-to-zh-hant.mjs --locale all --namespace github --write` command generated the Traditional Chinese queue entries with zero residual queue keys. `pnpm run i18n:pseudo` generated the pseudo queue entries.
- Desktop and mobile E2E runs rendered the queue state, position, and estimate in the two display scenarios, while the two action scenarios restored API, notification, duplicate-suppression, and mobile target coverage. The reviewed files were `apps/web/.pr-assets/pr-merge-queue--desktop-pr-merge-queue-status.png` and `apps/web/.pr-assets/mobile-pr-merge-queue--mobile-pr-merge-queue-status.png`; both were removed by the final `pnpm e2e:clean` run after preservation for PR media publication.
- No external side effects occurred. The implementation reads GitHub queue metadata and does not add queue-management actions.
- Queue precedence regressions pass for a queued PR with failure, changes
requested, dirty, behind, or draft fields, while failing siblings retain
aggregate priority. Future provider enums resolve to `queue_queued` and the
generic localized `Queued` label.
@@ -0,0 +1,81 @@
---
id: "03-responsive-merge-queue-e2e"
title: "Responsive merge-queue E2E"
status: done
wave: 3
depends_on: ["01-backend-queue-state", "02-frontend-queued-status"]
plan: "plan.md"
spec: "../../specs/github-pr-merge-queue/spec.md"
---
# Task 03: Responsive merge-queue E2E
## Acceptance
- Desktop E2E has separate action and display scenarios. The action scenario
proves the existing PR UI exposes `Merge PR`, returns the queued API outcome,
shows the success notification, and suppresses the accepted action. The
display scenario proves the task indicator, task hover summary, compact PR
popover, and PR detail notice expose queue state, position, and estimated
merge duration.
- Mobile E2E has separate action and display scenarios. The action scenario
reaches the queued outcome through Review using touch, verifies a minimum
44px action target, and checks the success notification. The display scenario
proves the existing PR status drawer and full-height Review surface expose the
same queue state and metadata without hover.
- Both display scenarios retain touch reachability and assert no document-level
horizontal overflow against a freshly built production bundle.
## Verification
```bash
cd apps && pnpm install --frozen-lockfile && cd web && pnpm e2e:run tests/pr/pr-merge-queue.spec.ts && pnpm e2e:run --no-build --project mobile-chrome tests/pr/mobile-pr-merge-queue.spec.ts
```
## Files likely touched
- `apps/web/e2e/helpers/api-client.ts`
- `apps/web/e2e/pages/session-page.ts`
- `apps/web/e2e/tests/pr/pr-merge-queue.spec.ts`
- `apps/web/e2e/tests/pr/mobile-pr-merge-queue.spec.ts`
## Dependencies
Tasks 01 and 02 must provide the seed contract and rendered queue surfaces.
## Parallelism
Sequential. These tests validate the integrated backend/frontend behavior and
must follow both implementation tasks.
## Inputs
- Spec scenarios for active queue entry, mobile reachability, and terminal or
authoritative queue exit behavior.
- Plan **E2E Tests** and **Mobile design contract** sections.
- Existing patterns in the two merge-queue specs, `SessionPage`,
`mockGitHubAssociateTaskPR`, and layout assertions.
## Risks
- The display tests must seed queue membership, position, and estimate as
authoritative TaskPR state rather than infer them from the merge-button
success toast. The action tests must seed an eligible, not-yet-queued PR so
the merge button and accepted response remain covered independently.
- Desktop and mobile projects must run separately; repeating `--project` in one
runner invocation would silently select only the final project.
## Output contract
Report the summary, exact files changed, discovered test counts, exact E2E
commands and results, failure artifact paths if any, cleanup/teardown evidence,
blockers, risks, and synchronized task/plan status in this conversation.
## Results
Passed:
- `cd apps/web && pnpm e2e:run tests/pr/pr-merge-queue.spec.ts` built the backend, Vite production bundle, and plugin, then passed 2 tests: the desktop merge action and the queued-status display. The display test retains the strict-tooltip locator correction.
- `cd apps/web && pnpm e2e:run --no-build --project mobile-chrome tests/pr/mobile-pr-merge-queue.spec.ts` passed 2 tests: the mobile Review merge action with the minimum target-height assertion and the drawer/Review queue display with no document-level horizontal overflow.
- `CAPTURE_PR_ASSETS=true pnpm e2e:run --no-build tests/pr/pr-merge-queue.spec.ts` and the matching mobile command continue to capture the display tests; the desktop and mobile PNGs were inspected and compressed with `pnpm dlx pngquant-bin@9.0.0 --quality 65-90 --ext .png --force`. Action coverage is behavioral and adds no capture asset.
- `cd apps/web && pnpm e2e:clean` removed generated E2E results, reports, PR assets, and shard logs. Tests used mock GitHub state and temporary repositories only; no external GitHub writes occurred.
+91 -22
View File
@@ -9,9 +9,13 @@ status: complete
## Overview
Extend the existing GitHub merge boundary to use GitHub's asynchronous,
queue-aware merge request and return a typed merged-or-queued outcome. Then
reuse that outcome in the existing PR merge button across the desktop detail,
compact status, and mobile Review surfaces, with targeted unit and E2E proof.
queue-aware merge request and return a typed merged-or-queued outcome. Observe
the resulting merge-queue entry through the existing GraphQL status sync,
persist its state, one-based position, and optional estimated duration, and
project it through the existing task and PR status surfaces. Reuse the typed
outcome and the persisted status in the existing PR merge button across the
desktop detail, compact status, and mobile Review surfaces, with targeted unit
and E2E proof.
## Backend
@@ -37,6 +41,21 @@ compact status, and mobile Review surfaces, with targeted unit and E2E proof.
`{"status":"merged"}` or `{"status":"queued"}` and retain the existing
operational-auth and provider-error mapping.
### Queue observation, persistence, and bounded projection
- Extend the batched GraphQL pull-request selection and normalized `PRStatus`
with `mergeQueueEntry { state position estimatedTimeToMerge }`. A populated
GraphQL result replaces all three queue fields atomically; queue-unaware REST
and `gh pr view` reads preserve the last complete observation, while an
authoritative null or terminal lifecycle state clears it.
- Add the queue state, one-based position, and optional estimate in seconds to
every `TaskPR` schema, migration, write, restore, and update path. Extend
the mock controller so integrated tests can seed the same contract.
- Carry queue membership through live and restart-built task status summaries
as the bounded `queued` state. Terminal states precede queue membership;
queue membership precedes other non-terminal states for one PR, while the
existing aggregate ranking keeps a failing sibling above a queued sibling.
## Frontend
### Queue-aware merge action
@@ -54,6 +73,22 @@ compact status, and mobile Review surfaces, with targeted unit and E2E proof.
`apps/web/src/locales/*/github.json`; generate the Traditional Chinese pair
through the repository script rather than translating them independently.
### Queue status color and surfaces
- Add the normalized queue fields to the web `TaskPR` contract and the shared
queued semantic color `text-[#966600]`. Terminal colors remain first; an
active queue entry is second, so hydrated failure, draft, dirty, or behind
fields cannot overwrite queue presentation. Multi-PR aggregation still ranks
a failing sibling above a queued sibling.
- Extend the task hover summary, compact desktop popover, phone status drawer,
and PR detail panel with translated queue state, one-based position, and an
optional estimate rounded up to localized whole minutes. Missing estimates
omit only the estimate line. Recognized provider states retain their labels;
future non-empty states use generic `Queued` copy.
- Keep queue derivation shared across desktop and mobile. Mobile display uses
the existing drawer and Review destination; the mobile merge-action test
separately verifies the existing 44px action target.
### Mobile design contract
- Desktop outcome: the existing PR detail header and compact status surface
@@ -92,31 +127,59 @@ compact status, and mobile Review surfaces, with targeted unit and E2E proof.
and refresh callback. **File:**
`apps/web/components/github/pr-merge-button.test.tsx`. **How:** component tests
with mocked API outcomes.
- **What:** queue observation, persistence, queue-unaware read preservation,
terminal clearing, and bounded live/restart projection. **Files:**
`apps/backend/internal/github/*merge_queue_status_test.go`,
`apps/backend/internal/github/store_taskpr_schema_drift_test.go`,
`apps/backend/internal/task/statussummary/merge_queue_status_test.go`, and
`apps/backend/internal/backendapp/status_summary_adapter_test.go`. **How:**
focused GraphQL, real-store, and projection tests.
- **What:** queue color precedence, failing-sibling aggregation, translated
queue metadata, estimate boundaries, terminal queue clearing, and generic
fallback copy. **Files:**
`apps/web/components/github/pr-task-icon.test.ts`,
`pr-task-status-summary.test.ts`, `pr-status-chip.test.tsx`,
`pr-merge-queue-status.test.tsx`, `pr-mergeability-row.test.tsx`, and
`pr-detail-panel.test.tsx`. **How:** pure formatter and focused component
tests for terminal, queued, future-state, missing-estimate, sub-minute, and
minute-boundary cases.
## E2E Tests
- **Scenario:** eligible direct merge reports merged. **File:**
`apps/web/e2e/tests/pr/pr-merge-queue.spec.ts`. **What to verify:** the desktop
PR surface exposes the action, submits it, and shows the merged notification.
- **Scenario:** queue-required merge reports queued and does not resubmit.
**File:** `apps/web/e2e/tests/pr/pr-merge-queue.spec.ts`. **What to verify:**
the desktop action remains available for the queue-required state and the
accepted queue notification is shown once.
- **Scenario:** phone Review surface provides the same queued outcome. **File:**
`apps/web/e2e/tests/pr/mobile-pr-merge-queue.spec.ts`. **What to verify:**
Review navigation, touch activation, queued notification, a touch-sized
action, and no document horizontal overflow.
- **Scenario:** an eligible queue-required merge is accepted. **File:**
`apps/web/e2e/tests/pr/pr-merge-queue.spec.ts`, action test. **What to
verify:** the desktop PR surface exposes `Merge PR`, the merge request
returns `{"status":"queued"}`, the success notification appears, and the
accepted state suppresses the duplicate action.
- **Scenario:** an already queued PR exposes hydrated queue metadata. **File:**
`apps/web/e2e/tests/pr/pr-merge-queue.spec.ts`, display test. **What to
verify:** task icon color, task hover summary, compact popover, and detail
notice show queued state, position, and estimated duration.
- **Scenario:** the same accepted action is touch-usable. **File:**
`apps/web/e2e/tests/pr/mobile-pr-merge-queue.spec.ts`, action test. **What to
verify:** Review navigation, touch activation, queued notification, a
minimum 44px action target, and no document horizontal overflow.
- **Scenario:** an already queued PR is readable on a phone. **File:**
`apps/web/e2e/tests/pr/mobile-pr-merge-queue.spec.ts`, display test. **What to
verify:** the existing PR status drawer and full-height Review surface show
queued state, position, and estimate without hover or horizontal overflow.
## Verification Results
- Backend: `make -C apps/backend test ARGS='./internal/github/...'` passed; the
Make target executed the full backend `go test -tags fts5 ./...` suite.
- Frontend: 96 focused Vitest tests passed; `pnpm run i18n:check` and
`pnpm run typecheck` passed.
- Desktop E2E: `pnpm e2e:run --no-build tests/pr/pr-merge-queue.spec.ts`
passed (1 test).
- Mobile E2E: `pnpm e2e:run --no-build --project mobile-chrome
tests/pr/mobile-pr-merge-queue.spec.ts` passed (1 test).
Recorded after the remediation run:
- Backend: `cd apps/backend && go test -tags fts5
./internal/github/... ./internal/task/statussummary/...
./internal/backendapp` passed 2,193 tests across 3 packages, including the
queue precedence regression.
- Frontend: the six-file queue-status command passed 160 tests. `pnpm run
typecheck` and `pnpm run lint` passed. `pnpm run i18n:check` passed with
7,223 referenced keys, 8,779 English entries, 48 orphans, and all five
required catalogs complete.
- Desktop E2E: the fresh-build `cd apps/web && pnpm e2e:run
tests/pr/pr-merge-queue.spec.ts` passed 2 tests in 12.2 seconds. Mobile E2E:
`pnpm e2e:run --no-build --project mobile-chrome
tests/pr/mobile-pr-merge-queue.spec.ts` passed 2 tests in 9.6 seconds.
## Implementation Waves And Parallel Candidates
@@ -129,5 +192,11 @@ Wave 2:
Wave 3:
- [x] [task-03-desktop-mobile-e2e](task-03-desktop-mobile-e2e.md)
The detailed queue-observation task package under
`docs/plans/github-pr-merge-queue-status/` is the synchronized execution record
for the persistence, projection, queue color, metadata, and responsive display
work described above. Its E2E task and this parent plan intentionally record
the same two desktop and two mobile scenarios.
Execution is sequential in the primary conversation unless the user explicitly
authorizes subagents.
@@ -25,6 +25,11 @@ spec: "../../specs/github-pr-merge-queue/spec.md"
- `apps/backend/internal/github/noop_client.go`
- `apps/backend/internal/github/service_pr.go`
- `apps/backend/internal/github/controller.go`
- `apps/backend/internal/github/graphql.go`
- `apps/backend/internal/github/models.go`
- `apps/backend/internal/github/store.go`
- `apps/backend/internal/github/service_pr_watch.go`
- `apps/backend/internal/task/statussummary/projector_pr.go`
- Their focused `*_test.go` files
## Acceptance
@@ -35,6 +40,10 @@ spec: "../../specs/github-pr-merge-queue/spec.md"
including already-queued idempotency, and unknown results fail closed.
- The workspace-scoped HTTP endpoint returns the normalized outcome while
retaining auth routing, cache invalidation, validation, and error mapping.
- The existing GraphQL status sync observes queue state, one-based position,
and optional estimate; persistence preserves queue-unaware reads, clears
authoritative exits and terminal states, and the bounded task projection
exposes the queued state with multi-PR attention ranking.
## Verification
@@ -35,11 +35,15 @@ spec: "../../specs/github-pr-merge-queue/spec.md"
PR state, and prevent duplicate submission; rejected requests remain retryable.
- Desktop, compact, and mobile Review surfaces reuse the same mutation and
eligibility behavior with accessible, touch-usable controls.
- An active queue entry uses the dedicated `#966600` color before other
non-terminal review, check, draft, dirty, or behind states. A failing sibling
still wins multi-PR aggregation, terminal colors remain authoritative, and
future non-empty queue states use generic queued copy.
## Verification
```bash
cd apps && pnpm install --frozen-lockfile && pnpm --filter @kandev/web test -- lib/api/domains/github-api.test.ts components/github/pr-task-icon.test.ts components/github/pr-merge-button.test.tsx && cd web && pnpm run i18n:check && pnpm run typecheck
cd apps && pnpm install --frozen-lockfile && pnpm --filter @kandev/web test -- lib/api/domains/github-api.test.ts components/github/pr-task-icon.test.ts components/github/pr-merge-button.test.tsx components/github/pr-task-status-summary.test.ts components/github/pr-status-chip.test.tsx components/github/pr-merge-queue-status.test.tsx && cd web && pnpm run i18n:check && pnpm run typecheck
```
## Dependencies And Risks
@@ -52,12 +56,21 @@ cd apps && pnpm install --frozen-lockfile && pnpm --filter @kandev/web test -- l
## Results
- `pnpm --filter @kandev/web test -- --run lib/api/domains/github-api.test.ts components/github/pr-task-icon.test.ts` passed: 96 tests.
- `pnpm run i18n:check` passed with all supported catalogs complete.
- The six-file queue-status command passed 160 tests, including the queue
precedence, failing-sibling, and future-state fallback regressions. The
existing API and merge-button action tests remain covered by Task 02's
frontend suite.
- `pnpm run i18n:check` passed with 7,223 referenced keys, 8,779 English
entries, 48 orphans, and all supported catalogs complete.
- `pnpm run typecheck` passed.
- Review remediation keeps GitHub's overloaded `blocked` state visually neutral
and labels the pre-submit action `Merge PR`; only the accepted response claims
that GitHub added the PR to its merge queue.
- Queue state is checked after terminal state and before other non-terminal
states in both task-icon and compact-chip status derivation. Multi-PR status
ranking still lets a failing sibling dominate a queued sibling.
- Future provider queue enums map to the generic queued status rather than an
`Unknown` label.
- Queue feedback is driven by GitHub's terminal `enqueued` result, not
asynchronous `pending` acceptance.
- Focused terminal-outcome coverage passes for merged, queued, rejected, and
@@ -26,18 +26,24 @@ spec: "../../specs/github-pr-merge-queue/spec.md"
## Acceptance
- Desktop E2E proves merge-queue acceptance from the existing PR UI.
- Component coverage proves immediate merge feedback and duplicate-submission
suppression without duplicating those deterministic cases in Playwright.
- Mobile E2E reaches the same queued outcome through Review using touch and
verifies action size and absence of horizontal document overflow.
- The managed runner builds fresh backend/frontend artifacts and both focused
projects pass without retries masking failures.
- Desktop E2E has separate action and display scenarios. The action scenario
proves the existing PR UI exposes `Merge PR`, returns the queued API outcome,
shows the success notification, and suppresses the accepted action. The
display scenario proves task hover, compact popover, and detail notice expose
queued state, position, and estimated duration.
- Mobile E2E has separate action and display scenarios. The action scenario
reaches the queued outcome through Review using touch, verifies a minimum
44px action target, and checks the success notification. The display scenario
verifies the existing status drawer and Review surface expose queue metadata
without hover.
- Both display scenarios retain the absence-of-horizontal-document-overflow
assertion, and the managed runner builds fresh backend/frontend artifacts
before the focused projects pass without retries masking failures.
## Verification
```bash
cd apps && pnpm install --frozen-lockfile && cd web && pnpm e2e:run tests/pr/pr-merge-queue.spec.ts && pnpm e2e:run --project mobile-chrome tests/pr/mobile-pr-merge-queue.spec.ts
cd apps && pnpm install --frozen-lockfile && cd web && pnpm e2e:run tests/pr/pr-merge-queue.spec.ts && pnpm e2e:run --no-build --project mobile-chrome tests/pr/mobile-pr-merge-queue.spec.ts
```
## Dependencies And Risks
@@ -50,10 +56,15 @@ cd apps && pnpm install --frozen-lockfile && cd web && pnpm e2e:run tests/pr/pr-
## Results
- Desktop managed E2E passed with one discovered test.
- Mobile Chrome managed E2E passed with one discovered test, including the
touch action, minimum target height, and horizontal-overflow assertions.
- `pnpm run typecheck` passed after the final E2E helper and spec changes.
- Isolated desktop and mobile screenshots were captured under
`/tmp/kandev-merge-queue-screenshots-20260817/`; capture-only test hooks were
removed and both specs passed again afterward.
Recorded after the remediation run:
- Desktop managed E2E passed with two discovered tests in 12.2 seconds: the
merge action and the queued-status display scenario.
- Mobile Chrome managed E2E passed with two discovered tests in 9.6 seconds:
the Review merge action with the minimum target-height assertion and the
drawer/Review queue display scenario. Both retained the horizontal-overflow
assertion.
- The fresh-build desktop command was followed by the mobile `--no-build`
command, so both projects exercised the same newly built artifacts.
- Existing queue-status screenshots remain valid for the display scenario;
action coverage is behavioral and does not add capture assets.
+2
View File
@@ -316,6 +316,8 @@ For a task with linked GitHub pull requests, open the PR status control above th
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.
When GitHub puts a linked pull request in a merge queue, the PR status control shows its queue state. It also shows the queue position and estimated merge time when GitHub provides them. The same status appears in the task summary, the mobile PR chip, and Review.
**Your review is requested** matches the GitHub account connected to the task's workspace. The first observation is a quiet baseline. Any later transition to a request for that account wakes the agent, including the first new request after baselining and a re-review request after changes. Clearing a request rearms the next transition. If the workspace's connected GitHub account changes, Kandev quietly rebinds the task and re-establishes every linked PR's baseline; switching accounts does not itself create a prompt.
**PR merged** and **PR closed without merging** are separate subscriptions to the same kind of follow-up: waking the agent when review work ends. Each notifies once when its linked PR enters the selected terminal state. Kandev delivers lifecycle notifications to the task's active promptable session, preferring the primary session. It does not interrupt a busy session: it queues a message for delivery when that session is available. If the task has no promptable session, Kandev records the per-PR delivery error, creates no new session, and retries once a session becomes promptable.
+98 -4
View File
@@ -26,6 +26,22 @@ path.
- A direct merge reports that the pull request merged. An accepted queued merge
reports that the pull request was added to the merge queue and prevents
repeated submission while local PR state refreshes.
- After GitHub reports an active merge queue entry, the linked pull request uses
GitHub's merge-queue color, `#966600`, in task and compact PR indicators. This
color is distinct from the yellow CI-in-progress, green passing, and emerald
ready states.
- The task PR hover summary, compact PR status popover or phone drawer, and PR
detail panel identify the pull request as queued. They translate GitHub's
queue state into user-facing copy instead of displaying the raw provider
enum.
- Queue surfaces show the pull request's current position in the merge queue.
They also show GitHub's estimated time to merge when GitHub supplies one,
formatted as a localized duration rather than raw seconds. Estimates below
one minute use a localized sub-minute label; larger estimates round up to the
next whole minute.
- Queue membership takes precedence over other non-terminal icon colors while
the pull request remains in the queue. Merged and closed states retain their
existing terminal colors.
- The action remains unavailable for drafts, conflicts, changes requested,
failed or incomplete required checks, and unmet required reviews.
- GitHub remains authoritative for final eligibility. A rejected request leaves
@@ -33,7 +49,30 @@ path.
request merged or entered the queue.
- Desktop and mobile use the existing PR detail behavior. On phones, the action
remains available through the full-height Review surface with a touch-sized
target and no horizontal document overflow.
target and no horizontal document overflow. Queue status is also available
through that Review surface and the existing PR status drawer, so it never
depends on hover.
## Data Model
The linked pull request stores the last successfully observed merge queue
entry in `github_task_prs`:
- `merge_queue_state TEXT NOT NULL DEFAULT ''` stores the normalized GitHub
`MergeQueueEntryState`. Supported values are `queued`, `awaiting_checks`,
`mergeable`, `unmergeable`, and `locked`.
- `merge_queue_position INTEGER NULL` stores GitHub's one-based queue position.
- `merge_queue_estimated_time_to_merge_seconds INTEGER NULL` stores GitHub's
current estimate as a non-negative duration in seconds.
An empty state with null metadata means no active queue entry is stored.
Existing rows start in that state and converge on their next successful
GraphQL status sync.
The queue fields are part of the existing `TaskPR` HTTP, boot, and WebSocket
payloads. The bounded task-status projection reduces a queued open pull request
to the aggregate state `queued` so task rows can retain the queue color before
the full task PR collection hydrates.
## API Surface
@@ -62,6 +101,29 @@ Content-Type: application/json
- Only `enqueued` maps to `queued`. An already-merged pull request maps to
`merged`, while `failed` remains an error that the user can retry.
Queue status reuses the existing GitHub status synchronization contract. The
batched GraphQL pull-request selection reads
`mergeQueueEntry { state position estimatedTimeToMerge }`; it does not add an
endpoint or a poller. `position` is a one-based integer.
`estimatedTimeToMerge` is an optional duration in seconds, not a timestamp. A
status result records whether queue membership was actually observed so REST
and `gh pr view` reads, which do not include `mergeQueueEntry`, cannot clear a
valid stored queue entry.
## State Machine
- An open pull request with no `mergeQueueEntry` is not queued.
- A successful GraphQL observation of `mergeQueueEntry` atomically enters or
updates its state, position, and optional estimate, then publishes the normal
task-PR update.
- A later successful GraphQL observation with `mergeQueueEntry: null` leaves
the queue and clears the stored state, position, estimate, and queued UI.
- A merged or closed pull request clears queue state and renders its existing
terminal status even if a less capable read path did not observe the queue
entry disappear.
- A failed or queue-unaware status read preserves the complete last stored
queue entry.
## Permissions
The action uses the active workspace's personal-write GitHub routing and
@@ -79,6 +141,20 @@ merge API. Kandev does not bypass repository rules or elevate the user.
- After an accepted request, Kandev invalidates cached PR feedback/status and
refreshes the linked pull request; the GitHub poller remains authoritative
for its eventual merged state.
- A failed GraphQL queue-status read preserves the previous queue state and
leaves the normal refresh affordance available. Kandev does not interpret a
missing field from a queue-unaware read as removal from the queue.
- An unknown future non-empty queue state still identifies the pull request as
queued with generic copy; Kandev does not expose the raw enum value.
- If GitHub omits the estimated time to merge, Kandev still shows queue state
and position without an empty or invented estimate.
## Persistence Guarantees
The last observed queue state, position, and estimate survive a Kandev restart
with the linked task PR. They can be temporarily stale until the next
successful GitHub status sync. Kandev labels the time as an estimate and does
not convert the duration to a durable predicted timestamp.
## Scenarios
@@ -92,6 +168,23 @@ merge API. Kandev does not bypass repository rules or elevate the user.
- **GIVEN** a PR already in the merge queue, **WHEN** the merge request is
repeated, **THEN** Kandev treats GitHub's idempotent response as queued and
does not report a failure.
- **GIVEN** a linked open PR with an active GitHub merge queue entry, **WHEN**
Kandev completes a status sync, **THEN** its task and compact PR indicators
use the dedicated queue color and its hover, drawer, popover, and detail
surfaces describe the queue state, position, and available merge estimate.
- **GIVEN** GitHub reports an active queue entry without an estimated time to
merge, **WHEN** a queue surface renders, **THEN** it shows queue state and
position and omits the estimate without placeholder or fallback data.
- **GIVEN** a linked PR with a stored queue state, **WHEN** a REST or `gh pr
view` feedback refresh completes without queue data, **THEN** the stored
queue state, position, estimate, and queued UI remain unchanged.
- **GIVEN** a linked queued PR is removed from the queue while remaining open,
**WHEN** a later GraphQL status sync observes no merge queue entry, **THEN**
Kandev clears the queued UI and resumes the normal review, CI, and merge
status color.
- **GIVEN** a linked queued PR reaches a merged or closed state, **WHEN** any
authoritative lifecycle sync completes, **THEN** the terminal state replaces
the queued presentation.
- **GIVEN** a draft, conflicted PR, failed checks, changes requested, or missing
required approvals, **WHEN** the PR surface renders, **THEN** no merge or
queue action is available.
@@ -105,13 +198,14 @@ merge API. Kandev does not bypass repository rules or elevate the user.
## Out of Scope
- Displaying queue position, estimated merge time, or the full merge queue.
- Displaying or navigating the full merge queue.
- Removing a pull request from the merge queue.
- Selecting between direct merge and merge queue when GitHub policy permits
both; GitHub's `default` behavior remains authoritative.
- Changing Kandev's independent CI auto-merge automation setting.
- GitLab merge-request behavior.
## Implementation Plan
## Implementation Plans
[Implementation plan](../../plans/github-pr-merge-queue/plan.md)
- [Queue-status visibility plan](../../plans/github-pr-merge-queue-status/plan.md)
- [Original queue-aware merge action plan](../../plans/github-pr-merge-queue/plan.md)