fix(github): reliable PR-task association across all launch paths (#485)

* fix(github): reliable PR-task association across all launch paths

Three bugs caused inconsistent PR detection for agent-opened PRs:
- StartCreatedSession never called ensureSessionPRWatch
- Push detection bailed out when a pr_number=0 watch existed
- PR watch branch was never updated after agent branch switches

* fix: extract searchPRForExistingWatch to reduce nesting depth

* fix: address review feedback and fix e2e test timeouts

- Fix UNIQUE constraint error when associatePRFromPush was called with
  an existing watch (update pr_number instead of creating new watch)
- Add UpdatePRWatchPRNumber to GitHubService interface
- Fix e2e test timeouts: increase budget to 180s, remove unnecessary
  clickTab("Changes"), replace 35s hard wait with polling assertion

* fix(e2e): accept both /t/ and /s/ URL patterns in PR detection tests

Task cards in the Done column navigate to /t/<task-id> (task view),
not /s/<session-id> (session view). The toHaveURL assertion must
accept both URL patterns.
This commit is contained in:
José Almeida
2026-03-29 20:32:18 +01:00
committed by GitHub
parent 3a71ae2fe6
commit f479393928
6 changed files with 473 additions and 12 deletions
+10
View File
@@ -203,6 +203,16 @@ func (s *Service) DeletePRWatch(ctx context.Context, id string) error {
return s.store.DeletePRWatch(ctx, id)
}
// UpdatePRWatchBranch updates a PR watch's branch (e.g. after the agent switches branches).
func (s *Service) UpdatePRWatchBranch(ctx context.Context, id, branch string) error {
return s.store.UpdatePRWatchBranch(ctx, id, branch)
}
// UpdatePRWatchPRNumber updates a PR watch's PR number after discovery.
func (s *Service) UpdatePRWatchPRNumber(ctx context.Context, id string, prNumber int) error {
return s.store.UpdatePRWatchPRNumber(ctx, id, prNumber)
}
// CheckPRWatch fetches latest feedback for a PR watch and determines if there are changes.
func (s *Service) CheckPRWatch(ctx context.Context, watch *PRWatch) (*PRFeedback, bool, error) {
if s.client == nil {
+8
View File
@@ -164,6 +164,14 @@ func (s *Store) UpdatePRWatchPRNumber(ctx context.Context, id string, prNumber i
return err
}
// UpdatePRWatchBranch updates a PR watch's branch after the agent switches branches.
func (s *Store) UpdatePRWatchBranch(ctx context.Context, id, branch string) error {
_, err := s.db.ExecContext(ctx,
`UPDATE github_pr_watches SET branch = ?, updated_at = ? WHERE id = ?`,
branch, time.Now().UTC(), id)
return err
}
// --- TaskPR operations ---
// CreateTaskPR associates a PR with a task.
@@ -24,6 +24,8 @@ type GitHubService interface {
CreatePRWatch(ctx context.Context, sessionID, taskID, owner, repo string, prNumber int, branch string) (*github.PRWatch, error)
EnsurePRWatch(ctx context.Context, sessionID, taskID, owner, repo, branch string) (*github.PRWatch, error)
GetPRWatchBySession(ctx context.Context, sessionID string) (*github.PRWatch, error)
UpdatePRWatchBranch(ctx context.Context, id, branch string) error
UpdatePRWatchPRNumber(ctx context.Context, id string, prNumber int) error
AssociatePRWithTask(ctx context.Context, taskID string, pr *github.PR) (*github.TaskPR, error)
GetTaskPR(ctx context.Context, taskID string) (*github.TaskPR, error)
RecordReviewPRTask(ctx context.Context, watchID, repoOwner, repoName string, prNumber int, prURL, taskID string) error
@@ -279,10 +281,18 @@ func (s *Service) detectPushAndAssociatePR(
return
}
// Check if we already have a watch for this session
// Check if we already have a watch for this session.
// If the watch already has a PR number, the PR was found — nothing to do.
// If the watch has pr_number=0, it's still searching — do an immediate
// search (faster than waiting for the 1-minute poller) and update the
// watch branch if the agent pushed from a different branch.
existing, err := s.githubService.GetPRWatchBySession(ctx, sessionID)
if err == nil && existing != nil {
return // already watching
if existing.PRNumber > 0 {
return // PR already found and being monitored
}
s.searchPRForExistingWatch(ctx, client, existing, sessionID, taskID, branch)
return
}
owner, repoName := s.resolveSessionRepo(ctx, sessionID)
@@ -317,6 +327,47 @@ func (s *Service) detectPushAndAssociatePR(
}
}
// searchPRForExistingWatch handles the case where a PR watch exists with pr_number=0
// (still searching). It updates the watch branch if the agent pushed from a different
// branch, then does a single immediate search so we don't wait for the 1-minute poller.
func (s *Service) searchPRForExistingWatch(
ctx context.Context, client github.Client, watch *github.PRWatch,
sessionID, taskID, branch string,
) {
// Update branch if the agent switched branches since the watch was created.
if watch.Branch != branch {
if err := s.githubService.UpdatePRWatchBranch(ctx, watch.ID, branch); err != nil {
s.logger.Warn("failed to update PR watch branch",
zap.String("watch_id", watch.ID),
zap.String("old_branch", watch.Branch),
zap.String("new_branch", branch),
zap.Error(err))
}
}
// Immediate search — if found, update the existing watch and associate.
// We must not call associatePRFromPush here because it calls CreatePRWatch,
// which would fail with a UNIQUE constraint since the watch already exists.
foundPR, findErr := client.FindPRByBranch(ctx, watch.Owner, watch.Repo, branch)
if findErr == nil && foundPR != nil {
if err := s.githubService.UpdatePRWatchPRNumber(ctx, watch.ID, foundPR.Number); err != nil {
s.logger.Warn("failed to update PR watch number",
zap.String("watch_id", watch.ID),
zap.Int("pr_number", foundPR.Number),
zap.Error(err))
}
if _, err := s.githubService.AssociatePRWithTask(ctx, taskID, foundPR); err != nil {
s.logger.Error("failed to associate PR with task",
zap.String("task_id", taskID),
zap.Int("pr_number", foundPR.Number),
zap.Error(err))
}
s.logger.Info("auto-detected PR from push (existing watch)",
zap.String("session_id", sessionID),
zap.Int("pr_number", foundPR.Number),
zap.String("branch", branch))
}
}
// resolveSessionRepo looks up the repository owner and name for a session.
// If provider info is missing but a local path exists, it detects from the git remote
// and backfills the DB record for future calls.
@@ -9,16 +9,21 @@ import (
"github.com/kandev/kandev/internal/task/models"
)
// mockGitHubService implements GitHubService for testing CheckSessionPR.
// mockGitHubService implements GitHubService for testing.
type mockGitHubService struct {
client github.Client
taskPR *github.TaskPR
taskPRErr error
ensureWatchCalls int
createWatchCalls int
associateCalls int
ensureWatchBranch string
createWatchBranch string
client github.Client
taskPR *github.TaskPR
taskPRErr error
prWatch *github.PRWatch // returned by GetPRWatchBySession (nil = no watch)
ensureWatchCalls int
createWatchCalls int
associateCalls int
updateBranchCalls int
updatePRNumberCalls int
ensureWatchBranch string
createWatchBranch string
updatedBranch string
updatedPRNumber int
}
func (m *mockGitHubService) Client() github.Client { return m.client }
@@ -31,7 +36,7 @@ func (m *mockGitHubService) EnsurePRWatch(_ context.Context, _, _, _, _, branch
return &github.PRWatch{}, nil
}
func (m *mockGitHubService) GetPRWatchBySession(_ context.Context, _ string) (*github.PRWatch, error) {
return nil, nil
return m.prWatch, nil
}
func (m *mockGitHubService) CreatePRWatch(_ context.Context, _, _, _, _ string, _ int, branch string) (*github.PRWatch, error) {
m.createWatchCalls++
@@ -42,6 +47,16 @@ func (m *mockGitHubService) AssociatePRWithTask(_ context.Context, _ string, _ *
m.associateCalls++
return &github.TaskPR{}, nil
}
func (m *mockGitHubService) UpdatePRWatchBranch(_ context.Context, _, branch string) error {
m.updateBranchCalls++
m.updatedBranch = branch
return nil
}
func (m *mockGitHubService) UpdatePRWatchPRNumber(_ context.Context, _ string, prNumber int) error {
m.updatePRNumberCalls++
m.updatedPRNumber = prNumber
return nil
}
func (m *mockGitHubService) RecordReviewPRTask(context.Context, string, string, string, int, string, string) error {
return nil
}
@@ -318,3 +333,164 @@ func TestCheckSessionPR(t *testing.T) {
}
})
}
// TestDetectPushAndAssociatePR tests the push detection flow for PR association.
func TestDetectPushAndAssociatePR(t *testing.T) {
ctx := context.Background()
now := time.Now().UTC()
testPR := &github.PR{
Number: 10,
Title: "Test PR",
HTMLURL: "https://github.com/myorg/myrepo/pull/10",
AuthorLogin: "alice",
RepoOwner: "myorg",
RepoName: "myrepo",
HeadBranch: "feature-branch",
BaseBranch: "main",
}
// seedSessionWithRepo creates a session linked to a GitHub repository
// for testing detectPushAndAssociatePR which uses resolveSessionRepo.
seedSessionWithRepo := func(t *testing.T) *Service {
t.Helper()
repo := setupTestRepo(t)
seedSession(t, repo, "t1", "s1", "step1")
repoObj := &models.Repository{
ID: "repo1", WorkspaceID: "ws1", Name: "myrepo",
SourceType: "provider", Provider: "github",
ProviderOwner: "myorg", ProviderName: "myrepo",
CreatedAt: now, UpdatedAt: now,
}
if err := repo.CreateRepository(ctx, repoObj); err != nil {
t.Fatalf("failed to create repository: %v", err)
}
session, _ := repo.GetTaskSession(ctx, "s1")
session.RepositoryID = "repo1"
if err := repo.UpdateTaskSession(ctx, session); err != nil {
t.Fatalf("failed to update session: %v", err)
}
return createTestService(repo, newMockStepGetter(), newMockTaskRepo())
}
t.Run("searches and finds PR when no watch exists", func(t *testing.T) {
svc := seedSessionWithRepo(t)
mockClient := github.NewMockClient()
mockClient.AddPR(testPR)
ghSvc := &mockGitHubService{client: mockClient}
svc.SetGitHubService(ghSvc)
svc.detectPushAndAssociatePR(ctx, "s1", "t1", "feature-branch")
if ghSvc.associateCalls != 1 {
t.Errorf("expected 1 AssociatePRWithTask call, got %d", ghSvc.associateCalls)
}
if ghSvc.createWatchCalls != 1 {
t.Errorf("expected 1 CreatePRWatch call, got %d", ghSvc.createWatchCalls)
}
})
t.Run("skips when watch has pr_number > 0", func(t *testing.T) {
svc := seedSessionWithRepo(t)
ghSvc := &mockGitHubService{
prWatch: &github.PRWatch{
ID: "w1", SessionID: "s1", TaskID: "t1",
Owner: "myorg", Repo: "myrepo",
PRNumber: 10, Branch: "feature-branch",
},
}
svc.SetGitHubService(ghSvc)
svc.detectPushAndAssociatePR(ctx, "s1", "t1", "feature-branch")
if ghSvc.associateCalls != 0 {
t.Errorf("expected no AssociatePRWithTask calls when PR already found, got %d", ghSvc.associateCalls)
}
})
t.Run("searches immediately when watch has pr_number=0", func(t *testing.T) {
svc := seedSessionWithRepo(t)
mockClient := github.NewMockClient()
mockClient.AddPR(testPR)
ghSvc := &mockGitHubService{
client: mockClient,
prWatch: &github.PRWatch{
ID: "w1", SessionID: "s1", TaskID: "t1",
Owner: "myorg", Repo: "myrepo",
PRNumber: 0, Branch: "feature-branch",
},
}
svc.SetGitHubService(ghSvc)
svc.detectPushAndAssociatePR(ctx, "s1", "t1", "feature-branch")
if ghSvc.associateCalls != 1 {
t.Errorf("expected 1 AssociatePRWithTask call when pr_number=0, got %d", ghSvc.associateCalls)
}
// Should update existing watch's PR number, not create a new watch
if ghSvc.updatePRNumberCalls != 1 {
t.Errorf("expected 1 UpdatePRWatchPRNumber call, got %d", ghSvc.updatePRNumberCalls)
}
if ghSvc.createWatchCalls != 0 {
t.Errorf("expected no CreatePRWatch calls (watch already exists), got %d", ghSvc.createWatchCalls)
}
})
t.Run("updates watch branch when agent pushes from different branch", func(t *testing.T) {
svc := seedSessionWithRepo(t)
mockClient := github.NewMockClient()
// PR is on the NEW branch, not the old one
prOnNewBranch := &github.PR{
Number: 10, Title: "Test PR",
HTMLURL: "https://github.com/myorg/myrepo/pull/10",
AuthorLogin: "alice", RepoOwner: "myorg", RepoName: "myrepo",
HeadBranch: "new-branch", BaseBranch: "main",
}
mockClient.AddPR(prOnNewBranch)
ghSvc := &mockGitHubService{
client: mockClient,
prWatch: &github.PRWatch{
ID: "w1", SessionID: "s1", TaskID: "t1",
Owner: "myorg", Repo: "myrepo",
PRNumber: 0, Branch: "old-branch", // watch created with original branch
},
}
svc.SetGitHubService(ghSvc)
// Agent pushed from "new-branch" (different from watch's "old-branch")
svc.detectPushAndAssociatePR(ctx, "s1", "t1", "new-branch")
if ghSvc.updateBranchCalls != 1 {
t.Errorf("expected 1 UpdatePRWatchBranch call, got %d", ghSvc.updateBranchCalls)
}
if ghSvc.updatedBranch != "new-branch" {
t.Errorf("expected updated branch %q, got %q", "new-branch", ghSvc.updatedBranch)
}
if ghSvc.associateCalls != 1 {
t.Errorf("expected 1 AssociatePRWithTask call, got %d", ghSvc.associateCalls)
}
})
t.Run("does not update branch when same as watch", func(t *testing.T) {
svc := seedSessionWithRepo(t)
mockClient := github.NewMockClient()
ghSvc := &mockGitHubService{
client: mockClient,
prWatch: &github.PRWatch{
ID: "w1", SessionID: "s1", TaskID: "t1",
Owner: "myorg", Repo: "myrepo",
PRNumber: 0, Branch: "feature-branch",
},
}
svc.SetGitHubService(ghSvc)
svc.detectPushAndAssociatePR(ctx, "s1", "t1", "feature-branch")
if ghSvc.updateBranchCalls != 0 {
t.Errorf("expected no UpdatePRWatchBranch calls when branch matches, got %d", ghSvc.updateBranchCalls)
}
})
}
@@ -308,6 +308,13 @@ func (s *Service) StartCreatedSession(ctx context.Context, taskID, sessionID, ag
// and event handlers (handleAgentReady) transition it to WAITING_FOR_INPUT.
s.postLaunchCreated(ctx, taskID, sessionID, effectivePrompt, skipMessageRecord, planModeActive, attachments)
// Ensure a PR watch exists so the poller can detect PRs created by the agent.
// PrepareTaskSession may have already created one, but if that goroutine failed
// or hadn't completed, this guarantees coverage.
if execution.WorktreeBranch != "" {
go s.ensureSessionPRWatch(context.Background(), taskID, execution.SessionID, execution.WorktreeBranch)
}
return execution, nil
}
@@ -0,0 +1,209 @@
import path from "node:path";
import { test, expect } from "../fixtures/test-base";
import { KanbanPage } from "../pages/kanban-page";
import { SessionPage } from "../pages/session-page";
/**
* Tests the full PR auto-detection pipeline: the backend detects a PR on
* GitHub (mock) and associates it with the task — without manually calling
* mockGitHubAssociateTaskPR.
*
* Detection flow exercised:
* useTaskPRDetection (frontend, every 30s)
* → github.check_session_pr (WS action)
* → CheckSessionPR (backend)
* → resolveTaskRepo → resolvePRWatchBranch → FindPRByBranch (mock)
* → AssociatePRWithTask → github.task_pr.updated (WS event)
* → PR button appears in topbar
*
* Prerequisites for detection to work:
* - Repository has provider=github with owner/name set
* - TaskRepository has checkout_branch set
* - Mock GitHub has a PR matching the checkout branch
*/
test.describe("PR auto-detection pipeline", () => {
test("detects PR automatically via check_session_pr", async ({
testPage,
apiClient,
seedData,
backend,
}) => {
test.setTimeout(180_000);
// --- Seed workflow: Inbox → Working (auto_start → Done) → Done ---
const workflow = await apiClient.createWorkflow(
seedData.workspaceId,
"PR Auto-Detection Workflow",
);
const inboxStep = await apiClient.createWorkflowStep(workflow.id, "Inbox", 0);
const workingStep = await apiClient.createWorkflowStep(workflow.id, "Working", 1);
const doneStep = await apiClient.createWorkflowStep(workflow.id, "Done", 2);
await apiClient.updateWorkflowStep(workingStep.id, {
prompt: 'e2e:message("done")\n{{task_prompt}}',
events: {
on_enter: [{ type: "auto_start_agent" }],
on_turn_complete: [{ type: "move_to_step", config: { step_id: doneStep.id } }],
},
});
await apiClient.saveUserSettings({
workspace_id: seedData.workspaceId,
workflow_filter_id: workflow.id,
enable_preview_on_click: false,
});
// --- Create repository with GitHub provider info ---
// The detection pipeline needs resolveTaskRepo to return a valid owner/repo,
// which requires provider=github with provider_owner and provider_name set.
const repoDir = path.join(backend.tmpDir, "repos", "e2e-repo");
const githubRepo = await apiClient.createRepository(seedData.workspaceId, repoDir, "main", {
name: "GitHub Test Repo",
provider: "github",
provider_owner: "testorg",
provider_name: "testrepo",
});
// --- Setup mock GitHub ---
await apiClient.mockGitHubReset();
await apiClient.mockGitHubSetUser("test-user");
// --- Create task with checkout_branch set ---
// Using `repositories` (not `repository_ids`) to set checkout_branch,
// which resolvePRWatchBranch uses to determine which branch to search.
const task = await apiClient.createTask(seedData.workspaceId, "Auto-Detect PR Task", {
workflow_id: workflow.id,
workflow_step_id: inboxStep.id,
agent_profile_id: seedData.agentProfileId,
repositories: [
{
repository_id: githubRepo.id,
checkout_branch: "main",
},
],
});
// Navigate to kanban BEFORE moving tasks so the WebSocket is subscribed
// when task.updated events fire.
const kanban = new KanbanPage(testPage);
await kanban.goto();
// Move task to Working → auto_start → mock agent completes → Done
await apiClient.moveTask(task.id, workflow.id, workingStep.id);
await expect(kanban.taskCardInColumn("Auto-Detect PR Task", doneStep.id)).toBeVisible({
timeout: 45_000,
});
// --- Add PR to mock GitHub AFTER task completion ---
// Simulates the agent having created a PR via `gh pr create`.
// The PR's head_branch must match the task's checkout_branch ("main").
await apiClient.mockGitHubAddPRs([
{
number: 99,
title: "Agent-created PR",
state: "open",
head_branch: "main",
base_branch: "develop",
author_login: "test-user",
repo_owner: "testorg",
repo_name: "testrepo",
additions: 30,
deletions: 5,
},
]);
// --- Open the task session ---
// This mounts the ChangesPanelContent which runs useTaskPRDetection.
// The hook calls github.check_session_pr immediately and every 30s.
// The backend's CheckSessionPR resolves the repo (testorg/testrepo)
// and branch ("main"), searches mock GitHub, and associates the PR.
await kanban.taskCardInColumn("Auto-Detect PR Task", doneStep.id).click();
await expect(testPage).toHaveURL(/\/[st]\//, { timeout: 15_000 });
const session = new SessionPage(testPage);
await session.waitForLoad();
// --- Verify PR button appears in topbar ---
// The detection hook fires immediately on mount, then every 30s.
// Allow up to 60s for the check to succeed (accounts for git.branch
// availability delay and the 30s polling interval).
await expect(session.prTopbarButton()).toBeVisible({ timeout: 60_000 });
await expect(session.prTopbarButton()).toContainText("#99");
});
test("does not show PR for tasks without a matching PR", async ({
testPage,
apiClient,
seedData,
backend,
}) => {
test.setTimeout(120_000);
// --- Seed workflow ---
const workflow = await apiClient.createWorkflow(seedData.workspaceId, "PR Negative Workflow");
const inboxStep = await apiClient.createWorkflowStep(workflow.id, "Inbox", 0);
const workingStep = await apiClient.createWorkflowStep(workflow.id, "Working", 1);
const doneStep = await apiClient.createWorkflowStep(workflow.id, "Done", 2);
await apiClient.updateWorkflowStep(workingStep.id, {
prompt: 'e2e:message("done")\n{{task_prompt}}',
events: {
on_enter: [{ type: "auto_start_agent" }],
on_turn_complete: [{ type: "move_to_step", config: { step_id: doneStep.id } }],
},
});
await apiClient.saveUserSettings({
workspace_id: seedData.workspaceId,
workflow_filter_id: workflow.id,
enable_preview_on_click: false,
});
const repoDir = path.join(backend.tmpDir, "repos", "e2e-repo");
const githubRepo = await apiClient.createRepository(seedData.workspaceId, repoDir, "main", {
name: "GitHub No-PR Repo",
provider: "github",
provider_owner: "testorg",
provider_name: "testrepo",
});
await apiClient.mockGitHubReset();
await apiClient.mockGitHubSetUser("test-user");
// No PRs added to mock GitHub — detection should find nothing
const task = await apiClient.createTask(seedData.workspaceId, "No PR Task", {
workflow_id: workflow.id,
workflow_step_id: inboxStep.id,
agent_profile_id: seedData.agentProfileId,
repositories: [
{
repository_id: githubRepo.id,
checkout_branch: "main",
},
],
});
const kanban = new KanbanPage(testPage);
await kanban.goto();
await apiClient.moveTask(task.id, workflow.id, workingStep.id);
await expect(kanban.taskCardInColumn("No PR Task", doneStep.id)).toBeVisible({
timeout: 45_000,
});
// Open the session
await kanban.taskCardInColumn("No PR Task", doneStep.id).click();
await expect(testPage).toHaveURL(/\/[st]\//, { timeout: 15_000 });
const session = new SessionPage(testPage);
await session.waitForLoad();
// The detection hook fires immediately on mount. Give it enough time
// for the check to complete (a few seconds), then verify no PR button.
// We don't need to wait a full 30s polling cycle — the immediate check
// on mount is sufficient to confirm no PR is found.
await expect(session.prTopbarButton()).not.toBeVisible({ timeout: 10_000 });
});
});