refactor: move integrations to top-level settings with install-wide configs (#787)

* refactor: move integrations to top-level settings with install-wide configs

Jira and Linear configurations are now install-wide singletons rather than
per-workspace duplicates, and the GitHub/Jira/Linear settings pages live
under /settings/integrations instead of being nested inside each workspace.
Issue and PR watchers stay per-workspace via a workspace switcher inside
each integration page. Backend ships one-shot migrations that promote the
most-recently-updated row and copy its secret onto the new global key.

* fix: address review feedback on integrations refactor

Fix migration crash on installs whose jira_configs predate the auth-health
columns by selecting only guaranteed-present legacy columns and falling back
to defaults for the rest. Cover the empty-legacy-table and pre-health-columns
upgrade paths with new store tests.

On the frontend, refactor useIntegrationEnabled to take string parameters
instead of an inline options object so getSnapshot stays referentially stable
across renders, and stop dispatching a misleading no-op sync event when
localStorage.setItem fails in private mode.

* fix: hydrate workspace list on integration settings pages

The integration pages wrapped their content in a fresh StateProvider, which
created a nested store scope with an empty initial state and shadowed the
settings layout's hydrated workspace list. WorkspaceScopedSection then saw
zero workspaces and rendered the "Create a workspace to configure this
integration" empty state even when the user had workspaces.

Drop the redundant StateProvider from the jira and linear pages so they share
the layout's store. The github page switches to StateHydrator so it can still
seed the GitHub OAuth status without resetting the rest of the store.

* refactor(integrations): flatten watcher tables, pick workspace in create dialog

Hiding watchers behind a workspace switcher made the list invisible at a
glance — a user with multiple workspaces had to flip between each one to
see what was configured. Replace the switcher with a flat table that lists
every watch across every workspace, with a Workspace column for context, and
move workspace selection into the create dialog so the user picks once when
the watcher is born.

Backend: jira list-issue-watches and github list-review-watches /
list-issue-watches accept the workspace_id query param as optional; when
omitted, the corresponding store ListAll* method returns rows across every
workspace. Per-row mutations still require workspace_id as the IDOR guard.

Frontend: useReviewWatches / useIssueWatches / useJiraIssueWatches gain a
three-state contract — string for one workspace, undefined for all
workspaces, null to skip fetching. Watch tables grow an optional
showWorkspace column. Watch dialogs accept an optional workspaceId prop;
when absent, the dialog renders a workspace dropdown for the create flow
(disabled when editing existing rows so refs aren't orphaned). Github
review-watch-dialog crossed the 600-line lint cap so the prompt editor
moved to review-watch-prompt-field.tsx.

* fix(integrations): make watcher step dropdown reactive across workspace switches

Switching to a workspace whose workflows had to be fetched left the workflow
step dropdown stuck — the user could pick a workflow but the step Select
either showed the previous workflow's steps or appeared inert. The cause was
the per-dialog useWorkflowSteps hook deferring its empty-state reset via
Promise.resolve().then(() => setSteps([])) to dodge a setState-in-effect
lint rule, which let stale steps survive into the next render and gave Radix
nothing to anchor the popover to during the in-flight fetch.

Hoist the hook into a shared useWorkflowSteps that resets via React's
official setState-during-render pattern, exposes a loading flag, and returns
a stepPlaceholder helper so the Select can render "Loading steps…" or "No
steps in this workflow" instead of an empty popover. The Step Select is now
also disabled while loading or when there are no steps, making the state of
the dropdown unambiguous.

* fix: address PR review feedback on integrations refactor

Backend:
- linear migration: add column-presence guard mirroring the Jira fix so
  installs that upgraded from the original Linear schema (without org_slug
  / last_checked_at / last_ok / last_error) don't crash startup with
  "no such column"; add TestStore_MigrateLegacyPerWorkspaceTable_PreHealthColumns
- jira/handlers.go: drop the now-unused errMsgWorkspaceIDRequired constant
  that was failing golangci-lint
- jira/mock_controller_test.go (new): cover setAuthHealth happy-path and
  invalid-JSON-rejection so the singleton-shaped payload is locked in

Frontend:
- useIntegrationAvailable: gate the auth-health probe on loaded && enabled
  so disabled integrations don't poll /config every 90s
- use-workflow-steps: initialize loading to !!workflowId so edit-mode opens
  show "Loading steps…" instead of "No steps in this workflow" before the
  first fetch lands
- use-workflow-steps.test.ts (new): cover the empty/non-empty workflowId,
  workflow switch, fetch error, and stepPlaceholder branches
- use-linear-enabled.test: tighten the legacy-key migration assertion to
  pin the migrated value rather than just verifying key cleanup

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
This commit is contained in:
João Salavisa
2026-05-03 10:22:57 +01:00
committed by GitHub
parent 9e8e9d7dde
commit bb36cb9e01
93 changed files with 2729 additions and 1881 deletions
+59 -43
View File
@@ -18,13 +18,10 @@ import { DefaultQueriesSection } from "./default-queries-section";
import { PRStatsPanel } from "./pr-stats";
import { useReviewWatches } from "@/hooks/domains/github/use-review-watches";
import { useIssueWatches } from "@/hooks/domains/github/use-issue-watches";
import { WorkspaceScopedSection } from "@/components/integrations/workspace-scoped-section";
import type { ReviewWatch, IssueWatch } from "@/lib/types/github";
type GitHubSettingsProps = {
workspaceId: string;
};
function useWatchActions(workspaceId: string | null) {
function useWatchActions(workspaceId?: string | null) {
const { items: watches, create, update, remove, trigger } = useReviewWatches(workspaceId);
const { toast } = useToast();
@@ -78,7 +75,7 @@ function useWatchActions(workspaceId: string | null) {
return { watches, create, update, handleDelete, handleTrigger, handleToggleEnabled };
}
function useIssueWatchActions(workspaceId: string | null) {
function useIssueWatchActions(workspaceId?: string | null) {
const { items: watches, create, update, remove, trigger } = useIssueWatches(workspaceId);
const { toast } = useToast();
@@ -132,49 +129,67 @@ function useIssueWatchActions(workspaceId: string | null) {
return { watches, create, update, handleDelete, handleTrigger, handleToggleEnabled };
}
export function GitHubSettings({ workspaceId }: GitHubSettingsProps) {
export function GitHubConnectionSection() {
return (
<>
<div>
<h2 className="text-2xl font-bold flex items-center gap-2">
<IconBrandGithub className="h-6 w-6" />
GitHub Integration
</h2>
<p className="text-sm text-muted-foreground mt-1">
Connect Kandev to GitHub. Authentication is shared across all workspaces; PR/issue
watchers and presets are configured per workspace.
</p>
</div>
<Separator />
<SettingsSection title="Connection Status" description="GitHub authentication status">
<Card>
<CardContent className="py-3">
<GitHubStatusCard />
</CardContent>
</Card>
</SettingsSection>
</>
);
}
// PerWorkspaceSection wraps the still-per-workspace surfaces (action presets,
// PR analytics) under a workspace switcher. Watchers don't go in here — they
// list flat across every workspace via their own sections.
function PerWorkspaceSection({ workspaceId }: { workspaceId: string }) {
return (
<div className="space-y-8">
<ActionPresetsSection workspaceId={workspaceId} />
<SettingsSection title="PR Analytics" description="Pull request activity for this workspace.">
<PRStatsPanel workspaceId={workspaceId} />
</SettingsSection>
</div>
);
}
export function GitHubIntegrationPage() {
return (
<TooltipProvider>
<div className="space-y-8">
<div>
<h2 className="text-2xl font-bold flex items-center gap-2">
<IconBrandGithub className="h-6 w-6" />
GitHub Integration
</h2>
<p className="text-sm text-muted-foreground mt-1">
Configure GitHub PR monitoring, issue tracking, and review queue automation.
</p>
</div>
<Separator />
<SettingsSection title="Connection Status" description="GitHub authentication status">
<Card>
<CardContent className="py-3">
<GitHubStatusCard />
</CardContent>
</Card>
</SettingsSection>
<ReviewWatchSection workspaceId={workspaceId} />
<IssueWatchSection workspaceId={workspaceId} />
<ActionPresetsSection workspaceId={workspaceId} />
<GitHubConnectionSection />
<ReviewWatchSection />
<IssueWatchSection />
<WorkspaceScopedSection label="Presets and analytics for">
{(ws) => <PerWorkspaceSection key={ws} workspaceId={ws} />}
</WorkspaceScopedSection>
<DefaultQueriesSection />
<SettingsSection
title="PR Analytics"
description="Pull request activity for this workspace."
>
<PRStatsPanel workspaceId={workspaceId} />
</SettingsSection>
</div>
</TooltipProvider>
);
}
function ReviewWatchSection({ workspaceId }: { workspaceId: string }) {
// ReviewWatchSection lists every review watch across every workspace in a
// single flat table. Pass `undefined` to the hook so it fetches all rows; the
// dialog's create flow asks the user to pick the workspace.
function ReviewWatchSection() {
const { watches, create, update, handleDelete, handleTrigger, handleToggleEnabled } =
useWatchActions(workspaceId);
useWatchActions(undefined);
const { toast } = useToast();
const [dialogOpen, setDialogOpen] = useState(false);
const [editingWatch, setEditingWatch] = useState<ReviewWatch | null>(null);
@@ -207,6 +222,7 @@ function ReviewWatchSection({ workspaceId }: { workspaceId: string }) {
<CardContent className="p-0">
<ReviewWatchTable
watches={watches}
showWorkspace
onEdit={handleEdit}
onDelete={handleDelete}
onTrigger={handleTrigger}
@@ -219,7 +235,7 @@ function ReviewWatchSection({ workspaceId }: { workspaceId: string }) {
open={dialogOpen}
onOpenChange={setDialogOpen}
watch={editingWatch}
workspaceId={workspaceId}
// No workspaceId — dialog shows a workspace picker for new watches.
onCreate={async (req) => {
await create(req);
toast({ description: "Review watch created", variant: "success" });
@@ -233,8 +249,8 @@ function ReviewWatchSection({ workspaceId }: { workspaceId: string }) {
);
}
function IssueWatchSection({ workspaceId }: { workspaceId: string }) {
const issueActions = useIssueWatchActions(workspaceId);
function IssueWatchSection() {
const issueActions = useIssueWatchActions(undefined);
const { toast } = useToast();
const [dialogOpen, setDialogOpen] = useState(false);
const [editingWatch, setEditingIssueWatch] = useState<IssueWatch | null>(null);
@@ -267,6 +283,7 @@ function IssueWatchSection({ workspaceId }: { workspaceId: string }) {
<CardContent className="p-0">
<IssueWatchTable
watches={issueActions.watches}
showWorkspace
onEdit={handleEdit}
onDelete={issueActions.handleDelete}
onTrigger={issueActions.handleTrigger}
@@ -279,7 +296,6 @@ function IssueWatchSection({ workspaceId }: { workspaceId: string }) {
open={dialogOpen}
onOpenChange={setDialogOpen}
watch={editingWatch}
workspaceId={workspaceId}
onCreate={async (req) => {
await issueActions.create(req);
toast({ description: "Issue watch created", variant: "success" });
@@ -20,7 +20,7 @@ import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@kande
import { useAppStore } from "@/components/state-provider";
import { useSettingsData } from "@/hooks/domains/settings/use-settings-data";
import { useWorkflows } from "@/hooks/use-workflows";
import { listWorkflowSteps } from "@/lib/api/domains/workflow-api";
import { useWorkflowSteps, stepPlaceholder } from "@/hooks/use-workflow-steps";
import {
ScriptEditor,
computeEditorHeight,
@@ -41,12 +41,15 @@ type IssueWatchDialogProps = {
open: boolean;
onOpenChange: (open: boolean) => void;
watch: IssueWatch | null;
workspaceId: string;
// Pre-binds the dialog to one workspace. Omit on the install-wide settings
// page so the create flow shows a workspace picker.
workspaceId?: string;
onCreate: (req: CreateIssueWatchRequest) => Promise<void>;
onUpdate: (id: string, req: UpdateIssueWatchRequest) => Promise<void>;
};
type FormState = {
workspaceId: string;
selectedRepos: RepoFilter[];
allRepos: boolean;
workflowId: string;
@@ -60,27 +63,29 @@ type FormState = {
pollInterval: number;
};
type WorkflowStepOption = { id: string; name: string };
const DEFAULT_QUERY = "type:issue state:open";
const defaultFormState: FormState = {
selectedRepos: [],
allRepos: false,
workflowId: "",
workflowStepId: "",
agentProfileId: "",
executorProfileId: "",
prompt: DEFAULT_ISSUE_WATCH_PROMPT,
labels: "",
customQuery: DEFAULT_QUERY,
enabled: true,
pollInterval: 300,
};
function makeDefaultForm(workspaceId: string): FormState {
return {
workspaceId,
selectedRepos: [],
allRepos: false,
workflowId: "",
workflowStepId: "",
agentProfileId: "",
executorProfileId: "",
prompt: DEFAULT_ISSUE_WATCH_PROMPT,
labels: "",
customQuery: DEFAULT_QUERY,
enabled: true,
pollInterval: 300,
};
}
function formStateFromWatch(watch: IssueWatch): FormState {
const hasRepos = watch.repos && watch.repos.length > 0;
return {
workspaceId: watch.workspace_id,
selectedRepos: hasRepos ? watch.repos : [],
allRepos: !hasRepos,
workflowId: watch.workflow_id,
@@ -95,32 +100,6 @@ function formStateFromWatch(watch: IssueWatch): FormState {
};
}
function useWorkflowSteps(workflowId: string) {
const [steps, setSteps] = useState<WorkflowStepOption[]>([]);
useEffect(() => {
if (!workflowId) {
void Promise.resolve().then(() => setSteps([]));
return;
}
let cancelled = false;
listWorkflowSteps(workflowId)
.then((response) => {
if (cancelled) return;
const sorted = [...response.steps].sort((a, b) => a.position - b.position);
setSteps(sorted.map((s) => ({ id: s.id, name: s.name })));
})
.catch(() => {
if (!cancelled) setSteps([]);
});
return () => {
cancelled = true;
};
}, [workflowId]);
return steps;
}
function useWatchFormData(workspaceId: string) {
useSettingsData(true);
useWorkflows(workspaceId, true);
@@ -179,25 +158,39 @@ function PlaceholdersHelp() {
function IssueWatchFormFields({
form,
setForm,
workspaceId,
workspaceLocked,
onAllReposChange,
onSelectedReposChange,
}: {
form: FormState;
setForm: React.Dispatch<React.SetStateAction<FormState>>;
workspaceId: string;
workspaceLocked: boolean;
onAllReposChange: (checked: boolean) => void;
onSelectedReposChange: (repos: RepoFilter[]) => void;
}) {
return (
<div className="space-y-5">
<WorkspacePicker
value={form.workspaceId}
onChange={(v) =>
setForm((prev) => ({
...prev,
workspaceId: v,
workflowId: "",
workflowStepId: "",
selectedRepos: [],
allRepos: false,
}))
}
disabled={workspaceLocked}
/>
<IssueFilterFields
form={form}
setForm={setForm}
onAllReposChange={onAllReposChange}
onSelectedReposChange={onSelectedReposChange}
/>
<IssueAutomationFields form={form} setForm={setForm} workspaceId={workspaceId} />
<IssueAutomationFields form={form} setForm={setForm} />
<IssueSettingsFields form={form} setForm={setForm} />
</div>
);
@@ -254,14 +247,12 @@ function IssueFilterFields({
function IssueAutomationFields({
form,
setForm,
workspaceId,
}: {
form: FormState;
setForm: React.Dispatch<React.SetStateAction<FormState>>;
workspaceId: string;
}) {
const { workflows, agentProfiles, allExecutorProfiles } = useWatchFormData(workspaceId);
const workflowSteps = useWorkflowSteps(form.workflowId);
const { workflows, agentProfiles, allExecutorProfiles } = useWatchFormData(form.workspaceId);
const { steps: workflowSteps, loading: stepsLoading } = useWorkflowSteps(form.workflowId);
return (
<>
@@ -280,8 +271,9 @@ function IssueAutomationFields({
description="Initial step for new tasks."
value={form.workflowStepId}
onChange={(v) => setForm((prev) => ({ ...prev, workflowStepId: v }))}
placeholder={form.workflowId ? "Select step" : "Select a workflow first"}
placeholder={stepPlaceholder(form.workflowId, stepsLoading, workflowSteps.length)}
items={workflowSteps.map((s) => ({ id: s.id, label: s.name }))}
disabled={!form.workflowId || stepsLoading || workflowSteps.length === 0}
/>
</div>
<div className="grid grid-cols-2 gap-4">
@@ -382,12 +374,19 @@ export function IssueWatchDialog({
onCreate,
onUpdate,
}: IssueWatchDialogProps) {
const activeWorkspaceId = useAppStore((s) => s.workspaces.activeId);
const [saving, setSaving] = useState(false);
const [form, setForm] = useState<FormState>(defaultFormState);
const [form, setForm] = useState<FormState>(() => makeDefaultForm(workspaceId ?? ""));
useEffect(() => {
setForm(watch ? formStateFromWatch(watch) : defaultFormState);
}, [watch, open]);
if (watch) {
setForm(formStateFromWatch(watch));
} else {
setForm(makeDefaultForm(workspaceId ?? activeWorkspaceId ?? ""));
}
}, [watch, open, workspaceId, activeWorkspaceId]);
const workspaceLocked = !!watch || !!workspaceId;
const handleSelectedReposChange = useCallback((repos: RepoFilter[]) => {
setForm((prev) => ({ ...prev, selectedRepos: repos }));
@@ -420,7 +419,7 @@ export function IssueWatchDialog({
if (watch) {
await onUpdate(watch.id, payload);
} else {
await onCreate({ ...payload, workspace_id: workspaceId });
await onCreate({ ...payload, workspace_id: form.workspaceId });
}
onOpenChange(false);
} catch {
@@ -428,9 +427,13 @@ export function IssueWatchDialog({
} finally {
setSaving(false);
}
}, [form, watch, workspaceId, onCreate, onUpdate, onOpenChange]);
}, [form, watch, onCreate, onUpdate, onOpenChange]);
const canSave = !!form.workflowId && !!form.workflowStepId && form.prompt.trim().length > 0;
const canSave =
!!form.workspaceId &&
!!form.workflowId &&
!!form.workflowStepId &&
form.prompt.trim().length > 0;
return (
<Dialog open={open} onOpenChange={onOpenChange}>
@@ -444,7 +447,7 @@ export function IssueWatchDialog({
<IssueWatchFormFields
form={form}
setForm={setForm}
workspaceId={workspaceId}
workspaceLocked={workspaceLocked}
onAllReposChange={handleAllReposChange}
onSelectedReposChange={handleSelectedReposChange}
/>
@@ -468,12 +471,17 @@ function SelectField(props: {
onChange: (v: string) => void;
placeholder: string;
items: { id: string; label: string }[];
disabled?: boolean;
}) {
return (
<div className="space-y-1.5">
<Label>{props.label}</Label>
{props.description && <p className="text-xs text-muted-foreground">{props.description}</p>}
<Select value={props.value || undefined} onValueChange={props.onChange}>
<Select
value={props.value || undefined}
onValueChange={props.onChange}
disabled={props.disabled}
>
<SelectTrigger className="cursor-pointer">
<SelectValue placeholder={props.placeholder} />
</SelectTrigger>
@@ -488,3 +496,26 @@ function SelectField(props: {
</div>
);
}
function WorkspacePicker({
value,
onChange,
disabled,
}: {
value: string;
onChange: (v: string) => void;
disabled?: boolean;
}) {
const workspaces = useAppStore((s) => s.workspaces.items);
return (
<SelectField
label="Workspace"
description="Tasks created by this watcher land in the selected workspace."
value={value}
onChange={onChange}
placeholder="Select workspace"
items={workspaces.map((w) => ({ id: w.id, label: w.name }))}
disabled={disabled}
/>
);
}
@@ -6,10 +6,14 @@ import { Badge } from "@kandev/ui/badge";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@kandev/ui/table";
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
import { useToast } from "@/components/toast-provider";
import { useAppStore } from "@/components/state-provider";
import type { IssueWatch } from "@/lib/types/github";
type IssueWatchTableProps = {
watches: IssueWatch[];
// showWorkspace renders a Workspace column when the table aggregates rows
// from every workspace (install-wide settings page).
showWorkspace?: boolean;
onEdit: (watch: IssueWatch) => void;
onDelete: (id: string) => void;
onTrigger: (id: string) => void;
@@ -109,11 +113,15 @@ function WatchActions({ watch, onToggleEnabled, onTrigger, onDelete }: WatchActi
export function IssueWatchTable({
watches,
showWorkspace,
onEdit,
onDelete,
onTrigger,
onToggleEnabled,
}: IssueWatchTableProps) {
const workspaces = useAppStore((s) => s.workspaces.items);
const workspaceName = (id: string) => workspaces.find((w) => w.id === id)?.name ?? id;
if (watches.length === 0) {
return (
<p className="text-sm text-muted-foreground py-4 text-center">
@@ -126,6 +134,7 @@ export function IssueWatchTable({
<Table>
<TableHeader>
<TableRow>
{showWorkspace && <TableHead>Workspace</TableHead>}
<TableHead>Repository</TableHead>
<TableHead>Labels</TableHead>
<TableHead>Interval</TableHead>
@@ -137,6 +146,11 @@ export function IssueWatchTable({
<TableBody>
{watches.map((watch) => (
<TableRow key={watch.id} className="cursor-pointer" onClick={() => onEdit(watch)}>
{showWorkspace && (
<TableCell className="text-xs text-muted-foreground">
{workspaceName(watch.workspace_id)}
</TableCell>
)}
<TableCell className="font-medium">{formatRepoNames(watch)}</TableCell>
<TableCell className="text-xs text-muted-foreground">
{formatLabels(watch) || "—"}
@@ -20,15 +20,13 @@ import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@kande
import { useAppStore } from "@/components/state-provider";
import { useSettingsData } from "@/hooks/domains/settings/use-settings-data";
import { useWorkflows } from "@/hooks/use-workflows";
import { listWorkflowSteps } from "@/lib/api/domains/workflow-api";
import {
ScriptEditor,
computeEditorHeight,
} from "@/components/settings/profile-edit/script-editor";
import {
REVIEW_WATCH_PLACEHOLDERS,
DEFAULT_REVIEW_WATCH_PROMPT,
} from "@/components/github/review-watch-placeholders";
useWorkflowSteps,
stepPlaceholder,
type WorkflowStepOption,
} from "@/hooks/use-workflow-steps";
import { DEFAULT_REVIEW_WATCH_PROMPT } from "@/components/github/review-watch-placeholders";
import { ReviewWatchPromptField } from "@/components/github/review-watch-prompt-field";
import { RepoFilterSelector } from "@/components/github/repo-filter-selector";
import type {
RepoFilter,
@@ -41,7 +39,9 @@ type ReviewWatchDialogProps = {
open: boolean;
onOpenChange: (open: boolean) => void;
watch: ReviewWatch | null;
workspaceId: string;
// Pre-binds the dialog to one workspace; omit on the install-wide settings
// page so the create flow shows a workspace picker.
workspaceId?: string;
onCreate: (req: CreateReviewWatchRequest) => Promise<void>;
onUpdate: (id: string, req: UpdateReviewWatchRequest) => Promise<void>;
};
@@ -52,6 +52,7 @@ const QUERY_TEMPLATES = {
} as const;
type FormState = {
workspaceId: string;
selectedRepos: RepoFilter[];
allRepos: boolean;
workflowId: string;
@@ -64,24 +65,26 @@ type FormState = {
pollInterval: number;
};
type WorkflowStepOption = { id: string; name: string };
const defaultFormState: FormState = {
selectedRepos: [],
allRepos: false,
workflowId: "",
workflowStepId: "",
agentProfileId: "",
executorProfileId: "",
prompt: DEFAULT_REVIEW_WATCH_PROMPT,
customQuery: QUERY_TEMPLATES.meAndTeams,
enabled: true,
pollInterval: 300,
};
function makeDefaultForm(workspaceId: string): FormState {
return {
workspaceId,
selectedRepos: [],
allRepos: false,
workflowId: "",
workflowStepId: "",
agentProfileId: "",
executorProfileId: "",
prompt: DEFAULT_REVIEW_WATCH_PROMPT,
customQuery: QUERY_TEMPLATES.meAndTeams,
enabled: true,
pollInterval: 300,
};
}
function formStateFromWatch(watch: ReviewWatch): FormState {
const hasRepos = watch.repos && watch.repos.length > 0;
return {
workspaceId: watch.workspace_id,
selectedRepos: hasRepos ? watch.repos : [],
allRepos: !hasRepos,
workflowId: watch.workflow_id,
@@ -104,6 +107,7 @@ type SelectFieldProps = {
onChange: (value: string) => void;
placeholder: string;
items: Array<{ id: string; label: string }>;
disabled?: boolean;
};
function SelectField({
@@ -113,12 +117,13 @@ function SelectField({
onChange,
placeholder,
items,
disabled,
}: SelectFieldProps) {
return (
<div className="space-y-1.5">
<Label>{label}</Label>
{description && <p className="text-xs text-muted-foreground">{description}</p>}
<Select value={value || undefined} onValueChange={onChange}>
<Select value={value || undefined} onValueChange={onChange} disabled={disabled}>
<SelectTrigger className="cursor-pointer">
<SelectValue placeholder={placeholder} />
</SelectTrigger>
@@ -134,34 +139,31 @@ function SelectField({
);
}
// --- Hooks ---
function useWorkflowSteps(workflowId: string) {
const [steps, setSteps] = useState<WorkflowStepOption[]>([]);
useEffect(() => {
if (!workflowId) {
void Promise.resolve().then(() => setSteps([]));
return;
}
let cancelled = false;
listWorkflowSteps(workflowId)
.then((response) => {
if (cancelled) return;
const sorted = [...response.steps].sort((a, b) => a.position - b.position);
setSteps(sorted.map((s) => ({ id: s.id, name: s.name })));
})
.catch(() => {
if (!cancelled) setSteps([]);
});
return () => {
cancelled = true;
};
}, [workflowId]);
return steps;
function WorkspacePicker({
value,
onChange,
disabled,
}: {
value: string;
onChange: (v: string) => void;
disabled?: boolean;
}) {
const workspaces = useAppStore((s) => s.workspaces.items);
return (
<SelectField
label="Workspace"
description="Tasks created by this watcher land in the selected workspace."
value={value}
onChange={onChange}
placeholder="Select workspace"
items={workspaces.map((w) => ({ id: w.id, label: w.name }))}
disabled={disabled}
/>
);
}
// --- Hooks ---
function useWatchFormData(workspaceId: string) {
useSettingsData(true);
useWorkflows(workspaceId, true);
@@ -272,18 +274,18 @@ function QueryField({
function WatchFormFields({
form,
setForm,
workspaceId,
workspaceLocked,
onAllReposChange,
onSelectedReposChange,
}: {
form: FormState;
setForm: React.Dispatch<React.SetStateAction<FormState>>;
workspaceId: string;
workspaceLocked: boolean;
onAllReposChange: (checked: boolean) => void;
onSelectedReposChange: (repos: RepoFilter[]) => void;
}) {
const { workflows, agentProfiles, allExecutorProfiles } = useWatchFormData(workspaceId);
const workflowSteps = useWorkflowSteps(form.workflowId);
const { workflows, agentProfiles, allExecutorProfiles } = useWatchFormData(form.workspaceId);
const { steps: workflowSteps, loading: stepsLoading } = useWorkflowSteps(form.workflowId);
const handleWorkflowChange = useCallback(
(v: string) => {
@@ -294,6 +296,23 @@ function WatchFormFields({
return (
<div className="space-y-5">
<WorkspacePicker
value={form.workspaceId}
onChange={(v) =>
setForm((prev) => ({
...prev,
workspaceId: v,
// Switching workspace invalidates workflow/step refs since those
// are workspace-scoped IDs.
workflowId: "",
workflowStepId: "",
// Repo selections are tied to the workspace's repository list too.
selectedRepos: [],
allRepos: false,
}))
}
disabled={workspaceLocked}
/>
<SectionHeader>Filter</SectionHeader>
<RepoFilterSelector
allRepos={form.allRepos}
@@ -308,6 +327,7 @@ function WatchFormFields({
setForm={setForm}
workflows={workflows}
workflowSteps={workflowSteps}
stepsLoading={stepsLoading}
onWorkflowChange={handleWorkflowChange}
/>
<ProfileFields
@@ -316,7 +336,10 @@ function WatchFormFields({
agentProfiles={agentProfiles}
executorProfiles={allExecutorProfiles}
/>
<PromptField form={form} setForm={setForm} />
<ReviewWatchPromptField
value={form.prompt}
onChange={(v) => setForm((prev) => ({ ...prev, prompt: v }))}
/>
<SectionHeader>Settings</SectionHeader>
<SettingsFields form={form} setForm={setForm} />
</div>
@@ -328,12 +351,14 @@ function WorkflowFields({
setForm,
workflows,
workflowSteps,
stepsLoading,
onWorkflowChange,
}: {
form: FormState;
setForm: React.Dispatch<React.SetStateAction<FormState>>;
workflows: Array<{ id: string; name: string }>;
workflowSteps: WorkflowStepOption[];
stepsLoading: boolean;
onWorkflowChange: (v: string) => void;
}) {
return (
@@ -351,8 +376,9 @@ function WorkflowFields({
description="Initial step for new tasks. Auto-start is set on the step."
value={form.workflowStepId}
onChange={(v) => setForm((prev) => ({ ...prev, workflowStepId: v }))}
placeholder={form.workflowId ? "Select step" : "Select a workflow first"}
placeholder={stepPlaceholder(form.workflowId, stepsLoading, workflowSteps.length)}
items={workflowSteps.map((s) => ({ id: s.id, label: s.name }))}
disabled={!form.workflowId || stepsLoading || workflowSteps.length === 0}
/>
</div>
);
@@ -420,69 +446,6 @@ function ProfileFields({
);
}
function PlaceholdersHelp() {
return (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<IconInfoCircle className="h-3.5 w-3.5 text-muted-foreground/50 hover:text-muted-foreground cursor-help shrink-0" />
</TooltipTrigger>
<TooltipContent className="max-w-xs" align="start">
<p className="text-xs font-medium mb-1">Available placeholders:</p>
<ul className="text-xs space-y-0.5">
{REVIEW_WATCH_PLACEHOLDERS.map((p) => (
<li key={p.key}>
<code className="text-[10px] bg-white/15 px-1 rounded">{`{{${p.key}}}`}</code>{" "}
<span className="opacity-70">{p.description}</span>
</li>
))}
</ul>
</TooltipContent>
</Tooltip>
</TooltipProvider>
);
}
function PromptField({
form,
setForm,
}: {
form: FormState;
setForm: React.Dispatch<React.SetStateAction<FormState>>;
}) {
return (
<div className="space-y-1.5">
<div className="flex items-center gap-1.5">
<Label>Task Prompt</Label>
<PlaceholdersHelp />
</div>
<p className="text-xs text-muted-foreground">
The prompt sent to the agent for each new PR. Type {"{{"} to insert placeholders.
</p>
<div className="rounded-md border border-border overflow-hidden">
<ScriptEditor
value={form.prompt}
onChange={(v) => setForm((prev) => ({ ...prev, prompt: v }))}
language="markdown"
height={computeEditorHeight(form.prompt)}
lineNumbers="off"
placeholders={REVIEW_WATCH_PLACEHOLDERS}
/>
</div>
<p className="text-xs text-muted-foreground/70">
The workflow step prompt wraps this prompt. For example, if the step prompt is{" "}
<code className="text-[10px] bg-muted px-1 rounded">
{"Analyze the task: {{task_prompt}}"}
</code>
, the final prompt becomes{" "}
<code className="text-[10px] bg-muted px-1 rounded">
{"Analyze the task: Pull Request ready for review: https://..."}
</code>
</p>
</div>
);
}
function SettingsFields({
form,
setForm,
@@ -533,12 +496,19 @@ export function ReviewWatchDialog({
onCreate,
onUpdate,
}: ReviewWatchDialogProps) {
const activeWorkspaceId = useAppStore((s) => s.workspaces.activeId);
const [saving, setSaving] = useState(false);
const [form, setForm] = useState<FormState>(defaultFormState);
const [form, setForm] = useState<FormState>(() => makeDefaultForm(workspaceId ?? ""));
useEffect(() => {
setForm(watch ? formStateFromWatch(watch) : defaultFormState);
}, [watch, open]);
if (watch) {
setForm(formStateFromWatch(watch));
} else {
setForm(makeDefaultForm(workspaceId ?? activeWorkspaceId ?? ""));
}
}, [watch, open, workspaceId, activeWorkspaceId]);
const workspaceLocked = !!watch || !!workspaceId;
const handleSelectedReposChange = useCallback((repos: RepoFilter[]) => {
setForm((prev) => ({ ...prev, selectedRepos: repos }));
@@ -570,7 +540,7 @@ export function ReviewWatchDialog({
if (watch) {
await onUpdate(watch.id, payload);
} else {
await onCreate({ ...payload, workspace_id: workspaceId });
await onCreate({ ...payload, workspace_id: form.workspaceId });
}
onOpenChange(false);
} catch {
@@ -578,9 +548,10 @@ export function ReviewWatchDialog({
} finally {
setSaving(false);
}
}, [form, watch, workspaceId, onCreate, onUpdate, onOpenChange]);
}, [form, watch, onCreate, onUpdate, onOpenChange]);
const canSave =
!!form.workspaceId &&
form.customQuery.trim().length > 0 &&
!!form.workflowId &&
!!form.workflowStepId &&
@@ -598,7 +569,7 @@ export function ReviewWatchDialog({
<WatchFormFields
form={form}
setForm={setForm}
workspaceId={workspaceId}
workspaceLocked={workspaceLocked}
onAllReposChange={handleAllReposChange}
onSelectedReposChange={handleSelectedReposChange}
/>
@@ -0,0 +1,77 @@
"use client";
import { IconInfoCircle } from "@tabler/icons-react";
import { Label } from "@kandev/ui/label";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@kandev/ui/tooltip";
import {
ScriptEditor,
computeEditorHeight,
} from "@/components/settings/profile-edit/script-editor";
import { REVIEW_WATCH_PLACEHOLDERS } from "@/components/github/review-watch-placeholders";
// Pulled out of review-watch-dialog.tsx to keep that file under the 600-line
// linter cap; the prompt editor + its placeholder help bubble are co-owned by
// this single screen and aren't reused elsewhere.
function PlaceholdersHelp() {
return (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<IconInfoCircle className="h-3.5 w-3.5 text-muted-foreground/50 hover:text-muted-foreground cursor-help shrink-0" />
</TooltipTrigger>
<TooltipContent className="max-w-xs" align="start">
<p className="text-xs font-medium mb-1">Available placeholders:</p>
<ul className="text-xs space-y-0.5">
{REVIEW_WATCH_PLACEHOLDERS.map((p) => (
<li key={p.key}>
<code className="text-[10px] bg-white/15 px-1 rounded">{`{{${p.key}}}`}</code>{" "}
<span className="opacity-70">{p.description}</span>
</li>
))}
</ul>
</TooltipContent>
</Tooltip>
</TooltipProvider>
);
}
export function ReviewWatchPromptField({
value,
onChange,
}: {
value: string;
onChange: (v: string) => void;
}) {
return (
<div className="space-y-1.5">
<div className="flex items-center gap-1.5">
<Label>Task Prompt</Label>
<PlaceholdersHelp />
</div>
<p className="text-xs text-muted-foreground">
The prompt sent to the agent for each new PR. Type {"{{"} to insert placeholders.
</p>
<div className="rounded-md border border-border overflow-hidden">
<ScriptEditor
value={value}
onChange={onChange}
language="markdown"
height={computeEditorHeight(value)}
lineNumbers="off"
placeholders={REVIEW_WATCH_PLACEHOLDERS}
/>
</div>
<p className="text-xs text-muted-foreground/70">
The workflow step prompt wraps this prompt. For example, if the step prompt is{" "}
<code className="text-[10px] bg-muted px-1 rounded">
{"Analyze the task: {{task_prompt}}"}
</code>
, the final prompt becomes{" "}
<code className="text-[10px] bg-muted px-1 rounded">
{"Analyze the task: Pull Request ready for review: https://..."}
</code>
</p>
</div>
);
}
@@ -6,10 +6,14 @@ import { Badge } from "@kandev/ui/badge";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@kandev/ui/table";
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
import { useToast } from "@/components/toast-provider";
import { useAppStore } from "@/components/state-provider";
import type { ReviewWatch } from "@/lib/types/github";
type ReviewWatchTableProps = {
watches: ReviewWatch[];
// showWorkspace renders a Workspace column when the table aggregates rows
// from every workspace (install-wide settings page).
showWorkspace?: boolean;
onEdit: (watch: ReviewWatch) => void;
onDelete: (id: string) => void;
onTrigger: (id: string) => void;
@@ -104,11 +108,15 @@ function WatchActions({ watch, onToggleEnabled, onTrigger, onDelete }: WatchActi
export function ReviewWatchTable({
watches,
showWorkspace,
onEdit,
onDelete,
onTrigger,
onToggleEnabled,
}: ReviewWatchTableProps) {
const workspaces = useAppStore((s) => s.workspaces.items);
const workspaceName = (id: string) => workspaces.find((w) => w.id === id)?.name ?? id;
if (watches.length === 0) {
return (
<p className="text-sm text-muted-foreground py-4 text-center">
@@ -121,6 +129,7 @@ export function ReviewWatchTable({
<Table>
<TableHeader>
<TableRow>
{showWorkspace && <TableHead>Workspace</TableHead>}
<TableHead>Repository</TableHead>
<TableHead>Interval</TableHead>
<TableHead>Last Polled</TableHead>
@@ -131,6 +140,11 @@ export function ReviewWatchTable({
<TableBody>
{watches.map((watch) => (
<TableRow key={watch.id} className="cursor-pointer" onClick={() => onEdit(watch)}>
{showWorkspace && (
<TableCell className="text-xs text-muted-foreground">
{workspaceName(watch.workspace_id)}
</TableCell>
)}
<TableCell className="font-medium">{formatRepoNames(watch)}</TableCell>
<TableCell className="text-xs text-muted-foreground">
{Math.round(watch.poll_interval_seconds / 60)}m