Files
kandev/apps/web/components/settings/settings-app-sidebar.tsx
T
João Salavisa 1b58a64fd8 feat(automations): /settings/automations with run-mode + per-automation config (#1016)
* feat: add automation system with triggers, backend-driven metadata, and PR association

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(automations): execution_mode + flat /settings/automations

Layered on top of #406's automation subsystem:

- Add execution_mode to Automation (task | run, default task). Run-mode
  firings create an ephemeral kanban-hidden task tagged with
  origin=automation_run. The session pipeline still runs against it, but
  users surface them through the AutomationRun history instead of the
  kanban. Pragmatic shim while AutomationRun-as-true-session-owner is
  deferred to a follow-up.

- Thread IsEphemeral + Origin through ReviewTaskRequest +
  reviewTaskCreatorAdapter so the orchestrator can create the hidden
  task in one call.

- Run-mode always auto-starts (the user never sees the task to drag).

- Flat /settings/automations route replaces the per-workspace sidebar
  entry. Picks the only workspace, shows a picker for many, or shows
  a CTA for zero workspaces.

- Editor exposes execution mode + table shows it as a badge column.

Spec at docs/specs/office/automations-settings.md documents the design,
deferred items, and scenarios.

* feat(automations): per-automation repository picker

Adds a repository_id field on Automation so users can pin scheduled and
webhook automations to a specific workspace repository instead of always
falling through to "first repo". github_pr triggers ignore the field and
keep using the PR's own repo — the editor disables the picker with a
hint when a PR trigger is selected.

Backend:
- repository_id column folded into the canonical CREATE TABLE (no
  migration needed — PR #406 introduces the table).
- RepositoryID threaded through model, DTOs, store INSERT/UPDATE, and
  service.CreateAutomation.
- resolveAutomationRepository prefers the explicit ID, falls back to
  workspace-first on empty.

Frontend:
- repository_id on the Automation TS type + Create/Update payloads.
- Repository SelectField in ConfigSection backed by useRepositories;
  "Auto" sentinel represents the empty/fallback choice.
- Disabled with help-text for github_pr triggers.

* feat(automations): repo picker shows discovered repos too

Matches the task-creation dialog's UX: the editor's repository picker
now lists registered workspace repos AND filesystem-discovered repos
under the workspace's roots. Picking a discovered repo registers it
with the workspace at save time (via createRepositoryAction), captures
the new id, and writes it onto the automation. After the first save
the picker selection is promoted from "discovered" to "registered" so
re-saving doesn't re-register.

Form state holds a RepositorySelection union (auto | registered |
discovered) rather than a plain id string so the picker can carry the
metadata needed to register.

github_pr triggers still disable the picker — PR events always override
any configured repo with the PR's own.

* fix(automations): add idempotent ALTERs for in-branch columns

The canonical CREATE TABLE covers fresh installs, but `CREATE TABLE
IF NOT EXISTS` is a no-op for DBs already initialised from an earlier
commit on this branch (PR #406's original schema). Without these
ALTERs, dev DBs created before execution_mode + repository_id existed
on the row hit "no such column" errors.

Three idempotent ALTERs: task_title_template, execution_mode,
repository_id. SQLite returns a duplicate-column error when the column
already exists; we swallow it.

* fix(automations): use generateUUID in non-secure contexts

crypto.randomUUID is only defined in secure contexts (HTTPS or
localhost). PR #406's editor used it directly, which throws "crypto.
randomUUID is not a function" when the app is reached via a plain
hostname like nova:58204. Switch to lib/utils.generateUUID, which
falls back to a Math.random-based implementation when crypto isn't
available.

* fix(automations): polish run-mode lifecycle, validation, and editor UX

Run-mode automations were partly broken end-to-end:
- workflow_id was sent for ephemeral tasks (rejected by task service)
  and was required by the editor + automation service, so "Create
  Automation" was always disabled and silently failed
- a permission_request hanging the agent left the run pinned at
  task_created forever; nothing reaped the ephemeral worktree
- trigger config inputs (cron, branches, authors) did not re-sync
  with the loaded automation on page reload
- runs row never linked back to the underlying task for task-mode
  automations, and the table header highlighted on hover

Backend
- skip workflow fields in CreateReviewTask / StartTask for run-mode
- relax automation.Service.CreateAutomation: workflow only required
  for task-mode
- auto-reject permission prompts on ephemeral automation tasks and
  mark the AutomationRun failed with the requested action
- on agent completion / failure for ephemeral automation tasks,
  flip the run to succeeded/failed and remove the worktree + branch
  immediately (new RunStatusSucceeded + MarkRunSucceededByTaskID)
- wire worktree.Manager into the orchestrator service

Frontend
- show Execution Mode first; hide Workflow / Workflow Step in run-mode
- canSave no longer requires workflow in run-mode
- surface save errors via toast instead of silent failure
- sync trigger-config local input state with loaded prop value
- runs table: clickable row → /tasks/<id> for task-mode runs,
  non-clickable in run-mode; suppress header hover

* fix(automations): address PR review feedback

Backend
- automation/scheduler.go: parseCronFields returns an error for
  unsupported expressions instead of silently defaulting to hourly
- automation/webhook.go: constant-time secret compare, header-only
  (no more ?secret= query param), reject with 409 when no enabled
  webhook trigger exists
- automation/service.go: enforce max_concurrent_runs in FireTrigger
  via maybeSkipForConcurrencyCap (records a skipped run when capped)
- cmd/kandev/e2e_reset.go: surface automation delete errors as 500
  instead of swallowing them
- orchestrator/event_handlers_git.go: auto-reject permission with
  cancelled=true so the message status is "rejected" and the session
  isn't flipped back to running
- orchestrator/event_handlers_agent.go: finalizeAutomationRunIfEphemeral
  now runs at the top of handleAgentFailed, before the resume/recoverable
  early returns, so session-backed run-mode failures get cleaned up

Frontend
- state/slices/automations/automations-slice.ts: declare _get/_api so
  the call site's arity matches and CodeQL stops flagging ignored
  trailing arguments
- automations/schedule-selector.tsx: clearing the input now propagates
  ""; cron is trimmed before validation+save
- automations/triggers-section.tsx: switching to webhook mode deletes
  the existing scheduled/condition triggers so they don't keep firing
  hidden in the background
- automations/trigger-configs/github-ci-config.tsx: useEffect re-sync
  for checkNames, matching the other trigger configs
- hooks/domains/settings/use-automations.ts: per-workspace fetch via
  loadedWorkspaceRef + render-safe loadedWorkspaceId state;
  inFlightWorkspaceRef discards stale responses after workspace switch

---------

Co-authored-by: Carlos Florêncio <carlosmflorencio@gmail.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Kandev Agent <agent@kandev.dev>
2026-05-22 22:01:59 +01:00

395 lines
14 KiB
TypeScript

"use client";
import { useEffect } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import {
IconSettings,
IconFolder,
IconRobot,
IconBell,
IconCode,
IconCpu,
IconKey,
IconMessageCircle,
IconBrandGithub,
IconBrandSlack,
IconHexagon,
IconSparkles,
IconWand,
IconGitBranch,
IconArrowsShuffle,
IconTicket,
IconPlugConnected,
IconBolt,
} from "@tabler/icons-react";
import {
Sidebar,
SidebarContent,
SidebarGroup,
SidebarGroupLabel,
SidebarGroupContent,
SidebarMenu,
SidebarMenuItem,
SidebarMenuButton,
SidebarMenuSub,
SidebarMenuSubItem,
SidebarMenuSubButton,
SidebarHeader,
useSidebar,
} from "@kandev/ui/sidebar";
import { ScrollArea } from "@kandev/ui/scroll-area";
import { ScrollOnOverflow } from "@kandev/ui/scroll-on-overflow";
import { useAppStore } from "@/components/state-provider";
import { useAvailableAgents } from "@/hooks/domains/settings/use-available-agents";
import { AgentLogo } from "@/components/agent-logo";
import { getExecutorIcon } from "@/lib/executor-icons";
import { getCapabilityWarning } from "@/lib/capability-warning";
import type { Agent, AgentProfile, Executor } from "@/lib/types/http";
import type { WorkspaceState } from "@/lib/state/slices";
type WorkspaceItem = WorkspaceState["items"][number];
type GeneralSidebarSectionProps = {
pathname: string;
};
function GeneralSidebarSection({ pathname }: GeneralSidebarSectionProps) {
return (
<SidebarMenuItem>
<SidebarMenuButton asChild tooltip="General">
<Link href="/settings/general">
<IconSettings className="h-4 w-4" />
<span>General</span>
</Link>
</SidebarMenuButton>
<SidebarMenuSub className="ml-3 mt-1">
<SidebarMenuSubItem>
<SidebarMenuSubButton
asChild
size="sm"
isActive={pathname === "/settings/general/notifications"}
>
<Link href="/settings/general/notifications">
<IconBell className="h-4 w-4" />
<span>Notifications</span>
</Link>
</SidebarMenuSubButton>
</SidebarMenuSubItem>
<SidebarMenuSubItem>
<SidebarMenuSubButton
asChild
size="sm"
isActive={pathname === "/settings/general/editors"}
>
<Link href="/settings/general/editors">
<IconCode className="h-4 w-4" />
<span>Editors</span>
</Link>
</SidebarMenuSubButton>
</SidebarMenuSubItem>
</SidebarMenuSub>
</SidebarMenuItem>
);
}
type WorkspacesSidebarSectionProps = {
pathname: string;
workspaces: WorkspaceItem[];
};
function WorkspacesSidebarSection({ pathname, workspaces }: WorkspacesSidebarSectionProps) {
return (
<SidebarMenuItem>
<SidebarMenuButton asChild tooltip="Workspaces">
<Link href="/settings/workspace">
<IconFolder className="h-4 w-4" />
<span>Workspaces</span>
</Link>
</SidebarMenuButton>
{workspaces.length > 0 && (
<SidebarMenuSub className="ml-3 mt-1">
{workspaces.map((workspace) => {
const workspacePath = `/settings/workspace/${workspace.id}`;
const workflowsPath = `${workspacePath}/workflows`;
const repositoriesPath = `${workspacePath}/repositories`;
return (
<SidebarMenuSubItem key={workspace.id}>
<SidebarMenuSubButton asChild isActive={pathname === workspacePath}>
<Link href={workspacePath}>
<span>{workspace.name}</span>
</Link>
</SidebarMenuSubButton>
<SidebarMenuSub className="ml-3">
<SidebarMenuSubItem>
<SidebarMenuSubButton
asChild
size="sm"
isActive={pathname === repositoriesPath}
>
<Link href={repositoriesPath}>
<IconGitBranch className="h-3.5 w-3.5" />
<span>Repositories</span>
</Link>
</SidebarMenuSubButton>
</SidebarMenuSubItem>
<SidebarMenuSubItem>
<SidebarMenuSubButton asChild size="sm" isActive={pathname === workflowsPath}>
<Link href={workflowsPath}>
<IconArrowsShuffle className="h-3.5 w-3.5" />
<span>Workflows</span>
</Link>
</SidebarMenuSubButton>
</SidebarMenuSubItem>
</SidebarMenuSub>
</SidebarMenuSubItem>
);
})}
</SidebarMenuSub>
)}
</SidebarMenuItem>
);
}
function IntegrationsSidebarSection({ pathname }: { pathname: string }) {
const items: Array<{ href: string; label: string; Icon: typeof IconBrandGithub }> = [
{ href: "/settings/integrations/github", label: "GitHub", Icon: IconBrandGithub },
{ href: "/settings/integrations/jira", label: "Jira", Icon: IconTicket },
{ href: "/settings/integrations/linear", label: "Linear", Icon: IconHexagon },
{ href: "/settings/integrations/slack", label: "Slack", Icon: IconBrandSlack },
];
return (
<SidebarMenuItem>
<SidebarMenuButton asChild tooltip="Integrations">
<Link href="/settings/integrations">
<IconPlugConnected className="h-4 w-4" />
<span>Integrations</span>
</Link>
</SidebarMenuButton>
<SidebarMenuSub className="ml-3 mt-1">
{items.map(({ href, label, Icon }) => (
<SidebarMenuSubItem key={href}>
<SidebarMenuSubButton asChild size="sm" isActive={pathname === href}>
<Link href={href}>
<Icon className="h-3.5 w-3.5" />
<span>{label}</span>
</Link>
</SidebarMenuSubButton>
</SidebarMenuSubItem>
))}
</SidebarMenuSub>
</SidebarMenuItem>
);
}
type AgentsSidebarSectionProps = {
pathname: string;
agents: Agent[];
};
function AgentsSidebarSection({ pathname, agents }: AgentsSidebarSectionProps) {
return (
<SidebarMenuItem>
<SidebarMenuButton asChild tooltip="Agents">
<Link href="/settings/agents">
<IconRobot className="h-4 w-4" />
<span>Agents</span>
</Link>
</SidebarMenuButton>
{agents.length > 0 && (
<SidebarMenuSub className="ml-3 mt-1">
{agents.flatMap((agent: Agent) =>
agent.profiles.map((profile: AgentProfile) => {
const encodedAgent = encodeURIComponent(agent.name);
const profilePath = `/settings/agents/${encodedAgent}/profiles/${profile.id}`;
const agentLabel = profile.agentDisplayName || agent.name;
const warning = getCapabilityWarning(agent.capability_status, agent.capability_error);
return (
<SidebarMenuSubItem key={profile.id} className="min-w-0">
<SidebarMenuSubButton asChild isActive={pathname === profilePath}>
<Link
href={profilePath}
className="!flex min-w-0 items-center gap-1.5"
title={warning?.title || `${agentLabel} • ${profile.name}`}
>
<AgentLogo agentName={agent.name} className="shrink-0" />
<ScrollOnOverflow className="min-w-0">
{agentLabel} • {profile.name}
</ScrollOnOverflow>
{warning && <warning.Icon className={`size-3.5 shrink-0 ${warning.color}`} />}
</Link>
</SidebarMenuSubButton>
</SidebarMenuSubItem>
);
}),
)}
</SidebarMenuSub>
)}
</SidebarMenuItem>
);
}
type ExecutorsSidebarSectionProps = {
pathname: string;
executors: Executor[];
};
function ExecutorsSidebarSection({ pathname, executors }: ExecutorsSidebarSectionProps) {
const allProfiles = executors.flatMap((e) =>
(e.profiles ?? []).map((p) => ({ ...p, executorType: e.type })),
);
return (
<SidebarMenuItem>
<SidebarMenuButton asChild tooltip="Executors" isActive={pathname === "/settings/executors"}>
<Link href="/settings/executors">
<IconCpu className="h-4 w-4" />
<span>Executors</span>
</Link>
</SidebarMenuButton>
{allProfiles.length > 0 && (
<SidebarMenuSub className="ml-3 mt-1">
{allProfiles.map((profile) => {
const Icon = getExecutorIcon(profile.executorType);
const profilePath = `/settings/executors/${profile.id}`;
return (
<SidebarMenuSubItem key={profile.id}>
<SidebarMenuSubButton asChild size="sm" isActive={pathname === profilePath}>
<Link href={profilePath} className="!flex items-center gap-1.5">
<Icon className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
<span>{profile.name}</span>
</Link>
</SidebarMenuSubButton>
</SidebarMenuSubItem>
);
})}
</SidebarMenuSub>
)}
</SidebarMenuItem>
);
}
function SecretsSidebarSection({ pathname }: { pathname: string }) {
return (
<SidebarMenuItem>
<SidebarMenuButton asChild isActive={pathname === "/settings/general/secrets"}>
<Link href="/settings/general/secrets">
<IconKey className="h-4 w-4" />
<span>Secrets</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
);
}
export function SettingsAppSidebar() {
const pathname = usePathname();
const { setOpenMobile, isMobile } = useSidebar();
const workspaces = useAppStore((state) => state.workspaces.items);
const executors = useAppStore((state) => state.executors.items);
const agents = useAppStore((state) => state.settingsAgents.items);
useAvailableAgents();
// Close mobile sidebar when navigating to a new page
useEffect(() => {
if (isMobile) {
setOpenMobile(false);
}
}, [pathname, isMobile, setOpenMobile]);
return (
<Sidebar variant="inset">
<SidebarHeader className="h-16 justify-center">
<SidebarMenu>
<SidebarMenuItem>
<SidebarMenuButton size="lg" asChild>
<Link href="/">
<span className="text-2xl font-bold">Kandev</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
</SidebarHeader>
<SidebarContent className="overflow-hidden">
<ScrollArea
className="h-full [&_[data-slot=scroll-area-viewport]>div]:!block [&_[data-slot=scroll-area-viewport]>div]:!min-w-0"
type="always"
>
<SidebarGroup>
<SidebarGroupLabel>Settings</SidebarGroupLabel>
<SidebarGroupContent>
<SidebarMenu>
<GeneralSidebarSection pathname={pathname} />
<WorkspacesSidebarSection pathname={pathname} workspaces={workspaces} />
<IntegrationsSidebarSection pathname={pathname} />
<AgentsSidebarSection pathname={pathname} agents={agents} />
{/* Prompts */}
<SidebarMenuItem>
<SidebarMenuButton asChild isActive={pathname === "/settings/prompts"}>
<Link href="/settings/prompts">
<IconMessageCircle className="h-4 w-4" />
<span>Prompts</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
{/* Utility Agents */}
<SidebarMenuItem>
<SidebarMenuButton asChild isActive={pathname === "/settings/utility-agents"}>
<Link href="/settings/utility-agents">
<IconWand className="h-4 w-4" />
<span>Utility Agents</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
<ExecutorsSidebarSection pathname={pathname} executors={executors} />
{/* Automations */}
<SidebarMenuItem>
<SidebarMenuButton
asChild
isActive={
pathname.startsWith("/settings/automations") ||
pathname.includes("/automations")
}
>
<Link href="/settings/automations">
<IconBolt className="h-4 w-4" />
<span>Automations</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
<SecretsSidebarSection pathname={pathname} />
{/* External MCP */}
<SidebarMenuItem>
<SidebarMenuButton asChild isActive={pathname === "/settings/external-mcp"}>
<Link href="/settings/external-mcp">
<IconPlugConnected className="h-4 w-4" />
<span>External MCP</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
{/* Changelog */}
<SidebarMenuItem>
<SidebarMenuButton asChild isActive={pathname === "/settings/changelog"}>
<Link href="/settings/changelog">
<IconSparkles className="h-4 w-4" />
<span>Changelog</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
</ScrollArea>
</SidebarContent>
</Sidebar>
);
}