Files
kandev/apps/backend/internal/automation/service.go
T
João Salavisa 1b58a64fd8 feat(automations): /settings/automations with run-mode + per-automation config (#1016)
* feat: add automation system with triggers, backend-driven metadata, and PR association

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(automations): execution_mode + flat /settings/automations

Layered on top of #406's automation subsystem:

- Add execution_mode to Automation (task | run, default task). Run-mode
  firings create an ephemeral kanban-hidden task tagged with
  origin=automation_run. The session pipeline still runs against it, but
  users surface them through the AutomationRun history instead of the
  kanban. Pragmatic shim while AutomationRun-as-true-session-owner is
  deferred to a follow-up.

- Thread IsEphemeral + Origin through ReviewTaskRequest +
  reviewTaskCreatorAdapter so the orchestrator can create the hidden
  task in one call.

- Run-mode always auto-starts (the user never sees the task to drag).

- Flat /settings/automations route replaces the per-workspace sidebar
  entry. Picks the only workspace, shows a picker for many, or shows
  a CTA for zero workspaces.

- Editor exposes execution mode + table shows it as a badge column.

Spec at docs/specs/office/automations-settings.md documents the design,
deferred items, and scenarios.

* feat(automations): per-automation repository picker

Adds a repository_id field on Automation so users can pin scheduled and
webhook automations to a specific workspace repository instead of always
falling through to "first repo". github_pr triggers ignore the field and
keep using the PR's own repo — the editor disables the picker with a
hint when a PR trigger is selected.

Backend:
- repository_id column folded into the canonical CREATE TABLE (no
  migration needed — PR #406 introduces the table).
- RepositoryID threaded through model, DTOs, store INSERT/UPDATE, and
  service.CreateAutomation.
- resolveAutomationRepository prefers the explicit ID, falls back to
  workspace-first on empty.

Frontend:
- repository_id on the Automation TS type + Create/Update payloads.
- Repository SelectField in ConfigSection backed by useRepositories;
  "Auto" sentinel represents the empty/fallback choice.
- Disabled with help-text for github_pr triggers.

* feat(automations): repo picker shows discovered repos too

Matches the task-creation dialog's UX: the editor's repository picker
now lists registered workspace repos AND filesystem-discovered repos
under the workspace's roots. Picking a discovered repo registers it
with the workspace at save time (via createRepositoryAction), captures
the new id, and writes it onto the automation. After the first save
the picker selection is promoted from "discovered" to "registered" so
re-saving doesn't re-register.

Form state holds a RepositorySelection union (auto | registered |
discovered) rather than a plain id string so the picker can carry the
metadata needed to register.

github_pr triggers still disable the picker — PR events always override
any configured repo with the PR's own.

* fix(automations): add idempotent ALTERs for in-branch columns

The canonical CREATE TABLE covers fresh installs, but `CREATE TABLE
IF NOT EXISTS` is a no-op for DBs already initialised from an earlier
commit on this branch (PR #406's original schema). Without these
ALTERs, dev DBs created before execution_mode + repository_id existed
on the row hit "no such column" errors.

Three idempotent ALTERs: task_title_template, execution_mode,
repository_id. SQLite returns a duplicate-column error when the column
already exists; we swallow it.

* fix(automations): use generateUUID in non-secure contexts

crypto.randomUUID is only defined in secure contexts (HTTPS or
localhost). PR #406's editor used it directly, which throws "crypto.
randomUUID is not a function" when the app is reached via a plain
hostname like nova:58204. Switch to lib/utils.generateUUID, which
falls back to a Math.random-based implementation when crypto isn't
available.

* fix(automations): polish run-mode lifecycle, validation, and editor UX

Run-mode automations were partly broken end-to-end:
- workflow_id was sent for ephemeral tasks (rejected by task service)
  and was required by the editor + automation service, so "Create
  Automation" was always disabled and silently failed
- a permission_request hanging the agent left the run pinned at
  task_created forever; nothing reaped the ephemeral worktree
- trigger config inputs (cron, branches, authors) did not re-sync
  with the loaded automation on page reload
- runs row never linked back to the underlying task for task-mode
  automations, and the table header highlighted on hover

Backend
- skip workflow fields in CreateReviewTask / StartTask for run-mode
- relax automation.Service.CreateAutomation: workflow only required
  for task-mode
- auto-reject permission prompts on ephemeral automation tasks and
  mark the AutomationRun failed with the requested action
- on agent completion / failure for ephemeral automation tasks,
  flip the run to succeeded/failed and remove the worktree + branch
  immediately (new RunStatusSucceeded + MarkRunSucceededByTaskID)
- wire worktree.Manager into the orchestrator service

Frontend
- show Execution Mode first; hide Workflow / Workflow Step in run-mode
- canSave no longer requires workflow in run-mode
- surface save errors via toast instead of silent failure
- sync trigger-config local input state with loaded prop value
- runs table: clickable row → /tasks/<id> for task-mode runs,
  non-clickable in run-mode; suppress header hover

* fix(automations): address PR review feedback

Backend
- automation/scheduler.go: parseCronFields returns an error for
  unsupported expressions instead of silently defaulting to hourly
- automation/webhook.go: constant-time secret compare, header-only
  (no more ?secret= query param), reject with 409 when no enabled
  webhook trigger exists
- automation/service.go: enforce max_concurrent_runs in FireTrigger
  via maybeSkipForConcurrencyCap (records a skipped run when capped)
- cmd/kandev/e2e_reset.go: surface automation delete errors as 500
  instead of swallowing them
- orchestrator/event_handlers_git.go: auto-reject permission with
  cancelled=true so the message status is "rejected" and the session
  isn't flipped back to running
- orchestrator/event_handlers_agent.go: finalizeAutomationRunIfEphemeral
  now runs at the top of handleAgentFailed, before the resume/recoverable
  early returns, so session-backed run-mode failures get cleaned up

Frontend
- state/slices/automations/automations-slice.ts: declare _get/_api so
  the call site's arity matches and CodeQL stops flagging ignored
  trailing arguments
- automations/schedule-selector.tsx: clearing the input now propagates
  ""; cron is trimmed before validation+save
- automations/triggers-section.tsx: switching to webhook mode deletes
  the existing scheduled/condition triggers so they don't keep firing
  hidden in the background
- automations/trigger-configs/github-ci-config.tsx: useEffect re-sync
  for checkNames, matching the other trigger configs
- hooks/domains/settings/use-automations.ts: per-workspace fetch via
  loadedWorkspaceRef + render-safe loadedWorkspaceId state;
  inFlightWorkspaceRef discards stale responses after workspace switch

---------

Co-authored-by: Carlos Florêncio <carlosmflorencio@gmail.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Kandev Agent <agent@kandev.dev>
2026-05-22 22:01:59 +01:00

303 lines
9.5 KiB
Go

package automation
import (
"context"
"encoding/json"
"fmt"
"time"
"go.uber.org/zap"
"github.com/kandev/kandev/internal/common/logger"
"github.com/kandev/kandev/internal/events"
"github.com/kandev/kandev/internal/events/bus"
)
// Service coordinates automation operations.
type Service struct {
store *Store
eventBus bus.EventBus
logger *logger.Logger
}
// NewService creates a new automation service.
func NewService(store *Store, eventBus bus.EventBus, log *logger.Logger) *Service {
return &Service{
store: store,
eventBus: eventBus,
logger: log,
}
}
// Store returns the underlying store (for scheduler/poller access).
func (s *Service) Store() *Store {
return s.store
}
// --- Automation CRUD ---
// CreateAutomation creates an automation with its initial triggers.
func (s *Service) CreateAutomation(ctx context.Context, req *CreateAutomationRequest) (*Automation, error) {
if req.Name == "" {
return nil, fmt.Errorf("name is required")
}
if req.WorkspaceID == "" {
return nil, fmt.Errorf("workspace_id is required")
}
maxRuns := req.MaxConcurrentRuns
if maxRuns <= 0 {
maxRuns = 1
}
mode := req.ExecutionMode
if !mode.Valid() {
mode = ExecutionModeTask
}
// Workflow + step are required for task-mode automations (the run is
// surfaced on the kanban and needs a starting column). Run-mode is
// ephemeral and bypasses the workflow entirely.
if mode == ExecutionModeTask {
if req.WorkflowID == "" {
return nil, fmt.Errorf("workflow_id is required")
}
if req.WorkflowStepID == "" {
return nil, fmt.Errorf("workflow_step_id is required")
}
}
a := &Automation{
WorkspaceID: req.WorkspaceID,
Name: req.Name,
Description: req.Description,
WorkflowID: req.WorkflowID,
WorkflowStepID: req.WorkflowStepID,
AgentProfileID: req.AgentProfileID,
ExecutorProfileID: req.ExecutorProfileID,
RepositoryID: req.RepositoryID,
Prompt: req.Prompt,
TaskTitleTemplate: req.TaskTitleTemplate,
ExecutionMode: mode,
Enabled: true,
MaxConcurrentRuns: maxRuns,
}
if err := s.store.CreateAutomation(ctx, a); err != nil {
return nil, fmt.Errorf("create automation: %w", err)
}
// Create initial triggers.
for _, ts := range req.Triggers {
t := &AutomationTrigger{
AutomationID: a.ID,
Type: ts.Type,
Config: ts.Config,
Enabled: ts.Enabled,
}
if err := s.store.CreateTrigger(ctx, t); err != nil {
s.logger.Error("failed to create trigger during automation creation",
zap.String("automation_id", a.ID),
zap.String("type", string(ts.Type)),
zap.Error(err))
}
}
return s.store.GetAutomation(ctx, a.ID)
}
// GetAutomation retrieves an automation by ID.
func (s *Service) GetAutomation(ctx context.Context, id string) (*Automation, error) {
return s.store.GetAutomation(ctx, id)
}
// ListAutomations returns all automations for a workspace.
func (s *Service) ListAutomations(ctx context.Context, workspaceID string) ([]*Automation, error) {
return s.store.ListAutomations(ctx, workspaceID)
}
// UpdateAutomation applies partial updates.
func (s *Service) UpdateAutomation(ctx context.Context, id string, req *UpdateAutomationRequest) (*Automation, error) {
if err := s.store.UpdateAutomation(ctx, id, req); err != nil {
return nil, err
}
return s.store.GetAutomation(ctx, id)
}
// DeleteAutomation removes an automation.
func (s *Service) DeleteAutomation(ctx context.Context, id string) error {
return s.store.DeleteAutomation(ctx, id)
}
// EnableAutomation sets enabled = true.
func (s *Service) EnableAutomation(ctx context.Context, id string) error {
enabled := true
return s.store.UpdateAutomation(ctx, id, &UpdateAutomationRequest{Enabled: &enabled})
}
// DisableAutomation sets enabled = false.
func (s *Service) DisableAutomation(ctx context.Context, id string) error {
enabled := false
return s.store.UpdateAutomation(ctx, id, &UpdateAutomationRequest{Enabled: &enabled})
}
// --- Trigger CRUD ---
// AddTrigger adds a trigger to an automation.
func (s *Service) AddTrigger(ctx context.Context, req *AddTriggerRequest) (*AutomationTrigger, error) {
if req.AutomationID == "" {
return nil, fmt.Errorf("automation_id is required")
}
t := &AutomationTrigger{
AutomationID: req.AutomationID,
Type: req.Type,
Config: req.Config,
Enabled: req.Enabled,
}
if err := s.store.CreateTrigger(ctx, t); err != nil {
return nil, err
}
return t, nil
}
// UpdateTrigger updates a trigger.
func (s *Service) UpdateTrigger(ctx context.Context, id string, req *UpdateTriggerRequest) error {
return s.store.UpdateTrigger(ctx, id, req)
}
// DeleteTrigger removes a trigger.
func (s *Service) DeleteTrigger(ctx context.Context, id string) error {
return s.store.DeleteTrigger(ctx, id)
}
// --- Run queries ---
// ListRuns returns recent runs for an automation.
func (s *Service) ListRuns(ctx context.Context, automationID string, limit int) ([]*AutomationRun, error) {
return s.store.ListRuns(ctx, automationID, limit)
}
// --- Trigger firing ---
// FireTrigger publishes an AutomationTriggered event for the given trigger.
// The orchestrator handles task creation in response.
func (s *Service) FireTrigger(ctx context.Context, automationID, triggerID string, triggerType TriggerType, triggerData json.RawMessage, dedupKey string) error {
// Check dedup.
if dedupKey != "" {
exists, err := s.store.HasRunWithDedupKey(ctx, automationID, dedupKey)
if err != nil {
return fmt.Errorf("check dedup: %w", err)
}
if exists {
s.logger.Debug("skipping duplicate trigger",
zap.String("automation_id", automationID),
zap.String("dedup_key", dedupKey))
return nil
}
}
// Enforce max_concurrent_runs: a run is "active" while still in
// task_created (succeeded/failed/skipped don't count). If at the cap,
// record a skipped run so the user can see the cap kicked in.
skipped, capErr := s.maybeSkipForConcurrencyCap(ctx, automationID, triggerID, triggerType, triggerData, dedupKey)
if capErr != nil {
return capErr
}
if skipped {
return nil
}
evt := &AutomationTriggeredEvent{
AutomationID: automationID,
TriggerID: triggerID,
TriggerType: triggerType,
TriggerData: triggerData,
DedupKey: dedupKey,
}
now := time.Now().UTC()
if updateErr := s.store.UpdateLastTriggered(ctx, automationID, now); updateErr != nil {
s.logger.Warn("failed to update last_triggered_at",
zap.String("automation_id", automationID), zap.Error(updateErr))
}
if updateErr := s.store.UpdateTriggerEvaluatedAt(ctx, triggerID, now); updateErr != nil {
s.logger.Warn("failed to update last_evaluated_at",
zap.String("trigger_id", triggerID), zap.Error(updateErr))
}
event := bus.NewEvent(events.AutomationTriggered, "automation_service", evt)
if err := s.eventBus.Publish(ctx, events.AutomationTriggered, event); err != nil {
return fmt.Errorf("publish automation triggered: %w", err)
}
s.logger.Info("automation trigger fired",
zap.String("automation_id", automationID),
zap.String("trigger_id", triggerID),
zap.String("type", string(triggerType)))
return nil
}
// RecordRun records a trigger run outcome.
func (s *Service) RecordRun(ctx context.Context, run *AutomationRun) error {
return s.store.CreateRun(ctx, run)
}
// maybeSkipForConcurrencyCap enforces max_concurrent_runs. Returns (skipped,
// err). When skipped, a "skipped" run row is persisted so the user can see
// the cap kicked in.
func (s *Service) maybeSkipForConcurrencyCap(ctx context.Context, automationID, triggerID string, triggerType TriggerType, triggerData json.RawMessage, dedupKey string) (bool, error) {
a, err := s.store.GetAutomation(ctx, automationID)
if err != nil || a == nil {
return false, nil // not our problem here; FireTrigger will hit it again downstream
}
if a.MaxConcurrentRuns <= 0 {
return false, nil
}
active, err := s.store.CountActiveRuns(ctx, automationID)
if err != nil {
return false, fmt.Errorf("count active runs: %w", err)
}
if active < a.MaxConcurrentRuns {
return false, nil
}
skipRun := &AutomationRun{
AutomationID: automationID,
TriggerID: triggerID,
TriggerType: triggerType,
Status: RunStatusSkipped,
DedupKey: dedupKey,
TriggerData: triggerData,
ErrorMessage: fmt.Sprintf("max_concurrent_runs=%d reached", a.MaxConcurrentRuns),
}
if recErr := s.store.CreateRun(ctx, skipRun); recErr != nil {
s.logger.Warn("failed to record skipped run", zap.Error(recErr))
}
s.logger.Info("automation trigger skipped: concurrency cap reached",
zap.String("automation_id", automationID),
zap.Int("active", active),
zap.Int("max", a.MaxConcurrentRuns))
return true, nil
}
// MarkRunFailedByTaskID transitions a still-pending run (task_created) into
// the failed state. Used when something downstream of task creation aborts
// the run, e.g. a permission prompt for a run-mode automation.
func (s *Service) MarkRunFailedByTaskID(ctx context.Context, taskID, errMsg string) error {
return s.store.MarkRunFailedByTaskID(ctx, taskID, errMsg)
}
// MarkRunSucceededByTaskID transitions a still-pending run (task_created)
// into the succeeded state when the launched agent finishes cleanly.
func (s *Service) MarkRunSucceededByTaskID(ctx context.Context, taskID string) error {
return s.store.MarkRunSucceededByTaskID(ctx, taskID)
}
// GetWebhookSecret returns the webhook secret for an automation.
func (s *Service) GetWebhookSecret(ctx context.Context, id string) (string, error) {
a, err := s.store.GetAutomation(ctx, id)
if err != nil {
return "", err
}
if a == nil {
return "", fmt.Errorf("automation not found: %s", id)
}
return a.WebhookSecret, nil
}