2a1f7c2edf
* feat: sync workflows from a configured github repo Per-workspace setting pointing at a GitHub repo directory of portable workflow export files. A background poller fetches it on an interval and creates, updates, or deletes the matching workflows; a force-sync endpoint bypasses the content-hash check. Synced workflows carry source/source_path provenance and coexist with manual ones; changes that cannot be applied safely (steps or workflows that still hold tasks, ambiguous step names, unparseable files) surface as warnings in the new settings section. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(web): fill workflow sync form from a pasted github link A new Repository link field parses plain repo URLs, SSH remotes, and tree/blob links (which also carry branch and directory) into the structured owner/repo/branch/path fields. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(web): simplify workflow sync form to link, branch, and interval The repository link is now the only repo input: owner, repo, and directory resolve from the pasted URL (echoed as a summary under the field), and a stored config renders back into a canonical tree link via buildGitHubRepoUrl. Branch and poll interval stay individually editable. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(web): collapse workflow sync into a button, dialog, and status card The Workflows settings page now shows only a GitHub Sync button by default; the link/branch/interval form lives in a dialog that closes on successful save or removal. Once configured, a compact status card (mirroring the GitHub connection-status card) shows the synced repo, branch, directory, last result, warnings, and a Sync now action. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(web): move github sync button into the workflows page header The GitHub Sync trigger now stacks under the Workspace settings button on the top right, and the extra separator around the sync area is gone — unconfigured workspaces show no sync chrome at all, configured ones show just the status card above the workflow list. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(web): move github sync button next to the workflow actions GitHub Sync now sits in the Workflows section toolbar alongside Export All, Import, and Add Workflow; the status card renders inside the section above the workflow list. The toolbar moved to its own component to keep the page under the file-size limit. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(web): separate sync status card from the workflow list Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(web): align sync status card with the workflow list gutter Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix: repair local edits to synced workflows on periodic sync Periodic syncs previously skipped applying when the repo content hash was unchanged, so local UI edits to a synced workflow were only reverted by a manual Sync now. Every sync now reconciles against the repo; the applier compares each step against its definition and only writes (and broadcasts) actual differences, so a no-drift sync stays silent. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat: make github-synced workflows read-only Workflows with source=github reject UI mutations: workflow rename, description, agent-profile, and delete return 409 from the task-domain handlers; step create/update/delete/reorder and template application are guarded in the workflow controller. The sync applier writes through the service/repo layer and stays exempt. The frontend disables the card's inputs, save/delete, and the step pipeline editor for synced workflows, with a tooltip pointing at the synced repository. Drift repair on sync remains as the backstop. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat: optional workflow sync polling and repo-derived branch picker A per-workspace auto-sync toggle (poll_enabled, default on) controls the background polling loop; when off the workspace only syncs via Sync now. The dialog's branch field becomes a select fed by the repository's actual branches (same loader the task-create dialog uses), falling back to free text until branches load. Existing dev databases gain the new column via an idempotent ALTER. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat: release synced workflows when the sync config is removed Deleting a workspace's workflow sync configuration converts its GitHub-sourced workflows back to manual ownership (source=manual), so they become editable instead of being stranded read-only. Release runs before the config row is deleted so a failure keeps the config for retry. The settings page reloads after removal (and after syncs that changed workflows) so cards unlock without a manual refresh. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(web): drop branch selector and compact the auto-sync row The pasted link already carries the branch (main by default), so the dialog no longer needs a branch field — the resolved summary echoes it. The auto-sync toggle is now one compact row with the interval inline and a single short helper line. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix: address PR review feedback Backend: fail-open read-only guard on workflow lookup errors (fixes MCP step handler CI failures); poller Stop holds its mutex through drain; per-workspace lock serializes syncs against config delete/replace; rollback workflow creation when provenance stamping fails; idiomatic duplicate-column migration via db.IsDuplicateColumnError; branch-name validation and a 30-day interval cap; generic 500s with logged detail; WS read-only rejections use CONFLICT with the real reason; e2e reset aborts when sync-config cleanup fails; test hygiene (t.Cleanup, SetMaxOpenConns). Frontend: malformed percent escapes parse as invalid instead of throwing; save disabled during initial load and for invalid intervals; Remove disabled while saving; stale async config responses discarded; delete-dialog confirms re-check read-only; focusable Synced badge; explicit button types; failed polls labeled 'last attempt'; unique warning list keys; test cleanup via afterEach. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix: guard workflow sync test fake against concurrent poller access The poller invokes the fake applier from its own goroutine while the synctest test asserts on call counts; -race caught the unguarded reads. Also documents that the per-workspace lock is deliberately held across the GitHub fetch. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Kandev Agent <agent@kandev.dev> Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
206 lines
6.0 KiB
Go
206 lines
6.0 KiB
Go
package workflowsync
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/jmoiron/sqlx"
|
|
|
|
"github.com/kandev/kandev/internal/db"
|
|
)
|
|
|
|
// Store persists workspace-scoped workflow sync configuration.
|
|
type Store struct {
|
|
db *sqlx.DB
|
|
ro *sqlx.DB
|
|
}
|
|
|
|
// NewStore creates a new Store and initializes the schema if needed.
|
|
func NewStore(writer, reader *sqlx.DB) (*Store, error) {
|
|
s := &Store{db: writer, ro: reader}
|
|
if err := s.initSchema(); err != nil {
|
|
return nil, fmt.Errorf("workflowsync schema init: %w", err)
|
|
}
|
|
return s, nil
|
|
}
|
|
|
|
const createTablesSQL = `
|
|
CREATE TABLE IF NOT EXISTS workflow_sync_configs (
|
|
workspace_id TEXT PRIMARY KEY,
|
|
repo_owner TEXT NOT NULL,
|
|
repo_name TEXT NOT NULL,
|
|
branch TEXT NOT NULL DEFAULT 'main',
|
|
path TEXT NOT NULL DEFAULT '',
|
|
interval_seconds INTEGER NOT NULL DEFAULT 300,
|
|
poll_enabled INTEGER NOT NULL DEFAULT 1,
|
|
last_synced_at DATETIME,
|
|
last_ok INTEGER NOT NULL DEFAULT 0,
|
|
last_error TEXT NOT NULL DEFAULT '',
|
|
last_warnings TEXT NOT NULL DEFAULT '[]',
|
|
last_hash TEXT NOT NULL DEFAULT '',
|
|
created_at DATETIME NOT NULL,
|
|
updated_at DATETIME NOT NULL
|
|
);
|
|
`
|
|
|
|
func (s *Store) initSchema() error {
|
|
if _, err := s.db.Exec(createTablesSQL); err != nil {
|
|
return err
|
|
}
|
|
return s.addPollEnabledColumn()
|
|
}
|
|
|
|
// addPollEnabledColumn brings databases created before the poll toggle up to
|
|
// the current schema. Idempotent and race-safe: the ALTER always runs and a
|
|
// "duplicate column name" failure is swallowed via the shared helper.
|
|
func (s *Store) addPollEnabledColumn() error {
|
|
_, err := s.db.Exec(`ALTER TABLE workflow_sync_configs ADD COLUMN poll_enabled INTEGER NOT NULL DEFAULT 1`)
|
|
if err != nil && !db.IsDuplicateColumnError(err) {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
const configSelectColumns = `workspace_id, repo_owner, repo_name, branch, path, interval_seconds,
|
|
poll_enabled, last_synced_at, last_ok, last_error, last_warnings, last_hash, created_at, updated_at`
|
|
|
|
type configScanner interface {
|
|
Scan(dest ...interface{}) error
|
|
}
|
|
|
|
func scanConfig(row configScanner) (*Config, error) {
|
|
cfg := &Config{}
|
|
var lastOk, pollEnabled int
|
|
var lastSyncedAt sql.NullTime
|
|
var warningsJSON string
|
|
if err := row.Scan(
|
|
&cfg.WorkspaceID,
|
|
&cfg.RepoOwner,
|
|
&cfg.RepoName,
|
|
&cfg.Branch,
|
|
&cfg.Path,
|
|
&cfg.IntervalSeconds,
|
|
&pollEnabled,
|
|
&lastSyncedAt,
|
|
&lastOk,
|
|
&cfg.LastError,
|
|
&warningsJSON,
|
|
&cfg.LastHash,
|
|
&cfg.CreatedAt,
|
|
&cfg.UpdatedAt,
|
|
); err != nil {
|
|
return nil, err
|
|
}
|
|
cfg.LastOk = lastOk != 0
|
|
cfg.PollEnabled = pollEnabled != 0
|
|
if lastSyncedAt.Valid {
|
|
t := lastSyncedAt.Time
|
|
cfg.LastSyncedAt = &t
|
|
}
|
|
if warningsJSON != "" {
|
|
// Corrupt JSON degrades to no warnings rather than failing the read.
|
|
_ = json.Unmarshal([]byte(warningsJSON), &cfg.LastWarnings)
|
|
}
|
|
return cfg, nil
|
|
}
|
|
|
|
// GetConfigForWorkspace returns the config for a workspace, or (nil, nil)
|
|
// when none is stored.
|
|
func (s *Store) GetConfigForWorkspace(ctx context.Context, workspaceID string) (*Config, error) {
|
|
row := s.ro.QueryRowContext(ctx, s.ro.Rebind(`
|
|
SELECT `+configSelectColumns+` FROM workflow_sync_configs WHERE workspace_id = ?
|
|
`), workspaceID)
|
|
cfg, err := scanConfig(row)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return nil, nil
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return cfg, nil
|
|
}
|
|
|
|
// ListConfigs returns every stored config, for the background poller.
|
|
func (s *Store) ListConfigs(ctx context.Context) ([]*Config, error) {
|
|
rows, err := s.ro.QueryContext(ctx, `SELECT `+configSelectColumns+` FROM workflow_sync_configs ORDER BY workspace_id`)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer func() { _ = rows.Close() }()
|
|
|
|
var configs []*Config
|
|
for rows.Next() {
|
|
cfg, err := scanConfig(rows)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
configs = append(configs, cfg)
|
|
}
|
|
return configs, rows.Err()
|
|
}
|
|
|
|
// UpsertConfigForWorkspace creates or replaces a workspace's config. The sync
|
|
// status columns are reset so the next sync re-fetches and re-applies.
|
|
func (s *Store) UpsertConfigForWorkspace(ctx context.Context, workspaceID string, req *SetConfigRequest) (*Config, error) {
|
|
now := time.Now().UTC()
|
|
_, err := s.db.ExecContext(ctx, s.db.Rebind(`
|
|
INSERT INTO workflow_sync_configs (
|
|
workspace_id, repo_owner, repo_name, branch, path, interval_seconds, poll_enabled,
|
|
last_synced_at, last_ok, last_error, last_warnings, last_hash, created_at, updated_at
|
|
) VALUES (?, ?, ?, ?, ?, ?, ?, NULL, 0, '', '[]', '', ?, ?)
|
|
ON CONFLICT(workspace_id) DO UPDATE SET
|
|
repo_owner = excluded.repo_owner,
|
|
repo_name = excluded.repo_name,
|
|
branch = excluded.branch,
|
|
path = excluded.path,
|
|
interval_seconds = excluded.interval_seconds,
|
|
poll_enabled = excluded.poll_enabled,
|
|
last_synced_at = NULL,
|
|
last_ok = 0,
|
|
last_error = '',
|
|
last_warnings = '[]',
|
|
last_hash = '',
|
|
updated_at = excluded.updated_at
|
|
`), workspaceID, req.RepoOwner, req.RepoName, req.Branch, req.Path, req.IntervalSeconds, boolToInt(req.PollEnabled != nil && *req.PollEnabled), now, now)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return s.GetConfigForWorkspace(ctx, workspaceID)
|
|
}
|
|
|
|
// RecordSyncStatus persists the outcome of a sync attempt.
|
|
func (s *Store) RecordSyncStatus(ctx context.Context, workspaceID string, ok bool, errMsg string, warnings []string, hash string, at time.Time) error {
|
|
warningsJSON, err := json.Marshal(warnings)
|
|
if err != nil {
|
|
warningsJSON = []byte("[]")
|
|
}
|
|
okInt := 0
|
|
if ok {
|
|
okInt = 1
|
|
}
|
|
_, err = s.db.ExecContext(ctx, s.db.Rebind(`
|
|
UPDATE workflow_sync_configs
|
|
SET last_synced_at = ?, last_ok = ?, last_error = ?, last_warnings = ?, last_hash = ?, updated_at = ?
|
|
WHERE workspace_id = ?
|
|
`), at, okInt, errMsg, string(warningsJSON), hash, at, workspaceID)
|
|
return err
|
|
}
|
|
|
|
// DeleteConfigForWorkspace removes a workspace's config. Deleting a missing
|
|
// config is a no-op.
|
|
func (s *Store) DeleteConfigForWorkspace(ctx context.Context, workspaceID string) error {
|
|
_, err := s.db.ExecContext(ctx, s.db.Rebind(`DELETE FROM workflow_sync_configs WHERE workspace_id = ?`), workspaceID)
|
|
return err
|
|
}
|
|
|
|
func boolToInt(b bool) int {
|
|
if b {
|
|
return 1
|
|
}
|
|
return 0
|
|
}
|