"use client"; import { useCallback, useEffect, useId, useMemo, useState } from "react"; import { Alert, AlertDescription } from "@kandev/ui/alert"; import { Button } from "@kandev/ui/button"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@kandev/ui/dialog"; import { Input } from "@kandev/ui/input"; import { Label } from "@kandev/ui/label"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@kandev/ui/select"; import { IconAlertTriangle } from "@tabler/icons-react"; import { useAppStore } from "@/components/state-provider"; import { useFeature } from "@/hooks/domains/features/use-feature"; import { WatcherRepositoryFields } from "@/components/watcher-repository-fields"; import { useSettingsData } from "@/hooks/domains/settings/use-settings-data"; import { useWorkflowSteps, stepPlaceholder } from "@/hooks/use-workflow-steps"; import { useWorkflows } from "@/hooks/use-workflows"; import { STEP_DEFAULT, resolveProfileId } from "@/lib/watcher-profile-default"; import { isSelectableAgentProfile } from "@/lib/state/slices/settings/types"; import type { CreateIssueWatchRequest, CreateReviewWatchRequest, UpdateIssueWatchRequest, UpdateReviewWatchRequest, } from "@/lib/api/domains/gitlab-api"; import type { IssueWatch, ReviewWatch } from "@/lib/types/gitlab"; import { buildWatchPayload, makeWatchForm, watchFormFromWatch, type GitLabWatchForm, type GitLabWatchKind, } from "./watch-form"; import { useTranslation } from "react-i18next"; import type { TFunction } from "i18next"; import { SettingsPromptEditor } from "@/components/settings/settings-prompt-editor"; import { gitlabIssueWatchPlaceholders } from "./issue-watch-placeholders"; import { gitlabReviewWatchPlaceholders } from "./review-watch-placeholders"; type Watch = ReviewWatch | IssueWatch; type CreateRequest = CreateReviewWatchRequest | CreateIssueWatchRequest; type UpdateRequest = UpdateReviewWatchRequest | UpdateIssueWatchRequest; export type GitLabWatchDialogProps = { kind: GitLabWatchKind; open: boolean; onOpenChange: (open: boolean) => void; watch: Watch | null; workspaceId: string; onCreate: (request: CreateRequest) => Promise; onUpdate: (id: string, request: UpdateRequest) => Promise; }; type SelectItemShape = { id: string; label: string }; function SelectField(props: { label: string; description: string; value: string; onChange: (value: string) => void; placeholder: string; items: SelectItemShape[]; disabled?: boolean; }) { const id = useId(); return (

{props.description}

); } function SectionTitle({ children }: { children: React.ReactNode }) { return

{children}

; } function useDialogData(workspaceId: string, workflowId: string) { useSettingsData(true); useWorkflows(workspaceId, true); const workflows = useAppStore((state) => state.workflows.items).filter((item) => !item.hidden); const agentProfiles = useAppStore((state) => state.agentProfiles.items); const dynamicRoutingEnabled = useFeature("dynamicAgentRouting"); const selectableAgentProfiles = useMemo( () => agentProfiles.filter((profile) => isSelectableAgentProfile(profile, dynamicRoutingEnabled)), [agentProfiles, dynamicRoutingEnabled], ); const executors = useAppStore((state) => state.executors.items); const executorProfiles = useMemo( () => executors .filter((item) => item.type !== "local" && item.type !== "local_pc") .flatMap((item) => item.profiles ?? []), [executors], ); const { steps, loading } = useWorkflowSteps(workflowId); return { workflows, agentProfiles: selectableAgentProfiles, executorProfiles, steps, stepsLoading: loading, }; } function FilterFields({ kind, form, setForm }: FormFieldsProps) { const { t } = useTranslation(); return (
{t("gitlab:match")}

{t("gitlab:optionalCommaSeparatedNamespaceProjectPaths")}

setForm((current) => ({ ...current, projectPaths: event.target.value })) } // Sample namespace/project paths, i.e. the shape of the GitLab data the // field accepts. Not copy — a translated "group" would stop being a // usable example. // eslint-disable-next-line i18next/no-literal-string -- example project paths placeholder="group/api, group/web" />
{kind === "issue" && (

{t("gitlab:optionalCommaSeparatedGitlabLabelsThat")}

setForm((current) => ({ ...current, labels: event.target.value }))} // Sample GitLab label names — user data, like the labels the user // will actually type here. // eslint-disable-next-line i18next/no-literal-string -- example label names placeholder="bug, priority::high" />
)}

