feat(workspaces): add repository branch policies (#2997)
This commit is contained in:
@@ -318,6 +318,7 @@ func (b bootStateBuilder) addHomeKanbanRouteState(ctx context.Context, req *http
|
||||
}
|
||||
b.addRepositoriesState(ctx, state, activeWorkspaceID)
|
||||
b.addRepositorySetsState(ctx, state, activeWorkspaceID)
|
||||
b.addRepositoryBranchPoliciesState(ctx, state, activeWorkspaceID)
|
||||
b.addKanbanSnapshotsState(ctx, state, workflows, activeWorkflowID)
|
||||
}
|
||||
|
||||
@@ -393,6 +394,10 @@ func (b bootStateBuilder) addRepositorySetsState(ctx context.Context, state map[
|
||||
state["repositorySets"] = repositorySetsState(workspaceID, items, loaded)
|
||||
}
|
||||
|
||||
func (b bootStateBuilder) addRepositoryBranchPoliciesState(ctx context.Context, state map[string]any, workspaceID string) {
|
||||
b.repositoryBranchPoliciesForState(ctx, workspaceID, state)
|
||||
}
|
||||
|
||||
func (b bootStateBuilder) addQuickChatState(
|
||||
ctx context.Context,
|
||||
req *http.Request,
|
||||
|
||||
@@ -62,7 +62,7 @@ func (b bootStateBuilder) tasksPageBootData(ctx context.Context, req *http.Reque
|
||||
state["userSettings"] = mapUserSettingsState(settings, activeWorkspaceID)
|
||||
}
|
||||
if activeWorkspaceID == "" {
|
||||
return state, map[string]any{"activeWorkspaceId": nil, "workflows": []any{}, "steps": []any{}, "repositories": []any{}, "repositorySets": []any{}, "tasks": []any{}, "total": 0, "tasksListSort": tasksListSort, "tasksListGroup": tasksListGroup}
|
||||
return state, map[string]any{"activeWorkspaceId": nil, "workflows": []any{}, "steps": []any{}, "repositories": []any{}, "repositorySets": []any{}, "repositoryBranchPolicies": []any{}, "tasks": []any{}, "total": 0, "tasksListSort": tasksListSort, "tasksListGroup": tasksListGroup}
|
||||
}
|
||||
workflows, err := b.p.taskSvc.ListWorkflows(ctx, activeWorkspaceID, false)
|
||||
if err != nil {
|
||||
@@ -77,18 +77,20 @@ func (b bootStateBuilder) tasksPageBootData(ctx context.Context, req *http.Reque
|
||||
}
|
||||
repositories := b.repositoriesForState(ctx, activeWorkspaceID, state)
|
||||
repositorySets := b.repositorySetsForState(ctx, activeWorkspaceID, state)
|
||||
repositoryBranchPolicies := b.repositoryBranchPoliciesForState(ctx, activeWorkspaceID, state)
|
||||
steps := b.workflowStepsForWorkspace(ctx, activeWorkspaceID)
|
||||
tasks, total := b.tasksForWorkspace(ctx, activeWorkspaceID, activeWorkflowID, settingsRepositoryID, tasksListSort)
|
||||
routeData := map[string]any{
|
||||
"activeWorkspaceId": activeWorkspaceID,
|
||||
"workflows": workflowsToDTOs(workflows),
|
||||
"steps": steps,
|
||||
"repositories": repositories,
|
||||
"repositorySets": repositorySets,
|
||||
"tasks": tasks,
|
||||
"total": total,
|
||||
"tasksListSort": tasksListSort,
|
||||
"tasksListGroup": tasksListGroup,
|
||||
"activeWorkspaceId": activeWorkspaceID,
|
||||
"workflows": workflowsToDTOs(workflows),
|
||||
"steps": steps,
|
||||
"repositories": repositories,
|
||||
"repositorySets": repositorySets,
|
||||
"repositoryBranchPolicies": repositoryBranchPolicies,
|
||||
"tasks": tasks,
|
||||
"total": total,
|
||||
"tasksListSort": tasksListSort,
|
||||
"tasksListGroup": tasksListGroup,
|
||||
}
|
||||
return state, routeData
|
||||
}
|
||||
@@ -128,7 +130,7 @@ func (b bootStateBuilder) routeContextBootData(ctx context.Context, req *http.Re
|
||||
state["userSettings"] = mapUserSettingsState(settings, activeWorkspaceID)
|
||||
}
|
||||
if activeWorkspaceID == "" {
|
||||
return state, map[string]any{"activeWorkspaceId": nil, "workflows": []any{}, "steps": []any{}, "repositories": []any{}, "repositorySets": []any{}}
|
||||
return state, map[string]any{"activeWorkspaceId": nil, "workflows": []any{}, "steps": []any{}, "repositories": []any{}, "repositorySets": []any{}, "repositoryBranchPolicies": []any{}}
|
||||
}
|
||||
workflows, err := b.p.taskSvc.ListWorkflows(ctx, activeWorkspaceID, false)
|
||||
if err != nil {
|
||||
@@ -145,13 +147,15 @@ func (b bootStateBuilder) routeContextBootData(ctx context.Context, req *http.Re
|
||||
}
|
||||
repositories := b.repositoriesForState(ctx, activeWorkspaceID, state)
|
||||
repositorySets := b.repositorySetsForState(ctx, activeWorkspaceID, state)
|
||||
repositoryBranchPolicies := b.repositoryBranchPoliciesForState(ctx, activeWorkspaceID, state)
|
||||
steps := b.workflowStepsForWorkspace(ctx, activeWorkspaceID)
|
||||
return state, map[string]any{
|
||||
"activeWorkspaceId": activeWorkspaceID,
|
||||
"workflows": workflowsToDTOs(workflows),
|
||||
"steps": steps,
|
||||
"repositories": repositories,
|
||||
"repositorySets": repositorySets,
|
||||
"activeWorkspaceId": activeWorkspaceID,
|
||||
"workflows": workflowsToDTOs(workflows),
|
||||
"steps": steps,
|
||||
"repositories": repositories,
|
||||
"repositorySets": repositorySets,
|
||||
"repositoryBranchPolicies": repositoryBranchPolicies,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -244,6 +248,64 @@ func (b bootStateBuilder) repositorySetsForState(
|
||||
return items
|
||||
}
|
||||
|
||||
// repositoryBranchPoliciesForState hydrates the repository-keyed policy slice
|
||||
// used by repository settings and the task-create picker.
|
||||
func (b bootStateBuilder) repositoryBranchPoliciesForState(
|
||||
ctx context.Context,
|
||||
workspaceID string,
|
||||
state map[string]any,
|
||||
) []taskdto.RepositoryBranchPolicyDTO {
|
||||
itemsByRepositoryID := map[string]any{}
|
||||
loadingByRepositoryID := map[string]any{}
|
||||
loadedByRepositoryID := map[string]any{}
|
||||
items := make([]taskdto.RepositoryBranchPolicyDTO, 0)
|
||||
repositories, err := b.p.taskSvc.ListRepositories(ctx, workspaceID)
|
||||
if err != nil {
|
||||
b.logBootError("list repositories for branch policies", err)
|
||||
state["repositoryBranchPolicies"] = map[string]any{
|
||||
"itemsByRepositoryId": itemsByRepositoryID,
|
||||
"loadingByRepositoryId": loadingByRepositoryID,
|
||||
"loadedByRepositoryId": loadedByRepositoryID,
|
||||
}
|
||||
return items
|
||||
}
|
||||
policies, err := b.p.taskSvc.ListRepositoryBranchPoliciesForWorkspace(ctx, workspaceID)
|
||||
if err != nil {
|
||||
b.logBootError("list repository branch policies", err)
|
||||
for _, repository := range repositories {
|
||||
if repository == nil {
|
||||
continue
|
||||
}
|
||||
itemsByRepositoryID[repository.ID] = []taskdto.RepositoryBranchPolicyDTO{}
|
||||
loadedByRepositoryID[repository.ID] = false
|
||||
loadingByRepositoryID[repository.ID] = false
|
||||
}
|
||||
} else {
|
||||
policiesByRepositoryID := make(map[string][]*taskmodels.RepositoryBranchPolicy)
|
||||
for _, policy := range policies {
|
||||
if policy != nil {
|
||||
policiesByRepositoryID[policy.RepositoryID] = append(policiesByRepositoryID[policy.RepositoryID], policy)
|
||||
}
|
||||
}
|
||||
for _, repository := range repositories {
|
||||
if repository == nil {
|
||||
continue
|
||||
}
|
||||
dtos := repositoryBranchPoliciesToDTOs(policiesByRepositoryID[repository.ID])
|
||||
itemsByRepositoryID[repository.ID] = dtos
|
||||
loadedByRepositoryID[repository.ID] = true
|
||||
loadingByRepositoryID[repository.ID] = false
|
||||
items = append(items, dtos...)
|
||||
}
|
||||
}
|
||||
state["repositoryBranchPolicies"] = map[string]any{
|
||||
"itemsByRepositoryId": itemsByRepositoryID,
|
||||
"loadingByRepositoryId": loadingByRepositoryID,
|
||||
"loadedByRepositoryId": loadedByRepositoryID,
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
// repositorySetsState is the workspace-keyed slice shape the web store expects.
|
||||
// An empty workspace still keys an entry: an absent key reads as "not loaded" to
|
||||
// the client hook, which then refetches on every dialog open.
|
||||
@@ -270,6 +332,16 @@ func repositorySetsToDTOs(sets []*taskmodels.RepositorySet) []taskdto.Repository
|
||||
return items
|
||||
}
|
||||
|
||||
func repositoryBranchPoliciesToDTOs(policies []*taskmodels.RepositoryBranchPolicy) []taskdto.RepositoryBranchPolicyDTO {
|
||||
items := make([]taskdto.RepositoryBranchPolicyDTO, 0, len(policies))
|
||||
for _, policy := range policies {
|
||||
if policy != nil {
|
||||
items = append(items, taskdto.FromRepositoryBranchPolicy(policy))
|
||||
}
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
// repositoriesToDTOs maps repository models to DTOs.
|
||||
func repositoriesToDTOs(repositories []*taskmodels.Repository) []taskdto.RepositoryDTO {
|
||||
items := make([]taskdto.RepositoryDTO, 0, len(repositories))
|
||||
|
||||
@@ -169,7 +169,7 @@ func (b *branchMaterializer) prepareMaterializeRequest(
|
||||
FallbackBaseBranch: repo.DefaultBranch,
|
||||
CheckoutBranch: tr.CheckoutBranch,
|
||||
WorktreeBranchPrefix: repo.WorktreeBranchPrefix,
|
||||
WorktreeBranchTemplate: repo.WorktreeBranchTemplate,
|
||||
WorktreeBranchTemplate: taskRepositoryBranchTemplate(repo, tr),
|
||||
WorktreeBranchTicket: worktree.TicketForBranchName(task.Identifier, task.Metadata),
|
||||
PullBeforeWorktree: repo.PullBeforeWorktree,
|
||||
TaskDirName: env.TaskDirName,
|
||||
@@ -179,6 +179,16 @@ func (b *branchMaterializer) prepareMaterializeRequest(
|
||||
return req, env, session, slug, true, nil
|
||||
}
|
||||
|
||||
func taskRepositoryBranchTemplate(repo *models.Repository, taskRepo *models.TaskRepository) string {
|
||||
if taskRepo != nil && taskRepo.BranchPolicyBranchTemplate != "" {
|
||||
return taskRepo.BranchPolicyBranchTemplate
|
||||
}
|
||||
if repo == nil {
|
||||
return ""
|
||||
}
|
||||
return repo.WorktreeBranchTemplate
|
||||
}
|
||||
|
||||
// finalizeMaterialize handles the post-Create plumbing: promote the task
|
||||
// environment's workspace_path to the task root when the new worktree is a
|
||||
// sibling, ping the running agentctl to add per-repo trackers, and emit a
|
||||
|
||||
@@ -202,6 +202,18 @@ func TestBranchMaterializer_SecondBranchKeepsTaskRootPromoted(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskRepositoryBranchTemplatePrefersPolicySnapshot(t *testing.T) {
|
||||
repo := &models.Repository{WorktreeBranchTemplate: "feature/{title}"}
|
||||
legacy := &models.TaskRepository{}
|
||||
if got := taskRepositoryBranchTemplate(repo, legacy); got != "feature/{title}" {
|
||||
t.Fatalf("legacy template = %q, want repository fallback", got)
|
||||
}
|
||||
policy := &models.TaskRepository{BranchPolicyBranchTemplate: "bugfix/{title}-{suffix}"}
|
||||
if got := taskRepositoryBranchTemplate(repo, policy); got != "bugfix/{title}-{suffix}" {
|
||||
t.Fatalf("policy template = %q, want snapshot template", got)
|
||||
}
|
||||
}
|
||||
|
||||
// setupMaterializerScenario creates a bare origin repo + a clone that
|
||||
// serves as the "primary" worktree at <task-root>/kandev/. Returns the
|
||||
// repository path, the task root, and the primary worktree path.
|
||||
|
||||
@@ -1146,6 +1146,7 @@ func registerTaskRoutes(p routeParams, planService *taskservice.PlanService, han
|
||||
}
|
||||
taskhandlers.RegisterRepositoryRoutes(p.router, p.gateway.Dispatcher, p.taskSvc, p.log)
|
||||
taskhandlers.RegisterRepositorySetRoutes(p.router, p.gateway.Dispatcher, p.taskSvc, p.log)
|
||||
taskhandlers.RegisterRepositoryBranchPolicyRoutes(p.router, p.gateway.Dispatcher, p.taskSvc, p.log)
|
||||
taskhandlers.RegisterExecutorRoutes(p.router, p.gateway.Dispatcher, p.taskSvc, p.log)
|
||||
taskhandlers.RegisterExecutorProfileRoutes(p.router, p.gateway.Dispatcher, p.taskSvc, p.agentList, p.log)
|
||||
taskhandlers.RegisterEnvironmentRoutes(p.router, p.gateway.Dispatcher, p.taskSvc, p.log)
|
||||
|
||||
@@ -135,6 +135,7 @@ func provideServices(cfg *config.Config, log *logger.Logger, repos *Repositories
|
||||
GitSnapshots: repos.Task,
|
||||
RepoEntities: repos.Task,
|
||||
RepositorySets: repos.Task,
|
||||
BranchPolicies: repos.Task,
|
||||
RepositoryCleanup: repos.Task,
|
||||
Executors: repos.Task,
|
||||
Environments: repos.Task,
|
||||
|
||||
@@ -140,6 +140,13 @@ const (
|
||||
RepositorySetDeleted = "repository_set.deleted"
|
||||
)
|
||||
|
||||
// Event types for repository branch policies.
|
||||
const (
|
||||
RepositoryBranchPolicyCreated = "repository_branch_policy.created"
|
||||
RepositoryBranchPolicyUpdated = "repository_branch_policy.updated"
|
||||
RepositoryBranchPolicyDeleted = "repository_branch_policy.deleted"
|
||||
)
|
||||
|
||||
// Event types for repository scripts
|
||||
const (
|
||||
RepositoryScriptCreated = "repository.script.created"
|
||||
|
||||
@@ -63,6 +63,9 @@ func RegisterTaskNotifications(ctx context.Context, eventBus bus.EventBus, hub *
|
||||
b.subscribe(eventBus, events.RepositorySetCreated, ws.ActionRepositorySetCreated)
|
||||
b.subscribe(eventBus, events.RepositorySetUpdated, ws.ActionRepositorySetUpdated)
|
||||
b.subscribe(eventBus, events.RepositorySetDeleted, ws.ActionRepositorySetDeleted)
|
||||
b.subscribe(eventBus, events.RepositoryBranchPolicyCreated, ws.ActionRepositoryBranchPolicyCreated)
|
||||
b.subscribe(eventBus, events.RepositoryBranchPolicyUpdated, ws.ActionRepositoryBranchPolicyUpdated)
|
||||
b.subscribe(eventBus, events.RepositoryBranchPolicyDeleted, ws.ActionRepositoryBranchPolicyDeleted)
|
||||
b.subscribe(eventBus, events.RepositoryScriptCreated, ws.ActionRepositoryScriptCreated)
|
||||
b.subscribe(eventBus, events.RepositoryScriptUpdated, ws.ActionRepositoryScriptUpdated)
|
||||
b.subscribe(eventBus, events.RepositoryScriptDeleted, ws.ActionRepositoryScriptDeleted)
|
||||
|
||||
@@ -111,7 +111,7 @@ func TestTaskEventBroadcaster_NoDuplicateSubscriptions(t *testing.T) {
|
||||
//
|
||||
// Update this number when adding or removing event subscriptions in
|
||||
// RegisterTaskNotifications — it is intentionally exact.
|
||||
const wantSubscriptions = 67
|
||||
const wantSubscriptions = 70
|
||||
if got := len(b.subscriptions); got != wantSubscriptions {
|
||||
t.Errorf("RegisterTaskNotifications created %d subscriptions, want %d — "+
|
||||
"did an event get subscribed twice?", got, wantSubscriptions)
|
||||
|
||||
@@ -3049,21 +3049,30 @@ func (s *Service) autoStartStepPrompt(
|
||||
return contextErr
|
||||
}
|
||||
}
|
||||
var pullRequestTargetContext string
|
||||
if needsRuntimeContext {
|
||||
recordedPrompt, pullRequestTargetContext = s.addTaskPullRequestTargetContext(
|
||||
ctx, taskID, recordedPrompt, session.IsPassthrough,
|
||||
)
|
||||
}
|
||||
if (session.State == models.TaskSessionStateCreated || step.HasOnEnterAction(wfmodels.OnEnterResetAgentContext)) && !session.IsPassthrough && (agentPrompt != "" || len(attachments) > 0) {
|
||||
configMode, _ := session.Metadata["config_mode"].(bool)
|
||||
requiresSignal := step != nil && step.AutoAdvanceRequiresSignal
|
||||
referenceContext := EntityReferenceContext(references)
|
||||
if isOfficeTask {
|
||||
recordedPrompt = sysprompt.InjectOfficeContextWithOptions(taskID, sessionID, agentPrompt, requiresSignal, referenceContext)
|
||||
recordedPrompt = sysprompt.InjectOfficeContextWithOptions(
|
||||
taskID, sessionID, recordedPrompt, requiresSignal,
|
||||
referenceContext, pullRequestTargetContext,
|
||||
)
|
||||
} else {
|
||||
recordedPrompt = sysprompt.InjectKandevContextWithOptions(taskID, sessionID, agentPrompt, sysprompt.KandevContextOptions{
|
||||
recordedPrompt = sysprompt.InjectKandevContextWithOptions(taskID, sessionID, recordedPrompt, sysprompt.KandevContextOptions{
|
||||
RequiresCompletionSignal: requiresSignal,
|
||||
IncludeCoordinatorTaskControls: !configMode,
|
||||
IncludeTaskTitleTool: !configMode && titleOwner,
|
||||
Autopilot: taskForPrompt != nil && taskForPrompt.Autopilot,
|
||||
IncludeUserQuestionTool: taskForPrompt == nil || !taskForPrompt.Autopilot,
|
||||
IncludeParentQuestionTool: taskForPrompt != nil && taskForPrompt.Autopilot && taskForPrompt.ParentID != "",
|
||||
}, referenceContext)
|
||||
}, referenceContext, pullRequestTargetContext)
|
||||
}
|
||||
}
|
||||
userMsgRecorded := s.recordAutoStartMessage(ctx, taskID, sessionID, recordedPrompt, planMode, origin, references)
|
||||
|
||||
@@ -221,6 +221,9 @@ func (e *Executor) resolveTaskRepoInfoForSession(
|
||||
info.RepositoryPath = repo.LocalPath
|
||||
info.WorktreeBranchPrefix = repo.WorktreeBranchPrefix
|
||||
info.WorktreeBranchTemplate = repo.WorktreeBranchTemplate
|
||||
if tr.BranchPolicyBranchTemplate != "" {
|
||||
info.WorktreeBranchTemplate = tr.BranchPolicyBranchTemplate
|
||||
}
|
||||
info.PullBeforeWorktree = repo.PullBeforeWorktree
|
||||
if info.BaseBranch == "" && repo.DefaultBranch != "" {
|
||||
info.BaseBranch = repo.DefaultBranch
|
||||
@@ -1432,6 +1435,9 @@ func (e *Executor) applyResumeWorktreeConfig(
|
||||
}
|
||||
req.WorktreeBranchPrefix = repository.WorktreeBranchPrefix
|
||||
req.WorktreeBranchTemplate = repository.WorktreeBranchTemplate
|
||||
if primaryTaskRepo != nil && primaryTaskRepo.RepositoryID == repositoryID && primaryTaskRepo.BranchPolicyBranchTemplate != "" {
|
||||
req.WorktreeBranchTemplate = primaryTaskRepo.BranchPolicyBranchTemplate
|
||||
}
|
||||
req.PullBeforeWorktree = repository.PullBeforeWorktree
|
||||
// Worktree manager requires TaskDirName and RepoName. Mirror the
|
||||
// initial-launch path (applyRepositoryConfig) so resumes of single-repo
|
||||
|
||||
@@ -1171,6 +1171,47 @@ func TestResolveResumeBaseBranchKeepsLegacyValueWhenRepositoryRowsAreAmbiguous(t
|
||||
}
|
||||
}
|
||||
|
||||
func TestResumeUsesTaskRepositoryBranchPolicyTemplateSnapshot(t *testing.T) {
|
||||
for _, testCase := range []struct {
|
||||
name string
|
||||
snapshot string
|
||||
want string
|
||||
}{
|
||||
{name: "policy snapshot overrides repository template", snapshot: "policy/{title}", want: "policy/{title}"},
|
||||
{name: "empty snapshot falls back to repository template", want: "repository/{title}"},
|
||||
} {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
repo := newMockRepository()
|
||||
repo.repositories["repo-1"] = &models.Repository{
|
||||
ID: "repo-1", WorkspaceID: "workspace-1", Name: "widgets", SourceType: sourceTypeLocal,
|
||||
LocalPath: t.TempDir(), WorktreeBranchTemplate: "repository/{title}",
|
||||
}
|
||||
repo.taskRepositories["task-repo-1"] = &models.TaskRepository{
|
||||
ID: "task-repo-1", TaskID: "task-1", RepositoryID: "repo-1",
|
||||
BranchPolicyBranchTemplate: testCase.snapshot,
|
||||
}
|
||||
exec := newTestExecutor(t, &mockAgentManager{}, repo)
|
||||
|
||||
info, err := exec.resolveTaskRepoInfoForSession(context.Background(), "session-1", repo.taskRepositories["task-repo-1"])
|
||||
if err != nil {
|
||||
t.Fatalf("resolveTaskRepoInfoForSession: %v", err)
|
||||
}
|
||||
if info.WorktreeBranchTemplate != testCase.want {
|
||||
t.Fatalf("resolved worktree template = %q, want %q", info.WorktreeBranchTemplate, testCase.want)
|
||||
}
|
||||
|
||||
req := &LaunchAgentRequest{}
|
||||
exec.applyResumeWorktreeConfig(
|
||||
context.Background(), &v1.Task{ID: "task-1", Title: "Resume task"}, req,
|
||||
repo.repositories["repo-1"], "repo-1", repo.repositories["repo-1"].LocalPath, "main", nil,
|
||||
)
|
||||
if req.WorktreeBranchTemplate != testCase.want {
|
||||
t.Fatalf("resume request worktree template = %q, want %q", req.WorktreeBranchTemplate, testCase.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyResumeWorktreeConfigPreservesSelectedRepositoryDestination(t *testing.T) {
|
||||
primaryDestination := resumeTestContributionDestination("200")
|
||||
selectedDestination := resumeTestContributionDestination("201")
|
||||
|
||||
@@ -473,12 +473,13 @@ func (o *reservedPromptCallbackOwner) stop() {
|
||||
|
||||
// Service is the main orchestrator service
|
||||
type Service struct {
|
||||
config ServiceConfig
|
||||
logger *logger.Logger
|
||||
eventBus bus.EventBus
|
||||
taskRepo scheduler.TaskRepository
|
||||
repo sessionExecutorStore
|
||||
agentManager executor.AgentManagerClient
|
||||
config ServiceConfig
|
||||
logger *logger.Logger
|
||||
eventBus bus.EventBus
|
||||
taskRepo scheduler.TaskRepository
|
||||
repo sessionExecutorStore
|
||||
promptTargets taskPullRequestTargetStore
|
||||
agentManager executor.AgentManagerClient
|
||||
|
||||
// Components
|
||||
queue *queue.TaskQueue
|
||||
@@ -1147,6 +1148,7 @@ func NewService(
|
||||
eventBus: eventBus,
|
||||
taskRepo: taskRepo,
|
||||
repo: repo,
|
||||
promptTargets: repo,
|
||||
agentManager: agentManager,
|
||||
queue: taskQueue,
|
||||
executor: exec,
|
||||
|
||||
@@ -666,6 +666,9 @@ func (s *Service) wrapCreatedSessionPrompt(
|
||||
references []v1.EntityReference,
|
||||
promptReferenceContext string,
|
||||
) string {
|
||||
prompt, pullRequestTargetContext := s.addTaskPullRequestTargetContext(
|
||||
ctx, taskID, prompt, session.IsPassthrough,
|
||||
)
|
||||
referenceContext := EntityReferenceContext(references)
|
||||
switch {
|
||||
case session.IsPassthrough:
|
||||
@@ -677,7 +680,7 @@ func (s *Service) wrapCreatedSessionPrompt(
|
||||
return sysprompt.InjectOfficeContextWithOptions(
|
||||
taskID, sessionID, prompt,
|
||||
s.WorkflowStepRequiresCompletionSignal(ctx, dbTask.WorkflowStepID),
|
||||
referenceContext, promptReferenceContext,
|
||||
referenceContext, promptReferenceContext, pullRequestTargetContext,
|
||||
)
|
||||
default:
|
||||
return sysprompt.InjectKandevContextWithOptions(taskID, sessionID, prompt, sysprompt.KandevContextOptions{
|
||||
@@ -687,7 +690,7 @@ func (s *Service) wrapCreatedSessionPrompt(
|
||||
Autopilot: dbTask.Autopilot,
|
||||
IncludeUserQuestionTool: !dbTask.Autopilot && !session.IsPassthrough,
|
||||
IncludeParentQuestionTool: dbTask.Autopilot && dbTask.ParentID != "",
|
||||
}, referenceContext, promptReferenceContext)
|
||||
}, referenceContext, promptReferenceContext, pullRequestTargetContext)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1241,6 +1244,10 @@ type launchPromptContext struct {
|
||||
// Passthrough profiles get attribution only, as plain text — see
|
||||
// applySpawnOriginText for why they skip the MCP block entirely.
|
||||
func (s *Service) applyLaunchPromptContext(ctx context.Context, p launchPromptContext) string {
|
||||
var pullRequestTargetContext string
|
||||
p.prompt, pullRequestTargetContext = s.addTaskPullRequestTargetContext(
|
||||
ctx, p.taskID, p.prompt, p.isPassthrough,
|
||||
)
|
||||
if p.isPassthrough {
|
||||
prompt := applySpawnOriginText(p.prompt, p.spawnOrigin)
|
||||
if p.includeTaskTitleTool {
|
||||
@@ -1257,7 +1264,7 @@ func (s *Service) applyLaunchPromptContext(ctx context.Context, p launchPromptCo
|
||||
return sysprompt.InjectOfficeContextWithOptions(
|
||||
p.taskID, p.sessionID, prompt,
|
||||
s.StepRequiresCompletionSignal(ctx, p.taskID),
|
||||
p.referenceContext, spawnContext,
|
||||
p.referenceContext, spawnContext, pullRequestTargetContext,
|
||||
)
|
||||
}
|
||||
return sysprompt.InjectKandevContextWithOptions(p.taskID, p.sessionID, prompt, sysprompt.KandevContextOptions{
|
||||
@@ -1267,7 +1274,7 @@ func (s *Service) applyLaunchPromptContext(ctx context.Context, p launchPromptCo
|
||||
Autopilot: p.autopilot,
|
||||
IncludeUserQuestionTool: !p.autopilot && !p.isPassthrough,
|
||||
IncludeParentQuestionTool: p.autopilot && p.includeParentQuestionTool,
|
||||
}, p.referenceContext, spawnContext)
|
||||
}, p.referenceContext, spawnContext, pullRequestTargetContext)
|
||||
}
|
||||
|
||||
// spawnOriginContent renders the spawner-attribution text for a launch requested
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package orchestrator
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/kandev/kandev/internal/sysprompt"
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
"github.com/kandev/kandev/internal/task/promptcontext"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
type taskPullRequestTargetStore interface {
|
||||
ListTaskRepositories(ctx context.Context, taskID string) ([]*models.TaskRepository, error)
|
||||
GetRepository(ctx context.Context, id string) (*models.Repository, error)
|
||||
}
|
||||
|
||||
func (s *Service) taskPullRequestTargets(ctx context.Context, taskID string) []sysprompt.PullRequestTarget {
|
||||
if s.promptTargets == nil {
|
||||
return nil
|
||||
}
|
||||
links, err := s.promptTargets.ListTaskRepositories(ctx, taskID)
|
||||
if err != nil {
|
||||
s.logPullRequestTargetLookupFailure("failed to load task repositories", taskID, "", err)
|
||||
return nil
|
||||
}
|
||||
return promptcontext.BuildPullRequestTargets(ctx, links, func(resolveCtx context.Context, repositoryID string) (string, error) {
|
||||
repository, err := s.promptTargets.GetRepository(resolveCtx, repositoryID)
|
||||
if err != nil {
|
||||
s.logPullRequestTargetLookupFailure(
|
||||
"failed to load repository for pull request target prompt", taskID, repositoryID, err,
|
||||
)
|
||||
return "", err
|
||||
}
|
||||
if repository == nil {
|
||||
return "", nil
|
||||
}
|
||||
return repository.Name, nil
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) logPullRequestTargetLookupFailure(message, taskID, repositoryID string, err error) {
|
||||
if s.logger == nil {
|
||||
return
|
||||
}
|
||||
fields := []zap.Field{zap.String("task_id", taskID), zap.Error(err)}
|
||||
if repositoryID != "" {
|
||||
fields = append(fields, zap.String("repository_id", repositoryID))
|
||||
}
|
||||
s.logger.Warn(message, fields...)
|
||||
}
|
||||
|
||||
func (s *Service) addTaskPullRequestTargetContext(
|
||||
ctx context.Context,
|
||||
taskID, prompt string,
|
||||
passthrough bool,
|
||||
) (string, string) {
|
||||
targets := s.taskPullRequestTargets(ctx, taskID)
|
||||
if passthrough {
|
||||
return sysprompt.PrependPullRequestTargetInstruction(prompt, targets), ""
|
||||
}
|
||||
return sysprompt.InjectPullRequestTargetContext(prompt, targets)
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package orchestrator
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/kandev/kandev/internal/sysprompt"
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
wfmodels "github.com/kandev/kandev/internal/workflow/models"
|
||||
v1 "github.com/kandev/kandev/pkg/api/v1"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// @covers AC-WORKSPACES-BRANCH-POLICIES-004.6
|
||||
func TestStartCreatedSession_InstructsAgentToUseSnapshottedPullRequestTarget(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := setupTestRepo(t)
|
||||
seedTaskAndSession(t, repo, "task1", "session1", models.TaskSessionStateCreated)
|
||||
seedExecutorRunning(t, repo, "session1", "task1", "exec-1")
|
||||
seedPolicyBackedTaskRepository(t, repo, "task1")
|
||||
|
||||
taskRepo := newMockTaskRepo()
|
||||
taskRepo.tasks["task1"] = &v1.Task{ID: "task1", Title: "Release", State: v1.TaskStateInProgress}
|
||||
agentMgr := &mockAgentManager{repoForExecutionLookup: repo}
|
||||
svc := createTestServiceWithScheduler(repo, newMockStepGetter(), taskRepo, agentMgr)
|
||||
svc.promptTargets = repo
|
||||
messages := &mockMessageCreator{}
|
||||
svc.messageCreator = messages
|
||||
|
||||
_, err := svc.StartCreatedSession(
|
||||
ctx, "task1", "session1", "profile1", "Create the release", false, false, false, nil, nil,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, messages.userMessages, 1)
|
||||
|
||||
content := messages.userMessages[0].content
|
||||
require.Contains(t, content, "BRANCH POLICY PULL REQUEST TARGETS")
|
||||
require.Contains(t, content, `Repository "kandev"`)
|
||||
require.Contains(t, content, `working branch "release/next"`)
|
||||
require.Contains(t, content, `target branch "main"`)
|
||||
require.Contains(t, content, `gh pr create --base "main"`)
|
||||
require.Equal(t, "Create the release", sysprompt.StripSystemContent(content))
|
||||
}
|
||||
|
||||
// @covers AC-WORKSPACES-BRANCH-POLICIES-004.6
|
||||
func TestStartCreatedSession_GivesPassthroughAgentPullRequestTargetInstruction(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := setupTestRepo(t)
|
||||
seedTaskAndSession(t, repo, "task1", "session1", models.TaskSessionStateCreated)
|
||||
seedExecutorRunning(t, repo, "session1", "task1", "exec-1")
|
||||
seedPolicyBackedTaskRepository(t, repo, "task1")
|
||||
|
||||
session, err := repo.GetTaskSession(ctx, "session1")
|
||||
require.NoError(t, err)
|
||||
session.IsPassthrough = true
|
||||
require.NoError(t, repo.UpdateTaskSession(ctx, session))
|
||||
|
||||
taskRepo := newMockTaskRepo()
|
||||
taskRepo.tasks["task1"] = &v1.Task{ID: "task1", Title: "Release", State: v1.TaskStateInProgress}
|
||||
agentMgr := &mockAgentManager{repoForExecutionLookup: repo}
|
||||
svc := createTestServiceWithScheduler(repo, newMockStepGetter(), taskRepo, agentMgr)
|
||||
svc.promptTargets = repo
|
||||
messages := &mockMessageCreator{}
|
||||
svc.messageCreator = messages
|
||||
|
||||
_, err = svc.StartCreatedSession(
|
||||
ctx, "task1", "session1", "profile1", "Create the release", false, false, false, nil, nil,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, messages.userMessages, 1)
|
||||
|
||||
content := messages.userMessages[0].content
|
||||
require.NotContains(t, content, sysprompt.TagStart)
|
||||
require.True(t, strings.HasSuffix(content, "Create the release"))
|
||||
require.Contains(t, content, `gh pr create --base "main"`)
|
||||
}
|
||||
|
||||
// @covers AC-WORKSPACES-BRANCH-POLICIES-004.6
|
||||
func TestAutoStartStepPrompt_ResetContextReinjectsSnapshottedPullRequestTarget(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := setupTestRepo(t)
|
||||
seedTaskAndSession(t, repo, "task1", "session1", models.TaskSessionStateWaitingForInput)
|
||||
seedPolicyBackedTaskRepository(t, repo, "task1")
|
||||
|
||||
session, err := repo.GetTaskSession(ctx, "session1")
|
||||
require.NoError(t, err)
|
||||
session.AgentExecutionID = "execution-1"
|
||||
require.NoError(t, repo.UpdateTaskSession(ctx, session))
|
||||
seedExecutorRunning(t, repo, session.ID, session.TaskID, session.AgentExecutionID)
|
||||
|
||||
step := &wfmodels.WorkflowStep{
|
||||
ID: "step-review", WorkflowID: "wf1", Name: "Review",
|
||||
Events: wfmodels.StepEvents{OnEnter: []wfmodels.OnEnterAction{
|
||||
{Type: wfmodels.OnEnterResetAgentContext},
|
||||
{Type: wfmodels.OnEnterAutoStartAgent},
|
||||
}},
|
||||
}
|
||||
stepGetter := newMockStepGetter()
|
||||
stepGetter.steps[step.ID] = step
|
||||
agentMgr := &mockAgentManager{repoForExecutionLookup: repo, isAgentRunning: true}
|
||||
svc := createTestServiceWithScheduler(repo, stepGetter, newMockTaskRepo(), agentMgr)
|
||||
svc.promptTargets = repo
|
||||
messages := &mockMessageCreator{}
|
||||
svc.messageCreator = messages
|
||||
|
||||
require.NoError(t, svc.autoStartStepPrompt(
|
||||
ctx, "task1", session, step, "Review the release", false, false,
|
||||
))
|
||||
require.Len(t, messages.userMessages, 1)
|
||||
require.Contains(t, messages.userMessages[0].content, `gh pr create --base "main"`)
|
||||
require.Len(t, agentMgr.capturedPromptCalls, 1)
|
||||
require.Contains(t, agentMgr.capturedPromptCalls[0].Prompt, `gh pr create --base "main"`)
|
||||
}
|
||||
|
||||
func seedPolicyBackedTaskRepository(t *testing.T, repo interface {
|
||||
CreateRepository(context.Context, *models.Repository) error
|
||||
CreateTaskRepository(context.Context, *models.TaskRepository) error
|
||||
}, taskID string) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
require.NoError(t, repo.CreateRepository(ctx, &models.Repository{
|
||||
ID: "repo-1", WorkspaceID: "ws1", Name: "kandev", SourceType: "local",
|
||||
}))
|
||||
require.NoError(t, repo.CreateTaskRepository(ctx, &models.TaskRepository{
|
||||
ID: "task-repo-1",
|
||||
TaskID: taskID,
|
||||
RepositoryID: "repo-1",
|
||||
BaseBranch: "develop",
|
||||
CheckoutBranch: "release/next",
|
||||
BranchPolicyID: "policy-release",
|
||||
BranchPolicyName: "Release",
|
||||
BranchPolicyBaseBranch: "develop",
|
||||
BranchPolicyBranchTemplate: "release/{title}-{suffix}",
|
||||
BranchPolicyPullRequestTarget: "main",
|
||||
}))
|
||||
}
|
||||
@@ -49,15 +49,25 @@ type TitleBranchRenameResult struct {
|
||||
Failed []TitleBranchFailure `json:"failed,omitempty"`
|
||||
}
|
||||
|
||||
func renderTitleBranchName(title string, task *models.Task, repository *models.Repository, suffix string) (string, error) {
|
||||
func renderTitleBranchNameForTaskRepository(
|
||||
title string,
|
||||
task *models.Task,
|
||||
repository *models.Repository,
|
||||
taskRepository *models.TaskRepository,
|
||||
suffix string,
|
||||
) (string, error) {
|
||||
if task == nil {
|
||||
return "", fmt.Errorf("task is required")
|
||||
}
|
||||
if repository == nil {
|
||||
return "", fmt.Errorf("repository is required")
|
||||
}
|
||||
template := repository.WorktreeBranchTemplate
|
||||
if taskRepository != nil && taskRepository.BranchPolicyBranchTemplate != "" {
|
||||
template = taskRepository.BranchPolicyBranchTemplate
|
||||
}
|
||||
return worktree.RenderTaskBranchName(worktree.BranchNameTemplateInput{
|
||||
Template: repository.WorktreeBranchTemplate,
|
||||
Template: template,
|
||||
TaskID: task.ID,
|
||||
Title: title,
|
||||
Ticket: worktree.TicketForBranchName(task.Identifier, task.Metadata),
|
||||
|
||||
@@ -375,7 +375,7 @@ func (s *Service) performTitleBranchRename(
|
||||
branch string,
|
||||
) (string, error) {
|
||||
suffix := titleBranchSuffix(executorType, task.ID)
|
||||
newName, err := renderTitleBranchName(title, task, binding.repository, suffix)
|
||||
newName, err := renderTitleBranchNameForTaskRepository(title, task, binding.repository, binding.taskRepository, suffix)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
@@ -7,17 +7,34 @@ import (
|
||||
)
|
||||
|
||||
func TestRenderTitleBranchNameUsesFinalTitleAndRepositoryTemplate(t *testing.T) {
|
||||
got, err := renderTitleBranchName(
|
||||
got, err := renderTitleBranchNameForTaskRepository(
|
||||
"Improve login flow",
|
||||
&models.Task{ID: "task-123", Identifier: "KAN-42"},
|
||||
&models.Repository{WorktreeBranchTemplate: "feature/{ticket}-{title}-{suffix}"},
|
||||
nil,
|
||||
"abc",
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("renderTitleBranchName returned error: %v", err)
|
||||
t.Fatalf("renderTitleBranchNameForTaskRepository returned error: %v", err)
|
||||
}
|
||||
if got != "feature/kan-42-improve-login-flow-abc" {
|
||||
t.Fatalf("renderTitleBranchName = %q, want final-title branch", got)
|
||||
t.Fatalf("renderTitleBranchNameForTaskRepository = %q, want final-title branch", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderTitleBranchNameUsesTaskPolicySnapshot(t *testing.T) {
|
||||
got, err := renderTitleBranchNameForTaskRepository(
|
||||
"Fix login flow",
|
||||
&models.Task{ID: "task-123", Identifier: "KAN-42"},
|
||||
&models.Repository{WorktreeBranchTemplate: "feature/{title}"},
|
||||
&models.TaskRepository{BranchPolicyBranchTemplate: "bugfix/{ticket}-{title}-{suffix}"},
|
||||
"abc",
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("renderTitleBranchNameForTaskRepository returned error: %v", err)
|
||||
}
|
||||
if got != "bugfix/kan-42-fix-login-flow-abc" {
|
||||
t.Fatalf("renderTitleBranchNameForTaskRepository = %q, want policy snapshot branch", got)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -68,6 +68,70 @@ const kandevContextMarker = "KANDEV MCP TOOLS"
|
||||
|
||||
const officeContextMarker = "KANDEV OFFICE MCP TOOLS"
|
||||
|
||||
const pullRequestTargetContextMarker = "BRANCH POLICY PULL REQUEST TARGETS"
|
||||
|
||||
// PullRequestTarget is immutable task context that tells an agent where a
|
||||
// branch-policy-backed pull request must merge.
|
||||
type PullRequestTarget struct {
|
||||
RepositoryName string
|
||||
WorkingBranch string
|
||||
TargetBranch string
|
||||
}
|
||||
|
||||
// FormatPullRequestTargetContext formats branch-policy targets as trusted
|
||||
// agent instructions. Values are quoted so repository configuration remains
|
||||
// data even when it contains punctuation.
|
||||
func FormatPullRequestTargetContext(targets []PullRequestTarget) string {
|
||||
if len(targets) == 0 {
|
||||
return ""
|
||||
}
|
||||
lines := []string{
|
||||
pullRequestTargetContextMarker + ":",
|
||||
"This task uses immutable branch-policy targets.",
|
||||
"When you create a pull request, use the matching target explicitly.",
|
||||
"Do not infer the target from the task base or working branch.",
|
||||
}
|
||||
for _, target := range targets {
|
||||
lines = append(lines, fmt.Sprintf(
|
||||
"- Repository %s, working branch %s: target branch %s. For GitHub, use gh pr create --base %s.",
|
||||
strconv.Quote(StripTags(target.RepositoryName)),
|
||||
strconv.Quote(StripTags(target.WorkingBranch)),
|
||||
strconv.Quote(StripTags(target.TargetBranch)),
|
||||
strconv.Quote(StripTags(target.TargetBranch)),
|
||||
))
|
||||
}
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
|
||||
// InjectPullRequestTargetContext prepends one canonical hidden target block.
|
||||
// It removes a stale or upstream copy before inserting the current snapshot.
|
||||
func InjectPullRequestTargetContext(prompt string, targets []PullRequestTarget) (string, string) {
|
||||
prompt = systemTagRegex.ReplaceAllStringFunc(prompt, func(block string) string {
|
||||
if strings.Contains(block, pullRequestTargetContextMarker) {
|
||||
return ""
|
||||
}
|
||||
return block
|
||||
})
|
||||
content := FormatPullRequestTargetContext(targets)
|
||||
if content == "" {
|
||||
return prompt, ""
|
||||
}
|
||||
return Wrap(content) + "\n\n" + prompt, content
|
||||
}
|
||||
|
||||
// PrependPullRequestTargetInstruction adds the compact plain-text equivalent
|
||||
// for passthrough sessions, which intentionally do not receive hidden blocks.
|
||||
func PrependPullRequestTargetInstruction(prompt string, targets []PullRequestTarget) string {
|
||||
content := FormatPullRequestTargetContext(targets)
|
||||
if content == "" {
|
||||
return prompt
|
||||
}
|
||||
if strings.HasPrefix(prompt, content+"\n\n") {
|
||||
return prompt
|
||||
}
|
||||
return content + "\n\n" + prompt
|
||||
}
|
||||
|
||||
type contextKind uint8
|
||||
|
||||
const (
|
||||
|
||||
@@ -96,6 +96,18 @@ type RepositorySetItemDTO struct {
|
||||
Position int `json:"position"`
|
||||
}
|
||||
|
||||
type RepositoryBranchPolicyDTO struct {
|
||||
ID string `json:"id"`
|
||||
RepositoryID string `json:"repository_id"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
BaseBranch string `json:"base_branch"`
|
||||
BranchTemplate string `json:"branch_template"`
|
||||
PullRequestTarget string `json:"pull_request_target"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type RepositoryScriptDTO struct {
|
||||
ID string `json:"id"`
|
||||
RepositoryID string `json:"repository_id"`
|
||||
@@ -264,15 +276,20 @@ type TaskDTO struct {
|
||||
}
|
||||
|
||||
type TaskRepositoryDTO struct {
|
||||
ID string `json:"id"`
|
||||
TaskID string `json:"task_id"`
|
||||
RepositoryID string `json:"repository_id"`
|
||||
BaseBranch string `json:"base_branch"`
|
||||
CheckoutBranch string `json:"checkout_branch,omitempty"`
|
||||
Position int `json:"position"`
|
||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
ID string `json:"id"`
|
||||
TaskID string `json:"task_id"`
|
||||
RepositoryID string `json:"repository_id"`
|
||||
BaseBranch string `json:"base_branch"`
|
||||
CheckoutBranch string `json:"checkout_branch,omitempty"`
|
||||
BranchPolicyID string `json:"branch_policy_id,omitempty"`
|
||||
BranchPolicyName string `json:"branch_policy_name,omitempty"`
|
||||
BranchPolicyBaseBranch string `json:"branch_policy_base_branch,omitempty"`
|
||||
BranchPolicyBranchTemplate string `json:"branch_policy_branch_template,omitempty"`
|
||||
BranchPolicyPullRequestTarget string `json:"branch_policy_pull_request_target,omitempty"`
|
||||
Position int `json:"position"`
|
||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// TaskWorkspaceFolderDTO is the API projection of a durable non-Git source.
|
||||
@@ -516,6 +533,11 @@ type ListRepositorySetsResponse struct {
|
||||
Total int `json:"total"`
|
||||
}
|
||||
|
||||
type ListRepositoryBranchPoliciesResponse struct {
|
||||
Policies []RepositoryBranchPolicyDTO `json:"repository_branch_policies"`
|
||||
Total int `json:"total"`
|
||||
}
|
||||
|
||||
type ListRepositoryScriptsResponse struct {
|
||||
Scripts []RepositoryScriptDTO `json:"scripts"`
|
||||
Total int `json:"total"`
|
||||
@@ -689,6 +711,15 @@ func FromRepositorySet(set *models.RepositorySet) RepositorySetDTO {
|
||||
}
|
||||
}
|
||||
|
||||
func FromRepositoryBranchPolicy(policy *models.RepositoryBranchPolicy) RepositoryBranchPolicyDTO {
|
||||
return RepositoryBranchPolicyDTO{
|
||||
ID: policy.ID, RepositoryID: policy.RepositoryID, Name: policy.Name,
|
||||
Description: policy.Description, BaseBranch: policy.BaseBranch,
|
||||
BranchTemplate: policy.BranchTemplate, PullRequestTarget: policy.PullRequestTarget,
|
||||
CreatedAt: policy.CreatedAt, UpdatedAt: policy.UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func FromRepositoryScript(script *models.RepositoryScript) RepositoryScriptDTO {
|
||||
return RepositoryScriptDTO{
|
||||
ID: script.ID,
|
||||
@@ -791,15 +822,20 @@ func FromTaskWithSessionInfo(
|
||||
var repositories []TaskRepositoryDTO
|
||||
for _, repo := range task.Repositories {
|
||||
repositories = append(repositories, TaskRepositoryDTO{
|
||||
ID: repo.ID,
|
||||
TaskID: repo.TaskID,
|
||||
RepositoryID: repo.RepositoryID,
|
||||
BaseBranch: repo.BaseBranch,
|
||||
CheckoutBranch: repo.CheckoutBranch,
|
||||
Position: repo.Position,
|
||||
Metadata: repo.Metadata,
|
||||
CreatedAt: repo.CreatedAt,
|
||||
UpdatedAt: repo.UpdatedAt,
|
||||
ID: repo.ID,
|
||||
TaskID: repo.TaskID,
|
||||
RepositoryID: repo.RepositoryID,
|
||||
BaseBranch: repo.BaseBranch,
|
||||
CheckoutBranch: repo.CheckoutBranch,
|
||||
BranchPolicyID: repo.BranchPolicyID,
|
||||
BranchPolicyName: repo.BranchPolicyName,
|
||||
BranchPolicyBaseBranch: repo.BranchPolicyBaseBranch,
|
||||
BranchPolicyBranchTemplate: repo.BranchPolicyBranchTemplate,
|
||||
BranchPolicyPullRequestTarget: repo.BranchPolicyPullRequestTarget,
|
||||
Position: repo.Position,
|
||||
Metadata: repo.Metadata,
|
||||
CreatedAt: repo.CreatedAt,
|
||||
UpdatedAt: repo.UpdatedAt,
|
||||
})
|
||||
}
|
||||
var workspaceFolders []TaskWorkspaceFolderDTO
|
||||
|
||||
@@ -258,6 +258,7 @@ type TaskRepositoryInput struct {
|
||||
RepositoryID string
|
||||
BaseBranch string
|
||||
CheckoutBranch string
|
||||
BranchPolicyID string
|
||||
PRNumber int // GitHub PR number when CheckoutBranch is a PR head; persisted into task_repositories.metadata["pr_number"].
|
||||
LocalPath string
|
||||
Name string
|
||||
@@ -268,6 +269,10 @@ type TaskRepositoryInput struct {
|
||||
ProviderRepoID string
|
||||
ProviderOwner string
|
||||
ProviderName string
|
||||
// PreserveBaseBranch is set only by the internal fresh-branch rewrite. It
|
||||
// keeps the generated branch as the effective base when the association is
|
||||
// recreated after policy resolution.
|
||||
PreserveBaseBranch bool
|
||||
}
|
||||
|
||||
type CreateTaskRequest struct {
|
||||
|
||||
@@ -31,13 +31,28 @@ func handleNotFound(c *gin.Context, log *logger.Logger, err error, fallback stri
|
||||
return
|
||||
}
|
||||
if isValidationError(err) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
c.JSON(http.StatusBadRequest, taskErrorBody(err))
|
||||
return
|
||||
}
|
||||
log.Error("request failed", zap.Error(err))
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "request failed"})
|
||||
}
|
||||
|
||||
func taskErrorBody(err error) gin.H {
|
||||
body := gin.H{"error": err.Error()}
|
||||
for key, value := range taskErrorDetails(err) {
|
||||
body[key] = value
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
func taskErrorDetails(err error) map[string]interface{} {
|
||||
if errors.Is(err, service.ErrRepositoryBranchPolicyStale) {
|
||||
return map[string]interface{}{"error_code": service.BranchPolicyStaleErrorCode}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func handleSelectedMoveError(c *gin.Context, log *logger.Logger, err error) {
|
||||
switch {
|
||||
case isClientDisconnect(err):
|
||||
|
||||
@@ -2,6 +2,7 @@ package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
@@ -93,6 +94,25 @@ func TestErrorsAreClassifiable(t *testing.T) {
|
||||
t.Fatalf("status=%d, want %d", rec.Code, http.StatusConflict)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("stale branch policies include a stable error code", func(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
rec := httptest.NewRecorder()
|
||||
ctx, _ := gin.CreateTestContext(rec)
|
||||
err := fmt.Errorf("%w: %w", service.ErrInvalidRepositoryBranchPolicy, service.ErrRepositoryBranchPolicyStale)
|
||||
handleNotFound(ctx, newTestLogger(t), err, "task not created")
|
||||
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status=%d, want %d", rec.Code, http.StatusBadRequest)
|
||||
}
|
||||
var payload map[string]string
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatalf("decode response: %v", err)
|
||||
}
|
||||
if payload["error_code"] != service.BranchPolicyStaleErrorCode {
|
||||
t.Fatalf("error_code=%q, want %q", payload["error_code"], service.BranchPolicyStaleErrorCode)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestIsTimeoutError pins the UX-classification contract for the prompt
|
||||
|
||||
@@ -445,8 +445,15 @@ func (h *MessageHandlers) wsAddMessage(ctx context.Context, msg *ws.Message) (*w
|
||||
}
|
||||
requiresSignal := h.orchestrator != nil && h.orchestrator.StepRequiresCompletionSignal(ctx, req.TaskID)
|
||||
referenceContext := orchestrator.EntityReferenceContext(req.EntityReferences)
|
||||
var pullRequestTargetContext string
|
||||
storedContent, pullRequestTargetContext = sysprompt.InjectPullRequestTargetContext(
|
||||
storedContent, h.taskPullRequestTargets(ctx, task),
|
||||
)
|
||||
if task.IsFromOffice {
|
||||
storedContent = sysprompt.InjectOfficeContextWithOptions(req.TaskID, req.TaskSessionID, storedContent, requiresSignal, referenceContext)
|
||||
storedContent = sysprompt.InjectOfficeContextWithOptions(
|
||||
req.TaskID, req.TaskSessionID, storedContent, requiresSignal,
|
||||
referenceContext, pullRequestTargetContext,
|
||||
)
|
||||
} else {
|
||||
storedContent = sysprompt.InjectKandevContextWithOptions(req.TaskID, req.TaskSessionID, storedContent, sysprompt.KandevContextOptions{
|
||||
RequiresCompletionSignal: requiresSignal,
|
||||
@@ -455,7 +462,7 @@ func (h *MessageHandlers) wsAddMessage(ctx context.Context, msg *ws.Message) (*w
|
||||
Autopilot: task.Autopilot,
|
||||
IncludeUserQuestionTool: !task.Autopilot && !sessionResp.Session.IsPassthrough,
|
||||
IncludeParentQuestionTool: task.Autopilot && task.ParentID != "",
|
||||
}, referenceContext)
|
||||
}, referenceContext, pullRequestTargetContext)
|
||||
}
|
||||
}
|
||||
req.Content = storedContent
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/kandev/kandev/internal/common/logger"
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
"github.com/kandev/kandev/internal/task/service"
|
||||
v1 "github.com/kandev/kandev/pkg/api/v1"
|
||||
ws "github.com/kandev/kandev/pkg/websocket"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type policyPromptMessageRepo struct {
|
||||
*messageAddSwitchRepo
|
||||
taskRepositories []*models.TaskRepository
|
||||
repositories map[string]*models.Repository
|
||||
}
|
||||
|
||||
func (r *policyPromptMessageRepo) ListTaskRepositories(
|
||||
_ context.Context,
|
||||
_ string,
|
||||
) ([]*models.TaskRepository, error) {
|
||||
return r.taskRepositories, nil
|
||||
}
|
||||
|
||||
func (r *policyPromptMessageRepo) GetRepository(
|
||||
_ context.Context,
|
||||
id string,
|
||||
) (*models.Repository, error) {
|
||||
return r.repositories[id], nil
|
||||
}
|
||||
|
||||
// @covers AC-WORKSPACES-BRANCH-POLICIES-004.6
|
||||
func TestWSAddMessage_PersistsSnapshottedPullRequestTargetContext(t *testing.T) {
|
||||
now := time.Now().UTC()
|
||||
base := &messageAddSwitchRepo{
|
||||
tasks: map[string]*models.Task{"t1": {
|
||||
ID: "t1", WorkspaceID: "ws1", State: v1.TaskStateInProgress, UpdatedAt: now,
|
||||
}},
|
||||
sessions: map[string]*models.TaskSession{"s1": {
|
||||
ID: "s1", TaskID: "t1", State: models.TaskSessionStateCreated,
|
||||
AgentProfileID: "profile-1", UpdatedAt: now,
|
||||
}},
|
||||
primaryID: "s1",
|
||||
}
|
||||
repo := &policyPromptMessageRepo{
|
||||
messageAddSwitchRepo: base,
|
||||
taskRepositories: []*models.TaskRepository{{
|
||||
ID: "task-repo-1",
|
||||
TaskID: "t1",
|
||||
RepositoryID: "repo-1",
|
||||
BaseBranch: "develop",
|
||||
CheckoutBranch: "release/next",
|
||||
BranchPolicyID: "policy-release",
|
||||
BranchPolicyPullRequestTarget: "main",
|
||||
}},
|
||||
repositories: map[string]*models.Repository{
|
||||
"repo-1": {ID: "repo-1", WorkspaceID: "ws1", Name: "kandev"},
|
||||
},
|
||||
}
|
||||
log, err := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "json"})
|
||||
require.NoError(t, err)
|
||||
svc := service.NewService(service.Repos{
|
||||
Workspaces: repo, Tasks: repo, TaskRepos: repo,
|
||||
Workflows: repo, Messages: repo, Turns: repo,
|
||||
Sessions: repo, GitSnapshots: repo, RepoEntities: repo,
|
||||
Executors: repo, Environments: repo, TaskEnvironments: repo,
|
||||
Reviews: repo,
|
||||
}, nil, log, service.RepositoryDiscoveryConfig{})
|
||||
orch := &firstTurnCaptureOrchestrator{started: make(chan capturedFirstTurn, 1)}
|
||||
handler := NewMessageHandlers(svc, orch, log)
|
||||
|
||||
req, err := ws.NewRequest("req-policy-target", ws.ActionMessageAdd, map[string]any{
|
||||
"task_id": "t1", "session_id": "s1", "content": "Create the release",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
response, err := handler.wsAddMessage(context.Background(), req)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, ws.MessageTypeResponse, response.Type)
|
||||
require.Len(t, base.messages, 1)
|
||||
require.Contains(t, base.messages[0].Content, `gh pr create --base "main"`)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/kandev/kandev/internal/sysprompt"
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
"github.com/kandev/kandev/internal/task/promptcontext"
|
||||
)
|
||||
|
||||
func (h *MessageHandlers) taskPullRequestTargets(
|
||||
ctx context.Context,
|
||||
task *models.Task,
|
||||
) []sysprompt.PullRequestTarget {
|
||||
return promptcontext.BuildPullRequestTargets(ctx, task.Repositories, func(resolveCtx context.Context, repositoryID string) (string, error) {
|
||||
repository, err := h.service.GetRepository(resolveCtx, repositoryID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if repository == nil {
|
||||
return "", nil
|
||||
}
|
||||
return repository.Name, nil
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
|
||||
"github.com/kandev/kandev/internal/common/logger"
|
||||
"github.com/kandev/kandev/internal/task/dto"
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
"github.com/kandev/kandev/internal/task/repository/repoerrors"
|
||||
"github.com/kandev/kandev/internal/task/service"
|
||||
ws "github.com/kandev/kandev/pkg/websocket"
|
||||
)
|
||||
|
||||
type RepositoryBranchPolicyHandlers struct {
|
||||
service *service.Service
|
||||
logger *logger.Logger
|
||||
}
|
||||
|
||||
func NewRepositoryBranchPolicyHandlers(svc *service.Service, log *logger.Logger) *RepositoryBranchPolicyHandlers {
|
||||
return &RepositoryBranchPolicyHandlers{service: svc, logger: log.WithFields(zap.String("component", "task-repository-branch-policy-handlers"))}
|
||||
}
|
||||
|
||||
func RegisterRepositoryBranchPolicyRoutes(router *gin.Engine, dispatcher *ws.Dispatcher, svc *service.Service, log *logger.Logger) {
|
||||
h := NewRepositoryBranchPolicyHandlers(svc, log)
|
||||
h.registerHTTP(router)
|
||||
h.registerWS(dispatcher)
|
||||
}
|
||||
|
||||
func (h *RepositoryBranchPolicyHandlers) registerHTTP(router *gin.Engine) {
|
||||
api := router.Group("/api/v1")
|
||||
api.GET("/repositories/:id/branch-policies", h.httpList)
|
||||
api.POST("/repositories/:id/branch-policies", h.httpCreate)
|
||||
api.POST("/repositories/:id/branch-policies/gitflow", h.httpGitflow)
|
||||
api.GET("/repository-branch-policies/:id", h.httpGet)
|
||||
api.PATCH("/repository-branch-policies/:id", h.httpUpdate)
|
||||
api.DELETE("/repository-branch-policies/:id", h.httpDelete)
|
||||
}
|
||||
|
||||
func (h *RepositoryBranchPolicyHandlers) registerWS(dispatcher *ws.Dispatcher) {
|
||||
dispatcher.RegisterFunc(ws.ActionRepositoryBranchPolicyList, h.wsList)
|
||||
dispatcher.RegisterFunc(ws.ActionRepositoryBranchPolicyCreate, h.wsCreate)
|
||||
dispatcher.RegisterFunc(ws.ActionRepositoryBranchPolicyGet, h.wsGet)
|
||||
dispatcher.RegisterFunc(ws.ActionRepositoryBranchPolicyUpdate, h.wsUpdate)
|
||||
dispatcher.RegisterFunc(ws.ActionRepositoryBranchPolicyDelete, h.wsDelete)
|
||||
dispatcher.RegisterFunc(ws.ActionRepositoryBranchPolicyGitflow, h.wsGitflow)
|
||||
}
|
||||
|
||||
type repositoryBranchPolicyCreateBody struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
BaseBranch string `json:"base_branch"`
|
||||
BranchTemplate string `json:"branch_template"`
|
||||
PullRequestTarget string `json:"pull_request_target"`
|
||||
}
|
||||
|
||||
type repositoryBranchPolicyUpdateBody struct {
|
||||
Name *string `json:"name"`
|
||||
Description *string `json:"description"`
|
||||
BaseBranch *string `json:"base_branch"`
|
||||
BranchTemplate *string `json:"branch_template"`
|
||||
PullRequestTarget *string `json:"pull_request_target"`
|
||||
}
|
||||
|
||||
type repositoryBranchPolicyGitflowBody struct {
|
||||
ProductionBranch string `json:"production_branch"`
|
||||
DevelopmentBranch string `json:"development_branch"`
|
||||
}
|
||||
|
||||
func branchPolicyListResponse(policies []*models.RepositoryBranchPolicy) dto.ListRepositoryBranchPoliciesResponse {
|
||||
items := make([]dto.RepositoryBranchPolicyDTO, 0, len(policies))
|
||||
for _, policy := range policies {
|
||||
if policy != nil {
|
||||
items = append(items, dto.FromRepositoryBranchPolicy(policy))
|
||||
}
|
||||
}
|
||||
return dto.ListRepositoryBranchPoliciesResponse{Policies: items, Total: len(items)}
|
||||
}
|
||||
|
||||
func branchPolicyStatus(err error) int {
|
||||
switch {
|
||||
case errors.Is(err, service.ErrInvalidRepositoryBranchPolicy):
|
||||
return http.StatusBadRequest
|
||||
case errors.Is(err, service.ErrRepositoryBranchPolicyNameConflict),
|
||||
errors.Is(err, service.ErrRepositoryBranchPolicyAlreadySeeded),
|
||||
errors.Is(err, service.ErrRepositoryBranchPolicyReadOnly):
|
||||
return http.StatusConflict
|
||||
case errors.Is(err, repoerrors.ErrRepositoryNotFound),
|
||||
errors.Is(err, repoerrors.ErrRepositoryBranchPolicyNotFound),
|
||||
errors.Is(err, repoerrors.ErrWorkspaceNotFound):
|
||||
return http.StatusNotFound
|
||||
default:
|
||||
return http.StatusInternalServerError
|
||||
}
|
||||
}
|
||||
|
||||
func (h *RepositoryBranchPolicyHandlers) abort(c *gin.Context, action string, err error) {
|
||||
status := branchPolicyStatus(err)
|
||||
if status == http.StatusInternalServerError {
|
||||
h.logger.Error("repository branch policy request failed", zap.String("action", action), zap.Error(err))
|
||||
c.JSON(status, gin.H{"error": "failed to " + action})
|
||||
return
|
||||
}
|
||||
c.JSON(status, gin.H{"error": err.Error()})
|
||||
}
|
||||
|
||||
func (h *RepositoryBranchPolicyHandlers) httpList(c *gin.Context) {
|
||||
policies, err := h.service.ListRepositoryBranchPolicies(c.Request.Context(), c.Param("id"))
|
||||
if err != nil {
|
||||
h.abort(c, "list repository branch policies", err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, branchPolicyListResponse(policies))
|
||||
}
|
||||
|
||||
func (h *RepositoryBranchPolicyHandlers) httpCreate(c *gin.Context) {
|
||||
var body repositoryBranchPolicyCreateBody
|
||||
if err := c.ShouldBindJSON(&body); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
|
||||
return
|
||||
}
|
||||
policy, err := h.service.CreateRepositoryBranchPolicy(c.Request.Context(), &service.CreateRepositoryBranchPolicyRequest{
|
||||
RepositoryID: c.Param("id"), Name: body.Name, Description: body.Description,
|
||||
BaseBranch: body.BaseBranch, BranchTemplate: body.BranchTemplate, PullRequestTarget: body.PullRequestTarget,
|
||||
})
|
||||
if err != nil {
|
||||
h.abort(c, "create repository branch policy", err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, dto.FromRepositoryBranchPolicy(policy))
|
||||
}
|
||||
|
||||
func (h *RepositoryBranchPolicyHandlers) httpGitflow(c *gin.Context) {
|
||||
var body repositoryBranchPolicyGitflowBody
|
||||
if err := c.ShouldBindJSON(&body); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
|
||||
return
|
||||
}
|
||||
policies, err := h.service.CreateGitflowRepositoryBranchPolicies(c.Request.Context(), &service.CreateGitflowRepositoryBranchPoliciesRequest{
|
||||
RepositoryID: c.Param("id"), ProductionBranch: body.ProductionBranch, DevelopmentBranch: body.DevelopmentBranch,
|
||||
})
|
||||
if err != nil {
|
||||
h.abort(c, "seed Gitflow repository branch policies", err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, branchPolicyListResponse(policies))
|
||||
}
|
||||
|
||||
func (h *RepositoryBranchPolicyHandlers) httpGet(c *gin.Context) {
|
||||
policy, err := h.service.GetRepositoryBranchPolicy(c.Request.Context(), c.Param("id"))
|
||||
if err != nil {
|
||||
h.abort(c, "get repository branch policy", err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, dto.FromRepositoryBranchPolicy(policy))
|
||||
}
|
||||
|
||||
func (h *RepositoryBranchPolicyHandlers) httpUpdate(c *gin.Context) {
|
||||
var body repositoryBranchPolicyUpdateBody
|
||||
if err := c.ShouldBindJSON(&body); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
|
||||
return
|
||||
}
|
||||
policy, err := h.service.GetRepositoryBranchPolicy(c.Request.Context(), c.Param("id"))
|
||||
if err != nil {
|
||||
h.abort(c, "get repository branch policy", err)
|
||||
return
|
||||
}
|
||||
updated, err := h.service.UpdateRepositoryBranchPolicy(c.Request.Context(), policy.ID, &service.UpdateRepositoryBranchPolicyRequest{
|
||||
Name: body.Name, Description: body.Description, BaseBranch: body.BaseBranch,
|
||||
BranchTemplate: body.BranchTemplate, PullRequestTarget: body.PullRequestTarget,
|
||||
})
|
||||
if err != nil {
|
||||
h.abort(c, "update repository branch policy", err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, dto.FromRepositoryBranchPolicy(updated))
|
||||
}
|
||||
|
||||
func (h *RepositoryBranchPolicyHandlers) httpDelete(c *gin.Context) {
|
||||
policy, err := h.service.GetRepositoryBranchPolicy(c.Request.Context(), c.Param("id"))
|
||||
if err != nil {
|
||||
h.abort(c, "get repository branch policy", err)
|
||||
return
|
||||
}
|
||||
if err := h.service.DeleteRepositoryBranchPolicy(c.Request.Context(), policy.ID); err != nil {
|
||||
h.abort(c, "delete repository branch policy", err)
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (h *RepositoryBranchPolicyHandlers) wsError(msg *ws.Message, action string, err error) (*ws.Message, error) {
|
||||
switch branchPolicyStatus(err) {
|
||||
case http.StatusBadRequest:
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, err.Error(), taskErrorDetails(err))
|
||||
case http.StatusConflict:
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeConflict, err.Error(), taskErrorDetails(err))
|
||||
case http.StatusNotFound:
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeNotFound, err.Error(), taskErrorDetails(err))
|
||||
default:
|
||||
h.logger.Error("repository branch policy request failed", zap.String("action", action), zap.Error(err))
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to "+action, nil)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *RepositoryBranchPolicyHandlers) wsList(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
||||
var req struct {
|
||||
RepositoryID string `json:"repository_id"`
|
||||
}
|
||||
if err := msg.ParsePayload(&req); err != nil {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil)
|
||||
}
|
||||
policies, err := h.service.ListRepositoryBranchPolicies(ctx, req.RepositoryID)
|
||||
if err != nil {
|
||||
return h.wsError(msg, "list repository branch policies", err)
|
||||
}
|
||||
return ws.NewResponse(msg.ID, msg.Action, branchPolicyListResponse(policies))
|
||||
}
|
||||
|
||||
func (h *RepositoryBranchPolicyHandlers) wsCreate(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
||||
var req struct {
|
||||
RepositoryID string `json:"repository_id"`
|
||||
repositoryBranchPolicyCreateBody
|
||||
}
|
||||
if err := msg.ParsePayload(&req); err != nil {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil)
|
||||
}
|
||||
policy, err := h.service.CreateRepositoryBranchPolicy(ctx, &service.CreateRepositoryBranchPolicyRequest{
|
||||
RepositoryID: req.RepositoryID, Name: req.Name, Description: req.Description,
|
||||
BaseBranch: req.BaseBranch, BranchTemplate: req.BranchTemplate, PullRequestTarget: req.PullRequestTarget,
|
||||
})
|
||||
if err != nil {
|
||||
return h.wsError(msg, "create repository branch policy", err)
|
||||
}
|
||||
return ws.NewResponse(msg.ID, msg.Action, dto.FromRepositoryBranchPolicy(policy))
|
||||
}
|
||||
|
||||
func (h *RepositoryBranchPolicyHandlers) wsGet(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
||||
var req struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
if err := msg.ParsePayload(&req); err != nil {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil)
|
||||
}
|
||||
policy, err := h.service.GetRepositoryBranchPolicy(ctx, req.ID)
|
||||
if err != nil {
|
||||
return h.wsError(msg, "get repository branch policy", err)
|
||||
}
|
||||
return ws.NewResponse(msg.ID, msg.Action, dto.FromRepositoryBranchPolicy(policy))
|
||||
}
|
||||
|
||||
func (h *RepositoryBranchPolicyHandlers) wsUpdate(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
||||
var req struct {
|
||||
ID string `json:"id"`
|
||||
repositoryBranchPolicyUpdateBody
|
||||
}
|
||||
if err := msg.ParsePayload(&req); err != nil {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil)
|
||||
}
|
||||
updated, err := h.service.UpdateRepositoryBranchPolicy(ctx, req.ID, &service.UpdateRepositoryBranchPolicyRequest{
|
||||
Name: req.Name, Description: req.Description, BaseBranch: req.BaseBranch,
|
||||
BranchTemplate: req.BranchTemplate, PullRequestTarget: req.PullRequestTarget,
|
||||
})
|
||||
if err != nil {
|
||||
return h.wsError(msg, "update repository branch policy", err)
|
||||
}
|
||||
return ws.NewResponse(msg.ID, msg.Action, dto.FromRepositoryBranchPolicy(updated))
|
||||
}
|
||||
|
||||
func (h *RepositoryBranchPolicyHandlers) wsDelete(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
||||
var req struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
if err := msg.ParsePayload(&req); err != nil {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil)
|
||||
}
|
||||
if err := h.service.DeleteRepositoryBranchPolicy(ctx, req.ID); err != nil {
|
||||
return h.wsError(msg, "delete repository branch policy", err)
|
||||
}
|
||||
return ws.NewResponse(msg.ID, msg.Action, gin.H{"id": req.ID, "deleted": true})
|
||||
}
|
||||
|
||||
func (h *RepositoryBranchPolicyHandlers) wsGitflow(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
||||
var req struct {
|
||||
RepositoryID string `json:"repository_id"`
|
||||
repositoryBranchPolicyGitflowBody
|
||||
}
|
||||
if err := msg.ParsePayload(&req); err != nil {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil)
|
||||
}
|
||||
policies, err := h.service.CreateGitflowRepositoryBranchPolicies(ctx, &service.CreateGitflowRepositoryBranchPoliciesRequest{
|
||||
RepositoryID: req.RepositoryID, ProductionBranch: req.ProductionBranch, DevelopmentBranch: req.DevelopmentBranch,
|
||||
})
|
||||
if err != nil {
|
||||
return h.wsError(msg, "seed Gitflow repository branch policies", err)
|
||||
}
|
||||
return ws.NewResponse(msg.ID, msg.Action, branchPolicyListResponse(policies))
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jmoiron/sqlx"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/kandev/kandev/internal/common/logger"
|
||||
"github.com/kandev/kandev/internal/db"
|
||||
"github.com/kandev/kandev/internal/events/bus"
|
||||
"github.com/kandev/kandev/internal/task/dto"
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
"github.com/kandev/kandev/internal/task/repository"
|
||||
taskrepo "github.com/kandev/kandev/internal/task/repository/sqlite"
|
||||
"github.com/kandev/kandev/internal/task/service"
|
||||
ws "github.com/kandev/kandev/pkg/websocket"
|
||||
)
|
||||
|
||||
func newRepositoryBranchPolicyTestRouter(t *testing.T, workspaceName string) (*gin.Engine, *ws.Dispatcher, *taskrepo.Repository) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
dbConn, err := db.OpenSQLite(filepath.Join(t.TempDir(), "branch-policies.db"))
|
||||
require.NoError(t, err)
|
||||
sqlxDB := sqlx.NewDb(dbConn, "sqlite3")
|
||||
repo, cleanup, err := repository.Provide(sqlxDB, sqlxDB, nil)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() {
|
||||
require.NoError(t, cleanup())
|
||||
require.NoError(t, sqlxDB.Close())
|
||||
})
|
||||
|
||||
ctx := context.Background()
|
||||
require.NoError(t, repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws-policy-handler", Name: workspaceName}))
|
||||
repositoryPath := initBranchPolicyGitRepository(t)
|
||||
require.NoError(t, repo.CreateRepository(ctx, &models.Repository{
|
||||
ID: "repo-policy-handler", WorkspaceID: "ws-policy-handler", Name: "policy-repo",
|
||||
SourceType: "local", LocalPath: repositoryPath, DefaultBranch: "main",
|
||||
}))
|
||||
|
||||
log, err := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "json", OutputPath: "stdout"})
|
||||
require.NoError(t, err)
|
||||
svc := service.NewService(service.Repos{
|
||||
Workspaces: repo, RepoEntities: repo, BranchPolicies: repo,
|
||||
}, bus.NewMemoryEventBus(log), log, service.RepositoryDiscoveryConfig{})
|
||||
router := gin.New()
|
||||
dispatcher := ws.NewDispatcher()
|
||||
RegisterRepositoryBranchPolicyRoutes(router, dispatcher, svc, log)
|
||||
return router, dispatcher, repo
|
||||
}
|
||||
|
||||
func initBranchPolicyGitRepository(t *testing.T) string {
|
||||
t.Helper()
|
||||
repositoryPath := filepath.Join(t.TempDir(), "repository")
|
||||
require.NoError(t, os.MkdirAll(repositoryPath, 0o755))
|
||||
runGit := func(args ...string) {
|
||||
t.Helper()
|
||||
cmd := exec.Command("git", args...)
|
||||
cmd.Dir = repositoryPath
|
||||
cmd.Env = append(os.Environ(), "GIT_CONFIG_NOSYSTEM=1")
|
||||
output, err := cmd.CombinedOutput()
|
||||
require.NoErrorf(t, err, "git %v failed: %s", args, output)
|
||||
}
|
||||
runGit("init", "-b", "main")
|
||||
require.NoError(t, os.WriteFile(filepath.Join(repositoryPath, "README.md"), []byte("branch policy test\n"), 0o644))
|
||||
runGit("config", "user.email", "test@example.com")
|
||||
runGit("config", "user.name", "Kandev Tests")
|
||||
runGit("add", "README.md")
|
||||
runGit("commit", "-m", "initial")
|
||||
runGit("branch", "develop")
|
||||
return repositoryPath
|
||||
}
|
||||
|
||||
func seedHandlerBranchPolicy(t *testing.T, repo *taskrepo.Repository) *models.RepositoryBranchPolicy {
|
||||
t.Helper()
|
||||
policy := &models.RepositoryBranchPolicy{
|
||||
ID: "policy-handler-existing", RepositoryID: "repo-policy-handler", Name: "Existing",
|
||||
Description: "Existing policy", BaseBranch: "main", BranchTemplate: "feature/{title}-{suffix}",
|
||||
PullRequestTarget: "main",
|
||||
}
|
||||
require.NoError(t, repo.CreateRepositoryBranchPolicy(context.Background(), policy))
|
||||
return policy
|
||||
}
|
||||
|
||||
func dispatchBranchPolicyAction(t *testing.T, dispatcher *ws.Dispatcher, action string, payload any) *ws.Message {
|
||||
t.Helper()
|
||||
message, err := ws.NewRequest("branch-policy-test", action, payload)
|
||||
require.NoError(t, err)
|
||||
response, err := dispatcher.Dispatch(context.Background(), message)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, response)
|
||||
return response
|
||||
}
|
||||
|
||||
func requireBranchPolicyWSConflict(t *testing.T, response *ws.Message) {
|
||||
t.Helper()
|
||||
require.Equal(t, ws.MessageTypeError, response.Type)
|
||||
var payload ws.ErrorPayload
|
||||
require.NoError(t, json.Unmarshal(response.Payload, &payload))
|
||||
require.Equal(t, ws.ErrorCodeConflict, payload.Code)
|
||||
require.Contains(t, payload.Message, "Improve Kandev")
|
||||
}
|
||||
|
||||
func TestRepositoryBranchPolicyHTTPHandlersCoverCRUDAndStatusMappings(t *testing.T) {
|
||||
router, _, _ := newRepositoryBranchPolicyTestRouter(t, "Policy workspace")
|
||||
|
||||
list := doJSON(t, router, http.MethodGet, "/api/v1/repositories/repo-policy-handler/branch-policies", nil)
|
||||
require.Equal(t, http.StatusOK, list.Code, list.Body.String())
|
||||
var empty dto.ListRepositoryBranchPoliciesResponse
|
||||
require.NoError(t, json.Unmarshal(list.Body.Bytes(), &empty))
|
||||
require.Empty(t, empty.Policies)
|
||||
|
||||
createdResponse := doJSON(t, router, http.MethodPost, "/api/v1/repositories/repo-policy-handler/branch-policies", map[string]any{
|
||||
"name": "Feature", "description": "Feature branches", "base_branch": "develop",
|
||||
"branch_template": "feature/{title}-{suffix}", "pull_request_target": "develop",
|
||||
})
|
||||
require.Equal(t, http.StatusCreated, createdResponse.Code, createdResponse.Body.String())
|
||||
var created dto.RepositoryBranchPolicyDTO
|
||||
require.NoError(t, json.Unmarshal(createdResponse.Body.Bytes(), &created))
|
||||
require.Equal(t, "Feature", created.Name)
|
||||
require.Equal(t, "develop", created.PullRequestTarget)
|
||||
|
||||
get := doJSON(t, router, http.MethodGet, "/api/v1/repository-branch-policies/"+created.ID, nil)
|
||||
require.Equal(t, http.StatusOK, get.Code, get.Body.String())
|
||||
|
||||
updated := doJSON(t, router, http.MethodPatch, "/api/v1/repository-branch-policies/"+created.ID, map[string]any{
|
||||
"description": "Updated description", "pull_request_target": "main",
|
||||
})
|
||||
require.Equal(t, http.StatusOK, updated.Code, updated.Body.String())
|
||||
var updatedPolicy dto.RepositoryBranchPolicyDTO
|
||||
require.NoError(t, json.Unmarshal(updated.Body.Bytes(), &updatedPolicy))
|
||||
require.Equal(t, "Updated description", updatedPolicy.Description)
|
||||
require.Equal(t, "main", updatedPolicy.PullRequestTarget)
|
||||
|
||||
duplicate := doJSON(t, router, http.MethodPost, "/api/v1/repositories/repo-policy-handler/branch-policies", map[string]any{
|
||||
"name": "feature", "base_branch": "main", "branch_template": "feature/{title}-{suffix}",
|
||||
"pull_request_target": "main",
|
||||
})
|
||||
require.Equal(t, http.StatusConflict, duplicate.Code, duplicate.Body.String())
|
||||
|
||||
invalid := doJSON(t, router, http.MethodPost, "/api/v1/repositories/repo-policy-handler/branch-policies", []string{"invalid"})
|
||||
require.Equal(t, http.StatusBadRequest, invalid.Code, invalid.Body.String())
|
||||
|
||||
missing := doJSON(t, router, http.MethodGet, "/api/v1/repository-branch-policies/missing", nil)
|
||||
require.Equal(t, http.StatusNotFound, missing.Code, missing.Body.String())
|
||||
|
||||
deleted := doJSON(t, router, http.MethodDelete, "/api/v1/repository-branch-policies/"+created.ID, nil)
|
||||
require.Equal(t, http.StatusNoContent, deleted.Code, deleted.Body.String())
|
||||
}
|
||||
|
||||
func TestRepositoryBranchPolicyHTTPGitflowMapsConflicts(t *testing.T) {
|
||||
router, _, _ := newRepositoryBranchPolicyTestRouter(t, "Policy workspace")
|
||||
body := map[string]any{"production_branch": "main", "development_branch": "develop"}
|
||||
|
||||
created := doJSON(t, router, http.MethodPost, "/api/v1/repositories/repo-policy-handler/branch-policies/gitflow", body)
|
||||
require.Equal(t, http.StatusCreated, created.Code, created.Body.String())
|
||||
var response dto.ListRepositoryBranchPoliciesResponse
|
||||
require.NoError(t, json.Unmarshal(created.Body.Bytes(), &response))
|
||||
require.Len(t, response.Policies, 4)
|
||||
|
||||
conflict := doJSON(t, router, http.MethodPost, "/api/v1/repositories/repo-policy-handler/branch-policies/gitflow", body)
|
||||
require.Equal(t, http.StatusConflict, conflict.Code, conflict.Body.String())
|
||||
}
|
||||
|
||||
func TestRepositoryBranchPolicyWSHandlersCoverCRUDAndGitflow(t *testing.T) {
|
||||
_, dispatcher, _ := newRepositoryBranchPolicyTestRouter(t, "Policy workspace")
|
||||
createPayload := map[string]any{
|
||||
"repository_id": "repo-policy-handler", "name": "Feature", "description": "Feature branches",
|
||||
"base_branch": "develop", "branch_template": "feature/{title}-{suffix}", "pull_request_target": "develop",
|
||||
}
|
||||
created := dispatchBranchPolicyAction(t, dispatcher, ws.ActionRepositoryBranchPolicyCreate, createPayload)
|
||||
require.NotEqual(t, ws.MessageTypeError, created.Type, string(created.Payload))
|
||||
var policy dto.RepositoryBranchPolicyDTO
|
||||
require.NoError(t, json.Unmarshal(created.Payload, &policy))
|
||||
|
||||
list := dispatchBranchPolicyAction(t, dispatcher, ws.ActionRepositoryBranchPolicyList, map[string]any{"repository_id": "repo-policy-handler"})
|
||||
require.NotEqual(t, ws.MessageTypeError, list.Type, string(list.Payload))
|
||||
get := dispatchBranchPolicyAction(t, dispatcher, ws.ActionRepositoryBranchPolicyGet, map[string]any{"id": policy.ID})
|
||||
require.NotEqual(t, ws.MessageTypeError, get.Type, string(get.Payload))
|
||||
update := dispatchBranchPolicyAction(t, dispatcher, ws.ActionRepositoryBranchPolicyUpdate, map[string]any{
|
||||
"id": policy.ID, "description": "Updated", "pull_request_target": "main",
|
||||
})
|
||||
require.NotEqual(t, ws.MessageTypeError, update.Type, string(update.Payload))
|
||||
deleted := dispatchBranchPolicyAction(t, dispatcher, ws.ActionRepositoryBranchPolicyDelete, map[string]any{"id": policy.ID})
|
||||
require.NotEqual(t, ws.MessageTypeError, deleted.Type, string(deleted.Payload))
|
||||
|
||||
gitflow := dispatchBranchPolicyAction(t, dispatcher, ws.ActionRepositoryBranchPolicyGitflow, map[string]any{
|
||||
"repository_id": "repo-policy-handler", "production_branch": "main", "development_branch": "develop",
|
||||
})
|
||||
require.NotEqual(t, ws.MessageTypeError, gitflow.Type, string(gitflow.Payload))
|
||||
gitflowConflict := dispatchBranchPolicyAction(t, dispatcher, ws.ActionRepositoryBranchPolicyGitflow, map[string]any{
|
||||
"repository_id": "repo-policy-handler", "production_branch": "main", "development_branch": "develop",
|
||||
})
|
||||
require.Equal(t, ws.MessageTypeError, gitflowConflict.Type)
|
||||
var conflictPayload ws.ErrorPayload
|
||||
require.NoError(t, json.Unmarshal(gitflowConflict.Payload, &conflictPayload))
|
||||
require.Equal(t, ws.ErrorCodeConflict, conflictPayload.Code)
|
||||
}
|
||||
|
||||
func TestRepositoryBranchPolicyHandlersRejectImproveWorkspaceMutations(t *testing.T) {
|
||||
router, dispatcher, repo := newRepositoryBranchPolicyTestRouter(t, models.WorkspaceNameImproveKandev)
|
||||
policy := seedHandlerBranchPolicy(t, repo)
|
||||
|
||||
create := doJSON(t, router, http.MethodPost, "/api/v1/repositories/repo-policy-handler/branch-policies", map[string]any{
|
||||
"name": "Blocked", "base_branch": "main", "branch_template": "feature/{title}-{suffix}",
|
||||
"pull_request_target": "main",
|
||||
})
|
||||
require.Equal(t, http.StatusConflict, create.Code, create.Body.String())
|
||||
|
||||
update := doJSON(t, router, http.MethodPatch, "/api/v1/repository-branch-policies/"+policy.ID, map[string]any{"name": "Renamed"})
|
||||
require.Equal(t, http.StatusConflict, update.Code, update.Body.String())
|
||||
delete := doJSON(t, router, http.MethodDelete, "/api/v1/repository-branch-policies/"+policy.ID, nil)
|
||||
require.Equal(t, http.StatusConflict, delete.Code, delete.Body.String())
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
action string
|
||||
payload any
|
||||
}{
|
||||
{"create", ws.ActionRepositoryBranchPolicyCreate, map[string]any{
|
||||
"repository_id": "repo-policy-handler", "name": "Blocked", "base_branch": "main",
|
||||
"branch_template": "feature/{title}-{suffix}", "pull_request_target": "main",
|
||||
}},
|
||||
{"update", ws.ActionRepositoryBranchPolicyUpdate, map[string]any{"id": policy.ID, "name": "Renamed"}},
|
||||
{"delete", ws.ActionRepositoryBranchPolicyDelete, map[string]any{"id": policy.ID}},
|
||||
{"gitflow", ws.ActionRepositoryBranchPolicyGitflow, map[string]any{
|
||||
"repository_id": "repo-policy-handler", "production_branch": "main", "development_branch": "develop",
|
||||
}},
|
||||
}
|
||||
for _, testCase := range cases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
requireBranchPolicyWSConflict(t, dispatchBranchPolicyAction(t, dispatcher, testCase.action, testCase.payload))
|
||||
})
|
||||
}
|
||||
|
||||
list := doJSON(t, router, http.MethodGet, "/api/v1/repositories/repo-policy-handler/branch-policies", nil)
|
||||
require.Equal(t, http.StatusOK, list.Code, list.Body.String())
|
||||
var policies dto.ListRepositoryBranchPoliciesResponse
|
||||
require.NoError(t, json.Unmarshal(list.Body.Bytes(), &policies))
|
||||
require.Len(t, policies.Policies, 1)
|
||||
require.Equal(t, policy.ID, policies.Policies[0].ID)
|
||||
}
|
||||
@@ -226,19 +226,21 @@ func convertToServiceRepos(repos []dto.TaskRepositoryInput) []service.TaskReposi
|
||||
result := make([]service.TaskRepositoryInput, len(repos))
|
||||
for i, r := range repos {
|
||||
result[i] = service.TaskRepositoryInput{
|
||||
RepositoryID: r.RepositoryID,
|
||||
BaseBranch: r.BaseBranch,
|
||||
CheckoutBranch: r.CheckoutBranch,
|
||||
PRNumber: r.PRNumber,
|
||||
LocalPath: r.LocalPath,
|
||||
Name: r.Name,
|
||||
DefaultBranch: r.DefaultBranch,
|
||||
GitHubURL: r.GitHubURL,
|
||||
RemoteURL: r.RemoteURL,
|
||||
Provider: r.Provider,
|
||||
ProviderRepoID: r.ProviderRepoID,
|
||||
ProviderOwner: r.ProviderOwner,
|
||||
ProviderName: r.ProviderName,
|
||||
RepositoryID: r.RepositoryID,
|
||||
BaseBranch: r.BaseBranch,
|
||||
CheckoutBranch: r.CheckoutBranch,
|
||||
BranchPolicyID: r.BranchPolicyID,
|
||||
PRNumber: r.PRNumber,
|
||||
LocalPath: r.LocalPath,
|
||||
Name: r.Name,
|
||||
DefaultBranch: r.DefaultBranch,
|
||||
GitHubURL: r.GitHubURL,
|
||||
RemoteURL: r.RemoteURL,
|
||||
Provider: r.Provider,
|
||||
ProviderRepoID: r.ProviderRepoID,
|
||||
ProviderOwner: r.ProviderOwner,
|
||||
ProviderName: r.ProviderName,
|
||||
PreserveBaseBranch: r.PreserveBaseBranch,
|
||||
}
|
||||
}
|
||||
return result
|
||||
|
||||
@@ -693,6 +693,7 @@ type httpTaskRepositoryInput struct {
|
||||
RepositoryID string `json:"repository_id"`
|
||||
BaseBranch string `json:"base_branch"`
|
||||
CheckoutBranch string `json:"checkout_branch"`
|
||||
BranchPolicyID string `json:"branch_policy_id,omitempty"`
|
||||
PRNumber int `json:"pr_number,omitempty"`
|
||||
LocalPath string `json:"local_path"`
|
||||
Name string `json:"name"`
|
||||
@@ -1197,7 +1198,7 @@ func (h *TaskHandlers) commitFreshBranch(
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to resolve task repository"})
|
||||
return false
|
||||
}
|
||||
if !h.applyFreshBranch(c, title, inputs, repos, task.Repositories) {
|
||||
if !h.applyFreshBranch(c, title, task, inputs, repos, task.Repositories) {
|
||||
h.rollbackFreshBranchTask(c.Request.Context(), taskID)
|
||||
return false
|
||||
}
|
||||
@@ -1237,6 +1238,7 @@ func (h *TaskHandlers) rollbackFreshBranchTask(ctx context.Context, taskID strin
|
||||
func (h *TaskHandlers) applyFreshBranch(
|
||||
c *gin.Context,
|
||||
taskTitle string,
|
||||
task *models.Task,
|
||||
inputs []httpTaskRepositoryInput,
|
||||
repos []dto.TaskRepositoryInput,
|
||||
persisted []*models.TaskRepository,
|
||||
@@ -1256,7 +1258,7 @@ func (h *TaskHandlers) applyFreshBranch(
|
||||
// User didn't pick one — fall back to the repo's checked-out branch.
|
||||
baseBranch, _ = h.service.RepositoryCurrentBranch(ctx, repositoryID)
|
||||
}
|
||||
newBranch := resolveFreshBranchName(raw.NewBranchName, taskTitle)
|
||||
newBranch := resolveFreshBranchNameForTask(raw.NewBranchName, taskTitle, task, persisted[i])
|
||||
err := h.service.PerformFreshBranch(ctx, service.FreshBranchRequest{
|
||||
RepositoryID: repositoryID,
|
||||
BaseBranch: baseBranch,
|
||||
@@ -1270,6 +1272,7 @@ func (h *TaskHandlers) applyFreshBranch(
|
||||
}
|
||||
repos[i].BaseBranch = newBranch
|
||||
repos[i].CheckoutBranch = ""
|
||||
repos[i].PreserveBaseBranch = true
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -1286,6 +1289,25 @@ func resolveFreshBranchName(rawNewBranch, taskTitle string) string {
|
||||
return worktree.SemanticWorktreeName(taskTitle, worktree.SmallSuffix(3))
|
||||
}
|
||||
|
||||
func resolveFreshBranchNameForTask(rawNewBranch, taskTitle string, task *models.Task, taskRepository *models.TaskRepository) string {
|
||||
if name := strings.TrimSpace(rawNewBranch); name != "" {
|
||||
return name
|
||||
}
|
||||
if task != nil && taskRepository != nil && taskRepository.BranchPolicyBranchTemplate != "" {
|
||||
branch, err := worktree.RenderTaskBranchName(worktree.BranchNameTemplateInput{
|
||||
Template: taskRepository.BranchPolicyBranchTemplate,
|
||||
TaskID: task.ID,
|
||||
Title: taskTitle,
|
||||
Ticket: worktree.TicketForBranchName(task.Identifier, task.Metadata),
|
||||
Suffix: worktree.SmallSuffix(3),
|
||||
})
|
||||
if err == nil {
|
||||
return branch
|
||||
}
|
||||
}
|
||||
return resolveFreshBranchName("", taskTitle)
|
||||
}
|
||||
|
||||
func (h *TaskHandlers) respondFreshBranchError(c *gin.Context, err error) {
|
||||
var dirty *service.ErrDirtyWorkingTree
|
||||
if errors.As(err, &dirty) {
|
||||
@@ -1332,6 +1354,7 @@ func convertCreateTaskRepositories(c *gin.Context, inputs []httpTaskRepositoryIn
|
||||
RepositoryID: r.RepositoryID,
|
||||
BaseBranch: r.BaseBranch,
|
||||
CheckoutBranch: r.CheckoutBranch,
|
||||
BranchPolicyID: r.BranchPolicyID,
|
||||
PRNumber: r.PRNumber,
|
||||
LocalPath: r.LocalPath,
|
||||
Name: r.Name,
|
||||
@@ -1559,6 +1582,7 @@ func (h *TaskHandlers) httpUpdateTask(c *gin.Context) {
|
||||
RepositoryID: r.RepositoryID,
|
||||
BaseBranch: r.BaseBranch,
|
||||
CheckoutBranch: r.CheckoutBranch,
|
||||
BranchPolicyID: r.BranchPolicyID,
|
||||
PRNumber: r.PRNumber,
|
||||
LocalPath: r.LocalPath,
|
||||
Name: r.Name,
|
||||
|
||||
@@ -1657,6 +1657,22 @@ func TestResolveFreshBranchName(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveFreshBranchNameForTaskUsesPolicySnapshot(t *testing.T) {
|
||||
task := &models.Task{
|
||||
ID: "task-123",
|
||||
Identifier: "KAN-7",
|
||||
Metadata: map[string]interface{}{},
|
||||
}
|
||||
taskRepository := &models.TaskRepository{
|
||||
BranchPolicyBranchTemplate: "bugfix/{ticket}-{title}-{suffix}",
|
||||
}
|
||||
|
||||
got := resolveFreshBranchNameForTask("", "Fix login", task, taskRepository)
|
||||
if !strings.HasPrefix(got, "bugfix/kan-7-fix-login-") {
|
||||
t.Fatalf("policy branch = %q, want bugfix/kan-7-fix-login-*", got)
|
||||
}
|
||||
}
|
||||
|
||||
type freshBranchIdentityRepository struct {
|
||||
mockRepository
|
||||
task *models.Task
|
||||
|
||||
@@ -133,6 +133,7 @@ func (h *TaskHandlers) wsCreateTask(ctx context.Context, msg *ws.Message) (*ws.M
|
||||
RepositoryID: r.RepositoryID,
|
||||
BaseBranch: r.BaseBranch,
|
||||
CheckoutBranch: r.CheckoutBranch,
|
||||
BranchPolicyID: r.BranchPolicyID,
|
||||
PRNumber: r.PRNumber,
|
||||
LocalPath: r.LocalPath,
|
||||
Name: r.Name,
|
||||
@@ -195,7 +196,7 @@ func (h *TaskHandlers) wsCreateTask(ctx context.Context, msg *ws.Message) (*ws.M
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeConflict, err.Error(), nil)
|
||||
}
|
||||
if isTaskCreateValidationError(err) {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, err.Error(), nil)
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, err.Error(), taskErrorDetails(err))
|
||||
}
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to create task", nil)
|
||||
}
|
||||
@@ -301,6 +302,7 @@ func (h *TaskHandlers) wsUpdateTask(ctx context.Context, msg *ws.Message) (*ws.M
|
||||
RepositoryID: r.RepositoryID,
|
||||
BaseBranch: r.BaseBranch,
|
||||
CheckoutBranch: r.CheckoutBranch,
|
||||
BranchPolicyID: r.BranchPolicyID,
|
||||
PRNumber: r.PRNumber,
|
||||
LocalPath: r.LocalPath,
|
||||
Name: r.Name,
|
||||
|
||||
@@ -1020,15 +1020,20 @@ type Workspace struct {
|
||||
|
||||
// TaskRepository represents a repository associated with a task
|
||||
type TaskRepository struct {
|
||||
ID string `json:"id"`
|
||||
TaskID string `json:"task_id"`
|
||||
RepositoryID string `json:"repository_id"`
|
||||
BaseBranch string `json:"base_branch"`
|
||||
CheckoutBranch string `json:"checkout_branch,omitempty"`
|
||||
Position int `json:"position"`
|
||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
ID string `json:"id"`
|
||||
TaskID string `json:"task_id"`
|
||||
RepositoryID string `json:"repository_id"`
|
||||
BaseBranch string `json:"base_branch"`
|
||||
CheckoutBranch string `json:"checkout_branch,omitempty"`
|
||||
BranchPolicyID string `json:"branch_policy_id,omitempty"`
|
||||
BranchPolicyName string `json:"branch_policy_name,omitempty"`
|
||||
BranchPolicyBaseBranch string `json:"branch_policy_base_branch,omitempty"`
|
||||
BranchPolicyBranchTemplate string `json:"branch_policy_branch_template,omitempty"`
|
||||
BranchPolicyPullRequestTarget string `json:"branch_policy_pull_request_target,omitempty"`
|
||||
Position int `json:"position"`
|
||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// TaskWorkspaceFolder is a canonical host-folder attachment owned by a task.
|
||||
@@ -1656,6 +1661,21 @@ type Repository struct {
|
||||
DeletedAt *time.Time `json:"deleted_at,omitempty"`
|
||||
}
|
||||
|
||||
// RepositoryBranchPolicy is a reusable branch workflow owned by one repository.
|
||||
// It is configuration, not task history: task repositories copy these fields
|
||||
// into their snapshot columns when a policy is selected.
|
||||
type RepositoryBranchPolicy struct {
|
||||
ID string `json:"id"`
|
||||
RepositoryID string `json:"repository_id"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description,omitempty"`
|
||||
BaseBranch string `json:"base_branch"`
|
||||
BranchTemplate string `json:"branch_template"`
|
||||
PullRequestTarget string `json:"pull_request_target"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// RepositorySet is a named, reusable group of workspace repositories that fills
|
||||
// the task-creation repository picker in one action.
|
||||
//
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package promptcontext
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/kandev/kandev/internal/sysprompt"
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
)
|
||||
|
||||
// RepositoryNameResolver resolves a repository's display name for prompt context.
|
||||
// An error leaves the repository ID as the stable fallback name.
|
||||
type RepositoryNameResolver func(context.Context, string) (string, error)
|
||||
|
||||
// BuildPullRequestTargets converts task repository snapshots into the prompt
|
||||
// context used by both task orchestration and task message handlers.
|
||||
func BuildPullRequestTargets(
|
||||
ctx context.Context,
|
||||
links []*models.TaskRepository,
|
||||
resolveRepositoryName RepositoryNameResolver,
|
||||
) []sysprompt.PullRequestTarget {
|
||||
targets := make([]sysprompt.PullRequestTarget, 0, len(links))
|
||||
for _, link := range links {
|
||||
if link == nil || link.BranchPolicyID == "" || link.BranchPolicyPullRequestTarget == "" {
|
||||
continue
|
||||
}
|
||||
repositoryName := link.RepositoryID
|
||||
if resolveRepositoryName != nil {
|
||||
if name, err := resolveRepositoryName(ctx, link.RepositoryID); err == nil && name != "" {
|
||||
repositoryName = name
|
||||
}
|
||||
}
|
||||
workingBranch := link.CheckoutBranch
|
||||
if workingBranch == "" {
|
||||
workingBranch = link.BaseBranch
|
||||
}
|
||||
targets = append(targets, sysprompt.PullRequestTarget{
|
||||
RepositoryName: repositoryName,
|
||||
WorkingBranch: workingBranch,
|
||||
TargetBranch: link.BranchPolicyPullRequestTarget,
|
||||
})
|
||||
}
|
||||
return targets
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package promptcontext
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/kandev/kandev/internal/sysprompt"
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestBuildPullRequestTargets(t *testing.T) {
|
||||
links := []*models.TaskRepository{
|
||||
{RepositoryID: "repo-1", BaseBranch: "develop", CheckoutBranch: "feature/task", BranchPolicyID: "policy-1", BranchPolicyPullRequestTarget: "main"},
|
||||
{RepositoryID: "repo-2", BaseBranch: "main", BranchPolicyID: "policy-2", BranchPolicyPullRequestTarget: "release"},
|
||||
{RepositoryID: "repo-3", BranchPolicyID: "policy-3"},
|
||||
{RepositoryID: "repo-4", BranchPolicyPullRequestTarget: "main"},
|
||||
nil,
|
||||
}
|
||||
|
||||
targets := BuildPullRequestTargets(context.Background(), links, func(_ context.Context, repositoryID string) (string, error) {
|
||||
if repositoryID == "repo-2" {
|
||||
return "", errors.New("repository unavailable")
|
||||
}
|
||||
return "repo-1-name", nil
|
||||
})
|
||||
|
||||
require.Equal(t, []sysprompt.PullRequestTarget{
|
||||
{RepositoryName: "repo-1-name", WorkingBranch: "feature/task", TargetBranch: "main"},
|
||||
{RepositoryName: "repo-2", WorkingBranch: "main", TargetBranch: "release"},
|
||||
}, targets)
|
||||
}
|
||||
@@ -446,6 +446,19 @@ type RepositorySetRepository interface {
|
||||
DeleteRepositorySet(ctx context.Context, id string) (bool, error)
|
||||
}
|
||||
|
||||
// RepositoryBranchPolicyRepository stores reusable branch workflows owned by
|
||||
// a repository. The batch method is an atomic, one-time Gitflow starter.
|
||||
type RepositoryBranchPolicyRepository interface {
|
||||
CreateRepositoryBranchPolicy(ctx context.Context, policy *models.RepositoryBranchPolicy) error
|
||||
GetRepositoryBranchPolicy(ctx context.Context, id string) (*models.RepositoryBranchPolicy, error)
|
||||
GetRepositoryBranchPolicyByName(ctx context.Context, repositoryID, name string) (*models.RepositoryBranchPolicy, error)
|
||||
ListRepositoryBranchPolicies(ctx context.Context, repositoryID string) ([]*models.RepositoryBranchPolicy, error)
|
||||
ListRepositoryBranchPoliciesByWorkspace(ctx context.Context, workspaceID string) ([]*models.RepositoryBranchPolicy, error)
|
||||
UpdateRepositoryBranchPolicy(ctx context.Context, policy *models.RepositoryBranchPolicy) error
|
||||
DeleteRepositoryBranchPolicy(ctx context.Context, id string) (bool, error)
|
||||
CreateRepositoryBranchPoliciesIfEmpty(ctx context.Context, repositoryID string, policies []*models.RepositoryBranchPolicy) error
|
||||
}
|
||||
|
||||
// RepositorySecretBindingRepository stores normalized repository environment
|
||||
// references. It is optional on RepositoryEntityRepository to keep legacy
|
||||
// adapters source-compatible while the SQLite implementation rolls out.
|
||||
|
||||
@@ -25,6 +25,13 @@ var ErrRepositoryNotFound = errors.New("repository not found")
|
||||
// ErrRepositorySetNotFound reports that no repository set row matched the supplied id.
|
||||
var ErrRepositorySetNotFound = errors.New("repository set not found")
|
||||
|
||||
// ErrRepositoryBranchPolicyNotFound reports that no policy row matched the id.
|
||||
var ErrRepositoryBranchPolicyNotFound = errors.New("repository branch policy not found")
|
||||
|
||||
// ErrRepositoryBranchPoliciesExist reports that a Gitflow starter cannot seed
|
||||
// a repository that already has one or more policies.
|
||||
var ErrRepositoryBranchPoliciesExist = errors.New("repository branch policies already exist")
|
||||
|
||||
// ErrTaskEnvironmentNotFound reports that no task environment row matched the supplied id.
|
||||
var ErrTaskEnvironmentNotFound = errors.New("task environment not found")
|
||||
|
||||
|
||||
@@ -60,6 +60,9 @@ func (r *Repository) runMigrations() error {
|
||||
if err := r.ensureRepositorySetsSchema(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := r.ensureRepositoryBranchPoliciesSchema(); err != nil {
|
||||
return err
|
||||
}
|
||||
r.migrate.Apply("task_sessions.execution_profile_id", `ALTER TABLE task_sessions ADD COLUMN execution_profile_id TEXT NOT NULL DEFAULT ''`)
|
||||
r.migrate.Apply("task_sessions.route_generation", `ALTER TABLE task_sessions ADD COLUMN route_generation INTEGER NOT NULL DEFAULT 0`)
|
||||
r.migrate.Apply("task_sessions.route_state", `ALTER TABLE task_sessions ADD COLUMN route_state TEXT NOT NULL DEFAULT ''`)
|
||||
@@ -77,6 +80,11 @@ func (r *Repository) runMigrations() error {
|
||||
r.migrate.Apply("executors_running.local_pid", `ALTER TABLE executors_running ADD COLUMN local_pid INTEGER DEFAULT 0`)
|
||||
r.migrate.Apply("tasks.is_ephemeral", `ALTER TABLE tasks ADD COLUMN is_ephemeral INTEGER NOT NULL DEFAULT 0`)
|
||||
r.migrate.Apply("task_repositories.checkout_branch", `ALTER TABLE task_repositories ADD COLUMN checkout_branch TEXT DEFAULT ''`)
|
||||
r.migrate.Apply("task_repositories.branch_policy_id", `ALTER TABLE task_repositories ADD COLUMN branch_policy_id TEXT DEFAULT ''`)
|
||||
r.migrate.Apply("task_repositories.branch_policy_name", `ALTER TABLE task_repositories ADD COLUMN branch_policy_name TEXT DEFAULT ''`)
|
||||
r.migrate.Apply("task_repositories.branch_policy_base_branch", `ALTER TABLE task_repositories ADD COLUMN branch_policy_base_branch TEXT DEFAULT ''`)
|
||||
r.migrate.Apply("task_repositories.branch_policy_branch_template", `ALTER TABLE task_repositories ADD COLUMN branch_policy_branch_template TEXT DEFAULT ''`)
|
||||
r.migrate.Apply("task_repositories.branch_policy_pull_request_target", `ALTER TABLE task_repositories ADD COLUMN branch_policy_pull_request_target TEXT DEFAULT ''`)
|
||||
// Multi-branch support: drop the old UNIQUE(task_id, repository_id) and
|
||||
// replace it with UNIQUE(task_id, repository_id, checkout_branch) so the
|
||||
// same repo can appear multiple times in a task on different branches.
|
||||
@@ -590,6 +598,15 @@ func (r *Repository) ensureRepositorySetsSchema() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// ensureRepositoryBranchPoliciesSchema replays the policy DDL for databases
|
||||
// created before repository branch policies existed.
|
||||
func (r *Repository) ensureRepositoryBranchPoliciesSchema() error {
|
||||
if _, err := r.db.Exec(repositoryBranchPoliciesSchemaDDL); err != nil {
|
||||
return fmt.Errorf("create repository branch policies schema: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// recreateTable checks whether tableName's DDL contains triggerPhrase and, if so,
|
||||
// runs statements inside a transaction with FK enforcement disabled.
|
||||
// This is the standard SQLite pattern for dropping columns or FK constraints,
|
||||
@@ -1058,6 +1075,11 @@ func (r *Repository) recreateTaskRepositoriesForMultiBranch(trigger string) erro
|
||||
repository_id TEXT NOT NULL,
|
||||
base_branch TEXT DEFAULT '',
|
||||
checkout_branch TEXT DEFAULT '',
|
||||
branch_policy_id TEXT DEFAULT '',
|
||||
branch_policy_name TEXT DEFAULT '',
|
||||
branch_policy_base_branch TEXT DEFAULT '',
|
||||
branch_policy_branch_template TEXT DEFAULT '',
|
||||
branch_policy_pull_request_target TEXT DEFAULT '',
|
||||
position INTEGER DEFAULT 0,
|
||||
metadata TEXT DEFAULT '{}',
|
||||
created_at TIMESTAMP NOT NULL,
|
||||
@@ -1069,6 +1091,9 @@ func (r *Repository) recreateTaskRepositoriesForMultiBranch(trigger string) erro
|
||||
`INSERT INTO task_repositories_new SELECT
|
||||
id, task_id, repository_id, base_branch,
|
||||
COALESCE(checkout_branch, ''),
|
||||
COALESCE(branch_policy_id, ''), COALESCE(branch_policy_name, ''),
|
||||
COALESCE(branch_policy_base_branch, ''), COALESCE(branch_policy_branch_template, ''),
|
||||
COALESCE(branch_policy_pull_request_target, ''),
|
||||
position, metadata, created_at, updated_at
|
||||
FROM task_repositories`,
|
||||
`DROP TABLE task_repositories`,
|
||||
|
||||
@@ -17,6 +17,7 @@ func (r *Repository) initSchema() error {
|
||||
steps := []func() error{
|
||||
r.initCoreSchema,
|
||||
r.initRepositorySetsSchema,
|
||||
r.initRepositoryBranchPoliciesSchema,
|
||||
r.initPlansSchema,
|
||||
r.initWalkthroughsSchema,
|
||||
r.initDocumentsSchema,
|
||||
@@ -424,6 +425,11 @@ func (r *Repository) initTaskSchema() error {
|
||||
repository_id TEXT NOT NULL,
|
||||
base_branch TEXT DEFAULT '',
|
||||
checkout_branch TEXT DEFAULT '',
|
||||
branch_policy_id TEXT DEFAULT '',
|
||||
branch_policy_name TEXT DEFAULT '',
|
||||
branch_policy_base_branch TEXT DEFAULT '',
|
||||
branch_policy_branch_template TEXT DEFAULT '',
|
||||
branch_policy_pull_request_target TEXT DEFAULT '',
|
||||
position INTEGER DEFAULT 0,
|
||||
metadata TEXT DEFAULT '{}',
|
||||
created_at TIMESTAMP NOT NULL,
|
||||
@@ -510,6 +516,30 @@ func (r *Repository) initRepositorySetsSchema() error {
|
||||
return err
|
||||
}
|
||||
|
||||
const repositoryBranchPoliciesSchemaDDL = `
|
||||
CREATE TABLE IF NOT EXISTS repository_branch_policies (
|
||||
id TEXT PRIMARY KEY,
|
||||
repository_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
description TEXT NOT NULL DEFAULT '',
|
||||
base_branch TEXT NOT NULL,
|
||||
branch_template TEXT NOT NULL,
|
||||
pull_request_target TEXT NOT NULL,
|
||||
created_at TIMESTAMP NOT NULL,
|
||||
updated_at TIMESTAMP NOT NULL,
|
||||
FOREIGN KEY (repository_id) REFERENCES repositories(id) ON DELETE CASCADE
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_repository_branch_policies_repository_id
|
||||
ON repository_branch_policies(repository_id);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uniq_repository_branch_policies_repository_lower_name
|
||||
ON repository_branch_policies(repository_id, LOWER(name));
|
||||
`
|
||||
|
||||
func (r *Repository) initRepositoryBranchPoliciesSchema() error {
|
||||
_, err := r.db.Exec(repositoryBranchPoliciesSchemaDDL)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *Repository) initCoreIndexes() error {
|
||||
_, err := r.db.Exec(`
|
||||
CREATE INDEX IF NOT EXISTS idx_tasks_workflow_id ON tasks(workflow_id);
|
||||
|
||||
@@ -90,7 +90,7 @@ func TestTaskRepositoryCRUDOrderingBatchAndCascade(t *testing.T) {
|
||||
}
|
||||
}
|
||||
links := []*models.TaskRepository{
|
||||
{ID: "link-second", TaskID: "task-repo-one", RepositoryID: "repo-two", BaseBranch: "main", CheckoutBranch: "feature", Position: 2, Metadata: map[string]any{"role": "secondary"}},
|
||||
{ID: "link-second", TaskID: "task-repo-one", RepositoryID: "repo-two", BaseBranch: "main", CheckoutBranch: "feature", BranchPolicyID: "policy-feature", BranchPolicyName: "Feature", BranchPolicyBaseBranch: "main", BranchPolicyBranchTemplate: "feature/{title}-{suffix}", BranchPolicyPullRequestTarget: "develop", Position: 2, Metadata: map[string]any{"role": "secondary"}},
|
||||
{ID: "link-first", TaskID: "task-repo-one", RepositoryID: "repo-one", BaseBranch: "main", Position: 1, Metadata: map[string]any{"role": "primary"}},
|
||||
{ID: "link-other", TaskID: "task-repo-two", RepositoryID: "repo-one", Position: 0},
|
||||
}
|
||||
@@ -100,14 +100,23 @@ func TestTaskRepositoryCRUDOrderingBatchAndCascade(t *testing.T) {
|
||||
}
|
||||
}
|
||||
got, err := repo.GetTaskRepository(ctx, "link-second")
|
||||
if err != nil || got.CheckoutBranch != "feature" || got.Metadata["role"] != "secondary" {
|
||||
if err != nil || got.CheckoutBranch != "feature" || got.Metadata["role"] != "secondary" || got.BranchPolicyID != "policy-feature" || got.BranchPolicyName != "Feature" || got.BranchPolicyBaseBranch != "main" || got.BranchPolicyBranchTemplate != "feature/{title}-{suffix}" || got.BranchPolicyPullRequestTarget != "develop" {
|
||||
t.Fatalf("GetTaskRepository = %+v, %v", got, err)
|
||||
}
|
||||
got.Position, got.BaseBranch, got.CheckoutBranch = 0, "develop", "next"
|
||||
got.BranchPolicyID = "policy-hotfix"
|
||||
got.BranchPolicyName = "Hotfix"
|
||||
got.BranchPolicyBaseBranch = "develop"
|
||||
got.BranchPolicyBranchTemplate = "hotfix/{title}"
|
||||
got.BranchPolicyPullRequestTarget = "main"
|
||||
got.Metadata = map[string]any{"updated": true}
|
||||
if err := repo.UpdateTaskRepository(ctx, got); err != nil {
|
||||
t.Fatalf("UpdateTaskRepository: %v", err)
|
||||
}
|
||||
updated, err := repo.GetTaskRepository(ctx, "link-second")
|
||||
if err != nil || updated.BranchPolicyID != "policy-hotfix" || updated.BranchPolicyName != "Hotfix" || updated.BranchPolicyBaseBranch != "develop" || updated.BranchPolicyBranchTemplate != "hotfix/{title}" || updated.BranchPolicyPullRequestTarget != "main" {
|
||||
t.Fatalf("updated task repository snapshot = %+v, %v", updated, err)
|
||||
}
|
||||
primary, err := repo.GetPrimaryTaskRepository(ctx, "task-repo-one")
|
||||
if err != nil || primary.ID != "link-second" {
|
||||
t.Fatalf("GetPrimaryTaskRepository = %+v, %v", primary, err)
|
||||
@@ -116,6 +125,10 @@ func TestTaskRepositoryCRUDOrderingBatchAndCascade(t *testing.T) {
|
||||
if err != nil || len(grouped["task-repo-one"]) != 2 || len(grouped["task-repo-two"]) != 1 {
|
||||
t.Fatalf("ListTaskRepositoriesByTaskIDs = %v, %v", grouped, err)
|
||||
}
|
||||
groupedSnapshot := grouped["task-repo-one"][0]
|
||||
if groupedSnapshot.BranchPolicyID != "policy-hotfix" || groupedSnapshot.BranchPolicyName != "Hotfix" || groupedSnapshot.BranchPolicyBaseBranch != "develop" || groupedSnapshot.BranchPolicyBranchTemplate != "hotfix/{title}" || groupedSnapshot.BranchPolicyPullRequestTarget != "main" {
|
||||
t.Fatalf("batched task repository snapshot = %+v", groupedSnapshot)
|
||||
}
|
||||
empty, err := repo.ListTaskRepositoriesByTaskIDs(ctx, nil)
|
||||
if err != nil || len(empty) != 0 {
|
||||
t.Fatalf("ListTaskRepositoriesByTaskIDs(nil) = %v, %v", empty, err)
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
package sqlite
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
"github.com/kandev/kandev/internal/task/repository/repoerrors"
|
||||
)
|
||||
|
||||
const repositoryBranchPolicyColumns = `id, repository_id, name, description, base_branch, branch_template, pull_request_target, created_at, updated_at`
|
||||
|
||||
func (r *Repository) CreateRepositoryBranchPolicy(ctx context.Context, policy *models.RepositoryBranchPolicy) error {
|
||||
if policy.ID == "" {
|
||||
policy.ID = uuid.New().String()
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
policy.CreatedAt = now
|
||||
policy.UpdatedAt = now
|
||||
_, err := r.db.ExecContext(ctx, r.db.Rebind(`
|
||||
INSERT INTO repository_branch_policies (`+repositoryBranchPolicyColumns+`)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`), policy.ID, policy.RepositoryID, policy.Name, policy.Description, policy.BaseBranch,
|
||||
policy.BranchTemplate, policy.PullRequestTarget, policy.CreatedAt, policy.UpdatedAt)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *Repository) scanRepositoryBranchPolicy(row *sql.Row) (*models.RepositoryBranchPolicy, error) {
|
||||
policy := &models.RepositoryBranchPolicy{}
|
||||
err := row.Scan(&policy.ID, &policy.RepositoryID, &policy.Name, &policy.Description,
|
||||
&policy.BaseBranch, &policy.BranchTemplate, &policy.PullRequestTarget,
|
||||
&policy.CreatedAt, &policy.UpdatedAt)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, repoerrors.ErrRepositoryBranchPolicyNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return policy, nil
|
||||
}
|
||||
|
||||
func (r *Repository) GetRepositoryBranchPolicy(ctx context.Context, id string) (*models.RepositoryBranchPolicy, error) {
|
||||
return r.scanRepositoryBranchPolicy(r.ro.QueryRowContext(ctx, r.ro.Rebind(
|
||||
`SELECT `+repositoryBranchPolicyColumns+` FROM repository_branch_policies WHERE id = ?`), id))
|
||||
}
|
||||
|
||||
func (r *Repository) GetRepositoryBranchPolicyByName(ctx context.Context, repositoryID, name string) (*models.RepositoryBranchPolicy, error) {
|
||||
policy, err := r.scanRepositoryBranchPolicy(r.ro.QueryRowContext(ctx, r.ro.Rebind(
|
||||
`SELECT `+repositoryBranchPolicyColumns+` FROM repository_branch_policies WHERE repository_id = ? AND LOWER(name) = ?`),
|
||||
repositoryID, strings.ToLower(strings.TrimSpace(name))))
|
||||
if errors.Is(err, repoerrors.ErrRepositoryBranchPolicyNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return policy, err
|
||||
}
|
||||
|
||||
func (r *Repository) ListRepositoryBranchPolicies(ctx context.Context, repositoryID string) ([]*models.RepositoryBranchPolicy, error) {
|
||||
rows, err := r.ro.QueryContext(ctx, r.ro.Rebind(`
|
||||
SELECT `+repositoryBranchPolicyColumns+` FROM repository_branch_policies
|
||||
WHERE repository_id = ? ORDER BY LOWER(name), id
|
||||
`), repositoryID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = rows.Close() }()
|
||||
policies := make([]*models.RepositoryBranchPolicy, 0)
|
||||
for rows.Next() {
|
||||
policy := &models.RepositoryBranchPolicy{}
|
||||
if err := rows.Scan(&policy.ID, &policy.RepositoryID, &policy.Name, &policy.Description,
|
||||
&policy.BaseBranch, &policy.BranchTemplate, &policy.PullRequestTarget,
|
||||
&policy.CreatedAt, &policy.UpdatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
policies = append(policies, policy)
|
||||
}
|
||||
return policies, rows.Err()
|
||||
}
|
||||
|
||||
func (r *Repository) ListRepositoryBranchPoliciesByWorkspace(ctx context.Context, workspaceID string) ([]*models.RepositoryBranchPolicy, error) {
|
||||
rows, err := r.ro.QueryContext(ctx, r.ro.Rebind(`
|
||||
SELECT `+repositoryBranchPolicyColumnsWithAlias("p")+` FROM repository_branch_policies p
|
||||
JOIN repositories r ON r.id = p.repository_id
|
||||
WHERE r.workspace_id = ? ORDER BY p.repository_id, LOWER(p.name), p.id
|
||||
`), workspaceID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = rows.Close() }()
|
||||
policies := make([]*models.RepositoryBranchPolicy, 0)
|
||||
for rows.Next() {
|
||||
policy := &models.RepositoryBranchPolicy{}
|
||||
if err := rows.Scan(&policy.ID, &policy.RepositoryID, &policy.Name, &policy.Description,
|
||||
&policy.BaseBranch, &policy.BranchTemplate, &policy.PullRequestTarget,
|
||||
&policy.CreatedAt, &policy.UpdatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
policies = append(policies, policy)
|
||||
}
|
||||
return policies, rows.Err()
|
||||
}
|
||||
|
||||
func repositoryBranchPolicyColumnsWithAlias(alias string) string {
|
||||
return alias + ".id, " + alias + ".repository_id, " + alias + ".name, " + alias + ".description, " +
|
||||
alias + ".base_branch, " + alias + ".branch_template, " + alias + ".pull_request_target, " +
|
||||
alias + ".created_at, " + alias + ".updated_at"
|
||||
}
|
||||
|
||||
func (r *Repository) UpdateRepositoryBranchPolicy(ctx context.Context, policy *models.RepositoryBranchPolicy) error {
|
||||
policy.UpdatedAt = time.Now().UTC()
|
||||
result, err := r.db.ExecContext(ctx, r.db.Rebind(`
|
||||
UPDATE repository_branch_policies
|
||||
SET name = ?, description = ?, base_branch = ?, branch_template = ?, pull_request_target = ?, updated_at = ?
|
||||
WHERE id = ?
|
||||
`), policy.Name, policy.Description, policy.BaseBranch, policy.BranchTemplate,
|
||||
policy.PullRequestTarget, policy.UpdatedAt, policy.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
count, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if count == 0 {
|
||||
return repoerrors.ErrRepositoryBranchPolicyNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Repository) DeleteRepositoryBranchPolicy(ctx context.Context, id string) (bool, error) {
|
||||
result, err := r.db.ExecContext(ctx, r.db.Rebind(`DELETE FROM repository_branch_policies WHERE id = ?`), id)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
count, err := result.RowsAffected()
|
||||
return count > 0, err
|
||||
}
|
||||
|
||||
func (r *Repository) CreateRepositoryBranchPoliciesIfEmpty(ctx context.Context, repositoryID string, policies []*models.RepositoryBranchPolicy) error {
|
||||
tx, err := r.db.BeginTxx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
var count int
|
||||
if err := tx.GetContext(ctx, &count, r.db.Rebind(`SELECT COUNT(*) FROM repository_branch_policies WHERE repository_id = ?`), repositoryID); err != nil {
|
||||
return err
|
||||
}
|
||||
if count > 0 {
|
||||
return repoerrors.ErrRepositoryBranchPoliciesExist
|
||||
}
|
||||
for _, policy := range policies {
|
||||
if policy.ID == "" {
|
||||
policy.ID = uuid.New().String()
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
policy.RepositoryID = repositoryID
|
||||
policy.CreatedAt = now
|
||||
policy.UpdatedAt = now
|
||||
if _, err := tx.ExecContext(ctx, r.db.Rebind(`
|
||||
INSERT INTO repository_branch_policies (`+repositoryBranchPolicyColumns+`)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`), policy.ID, policy.RepositoryID, policy.Name, policy.Description, policy.BaseBranch,
|
||||
policy.BranchTemplate, policy.PullRequestTarget, policy.CreatedAt, policy.UpdatedAt); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package sqlite
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
"github.com/kandev/kandev/internal/task/repository/repoerrors"
|
||||
)
|
||||
|
||||
func TestRepositoryBranchPolicySchemaExistsWithCaseInsensitiveNameIndex(t *testing.T) {
|
||||
repo := newRepoForSetTests(t)
|
||||
ctx := context.Background()
|
||||
|
||||
var tableName string
|
||||
if err := repo.DB().QueryRowContext(ctx, `
|
||||
SELECT name FROM sqlite_master
|
||||
WHERE type = 'table' AND name = 'repository_branch_policies'
|
||||
`).Scan(&tableName); err != nil {
|
||||
t.Fatalf("repository_branch_policies table is missing: %v", err)
|
||||
}
|
||||
if tableName != "repository_branch_policies" {
|
||||
t.Fatalf("table name = %q", tableName)
|
||||
}
|
||||
|
||||
var indexName string
|
||||
if err := repo.DB().QueryRowContext(ctx, `
|
||||
SELECT name FROM sqlite_master
|
||||
WHERE type = 'index' AND name = 'uniq_repository_branch_policies_repository_lower_name'
|
||||
`).Scan(&indexName); err != nil {
|
||||
t.Fatalf("case-insensitive policy-name index is missing: %v", err)
|
||||
}
|
||||
if indexName != "uniq_repository_branch_policies_repository_lower_name" {
|
||||
t.Fatalf("index name = %q", indexName)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRepositoryBranchPolicyCRUDAndCaseInsensitiveUniqueness(t *testing.T) {
|
||||
repo := newRepoForSetTests(t)
|
||||
ctx := context.Background()
|
||||
seedWorkspace(t, repo, "ws-policy")
|
||||
if err := repo.CreateRepository(ctx, &models.Repository{ID: "repo-policy", WorkspaceID: "ws-policy", Name: "repo-policy"}); err != nil {
|
||||
t.Fatalf("create repository: %v", err)
|
||||
}
|
||||
|
||||
policy := &models.RepositoryBranchPolicy{
|
||||
RepositoryID: "repo-policy",
|
||||
Name: "Feature",
|
||||
Description: "Fresh features",
|
||||
BaseBranch: "develop",
|
||||
BranchTemplate: "feature/{title}-{suffix}",
|
||||
PullRequestTarget: "develop",
|
||||
}
|
||||
if err := repo.CreateRepositoryBranchPolicy(ctx, policy); err != nil {
|
||||
t.Fatalf("create policy: %v", err)
|
||||
}
|
||||
loaded, err := repo.GetRepositoryBranchPolicy(ctx, policy.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("get policy: %v", err)
|
||||
}
|
||||
if loaded.Name != "Feature" || loaded.BaseBranch != "develop" {
|
||||
t.Fatalf("loaded policy = %+v", loaded)
|
||||
}
|
||||
byName, err := repo.GetRepositoryBranchPolicyByName(ctx, "repo-policy", "FEATURE")
|
||||
if err != nil || byName == nil || byName.ID != policy.ID {
|
||||
t.Fatalf("lookup by name = %+v, err=%v", byName, err)
|
||||
}
|
||||
|
||||
duplicate := *policy
|
||||
duplicate.ID = "duplicate-policy"
|
||||
duplicate.Name = "feature"
|
||||
if err := repo.CreateRepositoryBranchPolicy(ctx, &duplicate); err == nil {
|
||||
t.Fatal("case-insensitive duplicate policy name was accepted")
|
||||
}
|
||||
|
||||
policy.Description = "Updated"
|
||||
if err := repo.UpdateRepositoryBranchPolicy(ctx, policy); err != nil {
|
||||
t.Fatalf("update policy: %v", err)
|
||||
}
|
||||
policies, err := repo.ListRepositoryBranchPolicies(ctx, "repo-policy")
|
||||
if err != nil || len(policies) != 1 || policies[0].Description != "Updated" {
|
||||
t.Fatalf("list policies = %+v, err=%v", policies, err)
|
||||
}
|
||||
deleted, err := repo.DeleteRepositoryBranchPolicy(ctx, policy.ID)
|
||||
if err != nil || !deleted {
|
||||
t.Fatalf("delete policy = %t, err=%v", deleted, err)
|
||||
}
|
||||
if _, err := repo.GetRepositoryBranchPolicy(ctx, policy.ID); !errors.Is(err, repoerrors.ErrRepositoryBranchPolicyNotFound) {
|
||||
t.Fatalf("deleted policy error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRepositoryDeletePrunesBranchPolicies(t *testing.T) {
|
||||
repo := newRepoForSetTests(t)
|
||||
ctx := context.Background()
|
||||
seedWorkspace(t, repo, "ws-policy-prune")
|
||||
if err := repo.CreateRepository(ctx, &models.Repository{ID: "repo-policy-prune", WorkspaceID: "ws-policy-prune", Name: "repo-policy-prune"}); err != nil {
|
||||
t.Fatalf("create repository: %v", err)
|
||||
}
|
||||
if err := repo.CreateRepositoryBranchPolicy(ctx, &models.RepositoryBranchPolicy{ID: "policy-prune", RepositoryID: "repo-policy-prune", Name: "Feature"}); err != nil {
|
||||
t.Fatalf("create policy: %v", err)
|
||||
}
|
||||
if err := repo.DeleteRepository(ctx, "repo-policy-prune"); err != nil {
|
||||
t.Fatalf("delete repository: %v", err)
|
||||
}
|
||||
policies, err := repo.ListRepositoryBranchPolicies(ctx, "repo-policy-prune")
|
||||
if err != nil {
|
||||
t.Fatalf("list policies: %v", err)
|
||||
}
|
||||
if len(policies) != 0 {
|
||||
t.Fatalf("policies after repository deletion = %+v", policies)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListRepositoryBranchPoliciesByWorkspaceGroupsOnlyWorkspaceRepositories(t *testing.T) {
|
||||
repo := newRepoForSetTests(t)
|
||||
ctx := context.Background()
|
||||
seedWorkspace(t, repo, "ws-policy-batch")
|
||||
seedWorkspace(t, repo, "ws-policy-other")
|
||||
for _, item := range []struct {
|
||||
id string
|
||||
workspaceID string
|
||||
policyID string
|
||||
name string
|
||||
}{
|
||||
{id: "repo-batch-a", workspaceID: "ws-policy-batch", policyID: "policy-batch-a", name: "Feature"},
|
||||
{id: "repo-batch-b", workspaceID: "ws-policy-batch", policyID: "policy-batch-b", name: "Hotfix"},
|
||||
{id: "repo-other", workspaceID: "ws-policy-other", policyID: "policy-other", name: "Other"},
|
||||
} {
|
||||
if err := repo.CreateRepository(ctx, &models.Repository{ID: item.id, WorkspaceID: item.workspaceID, Name: item.id}); err != nil {
|
||||
t.Fatalf("create repository %s: %v", item.id, err)
|
||||
}
|
||||
if err := repo.CreateRepositoryBranchPolicy(ctx, &models.RepositoryBranchPolicy{
|
||||
ID: item.policyID, RepositoryID: item.id, Name: item.name,
|
||||
}); err != nil {
|
||||
t.Fatalf("create policy %s: %v", item.policyID, err)
|
||||
}
|
||||
}
|
||||
|
||||
policies, err := repo.ListRepositoryBranchPoliciesByWorkspace(ctx, "ws-policy-batch")
|
||||
if err != nil {
|
||||
t.Fatalf("list workspace policies: %v", err)
|
||||
}
|
||||
if len(policies) != 2 || policies[0].RepositoryID != "repo-batch-a" || policies[1].RepositoryID != "repo-batch-b" {
|
||||
t.Fatalf("workspace policies = %+v, want the two ordered workspace repositories", policies)
|
||||
}
|
||||
}
|
||||
@@ -161,6 +161,7 @@ func (r *Repository) UpdateRepositoryWithSecretBindings(
|
||||
func (r *Repository) pruneRepositoryDependents(ctx context.Context, tx *sqlx.Tx, id string) error {
|
||||
statements := []string{
|
||||
`DELETE FROM repository_secret_bindings WHERE repository_id = ?`,
|
||||
`DELETE FROM repository_branch_policies WHERE repository_id = ?`,
|
||||
// A membership row pointing at a deleted repository would offer the user
|
||||
// a repository they can no longer select. Repository sets keep existing
|
||||
// with their remaining members.
|
||||
|
||||
@@ -29,9 +29,14 @@ func (r *Repository) CreateTaskRepository(ctx context.Context, taskRepo *models.
|
||||
|
||||
_, err = r.db.ExecContext(ctx, r.db.Rebind(`
|
||||
INSERT INTO task_repositories (
|
||||
id, task_id, repository_id, base_branch, checkout_branch, position, metadata, created_at, updated_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`), taskRepo.ID, taskRepo.TaskID, taskRepo.RepositoryID, taskRepo.BaseBranch, taskRepo.CheckoutBranch, taskRepo.Position, string(metadataJSON), taskRepo.CreatedAt, taskRepo.UpdatedAt)
|
||||
id, task_id, repository_id, base_branch, checkout_branch, branch_policy_id, branch_policy_name,
|
||||
branch_policy_base_branch, branch_policy_branch_template, branch_policy_pull_request_target,
|
||||
position, metadata, created_at, updated_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`), taskRepo.ID, taskRepo.TaskID, taskRepo.RepositoryID, taskRepo.BaseBranch, taskRepo.CheckoutBranch,
|
||||
taskRepo.BranchPolicyID, taskRepo.BranchPolicyName, taskRepo.BranchPolicyBaseBranch,
|
||||
taskRepo.BranchPolicyBranchTemplate, taskRepo.BranchPolicyPullRequestTarget,
|
||||
taskRepo.Position, string(metadataJSON), taskRepo.CreatedAt, taskRepo.UpdatedAt)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -41,7 +46,9 @@ func (r *Repository) GetTaskRepository(ctx context.Context, id string) (*models.
|
||||
var metadataJSON string
|
||||
|
||||
err := r.ro.QueryRowContext(ctx, r.ro.Rebind(`
|
||||
SELECT id, task_id, repository_id, base_branch, checkout_branch, position, metadata, created_at, updated_at
|
||||
SELECT id, task_id, repository_id, base_branch, checkout_branch, branch_policy_id, branch_policy_name,
|
||||
branch_policy_base_branch, branch_policy_branch_template, branch_policy_pull_request_target,
|
||||
position, metadata, created_at, updated_at
|
||||
FROM task_repositories WHERE id = ?
|
||||
`), id).Scan(
|
||||
&taskRepo.ID,
|
||||
@@ -49,6 +56,11 @@ func (r *Repository) GetTaskRepository(ctx context.Context, id string) (*models.
|
||||
&taskRepo.RepositoryID,
|
||||
&taskRepo.BaseBranch,
|
||||
&taskRepo.CheckoutBranch,
|
||||
&taskRepo.BranchPolicyID,
|
||||
&taskRepo.BranchPolicyName,
|
||||
&taskRepo.BranchPolicyBaseBranch,
|
||||
&taskRepo.BranchPolicyBranchTemplate,
|
||||
&taskRepo.BranchPolicyPullRequestTarget,
|
||||
&taskRepo.Position,
|
||||
&metadataJSON,
|
||||
&taskRepo.CreatedAt,
|
||||
@@ -71,7 +83,9 @@ func (r *Repository) GetTaskRepository(ctx context.Context, id string) (*models.
|
||||
// ListTaskRepositories returns all repository links for a task
|
||||
func (r *Repository) ListTaskRepositories(ctx context.Context, taskID string) ([]*models.TaskRepository, error) {
|
||||
rows, err := r.ro.QueryContext(ctx, r.ro.Rebind(`
|
||||
SELECT id, task_id, repository_id, base_branch, checkout_branch, position, metadata, created_at, updated_at
|
||||
SELECT id, task_id, repository_id, base_branch, checkout_branch, branch_policy_id, branch_policy_name,
|
||||
branch_policy_base_branch, branch_policy_branch_template, branch_policy_pull_request_target,
|
||||
position, metadata, created_at, updated_at
|
||||
FROM task_repositories
|
||||
WHERE task_id = ?
|
||||
ORDER BY position ASC, created_at ASC
|
||||
@@ -91,6 +105,11 @@ func (r *Repository) ListTaskRepositories(ctx context.Context, taskID string) ([
|
||||
&taskRepo.RepositoryID,
|
||||
&taskRepo.BaseBranch,
|
||||
&taskRepo.CheckoutBranch,
|
||||
&taskRepo.BranchPolicyID,
|
||||
&taskRepo.BranchPolicyName,
|
||||
&taskRepo.BranchPolicyBaseBranch,
|
||||
&taskRepo.BranchPolicyBranchTemplate,
|
||||
&taskRepo.BranchPolicyPullRequestTarget,
|
||||
&taskRepo.Position,
|
||||
&metadataJSON,
|
||||
&taskRepo.CreatedAt,
|
||||
@@ -134,9 +153,14 @@ func (r *Repository) UpdateTaskRepository(ctx context.Context, taskRepo *models.
|
||||
|
||||
result, err := r.db.ExecContext(ctx, r.db.Rebind(`
|
||||
UPDATE task_repositories SET
|
||||
task_id = ?, repository_id = ?, base_branch = ?, checkout_branch = ?, position = ?, metadata = ?, updated_at = ?
|
||||
task_id = ?, repository_id = ?, base_branch = ?, checkout_branch = ?, branch_policy_id = ?, branch_policy_name = ?,
|
||||
branch_policy_base_branch = ?, branch_policy_branch_template = ?, branch_policy_pull_request_target = ?,
|
||||
position = ?, metadata = ?, updated_at = ?
|
||||
WHERE id = ?
|
||||
`), taskRepo.TaskID, taskRepo.RepositoryID, taskRepo.BaseBranch, taskRepo.CheckoutBranch, taskRepo.Position, string(metadataJSON), taskRepo.UpdatedAt, taskRepo.ID)
|
||||
`), taskRepo.TaskID, taskRepo.RepositoryID, taskRepo.BaseBranch, taskRepo.CheckoutBranch,
|
||||
taskRepo.BranchPolicyID, taskRepo.BranchPolicyName, taskRepo.BranchPolicyBaseBranch,
|
||||
taskRepo.BranchPolicyBranchTemplate, taskRepo.BranchPolicyPullRequestTarget,
|
||||
taskRepo.Position, string(metadataJSON), taskRepo.UpdatedAt, taskRepo.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -176,7 +200,9 @@ func (r *Repository) ListTaskRepositoriesByTaskIDs(ctx context.Context, taskIDs
|
||||
}
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
SELECT id, task_id, repository_id, base_branch, checkout_branch, position, metadata, created_at, updated_at
|
||||
SELECT id, task_id, repository_id, base_branch, checkout_branch, branch_policy_id, branch_policy_name,
|
||||
branch_policy_base_branch, branch_policy_branch_template, branch_policy_pull_request_target,
|
||||
position, metadata, created_at, updated_at
|
||||
FROM task_repositories
|
||||
WHERE task_id IN (%s)
|
||||
ORDER BY position ASC, created_at ASC
|
||||
@@ -197,6 +223,11 @@ func (r *Repository) ListTaskRepositoriesByTaskIDs(ctx context.Context, taskIDs
|
||||
&taskRepo.RepositoryID,
|
||||
&taskRepo.BaseBranch,
|
||||
&taskRepo.CheckoutBranch,
|
||||
&taskRepo.BranchPolicyID,
|
||||
&taskRepo.BranchPolicyName,
|
||||
&taskRepo.BranchPolicyBaseBranch,
|
||||
&taskRepo.BranchPolicyBranchTemplate,
|
||||
&taskRepo.BranchPolicyPullRequestTarget,
|
||||
&taskRepo.Position,
|
||||
&metadataJSON,
|
||||
&taskRepo.CreatedAt,
|
||||
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
package sqlite
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
)
|
||||
|
||||
func TestTaskRepositoryBranchPolicyMigrationPreservesLegacyRows(t *testing.T) {
|
||||
repo := newRepoForEntityTests(t)
|
||||
ctx := context.Background()
|
||||
seedWorkspace(t, repo, "workspace-task-repository-policy-migration")
|
||||
if err := repo.CreateWorkflow(ctx, &models.Workflow{
|
||||
ID: "workflow-task-repository-policy-migration", WorkspaceID: "workspace-task-repository-policy-migration", Name: "Workflow",
|
||||
}); err != nil {
|
||||
t.Fatalf("create workflow: %v", err)
|
||||
}
|
||||
if err := repo.CreateTask(ctx, &models.Task{
|
||||
ID: "task-task-repository-policy-migration", WorkspaceID: "workspace-task-repository-policy-migration",
|
||||
WorkflowID: "workflow-task-repository-policy-migration", Title: "Legacy task",
|
||||
}); err != nil {
|
||||
t.Fatalf("create task: %v", err)
|
||||
}
|
||||
if err := repo.CreateRepository(ctx, &models.Repository{
|
||||
ID: "repo-task-repository-policy-migration", WorkspaceID: "workspace-task-repository-policy-migration", Name: "Legacy repository",
|
||||
}); err != nil {
|
||||
t.Fatalf("create repository: %v", err)
|
||||
}
|
||||
if err := repo.CreateTaskRepository(ctx, &models.TaskRepository{
|
||||
ID: "task-repository-policy-migration", TaskID: "task-task-repository-policy-migration",
|
||||
RepositoryID: "repo-task-repository-policy-migration", BaseBranch: "main", Position: 0,
|
||||
}); err != nil {
|
||||
t.Fatalf("create legacy task repository: %v", err)
|
||||
}
|
||||
|
||||
for _, column := range []string{
|
||||
"branch_policy_pull_request_target",
|
||||
"branch_policy_branch_template",
|
||||
"branch_policy_base_branch",
|
||||
"branch_policy_name",
|
||||
"branch_policy_id",
|
||||
} {
|
||||
if _, err := repo.db.Exec(`ALTER TABLE task_repositories DROP COLUMN ` + column); err != nil {
|
||||
t.Fatalf("drop legacy column %s: %v", column, err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := repo.runMigrations(); err != nil {
|
||||
t.Fatalf("migrate legacy task repository schema: %v", err)
|
||||
}
|
||||
if err := repo.runMigrations(); err != nil {
|
||||
t.Fatalf("replay legacy task repository migration: %v", err)
|
||||
}
|
||||
|
||||
got, err := repo.GetTaskRepository(ctx, "task-repository-policy-migration")
|
||||
if err != nil {
|
||||
t.Fatalf("get migrated task repository: %v", err)
|
||||
}
|
||||
if got.BaseBranch != "main" {
|
||||
t.Fatalf("migrated base branch = %q, want main", got.BaseBranch)
|
||||
}
|
||||
if got.BranchPolicyID != "" || got.BranchPolicyName != "" || got.BranchPolicyBaseBranch != "" || got.BranchPolicyBranchTemplate != "" || got.BranchPolicyPullRequestTarget != "" {
|
||||
t.Fatalf("migrated policy snapshot = %+v, want empty fields", got)
|
||||
}
|
||||
}
|
||||
@@ -281,6 +281,7 @@ type Repos struct {
|
||||
GitSnapshots repository.GitSnapshotRepository
|
||||
RepoEntities repository.RepositoryEntityRepository
|
||||
RepositorySets repository.RepositorySetRepository
|
||||
BranchPolicies repository.RepositoryBranchPolicyRepository
|
||||
RepositoryCleanup repository.RepositoryCleanupRepository
|
||||
Executors repository.ExecutorRepository
|
||||
Environments repository.EnvironmentRepository
|
||||
@@ -307,6 +308,7 @@ type Service struct {
|
||||
gitSnapshots repository.GitSnapshotRepository
|
||||
repoEntities repository.RepositoryEntityRepository
|
||||
repositorySets repository.RepositorySetRepository
|
||||
branchPolicies repository.RepositoryBranchPolicyRepository
|
||||
repositoryCleanup repository.RepositoryCleanupRepository
|
||||
executors repository.ExecutorRepository
|
||||
environments repository.EnvironmentRepository
|
||||
@@ -452,6 +454,7 @@ func NewService(repos Repos, eventBus bus.EventBus, log *logger.Logger, discover
|
||||
gitSnapshots: repos.GitSnapshots,
|
||||
repoEntities: repos.RepoEntities,
|
||||
repositorySets: repos.RepositorySets,
|
||||
branchPolicies: repos.BranchPolicies,
|
||||
repositoryCleanup: repos.RepositoryCleanup,
|
||||
executors: repos.Executors,
|
||||
environments: repos.Environments,
|
||||
|
||||
@@ -675,14 +675,37 @@ func taskRepositoriesForEvent(ctx context.Context, s *Service, task *models.Task
|
||||
func serializeTaskRepositories(repos []*models.TaskRepository) []map[string]interface{} {
|
||||
out := make([]map[string]interface{}, 0, len(repos))
|
||||
for _, r := range repos {
|
||||
out = append(out, map[string]interface{}{
|
||||
"id": r.ID,
|
||||
"task_id": r.TaskID,
|
||||
"repository_id": r.RepositoryID,
|
||||
"base_branch": r.BaseBranch,
|
||||
"checkout_branch": r.CheckoutBranch,
|
||||
"position": r.Position,
|
||||
})
|
||||
serialized := map[string]interface{}{
|
||||
"id": r.ID,
|
||||
"task_id": r.TaskID,
|
||||
"repository_id": r.RepositoryID,
|
||||
"base_branch": r.BaseBranch,
|
||||
"position": r.Position,
|
||||
"created_at": r.CreatedAt.Format(time.RFC3339Nano),
|
||||
"updated_at": r.UpdatedAt.Format(time.RFC3339Nano),
|
||||
}
|
||||
if r.CheckoutBranch != "" {
|
||||
serialized["checkout_branch"] = r.CheckoutBranch
|
||||
}
|
||||
if r.BranchPolicyID != "" {
|
||||
serialized["branch_policy_id"] = r.BranchPolicyID
|
||||
}
|
||||
if r.BranchPolicyName != "" {
|
||||
serialized["branch_policy_name"] = r.BranchPolicyName
|
||||
}
|
||||
if r.BranchPolicyBaseBranch != "" {
|
||||
serialized["branch_policy_base_branch"] = r.BranchPolicyBaseBranch
|
||||
}
|
||||
if r.BranchPolicyBranchTemplate != "" {
|
||||
serialized["branch_policy_branch_template"] = r.BranchPolicyBranchTemplate
|
||||
}
|
||||
if r.BranchPolicyPullRequestTarget != "" {
|
||||
serialized["branch_policy_pull_request_target"] = r.BranchPolicyPullRequestTarget
|
||||
}
|
||||
if len(r.Metadata) > 0 {
|
||||
serialized["metadata"] = r.Metadata
|
||||
}
|
||||
out = append(out, serialized)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/kandev/kandev/internal/events"
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
)
|
||||
|
||||
func TestTaskEventsSerializeBranchPolicySnapshot(t *testing.T) {
|
||||
createdAt := time.Date(2026, 8, 24, 10, 0, 0, 0, time.UTC)
|
||||
updatedAt := createdAt.Add(time.Minute)
|
||||
|
||||
for _, eventType := range []string{events.TaskCreated, events.TaskUpdated} {
|
||||
t.Run(eventType, func(t *testing.T) {
|
||||
svc, eventBus, _ := createTestService(t)
|
||||
task := &models.Task{
|
||||
ID: "task-policy-event", WorkspaceID: "ws-policy-event", WorkflowID: "workflow-policy-event",
|
||||
Title: "Policy event", CreatedAt: createdAt, UpdatedAt: updatedAt,
|
||||
Repositories: []*models.TaskRepository{{
|
||||
ID: "task-repo-policy-event", TaskID: "task-policy-event", RepositoryID: "repo-policy-event",
|
||||
BaseBranch: "main", CheckoutBranch: "feature/policy-event", Position: 0,
|
||||
BranchPolicyID: "policy-event", BranchPolicyName: "Feature branches",
|
||||
BranchPolicyBaseBranch: "main", BranchPolicyBranchTemplate: "feature/{title}-{suffix}",
|
||||
BranchPolicyPullRequestTarget: "develop", Metadata: map[string]interface{}{"source": "test"},
|
||||
CreatedAt: createdAt, UpdatedAt: updatedAt,
|
||||
}},
|
||||
}
|
||||
|
||||
svc.publishTaskEvent(context.Background(), eventType, task, nil)
|
||||
|
||||
published := eventBus.GetPublishedEvents()
|
||||
if len(published) != 1 || published[0].Type != eventType {
|
||||
t.Fatalf("published events = %#v, want one %s event", published, eventType)
|
||||
}
|
||||
data, ok := published[0].Data.(map[string]interface{})
|
||||
if !ok {
|
||||
t.Fatalf("event data type = %T, want map[string]interface{}", published[0].Data)
|
||||
}
|
||||
repositories, ok := data["repositories"].([]map[string]interface{})
|
||||
if !ok || len(repositories) != 1 {
|
||||
t.Fatalf("repositories = %#v, want one serialized repository", data["repositories"])
|
||||
}
|
||||
repository := repositories[0]
|
||||
for key, want := range map[string]string{
|
||||
"branch_policy_id": "policy-event",
|
||||
"branch_policy_name": "Feature branches",
|
||||
"branch_policy_base_branch": "main",
|
||||
"branch_policy_branch_template": "feature/{title}-{suffix}",
|
||||
"branch_policy_pull_request_target": "develop",
|
||||
} {
|
||||
if got := repository[key]; got != want {
|
||||
t.Errorf("repositories[0][%q] = %#v, want %q", key, got, want)
|
||||
}
|
||||
}
|
||||
if got := repository["metadata"]; got == nil {
|
||||
t.Error("repositories[0][metadata] is missing")
|
||||
}
|
||||
if got := repository["created_at"]; got != createdAt.Format(time.RFC3339) {
|
||||
t.Errorf("repositories[0][created_at] = %#v, want %q", got, createdAt.Format(time.RFC3339))
|
||||
}
|
||||
if got := repository["updated_at"]; got != updatedAt.Format(time.RFC3339) {
|
||||
t.Errorf("repositories[0][updated_at] = %#v, want %q", got, updatedAt.Format(time.RFC3339))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go.uber.org/zap"
|
||||
|
||||
"github.com/kandev/kandev/internal/events"
|
||||
"github.com/kandev/kandev/internal/events/bus"
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
"github.com/kandev/kandev/internal/task/repository/repoerrors"
|
||||
"github.com/kandev/kandev/internal/worktree"
|
||||
)
|
||||
|
||||
const (
|
||||
repositoryBranchPolicyNameMaxLength = 100
|
||||
repositoryBranchPolicyDescriptionMaxLength = 500
|
||||
defaultGitflowDevelopmentBranch = "develop"
|
||||
BranchPolicyStaleErrorCode = "branch_policy_stale"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalidRepositoryBranchPolicy = errors.New("invalid repository branch policy")
|
||||
ErrRepositoryBranchPolicyNameConflict = errors.New("repository branch policy name already used")
|
||||
ErrRepositoryBranchPolicyAlreadySeeded = errors.New("repository branch policies already seeded")
|
||||
ErrRepositoryBranchPolicyReadOnly = errors.New("this workspace is managed by Improve Kandev and is read-only")
|
||||
ErrRepositoryBranchPolicyStoreMissing = errors.New("repository branch policy store is unavailable")
|
||||
ErrRepositoryBranchPolicyStale = errors.New("repository branch policy is no longer available")
|
||||
)
|
||||
|
||||
type CreateRepositoryBranchPolicyRequest struct {
|
||||
RepositoryID string `json:"repository_id"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
BaseBranch string `json:"base_branch"`
|
||||
BranchTemplate string `json:"branch_template"`
|
||||
PullRequestTarget string `json:"pull_request_target"`
|
||||
}
|
||||
|
||||
type UpdateRepositoryBranchPolicyRequest struct {
|
||||
Name *string `json:"name"`
|
||||
Description *string `json:"description"`
|
||||
BaseBranch *string `json:"base_branch"`
|
||||
BranchTemplate *string `json:"branch_template"`
|
||||
PullRequestTarget *string `json:"pull_request_target"`
|
||||
}
|
||||
|
||||
type CreateGitflowRepositoryBranchPoliciesRequest struct {
|
||||
RepositoryID string `json:"repository_id"`
|
||||
ProductionBranch string `json:"production_branch"`
|
||||
DevelopmentBranch string `json:"development_branch"`
|
||||
}
|
||||
|
||||
func (s *Service) CreateRepositoryBranchPolicy(ctx context.Context, req *CreateRepositoryBranchPolicyRequest) (*models.RepositoryBranchPolicy, error) {
|
||||
if err := s.ensureBranchPolicyStore(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
repository, err := s.authorizeWritableBranchPolicyRepository(ctx, req.RepositoryID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
policy, err := normalizeRepositoryBranchPolicy(&models.RepositoryBranchPolicy{
|
||||
RepositoryID: req.RepositoryID, Name: req.Name, Description: req.Description,
|
||||
BaseBranch: req.BaseBranch, BranchTemplate: req.BranchTemplate,
|
||||
PullRequestTarget: req.PullRequestTarget,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.assertBranchPolicyNameFree(ctx, repository.ID, policy.Name, ""); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.branchPolicies.CreateRepositoryBranchPolicy(ctx, policy); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.publishRepositoryBranchPolicyEvent(ctx, events.RepositoryBranchPolicyCreated, repository.WorkspaceID, policy)
|
||||
return policy, nil
|
||||
}
|
||||
|
||||
func (s *Service) GetRepositoryBranchPolicy(ctx context.Context, id string) (*models.RepositoryBranchPolicy, error) {
|
||||
if err := s.ensureBranchPolicyStore(); err != nil {
|
||||
return nil, repoerrors.ErrRepositoryBranchPolicyNotFound
|
||||
}
|
||||
policy, err := s.branchPolicies.GetRepositoryBranchPolicy(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := s.authorizeBranchPolicyRepository(ctx, policy.RepositoryID); err != nil {
|
||||
return nil, repoerrors.ErrRepositoryBranchPolicyNotFound
|
||||
}
|
||||
return policy, nil
|
||||
}
|
||||
|
||||
func (s *Service) ListRepositoryBranchPolicies(ctx context.Context, repositoryID string) ([]*models.RepositoryBranchPolicy, error) {
|
||||
if err := s.ensureBranchPolicyStore(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := s.authorizeBranchPolicyRepository(ctx, repositoryID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.branchPolicies.ListRepositoryBranchPolicies(ctx, repositoryID)
|
||||
}
|
||||
|
||||
func (s *Service) ListRepositoryBranchPoliciesForWorkspace(ctx context.Context, workspaceID string) ([]*models.RepositoryBranchPolicy, error) {
|
||||
if err := s.ensureBranchPolicyStore(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.authorizeWorkspaceID(ctx, workspaceID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.branchPolicies.ListRepositoryBranchPoliciesByWorkspace(ctx, workspaceID)
|
||||
}
|
||||
|
||||
func (s *Service) UpdateRepositoryBranchPolicy(ctx context.Context, id string, req *UpdateRepositoryBranchPolicyRequest) (*models.RepositoryBranchPolicy, error) {
|
||||
if err := s.ensureBranchPolicyStore(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
policy, err := s.GetRepositoryBranchPolicy(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if req.Name != nil {
|
||||
policy.Name = *req.Name
|
||||
}
|
||||
if req.Description != nil {
|
||||
policy.Description = *req.Description
|
||||
}
|
||||
if req.BaseBranch != nil {
|
||||
policy.BaseBranch = *req.BaseBranch
|
||||
}
|
||||
if req.BranchTemplate != nil {
|
||||
policy.BranchTemplate = *req.BranchTemplate
|
||||
}
|
||||
if req.PullRequestTarget != nil {
|
||||
policy.PullRequestTarget = *req.PullRequestTarget
|
||||
}
|
||||
repository, err := s.authorizeWritableBranchPolicyRepository(ctx, policy.RepositoryID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
normalized, err := normalizeRepositoryBranchPolicy(policy)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.assertBranchPolicyNameFree(ctx, policy.RepositoryID, normalized.Name, policy.ID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.branchPolicies.UpdateRepositoryBranchPolicy(ctx, normalized); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.publishRepositoryBranchPolicyEvent(ctx, events.RepositoryBranchPolicyUpdated, repository.WorkspaceID, normalized)
|
||||
return normalized, nil
|
||||
}
|
||||
|
||||
func (s *Service) DeleteRepositoryBranchPolicy(ctx context.Context, id string) error {
|
||||
if err := s.ensureBranchPolicyStore(); err != nil {
|
||||
return err
|
||||
}
|
||||
policy, err := s.GetRepositoryBranchPolicy(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
repository, err := s.authorizeWritableBranchPolicyRepository(ctx, policy.RepositoryID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
deleted, err := s.branchPolicies.DeleteRepositoryBranchPolicy(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !deleted {
|
||||
return repoerrors.ErrRepositoryBranchPolicyNotFound
|
||||
}
|
||||
s.publishRepositoryBranchPolicyEvent(ctx, events.RepositoryBranchPolicyDeleted, repository.WorkspaceID, policy)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) CreateGitflowRepositoryBranchPolicies(ctx context.Context, req *CreateGitflowRepositoryBranchPoliciesRequest) ([]*models.RepositoryBranchPolicy, error) {
|
||||
if err := s.ensureBranchPolicyStore(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
repository, err := s.authorizeWritableBranchPolicyRepository(ctx, req.RepositoryID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
production := strings.TrimSpace(req.ProductionBranch)
|
||||
if production == "" {
|
||||
production = strings.TrimSpace(repository.DefaultBranch)
|
||||
}
|
||||
development := strings.TrimSpace(req.DevelopmentBranch)
|
||||
if development == "" {
|
||||
development = defaultGitflowDevelopmentBranch
|
||||
}
|
||||
if err := validatePolicyBranchRef(production, "production branch"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := validatePolicyBranchRef(development, "development branch"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if production == development {
|
||||
return nil, fmt.Errorf("%w: production and development branches must differ", ErrInvalidRepositoryBranchPolicy)
|
||||
}
|
||||
if err := s.validateGitflowBranches(ctx, repository.ID, production, development); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
policies := gitflowPolicies(req.RepositoryID, production, development)
|
||||
if err := s.branchPolicies.CreateRepositoryBranchPoliciesIfEmpty(ctx, repository.ID, policies); err != nil {
|
||||
if errors.Is(err, repoerrors.ErrRepositoryBranchPoliciesExist) {
|
||||
return nil, fmt.Errorf("%w: repository already has branch policies", ErrRepositoryBranchPolicyAlreadySeeded)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
for _, policy := range policies {
|
||||
s.publishRepositoryBranchPolicyEvent(ctx, events.RepositoryBranchPolicyCreated, repository.WorkspaceID, policy)
|
||||
}
|
||||
return policies, nil
|
||||
}
|
||||
|
||||
func (s *Service) validateGitflowBranches(ctx context.Context, repositoryID, production, development string) error {
|
||||
branches, err := s.ListBranches(ctx, repositoryID, "")
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: cannot list branches: %v", ErrInvalidRepositoryBranchPolicy, err)
|
||||
}
|
||||
available := make(map[string]struct{}, len(branches)*2)
|
||||
for _, branch := range branches {
|
||||
available[branch.Name] = struct{}{}
|
||||
if branch.Type == "remote" && branch.Remote != "" {
|
||||
available[branch.Remote+"/"+branch.Name] = struct{}{}
|
||||
}
|
||||
}
|
||||
for label, branch := range map[string]string{
|
||||
"production branch": production,
|
||||
"development branch": development,
|
||||
} {
|
||||
if _, ok := available[branch]; !ok {
|
||||
return fmt.Errorf("%w: %s %q does not exist", ErrInvalidRepositoryBranchPolicy, label, branch)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) ensureBranchPolicyStore() error {
|
||||
if s.branchPolicies == nil {
|
||||
return ErrRepositoryBranchPolicyStoreMissing
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) authorizeBranchPolicyRepository(ctx context.Context, repositoryID string) (*models.Repository, error) {
|
||||
repository, err := s.repoEntities.GetRepository(ctx, repositoryID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if repository == nil {
|
||||
return nil, repoerrors.ErrRepositoryNotFound
|
||||
}
|
||||
if err := s.authorizeWorkspaceID(ctx, repository.WorkspaceID); err != nil {
|
||||
return nil, repoerrors.ErrRepositoryNotFound
|
||||
}
|
||||
return repository, nil
|
||||
}
|
||||
|
||||
func (s *Service) authorizeWritableBranchPolicyRepository(ctx context.Context, repositoryID string) (*models.Repository, error) {
|
||||
repository, err := s.authorizeBranchPolicyRepository(ctx, repositoryID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
workspace, err := s.workspaces.GetWorkspace(ctx, repository.WorkspaceID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if workspace != nil && workspace.IsImproveKandev() {
|
||||
return nil, ErrRepositoryBranchPolicyReadOnly
|
||||
}
|
||||
return repository, nil
|
||||
}
|
||||
|
||||
func (s *Service) assertBranchPolicyNameFree(ctx context.Context, repositoryID, name, exceptID string) error {
|
||||
existing, err := s.branchPolicies.GetRepositoryBranchPolicyByName(ctx, repositoryID, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if existing != nil && existing.ID != exceptID {
|
||||
return fmt.Errorf("%w: %q", ErrRepositoryBranchPolicyNameConflict, existing.Name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func normalizeRepositoryBranchPolicy(policy *models.RepositoryBranchPolicy) (*models.RepositoryBranchPolicy, error) {
|
||||
policy.Name = strings.TrimSpace(policy.Name)
|
||||
policy.Description = strings.TrimSpace(policy.Description)
|
||||
policy.BaseBranch = strings.TrimSpace(policy.BaseBranch)
|
||||
policy.BranchTemplate = strings.TrimSpace(policy.BranchTemplate)
|
||||
policy.PullRequestTarget = strings.TrimSpace(policy.PullRequestTarget)
|
||||
if policy.PullRequestTarget == "" {
|
||||
policy.PullRequestTarget = policy.BaseBranch
|
||||
}
|
||||
if policy.Name == "" || len([]rune(policy.Name)) > repositoryBranchPolicyNameMaxLength {
|
||||
return nil, fmt.Errorf("%w: name must be between 1 and %d characters", ErrInvalidRepositoryBranchPolicy, repositoryBranchPolicyNameMaxLength)
|
||||
}
|
||||
if len([]rune(policy.Description)) > repositoryBranchPolicyDescriptionMaxLength {
|
||||
return nil, fmt.Errorf("%w: description must be at most %d characters", ErrInvalidRepositoryBranchPolicy, repositoryBranchPolicyDescriptionMaxLength)
|
||||
}
|
||||
if err := validatePolicyBranchRef(policy.BaseBranch, "base branch"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := worktree.ValidateBranchNameTemplate(policy.BranchTemplate); err != nil {
|
||||
return nil, fmt.Errorf("%w: branch template: %v", ErrInvalidRepositoryBranchPolicy, err)
|
||||
}
|
||||
if err := validatePolicyBranchRef(policy.PullRequestTarget, "pull request target"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return policy, nil
|
||||
}
|
||||
|
||||
func validatePolicyBranchRef(value, label string) error {
|
||||
if _, err := sanitizeGitRef(strings.TrimSpace(value), label); err != nil {
|
||||
return fmt.Errorf("%w: %v", ErrInvalidRepositoryBranchPolicy, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func gitflowPolicies(repositoryID, production, development string) []*models.RepositoryBranchPolicy {
|
||||
return []*models.RepositoryBranchPolicy{
|
||||
{RepositoryID: repositoryID, Name: "Feature", Description: "Feature branches", BaseBranch: development, BranchTemplate: "feature/{title}-{suffix}", PullRequestTarget: development},
|
||||
{RepositoryID: repositoryID, Name: "Bugfix", Description: "Bug-fix branches", BaseBranch: development, BranchTemplate: "bugfix/{title}-{suffix}", PullRequestTarget: development},
|
||||
{RepositoryID: repositoryID, Name: "Hotfix", Description: "Production hotfix branches", BaseBranch: production, BranchTemplate: "hotfix/{title}-{suffix}", PullRequestTarget: production},
|
||||
{RepositoryID: repositoryID, Name: "Release", Description: "Release branches", BaseBranch: development, BranchTemplate: "release/{title}-{suffix}", PullRequestTarget: production},
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) publishRepositoryBranchPolicyEvent(ctx context.Context, eventType, workspaceID string, policy *models.RepositoryBranchPolicy) {
|
||||
if s.eventBus == nil || policy == nil {
|
||||
return
|
||||
}
|
||||
event := map[string]interface{}{
|
||||
"id": policy.ID, "repository_id": policy.RepositoryID, "workspace_id": workspaceID, "name": policy.Name,
|
||||
"description": policy.Description, "base_branch": policy.BaseBranch,
|
||||
"branch_template": policy.BranchTemplate, "pull_request_target": policy.PullRequestTarget,
|
||||
"created_at": policy.CreatedAt.Format(time.RFC3339), "updated_at": policy.UpdatedAt.Format(time.RFC3339),
|
||||
}
|
||||
if err := s.eventBus.Publish(ctx, eventType, bus.NewEvent(eventType, "task-service", event)); err != nil {
|
||||
s.logger.Error("failed to publish repository branch policy event", zap.String("event_type", eventType), zap.String("repository_branch_policy_id", policy.ID), zap.Error(err))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
"github.com/kandev/kandev/internal/task/repository/repoerrors"
|
||||
)
|
||||
|
||||
func seedBranchPolicyRepository(t *testing.T, repo interface {
|
||||
CreateWorkspace(context.Context, *models.Workspace) error
|
||||
CreateRepository(context.Context, *models.Repository) error
|
||||
}) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
if err := repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws-policy-service", Name: "Policy workspace"}); err != nil {
|
||||
t.Fatalf("create workspace: %v", err)
|
||||
}
|
||||
if err := repo.CreateRepository(ctx, &models.Repository{
|
||||
ID: "repo-policy-service", WorkspaceID: "ws-policy-service", Name: "Policy repo", DefaultBranch: "main",
|
||||
}); err != nil {
|
||||
t.Fatalf("create repository: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRepositoryBranchPolicyServiceNormalizesAndRejectsInvalidUpdates(t *testing.T) {
|
||||
svc, _, repo := createTestService(t)
|
||||
seedBranchPolicyRepository(t, repo)
|
||||
ctx := context.Background()
|
||||
|
||||
policy, err := svc.CreateRepositoryBranchPolicy(ctx, &CreateRepositoryBranchPolicyRequest{
|
||||
RepositoryID: "repo-policy-service", Name: " Feature ", Description: " branch flow ",
|
||||
BaseBranch: " develop ", BranchTemplate: " feature/{title}-{suffix} ", PullRequestTarget: " develop ",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateRepositoryBranchPolicy: %v", err)
|
||||
}
|
||||
if policy.Name != "Feature" || policy.Description != "branch flow" || policy.BaseBranch != "develop" {
|
||||
t.Fatalf("normalized policy = %+v", policy)
|
||||
}
|
||||
|
||||
_, err = svc.CreateRepositoryBranchPolicy(ctx, &CreateRepositoryBranchPolicyRequest{
|
||||
RepositoryID: "repo-policy-service", Name: "feature", BaseBranch: "main",
|
||||
BranchTemplate: "feature/{title}-{suffix}", PullRequestTarget: "main",
|
||||
})
|
||||
if !errors.Is(err, ErrRepositoryBranchPolicyNameConflict) {
|
||||
t.Fatalf("duplicate name error = %v", err)
|
||||
}
|
||||
|
||||
tooLong := make([]rune, repositoryBranchPolicyDescriptionMaxLength+1)
|
||||
for i := range tooLong {
|
||||
tooLong[i] = 'x'
|
||||
}
|
||||
_, err = svc.UpdateRepositoryBranchPolicy(ctx, policy.ID, &UpdateRepositoryBranchPolicyRequest{
|
||||
Description: stringPointer(string(tooLong)),
|
||||
})
|
||||
if !errors.Is(err, ErrInvalidRepositoryBranchPolicy) {
|
||||
t.Fatalf("long description error = %v", err)
|
||||
}
|
||||
|
||||
if _, err := svc.GetRepositoryBranchPolicy(ctx, "missing"); !errors.Is(err, repoerrors.ErrRepositoryBranchPolicyNotFound) {
|
||||
t.Fatalf("missing policy error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeRepositoryBranchPolicyDefaultsPullRequestTarget(t *testing.T) {
|
||||
policy, err := normalizeRepositoryBranchPolicy(&models.RepositoryBranchPolicy{
|
||||
Name: "Feature",
|
||||
BaseBranch: "develop",
|
||||
BranchTemplate: "feature/{title}-{suffix}",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("normalizeRepositoryBranchPolicy: %v", err)
|
||||
}
|
||||
if policy.PullRequestTarget != "develop" {
|
||||
t.Fatalf("pull request target = %q, want base branch", policy.PullRequestTarget)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRepositoryBranchPolicyServiceGitflowStarterIsAtomicAndOneTime(t *testing.T) {
|
||||
isolateGitEnvForTest(t)
|
||||
svc, eventBus, repo := createTestService(t)
|
||||
seedBranchPolicyRepository(t, repo)
|
||||
repository, err := repo.GetRepository(context.Background(), "repo-policy-service")
|
||||
if err != nil {
|
||||
t.Fatalf("get repository: %v", err)
|
||||
}
|
||||
repositoryPath := filepath.Join(t.TempDir(), "policy-repo")
|
||||
initRealGitRepo(t, repositoryPath)
|
||||
cmd := exec.Command("git", "branch", "develop")
|
||||
cmd.Dir = repositoryPath
|
||||
cmd.Env = isolatedGitEnv()
|
||||
if output, branchErr := cmd.CombinedOutput(); branchErr != nil {
|
||||
t.Fatalf("create develop branch: %v (%s)", branchErr, output)
|
||||
}
|
||||
repository.LocalPath = repositoryPath
|
||||
repository.SourceType = sourceTypeLocal
|
||||
if err := repo.UpdateRepository(context.Background(), repository); err != nil {
|
||||
t.Fatalf("update repository path: %v", err)
|
||||
}
|
||||
ctx := context.Background()
|
||||
|
||||
policies, err := svc.CreateGitflowRepositoryBranchPolicies(ctx, &CreateGitflowRepositoryBranchPoliciesRequest{
|
||||
RepositoryID: "repo-policy-service", ProductionBranch: "main", DevelopmentBranch: "develop",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateGitflowRepositoryBranchPolicies: %v", err)
|
||||
}
|
||||
if len(policies) != 4 {
|
||||
t.Fatalf("seeded %d policies, want 4", len(policies))
|
||||
}
|
||||
if policies[0].BaseBranch != "develop" || policies[2].BaseBranch != "main" || policies[3].PullRequestTarget != "main" {
|
||||
t.Fatalf("gitflow policies = %+v", policies)
|
||||
}
|
||||
if len(eventBus.GetPublishedEvents()) != 4 {
|
||||
t.Fatalf("published events = %d, want 4", len(eventBus.GetPublishedEvents()))
|
||||
}
|
||||
data, ok := eventBus.GetPublishedEvents()[0].Data.(map[string]interface{})
|
||||
if !ok || data["workspace_id"] != "ws-policy-service" {
|
||||
t.Fatalf("first policy event data = %#v, want workspace_id", eventBus.GetPublishedEvents()[0].Data)
|
||||
}
|
||||
|
||||
_, err = svc.CreateGitflowRepositoryBranchPolicies(ctx, &CreateGitflowRepositoryBranchPoliciesRequest{
|
||||
RepositoryID: "repo-policy-service", ProductionBranch: "main", DevelopmentBranch: "develop",
|
||||
})
|
||||
if !errors.Is(err, ErrRepositoryBranchPolicyAlreadySeeded) {
|
||||
t.Fatalf("second starter error = %v", err)
|
||||
}
|
||||
stored, err := repo.ListRepositoryBranchPolicies(ctx, "repo-policy-service")
|
||||
if err != nil || len(stored) != 4 {
|
||||
t.Fatalf("stored policies after rejected starter = %d, err=%v", len(stored), err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRepositoryBranchPolicyServiceRejectsImproveWorkspaceMutations(t *testing.T) {
|
||||
svc, eventBus, repo := createTestService(t)
|
||||
seedBranchPolicyRepository(t, repo)
|
||||
if err := repo.CreateRepositoryBranchPolicy(context.Background(), &models.RepositoryBranchPolicy{
|
||||
ID: "policy-improve", RepositoryID: "repo-policy-service", Name: "Existing",
|
||||
BaseBranch: "main", BranchTemplate: "feature/{title}-{suffix}", PullRequestTarget: "main",
|
||||
}); err != nil {
|
||||
t.Fatalf("seed branch policy: %v", err)
|
||||
}
|
||||
workspace, err := repo.GetWorkspace(context.Background(), "ws-policy-service")
|
||||
if err != nil {
|
||||
t.Fatalf("get workspace: %v", err)
|
||||
}
|
||||
workspace.Name = models.WorkspaceNameImproveKandev
|
||||
if err := repo.UpdateWorkspace(context.Background(), workspace); err != nil {
|
||||
t.Fatalf("update workspace: %v", err)
|
||||
}
|
||||
|
||||
_, err = svc.CreateRepositoryBranchPolicy(context.Background(), &CreateRepositoryBranchPolicyRequest{
|
||||
RepositoryID: "repo-policy-service", Name: "Feature", BaseBranch: "main",
|
||||
BranchTemplate: "feature/{title}-{suffix}", PullRequestTarget: "main",
|
||||
})
|
||||
if !errors.Is(err, ErrRepositoryBranchPolicyReadOnly) {
|
||||
t.Fatalf("create read-only workspace error = %v", err)
|
||||
}
|
||||
|
||||
_, err = svc.UpdateRepositoryBranchPolicy(context.Background(), "policy-improve", &UpdateRepositoryBranchPolicyRequest{
|
||||
Name: stringPointer("Renamed"),
|
||||
})
|
||||
if !errors.Is(err, ErrRepositoryBranchPolicyReadOnly) {
|
||||
t.Fatalf("update read-only workspace error = %v", err)
|
||||
}
|
||||
|
||||
_, err = svc.CreateGitflowRepositoryBranchPolicies(context.Background(), &CreateGitflowRepositoryBranchPoliciesRequest{
|
||||
RepositoryID: "repo-policy-service", ProductionBranch: "main", DevelopmentBranch: "develop",
|
||||
})
|
||||
if !errors.Is(err, ErrRepositoryBranchPolicyReadOnly) {
|
||||
t.Fatalf("gitflow read-only workspace error = %v", err)
|
||||
}
|
||||
|
||||
err = svc.DeleteRepositoryBranchPolicy(context.Background(), "policy-improve")
|
||||
if !errors.Is(err, ErrRepositoryBranchPolicyReadOnly) {
|
||||
t.Fatalf("delete read-only workspace error = %v", err)
|
||||
}
|
||||
if len(eventBus.GetPublishedEvents()) != 0 {
|
||||
t.Fatalf("read-only mutation published events = %d", len(eventBus.GetPublishedEvents()))
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateTaskRejectsRemoteContributionPolicyBaseMismatch(t *testing.T) {
|
||||
svc, _, repo := createTestService(t)
|
||||
ctx := context.Background()
|
||||
workflowID := seedWorkspaceAndWorkflowForCreate(t, ctx, repo, "ws-policy-remote")
|
||||
if err := repo.CreateRepository(ctx, &models.Repository{
|
||||
ID: "repo-policy-remote", WorkspaceID: "ws-policy-remote", Name: "remote", DefaultBranch: "main",
|
||||
}); err != nil {
|
||||
t.Fatalf("create repository: %v", err)
|
||||
}
|
||||
policy, err := svc.CreateRepositoryBranchPolicy(ctx, &CreateRepositoryBranchPolicyRequest{
|
||||
RepositoryID: "repo-policy-remote", Name: "Feature", BaseBranch: "main",
|
||||
BranchTemplate: "feature/{title}-{suffix}", PullRequestTarget: "main",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("create policy: %v", err)
|
||||
}
|
||||
|
||||
_, err = svc.CreateTask(ctx, &CreateTaskRequest{
|
||||
WorkspaceID: "ws-policy-remote", WorkflowID: workflowID, Title: "Remote contribution",
|
||||
Repositories: []TaskRepositoryInput{{
|
||||
RepositoryID: "repo-policy-remote", BranchPolicyID: policy.ID, BaseBranch: "release",
|
||||
CheckoutBranch: "feature/remote", RemoteContribution: &models.RemoteContribution{
|
||||
Version: 1, Provider: "github", Kind: "pull_request", CanonicalURL: "https://github.com/acme/remote/pull/1",
|
||||
Number: 1, State: "open", BaseBranch: "release", HeadBranch: "feature/remote",
|
||||
HeadSHA: "0123456789abcdef0123456789abcdef01234567",
|
||||
SourceRepository: models.RemoteContributionRepository{
|
||||
Host: "github.com", Path: "acme/remote", RemoteURL: "https://github.com/acme/remote.git",
|
||||
},
|
||||
},
|
||||
}},
|
||||
})
|
||||
if err == nil || !strings.Contains(err.Error(), "does not match branch policy base branch") {
|
||||
t.Fatalf("remote contribution mismatch error = %v", err)
|
||||
}
|
||||
_, total, err := repo.ListTasksByWorkspace(ctx, "ws-policy-remote", "", "", "", 1, 50, "", false, false, false, false)
|
||||
if err != nil {
|
||||
t.Fatalf("list tasks after rejected create: %v", err)
|
||||
}
|
||||
if total != 0 {
|
||||
t.Fatalf("rejected remote contribution mismatch persisted %d task(s)", total)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReplaceTaskRepositoriesPreservesFreshBranchWithPolicySnapshot(t *testing.T) {
|
||||
svc, _, repo := createTestService(t)
|
||||
ctx := context.Background()
|
||||
workflowID := seedWorkspaceAndWorkflowForCreate(t, ctx, repo, "ws-policy-fresh")
|
||||
if err := repo.CreateRepository(ctx, &models.Repository{
|
||||
ID: "repo-policy-fresh", WorkspaceID: "ws-policy-fresh", Name: "fresh", DefaultBranch: "main",
|
||||
}); err != nil {
|
||||
t.Fatalf("create repository: %v", err)
|
||||
}
|
||||
policy, err := svc.CreateRepositoryBranchPolicy(ctx, &CreateRepositoryBranchPolicyRequest{
|
||||
RepositoryID: "repo-policy-fresh", Name: "Feature", BaseBranch: "main",
|
||||
BranchTemplate: "feature/{title}-{suffix}", PullRequestTarget: "main",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("create policy: %v", err)
|
||||
}
|
||||
|
||||
result, err := svc.CreateTask(ctx, &CreateTaskRequest{
|
||||
WorkspaceID: "ws-policy-fresh", WorkflowID: workflowID, Title: "Fresh branch",
|
||||
Repositories: []TaskRepositoryInput{{
|
||||
RepositoryID: "repo-policy-fresh", BranchPolicyID: policy.ID, BaseBranch: "main",
|
||||
}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("create task: %v", err)
|
||||
}
|
||||
if _, err := svc.UpdateRepositoryBranchPolicy(ctx, policy.ID, &UpdateRepositoryBranchPolicyRequest{
|
||||
BaseBranch: stringPointer("develop"),
|
||||
}); err != nil {
|
||||
t.Fatalf("update policy after task creation: %v", err)
|
||||
}
|
||||
|
||||
if err := svc.ReplaceTaskRepositories(ctx, result.Task.ID, "ws-policy-fresh", []TaskRepositoryInput{{
|
||||
RepositoryID: "repo-policy-fresh", BranchPolicyID: policy.ID, BaseBranch: "feature/fresh-branch",
|
||||
PreserveBaseBranch: true,
|
||||
}}); err != nil {
|
||||
t.Fatalf("replace task repositories: %v", err)
|
||||
}
|
||||
|
||||
linked, err := repo.ListTaskRepositories(ctx, result.Task.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("list task repositories: %v", err)
|
||||
}
|
||||
if len(linked) != 1 {
|
||||
t.Fatalf("task repositories = %+v, want one association", linked)
|
||||
}
|
||||
if linked[0].BaseBranch != "feature/fresh-branch" {
|
||||
t.Fatalf("effective base branch = %q, want generated fresh branch", linked[0].BaseBranch)
|
||||
}
|
||||
if linked[0].BranchPolicyBaseBranch != "main" {
|
||||
t.Fatalf("policy snapshot base branch = %q, want main", linked[0].BranchPolicyBaseBranch)
|
||||
}
|
||||
}
|
||||
|
||||
func stringPointer(value string) *string { return &value }
|
||||
@@ -13,6 +13,7 @@ type TaskRepositoryInput struct {
|
||||
RepositoryID string `json:"repository_id"`
|
||||
BaseBranch string `json:"base_branch"`
|
||||
CheckoutBranch string `json:"checkout_branch,omitempty"`
|
||||
BranchPolicyID string `json:"branch_policy_id,omitempty"`
|
||||
PRNumber int `json:"pr_number,omitempty"` // GitHub PR number when CheckoutBranch is a PR head; persisted into task_repositories.metadata["pr_number"].
|
||||
LocalPath string `json:"local_path,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
@@ -26,6 +27,13 @@ type TaskRepositoryInput struct {
|
||||
ProviderOwner string `json:"provider_owner,omitempty"`
|
||||
ProviderName string `json:"provider_name,omitempty"`
|
||||
|
||||
// PreserveBaseBranch keeps an effective branch produced after policy
|
||||
// resolution (for example, the branch created by the local fresh-branch
|
||||
// flow) when task repositories are recreated. It is internal-only: normal
|
||||
// task creation must always anchor a policy-backed repository to the
|
||||
// policy's immutable base branch.
|
||||
PreserveBaseBranch bool `json:"-"`
|
||||
|
||||
// RemoteContribution is server-authored after provider resolution. It is
|
||||
// intentionally excluded from JSON request surfaces; callers must not be
|
||||
// able to forge a writable source binding.
|
||||
@@ -54,7 +62,8 @@ type TaskRepositoryInput struct {
|
||||
// resolver. Plugin descriptors must come through the authenticated plugin
|
||||
// Host Tasks.Create path, which sets this marker only after validating the
|
||||
// active plugin's provider ownership and clone origin.
|
||||
TrustedProviderDescriptor bool `json:"-"`
|
||||
TrustedProviderDescriptor bool `json:"-"`
|
||||
BranchPolicySnapshot *models.RepositoryBranchPolicy `json:"-"`
|
||||
}
|
||||
|
||||
// CreateTaskRequest contains the data for creating a new task
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
"github.com/kandev/kandev/internal/task/repository/repoerrors"
|
||||
)
|
||||
|
||||
// validateTaskRepositoryPolicies resolves every explicit policy before the task
|
||||
// row is inserted. This keeps a stale or cross-repository policy from creating
|
||||
// a task that cannot later materialize its requested branch workflow.
|
||||
func (s *Service) validateTaskRepositoryPolicies(ctx context.Context, workspaceID string, inputs []TaskRepositoryInput) error {
|
||||
for index := range inputs {
|
||||
input := &inputs[index]
|
||||
if input.BranchPolicyID == "" {
|
||||
continue
|
||||
}
|
||||
if input.RepositoryID == "" {
|
||||
return fmt.Errorf("%w: branch policy selection requires a repository id", ErrInvalidRepositoryBranchPolicy)
|
||||
}
|
||||
repository, err := s.repoEntities.GetRepository(ctx, input.RepositoryID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if repository == nil || repository.WorkspaceID != workspaceID {
|
||||
return repoerrors.ErrRepositoryNotFound
|
||||
}
|
||||
policy, err := s.resolveTaskRepositoryPolicy(ctx, input.RepositoryID, *input)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if input.RemoteContribution != nil && policy.BaseBranch != input.RemoteContribution.BaseBranch {
|
||||
return fmt.Errorf("remote contribution base branch %q does not match branch policy base branch %q", input.RemoteContribution.BaseBranch, policy.BaseBranch)
|
||||
}
|
||||
input.BranchPolicySnapshot = cloneBranchPolicy(policy)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// preserveTaskRepositoryPolicySnapshots carries the immutable policy fields
|
||||
// across an association replacement. Fresh-branch creation replaces the row
|
||||
// after the branch exists, so resolving the policy again could otherwise pick
|
||||
// up a later edit or fail after the policy was deleted.
|
||||
func preserveTaskRepositoryPolicySnapshots(inputs []TaskRepositoryInput, existing []*models.TaskRepository) {
|
||||
for index := range inputs {
|
||||
input := &inputs[index]
|
||||
if input.BranchPolicyID == "" || input.BranchPolicySnapshot != nil {
|
||||
continue
|
||||
}
|
||||
for _, repository := range existing {
|
||||
if repository.RepositoryID != input.RepositoryID || repository.BranchPolicyID != input.BranchPolicyID {
|
||||
continue
|
||||
}
|
||||
if snapshot := branchPolicyFromTaskRepository(repository); snapshot != nil {
|
||||
input.BranchPolicySnapshot = snapshot
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func branchPolicyFromTaskRepository(repository *models.TaskRepository) *models.RepositoryBranchPolicy {
|
||||
if repository == nil || repository.BranchPolicyID == "" || repository.BranchPolicyName == "" ||
|
||||
repository.BranchPolicyBaseBranch == "" || repository.BranchPolicyBranchTemplate == "" ||
|
||||
repository.BranchPolicyPullRequestTarget == "" {
|
||||
return nil
|
||||
}
|
||||
return &models.RepositoryBranchPolicy{
|
||||
ID: repository.BranchPolicyID,
|
||||
RepositoryID: repository.RepositoryID,
|
||||
Name: repository.BranchPolicyName,
|
||||
BaseBranch: repository.BranchPolicyBaseBranch,
|
||||
BranchTemplate: repository.BranchPolicyBranchTemplate,
|
||||
PullRequestTarget: repository.BranchPolicyPullRequestTarget,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) resolveTaskRepositoryPolicy(ctx context.Context, repositoryID string, input TaskRepositoryInput) (*models.RepositoryBranchPolicy, error) {
|
||||
if input.BranchPolicyID == "" {
|
||||
return nil, nil
|
||||
}
|
||||
if input.BranchPolicySnapshot != nil {
|
||||
if input.BranchPolicySnapshot.ID == input.BranchPolicyID && input.BranchPolicySnapshot.RepositoryID == repositoryID {
|
||||
return cloneBranchPolicy(input.BranchPolicySnapshot), nil
|
||||
}
|
||||
}
|
||||
if s.branchPolicies == nil {
|
||||
return nil, ErrRepositoryBranchPolicyStoreMissing
|
||||
}
|
||||
policy, err := s.branchPolicies.GetRepositoryBranchPolicy(ctx, input.BranchPolicyID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repoerrors.ErrRepositoryBranchPolicyNotFound) {
|
||||
return nil, fmt.Errorf("%w: %w", ErrInvalidRepositoryBranchPolicy, ErrRepositoryBranchPolicyStale)
|
||||
}
|
||||
return nil, fmt.Errorf("%w: resolve selected policy: %v", ErrInvalidRepositoryBranchPolicy, err)
|
||||
}
|
||||
if policy == nil {
|
||||
return nil, fmt.Errorf("%w: %w", ErrInvalidRepositoryBranchPolicy, ErrRepositoryBranchPolicyStale)
|
||||
}
|
||||
if policy.RepositoryID != repositoryID {
|
||||
return nil, fmt.Errorf("%w: selected policy does not belong to repository", ErrInvalidRepositoryBranchPolicy)
|
||||
}
|
||||
return cloneBranchPolicy(policy), nil
|
||||
}
|
||||
|
||||
func cloneBranchPolicy(policy *models.RepositoryBranchPolicy) *models.RepositoryBranchPolicy {
|
||||
if policy == nil {
|
||||
return nil
|
||||
}
|
||||
copy := *policy
|
||||
return ©
|
||||
}
|
||||
@@ -252,6 +252,9 @@ func (s *Service) prepareTaskForCreation(ctx context.Context, req *CreateTaskReq
|
||||
if err := s.inheritParentRepositories(ctx, req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.validateTaskRepositoryPolicies(ctx, req.WorkspaceID, req.Repositories); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// For office tasks, resolve workflow from workspace
|
||||
if isOfficeRequest(req) && req.WorkflowID == "" {
|
||||
@@ -831,6 +834,19 @@ func (s *Service) createTaskRepositories(ctx context.Context, taskID, workspaceI
|
||||
if repositoryID == "" {
|
||||
return fmt.Errorf("repository_id is required")
|
||||
}
|
||||
policy, err := s.resolveTaskRepositoryPolicy(ctx, repositoryID, repoInput)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if policy != nil {
|
||||
if repoInput.RemoteContribution != nil {
|
||||
if policy.BaseBranch != repoInput.RemoteContribution.BaseBranch {
|
||||
return fmt.Errorf("remote contribution base branch %q does not match branch policy base branch %q", repoInput.RemoteContribution.BaseBranch, policy.BaseBranch)
|
||||
}
|
||||
} else if !repoInput.PreserveBaseBranch {
|
||||
baseBranch = policy.BaseBranch
|
||||
}
|
||||
}
|
||||
// Multi-branch validation: the same repository may appear multiple
|
||||
// times in a task on different branches. Identity is
|
||||
// (repository_id, base_branch, checkout_branch) — base_branch matters
|
||||
@@ -874,6 +890,13 @@ func (s *Service) createTaskRepositories(ctx context.Context, taskID, workspaceI
|
||||
Position: i,
|
||||
Metadata: metadata,
|
||||
}
|
||||
if policy != nil {
|
||||
taskRepo.BranchPolicyID = policy.ID
|
||||
taskRepo.BranchPolicyName = policy.Name
|
||||
taskRepo.BranchPolicyBaseBranch = policy.BaseBranch
|
||||
taskRepo.BranchPolicyBranchTemplate = policy.BranchTemplate
|
||||
taskRepo.BranchPolicyPullRequestTarget = policy.PullRequestTarget
|
||||
}
|
||||
if err := s.taskRepos.CreateTaskRepository(ctx, taskRepo); err != nil {
|
||||
s.logger.Error("failed to create task repository", zap.Error(err))
|
||||
return err
|
||||
@@ -1522,6 +1545,15 @@ func (s *Service) ReplaceTaskRepositories(ctx context.Context, taskID, workspace
|
||||
|
||||
// replaceTaskRepositories deletes all existing task-repository associations and recreates them.
|
||||
func (s *Service) replaceTaskRepositories(ctx context.Context, taskID, workspaceID string, repositories []TaskRepositoryInput) error {
|
||||
existing, err := s.taskRepos.ListTaskRepositories(ctx, taskID)
|
||||
if err != nil {
|
||||
s.logger.Error("failed to load existing task repositories", zap.Error(err))
|
||||
return err
|
||||
}
|
||||
preserveTaskRepositoryPolicySnapshots(repositories, existing)
|
||||
if err := s.validateTaskRepositoryPolicies(ctx, workspaceID, repositories); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.taskRepos.DeleteTaskRepositoriesByTask(ctx, taskID); err != nil {
|
||||
s.logger.Error("failed to delete task repositories", zap.Error(err))
|
||||
return err
|
||||
|
||||
@@ -199,6 +199,7 @@ func createTestServiceWithSessionsRepo(
|
||||
GitSnapshots: repo,
|
||||
RepoEntities: repo,
|
||||
RepositorySets: repo,
|
||||
BranchPolicies: repo,
|
||||
RepositoryCleanup: repo,
|
||||
Executors: repo,
|
||||
Environments: repo,
|
||||
|
||||
@@ -960,11 +960,15 @@ func (s *Service) populateWorkspaceRepositorySpecs(ctx context.Context, taskID s
|
||||
branchPlans := worktree.BuildBranchIdentityPlans(workspaceBranchIdentityInputs(projections))
|
||||
for index, projection := range projections {
|
||||
taskRepository, repository := projection.taskRepository, projection.repository
|
||||
branchTemplate := repository.WorktreeBranchTemplate
|
||||
if taskRepository.BranchPolicyBranchTemplate != "" {
|
||||
branchTemplate = taskRepository.BranchPolicyBranchTemplate
|
||||
}
|
||||
spec := lifecycle.WorkspaceRepositorySpec{
|
||||
RepositoryID: taskRepository.RepositoryID, RepositoryPath: repository.LocalPath, RepoName: projection.repoName,
|
||||
BaseBranch: taskRepository.BaseBranch, DefaultBranch: repository.DefaultBranch,
|
||||
CheckoutBranch: taskRepository.CheckoutBranch, WorktreeBranchPrefix: repository.WorktreeBranchPrefix,
|
||||
WorktreeBranchTemplate: repository.WorktreeBranchTemplate, PullBeforeWorktree: repository.PullBeforeWorktree,
|
||||
WorktreeBranchTemplate: branchTemplate, PullBeforeWorktree: repository.PullBeforeWorktree,
|
||||
}
|
||||
if worktree := worktreesByIdentity[workspaceWorktreeKey{repositoryID: taskRepository.RepositoryID, branchSlug: branchPlans[index].IdentitySlug}]; worktree != nil {
|
||||
spec.WorktreeID = worktree.WorktreeID
|
||||
|
||||
@@ -166,8 +166,9 @@ type Task struct {
|
||||
|
||||
// TaskRepositoryInput for creating/updating task repositories
|
||||
type TaskRepositoryInput struct {
|
||||
RepositoryID string `json:"repository_id" binding:"required"`
|
||||
BaseBranch string `json:"base_branch" binding:"required"`
|
||||
RepositoryID string `json:"repository_id" binding:"required"`
|
||||
BaseBranch string `json:"base_branch" binding:"required"`
|
||||
BranchPolicyID string `json:"branch_policy_id,omitempty"`
|
||||
}
|
||||
|
||||
// CreateTaskRequest for creating a new task
|
||||
|
||||
@@ -34,6 +34,14 @@ const (
|
||||
ActionRepositorySetUpdate = "repository_set.update"
|
||||
ActionRepositorySetDelete = "repository_set.delete"
|
||||
|
||||
// Repository branch policy actions
|
||||
ActionRepositoryBranchPolicyList = "repository_branch_policy.list"
|
||||
ActionRepositoryBranchPolicyCreate = "repository_branch_policy.create"
|
||||
ActionRepositoryBranchPolicyGet = "repository_branch_policy.get"
|
||||
ActionRepositoryBranchPolicyUpdate = "repository_branch_policy.update"
|
||||
ActionRepositoryBranchPolicyDelete = "repository_branch_policy.delete"
|
||||
ActionRepositoryBranchPolicyGitflow = "repository_branch_policy.gitflow"
|
||||
|
||||
// Repository Script actions
|
||||
ActionRepositoryScriptList = "repository.script.list"
|
||||
ActionRepositoryScriptCreate = "repository.script.create"
|
||||
@@ -189,84 +197,87 @@ const (
|
||||
|
||||
// Native code review. The *.run / *.cancel / *.get / *.finding.update /
|
||||
// *.clear actions are client requests; the rest are server notifications.
|
||||
ActionTaskReviewRun = "task.review.run"
|
||||
ActionTaskReviewCancel = "task.review.cancel"
|
||||
ActionTaskReviewGet = "task.review.get"
|
||||
ActionTaskReviewFindingUpdate = "task.review.finding.update"
|
||||
ActionTaskReviewClear = "task.review.clear"
|
||||
ActionTaskReviewRunUpdated = "task.review.run_updated"
|
||||
ActionTaskReviewFindingsPublished = "task.review.findings_published"
|
||||
ActionTaskReviewFindingUpdated = "task.review.finding_updated"
|
||||
ActionTaskReviewCleared = "task.review.cleared"
|
||||
ActionAgentUpdated = "agent.updated"
|
||||
ActionAgentAvailableUpdated = "agent.available.updated"
|
||||
ActionAgentInstallStarted = "agent.install.started"
|
||||
ActionAgentInstallOutput = "agent.install.output"
|
||||
ActionAgentInstallFinished = "agent.install.finished"
|
||||
ActionAgentUpdateStarted = "agent.update.started"
|
||||
ActionAgentUpdateOutput = "agent.update.output"
|
||||
ActionAgentUpdateFinished = "agent.update.finished"
|
||||
ActionWorkspaceCreated = "workspace.created"
|
||||
ActionWorkspaceUpdated = "workspace.updated"
|
||||
ActionWorkspaceDeleted = "workspace.deleted"
|
||||
ActionWorkflowCreated = "workflow.created"
|
||||
ActionWorkflowUpdated = "workflow.updated"
|
||||
ActionWorkflowDeleted = "workflow.deleted"
|
||||
ActionWorkflowStepCreated = "workflow.step.created"
|
||||
ActionWorkflowStepUpdated = "workflow.step.updated"
|
||||
ActionWorkflowStepDeleted = "workflow.step.deleted"
|
||||
ActionSessionMessageAdded = "session.message.added"
|
||||
ActionSessionMessageUpdated = "session.message.updated"
|
||||
ActionSessionMessageDeleted = "session.message.deleted"
|
||||
ActionSessionStateChanged = "session.state_changed"
|
||||
ActionSessionActivityChanged = "session.activity_changed"
|
||||
ActionSessionCancellationChanged = "session.cancellation_changed"
|
||||
ActionTaskStatusSummaryUpdated = "task.status_summary.updated"
|
||||
ActionSessionAgentctlStarting = "session.agentctl_starting"
|
||||
ActionSessionAgentctlReady = "session.agentctl_ready"
|
||||
ActionSessionAgentctlError = "session.agentctl_error"
|
||||
ActionSessionTurnStarted = "session.turn.started"
|
||||
ActionSessionTurnCompleted = "session.turn.completed"
|
||||
ActionSessionAvailableCommands = "session.available_commands"
|
||||
ActionSessionModeChanged = "session.mode_changed"
|
||||
ActionSessionAgentCapabilities = "session.agent_capabilities"
|
||||
ActionSessionModelsUpdated = "session.models_updated"
|
||||
ActionSessionModelFallback = "session.model_fallback"
|
||||
ActionSessionModelSelectionWarning = "session.model_selection_warning"
|
||||
ActionSessionMCPStatusUpdated = "session.mcp_status_updated"
|
||||
ActionSessionInfoUpdated = "session.info_updated"
|
||||
ActionSessionSetMode = "session.set_mode"
|
||||
ActionSessionTodosUpdated = "session.todos_updated"
|
||||
ActionSessionPromptUsage = "session.prompt_usage"
|
||||
ActionSessionPollModeChanged = "session.poll_mode_changed"
|
||||
ActionSessionRouteChanging = "session.route_changing"
|
||||
ActionSessionRouteChanged = "session.route_changed"
|
||||
ActionSessionCapabilitiesReplaced = "session.capabilities_replaced"
|
||||
ActionSessionRouteWaiting = "session.route_waiting"
|
||||
ActionSessionRoutePending = "session.route_pending"
|
||||
ActionInputRequested = "input.requested"
|
||||
ActionRepositoryCreated = "repository.created"
|
||||
ActionRepositoryUpdated = "repository.updated"
|
||||
ActionRepositoryDeleted = "repository.deleted"
|
||||
ActionRepositorySetCreated = "repository_set.created"
|
||||
ActionRepositorySetUpdated = "repository_set.updated"
|
||||
ActionRepositorySetDeleted = "repository_set.deleted"
|
||||
ActionRepositoryScriptCreated = "repository.script.created"
|
||||
ActionRepositoryScriptUpdated = "repository.script.updated"
|
||||
ActionRepositoryScriptDeleted = "repository.script.deleted"
|
||||
ActionExecutorCreated = "executor.created"
|
||||
ActionExecutorUpdated = "executor.updated"
|
||||
ActionExecutorDeleted = "executor.deleted"
|
||||
ActionEnvironmentCreated = "environment.created"
|
||||
ActionEnvironmentUpdated = "environment.updated"
|
||||
ActionEnvironmentDeleted = "environment.deleted"
|
||||
ActionExecutorProfileCreated = "executor.profile.created"
|
||||
ActionExecutorProfileUpdated = "executor.profile.updated"
|
||||
ActionExecutorProfileDeleted = "executor.profile.deleted"
|
||||
ActionExecutorPrepareProgress = "executor.prepare.progress"
|
||||
ActionExecutorPrepareCompleted = "executor.prepare.completed"
|
||||
ActionSystemMetricsUpdated = "system.metrics.updated"
|
||||
ActionUpdateAvailable = "system.update_available"
|
||||
ActionTaskReviewRun = "task.review.run"
|
||||
ActionTaskReviewCancel = "task.review.cancel"
|
||||
ActionTaskReviewGet = "task.review.get"
|
||||
ActionTaskReviewFindingUpdate = "task.review.finding.update"
|
||||
ActionTaskReviewClear = "task.review.clear"
|
||||
ActionTaskReviewRunUpdated = "task.review.run_updated"
|
||||
ActionTaskReviewFindingsPublished = "task.review.findings_published"
|
||||
ActionTaskReviewFindingUpdated = "task.review.finding_updated"
|
||||
ActionTaskReviewCleared = "task.review.cleared"
|
||||
ActionAgentUpdated = "agent.updated"
|
||||
ActionAgentAvailableUpdated = "agent.available.updated"
|
||||
ActionAgentInstallStarted = "agent.install.started"
|
||||
ActionAgentInstallOutput = "agent.install.output"
|
||||
ActionAgentInstallFinished = "agent.install.finished"
|
||||
ActionAgentUpdateStarted = "agent.update.started"
|
||||
ActionAgentUpdateOutput = "agent.update.output"
|
||||
ActionAgentUpdateFinished = "agent.update.finished"
|
||||
ActionWorkspaceCreated = "workspace.created"
|
||||
ActionWorkspaceUpdated = "workspace.updated"
|
||||
ActionWorkspaceDeleted = "workspace.deleted"
|
||||
ActionWorkflowCreated = "workflow.created"
|
||||
ActionWorkflowUpdated = "workflow.updated"
|
||||
ActionWorkflowDeleted = "workflow.deleted"
|
||||
ActionWorkflowStepCreated = "workflow.step.created"
|
||||
ActionWorkflowStepUpdated = "workflow.step.updated"
|
||||
ActionWorkflowStepDeleted = "workflow.step.deleted"
|
||||
ActionSessionMessageAdded = "session.message.added"
|
||||
ActionSessionMessageUpdated = "session.message.updated"
|
||||
ActionSessionMessageDeleted = "session.message.deleted"
|
||||
ActionSessionStateChanged = "session.state_changed"
|
||||
ActionSessionActivityChanged = "session.activity_changed"
|
||||
ActionSessionCancellationChanged = "session.cancellation_changed"
|
||||
ActionTaskStatusSummaryUpdated = "task.status_summary.updated"
|
||||
ActionSessionAgentctlStarting = "session.agentctl_starting"
|
||||
ActionSessionAgentctlReady = "session.agentctl_ready"
|
||||
ActionSessionAgentctlError = "session.agentctl_error"
|
||||
ActionSessionTurnStarted = "session.turn.started"
|
||||
ActionSessionTurnCompleted = "session.turn.completed"
|
||||
ActionSessionAvailableCommands = "session.available_commands"
|
||||
ActionSessionModeChanged = "session.mode_changed"
|
||||
ActionSessionAgentCapabilities = "session.agent_capabilities"
|
||||
ActionSessionModelsUpdated = "session.models_updated"
|
||||
ActionSessionModelFallback = "session.model_fallback"
|
||||
ActionSessionModelSelectionWarning = "session.model_selection_warning"
|
||||
ActionSessionMCPStatusUpdated = "session.mcp_status_updated"
|
||||
ActionSessionInfoUpdated = "session.info_updated"
|
||||
ActionSessionSetMode = "session.set_mode"
|
||||
ActionSessionTodosUpdated = "session.todos_updated"
|
||||
ActionSessionPromptUsage = "session.prompt_usage"
|
||||
ActionSessionPollModeChanged = "session.poll_mode_changed"
|
||||
ActionSessionRouteChanging = "session.route_changing"
|
||||
ActionSessionRouteChanged = "session.route_changed"
|
||||
ActionSessionCapabilitiesReplaced = "session.capabilities_replaced"
|
||||
ActionSessionRouteWaiting = "session.route_waiting"
|
||||
ActionSessionRoutePending = "session.route_pending"
|
||||
ActionInputRequested = "input.requested"
|
||||
ActionRepositoryCreated = "repository.created"
|
||||
ActionRepositoryUpdated = "repository.updated"
|
||||
ActionRepositoryDeleted = "repository.deleted"
|
||||
ActionRepositorySetCreated = "repository_set.created"
|
||||
ActionRepositorySetUpdated = "repository_set.updated"
|
||||
ActionRepositorySetDeleted = "repository_set.deleted"
|
||||
ActionRepositoryBranchPolicyCreated = "repository_branch_policy.created"
|
||||
ActionRepositoryBranchPolicyUpdated = "repository_branch_policy.updated"
|
||||
ActionRepositoryBranchPolicyDeleted = "repository_branch_policy.deleted"
|
||||
ActionRepositoryScriptCreated = "repository.script.created"
|
||||
ActionRepositoryScriptUpdated = "repository.script.updated"
|
||||
ActionRepositoryScriptDeleted = "repository.script.deleted"
|
||||
ActionExecutorCreated = "executor.created"
|
||||
ActionExecutorUpdated = "executor.updated"
|
||||
ActionExecutorDeleted = "executor.deleted"
|
||||
ActionEnvironmentCreated = "environment.created"
|
||||
ActionEnvironmentUpdated = "environment.updated"
|
||||
ActionEnvironmentDeleted = "environment.deleted"
|
||||
ActionExecutorProfileCreated = "executor.profile.created"
|
||||
ActionExecutorProfileUpdated = "executor.profile.updated"
|
||||
ActionExecutorProfileDeleted = "executor.profile.deleted"
|
||||
ActionExecutorPrepareProgress = "executor.prepare.progress"
|
||||
ActionExecutorPrepareCompleted = "executor.prepare.completed"
|
||||
ActionSystemMetricsUpdated = "system.metrics.updated"
|
||||
ActionUpdateAvailable = "system.update_available"
|
||||
|
||||
ActionAgentProfileDeleted = "agent.profile.deleted"
|
||||
ActionAgentProfileCreated = "agent.profile.created"
|
||||
|
||||
@@ -7,6 +7,10 @@ import { useDockviewStore } from "@/lib/state/dockview-store";
|
||||
import { applyLayout } from "@/lib/state/layout-manager";
|
||||
import { setupGroupTracking, setupPortalCleanup } from "@/components/task/dockview-layout-setup";
|
||||
import { useAppStore, useAppStoreApi } from "@/components/state-provider";
|
||||
import {
|
||||
resolveTaskPullRequestProps,
|
||||
selectWorkspaceRepositories,
|
||||
} from "@/components/task/task-page-content-helpers";
|
||||
import {
|
||||
CENTER_GROUP,
|
||||
RIGHT_TOP_GROUP,
|
||||
@@ -29,6 +33,7 @@ import {
|
||||
ContextMenuTab,
|
||||
renderPanel,
|
||||
} from "@/components/task/dockview-shared";
|
||||
import type { Task as OfficeTask } from "./types";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// OFFICE LAYOUT — no sidebar, no persistence, no multi-session
|
||||
@@ -57,13 +62,22 @@ function officeLayout(): LayoutState {
|
||||
type OfficeDockviewLayoutProps = {
|
||||
taskId: string;
|
||||
sessionId: string | null;
|
||||
task?: OfficeTask;
|
||||
};
|
||||
|
||||
export function OfficeDockviewLayout({ taskId, sessionId }: OfficeDockviewLayoutProps) {
|
||||
export function OfficeDockviewLayout({ taskId, sessionId, task }: OfficeDockviewLayoutProps) {
|
||||
const setApi = useDockviewStore((s) => s.setApi);
|
||||
const appStore = useAppStoreApi();
|
||||
const setActiveSession = useAppStore((s) => s.setActiveSession);
|
||||
const setActiveTask = useAppStore((s) => s.setActiveTask);
|
||||
const storedOfficeTask = useAppStore((s) =>
|
||||
s.office.tasks.items.find((item) => item.id === taskId),
|
||||
);
|
||||
const officeTask = task ?? storedOfficeTask;
|
||||
const workspaceRepositories = useAppStore((s) =>
|
||||
selectWorkspaceRepositories(s.repositories.itemsByWorkspaceId, officeTask?.workspaceId),
|
||||
);
|
||||
const pullRequestProps = resolveTaskPullRequestProps(officeTask ?? null, workspaceRepositories);
|
||||
|
||||
// Wire office session into the global store so shared panels can read it.
|
||||
useEffect(() => {
|
||||
@@ -135,7 +149,14 @@ export function OfficeDockviewLayout({ taskId, sessionId }: OfficeDockviewLayout
|
||||
);
|
||||
|
||||
return (
|
||||
<VcsDialogsProvider sessionId={sessionId}>
|
||||
<VcsDialogsProvider
|
||||
sessionId={sessionId}
|
||||
baseBranch={pullRequestProps.baseBranch}
|
||||
pullRequestBaseBranch={pullRequestProps.pullRequestTarget}
|
||||
pullRequestTargetsByRepository={pullRequestProps.pullRequestTargetsByRepository}
|
||||
taskTitle={pullRequestProps.taskTitle}
|
||||
displayBranch={officeTask?.repositories?.[0]?.checkout_branch}
|
||||
>
|
||||
<div className="flex-1 min-h-0">
|
||||
<DockviewReact
|
||||
theme={themeKandev}
|
||||
|
||||
@@ -64,7 +64,7 @@ export function TaskAdvancedMode({ task, onToggleSimple }: TaskAdvancedModeProps
|
||||
<span className="text-sm text-muted-foreground">{t("office:agentSessionEnded")}</span>
|
||||
</div>
|
||||
)}
|
||||
<OfficeDockviewLayout taskId={task.id} sessionId={sessionId} />
|
||||
<OfficeDockviewLayout taskId={task.id} sessionId={sessionId} task={task} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -572,6 +572,7 @@ export function WorkspaceRepositoriesClient({
|
||||
<RepositoryCard
|
||||
key={repo.id}
|
||||
repository={repo}
|
||||
workspaceId={workspace.id}
|
||||
savedRepository={savedRepositoriesById.get(repo.id)}
|
||||
isRepositoryDirty={isRepositoryDirty(repo, savedRepositoriesById.get(repo.id))}
|
||||
areScriptsDirty={areRepositoryScriptsDirty(repo, savedRepositoriesById.get(repo.id))}
|
||||
|
||||
@@ -552,6 +552,7 @@ function KanbanBoardDialogs({
|
||||
workflowStepId: editingTask.workflowStepId,
|
||||
state: editingTask.state as BackendTask["state"],
|
||||
repositoryId: editingTask.repositoryId,
|
||||
repositories: editingTask.repositories,
|
||||
}
|
||||
: null
|
||||
}
|
||||
@@ -563,6 +564,7 @@ function KanbanBoardDialogs({
|
||||
description: editingTask.description,
|
||||
state: editingTask.state as BackendTask["state"],
|
||||
repositoryId: editingTask.repositoryId,
|
||||
repositories: editingTask.repositories,
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
|
||||
@@ -47,7 +47,18 @@ export interface Task {
|
||||
position?: number;
|
||||
repositoryId?: string;
|
||||
/** All repositories linked to the task; used to render a "+N" chip for multi-repo. */
|
||||
repositories?: Array<{ id: string; repository_id: string; position: number }>;
|
||||
repositories?: Array<{
|
||||
id: string;
|
||||
repository_id: string;
|
||||
base_branch?: string;
|
||||
checkout_branch?: string;
|
||||
branch_policy_id?: string;
|
||||
branch_policy_name?: string;
|
||||
branch_policy_base_branch?: string;
|
||||
branch_policy_branch_template?: string;
|
||||
branch_policy_pull_request_target?: string;
|
||||
position: number;
|
||||
}>;
|
||||
sessionCount?: number | null;
|
||||
primarySessionId?: string | null;
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,556 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { IconChevronDown, IconPencil, IconPlus, IconTrash } from "@tabler/icons-react";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@kandev/ui/alert-dialog";
|
||||
import { Button } from "@kandev/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@kandev/ui/dialog";
|
||||
import {
|
||||
Drawer,
|
||||
DrawerContent,
|
||||
DrawerDescription,
|
||||
DrawerFooter,
|
||||
DrawerHeader,
|
||||
DrawerTitle,
|
||||
} from "@kandev/ui/drawer";
|
||||
import { useToast } from "@/components/toast-provider";
|
||||
import { useResponsiveBreakpoint } from "@/hooks/use-responsive-breakpoint";
|
||||
import { useBranches } from "@/hooks/domains/workspace/use-repository-branches";
|
||||
import { useRepositoryBranchPolicies } from "@/hooks/domains/workspace/use-repository-branch-policies";
|
||||
import type { Repository, RepositoryBranchPolicy } from "@/lib/types/http";
|
||||
import { branchToOption, sortBranches } from "@/components/task-create-dialog-branch-options";
|
||||
import {
|
||||
BranchPolicyBranchField,
|
||||
PolicyFields,
|
||||
draftFromPolicy,
|
||||
type PolicyDraft,
|
||||
} from "@/components/settings/repository-branch-policy-fields";
|
||||
|
||||
const TOUCH_TARGET_CLASS = "min-h-11";
|
||||
const CANCEL_LABEL_KEY = "common:cancel";
|
||||
|
||||
function PolicySurface({
|
||||
open,
|
||||
onOpenChange,
|
||||
title,
|
||||
description,
|
||||
draft,
|
||||
setDraft,
|
||||
branches,
|
||||
refreshBranches,
|
||||
branchesLoading,
|
||||
idPrefix,
|
||||
onSubmit,
|
||||
loading,
|
||||
}: {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
title: string;
|
||||
description: string;
|
||||
draft: PolicyDraft;
|
||||
setDraft: (next: PolicyDraft) => void;
|
||||
branches: ReturnType<typeof useBranches>["branches"];
|
||||
refreshBranches?: () => void;
|
||||
branchesLoading: boolean;
|
||||
idPrefix: string;
|
||||
onSubmit: () => void;
|
||||
loading: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const { isMobile } = useResponsiveBreakpoint();
|
||||
const formId = `${idPrefix}-form`;
|
||||
const body = (
|
||||
<form
|
||||
id={formId}
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
onSubmit();
|
||||
}}
|
||||
className="min-h-0 flex-1 overflow-y-auto overscroll-contain px-4 py-4"
|
||||
>
|
||||
<PolicyFields
|
||||
draft={draft}
|
||||
setDraft={setDraft}
|
||||
branches={branches}
|
||||
refreshBranches={refreshBranches}
|
||||
branchesLoading={branchesLoading}
|
||||
idPrefix={idPrefix}
|
||||
/>
|
||||
</form>
|
||||
);
|
||||
const footer = isMobile ? (
|
||||
<DrawerFooter className="shrink-0 border-t px-4 pt-3 pb-[max(1rem,env(safe-area-inset-bottom))]">
|
||||
<Button type="submit" form={formId} disabled={loading} className={TOUCH_TARGET_CLASS}>
|
||||
{t("common:save")}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => onOpenChange(false)}
|
||||
className={TOUCH_TARGET_CLASS}
|
||||
>
|
||||
{t(CANCEL_LABEL_KEY)}
|
||||
</Button>
|
||||
</DrawerFooter>
|
||||
) : (
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
|
||||
{t(CANCEL_LABEL_KEY)}
|
||||
</Button>
|
||||
<Button type="submit" form={formId} disabled={loading}>
|
||||
{t("common:save")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
);
|
||||
if (isMobile) {
|
||||
return (
|
||||
<Drawer open={open} onOpenChange={onOpenChange}>
|
||||
<DrawerContent className="flex h-[100dvh] max-h-[100dvh] flex-col overflow-hidden">
|
||||
<DrawerHeader className="shrink-0 px-4 py-3 text-left">
|
||||
<DrawerTitle>{title}</DrawerTitle>
|
||||
<DrawerDescription>{description}</DrawerDescription>
|
||||
</DrawerHeader>
|
||||
{body}
|
||||
{footer}
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="flex max-h-[92dvh] flex-col gap-0 overflow-hidden p-0 sm:max-w-2xl">
|
||||
<DialogHeader className="shrink-0 px-4 pb-1 pt-3 text-left">
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
<DialogDescription>{description}</DialogDescription>
|
||||
</DialogHeader>
|
||||
{body}
|
||||
{footer}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
// eslint-disable-next-line max-lines-per-function -- Shares validated fields and one responsive surface.
|
||||
function GitflowSurface({
|
||||
open,
|
||||
onOpenChange,
|
||||
productionBranch,
|
||||
developmentBranch,
|
||||
setProductionBranch,
|
||||
setDevelopmentBranch,
|
||||
branches,
|
||||
branchOptions,
|
||||
refreshBranches,
|
||||
idPrefix,
|
||||
branchesLoading,
|
||||
onSubmit,
|
||||
loading,
|
||||
}: {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
productionBranch: string;
|
||||
developmentBranch: string;
|
||||
setProductionBranch: (value: string) => void;
|
||||
setDevelopmentBranch: (value: string) => void;
|
||||
branchOptions: string[];
|
||||
branches: ReturnType<typeof useBranches>["branches"];
|
||||
refreshBranches?: () => void;
|
||||
idPrefix: string;
|
||||
branchesLoading: boolean;
|
||||
onSubmit: () => void;
|
||||
loading: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const { isMobile } = useResponsiveBreakpoint();
|
||||
const fields = (
|
||||
<div className="space-y-4 px-4 py-4">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("workspaces:branchPolicyGitflowDescription")}
|
||||
</p>
|
||||
<BranchPolicyBranchField
|
||||
label={t("workspaces:branchPolicyProductionBranch")}
|
||||
value={productionBranch}
|
||||
onChange={setProductionBranch}
|
||||
branches={branches}
|
||||
onRefresh={refreshBranches}
|
||||
loading={branchesLoading}
|
||||
helpLabel={t("workspaces:branchPolicyProductionHelpLabel")}
|
||||
help={t("workspaces:branchPolicyProductionHelp")}
|
||||
testId={`${idPrefix}-gitflow-production-picker`}
|
||||
/>
|
||||
<BranchPolicyBranchField
|
||||
label={t("workspaces:branchPolicyDevelopmentBranch")}
|
||||
value={developmentBranch}
|
||||
onChange={setDevelopmentBranch}
|
||||
branches={branches}
|
||||
onRefresh={refreshBranches}
|
||||
loading={branchesLoading}
|
||||
helpLabel={t("workspaces:branchPolicyDevelopmentHelpLabel")}
|
||||
help={t("workspaces:branchPolicyDevelopmentHelp")}
|
||||
testId={`${idPrefix}-gitflow-development-picker`}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">{t("workspaces:branchPolicyGitflowPreview")}</p>
|
||||
</div>
|
||||
);
|
||||
const valid =
|
||||
!branchesLoading &&
|
||||
productionBranch.trim() !== "" &&
|
||||
developmentBranch.trim() !== "" &&
|
||||
productionBranch.trim() !== developmentBranch.trim() &&
|
||||
branchOptions.includes(productionBranch.trim()) &&
|
||||
branchOptions.includes(developmentBranch.trim());
|
||||
const footer = isMobile ? (
|
||||
<DrawerFooter className="border-t px-4 pt-3 pb-[max(1rem,env(safe-area-inset-bottom))]">
|
||||
<Button
|
||||
type="button"
|
||||
onClick={onSubmit}
|
||||
disabled={!valid || loading}
|
||||
className={TOUCH_TARGET_CLASS}
|
||||
>
|
||||
{t("workspaces:branchPolicyGitflowCreate")}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => onOpenChange(false)}
|
||||
className={TOUCH_TARGET_CLASS}
|
||||
>
|
||||
{t(CANCEL_LABEL_KEY)}
|
||||
</Button>
|
||||
</DrawerFooter>
|
||||
) : (
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
|
||||
{t(CANCEL_LABEL_KEY)}
|
||||
</Button>
|
||||
<Button type="button" onClick={onSubmit} disabled={!valid || loading}>
|
||||
{t("workspaces:branchPolicyGitflowCreate")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
);
|
||||
if (isMobile) {
|
||||
return (
|
||||
<Drawer open={open} onOpenChange={onOpenChange}>
|
||||
<DrawerContent className="flex h-[100dvh] max-h-[100dvh] flex-col overflow-hidden">
|
||||
<DrawerHeader className="shrink-0 px-4 py-3 text-left">
|
||||
<DrawerTitle>{t("workspaces:branchPolicyGitflowTitle")}</DrawerTitle>
|
||||
<DrawerDescription>{t("workspaces:branchPolicyGitflowDescription")}</DrawerDescription>
|
||||
</DrawerHeader>
|
||||
<div className="min-h-0 flex-1 overflow-y-auto overscroll-contain">{fields}</div>
|
||||
{footer}
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t("workspaces:branchPolicyGitflowTitle")}</DialogTitle>
|
||||
<DialogDescription>{t("workspaces:branchPolicyGitflowDescription")}</DialogDescription>
|
||||
</DialogHeader>
|
||||
{fields}
|
||||
{footer}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
// eslint-disable-next-line max-lines-per-function -- Coordinates policy CRUD, Gitflow seeding, and editors.
|
||||
export function RepositoryBranchPolicies({
|
||||
repository,
|
||||
workspaceId,
|
||||
}: {
|
||||
repository: Repository;
|
||||
workspaceId: string;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const { toast } = useToast();
|
||||
const isSaved = !repository.id.startsWith("temp-repo-");
|
||||
const idPrefix = `branch-policy-${repository.id.replace(/[^a-zA-Z0-9_-]/g, "-")}`;
|
||||
const { policies, hasError, isLoading, refresh, create, update, remove, seedGitflow } =
|
||||
useRepositoryBranchPolicies(repository.id, isSaved);
|
||||
const {
|
||||
branches,
|
||||
isLoading: branchesLoading,
|
||||
refresh: refreshBranches,
|
||||
} = useBranches(
|
||||
isSaved ? { kind: "id", workspaceId, repositoryId: repository.id } : null,
|
||||
isSaved,
|
||||
);
|
||||
const branchOptions = useMemo(() => {
|
||||
const names = sortBranches(branches).map((branch) => branchToOption(branch).value);
|
||||
return [...new Set(names)];
|
||||
}, [branches]);
|
||||
const [editorPolicy, setEditorPolicy] = useState<RepositoryBranchPolicy | undefined>();
|
||||
const [draft, setDraft] = useState<PolicyDraft>(() => draftFromPolicy());
|
||||
const [editorOpen, setEditorOpen] = useState(false);
|
||||
const [gitflowOpen, setGitflowOpen] = useState(false);
|
||||
const [productionBranch, setProductionBranch] = useState("");
|
||||
const [developmentBranch, setDevelopmentBranch] = useState("");
|
||||
const [pending, setPending] = useState(false);
|
||||
const [deletePolicy, setDeletePolicy] = useState<RepositoryBranchPolicy | undefined>();
|
||||
|
||||
const openCreate = () => {
|
||||
setEditorPolicy(undefined);
|
||||
setDraft(draftFromPolicy());
|
||||
setEditorOpen(true);
|
||||
};
|
||||
const openEdit = (policy: RepositoryBranchPolicy) => {
|
||||
setEditorPolicy(policy);
|
||||
setDraft(draftFromPolicy(policy));
|
||||
setEditorOpen(true);
|
||||
};
|
||||
const submitPolicy = async () => {
|
||||
setPending(true);
|
||||
try {
|
||||
if (editorPolicy) await update(editorPolicy.id, draft);
|
||||
else await create(draft);
|
||||
setEditorOpen(false);
|
||||
toast({ title: t("workspaces:branchPolicySaved"), variant: "success" });
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: t("workspaces:branchPolicySaveFailed"),
|
||||
description: error instanceof Error ? error.message : t("common:requestFailed"),
|
||||
variant: "error",
|
||||
});
|
||||
} finally {
|
||||
setPending(false);
|
||||
}
|
||||
};
|
||||
const submitGitflow = async () => {
|
||||
setPending(true);
|
||||
try {
|
||||
await seedGitflow(productionBranch.trim(), developmentBranch.trim());
|
||||
setGitflowOpen(false);
|
||||
toast({ title: t("workspaces:branchPolicyGitflowCreated"), variant: "success" });
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: t("workspaces:branchPolicyGitflowFailed"),
|
||||
description: error instanceof Error ? error.message : t("common:requestFailed"),
|
||||
variant: "error",
|
||||
});
|
||||
} finally {
|
||||
setPending(false);
|
||||
}
|
||||
};
|
||||
const confirmDelete = async () => {
|
||||
if (!deletePolicy) return;
|
||||
setPending(true);
|
||||
try {
|
||||
await remove(deletePolicy.id);
|
||||
setDeletePolicy(undefined);
|
||||
toast({ title: t("workspaces:branchPolicyDeleted"), variant: "success" });
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: t("workspaces:branchPolicyDeleteFailed"),
|
||||
description: error instanceof Error ? error.message : t("common:requestFailed"),
|
||||
variant: "error",
|
||||
});
|
||||
} finally {
|
||||
setPending(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<details
|
||||
className="group rounded-md border border-border/70 p-3"
|
||||
data-testid={`branch-policies-${repository.id}`}
|
||||
>
|
||||
<summary className="flex min-h-11 cursor-pointer list-none items-center justify-between gap-3 [&::-webkit-details-marker]:hidden">
|
||||
<span className="flex items-center gap-2 font-medium">
|
||||
<IconChevronDown className="h-4 w-4 transition-transform group-open:rotate-180" />
|
||||
{t("workspaces:branchPoliciesTitle")}
|
||||
<span className="rounded-full bg-muted px-2 py-0.5 text-xs tabular-nums">
|
||||
{policies.length}
|
||||
</span>
|
||||
</span>
|
||||
</summary>
|
||||
<div className="space-y-3 pt-3">
|
||||
<p className="text-sm text-muted-foreground">{t("workspaces:branchPoliciesDescription")}</p>
|
||||
{!isSaved ? (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("workspaces:branchPoliciesSaveRepositoryFirst")}
|
||||
</p>
|
||||
) : null}
|
||||
{isSaved && hasError ? (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<p className="text-sm text-destructive">{t("workspaces:branchPoliciesLoadFailed")}</p>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className={TOUCH_TARGET_CLASS}
|
||||
onClick={() => void refresh().catch(() => undefined)}
|
||||
>
|
||||
{t("workspaces:branchPoliciesRetry")}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
{isSaved && !hasError && policies.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">{t("workspaces:branchPoliciesEmpty")}</p>
|
||||
) : null}
|
||||
<div className="space-y-2">
|
||||
{policies.map((policy) => (
|
||||
<div
|
||||
key={policy.id}
|
||||
className="flex flex-wrap items-center justify-between gap-2 rounded-md bg-muted/40 p-3"
|
||||
data-testid={`branch-policy-${policy.id}`}
|
||||
>
|
||||
<div className="min-w-0 space-y-0.5">
|
||||
<p className="font-medium">{policy.name}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("workspaces:branchPolicySummary", {
|
||||
base: policy.base_branch,
|
||||
template: policy.branch_template,
|
||||
target: policy.pull_request_target,
|
||||
})}
|
||||
</p>
|
||||
{policy.description ? (
|
||||
<p className="text-xs text-muted-foreground">{policy.description}</p>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-11 w-11"
|
||||
onClick={() => openEdit(policy)}
|
||||
aria-label={t("workspaces:branchPolicyEdit", { name: policy.name })}
|
||||
>
|
||||
<IconPencil className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-11 w-11"
|
||||
onClick={() => setDeletePolicy(policy)}
|
||||
aria-label={t("workspaces:branchPolicyDelete", { name: policy.name })}
|
||||
>
|
||||
<IconTrash className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{isSaved ? (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className={TOUCH_TARGET_CLASS}
|
||||
onClick={openCreate}
|
||||
>
|
||||
<IconPlus className="mr-2 h-4 w-4" />
|
||||
{t("workspaces:branchPolicyAdd")}
|
||||
</Button>
|
||||
{!hasError && policies.length === 0 ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className={TOUCH_TARGET_CLASS}
|
||||
disabled={branchesLoading}
|
||||
onClick={() => {
|
||||
setProductionBranch(repository.default_branch || branchOptions[0] || "");
|
||||
setDevelopmentBranch(
|
||||
branchOptions.includes("develop")
|
||||
? "develop"
|
||||
: branchOptions.find(
|
||||
(branch) => branch !== (repository.default_branch || branchOptions[0]),
|
||||
) || "",
|
||||
);
|
||||
setGitflowOpen(true);
|
||||
}}
|
||||
>
|
||||
{t("workspaces:branchPolicyGitflowAdd")}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
<PolicySurface
|
||||
open={editorOpen}
|
||||
onOpenChange={setEditorOpen}
|
||||
title={
|
||||
editorPolicy
|
||||
? t("workspaces:branchPolicyEditTitle")
|
||||
: t("workspaces:branchPolicyAddTitle")
|
||||
}
|
||||
description={t("workspaces:branchPolicyEditorDescription")}
|
||||
draft={draft}
|
||||
setDraft={setDraft}
|
||||
branches={branches}
|
||||
refreshBranches={refreshBranches}
|
||||
branchesLoading={branchesLoading}
|
||||
idPrefix={idPrefix}
|
||||
onSubmit={() => void submitPolicy()}
|
||||
loading={pending}
|
||||
/>
|
||||
<GitflowSurface
|
||||
open={gitflowOpen}
|
||||
onOpenChange={setGitflowOpen}
|
||||
productionBranch={productionBranch}
|
||||
developmentBranch={developmentBranch}
|
||||
setProductionBranch={setProductionBranch}
|
||||
setDevelopmentBranch={setDevelopmentBranch}
|
||||
branches={branches}
|
||||
branchOptions={branchOptions}
|
||||
refreshBranches={refreshBranches}
|
||||
idPrefix={idPrefix}
|
||||
branchesLoading={branchesLoading}
|
||||
onSubmit={() => void submitGitflow()}
|
||||
loading={pending}
|
||||
/>
|
||||
<AlertDialog
|
||||
open={Boolean(deletePolicy)}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setDeletePolicy(undefined);
|
||||
}}
|
||||
>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>
|
||||
{t("workspaces:branchPolicyDeleteTitle", { name: deletePolicy?.name ?? "" })}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{t("workspaces:branchPolicyDeleteDescription")}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel className="cursor-pointer">{t(CANCEL_LABEL_KEY)}</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
className="cursor-pointer"
|
||||
disabled={pending}
|
||||
onClick={() => void confirmDelete()}
|
||||
>
|
||||
{t("workspaces:branchPolicyDeleteConfirm")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
{isLoading ? (
|
||||
<p className="pt-2 text-xs text-muted-foreground">
|
||||
{t("workspaces:branchPoliciesLoading")}
|
||||
</p>
|
||||
) : null}
|
||||
</details>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";
|
||||
import { TooltipProvider } from "@kandev/ui/tooltip";
|
||||
import type { Branch } from "@/lib/types/http";
|
||||
import { BranchPolicyBranchPicker } from "./repository-branch-policy-fields";
|
||||
|
||||
vi.mock("@/hooks/use-compact-task-chrome", () => ({ useTouchDrawer: () => false }));
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
describe("BranchPolicyBranchPicker", () => {
|
||||
it("filters all local and remote branches and refreshes from the picker", () => {
|
||||
const onChange = vi.fn();
|
||||
const onRefresh = vi.fn();
|
||||
const branches: Branch[] = [
|
||||
{ name: "main", type: "local" },
|
||||
{ name: "main", type: "remote", remote: "origin" },
|
||||
{ name: "release/candidate", type: "remote", remote: "upstream" },
|
||||
];
|
||||
|
||||
render(
|
||||
<TooltipProvider>
|
||||
<BranchPolicyBranchPicker
|
||||
label="Base branch"
|
||||
value="main"
|
||||
onChange={onChange}
|
||||
branches={branches}
|
||||
onRefresh={onRefresh}
|
||||
loading={false}
|
||||
testId="policy-base-picker"
|
||||
/>
|
||||
</TooltipProvider>,
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole("combobox", { name: "Base branch" }));
|
||||
expect(screen.getByPlaceholderText("Search branches...")).toBeTruthy();
|
||||
expect(screen.getByRole("option", { name: /^main local/ })).toBeTruthy();
|
||||
expect(screen.getByRole("option", { name: /^origin\/main origin/ })).toBeTruthy();
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText("Search branches..."), {
|
||||
target: { value: "candidate" },
|
||||
});
|
||||
const listbox = screen.getByRole("listbox");
|
||||
expect(
|
||||
within(listbox).getByRole("option", { name: /^upstream\/release\/candidate upstream/ }),
|
||||
).toBeTruthy();
|
||||
expect(within(listbox).queryByRole("option", { name: /^main local/ })).toBeNull();
|
||||
|
||||
fireEvent.click(screen.getByTestId("branch-refresh-button"));
|
||||
expect(onRefresh).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,269 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { IconInfoCircle } from "@tabler/icons-react";
|
||||
import {
|
||||
Drawer,
|
||||
DrawerContent,
|
||||
DrawerDescription,
|
||||
DrawerHeader,
|
||||
DrawerTitle,
|
||||
DrawerTrigger,
|
||||
} from "@kandev/ui/drawer";
|
||||
import { Input } from "@kandev/ui/input";
|
||||
import { Label } from "@kandev/ui/label";
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@kandev/ui/tooltip";
|
||||
import { BranchSelector } from "@/components/task-create-dialog-selectors";
|
||||
import {
|
||||
branchToOption,
|
||||
buildBranchKeywords,
|
||||
sortBranches,
|
||||
} from "@/components/task-create-dialog-branch-options";
|
||||
import { useTouchDrawer } from "@/hooks/use-compact-task-chrome";
|
||||
import type { Branch, RepositoryBranchPolicy } from "@/lib/types/http";
|
||||
|
||||
export type PolicyDraft = Omit<
|
||||
RepositoryBranchPolicy,
|
||||
"id" | "repository_id" | "created_at" | "updated_at"
|
||||
>;
|
||||
|
||||
export const DEFAULT_POLICY_DRAFT: PolicyDraft = {
|
||||
name: "",
|
||||
description: "",
|
||||
base_branch: "",
|
||||
// i18n-exempt: branch template protocol
|
||||
branch_template: "feature/{title}-{suffix}",
|
||||
pull_request_target: "",
|
||||
};
|
||||
|
||||
export function draftFromPolicy(policy?: RepositoryBranchPolicy): PolicyDraft {
|
||||
return policy
|
||||
? {
|
||||
name: policy.name,
|
||||
description: policy.description,
|
||||
base_branch: policy.base_branch,
|
||||
branch_template: policy.branch_template,
|
||||
pull_request_target: policy.pull_request_target,
|
||||
}
|
||||
: { ...DEFAULT_POLICY_DRAFT };
|
||||
}
|
||||
|
||||
export function FieldHelp({ label, description }: { label: string; description: string }) {
|
||||
const usesTouchDrawer = useTouchDrawer();
|
||||
const [open, setOpen] = useState(false);
|
||||
const button = (
|
||||
<button
|
||||
type="button"
|
||||
className="min-h-11 min-w-11 cursor-pointer text-muted-foreground hover:text-foreground"
|
||||
aria-label={label}
|
||||
aria-haspopup={usesTouchDrawer ? "dialog" : undefined}
|
||||
aria-expanded={usesTouchDrawer ? open : undefined}
|
||||
>
|
||||
<IconInfoCircle className="mx-auto h-4 w-4" />
|
||||
</button>
|
||||
);
|
||||
if (!usesTouchDrawer) {
|
||||
return (
|
||||
<TooltipProvider delayDuration={150}>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>{button}</TooltipTrigger>
|
||||
<TooltipContent className="w-80 text-xs">{description}</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Drawer open={open} onOpenChange={setOpen}>
|
||||
<DrawerTrigger asChild>{button}</DrawerTrigger>
|
||||
<DrawerContent>
|
||||
<DrawerHeader>
|
||||
<DrawerTitle>{label}</DrawerTitle>
|
||||
<DrawerDescription>{description}</DrawerDescription>
|
||||
</DrawerHeader>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
);
|
||||
}
|
||||
|
||||
function selectedFallbackOption(value: string) {
|
||||
return {
|
||||
value,
|
||||
label: value,
|
||||
keywords: buildBranchKeywords(value),
|
||||
renderLabel: () => <span className="truncate">{value}</span>,
|
||||
};
|
||||
}
|
||||
|
||||
export function BranchPolicyBranchPicker({
|
||||
label,
|
||||
value,
|
||||
onChange,
|
||||
branches,
|
||||
onRefresh,
|
||||
loading,
|
||||
testId,
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
branches: Branch[];
|
||||
onRefresh?: () => void;
|
||||
loading: boolean;
|
||||
testId: string;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const options = useMemo(() => {
|
||||
const available = sortBranches(branches).map(branchToOption);
|
||||
if (!value || available.some((option) => option.value === value)) return available;
|
||||
return [selectedFallbackOption(value), ...available];
|
||||
}, [branches, value]);
|
||||
|
||||
return (
|
||||
<BranchSelector
|
||||
options={options}
|
||||
value={value}
|
||||
onValueChange={onChange}
|
||||
disabled={loading || options.length === 0}
|
||||
placeholder={loading ? t("common:loading") : t("task:noBranchesShort")}
|
||||
searchPlaceholder={t("task:searchBranches")}
|
||||
emptyMessage={t("task:noBranches")}
|
||||
onRefresh={onRefresh}
|
||||
refreshing={loading}
|
||||
loading={loading}
|
||||
ariaLabel={label}
|
||||
dropdownLabel={label}
|
||||
testId={testId}
|
||||
triggerClassName="min-h-11 border border-input bg-background px-3 hover:bg-background"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function BranchPolicyBranchField({
|
||||
label,
|
||||
value,
|
||||
onChange,
|
||||
branches,
|
||||
onRefresh,
|
||||
loading,
|
||||
helpLabel,
|
||||
help,
|
||||
testId,
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
branches: Branch[];
|
||||
onRefresh?: () => void;
|
||||
loading: boolean;
|
||||
helpLabel: string;
|
||||
help: string;
|
||||
testId: string;
|
||||
}) {
|
||||
return (
|
||||
<div className="space-y-1.5">
|
||||
<div className="flex items-center gap-1">
|
||||
<Label>{label}</Label>
|
||||
<FieldHelp label={helpLabel} description={help} />
|
||||
</div>
|
||||
<BranchPolicyBranchPicker
|
||||
label={label}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
branches={branches}
|
||||
onRefresh={onRefresh}
|
||||
loading={loading}
|
||||
testId={testId}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function PolicyFields({
|
||||
draft,
|
||||
setDraft,
|
||||
branches,
|
||||
refreshBranches,
|
||||
branchesLoading,
|
||||
idPrefix,
|
||||
}: {
|
||||
draft: PolicyDraft;
|
||||
setDraft: (next: PolicyDraft) => void;
|
||||
branches: Branch[];
|
||||
refreshBranches?: () => void;
|
||||
branchesLoading: boolean;
|
||||
idPrefix: string;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const fieldId = (name: string) => `${idPrefix}-${name}`;
|
||||
const update = (key: keyof PolicyDraft, value: string) => setDraft({ ...draft, [key]: value });
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-1.5">
|
||||
<div className="flex items-center gap-1">
|
||||
<Label htmlFor={fieldId("name")}>{t("workspaces:branchPolicyName")}</Label>
|
||||
<FieldHelp
|
||||
label={t("workspaces:branchPolicyNameHelpLabel")}
|
||||
description={t("workspaces:branchPolicyNameHelp")}
|
||||
/>
|
||||
</div>
|
||||
<Input
|
||||
id={fieldId("name")}
|
||||
value={draft.name}
|
||||
onChange={(event) => update("name", event.target.value)}
|
||||
maxLength={100}
|
||||
autoFocus
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">{t("workspaces:branchPolicyNameHint")}</p>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor={fieldId("description")}>{t("workspaces:branchPolicyDescription")}</Label>
|
||||
<Input
|
||||
id={fieldId("description")}
|
||||
value={draft.description}
|
||||
onChange={(event) => update("description", event.target.value)}
|
||||
maxLength={500}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<BranchPolicyBranchField
|
||||
label={t("workspaces:branchPolicyBaseBranch")}
|
||||
value={draft.base_branch}
|
||||
onChange={(value) => update("base_branch", value)}
|
||||
branches={branches}
|
||||
onRefresh={refreshBranches}
|
||||
loading={branchesLoading}
|
||||
helpLabel={t("workspaces:branchPolicyBaseBranchHelpLabel")}
|
||||
help={t("workspaces:branchPolicyBaseBranchHelp")}
|
||||
testId={fieldId("base-picker")}
|
||||
/>
|
||||
<BranchPolicyBranchField
|
||||
label={t("workspaces:branchPolicyPullRequestTarget")}
|
||||
value={draft.pull_request_target}
|
||||
onChange={(value) => update("pull_request_target", value)}
|
||||
branches={branches}
|
||||
onRefresh={refreshBranches}
|
||||
loading={branchesLoading}
|
||||
helpLabel={t("workspaces:branchPolicyPullRequestTargetHelpLabel")}
|
||||
help={t("workspaces:branchPolicyPullRequestTargetHelp")}
|
||||
testId={fieldId("target-picker")}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<div className="flex items-center gap-1">
|
||||
<Label htmlFor={fieldId("template")}>{t("workspaces:branchPolicyTemplate")}</Label>
|
||||
<FieldHelp
|
||||
label={t("workspaces:branchPolicyTemplateHelpLabel")}
|
||||
description={t("workspaces:branchPolicyTemplateHelp")}
|
||||
/>
|
||||
</div>
|
||||
<Input
|
||||
id={fieldId("template")}
|
||||
value={draft.branch_template}
|
||||
onChange={(event) => update("branch_template", event.target.value)}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">{t("workspaces:branchPolicyTemplateHint")}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { cleanup, render, screen } from "@testing-library/react";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { i18n } from "@/lib/i18n";
|
||||
import { StateProvider } from "@/components/state-provider";
|
||||
import { RepositoryCard } from "./repository-card";
|
||||
import { SettingsSaveProvider } from "./settings-save-provider";
|
||||
import { ToastProvider } from "@/components/toast-provider";
|
||||
@@ -66,23 +67,26 @@ function script(id: string): RepositoryScript {
|
||||
|
||||
function renderCard(repo: RepositoryWithScripts, autoOpen = false) {
|
||||
return render(
|
||||
<ToastProvider>
|
||||
<SettingsSaveProvider>
|
||||
<RepositoryCard
|
||||
repository={repo}
|
||||
savedRepository={repo}
|
||||
isRepositoryDirty={false}
|
||||
areScriptsDirty={false}
|
||||
autoOpen={autoOpen}
|
||||
onUpdate={vi.fn()}
|
||||
onAddScript={vi.fn()}
|
||||
onUpdateScript={vi.fn()}
|
||||
onDeleteScript={vi.fn()}
|
||||
onSave={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
/>
|
||||
</SettingsSaveProvider>
|
||||
</ToastProvider>,
|
||||
<StateProvider>
|
||||
<ToastProvider>
|
||||
<SettingsSaveProvider>
|
||||
<RepositoryCard
|
||||
repository={repo}
|
||||
workspaceId="workspace-1"
|
||||
savedRepository={repo}
|
||||
isRepositoryDirty={false}
|
||||
areScriptsDirty={false}
|
||||
autoOpen={autoOpen}
|
||||
onUpdate={vi.fn()}
|
||||
onAddScript={vi.fn()}
|
||||
onUpdateScript={vi.fn()}
|
||||
onDeleteScript={vi.fn()}
|
||||
onSave={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
/>
|
||||
</SettingsSaveProvider>
|
||||
</ToastProvider>
|
||||
</StateProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ import { RepositoryBranchTemplateHelp } from "@/components/settings/repository-b
|
||||
import { DeleteRepositoryDialog } from "@/components/settings/repository-delete-dialog";
|
||||
import { CopyFilesField } from "@/components/settings/repository-copy-files-help";
|
||||
import { RepositoryCustomScripts } from "@/components/settings/repository-custom-scripts";
|
||||
import { RepositoryBranchPolicies } from "@/components/settings/repository-branch-policies";
|
||||
import {
|
||||
RepositorySecretBindings,
|
||||
validateRepositorySecretBindings,
|
||||
@@ -220,6 +221,7 @@ function RepositoryScriptFields({
|
||||
|
||||
type RepositoryEditViewProps = {
|
||||
repository: RepositoryWithScripts;
|
||||
workspaceId: string;
|
||||
savedRepository?: RepositoryWithScripts;
|
||||
isDirty: boolean;
|
||||
areScriptsDirty: boolean;
|
||||
@@ -234,6 +236,7 @@ type RepositoryEditViewProps = {
|
||||
|
||||
function RepositoryEditView({
|
||||
repository,
|
||||
workspaceId,
|
||||
savedRepository,
|
||||
isDirty,
|
||||
areScriptsDirty,
|
||||
@@ -283,6 +286,8 @@ function RepositoryEditView({
|
||||
pullBeforeWorktree={repository.pull_before_worktree ?? true}
|
||||
/>
|
||||
|
||||
<RepositoryBranchPolicies repository={repository} workspaceId={workspaceId} />
|
||||
|
||||
<RepositoryScriptFields
|
||||
repositoryId={repository.id}
|
||||
savedRepository={savedRepository}
|
||||
@@ -341,6 +346,7 @@ function repositorySecretInvalidReason(
|
||||
|
||||
type RepositoryCardProps = {
|
||||
repository: RepositoryWithScripts;
|
||||
workspaceId: string;
|
||||
savedRepository?: RepositoryWithScripts;
|
||||
isRepositoryDirty: boolean;
|
||||
areScriptsDirty: boolean;
|
||||
@@ -421,6 +427,7 @@ function useRepositoryDelete(
|
||||
|
||||
export function RepositoryCard({
|
||||
repository,
|
||||
workspaceId,
|
||||
savedRepository,
|
||||
isRepositoryDirty,
|
||||
areScriptsDirty,
|
||||
@@ -488,6 +495,7 @@ export function RepositoryCard({
|
||||
renderEdit={({ close }) => (
|
||||
<RepositoryEditView
|
||||
repository={repository}
|
||||
workspaceId={workspaceId}
|
||||
savedRepository={savedRepository}
|
||||
isDirty={isDirty}
|
||||
areScriptsDirty={areScriptsDirty}
|
||||
|
||||
@@ -54,6 +54,8 @@ export function branchToOption(b: Branch): PillOption {
|
||||
value: display,
|
||||
label: display,
|
||||
keywords: buildBranchKeywords(b.name, b.remote),
|
||||
group: "branches",
|
||||
groupLabel: t("task:branchesGroup"),
|
||||
renderLabel: () => (
|
||||
<span className="flex min-w-0 flex-1 items-center justify-between gap-2">
|
||||
<span className="truncate" title={display}>
|
||||
|
||||
@@ -132,7 +132,9 @@ function makeFs(): DialogFormState {
|
||||
currentDefaults: { name: "", description: "" },
|
||||
descriptionInputRef: createRef<TaskFormInputsHandle>(),
|
||||
repositories: [],
|
||||
repositoriesDirty: false,
|
||||
setRepositories: () => {},
|
||||
setRepositoriesDirty: () => {},
|
||||
addRepository: () => {},
|
||||
removeRepository: () => {},
|
||||
updateRepository: () => {},
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import type { LocalRepository } from "@/lib/types/http";
|
||||
import type {
|
||||
StepType,
|
||||
TaskCreateDialogInitialValues,
|
||||
TaskRemoteRepoRow,
|
||||
TaskRepoRow,
|
||||
} from "@/components/task-create-dialog-types";
|
||||
|
||||
export type FormResetters = {
|
||||
setTaskName: (value: string) => void;
|
||||
setHasTitle: (value: boolean) => void;
|
||||
setHasDescription: (value: boolean) => void;
|
||||
setHasPendingAttachmentUploads: (value: boolean) => void;
|
||||
setRepositories: (value: TaskRepoRow[]) => void;
|
||||
setRepositoriesDirty: (value: boolean) => void;
|
||||
setRemoteRepos: (value: TaskRemoteRepoRow[]) => void;
|
||||
setAgentProfileId: (value: string) => void;
|
||||
setExecutorId: (value: string) => void;
|
||||
setExecutorProfileId: (value: string) => void;
|
||||
setSelectedWorkflowId: (value: string | null) => void;
|
||||
setFetchedSteps: (value: StepType[] | null) => void;
|
||||
setDiscoveredRepositories: (value: LocalRepository[]) => void;
|
||||
setDiscoverReposLoaded: (value: boolean) => void;
|
||||
setUseRemote: (value: boolean) => void;
|
||||
setNoRepository: (value: boolean) => void;
|
||||
setWorkspacePath: (value: string) => void;
|
||||
setAutopilot: (value: boolean) => void;
|
||||
setGitHubUrlError: (value: string | null) => void;
|
||||
setFreshBranchEnabled: (value: boolean) => void;
|
||||
setCurrentLocalBranch: (value: string) => void;
|
||||
setBlockedBy: (value: string[]) => void;
|
||||
};
|
||||
|
||||
export function resetTaskForm(
|
||||
resetters: FormResetters,
|
||||
name: string,
|
||||
description: string,
|
||||
workflowId: string | null,
|
||||
initialValues?: TaskCreateDialogInitialValues,
|
||||
) {
|
||||
resetters.setTaskName(name);
|
||||
resetters.setHasTitle(name.trim().length > 0);
|
||||
resetters.setHasDescription(description.trim().length > 0);
|
||||
resetters.setHasPendingAttachmentUploads(false);
|
||||
const savedRepositories = initialValues?.repositories ?? [];
|
||||
const restoredRepositories = savedRepositories.map((repository, index) => ({
|
||||
key: `row-${index}`,
|
||||
repositoryId: repository.repository_id,
|
||||
branch:
|
||||
repository.branch_policy_base_branch ??
|
||||
repository.base_branch ??
|
||||
repository.checkout_branch ??
|
||||
"",
|
||||
branchPolicyId: repository.branch_policy_id,
|
||||
}));
|
||||
if (restoredRepositories.length === 0 && initialValues?.repositoryId) {
|
||||
restoredRepositories.push({
|
||||
key: "row-0",
|
||||
repositoryId: initialValues.repositoryId,
|
||||
branch: initialValues.branch ?? "",
|
||||
branchPolicyId: undefined,
|
||||
});
|
||||
}
|
||||
resetters.setRepositories(restoredRepositories);
|
||||
resetters.setRepositoriesDirty(false);
|
||||
resetters.setAgentProfileId("");
|
||||
resetters.setExecutorId("");
|
||||
resetters.setExecutorProfileId("");
|
||||
resetters.setSelectedWorkflowId(workflowId);
|
||||
resetters.setFetchedSteps(null);
|
||||
resetters.setAutopilot(false);
|
||||
}
|
||||
@@ -265,8 +265,8 @@ function useRepositoryHandlers(fs: DialogFormState, repositories: Repository[])
|
||||
const wasLocalPath = Boolean(fs.repositories.find((row) => row.key === key)?.localPath);
|
||||
const isLocalPath = !isWorkspaceRepo && Boolean(value);
|
||||
const patch: Partial<TaskRepoRow> = isWorkspaceRepo
|
||||
? { repositoryId: value, localPath: undefined, branch: "" }
|
||||
: { repositoryId: undefined, localPath: value, branch: "" };
|
||||
? { repositoryId: value, localPath: undefined, branch: "", branchPolicyId: undefined }
|
||||
: { repositoryId: undefined, localPath: value, branch: "", branchPolicyId: undefined };
|
||||
fs.updateRepository(key, patch);
|
||||
if (wasLocalPath !== isLocalPath) {
|
||||
fs.setExecutorId("");
|
||||
@@ -286,13 +286,21 @@ function useRepositoryHandlers(fs: DialogFormState, repositories: Repository[])
|
||||
|
||||
const handleRowBranchChange = useCallback(
|
||||
(key: string, value: string) => {
|
||||
fs.updateRepository(key, { branch: value });
|
||||
fs.updateRepository(key, { branch: value, branchPolicyId: undefined });
|
||||
syncTaskCreateLastUsed({ branch: value });
|
||||
},
|
||||
[fs],
|
||||
);
|
||||
|
||||
return { handleRowRepositoryChange, handleRowBranchChange };
|
||||
const handleRowPolicyChange = useCallback(
|
||||
(key: string, policyId: string, baseBranch: string) => {
|
||||
fs.updateRepository(key, { branch: baseBranch, branchPolicyId: policyId });
|
||||
syncTaskCreateLastUsed({ branch: baseBranch });
|
||||
},
|
||||
[fs],
|
||||
);
|
||||
|
||||
return { handleRowRepositoryChange, handleRowBranchChange, handleRowPolicyChange };
|
||||
}
|
||||
|
||||
function useProfileAndNameHandlers(fs: DialogFormState) {
|
||||
|
||||
@@ -3,6 +3,8 @@ import { buildRepositoriesPayload, findDuplicateRemoteRepo } from "./task-create
|
||||
import type { TaskRemoteRepoRow } from "@/components/task-create-dialog-types";
|
||||
import type { PRInfo } from "@/hooks/domains/github/use-pr-info-by-url";
|
||||
|
||||
const FRONT_REPOSITORY_ID = "repo-front";
|
||||
|
||||
/** Minimal TaskRemoteRepoRow builder for the dedup tests. */
|
||||
function remoteRow(key: string, url: string, branch = ""): TaskRemoteRepoRow {
|
||||
return { key, url, branch, source: "paste" };
|
||||
@@ -23,7 +25,7 @@ describe("buildRepositoriesPayload — unified rows", () => {
|
||||
useRemote: false,
|
||||
remoteRepos: [],
|
||||
repositories: [
|
||||
{ key: "r0", repositoryId: "repo-front", branch: "main" },
|
||||
{ key: "r0", repositoryId: FRONT_REPOSITORY_ID, branch: "main" },
|
||||
{ key: "r1", repositoryId: "repo-back", branch: "develop" },
|
||||
{ key: "r2", branch: "" }, // no repo picked yet — dropped
|
||||
{ key: "r3", repositoryId: "repo-shared", branch: "" },
|
||||
@@ -31,12 +33,41 @@ describe("buildRepositoriesPayload — unified rows", () => {
|
||||
discoveredRepositories: [],
|
||||
});
|
||||
expect(payload).toEqual([
|
||||
{ repository_id: "repo-front", base_branch: "main", checkout_branch: undefined },
|
||||
{
|
||||
repository_id: FRONT_REPOSITORY_ID,
|
||||
base_branch: "main",
|
||||
checkout_branch: undefined,
|
||||
},
|
||||
{ repository_id: "repo-back", base_branch: "develop", checkout_branch: undefined },
|
||||
{ repository_id: "repo-shared", base_branch: undefined, checkout_branch: undefined },
|
||||
]);
|
||||
});
|
||||
|
||||
it("submits a selected branch policy id without deriving identity from its label", () => {
|
||||
const payload = buildRepositoriesPayload({
|
||||
useRemote: false,
|
||||
remoteRepos: [],
|
||||
repositories: [
|
||||
{
|
||||
key: "r0",
|
||||
repositoryId: FRONT_REPOSITORY_ID,
|
||||
branch: "develop",
|
||||
branchPolicyId: "policy-hotfix",
|
||||
},
|
||||
],
|
||||
discoveredRepositories: [],
|
||||
});
|
||||
|
||||
expect(payload).toEqual([
|
||||
{
|
||||
repository_id: FRONT_REPOSITORY_ID,
|
||||
base_branch: "develop",
|
||||
checkout_branch: undefined,
|
||||
branch_policy_id: "policy-hotfix",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("emits local_path + default_branch for discovered (on-machine) rows", () => {
|
||||
const payload = buildRepositoriesPayload({
|
||||
useRemote: false,
|
||||
|
||||
@@ -339,6 +339,7 @@ export function buildRepositoriesPayload(opts: {
|
||||
if (row.repositoryId) {
|
||||
return {
|
||||
repository_id: row.repositoryId,
|
||||
...(row.branchPolicyId ? { branch_policy_id: row.branchPolicyId } : {}),
|
||||
base_branch: branches.base_branch,
|
||||
checkout_branch: branches.checkout_branch,
|
||||
...fresh,
|
||||
|
||||
@@ -31,6 +31,7 @@ export function useLockedFieldSync(
|
||||
if (lockedWorkflow && workflowId && workflowId !== fs.selectedWorkflowId) {
|
||||
fs.setSelectedWorkflowId(workflowId);
|
||||
}
|
||||
if (initialValues?.repositories?.length) return;
|
||||
if (!repoId) return;
|
||||
const current = fs.repositories[0];
|
||||
if (current?.repositoryId === repoId && current?.branch === (branch ?? "")) return;
|
||||
|
||||
@@ -162,7 +162,45 @@ describe("sortBranches", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("grouped pill options", () => {
|
||||
it("keeps branch policies before branches even when a branch is selected", async () => {
|
||||
render(
|
||||
<Pill
|
||||
icon={<span aria-hidden="true" />}
|
||||
value="main"
|
||||
placeholder="branch"
|
||||
options={[
|
||||
{ value: "main", label: "main", group: "branches", groupLabel: "Branches" },
|
||||
{
|
||||
value: "policy:feature",
|
||||
label: "Feature policy",
|
||||
group: "policies",
|
||||
groupLabel: "Branch policies",
|
||||
},
|
||||
]}
|
||||
onSelect={vi.fn()}
|
||||
searchPlaceholder="Search branches..."
|
||||
emptyMessage="No branches"
|
||||
/>,
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /main/i }));
|
||||
const policies = await screen.findByText("Branch policies");
|
||||
const branches = await screen.findByText("Branches");
|
||||
expect(
|
||||
Boolean(policies.compareDocumentPosition(branches) & Node.DOCUMENT_POSITION_FOLLOWING),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("branchToOption keywords", () => {
|
||||
it("tags branch options for the grouped selector", () => {
|
||||
expect(branchToOption(localBranch("main"))).toMatchObject({
|
||||
group: "branches",
|
||||
groupLabel: expect.any(String),
|
||||
});
|
||||
});
|
||||
|
||||
function keywords(b: Branch): string[] {
|
||||
return branchToOption(b).keywords ?? [];
|
||||
}
|
||||
|
||||
@@ -24,6 +24,11 @@ export type PillOption = {
|
||||
label: string;
|
||||
keywords?: string[];
|
||||
renderLabel?: () => React.ReactNode;
|
||||
renderAccessory?: () => React.ReactNode;
|
||||
group?: string;
|
||||
groupLabel?: string;
|
||||
disabled?: boolean;
|
||||
disabledReason?: string;
|
||||
};
|
||||
|
||||
export type PillAction = {
|
||||
@@ -102,36 +107,71 @@ function PillCommandList({
|
||||
setOpen: (open: boolean) => void;
|
||||
emptyMessage: string;
|
||||
}) {
|
||||
const orderedOptions = prioritizeSelectedOption(options, value, (option) => option.value);
|
||||
const groups = new Map<string, { label?: string; options: PillOption[] }>();
|
||||
for (const option of options) {
|
||||
const key = option.group ?? "";
|
||||
const group = groups.get(key) ?? { label: option.groupLabel, options: [] };
|
||||
group.options.push(option);
|
||||
groups.set(key, group);
|
||||
}
|
||||
const groupOrder = new Map([
|
||||
["policies", 0],
|
||||
["branches", 1],
|
||||
]);
|
||||
const orderedGroups = Array.from(groups.entries()).sort(
|
||||
([firstKey], [secondKey]) =>
|
||||
(groupOrder.get(firstKey) ?? Number.MAX_SAFE_INTEGER) -
|
||||
(groupOrder.get(secondKey) ?? Number.MAX_SAFE_INTEGER),
|
||||
);
|
||||
|
||||
return (
|
||||
<CommandList>
|
||||
<CommandEmpty>{emptyMessage}</CommandEmpty>
|
||||
<CommandGroup>
|
||||
{orderedOptions.map((option) => {
|
||||
const selected = option.value === value;
|
||||
return (
|
||||
<CommandItem
|
||||
key={option.value}
|
||||
value={option.value}
|
||||
keywords={[option.label, ...(option.keywords ?? [])]}
|
||||
onPointerDown={(event) => onPointerSelect(event.pointerType)}
|
||||
onSelect={() => {
|
||||
onSelect(option.value);
|
||||
setOpen(false);
|
||||
}}
|
||||
className={selectorOptionClassName(selected)}
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
{option.renderLabel ? option.renderLabel() : option.label}
|
||||
</div>
|
||||
<IconCheck
|
||||
className={cn("absolute right-2 h-4 w-4", selected ? "opacity-100" : "opacity-0")}
|
||||
/>
|
||||
</CommandItem>
|
||||
);
|
||||
})}
|
||||
</CommandGroup>
|
||||
{orderedGroups.map(([key, group]) => (
|
||||
<CommandGroup key={key || "ungrouped"} heading={group.label}>
|
||||
{prioritizeSelectedOption(group.options, value, (option) => option.value).map(
|
||||
(option) => {
|
||||
const selected = option.value === value;
|
||||
const item = (
|
||||
<CommandItem
|
||||
key={option.renderAccessory ? undefined : option.value}
|
||||
value={option.value}
|
||||
keywords={[option.label, ...(option.keywords ?? [])]}
|
||||
disabled={option.disabled}
|
||||
onPointerDown={(event) => onPointerSelect(event.pointerType)}
|
||||
onSelect={() => {
|
||||
onSelect(option.value);
|
||||
setOpen(false);
|
||||
}}
|
||||
className={cn(
|
||||
selectorOptionClassName(selected),
|
||||
option.renderAccessory && "pr-14",
|
||||
)}
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
{option.renderLabel ? option.renderLabel() : option.label}
|
||||
</div>
|
||||
<IconCheck
|
||||
className={cn(
|
||||
"absolute right-2 h-4 w-4",
|
||||
selected ? "opacity-100" : "opacity-0",
|
||||
)}
|
||||
/>
|
||||
</CommandItem>
|
||||
);
|
||||
if (!option.renderAccessory) return item;
|
||||
return (
|
||||
<div key={option.value} className="relative">
|
||||
{item}
|
||||
<div className="absolute inset-y-0 right-7 z-10 flex items-center">
|
||||
{option.renderAccessory()}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
)}
|
||||
</CommandGroup>
|
||||
))}
|
||||
</CommandList>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -40,6 +40,7 @@ export function buildDialogFormBodyProps(
|
||||
onTaskNameChange: handlers.handleTaskNameChange,
|
||||
onRowRepositoryChange: handlers.handleRowRepositoryChange,
|
||||
onRowBranchChange: handlers.handleRowBranchChange,
|
||||
onRowPolicyChange: handlers.handleRowPolicyChange,
|
||||
initialDescription: fs.currentDefaults.description,
|
||||
workspaceId: props.workspaceId,
|
||||
onJiraImport: setup.handleJiraImport,
|
||||
|
||||
@@ -0,0 +1,295 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo, useState } from "react";
|
||||
import { IconCode, IconFolderPlus, IconGitBranch, IconInfoCircle } from "@tabler/icons-react";
|
||||
import { Badge } from "@kandev/ui/badge";
|
||||
import {
|
||||
Drawer,
|
||||
DrawerContent,
|
||||
DrawerDescription,
|
||||
DrawerHeader,
|
||||
DrawerTitle,
|
||||
DrawerTrigger,
|
||||
} from "@kandev/ui/drawer";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
|
||||
import { Pill, type PillAction, type PillOption } from "@/components/task-create-dialog-pill";
|
||||
import type { Branch, RepositoryBranchPolicy } from "@/lib/types/http";
|
||||
import type { TaskRepoRow } from "@/components/task-create-dialog-types";
|
||||
import { computeBranchPlaceholder } from "@/components/task-create-dialog-branch-options";
|
||||
import {
|
||||
computeBranchDisabledReason,
|
||||
computeBranchPrefix,
|
||||
computeBranchTooltip,
|
||||
type BranchIntent,
|
||||
} from "@/components/task-create-dialog-branch-utils";
|
||||
import { scoreBranch } from "@/lib/utils/branch-filter";
|
||||
import { t } from "@/lib/i18n";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useTouchDrawer } from "@/hooks/use-compact-task-chrome";
|
||||
|
||||
function BranchPolicyOptionInfo({
|
||||
policy,
|
||||
summary,
|
||||
unavailableReason,
|
||||
}: {
|
||||
policy: RepositoryBranchPolicy;
|
||||
summary: string;
|
||||
unavailableReason?: string;
|
||||
}) {
|
||||
const usesTouchDrawer = useTouchDrawer();
|
||||
const [open, setOpen] = useState(false);
|
||||
const details = unavailableReason ? `${summary} ${unavailableReason}` : summary;
|
||||
const trigger = (
|
||||
<button
|
||||
type="button"
|
||||
aria-label={details}
|
||||
aria-haspopup={usesTouchDrawer ? "dialog" : undefined}
|
||||
aria-expanded={usesTouchDrawer ? open : undefined}
|
||||
data-testid={`branch-policy-option-info-${policy.id}`}
|
||||
className="flex h-11 w-11 shrink-0 cursor-help items-center justify-center rounded-sm text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring sm:h-7 sm:w-7"
|
||||
onPointerDown={(event) => event.stopPropagation()}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
<IconInfoCircle className="h-4 w-4" aria-hidden="true" />
|
||||
</button>
|
||||
);
|
||||
|
||||
if (!usesTouchDrawer) {
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>{trigger}</TooltipTrigger>
|
||||
<TooltipContent className="max-w-80 text-xs">{details}</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Drawer open={open} onOpenChange={setOpen}>
|
||||
<DrawerTrigger asChild>{trigger}</DrawerTrigger>
|
||||
<DrawerContent>
|
||||
<DrawerHeader>
|
||||
<DrawerTitle>{policy.name}</DrawerTitle>
|
||||
<DrawerDescription>{details}</DrawerDescription>
|
||||
</DrawerHeader>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
);
|
||||
}
|
||||
|
||||
function branchPolicyToOption(
|
||||
policy: RepositoryBranchPolicy,
|
||||
branches: Branch[],
|
||||
policyDisabledReason?: string,
|
||||
): PillOption {
|
||||
const baseBranchAvailable = branches.some((branch) => {
|
||||
if (branch.name === policy.base_branch) return true;
|
||||
return branch.type === "remote" && `${branch.remote}/${branch.name}` === policy.base_branch;
|
||||
});
|
||||
const unavailableReason =
|
||||
policyDisabledReason ?? (baseBranchAvailable ? undefined : t("task:branchPolicyUnavailable"));
|
||||
const summary = t("workspaces:branchPolicySummary", {
|
||||
base: policy.base_branch,
|
||||
template: policy.branch_template,
|
||||
target: policy.pull_request_target,
|
||||
});
|
||||
return {
|
||||
value: `policy:${policy.id}`,
|
||||
label: policy.name,
|
||||
keywords: [
|
||||
policy.name,
|
||||
policy.description,
|
||||
policy.base_branch,
|
||||
policy.branch_template,
|
||||
policy.pull_request_target,
|
||||
].filter(Boolean),
|
||||
group: "policies",
|
||||
groupLabel: t("task:branchPoliciesGroup"),
|
||||
disabled: Boolean(unavailableReason),
|
||||
disabledReason: unavailableReason,
|
||||
renderLabel: () => (
|
||||
<span className="flex min-w-0 flex-1 items-center gap-2">
|
||||
<Badge variant="secondary" className="shrink-0 text-xs">
|
||||
{t("task:branchPolicyMarker")}
|
||||
</Badge>
|
||||
<span className="truncate" title={policy.name}>
|
||||
{policy.name}
|
||||
</span>
|
||||
</span>
|
||||
),
|
||||
renderAccessory: () => (
|
||||
<BranchPolicyOptionInfo
|
||||
policy={policy}
|
||||
summary={summary}
|
||||
unavailableReason={unavailableReason}
|
||||
/>
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export function useRepoChipBranchPicker({
|
||||
row,
|
||||
branchPolicies,
|
||||
branches,
|
||||
branchOptions,
|
||||
branchesLoading,
|
||||
preferredDefaultBranchLoading,
|
||||
policyDisabledReason,
|
||||
onBranchChange,
|
||||
onPolicyChange,
|
||||
onPolicySelected,
|
||||
}: {
|
||||
row: TaskRepoRow;
|
||||
branchPolicies: RepositoryBranchPolicy[];
|
||||
branches: Branch[];
|
||||
branchOptions: PillOption[];
|
||||
branchesLoading: boolean;
|
||||
preferredDefaultBranchLoading?: boolean;
|
||||
policyDisabledReason?: string;
|
||||
onBranchChange: (value: string) => void;
|
||||
onPolicyChange?: (policyId: string, baseBranch: string) => void;
|
||||
onPolicySelected?: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const hasRepo = !!(row.repositoryId || row.localPath);
|
||||
const branchValue = preferredDefaultBranchLoading ? "" : row.branch;
|
||||
const selectedPolicy = branchPolicies.find((policy) => policy.id === row.branchPolicyId);
|
||||
const policyOptions = useMemo(
|
||||
() =>
|
||||
branchPolicies.map((policy) => branchPolicyToOption(policy, branches, policyDisabledReason)),
|
||||
[branchPolicies, branches, policyDisabledReason],
|
||||
);
|
||||
const branchPickerOptions = useMemo(
|
||||
() => [...policyOptions, ...branchOptions],
|
||||
[branchOptions, policyOptions],
|
||||
);
|
||||
const selectedBranchValue = selectedPolicy ? `policy:${selectedPolicy.id}` : branchValue;
|
||||
const selectedBranchLabel = selectedPolicy
|
||||
? t("task:branchPolicySelected", {
|
||||
name: selectedPolicy.name,
|
||||
base: selectedPolicy.base_branch,
|
||||
})
|
||||
: branchValue;
|
||||
const handleBranchSelect = (value: string) => {
|
||||
if (value.startsWith("policy:")) {
|
||||
const policy = branchPolicies.find((candidate) => `policy:${candidate.id}` === value);
|
||||
if (policy) {
|
||||
onPolicyChange?.(policy.id, policy.base_branch);
|
||||
onPolicySelected?.();
|
||||
}
|
||||
return;
|
||||
}
|
||||
onBranchChange(value);
|
||||
};
|
||||
const branchPlaceholder = computeBranchPlaceholder(
|
||||
hasRepo,
|
||||
branchesLoading || !!preferredDefaultBranchLoading,
|
||||
branchPickerOptions.length,
|
||||
);
|
||||
return {
|
||||
hasRepo,
|
||||
branchPickerOptions,
|
||||
selectedBranchValue,
|
||||
selectedBranchLabel,
|
||||
handleBranchSelect,
|
||||
branchPlaceholder,
|
||||
};
|
||||
}
|
||||
|
||||
export type RepoChipBranchPicker = ReturnType<typeof useRepoChipBranchPicker>;
|
||||
|
||||
function buildCreateRepositoryAction(onSelect?: () => void): PillAction | undefined {
|
||||
if (!onSelect) return undefined;
|
||||
return {
|
||||
label: t("task:createNewRepository"),
|
||||
icon: <IconFolderPlus className="h-3.5 w-3.5" />,
|
||||
onSelect,
|
||||
};
|
||||
}
|
||||
|
||||
export function RepoChipRepositoryPill({
|
||||
repoLabel,
|
||||
repoTooltip,
|
||||
repositoryValue,
|
||||
repoOptions,
|
||||
onRepositoryChange,
|
||||
onCreateRepository,
|
||||
onRefreshRepositories,
|
||||
repositoriesRefreshing,
|
||||
}: {
|
||||
repoLabel: string;
|
||||
repoTooltip: string;
|
||||
repositoryValue: string;
|
||||
repoOptions: PillOption[];
|
||||
onRepositoryChange: (value: string) => void;
|
||||
onCreateRepository?: () => void;
|
||||
onRefreshRepositories?: () => void;
|
||||
repositoriesRefreshing?: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Pill
|
||||
icon={<IconCode className="h-3 w-3 shrink-0 text-muted-foreground" />}
|
||||
value={repoLabel}
|
||||
selectedValue={repositoryValue}
|
||||
placeholder={t("task:repository")}
|
||||
options={repoOptions}
|
||||
onSelect={onRepositoryChange}
|
||||
searchPlaceholder={t("task:searchRepositories")}
|
||||
emptyMessage={t("task:noRepositories")}
|
||||
testId="repo-chip-trigger"
|
||||
tooltip={repoTooltip}
|
||||
action={buildCreateRepositoryAction(onCreateRepository)}
|
||||
onRefresh={onRefreshRepositories}
|
||||
refreshing={repositoriesRefreshing}
|
||||
refreshLabel="repositories"
|
||||
flat
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function RepoChipBranchPill({
|
||||
branchPicker,
|
||||
branchIntent,
|
||||
branchLocked,
|
||||
branchesLoading,
|
||||
refreshBranches,
|
||||
}: {
|
||||
branchPicker: RepoChipBranchPicker;
|
||||
branchIntent?: BranchIntent;
|
||||
branchLocked?: boolean;
|
||||
branchesLoading: boolean;
|
||||
refreshBranches?: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Pill
|
||||
icon={<IconGitBranch className="h-3 w-3 shrink-0 text-muted-foreground" />}
|
||||
value={branchPicker.selectedBranchLabel}
|
||||
selectedValue={branchPicker.selectedBranchValue}
|
||||
placeholder={branchPicker.branchPlaceholder}
|
||||
prefix={computeBranchPrefix(branchIntent ?? "none")}
|
||||
options={branchPicker.branchPickerOptions}
|
||||
onSelect={branchPicker.handleBranchSelect}
|
||||
disabled={
|
||||
branchLocked ||
|
||||
!branchPicker.hasRepo ||
|
||||
branchesLoading ||
|
||||
branchPicker.branchPickerOptions.length === 0
|
||||
}
|
||||
disabledReason={computeBranchDisabledReason({
|
||||
branchLocked: !!branchLocked,
|
||||
hasRepo: branchPicker.hasRepo,
|
||||
branchesLoading,
|
||||
optionCount: branchPicker.branchPickerOptions.length,
|
||||
})}
|
||||
searchPlaceholder={t("task:searchBranches")}
|
||||
emptyMessage={t("task:noBranches")}
|
||||
testId="branch-chip-trigger"
|
||||
tooltip={computeBranchTooltip(branchIntent)}
|
||||
onRefresh={refreshBranches}
|
||||
refreshing={branchesLoading}
|
||||
filter={scoreBranch}
|
||||
flat
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, it, expect, vi, afterEach } from "vitest";
|
||||
import { render, screen, fireEvent, cleanup } from "@testing-library/react";
|
||||
import type { Branch, Repository } from "@/lib/types/http";
|
||||
import type { Branch, Repository, RepositoryBranchPolicy } from "@/lib/types/http";
|
||||
import type { DialogFormState, TaskRepoRow } from "./task-create-dialog-types";
|
||||
import { TooltipProvider } from "@kandev/ui/tooltip";
|
||||
|
||||
@@ -10,6 +10,7 @@ const lastBranchSource = vi.hoisted((): { value: unknown } => ({ value: null }))
|
||||
const mockBranches = vi.hoisted((): { value: { branches: Branch[]; isLoading: boolean } } => ({
|
||||
value: { branches: [], isLoading: false },
|
||||
}));
|
||||
const mockPolicies = vi.hoisted((): { value: RepositoryBranchPolicy[] } => ({ value: [] }));
|
||||
|
||||
vi.mock("@/hooks/domains/workspace/use-repository-branches", () => ({
|
||||
useBranches: (source: unknown) => {
|
||||
@@ -18,6 +19,10 @@ vi.mock("@/hooks/domains/workspace/use-repository-branches", () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/hooks/domains/workspace/use-repository-branch-policies", () => ({
|
||||
useRepositoryBranchPolicies: () => ({ policies: mockPolicies.value }),
|
||||
}));
|
||||
|
||||
// The Remote-mode branch of RepoChipsRow renders RemoteRepoChipsRow, which
|
||||
// in turn renders RemoteRepoChip — a heavy popover with its own GitHub
|
||||
// hook. Stub the chip here so tests for this row stay focused on the
|
||||
@@ -29,7 +34,11 @@ vi.mock("./task-create-dialog-remote-repo-chip", () => ({
|
||||
|
||||
import { RepoChipsRow } from "./task-create-dialog-repo-chips";
|
||||
|
||||
afterEach(cleanup);
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
mockBranches.value = { branches: [], isLoading: false };
|
||||
mockPolicies.value = [];
|
||||
});
|
||||
|
||||
const REPO_FRONT_ID = "repo-front";
|
||||
const REPO_BACK_ID = "repo-back";
|
||||
@@ -236,6 +245,51 @@ describe("RepoChipsRow", () => {
|
||||
expect(onRowBranchChange).toHaveBeenCalledWith("r0", "main");
|
||||
});
|
||||
|
||||
it("disables branch policies for multi-repo local execution", () => {
|
||||
mockBranches.value = {
|
||||
branches: [{ name: "main", type: "local" } as Branch],
|
||||
isLoading: false,
|
||||
};
|
||||
mockPolicies.value = [
|
||||
{
|
||||
id: "policy-1",
|
||||
repository_id: REPO_FRONT_ID as RepositoryBranchPolicy["repository_id"],
|
||||
name: "Feature policy",
|
||||
description: "",
|
||||
base_branch: "main",
|
||||
branch_template: "feature/{title}-{suffix}",
|
||||
pull_request_target: "develop",
|
||||
created_at: "2026-08-24T10:00:00Z",
|
||||
updated_at: "2026-08-24T10:00:00Z",
|
||||
},
|
||||
];
|
||||
renderInProvider(
|
||||
<RepoChipsRow
|
||||
fs={makeFs({
|
||||
repositories: [
|
||||
row({ key: "r0", repositoryId: REPO_FRONT_ID }),
|
||||
row({ key: "r1", repositoryId: REPO_BACK_ID, branch: "main" }),
|
||||
],
|
||||
})}
|
||||
repositories={[makeRepo(REPO_FRONT_ID, "frontend"), makeRepo(REPO_BACK_ID, "backend")]}
|
||||
isTaskStarted={false}
|
||||
workspaceId="ws-1"
|
||||
onRowRepositoryChange={NOOP}
|
||||
onRowBranchChange={NOOP}
|
||||
isLocalExecutor
|
||||
freshBranchAvailable={false}
|
||||
/>,
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getAllByTestId("branch-chip-trigger")[0]);
|
||||
|
||||
const option = screen.getByRole("option", { name: /Feature policy/ });
|
||||
expect(option.getAttribute("aria-disabled")).toBe("true");
|
||||
expect(
|
||||
screen.getByTestId("branch-policy-option-info-policy-1").getAttribute("aria-label"),
|
||||
).toContain("single repository");
|
||||
});
|
||||
|
||||
it("local-executor row shows the loading placeholder while resolving the current branch", () => {
|
||||
mockBranches.value = { branches: [], isLoading: false };
|
||||
renderInProvider(
|
||||
|
||||
@@ -32,6 +32,8 @@ type RepoChipsRowProps = {
|
||||
*/
|
||||
onRowRepositoryChange: (key: string, value: string) => void;
|
||||
onRowBranchChange: (key: string, value: string) => void;
|
||||
onRowPolicyChange?: (key: string, policyId: string, baseBranch: string) => void;
|
||||
onPolicySelected?: () => void;
|
||||
/** Toggles the Remote tab on/off. Remote-mode rows live in `fs.remoteRepos`. */
|
||||
onToggleRemote?: () => void;
|
||||
/**
|
||||
@@ -89,6 +91,8 @@ export function RepoChipsRow({
|
||||
workspaceId,
|
||||
onRowRepositoryChange,
|
||||
onRowBranchChange,
|
||||
onRowPolicyChange,
|
||||
onPolicySelected,
|
||||
onToggleRemote,
|
||||
freshBranchAvailable,
|
||||
freshBranchEnabled,
|
||||
@@ -137,6 +141,7 @@ export function RepoChipsRow({
|
||||
const hasDiscovered = fs.discoveredRepositories.length > 0;
|
||||
const canAddMore = repositories.length > 0 || hasDiscovered;
|
||||
const addHint = computeAddHint(canAddMore, repositories.length);
|
||||
const branchPolicyDisabledReason = policyDisabled(isLocalExecutor, freshBranchAvailable);
|
||||
|
||||
return (
|
||||
// min-h-9 reserves enough vertical space for the tallest mode body so the
|
||||
@@ -158,8 +163,11 @@ export function RepoChipsRow({
|
||||
addHint={addHint}
|
||||
freshBranchAvailable={freshBranchAvailable}
|
||||
freshBranchEnabled={freshBranchEnabled}
|
||||
branchPolicyDisabledReason={branchPolicyDisabledReason}
|
||||
onRowRepositoryChange={onRowRepositoryChange}
|
||||
onRowBranchChange={onRowBranchChange}
|
||||
onRowPolicyChange={onRowPolicyChange}
|
||||
onPolicySelected={onPolicySelected}
|
||||
onToggleFreshBranch={onToggleFreshBranch}
|
||||
onWorkspacePathChange={onWorkspacePathChange}
|
||||
lastUsedBranch={lastUsedBranch}
|
||||
@@ -245,8 +253,11 @@ function ModeBody({
|
||||
addHint,
|
||||
freshBranchAvailable,
|
||||
freshBranchEnabled,
|
||||
branchPolicyDisabledReason,
|
||||
onRowRepositoryChange,
|
||||
onRowBranchChange,
|
||||
onRowPolicyChange,
|
||||
onPolicySelected,
|
||||
onToggleFreshBranch,
|
||||
onWorkspacePathChange,
|
||||
lastUsedBranch,
|
||||
@@ -264,8 +275,11 @@ function ModeBody({
|
||||
addHint: string | undefined;
|
||||
freshBranchAvailable?: boolean;
|
||||
freshBranchEnabled?: boolean;
|
||||
branchPolicyDisabledReason?: string;
|
||||
onRowRepositoryChange: (key: string, value: string) => void;
|
||||
onRowBranchChange: (key: string, value: string) => void;
|
||||
onRowPolicyChange?: (key: string, policyId: string, baseBranch: string) => void;
|
||||
onPolicySelected?: () => void;
|
||||
onToggleFreshBranch?: (enabled: boolean) => void;
|
||||
onWorkspacePathChange?: (value: string) => void;
|
||||
lastUsedBranch?: string | null;
|
||||
@@ -306,12 +320,16 @@ function ModeBody({
|
||||
currentLocalBranch={fs.currentLocalBranch}
|
||||
currentLocalBranchLoading={fs.currentLocalBranchLoading}
|
||||
freshBranchEnabled={fs.freshBranchEnabled}
|
||||
branchPolicyDisabledReason={branchPolicyDisabledReason}
|
||||
canAddMore={canAddMore}
|
||||
addHint={addHint}
|
||||
onAdd={fs.addRepository}
|
||||
onRemove={fs.removeRepository}
|
||||
onRowRepositoryChange={onRowRepositoryChange}
|
||||
onRowBranchChange={onRowBranchChange}
|
||||
onRowPolicyChange={onRowPolicyChange}
|
||||
onPolicySelected={onPolicySelected}
|
||||
showBranchPolicies
|
||||
lastUsedBranch={lastUsedBranch}
|
||||
userSettingsLoaded={userSettingsLoaded}
|
||||
onCreateRepository={onCreateRepository}
|
||||
@@ -367,3 +385,12 @@ function computeAddHint(canAddMore: boolean, workspaceRepoCount: number): string
|
||||
if (workspaceRepoCount === 0) return t("task:noRepositoriesAvailableInWorkspace");
|
||||
return t("task:allWorkspaceRepositoriesAdded");
|
||||
}
|
||||
|
||||
function policyDisabled(
|
||||
isLocalExecutor: boolean | undefined,
|
||||
freshBranchAvailable: boolean | undefined,
|
||||
): string | undefined {
|
||||
return isLocalExecutor && !freshBranchAvailable
|
||||
? t("task:branchPolicyRequiresSingleRepository")
|
||||
: undefined;
|
||||
}
|
||||
|
||||
@@ -13,23 +13,35 @@ import type { TaskRemoteRepoRow, TaskRepoRow } from "@/components/task-create-di
|
||||
*/
|
||||
export function useRepositoriesState() {
|
||||
const [repositories, setRepositories] = useState<TaskRepoRow[]>([]);
|
||||
const [repositoriesDirty, setRepositoriesDirty] = useState(false);
|
||||
const nextKeyRef = useRef(0);
|
||||
|
||||
const addRepository = useCallback(() => {
|
||||
nextKeyRef.current += 1;
|
||||
const key = `row-${nextKeyRef.current}`;
|
||||
setRepositories((rows) => [...rows, { key, branch: "" }]);
|
||||
setRepositoriesDirty(true);
|
||||
}, []);
|
||||
|
||||
const removeRepository = useCallback((key: string) => {
|
||||
setRepositories((rows) => rows.filter((r) => r.key !== key));
|
||||
setRepositoriesDirty(true);
|
||||
}, []);
|
||||
|
||||
const updateRepository = useCallback((key: string, patch: Partial<TaskRepoRow>) => {
|
||||
setRepositories((rows) => rows.map((r) => (r.key === key ? { ...r, ...patch } : r)));
|
||||
setRepositoriesDirty(true);
|
||||
}, []);
|
||||
|
||||
return { repositories, setRepositories, addRepository, removeRepository, updateRepository };
|
||||
return {
|
||||
repositories,
|
||||
repositoriesDirty,
|
||||
setRepositories,
|
||||
setRepositoriesDirty,
|
||||
addRepository,
|
||||
removeRepository,
|
||||
updateRepository,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -12,6 +12,7 @@ type UseApplyRepositorySetArgs = {
|
||||
rows: TaskRepoRow[];
|
||||
repositories: Repository[];
|
||||
setRepositories: (rows: TaskRepoRow[]) => void;
|
||||
setRepositoriesDirty: (dirty: boolean) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -27,6 +28,7 @@ export function useApplyRepositorySet({
|
||||
rows,
|
||||
repositories,
|
||||
setRepositories,
|
||||
setRepositoriesDirty,
|
||||
}: UseApplyRepositorySetArgs) {
|
||||
const { t } = useTranslation();
|
||||
const { toast } = useToast();
|
||||
@@ -36,6 +38,7 @@ export function useApplyRepositorySet({
|
||||
const outcome = applyRepositorySet({ rows, set, repositories });
|
||||
if (outcome.addedCount > 0) {
|
||||
setRepositories(outcome.rows);
|
||||
setRepositoriesDirty(true);
|
||||
}
|
||||
if (outcome.missingCount > 0) {
|
||||
toast({
|
||||
@@ -58,6 +61,6 @@ export function useApplyRepositorySet({
|
||||
});
|
||||
}
|
||||
},
|
||||
[rows, repositories, setRepositories, t, toast],
|
||||
[rows, repositories, setRepositories, setRepositoriesDirty, t, toast],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -122,7 +122,7 @@ type BranchOption = {
|
||||
value: string;
|
||||
label: string;
|
||||
keywords?: string[];
|
||||
renderLabel: () => React.ReactNode;
|
||||
renderLabel?: () => React.ReactNode;
|
||||
};
|
||||
|
||||
type BranchSelectorProps = {
|
||||
@@ -139,6 +139,10 @@ type BranchSelectorProps = {
|
||||
fetchedAt?: string;
|
||||
fetchError?: string;
|
||||
loading?: boolean;
|
||||
ariaLabel?: string;
|
||||
testId?: string;
|
||||
dropdownTestId?: string;
|
||||
dropdownLabel?: string;
|
||||
};
|
||||
|
||||
export const BranchSelector = memo(function BranchSelector({
|
||||
@@ -155,6 +159,10 @@ export const BranchSelector = memo(function BranchSelector({
|
||||
fetchedAt,
|
||||
fetchError,
|
||||
loading,
|
||||
ariaLabel,
|
||||
testId = "branch-selector",
|
||||
dropdownTestId,
|
||||
dropdownLabel = t("task:baseBranch2"),
|
||||
}: BranchSelectorProps) {
|
||||
const headerAction = onRefresh ? (
|
||||
<BranchRefreshButton
|
||||
@@ -173,10 +181,12 @@ export const BranchSelector = memo(function BranchSelector({
|
||||
searchPlaceholder={searchPlaceholder}
|
||||
emptyMessage={emptyMessage}
|
||||
disabled={disabled}
|
||||
dropdownLabel={t("task:baseBranch2")}
|
||||
ariaLabel={ariaLabel}
|
||||
dropdownLabel={dropdownLabel}
|
||||
className={disabled ? undefined : CURSOR_POINTER_CLASS}
|
||||
triggerClassName={triggerClassName}
|
||||
testId="branch-selector"
|
||||
testId={testId}
|
||||
dropdownTestId={dropdownTestId}
|
||||
filter={scoreBranch}
|
||||
headerAction={headerAction}
|
||||
loading={loading}
|
||||
|
||||
@@ -27,10 +27,17 @@ vi.mock("@/hooks/use-prompt-result-delivery", () => ({
|
||||
}));
|
||||
vi.mock("@/components/toast-provider", () => ({ useToast: () => ({ toast: vi.fn() }) }));
|
||||
vi.mock("@/components/state-provider", () => ({
|
||||
useAppStoreApi: () => ({
|
||||
getState: () => ({
|
||||
repositoryBranchPolicies: { revisionByRepositoryId: {} },
|
||||
}),
|
||||
}),
|
||||
useAppStore: (selector: (state: unknown) => unknown) =>
|
||||
selector({
|
||||
userSettings: { agentGeneratedTaskTitles: mocks.agentGeneratedTaskTitles },
|
||||
upsertRepository: vi.fn(),
|
||||
setRepositoryBranchPolicies: vi.fn(),
|
||||
setRepositoryBranchPoliciesLoading: vi.fn(),
|
||||
repositorySets: {
|
||||
itemsByWorkspaceId: {},
|
||||
loadingByWorkspaceId: {},
|
||||
|
||||
@@ -14,7 +14,7 @@ import { useToast } from "@/components/toast-provider";
|
||||
import { useRepositorySets } from "@/hooks/domains/workspace/use-repository-sets";
|
||||
import { useApplyRepositorySet } from "@/components/task-create-dialog-repository-sets-apply";
|
||||
import { selectedRepositoryIdsForSet } from "@/components/task-create-dialog-repository-sets";
|
||||
import { useAppStore } from "@/components/state-provider";
|
||||
import { useAppStore, useAppStoreApi } from "@/components/state-provider";
|
||||
import {
|
||||
useDialogFormState,
|
||||
useTaskCreateDialogEffects,
|
||||
@@ -29,6 +29,7 @@ import type { TaskCreateDialogProps } from "@/components/task-create-dialog";
|
||||
import { useResolvedTaskCreateWorkflowContext } from "@/components/task-create-dialog-workflow-context";
|
||||
import { truncateRemoteTaskTitle } from "@/lib/task-title";
|
||||
import { t } from "@/lib/i18n";
|
||||
import { listRepositoryBranchPolicies } from "@/lib/api";
|
||||
|
||||
// Catalog key: module scope, so it is resolved at the call site.
|
||||
const PROMPT_INSERTED_MESSAGE_KEY = "task:enhancedPromptInserted";
|
||||
@@ -120,6 +121,7 @@ type SubmitWiringArgs = {
|
||||
isSessionMode: boolean;
|
||||
isEditMode: boolean;
|
||||
autoTitle: boolean;
|
||||
refreshBranchPolicies: () => Promise<void>;
|
||||
preserveQueuedLastUsedOnClose: () => void;
|
||||
};
|
||||
|
||||
@@ -132,6 +134,7 @@ function useSubmitHandlersWiring({
|
||||
isSessionMode,
|
||||
isEditMode,
|
||||
autoTitle,
|
||||
refreshBranchPolicies,
|
||||
preserveQueuedLastUsedOnClose,
|
||||
}: SubmitWiringArgs) {
|
||||
const {
|
||||
@@ -156,6 +159,7 @@ function useSubmitHandlersWiring({
|
||||
workflowId,
|
||||
effectiveWorkflowId: computed.effectiveWorkflowId,
|
||||
repositories: fs.repositories,
|
||||
repositoriesDirty: fs.repositoriesDirty,
|
||||
discoveredRepositories: fs.discoveredRepositories,
|
||||
workspaceRepositories,
|
||||
useRemote: fs.useRemote,
|
||||
@@ -169,6 +173,7 @@ function useSubmitHandlersWiring({
|
||||
onCreateSession,
|
||||
onOpenChange,
|
||||
createTask,
|
||||
refreshBranchPolicies,
|
||||
preserveTaskCreateLastUsedOnClose: preserveQueuedLastUsedOnClose,
|
||||
taskId,
|
||||
parentTaskId,
|
||||
@@ -209,7 +214,12 @@ function useDialogSetupData(
|
||||
) {
|
||||
const { open, workspaceId, workflowId, defaultStepId, initialValues } = props;
|
||||
const { toast } = useToast();
|
||||
const storeApi = useAppStoreApi();
|
||||
const upsertWorkspaceRepository = useAppStore((state) => state.upsertRepository);
|
||||
const setRepositoryBranchPolicies = useAppStore((state) => state.setRepositoryBranchPolicies);
|
||||
const setRepositoryBranchPoliciesLoading = useAppStore(
|
||||
(state) => state.setRepositoryBranchPoliciesLoading,
|
||||
);
|
||||
const data = useTaskCreateDialogData({
|
||||
open,
|
||||
workspaceId,
|
||||
@@ -256,9 +266,38 @@ function useDialogSetupData(
|
||||
executors,
|
||||
upsertWorkspaceRepository,
|
||||
});
|
||||
const refreshBranchPolicies = useCallback(async () => {
|
||||
const repositoryIds = [
|
||||
...new Set(
|
||||
fs.repositories
|
||||
.map((row) => row.repositoryId)
|
||||
.filter((repositoryId): repositoryId is string => Boolean(repositoryId)),
|
||||
),
|
||||
];
|
||||
await Promise.all(
|
||||
repositoryIds.map(async (repositoryId) => {
|
||||
const requestRevision =
|
||||
storeApi.getState().repositoryBranchPolicies.revisionByRepositoryId[repositoryId] ?? 0;
|
||||
setRepositoryBranchPoliciesLoading(repositoryId, true);
|
||||
try {
|
||||
const response = await listRepositoryBranchPolicies(repositoryId, { cache: "no-store" });
|
||||
setRepositoryBranchPolicies(
|
||||
repositoryId,
|
||||
response.repository_branch_policies,
|
||||
requestRevision,
|
||||
);
|
||||
} catch {
|
||||
// Keep the original task error visible when recovery cannot refresh.
|
||||
} finally {
|
||||
setRepositoryBranchPoliciesLoading(repositoryId, false);
|
||||
}
|
||||
}),
|
||||
);
|
||||
}, [fs.repositories, setRepositoryBranchPolicies, setRepositoryBranchPoliciesLoading, storeApi]);
|
||||
return {
|
||||
...data,
|
||||
handlers,
|
||||
refreshBranchPolicies,
|
||||
repositoryLocalPath: resolveSingleRowLocalPath(fs, repositories),
|
||||
};
|
||||
}
|
||||
@@ -298,6 +337,7 @@ export function useTaskCreateDialogSetup(
|
||||
computed,
|
||||
handlers,
|
||||
repositoryLocalPath,
|
||||
refreshBranchPolicies,
|
||||
} = data;
|
||||
const submitHandlers = useSubmitHandlersWiring({
|
||||
props: resolvedProps,
|
||||
@@ -308,6 +348,7 @@ export function useTaskCreateDialogSetup(
|
||||
isSessionMode,
|
||||
isEditMode,
|
||||
autoTitle,
|
||||
refreshBranchPolicies,
|
||||
preserveQueuedLastUsedOnClose: options.preserveQueuedLastUsedOnClose ?? (() => undefined),
|
||||
});
|
||||
const guardedHandleSubmit = useGuardedSubmit(
|
||||
@@ -328,6 +369,7 @@ export function useTaskCreateDialogSetup(
|
||||
rows: fs.repositories,
|
||||
repositories,
|
||||
setRepositories: fs.setRepositories,
|
||||
setRepositoriesDirty: fs.setRepositoriesDirty,
|
||||
userSettingsLoaded,
|
||||
});
|
||||
return {
|
||||
@@ -365,6 +407,7 @@ type RepositorySetsForDialogArgs = {
|
||||
rows: DialogFormState["repositories"];
|
||||
repositories: Repository[];
|
||||
setRepositories: DialogFormState["setRepositories"];
|
||||
setRepositoriesDirty: DialogFormState["setRepositoriesDirty"];
|
||||
userSettingsLoaded: boolean;
|
||||
};
|
||||
|
||||
@@ -382,10 +425,16 @@ function useRepositorySetsForDialog({
|
||||
rows,
|
||||
repositories,
|
||||
setRepositories,
|
||||
setRepositoriesDirty,
|
||||
userSettingsLoaded,
|
||||
}: RepositorySetsForDialogArgs) {
|
||||
const { sets } = useRepositorySets(workspaceId, open);
|
||||
const onApply = useApplyRepositorySet({ rows, repositories, setRepositories });
|
||||
const onApply = useApplyRepositorySet({
|
||||
rows,
|
||||
repositories,
|
||||
setRepositories,
|
||||
setRepositoriesDirty,
|
||||
});
|
||||
const [saveOpen, setSaveOpen] = useState(false);
|
||||
// Offer "Save as set" only when there is a workspace-repository selection worth
|
||||
// saving, so the action is never a dead end.
|
||||
|
||||
@@ -211,6 +211,48 @@ describe("useDialogFormState — remoteRepos mode", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("useDialogFormState — repository policy snapshots", () => {
|
||||
it("restores a policy-backed repository row without marking it as edited", () => {
|
||||
const { result } = renderHook(() =>
|
||||
useDialogFormState(true, "ws-1", null, {
|
||||
title: "Existing task",
|
||||
repositories: [
|
||||
{
|
||||
id: "task-repo-1",
|
||||
task_id: "task-1",
|
||||
repository_id: "repo-1",
|
||||
base_branch: "main",
|
||||
checkout_branch: "feature/existing",
|
||||
branch_policy_id: "policy-1",
|
||||
branch_policy_name: "Feature branches",
|
||||
branch_policy_base_branch: "main",
|
||||
branch_policy_branch_template: "feature/{title}-{suffix}",
|
||||
branch_policy_pull_request_target: "main",
|
||||
position: 0,
|
||||
created_at: "2026-08-24T10:00:00Z",
|
||||
updated_at: "2026-08-24T10:00:00Z",
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.current.repositories).toEqual([
|
||||
expect.objectContaining({
|
||||
repositoryId: "repo-1",
|
||||
branch: "main",
|
||||
branchPolicyId: "policy-1",
|
||||
}),
|
||||
]);
|
||||
expect(result.current.repositoriesDirty).toBe(false);
|
||||
|
||||
act(() => {
|
||||
result.current.updateRepository(result.current.repositories[0]!.key, { branch: "develop" });
|
||||
});
|
||||
|
||||
expect(result.current.repositoriesDirty).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("useDialogFormState — provider-neutral initial values", () => {
|
||||
it("seeds an authorized provider descriptor before asynchronous URL inspection", () => {
|
||||
const initialValues = {
|
||||
|
||||
@@ -6,6 +6,7 @@ import type {
|
||||
TaskFormInputsHandle,
|
||||
TaskRemoteRepoRow,
|
||||
} from "@/components/task-create-dialog-types";
|
||||
import { resetTaskForm, type FormResetters } from "@/components/task-create-dialog-form-reset";
|
||||
import { useBranchesByURL } from "@/hooks/domains/github/use-branches-by-url";
|
||||
import { usePRInfoByURL } from "@/hooks/domains/github/use-pr-info-by-url";
|
||||
import { useAppStore } from "@/components/state-provider";
|
||||
@@ -17,7 +18,6 @@ import type {
|
||||
StepType,
|
||||
TaskCreateDialogInitialValues,
|
||||
DialogFormState,
|
||||
TaskRepoRow,
|
||||
} from "@/components/task-create-dialog-types";
|
||||
import {
|
||||
useRemoteReposSeedEffect,
|
||||
@@ -37,30 +37,6 @@ export type {
|
||||
export { autoSelectBranch } from "@/components/task-create-dialog-helpers";
|
||||
export { useLockedFieldSync } from "@/components/task-create-dialog-locked-fields";
|
||||
|
||||
type FormResetters = {
|
||||
setTaskName: (v: string) => void;
|
||||
setHasTitle: (v: boolean) => void;
|
||||
setHasDescription: (v: boolean) => void;
|
||||
setHasPendingAttachmentUploads: (v: boolean) => void;
|
||||
setRepositories: (v: TaskRepoRow[]) => void;
|
||||
setRemoteRepos: (v: TaskRemoteRepoRow[]) => void;
|
||||
setAgentProfileId: (v: string) => void;
|
||||
setExecutorId: (v: string) => void;
|
||||
setExecutorProfileId: (v: string) => void;
|
||||
setSelectedWorkflowId: (v: string | null) => void;
|
||||
setFetchedSteps: (v: StepType[] | null) => void;
|
||||
setDiscoveredRepositories: (v: LocalRepository[]) => void;
|
||||
setDiscoverReposLoaded: (v: boolean) => void;
|
||||
setUseRemote: (v: boolean) => void;
|
||||
setNoRepository: (v: boolean) => void;
|
||||
setWorkspacePath: (v: string) => void;
|
||||
setAutopilot: (v: boolean) => void;
|
||||
setGitHubUrlError: (v: string | null) => void;
|
||||
setFreshBranchEnabled: (v: boolean) => void;
|
||||
setCurrentLocalBranch: (v: string) => void;
|
||||
setBlockedBy: (v: string[]) => void;
|
||||
};
|
||||
|
||||
type FormResetEffectsArgs = {
|
||||
open: boolean;
|
||||
workspaceId: string | null;
|
||||
@@ -86,15 +62,12 @@ function useFormResetEffects({
|
||||
prevOpenRef,
|
||||
lockedWorkflow,
|
||||
}: FormResetEffectsArgs) {
|
||||
// Restore draft or initialValues when dialog opens
|
||||
useEffect(() => {
|
||||
// Only run on rising edge (dialog opening)
|
||||
const wasOpen = prevOpenRef.current;
|
||||
(prevOpenRef as React.MutableRefObject<boolean>).current = open;
|
||||
|
||||
if (!open || wasOpen) return;
|
||||
|
||||
// Increment cycle to force TaskFormInputs remount
|
||||
setOpenCycle((c) => c + 1);
|
||||
|
||||
const defaults = resolveFormDefaults(initialValues, workspaceId);
|
||||
@@ -143,7 +116,6 @@ function resolveFormDefaults(
|
||||
initialValues: TaskCreateDialogInitialValues | undefined,
|
||||
workspaceId: string | null,
|
||||
) {
|
||||
// In edit mode (has content), use initialValues; in create mode, try draft
|
||||
const draft =
|
||||
!hasUserContent(initialValues) && workspaceId ? getTaskCreateDraft(workspaceId) : null;
|
||||
const initTitle = initialValues?.title ?? "";
|
||||
@@ -170,40 +142,6 @@ function resolveDefaultsSource(
|
||||
return "empty";
|
||||
}
|
||||
|
||||
/** Resets task form fields to specified values */
|
||||
function resetTaskForm(
|
||||
resetters: FormResetters,
|
||||
name: string,
|
||||
description: string,
|
||||
workflowId: string | null,
|
||||
initialValues?: TaskCreateDialogInitialValues,
|
||||
) {
|
||||
resetters.setTaskName(name);
|
||||
resetters.setHasTitle(name.trim().length > 0);
|
||||
resetters.setHasDescription(description.trim().length > 0);
|
||||
resetters.setHasPendingAttachmentUploads(false);
|
||||
// Seed the unified repos list from initialValues. A repo + branch pre-fill
|
||||
// becomes a single row; nothing seeds an empty list (the auto-select
|
||||
// effect later picks the user's last-used repo or the first workspace one).
|
||||
if (initialValues?.repositoryId) {
|
||||
resetters.setRepositories([
|
||||
{
|
||||
key: "row-0",
|
||||
repositoryId: initialValues.repositoryId,
|
||||
branch: initialValues.branch ?? "",
|
||||
},
|
||||
]);
|
||||
} else {
|
||||
resetters.setRepositories([]);
|
||||
}
|
||||
resetters.setAgentProfileId("");
|
||||
resetters.setExecutorId("");
|
||||
resetters.setExecutorProfileId("");
|
||||
resetters.setSelectedWorkflowId(workflowId);
|
||||
resetters.setFetchedSteps(null);
|
||||
resetters.setAutopilot(false);
|
||||
}
|
||||
|
||||
function firstDefined<T>(...values: Array<T | undefined>): T | undefined {
|
||||
return values.find((value) => value !== undefined);
|
||||
}
|
||||
@@ -225,11 +163,7 @@ function seededRemoteRepositories(iv?: TaskCreateDialogInitialValues): TaskRemot
|
||||
inspection ?? {};
|
||||
const remoteUrl = definedOr("", initial.remoteUrl, initial.githubUrl, repository.cloneUrl);
|
||||
if (!remoteUrl) return [];
|
||||
// Seed remoteRepos with a single paste row when the dialog opens with a
|
||||
// pre-filled URL (Quick-task launcher path). When `checkoutBranch` is set
|
||||
// (PR launch flow), seed the row's branch with it so the chip pill shows
|
||||
// the PR head immediately. Otherwise start empty — the seed effect creates
|
||||
// an empty row on mode toggle.
|
||||
// Seed a pre-filled URL and preserve its PR head when one is provided.
|
||||
const seededBranch = definedOr(
|
||||
"",
|
||||
initial.checkoutBranch,
|
||||
@@ -258,7 +192,6 @@ function seededRemoteRepositories(iv?: TaskCreateDialogInitialValues): TaskRemot
|
||||
];
|
||||
}
|
||||
|
||||
/** Resets repository discovery state. */
|
||||
function resetDiscoveryState(resetters: FormResetters, iv?: TaskCreateDialogInitialValues) {
|
||||
const remoteRepositories = seededRemoteRepositories(iv);
|
||||
resetters.setDiscoveredRepositories([]);
|
||||
@@ -487,6 +420,7 @@ export function useDialogFormState(
|
||||
setHasDescription: form.setHasDescription,
|
||||
setHasPendingAttachmentUploads: form.setHasPendingAttachmentUploads,
|
||||
setRepositories: repos.setRepositories,
|
||||
setRepositoriesDirty: repos.setRepositoriesDirty,
|
||||
setRemoteRepos: remoteRepos.setRemoteRepos,
|
||||
setAgentProfileId: form.setAgentProfileId,
|
||||
setExecutorId: form.setExecutorId,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { renderHook, act } from "@testing-library/react";
|
||||
import { createRef } from "react";
|
||||
import { ApiError } from "@/lib/api/client";
|
||||
|
||||
// All external module mocks must be declared with vi.mock before the import of
|
||||
// the unit under test so vitest hoists them. The mocks below capture the
|
||||
@@ -12,6 +13,10 @@ const pushMock = vi.fn();
|
||||
const TASK_ID = "task-1";
|
||||
const RENAMED_TITLE = "Renamed task";
|
||||
const ORIGINAL_PROMPT = "Original prompt";
|
||||
const UPDATED_PROMPT = "Updated prompt";
|
||||
const ORIGINAL_TITLE = "Original title";
|
||||
const MAIN_BRANCH = "main";
|
||||
const TODO_STATE = "TODO" as const;
|
||||
vi.mock("@/lib/routing/client-router", () => ({
|
||||
useRouter: () => ({ push: pushMock, replace: vi.fn(), back: vi.fn() }),
|
||||
}));
|
||||
@@ -72,7 +77,7 @@ vi.mock("@/components/task-create-dialog-helpers", () => ({
|
||||
Boolean(
|
||||
isEditMode &&
|
||||
editingTask?.state &&
|
||||
editingTask.state !== "TODO" &&
|
||||
editingTask.state !== TODO_STATE &&
|
||||
editingTask.state !== "CREATED",
|
||||
),
|
||||
findDuplicateRemoteRepo: () => null,
|
||||
@@ -131,6 +136,7 @@ function makeDeps(overrides: Partial<SubmitHandlersDeps>): SubmitHandlersDeps {
|
||||
workflowId: "wf-1",
|
||||
effectiveWorkflowId: "wf-1",
|
||||
repositories: [],
|
||||
repositoriesDirty: false,
|
||||
discoveredRepositories: [],
|
||||
workspaceRepositories: [],
|
||||
useRemote: false,
|
||||
@@ -149,6 +155,7 @@ function makeDeps(overrides: Partial<SubmitHandlersDeps>): SubmitHandlersDeps {
|
||||
editingTask: null,
|
||||
onSuccess: vi.fn(),
|
||||
onOpenChange: vi.fn(),
|
||||
refreshBranchPolicies: vi.fn(async () => undefined),
|
||||
taskId: null,
|
||||
descriptionInputRef: makeRef(""),
|
||||
setIsCreatingSession: vi.fn(),
|
||||
@@ -186,6 +193,7 @@ beforeEach(() => {
|
||||
toastMock.mockClear();
|
||||
});
|
||||
|
||||
// eslint-disable-next-line max-lines-per-function -- grouped edit regressions share one fixture.
|
||||
describe("useTaskSubmitHandlers — started task edits", () => {
|
||||
it("preserves a legacy overlong title when it was not edited", async () => {
|
||||
const legacyTitle = "x".repeat(80);
|
||||
@@ -212,14 +220,14 @@ describe("useTaskSubmitHandlers — started task edits", () => {
|
||||
|
||||
it("updates only the title so a locked prompt cannot be cleared", async () => {
|
||||
buildRepositoriesPayloadMock.mockReturnValue([
|
||||
{ repository_id: "repo-1", base_branch: "main" },
|
||||
{ repository_id: "repo-1", base_branch: MAIN_BRANCH },
|
||||
]);
|
||||
const deps = makeDeps({
|
||||
isEditMode: true,
|
||||
taskName: RENAMED_TITLE,
|
||||
editingTask: {
|
||||
id: TASK_ID,
|
||||
title: "Original title",
|
||||
title: ORIGINAL_TITLE,
|
||||
description: ORIGINAL_PROMPT,
|
||||
workflowStepId: "step-1",
|
||||
state: "IN_PROGRESS",
|
||||
@@ -238,20 +246,21 @@ describe("useTaskSubmitHandlers — started task edits", () => {
|
||||
});
|
||||
|
||||
it("keeps repository updates for tasks that have not started", async () => {
|
||||
const repositories = [{ repository_id: "repo-1", base_branch: "main" }];
|
||||
const repositories = [{ repository_id: "repo-1", base_branch: MAIN_BRANCH }];
|
||||
buildRepositoriesPayloadMock.mockReturnValue(repositories);
|
||||
const deps = makeDeps({
|
||||
isEditMode: true,
|
||||
taskName: RENAMED_TITLE,
|
||||
editingTask: {
|
||||
id: TASK_ID,
|
||||
title: "Original title",
|
||||
title: ORIGINAL_TITLE,
|
||||
description: ORIGINAL_PROMPT,
|
||||
workflowStepId: "step-1",
|
||||
state: "TODO",
|
||||
state: TODO_STATE,
|
||||
},
|
||||
descriptionInputRef: makeRef("Updated prompt"),
|
||||
descriptionInputRef: makeRef(UPDATED_PROMPT),
|
||||
noRepository: false,
|
||||
repositoriesDirty: true,
|
||||
});
|
||||
const { result } = renderHook(() => useTaskSubmitHandlers(deps));
|
||||
|
||||
@@ -261,11 +270,76 @@ describe("useTaskSubmitHandlers — started task edits", () => {
|
||||
|
||||
expect(updateTaskMock).toHaveBeenCalledWith(TASK_ID, {
|
||||
title: RENAMED_TITLE,
|
||||
description: "Updated prompt",
|
||||
description: UPDATED_PROMPT,
|
||||
repositories,
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves a policy snapshot during an ordinary unstarted-task edit", async () => {
|
||||
const deps = makeDeps({
|
||||
isEditMode: true,
|
||||
taskName: RENAMED_TITLE,
|
||||
editingTask: {
|
||||
id: TASK_ID,
|
||||
title: ORIGINAL_TITLE,
|
||||
description: ORIGINAL_PROMPT,
|
||||
workflowStepId: "step-1",
|
||||
state: TODO_STATE,
|
||||
},
|
||||
repositories: [
|
||||
{
|
||||
key: "row-0",
|
||||
repositoryId: "repo-1",
|
||||
branch: MAIN_BRANCH,
|
||||
branchPolicyId: "policy-1",
|
||||
},
|
||||
],
|
||||
descriptionInputRef: makeRef(UPDATED_PROMPT),
|
||||
noRepository: false,
|
||||
repositoriesDirty: false,
|
||||
});
|
||||
const { result } = renderHook(() => useTaskSubmitHandlers(deps));
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleUpdateWithoutAgent();
|
||||
});
|
||||
|
||||
expect(updateTaskMock).toHaveBeenCalledWith(TASK_ID, {
|
||||
title: RENAMED_TITLE,
|
||||
description: UPDATED_PROMPT,
|
||||
});
|
||||
expect(buildRepositoriesPayloadMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("sends an explicit empty repository list when a policy-backed row is removed", async () => {
|
||||
const deps = makeDeps({
|
||||
isEditMode: true,
|
||||
taskName: ORIGINAL_TITLE,
|
||||
editingTask: {
|
||||
id: TASK_ID,
|
||||
title: ORIGINAL_TITLE,
|
||||
description: ORIGINAL_PROMPT,
|
||||
workflowStepId: "step-1",
|
||||
state: TODO_STATE,
|
||||
},
|
||||
repositories: [],
|
||||
descriptionInputRef: makeRef(ORIGINAL_PROMPT),
|
||||
noRepository: false,
|
||||
repositoriesDirty: true,
|
||||
});
|
||||
const { result } = renderHook(() => useTaskSubmitHandlers(deps));
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleUpdateWithoutAgent();
|
||||
});
|
||||
|
||||
expect(updateTaskMock).toHaveBeenCalledWith(TASK_ID, {
|
||||
description: ORIGINAL_PROMPT,
|
||||
repositories: [],
|
||||
});
|
||||
expect(buildRepositoriesPayloadMock).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses the update-only path when the started edit form is submitted", async () => {
|
||||
const onSuccess = vi.fn();
|
||||
const deps = makeDeps({
|
||||
@@ -273,7 +347,7 @@ describe("useTaskSubmitHandlers — started task edits", () => {
|
||||
taskName: RENAMED_TITLE,
|
||||
editingTask: {
|
||||
id: TASK_ID,
|
||||
title: "Original title",
|
||||
title: ORIGINAL_TITLE,
|
||||
description: ORIGINAL_PROMPT,
|
||||
workflowStepId: "step-1",
|
||||
state: "IN_PROGRESS",
|
||||
@@ -293,7 +367,33 @@ describe("useTaskSubmitHandlers — started task edits", () => {
|
||||
});
|
||||
});
|
||||
|
||||
// eslint-disable-next-line max-lines-per-function -- create-mode parity cases share transport setup.
|
||||
describe("useTaskSubmitHandlers — handleCreateSubmit (CLI-mode parity)", () => {
|
||||
it("refreshes stale policy options and keeps the dialog open", async () => {
|
||||
const refreshBranchPolicies = vi.fn(async () => undefined);
|
||||
const onOpenChange = vi.fn();
|
||||
const createTask = vi.fn().mockRejectedValue(
|
||||
new ApiError("invalid repository branch policy", 400, {
|
||||
error: "invalid repository branch policy",
|
||||
error_code: "branch_policy_stale",
|
||||
}),
|
||||
);
|
||||
const deps = makeDeps({
|
||||
createTask,
|
||||
refreshBranchPolicies,
|
||||
onOpenChange,
|
||||
descriptionInputRef: makeRef("create with a policy"),
|
||||
});
|
||||
const { result } = renderHook(() => useTaskSubmitHandlers(deps));
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleSubmit({ preventDefault: () => {} } as never);
|
||||
});
|
||||
|
||||
expect(refreshBranchPolicies).toHaveBeenCalledTimes(1);
|
||||
expect(onOpenChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses the create-mode transport override", async () => {
|
||||
const createTask = vi.fn().mockResolvedValue({ id: TASK_ID, session_id: "session-plugin" });
|
||||
const deps = makeDeps({
|
||||
|
||||
@@ -14,6 +14,7 @@ import type { SubmitHandlersDeps } from "@/components/task-create-dialog-types";
|
||||
import { t } from "@/lib/i18n";
|
||||
import { useFreshBranchConsent } from "@/components/task-create-dialog-fresh-branch-consent";
|
||||
import { queueTaskCreateLastUsedFromPayload } from "@/components/task-create-dialog-handlers";
|
||||
import { ApiError } from "@/lib/api/client";
|
||||
|
||||
const GENERIC_ERROR_KEY = "common:anErrorOccurred";
|
||||
|
||||
@@ -60,6 +61,12 @@ function resolveWorkspacePath(noRepository: boolean, workspacePath: string): str
|
||||
return workspacePath.trim() || undefined;
|
||||
}
|
||||
|
||||
function isStaleBranchPolicyError(error: unknown): boolean {
|
||||
return (
|
||||
error instanceof ApiError && error.status === 400 && error.errorCode === "branch_policy_stale"
|
||||
);
|
||||
}
|
||||
|
||||
// eslint-disable-next-line max-lines-per-function
|
||||
export function useTaskSubmitHandlers({
|
||||
isSessionMode,
|
||||
@@ -72,6 +79,7 @@ export function useTaskSubmitHandlers({
|
||||
workflowId,
|
||||
effectiveWorkflowId,
|
||||
repositories,
|
||||
repositoriesDirty,
|
||||
discoveredRepositories,
|
||||
workspaceRepositories,
|
||||
useRemote,
|
||||
@@ -85,6 +93,7 @@ export function useTaskSubmitHandlers({
|
||||
onCreateSession,
|
||||
onOpenChange,
|
||||
createTask,
|
||||
refreshBranchPolicies,
|
||||
preserveTaskCreateLastUsedOnClose,
|
||||
taskId,
|
||||
parentTaskId,
|
||||
@@ -126,6 +135,15 @@ export function useTaskSubmitHandlers({
|
||||
createTask,
|
||||
});
|
||||
|
||||
const refreshStaleBranchPolicies = useCallback(
|
||||
async (error: unknown) => {
|
||||
if (!isStaleBranchPolicyError(error)) return false;
|
||||
if (refreshBranchPolicies) await refreshBranchPolicies().catch(() => undefined);
|
||||
return true;
|
||||
},
|
||||
[refreshBranchPolicies],
|
||||
);
|
||||
|
||||
const buildFreshBranchPayload = (consentedDirtyFiles: string[]) =>
|
||||
isFreshBranchActive ? { confirmDiscard: true, consentedDirtyFiles } : undefined;
|
||||
|
||||
@@ -312,22 +330,30 @@ export function useTaskSubmitHandlers({
|
||||
? (editingTask.description ?? "")
|
||||
: (descriptionInputRef.current?.getValue() ?? "");
|
||||
const trimmedDescription = description.trim();
|
||||
const repositoriesPayload = isStartedEdit ? [] : getRepositoriesPayload();
|
||||
const repositoriesPayload = !isStartedEdit && repositoriesDirty ? getRepositoriesPayload() : [];
|
||||
const titleChanged = trimmedTitle !== editingTask.title;
|
||||
|
||||
const updatePayload: Parameters<typeof updateTask>[1] = {
|
||||
...(titleChanged && { title: trimmedTitle }),
|
||||
...(!isStartedEdit && { description: trimmedDescription }),
|
||||
...(repositoriesPayload.length > 0 && { repositories: repositoriesPayload }),
|
||||
...(!isStartedEdit && repositoriesDirty && { repositories: repositoriesPayload }),
|
||||
};
|
||||
|
||||
const updatedTask = await updateTask(editingTask.id, updatePayload);
|
||||
return { updatedTask, trimmedDescription };
|
||||
}, [editingTask, taskName, descriptionInputRef, getRepositoriesPayload, isStartedEdit]);
|
||||
}, [
|
||||
editingTask,
|
||||
taskName,
|
||||
descriptionInputRef,
|
||||
getRepositoriesPayload,
|
||||
isStartedEdit,
|
||||
repositoriesDirty,
|
||||
]);
|
||||
|
||||
const handleEditSubmit = useCallback(async () => {
|
||||
if (checkRemoteResolution()) return;
|
||||
setIsCreatingTask(true);
|
||||
let closeDialog = true;
|
||||
try {
|
||||
const result = await performTaskUpdate();
|
||||
if (!result) return;
|
||||
@@ -350,13 +376,14 @@ export function useTaskSubmitHandlers({
|
||||
|
||||
onSuccess?.(updatedTask, "edit", { taskSessionId });
|
||||
} catch (error) {
|
||||
closeDialog = !(await refreshStaleBranchPolicies(error));
|
||||
toast({
|
||||
title: t("task:failedToUpdateTask"),
|
||||
description: error instanceof Error ? error.message : t(GENERIC_ERROR_KEY),
|
||||
variant: "error",
|
||||
});
|
||||
} finally {
|
||||
onOpenChange(false);
|
||||
if (closeDialog) onOpenChange(false);
|
||||
setIsCreatingTask(false);
|
||||
}
|
||||
}, [
|
||||
@@ -367,6 +394,7 @@ export function useTaskSubmitHandlers({
|
||||
executorProfileId,
|
||||
onSuccess,
|
||||
onOpenChange,
|
||||
refreshStaleBranchPolicies,
|
||||
toast,
|
||||
setIsCreatingTask,
|
||||
]);
|
||||
@@ -374,21 +402,31 @@ export function useTaskSubmitHandlers({
|
||||
const handleUpdateWithoutAgent = useCallback(async () => {
|
||||
if (checkRemoteResolution()) return;
|
||||
setIsCreatingTask(true);
|
||||
let closeDialog = true;
|
||||
try {
|
||||
const result = await performTaskUpdate();
|
||||
if (!result) return;
|
||||
onSuccess?.(result.updatedTask, "edit");
|
||||
} catch (error) {
|
||||
closeDialog = !(await refreshStaleBranchPolicies(error));
|
||||
toast({
|
||||
title: t("task:failedToUpdateTask"),
|
||||
description: error instanceof Error ? error.message : t(GENERIC_ERROR_KEY),
|
||||
variant: "error",
|
||||
});
|
||||
} finally {
|
||||
onOpenChange(false);
|
||||
if (closeDialog) onOpenChange(false);
|
||||
setIsCreatingTask(false);
|
||||
}
|
||||
}, [checkRemoteResolution, performTaskUpdate, onSuccess, onOpenChange, toast, setIsCreatingTask]);
|
||||
}, [
|
||||
checkRemoteResolution,
|
||||
performTaskUpdate,
|
||||
onSuccess,
|
||||
onOpenChange,
|
||||
refreshStaleBranchPolicies,
|
||||
toast,
|
||||
setIsCreatingTask,
|
||||
]);
|
||||
|
||||
const performCreate = useCallback(
|
||||
async (opts: {
|
||||
@@ -533,6 +571,7 @@ export function useTaskSubmitHandlers({
|
||||
try {
|
||||
await performEditWithPlanMode();
|
||||
} catch (error) {
|
||||
await refreshStaleBranchPolicies(error);
|
||||
toast({
|
||||
title: t("task:failedToStartTaskPlanMode"),
|
||||
description: error instanceof Error ? error.message : t(GENERIC_ERROR_KEY),
|
||||
@@ -564,6 +603,7 @@ export function useTaskSubmitHandlers({
|
||||
attachments,
|
||||
});
|
||||
} catch (error) {
|
||||
await refreshStaleBranchPolicies(error);
|
||||
toast({
|
||||
title: t("task:failedToStartTaskPlanMode"),
|
||||
description: error instanceof Error ? error.message : t(GENERIC_ERROR_KEY),
|
||||
@@ -580,6 +620,7 @@ export function useTaskSubmitHandlers({
|
||||
hasRemoteSubmitBlocker,
|
||||
ensureFreshBranchConsent,
|
||||
performCreate,
|
||||
refreshStaleBranchPolicies,
|
||||
toast,
|
||||
descriptionInputRef,
|
||||
setIsCreatingTask,
|
||||
@@ -632,6 +673,7 @@ export function useTaskSubmitHandlers({
|
||||
try {
|
||||
await submitCreateTask({ trimmedTitle, trimmedDescription, consent, attachments });
|
||||
} catch (error) {
|
||||
await refreshStaleBranchPolicies(error);
|
||||
toast({
|
||||
title: t("task:failedToCreateTask"),
|
||||
description: error instanceof Error ? error.message : t(GENERIC_ERROR_KEY),
|
||||
@@ -646,6 +688,7 @@ export function useTaskSubmitHandlers({
|
||||
hasRemoteSubmitBlocker,
|
||||
ensureFreshBranchConsent,
|
||||
submitCreateTask,
|
||||
refreshStaleBranchPolicies,
|
||||
toast,
|
||||
descriptionInputRef,
|
||||
setIsCreatingTask,
|
||||
@@ -700,6 +743,7 @@ export function useTaskSubmitHandlers({
|
||||
preserveTaskCreateLastUsedOnClose?.();
|
||||
onOpenChange(false);
|
||||
} catch (error) {
|
||||
await refreshStaleBranchPolicies(error);
|
||||
toast({
|
||||
title: t("task:failedToCreateTask"),
|
||||
description: error instanceof Error ? error.message : t(GENERIC_ERROR_KEY),
|
||||
@@ -724,6 +768,7 @@ export function useTaskSubmitHandlers({
|
||||
getRepositoriesPayload,
|
||||
ensureFreshBranchConsent,
|
||||
createTaskWithFreshBranchRetry,
|
||||
refreshStaleBranchPolicies,
|
||||
onSuccess,
|
||||
onOpenChange,
|
||||
preserveTaskCreateLastUsedOnClose,
|
||||
|
||||
@@ -54,6 +54,7 @@ export interface TaskCreateDialogProps {
|
||||
workflowStepId: string;
|
||||
state?: Task["state"];
|
||||
repositoryId?: string;
|
||||
repositories?: TaskRepositorySnapshot[];
|
||||
} | null;
|
||||
onSuccess?: (
|
||||
task: Task,
|
||||
@@ -109,6 +110,26 @@ export type TaskRepoRow = {
|
||||
/** On-machine repo path, when the user picked from discovered repos. */
|
||||
localPath?: string;
|
||||
branch: string;
|
||||
/** Saved repository policy selected for this row. */
|
||||
branchPolicyId?: string;
|
||||
};
|
||||
|
||||
/** Repository fields needed to rehydrate an edit form without losing a policy snapshot. */
|
||||
export type TaskRepositorySnapshot = {
|
||||
repository_id: string;
|
||||
base_branch?: string;
|
||||
id?: string;
|
||||
task_id?: string;
|
||||
checkout_branch?: string;
|
||||
branch_policy_id?: string;
|
||||
branch_policy_name?: string;
|
||||
branch_policy_base_branch?: string;
|
||||
branch_policy_branch_template?: string;
|
||||
branch_policy_pull_request_target?: string;
|
||||
position?: number;
|
||||
metadata?: Record<string, unknown>;
|
||||
created_at?: string;
|
||||
updated_at?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -152,6 +173,8 @@ export type StepType = {
|
||||
export type TaskCreateDialogInitialValues = {
|
||||
title: string;
|
||||
description?: string;
|
||||
/** Existing task repository rows, including immutable policy snapshots. */
|
||||
repositories?: TaskRepositorySnapshot[];
|
||||
repositoryId?: string;
|
||||
branch?: string;
|
||||
/** Existing remote branch to check out directly in the worktree (e.g. a PR's head branch),
|
||||
@@ -329,7 +352,10 @@ export type DialogFormState = {
|
||||
* order is the position the backend sees. There is no "primary" concept.
|
||||
*/
|
||||
repositories: TaskRepoRow[];
|
||||
/** False while rows are hydrated from an existing task; true after user edits. */
|
||||
repositoriesDirty: boolean;
|
||||
setRepositories: React.Dispatch<React.SetStateAction<TaskRepoRow[]>>;
|
||||
setRepositoriesDirty: (dirty: boolean) => void;
|
||||
addRepository: () => void;
|
||||
removeRepository: (key: string) => void;
|
||||
updateRepository: (key: string, patch: Partial<TaskRepoRow>) => void;
|
||||
@@ -419,6 +445,8 @@ export type SubmitHandlersDeps = {
|
||||
effectiveWorkflowId: string | null;
|
||||
/** Unified repo list from the form. Empty when in GitHub URL mode. */
|
||||
repositories: TaskRepoRow[];
|
||||
/** Whether the user explicitly changed repository selections in this form. */
|
||||
repositoriesDirty: boolean;
|
||||
/** All on-machine discovered repos — used to look up `default_branch` for `localPath` rows. */
|
||||
discoveredRepositories: LocalRepository[];
|
||||
/** Workspace repositories — used to look up `default_branch` for `repositoryId` rows. */
|
||||
@@ -443,6 +471,7 @@ export type SubmitHandlersDeps = {
|
||||
workflowStepId: string;
|
||||
state?: Task["state"];
|
||||
repositoryId?: string;
|
||||
repositories?: TaskRepositorySnapshot[];
|
||||
} | null;
|
||||
onSuccess?: (
|
||||
task: Task,
|
||||
@@ -460,6 +489,8 @@ export type SubmitHandlersDeps = {
|
||||
onOpenChange: (open: boolean) => void;
|
||||
/** Create-mode transport override. Omitted to use Kandev's REST task endpoint. */
|
||||
createTask?: TaskCreateSubmit;
|
||||
/** Refreshes selected branch-policy options after a stale task submission. */
|
||||
refreshBranchPolicies?: () => Promise<void>;
|
||||
preserveTaskCreateLastUsedOnClose?: () => void;
|
||||
taskId: string | null;
|
||||
parentTaskId?: string;
|
||||
@@ -534,6 +565,7 @@ export type DialogFormBodyProps = {
|
||||
onTaskNameChange: (v: string) => void;
|
||||
onRowRepositoryChange: (key: string, value: string) => void;
|
||||
onRowBranchChange: (key: string, value: string) => void;
|
||||
onRowPolicyChange?: (key: string, policyId: string, baseBranch: string) => void;
|
||||
onAgentProfileChange: (v: string) => void;
|
||||
onExecutorProfileChange: (v: string) => void;
|
||||
onWorkflowChange: (v: string) => void;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";
|
||||
import { TooltipProvider } from "@kandev/ui/tooltip";
|
||||
import { StateProvider } from "@/components/state-provider";
|
||||
import type { Repository } from "@/lib/types/http";
|
||||
import type { DialogFormState, TaskRepoRow } from "./task-create-dialog-types";
|
||||
import { WorkspaceRepoChips } from "./task-create-dialog-workspace-repo-chips";
|
||||
@@ -9,6 +10,24 @@ vi.mock("@/hooks/domains/workspace/use-repository-branches", () => ({
|
||||
useBranches: () => ({ branches: [], isLoading: false }),
|
||||
}));
|
||||
|
||||
vi.mock("@/hooks/domains/workspace/use-repository-branch-policies", () => ({
|
||||
useRepositoryBranchPolicies: () => ({
|
||||
policies: [
|
||||
{
|
||||
id: "policy-1",
|
||||
repository_id: "repo-front",
|
||||
name: "Feature branches",
|
||||
description: "Policy description",
|
||||
base_branch: "main",
|
||||
branch_template: "feature/{title}-{suffix}",
|
||||
pull_request_target: "develop",
|
||||
created_at: "2026-08-24T10:00:00Z",
|
||||
updated_at: "2026-08-24T10:00:00Z",
|
||||
},
|
||||
],
|
||||
}),
|
||||
}));
|
||||
|
||||
const FRONTEND_ID = "repo-front";
|
||||
const BACKEND_ID = "repo-back";
|
||||
const CHIP_TRIGGER = "repo-chip-trigger";
|
||||
@@ -58,7 +77,11 @@ function chips(overrides: Partial<ChipsProps> = {}) {
|
||||
}
|
||||
|
||||
function renderChips(overrides: Partial<ChipsProps> = {}) {
|
||||
return render(<TooltipProvider>{chips(overrides)}</TooltipProvider>);
|
||||
return render(
|
||||
<StateProvider>
|
||||
<TooltipProvider>{chips(overrides)}</TooltipProvider>
|
||||
</StateProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
afterEach(cleanup);
|
||||
@@ -115,6 +138,23 @@ describe("WorkspaceRepoChips duplicate policy", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("WorkspaceRepoChips branch policy preview", () => {
|
||||
it("keeps policy choices on one line and moves details behind an info control", () => {
|
||||
renderChips({
|
||||
rows: [row({ key: "r0", repositoryId: FRONTEND_ID, branch: "main" })],
|
||||
showBranchPolicies: true,
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByTestId("branch-chip-trigger"));
|
||||
|
||||
const option = screen.getByRole("option", { name: /Feature branches/ });
|
||||
expect(option.textContent).not.toContain("feature/{title}-{suffix}");
|
||||
expect(
|
||||
screen.getByTestId("branch-policy-option-info-policy-1").getAttribute("aria-label"),
|
||||
).toContain("feature/{title}-{suffix}");
|
||||
});
|
||||
});
|
||||
|
||||
describe("WorkspaceRepoChips workspace markers", () => {
|
||||
it("marks another task row's workspace repository while keeping it selectable", () => {
|
||||
const onRowRepositoryChange = vi.fn();
|
||||
@@ -155,9 +195,11 @@ describe("WorkspaceRepoChips workspace markers", () => {
|
||||
).toBeTruthy();
|
||||
|
||||
rerender(
|
||||
<TooltipProvider>
|
||||
{chips({ rows: [row({ key: "r0", repositoryId: BACKEND_ID }), row({ key: "r1" })] })}
|
||||
</TooltipProvider>,
|
||||
<StateProvider>
|
||||
<TooltipProvider>
|
||||
{chips({ rows: [row({ key: "r0", repositoryId: BACKEND_ID }), row({ key: "r1" })] })}
|
||||
</TooltipProvider>
|
||||
</StateProvider>,
|
||||
);
|
||||
expect(
|
||||
within(screen.getByRole("option", { name: /^frontend/ })).queryByTestId(ADDED_MARKER),
|
||||
@@ -166,7 +208,11 @@ describe("WorkspaceRepoChips workspace markers", () => {
|
||||
within(screen.getByRole("option", { name: /^backend/ })).getByTestId(ADDED_MARKER),
|
||||
).toBeTruthy();
|
||||
|
||||
rerender(<TooltipProvider>{chips({ rows: [row({ key: "r1" })] })}</TooltipProvider>);
|
||||
rerender(
|
||||
<StateProvider>
|
||||
<TooltipProvider>{chips({ rows: [row({ key: "r1" })] })}</TooltipProvider>
|
||||
</StateProvider>,
|
||||
);
|
||||
expect(
|
||||
within(screen.getByRole("option", { name: /^backend/ })).queryByTestId(ADDED_MARKER),
|
||||
).toBeNull();
|
||||
@@ -189,24 +235,28 @@ describe("WorkspaceRepoChips discovered markers", () => {
|
||||
).toBeTruthy();
|
||||
|
||||
rerender(
|
||||
<TooltipProvider>
|
||||
{chips({
|
||||
rows: [
|
||||
row({ key: "r0", localPath: "/home/me/projects/another-project" }),
|
||||
row({ key: "r1" }),
|
||||
],
|
||||
discoveredRepositories,
|
||||
})}
|
||||
</TooltipProvider>,
|
||||
<StateProvider>
|
||||
<TooltipProvider>
|
||||
{chips({
|
||||
rows: [
|
||||
row({ key: "r0", localPath: "/home/me/projects/another-project" }),
|
||||
row({ key: "r1" }),
|
||||
],
|
||||
discoveredRepositories,
|
||||
})}
|
||||
</TooltipProvider>
|
||||
</StateProvider>,
|
||||
);
|
||||
expect(
|
||||
within(screen.getByRole("option", { name: /^local-project/ })).queryByTestId(ADDED_MARKER),
|
||||
).toBeNull();
|
||||
|
||||
rerender(
|
||||
<TooltipProvider>
|
||||
{chips({ rows: [row({ key: "r1" })], discoveredRepositories })}
|
||||
</TooltipProvider>,
|
||||
<StateProvider>
|
||||
<TooltipProvider>
|
||||
{chips({ rows: [row({ key: "r1" })], discoveredRepositories })}
|
||||
</TooltipProvider>
|
||||
</StateProvider>,
|
||||
);
|
||||
expect(
|
||||
within(screen.getByRole("option", { name: /^local-project/ })).queryByTestId(ADDED_MARKER),
|
||||
|
||||
@@ -1,36 +1,26 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo } from "react";
|
||||
import {
|
||||
IconPlus,
|
||||
IconX,
|
||||
IconCode,
|
||||
IconGitBranch,
|
||||
IconFolderPlus,
|
||||
IconCheck,
|
||||
} from "@tabler/icons-react";
|
||||
import { IconPlus, IconX, IconCheck } from "@tabler/icons-react";
|
||||
import { Badge } from "@kandev/ui/badge";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
|
||||
import { useBranches, type BranchSource } from "@/hooks/domains/workspace/use-repository-branches";
|
||||
import type { LocalRepository, Repository } from "@/lib/types/http";
|
||||
import type { LocalRepository, Repository, RepositoryBranchPolicy } from "@/lib/types/http";
|
||||
import type { TaskRepoRow } from "@/components/task-create-dialog-types";
|
||||
import { cn, formatUserHomePath } from "@/lib/utils";
|
||||
import { scoreBranch } from "@/lib/utils/branch-filter";
|
||||
import { scoreRepo } from "@/lib/utils/repo-filter";
|
||||
import { Pill, type PillAction, type PillOption } from "@/components/task-create-dialog-pill";
|
||||
import {
|
||||
branchToOption,
|
||||
computeBranchPlaceholder,
|
||||
sortBranches,
|
||||
} from "@/components/task-create-dialog-branch-options";
|
||||
import { type PillOption } from "@/components/task-create-dialog-pill";
|
||||
import { branchToOption, sortBranches } from "@/components/task-create-dialog-branch-options";
|
||||
import {
|
||||
computeBranchIntent,
|
||||
computeBranchPrefix,
|
||||
computeBranchTooltip,
|
||||
computeBranchDisabledReason,
|
||||
type BranchIntent,
|
||||
} from "@/components/task-create-dialog-branch-utils";
|
||||
import { useRepoBranchAutoselect } from "@/components/task-create-dialog-repo-branch-autoselect";
|
||||
import { useRepositoryBranchPolicies } from "@/hooks/domains/workspace/use-repository-branch-policies";
|
||||
import {
|
||||
RepoChipBranchPill,
|
||||
RepoChipRepositoryPill,
|
||||
useRepoChipBranchPicker,
|
||||
} from "@/components/task-create-dialog-repo-chip-parts";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { t } from "@/lib/i18n";
|
||||
|
||||
@@ -44,6 +34,8 @@ type WorkspaceRepoChipsProps = {
|
||||
currentLocalBranch?: string;
|
||||
currentLocalBranchLoading?: boolean;
|
||||
freshBranchEnabled?: boolean;
|
||||
branchPolicyDisabledReason?: string;
|
||||
showBranchPolicies?: boolean;
|
||||
canAddMore: boolean;
|
||||
addHint?: string;
|
||||
addLabel?: string;
|
||||
@@ -53,6 +45,8 @@ type WorkspaceRepoChipsProps = {
|
||||
onRemove: (key: string) => void;
|
||||
onRowRepositoryChange: (key: string, value: string) => void;
|
||||
onRowBranchChange: (key: string, value: string) => void;
|
||||
onRowPolicyChange?: (key: string, policyId: string, baseBranch: string) => void;
|
||||
onPolicySelected?: () => void;
|
||||
onCreateRepository?: (key: string) => void;
|
||||
onRefreshRepositories?: () => void;
|
||||
repositoriesRefreshing?: boolean;
|
||||
@@ -75,6 +69,8 @@ export function WorkspaceRepoChips({
|
||||
currentLocalBranch,
|
||||
currentLocalBranchLoading,
|
||||
freshBranchEnabled,
|
||||
branchPolicyDisabledReason,
|
||||
showBranchPolicies = false,
|
||||
canAddMore,
|
||||
addHint,
|
||||
addLabel,
|
||||
@@ -84,6 +80,8 @@ export function WorkspaceRepoChips({
|
||||
onRemove,
|
||||
onRowRepositoryChange,
|
||||
onRowBranchChange,
|
||||
onRowPolicyChange,
|
||||
onPolicySelected,
|
||||
onCreateRepository,
|
||||
onRefreshRepositories,
|
||||
repositoriesRefreshing,
|
||||
@@ -119,8 +117,16 @@ export function WorkspaceRepoChips({
|
||||
currentLocalBranch: currentLocalBranch ?? "",
|
||||
freshBranchEnabled: !!freshBranchEnabled,
|
||||
})}
|
||||
branchPolicyDisabledReason={branchPolicyDisabledReason}
|
||||
onRepositoryChange={(value) => onRowRepositoryChange(row.key, value)}
|
||||
onBranchChange={(value) => onRowBranchChange(row.key, value)}
|
||||
onPolicyChange={
|
||||
onRowPolicyChange
|
||||
? (policyId, baseBranch) => onRowPolicyChange(row.key, policyId, baseBranch)
|
||||
: undefined
|
||||
}
|
||||
onPolicySelected={onPolicySelected}
|
||||
showBranchPolicies={showBranchPolicies}
|
||||
onCreateRepository={
|
||||
rows.length === 1 && onCreateRepository ? () => onCreateRepository(row.key) : undefined
|
||||
}
|
||||
@@ -253,12 +259,63 @@ type RepoChipProps = {
|
||||
branchIntent?: BranchIntent;
|
||||
onRepositoryChange: (value: string) => void;
|
||||
onBranchChange: (value: string) => void;
|
||||
onPolicyChange?: (policyId: string, baseBranch: string) => void;
|
||||
onPolicySelected?: () => void;
|
||||
branchPolicyDisabledReason?: string;
|
||||
showBranchPolicies?: boolean;
|
||||
onRemove: () => void;
|
||||
onCreateRepository?: () => void;
|
||||
onRefreshRepositories?: () => void;
|
||||
repositoriesRefreshing?: boolean;
|
||||
};
|
||||
|
||||
function useRepoChipBranchData({
|
||||
row,
|
||||
workspaceId,
|
||||
onBranchChange,
|
||||
preferredDefaultBranch,
|
||||
preferredDefaultBranchLoading,
|
||||
lastUsedBranch,
|
||||
userSettingsLoaded,
|
||||
}: Pick<
|
||||
RepoChipProps,
|
||||
| "row"
|
||||
| "workspaceId"
|
||||
| "onBranchChange"
|
||||
| "preferredDefaultBranch"
|
||||
| "preferredDefaultBranchLoading"
|
||||
| "lastUsedBranch"
|
||||
| "userSettingsLoaded"
|
||||
>) {
|
||||
const branchSource = useMemo<BranchSource | null>(() => {
|
||||
if (!workspaceId) return null;
|
||||
if (row.repositoryId) {
|
||||
return { kind: "id", workspaceId, repositoryId: row.repositoryId };
|
||||
}
|
||||
if (row.localPath) {
|
||||
return { kind: "path", workspaceId, path: row.localPath };
|
||||
}
|
||||
return null;
|
||||
}, [workspaceId, row.repositoryId, row.localPath]);
|
||||
const {
|
||||
branches,
|
||||
isLoading: branchesLoading,
|
||||
refresh: refreshBranches,
|
||||
} = useBranches(branchSource, !!branchSource);
|
||||
useRepoBranchAutoselect({
|
||||
branchSource,
|
||||
branchesLoading,
|
||||
branches,
|
||||
rowBranch: row.branch,
|
||||
onBranchChange,
|
||||
preferredDefaultBranch,
|
||||
preferredDefaultBranchLoading,
|
||||
lastUsedBranch,
|
||||
userSettingsLoaded,
|
||||
});
|
||||
return { branches, branchesLoading, refreshBranches };
|
||||
}
|
||||
|
||||
function useRepoChipData({
|
||||
row,
|
||||
workspaceId,
|
||||
@@ -302,27 +359,9 @@ function useRepoChipData({
|
||||
(!excludedRepoIds.has(r.path) || r.path === row.localPath),
|
||||
);
|
||||
}, [filteredRepos, discoveredRepositories, excludedRepoIds, row.localPath]);
|
||||
|
||||
const branchSource = useMemo<BranchSource | null>(() => {
|
||||
if (!workspaceId) return null;
|
||||
if (row.repositoryId) {
|
||||
return { kind: "id", workspaceId, repositoryId: row.repositoryId };
|
||||
}
|
||||
if (row.localPath) {
|
||||
return { kind: "path", workspaceId, path: row.localPath };
|
||||
}
|
||||
return null;
|
||||
}, [workspaceId, row.repositoryId, row.localPath]);
|
||||
const {
|
||||
branches,
|
||||
isLoading: branchesLoading,
|
||||
refresh: refreshBranches,
|
||||
} = useBranches(branchSource, !!branchSource);
|
||||
useRepoBranchAutoselect({
|
||||
branchSource,
|
||||
branchesLoading,
|
||||
branches,
|
||||
rowBranch: row.branch,
|
||||
const { branches, branchesLoading, refreshBranches } = useRepoChipBranchData({
|
||||
row,
|
||||
workspaceId,
|
||||
onBranchChange,
|
||||
preferredDefaultBranch,
|
||||
preferredDefaultBranchLoading,
|
||||
@@ -359,7 +398,7 @@ function useRepoChipData({
|
||||
() => sortBranches(branches).map(branchToOption),
|
||||
[branches],
|
||||
);
|
||||
return { repoOptions, branchOptions, branchesLoading, refreshBranches };
|
||||
return { repoOptions, branchOptions, branches, branchesLoading, refreshBranches };
|
||||
}
|
||||
|
||||
function computeRepoChipDisplay(
|
||||
@@ -377,37 +416,24 @@ function computeRepoChipDisplay(
|
||||
return { repoLabel, repoTooltip };
|
||||
}
|
||||
|
||||
function buildCreateRepositoryAction(onSelect?: () => void): PillAction | undefined {
|
||||
if (!onSelect) return undefined;
|
||||
return {
|
||||
label: t("task:createNewRepository"),
|
||||
icon: <IconFolderPlus className="h-3.5 w-3.5" />,
|
||||
onSelect,
|
||||
};
|
||||
}
|
||||
type RepoChipData = ReturnType<typeof useRepoChipData>;
|
||||
|
||||
function RepoChip({
|
||||
row,
|
||||
workspaceId,
|
||||
repositories,
|
||||
discoveredRepositories,
|
||||
excludedRepoIds,
|
||||
selectedElsewhere,
|
||||
branchLocked,
|
||||
preferredDefaultBranch,
|
||||
preferredDefaultBranchLoading,
|
||||
lastUsedBranch,
|
||||
userSettingsLoaded,
|
||||
branchIntent,
|
||||
onRepositoryChange,
|
||||
onBranchChange,
|
||||
onRemove,
|
||||
onCreateRepository,
|
||||
onRefreshRepositories,
|
||||
repositoriesRefreshing,
|
||||
}: RepoChipProps) {
|
||||
const { t } = useTranslation();
|
||||
const { repoOptions, branchOptions, branchesLoading, refreshBranches } = useRepoChipData({
|
||||
function RepoChip(props: RepoChipProps) {
|
||||
const {
|
||||
row,
|
||||
workspaceId,
|
||||
repositories,
|
||||
discoveredRepositories,
|
||||
excludedRepoIds,
|
||||
selectedElsewhere,
|
||||
onBranchChange,
|
||||
showBranchPolicies,
|
||||
preferredDefaultBranch,
|
||||
preferredDefaultBranchLoading,
|
||||
lastUsedBranch,
|
||||
userSettingsLoaded,
|
||||
} = props;
|
||||
const data = useRepoChipData({
|
||||
row,
|
||||
workspaceId,
|
||||
repositories,
|
||||
@@ -420,18 +446,58 @@ function RepoChip({
|
||||
lastUsedBranch,
|
||||
userSettingsLoaded,
|
||||
});
|
||||
if (showBranchPolicies) {
|
||||
return <RepoChipWithPolicies {...props} data={data} />;
|
||||
}
|
||||
return <RepoChipContent {...props} data={data} branchPolicies={[]} />;
|
||||
}
|
||||
|
||||
function RepoChipWithPolicies({ data, ...props }: RepoChipProps & { data: RepoChipData }) {
|
||||
const { row } = props;
|
||||
const { policies: branchPolicies } = useRepositoryBranchPolicies(
|
||||
row.repositoryId ?? null,
|
||||
!!row.repositoryId,
|
||||
);
|
||||
return <RepoChipContent {...props} data={data} branchPolicies={branchPolicies} />;
|
||||
}
|
||||
|
||||
function RepoChipContent({
|
||||
data,
|
||||
branchPolicies,
|
||||
row,
|
||||
repositories,
|
||||
discoveredRepositories,
|
||||
branchLocked,
|
||||
preferredDefaultBranchLoading,
|
||||
branchIntent,
|
||||
onRepositoryChange,
|
||||
onBranchChange,
|
||||
onPolicyChange,
|
||||
onPolicySelected,
|
||||
branchPolicyDisabledReason,
|
||||
onRemove,
|
||||
onCreateRepository,
|
||||
onRefreshRepositories,
|
||||
repositoriesRefreshing,
|
||||
}: RepoChipProps & { data: RepoChipData; branchPolicies: RepositoryBranchPolicy[] }) {
|
||||
const { repoOptions, branchOptions, branches, branchesLoading, refreshBranches } = data;
|
||||
const { repoLabel, repoTooltip } = computeRepoChipDisplay(
|
||||
row,
|
||||
repositories,
|
||||
discoveredRepositories,
|
||||
);
|
||||
const hasRepo = !!(row.repositoryId || row.localPath);
|
||||
const branchValue = preferredDefaultBranchLoading ? "" : row.branch;
|
||||
const branchPlaceholder = computeBranchPlaceholder(
|
||||
hasRepo,
|
||||
branchesLoading || !!preferredDefaultBranchLoading,
|
||||
branchOptions.length,
|
||||
);
|
||||
const branchPicker = useRepoChipBranchPicker({
|
||||
row,
|
||||
branchPolicies,
|
||||
branches,
|
||||
branchOptions,
|
||||
branchesLoading,
|
||||
preferredDefaultBranchLoading,
|
||||
policyDisabledReason: branchPolicyDisabledReason,
|
||||
onBranchChange,
|
||||
onPolicyChange,
|
||||
onPolicySelected,
|
||||
});
|
||||
return (
|
||||
<span
|
||||
className="inline-flex items-center rounded-md border border-input bg-input/20 dark:bg-input/30 pr-0.5"
|
||||
@@ -439,46 +505,22 @@ function RepoChip({
|
||||
data-repository-id={row.repositoryId || row.localPath || ""}
|
||||
data-repo-row-key={row.key}
|
||||
>
|
||||
<Pill
|
||||
icon={<IconCode className="h-3 w-3 shrink-0 text-muted-foreground" />}
|
||||
value={repoLabel}
|
||||
selectedValue={row.repositoryId || row.localPath || ""}
|
||||
placeholder={t("task:repository")}
|
||||
options={repoOptions}
|
||||
onSelect={onRepositoryChange}
|
||||
searchPlaceholder={t("task:searchRepositories")}
|
||||
emptyMessage={t("task:noRepositories")}
|
||||
testId="repo-chip-trigger"
|
||||
tooltip={repoTooltip}
|
||||
filter={scoreRepo}
|
||||
action={buildCreateRepositoryAction(onCreateRepository)}
|
||||
onRefresh={onRefreshRepositories}
|
||||
refreshing={repositoriesRefreshing}
|
||||
refreshLabel="repositories"
|
||||
flat
|
||||
<RepoChipRepositoryPill
|
||||
repoLabel={repoLabel}
|
||||
repoTooltip={repoTooltip}
|
||||
repositoryValue={row.repositoryId || row.localPath || ""}
|
||||
repoOptions={repoOptions}
|
||||
onRepositoryChange={onRepositoryChange}
|
||||
onCreateRepository={onCreateRepository}
|
||||
onRefreshRepositories={onRefreshRepositories}
|
||||
repositoriesRefreshing={repositoriesRefreshing}
|
||||
/>
|
||||
<Pill
|
||||
icon={<IconGitBranch className="h-3 w-3 shrink-0 text-muted-foreground" />}
|
||||
value={branchValue}
|
||||
placeholder={branchPlaceholder}
|
||||
prefix={computeBranchPrefix(branchIntent ?? "none")}
|
||||
options={branchOptions}
|
||||
onSelect={onBranchChange}
|
||||
disabled={branchLocked || !hasRepo || branchesLoading || branchOptions.length === 0}
|
||||
disabledReason={computeBranchDisabledReason({
|
||||
branchLocked: !!branchLocked,
|
||||
hasRepo,
|
||||
branchesLoading,
|
||||
optionCount: branchOptions.length,
|
||||
})}
|
||||
searchPlaceholder={t("task:searchBranches")}
|
||||
emptyMessage={t("task:noBranches")}
|
||||
testId="branch-chip-trigger"
|
||||
tooltip={computeBranchTooltip(branchIntent)}
|
||||
onRefresh={refreshBranches}
|
||||
refreshing={branchesLoading}
|
||||
filter={scoreBranch}
|
||||
flat
|
||||
<RepoChipBranchPill
|
||||
branchPicker={branchPicker}
|
||||
branchIntent={branchIntent}
|
||||
branchLocked={branchLocked}
|
||||
branchesLoading={branchesLoading}
|
||||
refreshBranches={refreshBranches}
|
||||
/>
|
||||
<RepoChipRemoveButton onRemove={onRemove} />
|
||||
</span>
|
||||
|
||||
@@ -121,6 +121,11 @@ vi.mock("@/components/state-provider", () => ({
|
||||
setRepositorySets: () => undefined,
|
||||
setRepositorySetsLoading: () => undefined,
|
||||
}),
|
||||
useAppStoreApi: () => ({
|
||||
getState: () => ({
|
||||
repositoryBranchPolicies: { revisionByRepositoryId: {} },
|
||||
}),
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("@/components/task-create-dialog-submit", () => ({
|
||||
@@ -272,7 +277,9 @@ function buildMockFs(initialDescription = ORIGINAL_PROMPT): DialogFormState {
|
||||
currentDefaults: { name: "Task title", description: initialDescription },
|
||||
descriptionInputRef: createRef<TaskFormInputsHandle>(),
|
||||
repositories: [],
|
||||
repositoriesDirty: false,
|
||||
setRepositories: () => undefined,
|
||||
setRepositoriesDirty: () => undefined,
|
||||
addRepository: () => undefined,
|
||||
removeRepository: () => undefined,
|
||||
updateRepository: () => undefined,
|
||||
|
||||
@@ -52,6 +52,7 @@ function CreateModeBody(props: DialogFormBodyProps) {
|
||||
onTaskNameChange,
|
||||
onRowRepositoryChange,
|
||||
onRowBranchChange,
|
||||
onRowPolicyChange,
|
||||
onToggleRemote,
|
||||
onToggleFreshBranch,
|
||||
repositories,
|
||||
@@ -73,6 +74,10 @@ function CreateModeBody(props: DialogFormBodyProps) {
|
||||
workspaceId={workspaceId}
|
||||
onRowRepositoryChange={onRowRepositoryChange}
|
||||
onRowBranchChange={onRowBranchChange}
|
||||
onRowPolicyChange={onRowPolicyChange}
|
||||
onPolicySelected={
|
||||
isLocalExecutor && freshBranchAvailable ? () => onToggleFreshBranch(true) : undefined
|
||||
}
|
||||
onToggleRemote={onToggleRemote}
|
||||
freshBranchAvailable={freshBranchAvailable}
|
||||
freshBranchEnabled={fs.freshBranchEnabled}
|
||||
|
||||
@@ -78,6 +78,7 @@ type SessionMobileLayoutProps = {
|
||||
workflowId: string | null;
|
||||
sessionId?: string | null;
|
||||
baseBranch?: string;
|
||||
pullRequestTarget?: string;
|
||||
worktreeBranch?: string | null;
|
||||
taskTitle?: string;
|
||||
/** `owner/repo` (or the repository name) of the task's primary repository. */
|
||||
@@ -358,6 +359,7 @@ type MobileTopBarStickyProps = {
|
||||
repositoryLabel?: string | null;
|
||||
effectiveSessionId: string | null;
|
||||
baseBranch?: string;
|
||||
pullRequestTarget?: string;
|
||||
worktreeBranch?: string | null;
|
||||
onMenuClick: () => void;
|
||||
showApproveButton: boolean;
|
||||
@@ -385,6 +387,7 @@ function MobileTopBarSticky(props: MobileTopBarStickyProps) {
|
||||
repositoryLabel={props.repositoryLabel}
|
||||
sessionId={props.effectiveSessionId}
|
||||
baseBranch={props.baseBranch}
|
||||
pullRequestTarget={props.pullRequestTarget}
|
||||
worktreeBranch={props.worktreeBranch}
|
||||
onMenuClick={props.onMenuClick}
|
||||
showApproveButton={props.showApproveButton}
|
||||
|
||||
@@ -354,9 +354,14 @@ function createPrSuccessToast(
|
||||
};
|
||||
}
|
||||
|
||||
type MobileGitActionContext = {
|
||||
sessionId: string | null | undefined;
|
||||
baseBranch: string | undefined;
|
||||
pullRequestTarget: string | undefined;
|
||||
};
|
||||
|
||||
export function useMobileGitActions(
|
||||
sessionId: string | null | undefined,
|
||||
baseBranch: string | undefined,
|
||||
{ sessionId, baseBranch, pullRequestTarget }: MobileGitActionContext,
|
||||
setCommitDialogOpen: (v: boolean) => void,
|
||||
setPrDialogOpen: (v: boolean) => void,
|
||||
setPrBranchPushed: (v: boolean) => void,
|
||||
@@ -407,7 +412,7 @@ export function useMobileGitActions(
|
||||
async (title: string, body: string, draft: boolean) => {
|
||||
setPrDialogOpen(false);
|
||||
try {
|
||||
const result = await createPR(title, body, baseBranch, draft);
|
||||
const result = await createPR(title, body, pullRequestTarget ?? baseBranch, draft);
|
||||
if (result.success) {
|
||||
const terms = resolveChangeRequestTerminology(result.provider, defaultTerminology);
|
||||
toast(createPrSuccessToast(terms.longName, result.pr_url, draft, t));
|
||||
@@ -438,6 +443,7 @@ export function useMobileGitActions(
|
||||
[
|
||||
createPR,
|
||||
baseBranch,
|
||||
pullRequestTarget,
|
||||
toast,
|
||||
setPrDialogOpen,
|
||||
setPrBranchPushed,
|
||||
|
||||
@@ -43,6 +43,7 @@ type SessionMobileTopBarProps = {
|
||||
repositoryLabel?: string | null;
|
||||
sessionId?: string | null;
|
||||
baseBranch?: string;
|
||||
pullRequestTarget?: string;
|
||||
worktreeBranch?: string | null;
|
||||
onMenuClick: () => void;
|
||||
showApproveButton?: boolean;
|
||||
@@ -473,13 +474,38 @@ function MobileTopBarActions({
|
||||
);
|
||||
}
|
||||
|
||||
function useSessionMobileTopBarState(props: SessionMobileTopBarProps) {
|
||||
const [commitDialogOpen, setCommitDialogOpen] = useState(false);
|
||||
const [prDialogOpen, setPrDialogOpen] = useState(false);
|
||||
const [prBranchPushed, setPrBranchPushed] = useState(false);
|
||||
const metrics = useMobileGitMetrics(props.sessionId, props.worktreeBranch, props.baseBranch);
|
||||
const actions = useMobileGitActions(
|
||||
{
|
||||
sessionId: props.sessionId,
|
||||
baseBranch: props.baseBranch,
|
||||
pullRequestTarget: props.pullRequestTarget,
|
||||
},
|
||||
setCommitDialogOpen,
|
||||
setPrDialogOpen,
|
||||
setPrBranchPushed,
|
||||
);
|
||||
|
||||
return {
|
||||
...metrics,
|
||||
...actions,
|
||||
commitDialogOpen,
|
||||
setCommitDialogOpen,
|
||||
prDialogOpen,
|
||||
setPrDialogOpen,
|
||||
prBranchPushed,
|
||||
setPrBranchPushed,
|
||||
};
|
||||
}
|
||||
|
||||
export const SessionMobileTopBar = memo(function SessionMobileTopBar(
|
||||
props: SessionMobileTopBarProps,
|
||||
) {
|
||||
const { t } = useTranslation();
|
||||
const [commitDialogOpen, setCommitDialogOpen] = useState(false);
|
||||
const [prDialogOpen, setPrDialogOpen] = useState(false);
|
||||
const [prBranchPushed, setPrBranchPushed] = useState(false);
|
||||
const {
|
||||
commits,
|
||||
displayBranch,
|
||||
@@ -488,8 +514,12 @@ export const SessionMobileTopBar = memo(function SessionMobileTopBar(
|
||||
uncommittedCount,
|
||||
totalAdditions,
|
||||
totalDeletions,
|
||||
} = useMobileGitMetrics(props.sessionId, props.worktreeBranch, props.baseBranch);
|
||||
const {
|
||||
commitDialogOpen,
|
||||
setCommitDialogOpen,
|
||||
prDialogOpen,
|
||||
setPrDialogOpen,
|
||||
prBranchPushed,
|
||||
setPrBranchPushed,
|
||||
isGitLoading,
|
||||
handlePull,
|
||||
handlePush,
|
||||
@@ -497,13 +527,7 @@ export const SessionMobileTopBar = memo(function SessionMobileTopBar(
|
||||
handleMerge,
|
||||
handleCommit,
|
||||
handleCreatePR,
|
||||
} = useMobileGitActions(
|
||||
props.sessionId,
|
||||
props.baseBranch,
|
||||
setCommitDialogOpen,
|
||||
setPrDialogOpen,
|
||||
setPrBranchPushed,
|
||||
);
|
||||
} = useSessionMobileTopBarState(props);
|
||||
return (
|
||||
<header className="flex items-center justify-between px-2 py-2 bg-background">
|
||||
<div className="flex items-center gap-2 min-w-0 flex-1">
|
||||
@@ -558,7 +582,7 @@ export const SessionMobileTopBar = memo(function SessionMobileTopBar(
|
||||
prDialogOpen={prDialogOpen}
|
||||
setPrDialogOpen={setPrDialogOpen}
|
||||
displayBranch={displayBranch}
|
||||
baseBranch={props.baseBranch}
|
||||
baseBranch={props.pullRequestTarget ?? props.baseBranch}
|
||||
taskTitle={props.taskTitle}
|
||||
firstCommitMessage={commits[0]?.commit_message}
|
||||
isGitLoading={isGitLoading}
|
||||
|
||||
@@ -178,6 +178,11 @@ function mapTaskRepositories(
|
||||
repository_id: r.repository_id,
|
||||
base_branch: r.base_branch,
|
||||
checkout_branch: r.checkout_branch,
|
||||
branch_policy_id: r.branch_policy_id,
|
||||
branch_policy_name: r.branch_policy_name,
|
||||
branch_policy_base_branch: r.branch_policy_base_branch,
|
||||
branch_policy_branch_template: r.branch_policy_branch_template,
|
||||
branch_policy_pull_request_target: r.branch_policy_pull_request_target,
|
||||
position: r.position,
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -391,6 +391,18 @@ function NewSubtaskForm({
|
||||
const allExecutorProfiles = useExecutorProfiles(executors);
|
||||
const executorProfileOptions = useExecutorProfileOptions(allExecutorProfiles);
|
||||
useExecutorDefault(allExecutorProfiles, fs.executorProfileId, fs.setExecutorProfileId);
|
||||
const selectedExecutorProfile = executorProfileOptions.find(
|
||||
(profile) => profile.value === fs.executorProfileId,
|
||||
);
|
||||
const isLocalExecutor = Boolean(
|
||||
selectedExecutorProfile?.executorType === "local" ||
|
||||
selectedExecutorProfile?.executorType === "local_pc",
|
||||
);
|
||||
const freshBranchAvailable =
|
||||
workspaceMode === "new_workspace" &&
|
||||
!fs.useRemote &&
|
||||
isLocalExecutor &&
|
||||
fs.repositories.length === 1;
|
||||
const promptZone = useSubtaskPromptZone({
|
||||
parentTaskId,
|
||||
workspaceId,
|
||||
@@ -424,6 +436,7 @@ function NewSubtaskForm({
|
||||
title,
|
||||
autoTitle,
|
||||
autopilot: fs.autopilot,
|
||||
isLocalExecutor,
|
||||
setIsCreating,
|
||||
onClose,
|
||||
workspaceMode,
|
||||
@@ -442,7 +455,12 @@ function NewSubtaskForm({
|
||||
executorProfileOptions,
|
||||
agentProfileId: fs.agentProfileId || defaultProfileId,
|
||||
workspaceMode,
|
||||
onWorkspaceModeChange: setWorkspaceMode,
|
||||
onWorkspaceModeChange: (mode: SubtaskWorkspaceMode) => {
|
||||
if (mode !== "new_workspace") fs.setFreshBranchEnabled(false);
|
||||
setWorkspaceMode(mode);
|
||||
},
|
||||
isLocalExecutor,
|
||||
freshBranchAvailable,
|
||||
contextValue,
|
||||
onContextChange: handleContextChange,
|
||||
hasInitialPrompt: !!initialPrompt,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user