Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(autopilots): unified create/edit dialog with issue-modal layout (#1501)
Naiyuan Qingcd6bb4828364
diff --git a/packages/views/autopilots/components/autopilot-detail-page.tsx b/packages/views/autopilots/components/autopilot-detail-page.tsxindex 7fc92f8e47..f87fa8a0de 100644--- a/packages/views/autopilots/components/autopilot-detail-page.tsx+++ b/packages/views/autopilots/components/autopilot-detail-page.tsx@@ -1,6 +1,6 @@"use client";-import { useState, useEffect } from "react";+import { useState } from "react";import { Zap, Play, Clock, Plus, Trash2, CheckCircle2, XCircle, Loader2, Pencil } from "lucide-react";import { useQuery } from "@tanstack/react-query";import { autopilotDetailOptions, autopilotRunsOptions } from "@multica/core/autopilots/queries";@@ -11,7 +11,6 @@ import {useCreateAutopilotTrigger,useDeleteAutopilotTrigger,} from "@multica/core/autopilots/mutations";-import { agentListOptions } from "@multica/core/workspace/queries";import { useWorkspaceId } from "@multica/core/hooks";import { useWorkspacePaths } from "@multica/core/paths";import { useActorName } from "@multica/core/workspace/hooks";@@ -28,20 +27,15 @@ import {DialogContent,DialogTitle,} from "@multica/ui/components/ui/dialog";-import {- Select,- SelectTrigger,- SelectValue,- SelectContent,- SelectItem,-} from "@multica/ui/components/ui/select";import {TriggerConfigSection,getDefaultTriggerConfig,toCronExpression,} from "./trigger-config";import type { TriggerConfig } from "./trigger-config";-import type { AutopilotRun, AutopilotTrigger } from "@multica/core/types";+import type { AutopilotExecutionMode, AutopilotRun, AutopilotTrigger } from "@multica/core/types";+import { ReadonlyContent } from "../../editor";+import { AutopilotDialog } from "./autopilot-dialog";function formatDate(date: string): string {return new Date(date).toLocaleString(undefined, {@@ -138,170 +132,6 @@ function TriggerRow({ trigger, autopilotId }: { trigger: AutopilotTrigger; autop);}-const PRIORITY_OPTIONS = [- { value: "urgent", label: "Urgent" },- { value: "high", label: "High" },- { value: "medium", label: "Medium" },- { value: "low", label: "Low" },- { value: "none", label: "None" },-];--const EXECUTION_MODE_OPTIONS = [- { value: "create_issue", label: "Create Issue" },- { value: "run_only", label: "Run Only" },-];--function EditAutopilotDialog({- open,- onOpenChange,- autopilot,- agents,-}: {- open: boolean;- onOpenChange: (open: boolean) => void;- autopilot: { id: string; title: string; description?: string | null; assignee_id: string; priority: string; execution_mode: string; issue_title_template?: string | null };- agents: { id: string; name: string; archived_at?: string | null }[];-}) {- const updateAutopilot = useUpdateAutopilot();- const [title, setTitle] = useState(autopilot.title);- const [description, setDescription] = useState(autopilot.description ?? "");- const [assigneeId, setAssigneeId] = useState(autopilot.assignee_id);- const [priority, setPriority] = useState(autopilot.priority);- const [executionMode, setExecutionMode] = useState(autopilot.execution_mode);- const [submitting, setSubmitting] = useState(false);-- const activeAgents = agents.filter((a) => !a.archived_at);-- // Sync form when autopilot data changes (e.g. after optimistic update)- useEffect(() => {- setTitle(autopilot.title);- setDescription(autopilot.description ?? "");- setAssigneeId(autopilot.assignee_id);- setPriority(autopilot.priority);- setExecutionMode(autopilot.execution_mode);- }, [autopilot]);-- const handleSubmit = async () => {- if (!title.trim() || !assigneeId || submitting) return;- setSubmitting(true);- try {- await updateAutopilot.mutateAsync({- id: autopilot.id,- title: title.trim(),- description: description.trim() || null,- assignee_id: assigneeId,- priority,- execution_mode: executionMode as "create_issue" | "run_only",- });- onOpenChange(false);- toast.success("Autopilot updated");- } catch {- toast.error("Failed to update autopilot");- } finally {- setSubmitting(false);- }- };-- return (- <Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent className="max-w-lg">- <DialogTitle>Edit Autopilot</DialogTitle>- <div className="space-y-4 pt-2">- {/* Name */}- <div>- <label className="text-xs font-medium text-muted-foreground">Name</label>- <input- type="text"- value={title}- onChange={(e) => setTitle(e.target.value)}- placeholder="e.g. Daily code review"- className="mt-1 w-full rounded-md border bg-background px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring"- autoFocus- />- </div>-- {/* Prompt */}- <div>- <label className="text-xs font-medium text-muted-foreground">Prompt</label>- <textarea- value={description}- onChange={(e) => setDescription(e.target.value)}- placeholder="Step-by-step instructions for the agent..."- rows={6}- className="mt-1 w-full rounded-md border bg-background px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring resize-y"- />- </div>-- {/* Agent + Priority */}- <div className="grid grid-cols-2 gap-3">- <div>- <label className="text-xs font-medium text-muted-foreground">Agent</label>- <Select value={assigneeId} onValueChange={(v) => v && setAssigneeId(v)}>- <SelectTrigger className="mt-1 w-full">- <SelectValue>- {(value: string | null) => {- if (!value) return "Select agent...";- const agent = activeAgents.find((a) => a.id === value);- return agent?.name ?? "Unknown Agent";- }}- </SelectValue>- </SelectTrigger>- <SelectContent>- {activeAgents.map((a) => (- <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>- ))}- </SelectContent>- </Select>- </div>- <div>- <label className="text-xs font-medium text-muted-foreground">Priority</label>- <Select value={priority} onValueChange={(v) => v && setPriority(v)}>- <SelectTrigger className="mt-1 w-full">- <SelectValue>- {(value: string | null) => PRIORITY_OPTIONS.find((o) => o.value === value)?.label ?? "Medium"}- </SelectValue>- </SelectTrigger>- <SelectContent>- {PRIORITY_OPTIONS.map((o) => (- <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>- ))}- </SelectContent>- </Select>- </div>- </div>-- {/* Execution Mode */}- <div>- <label className="text-xs font-medium text-muted-foreground">Execution Mode</label>- <Select value={executionMode} onValueChange={(v) => v && setExecutionMode(v)}>- <SelectTrigger className="mt-1 w-full">- <SelectValue>- {(value: string | null) => EXECUTION_MODE_OPTIONS.find((o) => o.value === value)?.label ?? "Create Issue"}- </SelectValue>- </SelectTrigger>- <SelectContent>- {EXECUTION_MODE_OPTIONS.map((o) => (- <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>- ))}- </SelectContent>- </Select>- </div>-- {/* Actions */}- <div className="flex justify-end gap-2 pt-1">- <Button size="sm" variant="outline" onClick={() => onOpenChange(false)}>- Cancel- </Button>- <Button size="sm" onClick={handleSubmit} disabled={!title.trim() || !assigneeId || submitting}>- {submitting ? "Saving..." : "Save"}- </Button>- </div>- </div>- </DialogContent>- </Dialog>- );-}-function AddTriggerDialog({open,onOpenChange,@@ -375,7 +205,6 @@ export function AutopilotDetailPage({ autopilotId }: { autopilotId: string }) {const { data, isLoading } = useQuery(autopilotDetailOptions(wsId, autopilotId));const { data: runs = [], isLoading: runsLoading } = useQuery(autopilotRunsOptions(wsId, autopilotId));- const { data: agents = [] } = useQuery(agentListOptions(wsId));const updateAutopilot = useUpdateAutopilot();const deleteAutopilot = useDeleteAutopilot();const triggerAutopilot = useTriggerAutopilot();@@ -521,7 +350,9 @@ export function AutopilotDetailPage({ autopilotId }: { autopilotId: string }) {{autopilot.description && (<div className="col-span-2"><label className="text-xs text-muted-foreground">Prompt</label>- <div className="mt-1 whitespace-pre-wrap text-sm">{autopilot.description}</div>+ <div className="mt-1">+ <ReadonlyContent content={autopilot.description} />+ </div></div>)}</div>@@ -587,12 +418,22 @@ export function AutopilotDetailPage({ autopilotId }: { autopilotId: string }) {onOpenChange={setTriggerDialogOpen}autopilotId={autopilotId}/>- <EditAutopilotDialog- open={editDialogOpen}- onOpenChange={setEditDialogOpen}- autopilot={autopilot}- agents={agents}- />+ {editDialogOpen && (+ <AutopilotDialog+ mode="edit"+ open={editDialogOpen}+ onOpenChange={setEditDialogOpen}+ autopilotId={autopilot.id}+ initial={{+ title: autopilot.title,+ description: autopilot.description ?? "",+ assignee_id: autopilot.assignee_id,+ priority: autopilot.priority,+ execution_mode: autopilot.execution_mode as AutopilotExecutionMode,+ }}+ triggers={triggers}+ />+ )}</div>);}diff --git a/packages/views/autopilots/components/autopilot-dialog.tsx b/packages/views/autopilots/components/autopilot-dialog.tsxnew file mode 100644index 0000000000..aa13aa51cc--- /dev/null+++ b/packages/views/autopilots/components/autopilot-dialog.tsx@@ -0,0 +1,350 @@+"use client";++import { useRef, useState } from "react";+import { toast } from "sonner";+import { Calendar, ChevronRight, Maximize2, Minimize2, Rocket, X as XIcon } from "lucide-react";+import { cn } from "@multica/ui/lib/utils";+import {+ Dialog,+ DialogContent,+ DialogTitle,+} from "@multica/ui/components/ui/dialog";+import { Tooltip, TooltipTrigger, TooltipContent } from "@multica/ui/components/ui/tooltip";+import { Button } from "@multica/ui/components/ui/button";+import { useCurrentWorkspace } from "@multica/core/paths";+import {+ useCreateAutopilot,+ useCreateAutopilotTrigger,+ useUpdateAutopilot,+ useUpdateAutopilotTrigger,+} from "@multica/core/autopilots/mutations";+import type {+ AutopilotExecutionMode,+ AutopilotTrigger,+ IssuePriority,+} from "@multica/core/types";+import { TitleEditor, ContentEditor } from "../../editor";+import { PillButton } from "../../common/pill-button";+import { PriorityPicker } from "../../issues/components/pickers";+import {+ getDefaultTriggerConfig,+ parseCronExpression,+ summarizeTrigger,+ toCronExpression,+ type TriggerConfig,+} from "./trigger-config";+import { AgentPicker } from "./pickers/agent-picker";+import { ExecutionModePicker } from "./pickers/execution-mode-picker";+import { SchedulePicker } from "./pickers/schedule-picker";++// ---------------------------------------------------------------------------+// Types+// ---------------------------------------------------------------------------++export interface AutopilotInitial {+ title: string;+ description: string;+ assignee_id: string;+ priority: string;+ execution_mode: AutopilotExecutionMode;+}++export type AutopilotDialogProps =+ | {+ mode: "create";+ open: boolean;+ onOpenChange: (v: boolean) => void;+ initial?: Partial<AutopilotInitial>;+ initialTriggerConfig?: Partial<TriggerConfig>;+ }+ | {+ mode: "edit";+ open: boolean;+ onOpenChange: (v: boolean) => void;+ autopilotId: string;+ initial: AutopilotInitial;+ triggers: AutopilotTrigger[];+ };++// ---------------------------------------------------------------------------+// AutopilotDialog — shared Create/Edit dialog for autopilots+// ---------------------------------------------------------------------------++export function AutopilotDialog(props: AutopilotDialogProps) {+ const { open, onOpenChange } = props;+ const workspaceName = useCurrentWorkspace()?.name;+ const [isExpanded, setIsExpanded] = useState(false);++ const isCreate = props.mode === "create";+ const initial: Partial<AutopilotInitial> = isCreate ? props.initial ?? {} : props.initial;+ const [title, setTitle] = useState(initial.title ?? "");+ const [description, setDescription] = useState(initial.description ?? "");+ const [assigneeId, setAssigneeId] = useState<string>(initial.assignee_id ?? "");+ const [priority, setPriority] = useState<string>(initial.priority ?? "medium");+ const [executionMode, setExecutionMode] = useState<AutopilotExecutionMode>(+ initial.execution_mode ?? "create_issue",+ );++ const initialCfg: TriggerConfig = (() => {+ if (isCreate) {+ const tpl = props.initialTriggerConfig;+ return tpl ? { ...getDefaultTriggerConfig(), ...tpl } : getDefaultTriggerConfig();+ }+ const first = props.triggers[0];+ if (first?.cron_expression) {+ return parseCronExpression(first.cron_expression, first.timezone ?? "UTC");+ }+ return getDefaultTriggerConfig();+ })();+ const [triggerConfig, setTriggerConfig] = useState<TriggerConfig>(initialCfg);+ // Snapshot initial cron payload at mount so `scheduleDirty` only flips when+ // the payload actually changes (prevents phantom trigger creates when the+ // user opens the popover, clicks the already-active option, then Saves).+ const initialCronRef = useRef(toCronExpression(initialCfg));+ const initialTimezoneRef = useRef(initialCfg.timezone);+ const scheduleDirty =+ toCronExpression(triggerConfig) !== initialCronRef.current ||+ triggerConfig.timezone !== initialTimezoneRef.current;++ // Snapshot the first-trigger id at mount. Parent `triggers` prop can update+ // mid-dialog via WS refetch — we want Save to act on the trigger we showed.+ const firstTriggerIdRef = useRef(+ !isCreate && props.triggers[0] ? props.triggers[0].id : null,+ );++ const triggerCount = isCreate ? 0 : props.triggers.length;+ const schedulePillDisabled = !isCreate && triggerCount >= 2;++ const schedulePillLabel = (() => {+ if (isCreate) return summarizeTrigger(triggerConfig);+ if (triggerCount === 0) return "Add schedule";+ if (triggerCount === 1) return summarizeTrigger(triggerConfig);+ return `${triggerCount} schedules`;+ })();++ const createAutopilot = useCreateAutopilot();+ const createTrigger = useCreateAutopilotTrigger();+ const updateAutopilot = useUpdateAutopilot();+ const updateTrigger = useUpdateAutopilotTrigger();+ const [submitting, setSubmitting] = useState(false);++ const canSubmit = title.trim().length > 0 && assigneeId.length > 0 && !submitting;++ const handleSubmit = async () => {+ if (!canSubmit) return;+ setSubmitting(true);+ try {+ if (isCreate) {+ const autopilot = await createAutopilot.mutateAsync({+ title: title.trim(),+ description: description.trim() || undefined,+ assignee_id: assigneeId,+ priority,+ execution_mode: executionMode,+ });+ let scheduleOk = true;+ try {+ await createTrigger.mutateAsync({+ autopilotId: autopilot.id,+ kind: "schedule",+ cron_expression: toCronExpression(triggerConfig),+ timezone: triggerConfig.timezone,+ });+ } catch {+ scheduleOk = false;+ }+ onOpenChange(false);+ if (scheduleOk) toast.success("Autopilot created");+ else toast.error("Autopilot created, but schedule failed to save");+ } else {+ await updateAutopilot.mutateAsync({+ id: props.autopilotId,+ title: title.trim(),+ description: description.trim() || null,+ assignee_id: assigneeId,+ priority,+ execution_mode: executionMode,+ });+ // Schedule: patch the trigger we snapshotted at mount, else create one.+ let scheduleOk = true;+ if (scheduleDirty && !schedulePillDisabled) {+ const snapshottedTriggerId = firstTriggerIdRef.current;+ try {+ if (snapshottedTriggerId) {+ await updateTrigger.mutateAsync({+ autopilotId: props.autopilotId,+ triggerId: snapshottedTriggerId,+ cron_expression: toCronExpression(triggerConfig),+ timezone: triggerConfig.timezone,+ });+ } else {+ await createTrigger.mutateAsync({+ autopilotId: props.autopilotId,+ kind: "schedule",+ cron_expression: toCronExpression(triggerConfig),+ timezone: triggerConfig.timezone,+ });+ }+ } catch {+ scheduleOk = false;+ }+ }+ onOpenChange(false);+ if (scheduleOk) toast.success("Autopilot updated");+ else toast.error("Autopilot updated, but schedule failed to save");+ }+ } catch {+ toast.error(isCreate ? "Failed to create autopilot" : "Failed to update autopilot");+ } finally {+ setSubmitting(false);+ }+ };++ const contentKey = isCreate ? "create" : props.autopilotId;++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent+ showCloseButton={false}+ className={cn(+ "p-0 gap-0 flex flex-col overflow-hidden",+ "!transition-all !duration-300 !ease-out !-translate-y-1/2",+ "!w-[calc(100vw-2rem)]",+ isExpanded ? "!max-w-4xl !h-5/6" : "!max-w-2xl !h-96",+ )}+ >+ <DialogTitle className="sr-only">+ {isCreate ? "New Autopilot" : "Edit Autopilot"}+ </DialogTitle>++ {/* Header */}+ <div className="flex items-center justify-between px-5 pt-3 pb-2 shrink-0">+ <div className="flex items-center gap-1.5 text-xs">+ <span className="text-muted-foreground">{workspaceName}</span>+ <ChevronRight className="size-3 text-muted-foreground/50" />+ <Rocket className="size-3 text-muted-foreground" />+ <span className="font-medium">+ {isCreate ? "New autopilot" : "Edit autopilot"}+ </span>+ </div>+ <div className="flex items-center gap-1">+ <Tooltip>+ <TooltipTrigger+ render={+ <button+ onClick={() => setIsExpanded((v) => !v)}+ className="rounded-sm p-1.5 opacity-70 hover:opacity-100 hover:bg-accent/60 transition-all cursor-pointer"+ >+ {isExpanded ? <Minimize2 className="size-4" /> : <Maximize2 className="size-4" />}+ </button>+ }+ />+ <TooltipContent side="bottom">{isExpanded ? "Collapse" : "Expand"}</TooltipContent>+ </Tooltip>+ <Tooltip>+ <TooltipTrigger+ render={+ <button+ onClick={() => onOpenChange(false)}+ className="rounded-sm p-1.5 opacity-70 hover:opacity-100 hover:bg-accent/60 transition-all cursor-pointer"+ >+ <XIcon className="size-4" />+ </button>+ }+ />+ <TooltipContent side="bottom">Close</TooltipContent>+ </Tooltip>+ </div>+ </div>++ {/* Body re-mounts when switching between autopilots (or create/edit) */}+ <div key={contentKey} className="flex-1 flex flex-col min-h-0">+ {/* Name */}+ <div className="px-5 pb-2 shrink-0">+ <TitleEditor+ autoFocus={isCreate}+ defaultValue={initial.title ?? ""}+ placeholder="Autopilot name"+ className="text-lg font-semibold"+ onChange={setTitle}+ onSubmit={handleSubmit}+ />+ </div>++ {/* Prompt — takes remaining space */}+ <div className="relative flex-1 min-h-0 overflow-y-auto px-5">+ <ContentEditor+ defaultValue={initial.description ?? ""}+ placeholder="Step-by-step instructions for the agent..."+ onUpdate={setDescription}+ debounceMs={300}+ showBubbleMenu={false}+ />+ </div>++ {/* Pill toolbar */}+ <div className="flex items-center gap-1.5 px-4 py-2 shrink-0 flex-wrap">+ <AgentPicker+ agentId={assigneeId || null}+ onChange={setAssigneeId}+ triggerRender={<PillButton />}+ align="start"+ />+ <PriorityPicker+ priority={priority as IssuePriority}+ onUpdate={(u) => { if (u.priority) setPriority(u.priority); }}+ triggerRender={<PillButton />}+ align="start"+ />+ <ExecutionModePicker+ mode={executionMode}+ onChange={setExecutionMode}+ triggerRender={<PillButton />}+ align="start"+ />+ {schedulePillDisabled ? (+ <Tooltip>+ <TooltipTrigger+ render={+ <PillButton+ disabled+ className="opacity-60 cursor-not-allowed"+ >+ <Calendar className="size-3" />+ <span className="truncate">{schedulePillLabel}</span>+ </PillButton>+ }+ />+ <TooltipContent side="top">Edit schedules in detail page</TooltipContent>+ </Tooltip>+ ) : (+ <SchedulePicker+ config={triggerConfig}+ onChange={setTriggerConfig}+ triggerRender={+ <PillButton>+ <Calendar className="size-3" />+ <span className="truncate">{schedulePillLabel}</span>+ </PillButton>+ }+ />+ )}+ </div>++ {/* Footer */}+ <div className="flex items-center justify-end gap-2 px-4 py-3 border-t shrink-0">+ <Button size="sm" variant="outline" onClick={() => onOpenChange(false)}>+ Cancel+ </Button>+ <Button size="sm" onClick={handleSubmit} disabled={!canSubmit}>+ {submitting+ ? isCreate ? "Creating..." : "Saving..."+ : isCreate ? "Create autopilot" : "Save"}+ </Button>+ </div>+ </div>++ </DialogContent>+ </Dialog>+ );+}diff --git a/packages/views/autopilots/components/autopilots-page.tsx b/packages/views/autopilots/components/autopilots-page.tsxindex ec65af2fb6..f65c640937 100644--- a/packages/views/autopilots/components/autopilots-page.tsx+++ b/packages/views/autopilots/components/autopilots-page.tsx@@ -4,8 +4,6 @@ import { useState } from "react";import { Plus, Zap, Play, Pause, AlertCircle, Newspaper, GitPullRequest, Bug, BarChart3, Shield, FileSearch } from "lucide-react";import { useQuery } from "@tanstack/react-query";import { autopilotListOptions } from "@multica/core/autopilots/queries";-import { useCreateAutopilot, useCreateAutopilotTrigger } from "@multica/core/autopilots/mutations";-import { agentListOptions } from "@multica/core/workspace/queries";import { useWorkspaceId } from "@multica/core/hooks";import { useWorkspacePaths } from "@multica/core/paths";import { useActorName } from "@multica/core/workspace/hooks";@@ -15,25 +13,7 @@ import { PageHeader } from "../../layout/page-header";import { Skeleton } from "@multica/ui/components/ui/skeleton";import { Button } from "@multica/ui/components/ui/button";import { cn } from "@multica/ui/lib/utils";-import { toast } from "sonner";-import {- Dialog,- DialogContent,- DialogTitle,-} from "@multica/ui/components/ui/dialog";-import {- Select,- SelectTrigger,- SelectValue,- SelectContent,- SelectItem,-} from "@multica/ui/components/ui/select";-import {- TriggerConfigSection,- getDefaultTriggerConfig,- toCronExpression,-} from "./trigger-config";-import type { TriggerConfig } from "./trigger-config";+import { AutopilotDialog } from "./autopilot-dialog";import type { Autopilot } from "@multica/core/types";import type { TriggerFrequency } from "./trigger-config";@@ -186,155 +166,6 @@ function AutopilotRow({ autopilot }: { autopilot: Autopilot }) {);}-function CreateAutopilotDialog({- open,- onOpenChange,- template,-}: {- open: boolean;- onOpenChange: (open: boolean) => void;- template?: AutopilotTemplate | null;-}) {- const wsId = useWorkspaceId();- const { data: agents = [] } = useQuery(agentListOptions(wsId));- const createAutopilot = useCreateAutopilot();- const createTrigger = useCreateAutopilotTrigger();-- const [title, setTitle] = useState("");- const [description, setDescription] = useState("");- const [assigneeId, setAssigneeId] = useState("");- const [triggerConfig, setTriggerConfig] = useState<TriggerConfig>(getDefaultTriggerConfig);- const [submitting, setSubmitting] = useState(false);-- // Apply template when it changes- const [appliedTemplate, setAppliedTemplate] = useState<AutopilotTemplate | null | undefined>(null);- if (template !== appliedTemplate && open) {- setAppliedTemplate(template);- if (template) {- setTitle(template.title);- setDescription(template.prompt);- setTriggerConfig({- ...getDefaultTriggerConfig(),- frequency: template.frequency,- time: template.time,- });- }- }-- const activeAgents = agents.filter((a) => !a.archived_at);-- const handleSubmit = async () => {- if (!title.trim() || !assigneeId || submitting) return;- setSubmitting(true);- try {- const autopilot = await createAutopilot.mutateAsync({- title: title.trim(),- description: description.trim() || undefined,- assignee_id: assigneeId,- execution_mode: "create_issue",- });-- // Attach schedule trigger- try {- await createTrigger.mutateAsync({- autopilotId: autopilot.id,- kind: "schedule",- cron_expression: toCronExpression(triggerConfig),- timezone: triggerConfig.timezone,- });- } catch {- toast.error("Autopilot created, but trigger failed to save");- }-- onOpenChange(false);- setTitle("");- setDescription("");- setAssigneeId("");- setTriggerConfig(getDefaultTriggerConfig());- toast.success("Autopilot created");- } catch {- toast.error("Failed to create autopilot");- } finally {- setSubmitting(false);- }- };-- return (- <Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent className="max-w-lg">- <DialogTitle>New Autopilot</DialogTitle>- <div className="space-y-5 pt-2">- {/* Name */}- <div>- <label className="text-xs font-medium text-muted-foreground">Name</label>- <input- type="text"- value={title}- onChange={(e) => setTitle(e.target.value)}- placeholder="e.g. Daily code review"- className="mt-1 w-full rounded-md border bg-background px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring"- autoFocus- />- </div>-- {/* Prompt */}- <div>- <label className="text-xs font-medium text-muted-foreground">Prompt</label>- <textarea- value={description}- onChange={(e) => setDescription(e.target.value)}- placeholder="Step-by-step instructions for the agent..."- rows={6}- className="mt-1 w-full rounded-md border bg-background px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring resize-y"- />- </div>-- {/* Agent */}- <div>- <label className="text-xs font-medium text-muted-foreground">Agent</label>- <Select value={assigneeId} onValueChange={(v) => v && setAssigneeId(v)}>- <SelectTrigger className="mt-1 w-full">- <SelectValue>- {(value: string | null) => {- if (!value) return "Select agent...";- const agent = activeAgents.find((a) => a.id === value);- return agent?.name ?? "Unknown Agent";- }}- </SelectValue>- </SelectTrigger>- <SelectContent>- {activeAgents.map((a) => (- <SelectItem key={a.id} value={a.id}>- {a.name}- </SelectItem>- ))}- </SelectContent>- </Select>- </div>-- {/* Schedule */}- <div>- <label className="text-xs font-medium text-muted-foreground">Schedule</label>- <div className="mt-2">- <TriggerConfigSection config={triggerConfig} onChange={setTriggerConfig} />- </div>- </div>-- {/* Actions */}- <div className="flex justify-end gap-2 pt-1">- <Button size="sm" variant="outline" onClick={() => onOpenChange(false)}>- Cancel- </Button>- <Button size="sm" onClick={handleSubmit} disabled={!title.trim() || !assigneeId || submitting}>- {submitting ? "Creating..." : "Create"}- </Button>- </div>- </div>- </DialogContent>- </Dialog>- );-}-export function AutopilotsPage() {const wsId = useWorkspaceId();const { data: autopilots = [], isLoading } = useQuery(autopilotListOptions(wsId));@@ -430,7 +261,23 @@ export function AutopilotsPage() {)}</div>- <CreateAutopilotDialog open={createOpen} onOpenChange={setCreateOpen} template={selectedTemplate} />+ {createOpen && (+ <AutopilotDialog+ mode="create"+ open={createOpen}+ onOpenChange={setCreateOpen}+ initial={+ selectedTemplate+ ? { title: selectedTemplate.title, description: selectedTemplate.prompt }+ : undefined+ }+ initialTriggerConfig={+ selectedTemplate+ ? { frequency: selectedTemplate.frequency, time: selectedTemplate.time }+ : undefined+ }+ />+ )}</div>);}diff --git a/packages/views/autopilots/components/pickers/agent-picker.tsx b/packages/views/autopilots/components/pickers/agent-picker.tsxnew file mode 100644index 0000000000..88366f4a7c--- /dev/null+++ b/packages/views/autopilots/components/pickers/agent-picker.tsx@@ -0,0 +1,87 @@+"use client";++import { useState } from "react";+import { useQuery } from "@tanstack/react-query";+import { Bot } from "lucide-react";+import { useWorkspaceId } from "@multica/core/hooks";+import { agentListOptions } from "@multica/core/workspace/queries";+import { ActorAvatar } from "../../../common/actor-avatar";+import {+ PropertyPicker,+ PickerItem,+ PickerEmpty,+} from "../../../issues/components/pickers/property-picker";++export function AgentPicker({+ agentId,+ onChange,+ trigger: customTrigger,+ triggerRender,+ align = "start",+}: {+ agentId: string | null;+ onChange: (id: string) => void;+ trigger?: React.ReactNode;+ triggerRender?: React.ReactElement;+ align?: "start" | "center" | "end";+}) {+ const wsId = useWorkspaceId();+ const [open, setOpen] = useState(false);+ const [filter, setFilter] = useState("");+ const { data: agents = [] } = useQuery(agentListOptions(wsId));+ const active = agents.filter((a) => !a.archived_at);+ const selected = active.find((a) => a.id === agentId);++ const query = filter.trim().toLowerCase();+ const filteredAgents = query+ ? active.filter((a) => a.name.toLowerCase().includes(query))+ : active;++ return (+ <PropertyPicker+ open={open}+ onOpenChange={setOpen}+ width="w-56"+ align={align}+ searchable+ searchPlaceholder="Filter agents..."+ onSearchChange={setFilter}+ triggerRender={triggerRender}+ trigger={+ customTrigger ?? (+ <>+ {selected ? (+ <>+ <ActorAvatar actorType="agent" actorId={selected.id} size={16} />+ <span className="truncate">{selected.name}</span>+ </>+ ) : (+ <>+ <Bot className="size-3" />+ <span>Select agent</span>+ </>+ )}+ </>+ )+ }+ >+ {filteredAgents.length === 0 ? (+ <PickerEmpty />+ ) : (+ filteredAgents.map((a) => (+ <PickerItem+ key={a.id}+ selected={a.id === agentId}+ onClick={() => {+ onChange(a.id);+ setOpen(false);+ }}+ >+ <ActorAvatar actorType="agent" actorId={a.id} size={16} />+ <span className="truncate">{a.name}</span>+ </PickerItem>+ ))+ )}+ </PropertyPicker>+ );+}diff --git a/packages/views/autopilots/components/pickers/execution-mode-picker.tsx b/packages/views/autopilots/components/pickers/execution-mode-picker.tsxnew file mode 100644index 0000000000..dd2e919dfb--- /dev/null+++ b/packages/views/autopilots/components/pickers/execution-mode-picker.tsx@@ -0,0 +1,76 @@+"use client";++import { useState } from "react";+import { FilePlus2, Play } from "lucide-react";+import type { AutopilotExecutionMode } from "@multica/core/types";+import { Tooltip, TooltipTrigger, TooltipContent } from "@multica/ui/components/ui/tooltip";+import {+ PropertyPicker,+ PickerItem,+} from "../../../issues/components/pickers/property-picker";++const OPTIONS: { value: AutopilotExecutionMode; label: string; description: string; Icon: typeof FilePlus2 }[] = [+ { value: "create_issue", label: "Create Issue", description: "File an issue with the agent assigned", Icon: FilePlus2 },+ { value: "run_only", label: "Run Only", description: "Run the agent without creating an issue", Icon: Play },+];++export function ExecutionModePicker({+ mode,+ onChange,+ trigger: customTrigger,+ triggerRender,+ align = "start",+}: {+ mode: AutopilotExecutionMode;+ onChange: (mode: AutopilotExecutionMode) => void;+ trigger?: React.ReactNode;+ triggerRender?: React.ReactElement;+ align?: "start" | "center" | "end";+}) {+ const [open, setOpen] = useState(false);+ const current = OPTIONS.find((o) => o.value === mode) ?? OPTIONS[0]!;+ const CurrentIcon = current.Icon;++ return (+ <PropertyPicker+ open={open}+ onOpenChange={setOpen}+ width="w-52"+ align={align}+ triggerRender={triggerRender}+ trigger={+ customTrigger ?? (+ <>+ <CurrentIcon className="size-3 shrink-0" />+ <span className="truncate">{current.label}</span>+ </>+ )+ }+ >+ {OPTIONS.map((o) => {+ const Icon = o.Icon;+ return (+ <Tooltip key={o.value}>+ <TooltipTrigger+ render={+ <PickerItem+ selected={o.value === mode}+ onClick={() => {+ onChange(o.value);+ setOpen(false);+ }}+ >+ <Icon className="size-3.5 shrink-0 text-muted-foreground" />+ <span>{o.label}</span>+ </PickerItem>+ }+ />+ <TooltipContent side="right" sideOffset={8}>+ {o.description}+ </TooltipContent>+ </Tooltip>+ );+ })}+ </PropertyPicker>+ );+}diff --git a/packages/views/autopilots/components/pickers/schedule-picker.tsx b/packages/views/autopilots/components/pickers/schedule-picker.tsxnew file mode 100644index 0000000000..76c4569d37--- /dev/null+++ b/packages/views/autopilots/components/pickers/schedule-picker.tsx@@ -0,0 +1,32 @@+"use client";++import { useState } from "react";+import {+ Popover,+ PopoverTrigger,+ PopoverContent,+} from "@multica/ui/components/ui/popover";+import {+ TriggerConfigSection,+ type TriggerConfig,+} from "../trigger-config";++export function SchedulePicker({+ config,+ onChange,+ triggerRender,+}: {+ config: TriggerConfig;+ onChange: (cfg: TriggerConfig) => void;+ triggerRender: React.ReactElement;+}) {+ const [open, setOpen] = useState(false);+ return (+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger render={triggerRender} />+ <PopoverContent align="start" className="w-96 p-3">+ <TriggerConfigSection config={config} onChange={onChange} />+ </PopoverContent>+ </Popover>+ );+}diff --git a/packages/views/autopilots/components/trigger-config.test.ts b/packages/views/autopilots/components/trigger-config.test.tsnew file mode 100644index 0000000000..650bd33d51--- /dev/null+++ b/packages/views/autopilots/components/trigger-config.test.ts@@ -0,0 +1,68 @@+import { describe, it, expect } from "vitest";+import {+ parseCronExpression,+ toCronExpression,+ getDefaultTriggerConfig,+} from "./trigger-config";++describe("parseCronExpression", () => {+ it("round-trips hourly", () => {+ const cfg = { ...getDefaultTriggerConfig(), frequency: "hourly" as const, time: "00:15" };+ const cron = toCronExpression(cfg);+ const parsed = parseCronExpression(cron, "UTC");+ expect(parsed.frequency).toBe("hourly");+ });++ it("round-trips daily at 09:30", () => {+ const cfg = { ...getDefaultTriggerConfig(), frequency: "daily" as const, time: "09:30" };+ const cron = toCronExpression(cfg);+ const parsed = parseCronExpression(cron, "UTC");+ expect(parsed.frequency).toBe("daily");+ expect(parsed.time).toBe("09:30");+ });++ it("recognises weekdays pattern", () => {+ const parsed = parseCronExpression("0 9 * * 1-5", "UTC");+ expect(parsed.frequency).toBe("weekdays");+ expect(parsed.time).toBe("09:00");+ });++ it("recognises weekly with multiple days", () => {+ const parsed = parseCronExpression("0 9 * * 1,3,5", "UTC");+ expect(parsed.frequency).toBe("weekly");+ expect(parsed.daysOfWeek).toEqual([1, 3, 5]);+ expect(parsed.time).toBe("09:00");+ });++ it("falls back to custom for non-matching pattern", () => {+ const parsed = parseCronExpression("*/15 * * * *", "UTC");+ expect(parsed.frequency).toBe("custom");+ expect(parsed.cronExpression).toBe("*/15 * * * *");+ });++ it("falls back to custom for malformed input", () => {+ const parsed = parseCronExpression("not a cron", "UTC");+ expect(parsed.frequency).toBe("custom");+ });++ it("preserves provided timezone", () => {+ const parsed = parseCronExpression("0 9 * * *", "Asia/Shanghai");+ expect(parsed.timezone).toBe("Asia/Shanghai");+ });++ it("rejects out-of-range minute", () => {+ expect(parseCronExpression("60 * * * *", "UTC").frequency).toBe("custom");+ });++ it("rejects out-of-range hour", () => {+ expect(parseCronExpression("0 24 * * *", "UTC").frequency).toBe("custom");+ });++ it("round-trips weekly preserving daysOfWeek", () => {+ const cfg = { ...getDefaultTriggerConfig(), frequency: "weekly" as const, time: "14:45", daysOfWeek: [0, 2, 6] };+ const parsed = parseCronExpression(toCronExpression(cfg), "UTC");+ expect(parsed.frequency).toBe("weekly");+ expect(parsed.time).toBe("14:45");+ expect(parsed.daysOfWeek).toEqual([0, 2, 6]);+ });+});diff --git a/packages/views/autopilots/components/trigger-config.tsx b/packages/views/autopilots/components/trigger-config.tsxindex 3f4ce98a4a..382e31c45a 100644--- a/packages/views/autopilots/components/trigger-config.tsx+++ b/packages/views/autopilots/components/trigger-config.tsx@@ -139,6 +139,57 @@ export function toCronExpression(cfg: TriggerConfig): string {}}+export function parseCronExpression(cron: string, timezone: string): TriggerConfig {+ const base: TriggerConfig = {+ ...getDefaultTriggerConfig(),+ timezone,+ cronExpression: cron,+ };+ const parts = cron.trim().split(/\s+/);+ if (parts.length !== 5) return { ...base, frequency: "custom" };+ const minStr = parts[0] ?? "";+ const hourStr = parts[1] ?? "";+ const dom = parts[2] ?? "";+ const mon = parts[3] ?? "";+ const dow = parts[4] ?? "";+ if (dom !== "*" || mon !== "*") return { ...base, frequency: "custom" };+ const min = parseInt(minStr, 10);+ if (Number.isNaN(min) || min < 0 || min > 59) return { ...base, frequency: "custom" };++ if (hourStr === "*" && dow === "*") {+ const time = `00:${String(min).padStart(2, "0")}`;+ return { ...base, frequency: "hourly", time };+ }+ const hour = parseInt(hourStr, 10);+ if (Number.isNaN(hour) || hour < 0 || hour > 23) return { ...base, frequency: "custom" };+ const time = `${String(hour).padStart(2, "0")}:${String(min).padStart(2, "0")}`;++ if (dow === "*") return { ...base, frequency: "daily", time };+ if (dow === "1-5") return { ...base, frequency: "weekdays", time, daysOfWeek: [1, 2, 3, 4, 5] };+ if (/^[0-6](,[0-6])*$/.test(dow)) {+ const days = dow.split(",").map((n) => parseInt(n, 10));+ return { ...base, frequency: "weekly", time, daysOfWeek: days };+ }+ return { ...base, frequency: "custom" };+}++export function summarizeTrigger(cfg: TriggerConfig): string {+ switch (cfg.frequency) {+ case "hourly": {+ const min = cfg.time.split(":")[1] ?? "00";+ return `Hourly · :${min}`;+ }+ case "daily":+ return `Daily ${cfg.time}`;+ case "weekdays":+ return `Weekdays ${cfg.time}`;+ case "weekly":+ return `${formatDayList(cfg.daysOfWeek)} ${cfg.time}`;+ case "custom":+ return "Custom cron";+ }+}+export function describeTrigger(cfg: TriggerConfig): string {const offset = getTimezoneOffset(cfg.timezone);switch (cfg.frequency) {diff --git a/packages/views/common/pill-button.tsx b/packages/views/common/pill-button.tsxnew file mode 100644index 0000000000..11ded8b2ef--- /dev/null+++ b/packages/views/common/pill-button.tsx@@ -0,0 +1,25 @@+"use client";++import { cn } from "@multica/ui/lib/utils";++export function PillButton({+ children,+ className,+ ...props+}: React.ButtonHTMLAttributes<HTMLButtonElement>) {+ return (+ <button+ type="button"+ className={cn(+ "inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs",+ "hover:bg-accent/60 transition-colors cursor-pointer",+ "data-popup-open:bg-accent data-popup-open:text-accent-foreground",+ "disabled:cursor-not-allowed disabled:hover:bg-transparent",+ className,+ )}+ {...props}+ >+ {children}+ </button>+ );+}diff --git a/packages/views/modals/create-issue.tsx b/packages/views/modals/create-issue.tsxindex 7b92491084..b5dd511483 100644--- a/packages/views/modals/create-issue.tsx+++ b/packages/views/modals/create-issue.tsx@@ -23,30 +23,7 @@ import { useCreateIssue, useUpdateIssue } from "@multica/core/issues/mutations";import { useFileUpload } from "@multica/core/hooks/use-file-upload";import { api } from "@multica/core/api";import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";--// ----------------------------------------------------------------------------// Pill trigger — shared rounded-full button style for toolbar-// -----------------------------------------------------------------------------function PillButton({- children,- className,- ...props-}: React.ButtonHTMLAttributes<HTMLButtonElement>) {- return (- <button- type="button"- className={cn(- "inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs",- "hover:bg-accent/60 transition-colors cursor-pointer",- className,- )}- {...props}- >- {children}- </button>- );-}+import { PillButton } from "../common/pill-button";// ---------------------------------------------------------------------------// CreateIssueModal