Files
kandev/apps/web/components/settings/workflow-sync-dialog.tsx
T
João Salavisa 2a1f7c2edf feat: sync workflows from a configured github repo (#1721)
* 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>
2026-07-16 08:31:20 +01:00

191 lines
6.4 KiB
TypeScript

"use client";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@kandev/ui/dialog";
import { Button } from "@kandev/ui/button";
import { Input } from "@kandev/ui/input";
import { Label } from "@kandev/ui/label";
import { Switch } from "@kandev/ui/switch";
import type {
WorkflowSyncController,
WorkflowSyncFormState,
} from "@/hooks/domains/settings/use-workflow-sync";
const HELP_TEXT =
"The directory should contain workflow export files (.yml/.yaml/.json) in the kandev_workflow format — the same format produced by workflow export.";
type RepoUrlFieldProps = {
url: string;
invalid: boolean;
resolved: string;
onChange: (value: string) => void;
};
// RepoUrlField is the primary input: a full GitHub link (optionally with
// /tree/<branch>/<directory>) that resolves into the stored owner, repo,
// branch, and directory. The resolved target is echoed underneath so the
// structured fields stay visible to the user.
function RepoUrlField({ url, invalid, resolved, onChange }: RepoUrlFieldProps) {
return (
<div className="space-y-1.5">
<Label htmlFor="workflow-sync-url">Repository link</Label>
<Input
id="workflow-sync-url"
data-testid="workflow-sync-url-input"
placeholder="https://github.com/kdlbs/kandev/tree/main/.kandev/workflows"
value={url}
onChange={(e) => onChange(e.target.value)}
aria-invalid={invalid}
/>
{invalid ? (
<p className="text-xs text-destructive">Not a recognized GitHub repository link.</p>
) : (
<p className="text-xs text-muted-foreground" data-testid="workflow-sync-resolved">
{resolved || "Paste a GitHub link — /tree/… links carry the branch and directory too."}
</p>
)}
</div>
);
}
type FieldsProps = {
form: WorkflowSyncFormState;
update: <K extends keyof WorkflowSyncFormState>(key: K, value: WorkflowSyncFormState[K]) => void;
};
// PollFields is a single compact row: the auto-sync switch and, when on, the
// interval right beside it. The branch needs no field of its own — it comes
// from the pasted link (or defaults to main) and is echoed in the resolved
// summary under the link input.
function PollFields({ form, update }: FieldsProps) {
return (
<div className="space-y-1.5">
<div className="flex flex-wrap items-center gap-3">
<Switch
id="workflow-sync-poll-toggle"
data-testid="workflow-sync-poll-toggle"
checked={form.poll_enabled}
onCheckedChange={(checked) => update("poll_enabled", checked)}
className="cursor-pointer"
/>
<Label htmlFor="workflow-sync-poll-toggle" className="cursor-pointer">
Auto-sync
</Label>
{form.poll_enabled && (
<div className="ml-auto flex items-center gap-2">
<Label htmlFor="workflow-sync-interval" className="sr-only">
Poll interval (seconds)
</Label>
<Input
id="workflow-sync-interval"
data-testid="workflow-sync-interval-input"
type="number"
min={60}
className="w-24"
value={form.interval_seconds}
onChange={(e) => update("interval_seconds", Number(e.target.value) || 0)}
/>
<span className="text-xs text-muted-foreground">seconds</span>
</div>
)}
</div>
<p className="text-xs text-muted-foreground">
{form.poll_enabled
? "Checks the repository on this interval (minimum 60s)."
: "Syncs only run when you press Sync now."}
</p>
</div>
);
}
type WorkflowSyncDialogProps = {
open: boolean;
onOpenChange: (open: boolean) => void;
sync: WorkflowSyncController;
};
// WorkflowSyncDialog holds the GitHub Sync configuration form. It closes
// itself after a successful save or removal; failures keep it open with the
// error surfaced via toast.
export function WorkflowSyncDialog({ open, onOpenChange, sync }: WorkflowSyncDialogProps) {
const hasConfig = !!sync.config;
const intervalInvalid =
sync.form.poll_enabled &&
(!Number.isInteger(sync.form.interval_seconds) || sync.form.interval_seconds < 60);
const disableSave =
sync.saving ||
sync.loading ||
sync.urlInvalid ||
intervalInvalid ||
!sync.form.repo_owner.trim() ||
!sync.form.repo_name.trim();
const resolved = sync.form.repo_owner
? `Syncing ${sync.form.repo_owner}/${sync.form.repo_name} @ ${sync.form.branch || "main"} — directory ${sync.form.path || "(repository root)"}.`
: "";
const handleSave = async () => {
if (await sync.handleSave()) onOpenChange(false);
};
const handleRemove = async () => {
if (await sync.handleDelete()) onOpenChange(false);
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-lg" data-testid="workflow-sync-dialog">
<DialogHeader>
<DialogTitle>GitHub Sync</DialogTitle>
<DialogDescription>
Automatically sync workflow definitions from a GitHub repository into this workspace.
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<RepoUrlField
url={sync.url}
invalid={sync.urlInvalid}
resolved={resolved}
onChange={sync.setUrlInput}
/>
<PollFields form={sync.form} update={sync.update} />
<p className="text-xs text-muted-foreground">{HELP_TEXT}</p>
</div>
<DialogFooter>
{hasConfig && (
<Button
type="button"
variant="destructive"
onClick={handleRemove}
disabled={sync.saving}
className="sm:mr-auto cursor-pointer"
data-testid="workflow-sync-remove"
>
Remove
</Button>
)}
<Button
type="button"
onClick={handleSave}
disabled={disableSave}
className="cursor-pointer"
data-testid="workflow-sync-save"
data-dialog-default-action
>
{saveLabel(sync.saving, hasConfig)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
function saveLabel(saving: boolean, hasConfig: boolean): string {
if (saving) return "Saving...";
return hasConfig ? "Update" : "Save";
}