"use client"; import { useState, useEffect, useCallback, useMemo } from "react"; import { Button } from "@kandev/ui/button"; import { Separator } from "@kandev/ui/separator"; import { Switch } from "@kandev/ui/switch"; import { Label } from "@kandev/ui/label"; import { Input } from "@kandev/ui/input"; import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter, } from "@kandev/ui/dialog"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@kandev/ui/select"; import { IconInfoCircle } from "@tabler/icons-react"; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@kandev/ui/tooltip"; import { CliModeIcon } from "@/components/cli-mode-icon"; import { useAppStore } from "@/components/state-provider"; import { useSettingsData } from "@/hooks/domains/settings/use-settings-data"; import { useWorkflows } from "@/hooks/use-workflows"; import { useWorkflowSteps, stepPlaceholder } from "@/hooks/use-workflow-steps"; import { ScriptEditor, computeEditorHeight, } from "@/components/settings/profile-edit/script-editor"; import { LabelMultiSelect, PriorityMultiSelect, StateMultiSelect, useTeamsAndStates, } from "./linear-issue-watch-fields"; import { LINEAR_ISSUE_WATCH_PLACEHOLDERS } from "./linear-issue-watch-placeholders"; import { STEP_DEFAULT, STEP_DEFAULT_LABEL, resolveProfileId } from "@/lib/watcher-profile-default"; import { ASSIGNED_ANY, CREATOR_ANY, type FormState, type LinearPriority, buildWatchPayload, creatorPlaceholder, formStateFromWatch, isWatchFormReady, makeEmptyForm, parseMaxInflightTasks, userOptionLabel, } from "./linear-issue-watch-form"; import type { CreateLinearIssueWatchInput, LinearIssueWatch, LinearTeam, LinearUser, UpdateLinearIssueWatchInput, } from "@/lib/types/linear"; type Props = { open: boolean; onOpenChange: (open: boolean) => void; watch: LinearIssueWatch | null; workspaceId?: string; onCreate: (req: CreateLinearIssueWatchInput) => Promise; onUpdate: (id: string, req: UpdateLinearIssueWatchInput) => Promise; }; function useFormData(workspaceId: string) { useSettingsData(true); useWorkflows(workspaceId, true); const allWorkflows = useAppStore((s) => s.workflows.items); const workflows = useMemo(() => allWorkflows.filter((w) => !w.hidden), [allWorkflows]); const agentProfiles = useAppStore((s) => s.agentProfiles.items); const executors = useAppStore((s) => s.executors.items); const allExecutorProfiles = useMemo( () => executors .filter((e) => e.type !== "local" && e.type !== "local_pc") .flatMap((e) => e.profiles ?? []), [executors], ); return { workflows, agentProfiles, allExecutorProfiles }; } type SelectFieldItem = { id: string; label: string; icon?: React.ReactNode }; function SelectField(props: { label: string; description?: string; value: string; onChange: (v: string) => void; placeholder: string; items: SelectFieldItem[]; disabled?: boolean; }) { return (
{props.description &&

{props.description}

}
); } function FilterFields({ form, setForm, }: { form: FormState; setForm: React.Dispatch>; }) { const { teams, states, labels, users, loadingStates, loadingLabels, loadingUsers } = useTeamsAndStates(form.teamKey); const toggleState = useCallback( (id: string) => setForm((p) => ({ ...p, stateIds: p.stateIds.includes(id) ? p.stateIds.filter((s) => s !== id) : [...p.stateIds, id], })), [setForm], ); const toggleLabel = useCallback( (id: string) => setForm((p) => ({ ...p, labelIds: p.labelIds.includes(id) ? p.labelIds.filter((l) => l !== id) : [...p.labelIds, id], })), [setForm], ); const togglePriority = useCallback( (priority: LinearPriority) => setForm((p) => ({ ...p, priorities: p.priorities.includes(priority) ? p.priorities.filter((x) => x !== priority) : [...p.priorities, priority], })), [setForm], ); return ( <>

Click to toggle. Matches issues at ANY of the selected priorities.

{form.teamKey ? "Click states to toggle. Empty matches every state on the team." : "Pick a team to choose specific workflow states."}

{form.teamKey ? "Click to toggle. Matches ANY of the selected labels." : "Pick a team to choose specific labels."}

); } type FormSetter = React.Dispatch>; function TeamRow({ form, setForm, teams, }: { form: FormState; setForm: FormSetter; teams: LinearTeam[]; }) { return ( setForm((p) => ({ ...p, teamKey: v, stateIds: [], labelIds: [], creatorId: "" })) } placeholder="(any team)" items={teams.map((t) => ({ id: t.key, label: `${t.name} (${t.key})` }))} /> ); } function AssigneeAndCreatorRow({ form, setForm, users, loadingUsers, }: { form: FormState; setForm: FormSetter; users: LinearUser[]; loadingUsers: boolean; }) { return (
setForm((p) => ({ ...p, assigned: v === ASSIGNED_ANY ? "" : v }))} placeholder="(any)" items={[ { id: ASSIGNED_ANY, label: "(any)" }, { id: "me", label: "Me" }, { id: "unassigned", label: "Unassigned" }, ]} /> setForm((p) => ({ ...p, creatorId: v === CREATOR_ANY ? "" : v }))} placeholder={creatorPlaceholder(form.teamKey, loadingUsers)} items={[ { id: CREATOR_ANY, label: "(any)" }, ...users.map((u) => ({ id: u.id, label: userOptionLabel(u) })), ]} disabled={!form.teamKey || loadingUsers} />
); } function EstimateRow({ form, setForm }: { form: FormState; setForm: FormSetter }) { return (

Lower bound in points (optional).

setForm((p) => ({ ...p, estimateMin: e.target.value }))} min={0} step="0.5" placeholder="e.g. 1" />

Upper bound in points (optional).

setForm((p) => ({ ...p, estimateMax: e.target.value }))} min={0} step="0.5" placeholder="e.g. 5" />
); } function QueryField({ form, setForm }: { form: FormState; setForm: FormSetter }) { return (

Free-text match across title and description (optional).

setForm((p) => ({ ...p, query: e.target.value }))} placeholder="auth bug" />
); } function PlaceholdersHelp() { return (

Available placeholders:

    {LINEAR_ISSUE_WATCH_PLACEHOLDERS.map((p) => (
  • {`{{${p.key}}}`}{" "} {p.description}
  • ))}
); } function PromptField({ value, onChange }: { value: string; onChange: (v: string) => void }) { return (

The prompt sent to the agent for each new issue. Type {"{{"} to insert placeholders.

); } function WorkspacePicker({ value, onChange, disabled, }: { value: string; onChange: (v: string) => void; disabled?: boolean; }) { const workspaces = useAppStore((s) => s.workspaces.items); return ( ({ id: w.id, label: w.name }))} disabled={disabled} /> ); } function AutomationFields({ form, setForm, }: { form: FormState; setForm: React.Dispatch>; }) { const { workflows, agentProfiles, allExecutorProfiles } = useFormData(form.workspaceId); const { steps, loading: stepsLoading } = useWorkflowSteps(form.workflowId); return ( <>
setForm((p) => ({ ...p, workflowId: v, workflowStepId: "" }))} placeholder="Select workflow" items={workflows.map((w) => ({ id: w.id, label: w.name }))} /> setForm((p) => ({ ...p, workflowStepId: v }))} placeholder={stepPlaceholder(form.workflowId, stepsLoading, steps.length)} items={steps.map((s) => ({ id: s.id, label: s.name }))} disabled={!form.workflowId || stepsLoading || steps.length === 0} />
setForm((p) => ({ ...p, agentProfileId: resolveProfileId(v) }))} placeholder={STEP_DEFAULT_LABEL} items={[ { id: STEP_DEFAULT, label: STEP_DEFAULT_LABEL }, ...agentProfiles.map((p) => ({ id: p.id, label: p.label, icon: p.cli_passthrough ? : undefined, })), ]} /> setForm((p) => ({ ...p, executorProfileId: resolveProfileId(v) }))} placeholder={STEP_DEFAULT_LABEL} items={[ { id: STEP_DEFAULT, label: STEP_DEFAULT_LABEL }, ...allExecutorProfiles.map((p) => ({ id: p.id, label: p.name })), ]} />
); } function MaxInflightTasksField({ form, setForm, }: { form: FormState; setForm: React.Dispatch>; }) { const parsed = parseMaxInflightTasks(form.maxInflightTasks); const invalid = parsed === "invalid"; return (

Cap on open tasks created by this watcher. Leave blank for no cap. New matches are deferred to the next poll when the cap is reached.

setForm((p) => ({ ...p, maxInflightTasks: e.target.value }))} min={1} step={1} placeholder="(no cap)" aria-invalid={invalid} /> {invalid && (

Enter a positive integer or leave blank.

)}
); } function SettingsFields({ form, setForm, }: { form: FormState; setForm: React.Dispatch>; }) { return ( <>

How often to re-run the search. Minimum 60s, maximum 3600s.

setForm((p) => ({ ...p, pollInterval: Number(e.target.value) }))} min={60} max={3600} />

Pause or resume polling.

setForm((p) => ({ ...p, enabled: v }))} className="cursor-pointer" />
); } function savingLabel(saving: boolean, isEdit: boolean): string { if (saving) return "Saving…"; return isEdit ? "Update" : "Create"; } export function LinearIssueWatchDialog({ open, onOpenChange, watch, workspaceId, onCreate, onUpdate, }: Props) { const activeWorkspaceId = useAppStore((s) => s.workspaces.activeId); const [saving, setSaving] = useState(false); const [form, setForm] = useState(() => makeEmptyForm(workspaceId ?? "")); useEffect(() => { if (watch) { setForm(formStateFromWatch(watch)); } else { setForm(makeEmptyForm(workspaceId ?? activeWorkspaceId ?? "")); } }, [watch, open, workspaceId, activeWorkspaceId]); const workspaceLocked = !!watch || !!workspaceId; const canSave = isWatchFormReady(form); const handleSave = useCallback(async () => { const payload = buildWatchPayload(form); if (!payload) return; // re-checks the cap input — see canSave gate setSaving(true); try { if (watch) { await onUpdate(watch.id, payload); } else { await onCreate({ ...payload, workspaceId: form.workspaceId }); } onOpenChange(false); } catch { // Error surfaced by caller's toast. } finally { setSaving(false); } }, [form, watch, onCreate, onUpdate, onOpenChange]); return ( {watch ? "Edit Linear Watcher" : "Create Linear Watcher"} Poll Linear with a structured filter and auto-create a Kandev task for each newly-matching issue. Issues are not bound to a repository — the workflow step's defaults decide where the task runs.
setForm((p) => ({ ...p, workspaceId: v, workflowId: "", workflowStepId: "" })) } disabled={workspaceLocked} /> {/* Hairlines separate the five conceptual blocks (Destination / Filter / Automation / Prompt / Settings). Each block answers a different question, so a consistent rhythm helps users navigate the form visually instead of reading it as one long stack. */} setForm((p) => ({ ...p, prompt: v }))} />
); }