{kind === "review" ? t("gitlab:leaveEmptyToMatchMergeRequests") : // The example is a literal GitLab API query string, so it is // interpolated rather than written into the catalog — a translated // (or pseudo-transliterated) copy of it would not parse. t("gitlab:optionalGitlabApiQueryParametersSuch", { example: "state=opened&milestone=Next", })}

setForm((current) => ({ ...current, customQuery: event.target.value })) } // A literal GitLab API query parameter. It is submitted to GitLab // verbatim, so it is protocol, not copy. // eslint-disable-next-line i18next/no-literal-string -- GitLab API query parameter placeholder="state=opened" className="font-mono text-xs" />
{kind === "review" && ( setForm((current) => ({ ...current, reviewScope: value as GitLabWatchForm["reviewScope"], })) } placeholder={t("gitlab:directRequests")} items={[ { id: "user", label: t("gitlab:directRequests") }, { id: "user_and_teams", label: t("gitlab:directAndGroupCompatibleRequests") }, ]} /> )}
); } type FormFieldsProps = { kind: GitLabWatchKind; form: GitLabWatchForm; setForm: React.Dispatch>; }; function AutomationFields({ kind, form, setForm }: FormFieldsProps) { const { t } = useTranslation(); const stepDefaultLabel = t("common:useStepDefaultOption"); const data = useDialogData(form.workspaceId, form.workflowId); const placeholders = useMemo( () => (kind === "review" ? gitlabReviewWatchPlaceholders(t) : gitlabIssueWatchPlaceholders(t)), [kind, t], ); return (
{t("gitlab:taskAutomation")}
setForm((current) => ({ ...current, workflowId, workflowStepId: "" })) } placeholder={t("gitlab:selectWorkflow")} items={data.workflows.map((item) => ({ id: item.id, label: item.name }))} /> setForm((current) => ({ ...current, workflowStepId }))} placeholder={stepPlaceholder(form.workflowId, data.stepsLoading, data.steps.length)} items={data.steps.map((item) => ({ id: item.id, label: item.name }))} disabled={!form.workflowId || data.stepsLoading || data.steps.length === 0} />
setForm((current) => ({ ...current, repositoryId, baseBranch: "" })) } onBaseBranchChange={(baseBranch) => setForm((current) => ({ ...current, baseBranch }))} />
setForm((current) => ({ ...current, agentProfileId: resolveProfileId(value) })) } placeholder={stepDefaultLabel} items={[ { id: STEP_DEFAULT, label: stepDefaultLabel }, ...data.agentProfiles.map((item) => ({ id: item.id, label: item.label })), ]} /> setForm((current) => ({ ...current, executorProfileId: resolveProfileId(value) })) } placeholder={stepDefaultLabel} items={[ { id: STEP_DEFAULT, label: stepDefaultLabel }, ...data.executorProfiles.map((item) => ({ id: item.id, label: item.name })), ]} />

{t("gitlab:promptSentToTheSelectedAgent")}

setForm((current) => ({ ...current, prompt: value }))} placeholders={placeholders} promptReferences ariaLabel={t("gitlab:taskPrompt")} testId={`${kind}-watch-prompt-editor`} help={

{t("gitlab:promptSentToTheSelectedAgent")}

} />
); } function ScheduleFields({ kind, form, setForm }: FormFieldsProps) { const { t } = useTranslation(); return (
{t("gitlab:pollingAndCleanup")}

{t("gitlab:between60And3600Seconds")}

setForm((current) => ({ ...current, pollIntervalSeconds: event.target.value })) } />

{t("gitlab:optionalCapPollingResumesWhenActive")}

setForm((current) => ({ ...current, maxInflightTasks: event.target.value })) } placeholder={t("gitlab:noLimit")} />
setForm((current) => ({ ...current, cleanupPolicy: value as GitLabWatchForm["cleanupPolicy"], })) } placeholder={t("gitlab:auto")} items={[ { id: "auto", label: t("gitlab:autoKeepEngagedTasks") }, { id: "always", label: t("gitlab:alwaysDelete") }, { id: "never", label: t("gitlab:neverDelete") }, ]} />
); } function dialogTitle(t: TFunction, kind: GitLabWatchKind, editing: boolean): string { if (kind === "review") { return editing ? t("gitlab:editReviewWatch") : t("gitlab:createReviewWatch"); } return editing ? t("gitlab:editIssueWatch") : t("gitlab:createIssueWatch"); } export function GitLabWatchDialog({ kind, open, onOpenChange, watch, workspaceId, onCreate, onUpdate, }: GitLabWatchDialogProps) { const { t } = useTranslation(); const [form, setForm] = useState(() => makeWatchForm(kind, workspaceId)); const [saving, setSaving] = useState(false); const [error, setError] = useState(""); useEffect(() => { setForm(watch ? watchFormFromWatch(kind, watch) : makeWatchForm(kind, workspaceId)); setError(""); }, [kind, open, watch, workspaceId]); const payload = buildWatchPayload(kind as "review", form, Boolean(watch)) as CreateRequest | null; const save = useCallback(async () => { if (!payload) return; setSaving(true); setError(""); try { if (watch) { const { workspace_id: _workspaceId, ...update } = payload; await onUpdate(watch.id, update); } else { await onCreate(payload); } onOpenChange(false); } catch (cause) { setError(cause instanceof Error ? cause.message : t("gitlab:gitlabWatchCouldNotBeSaved")); } finally { setSaving(false); } }, [onCreate, onOpenChange, onUpdate, payload, t, watch]); let saveLabel = t("gitlab:createWatch"); if (watch) saveLabel = t("gitlab:updateWatch"); if (saving) saveLabel = t("gitlab:saving"); return ( {/* Four whole sentences rather than "Edit"/"Create" + a `kind` noun: `kind` is the wire discriminant and must never be translated, and splicing a translated noun into a translated stem fixes English word order. */} {dialogTitle(t, kind, Boolean(watch))} {kind === "review" ? t("gitlab:reviewWatchDialogDescription") : t("gitlab:issueWatchDialogDescription")} {error && ( {error} )}
); }